@runfusion/fusion 0.5.0 → 0.7.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 (64) hide show
  1. package/dist/bin.js +5092 -1417
  2. package/dist/client/assets/AgentDetailView-C1_lTTET.css +1 -0
  3. package/dist/client/assets/AgentDetailView-Du65-jDo.js +18 -0
  4. package/dist/client/assets/AgentsView-BkgNEbNs.js +522 -0
  5. package/dist/client/assets/AgentsView-D12CuIFc.css +1 -0
  6. package/dist/client/assets/ChatView-LDte0TdV.js +1 -0
  7. package/dist/client/assets/DevServerView-AXznq3jv.js +6 -0
  8. package/dist/client/assets/DevServerView-DlZpuAnj.css +1 -0
  9. package/dist/client/assets/{DirectoryPicker-B3ejJOl0.js → DirectoryPicker-CSp3G115.js} +1 -1
  10. package/dist/client/assets/DocumentsView-BrhyOdeE.css +1 -0
  11. package/dist/client/assets/DocumentsView-DOe0E1WQ.js +1 -0
  12. package/dist/client/assets/{InsightsView-CoRsf8DC.js → InsightsView-DWZbS6z-.js} +1 -1
  13. package/dist/client/assets/{MemoryView-oFUIaoM5.js → MemoryView-BxnlhBoa.js} +1 -1
  14. package/dist/client/assets/{NodesView-BXUaViVf.js → NodesView-DO9jxhM4.js} +1 -1
  15. package/dist/client/assets/{PiExtensionsManager-DJRC5zRv.js → PiExtensionsManager-CfXZaWl7.js} +3 -3
  16. package/dist/client/assets/PluginManager-jyNkJZSz.css +1 -0
  17. package/dist/client/assets/PluginManager-r6CWD9u-.js +1 -0
  18. package/dist/client/assets/RoadmapsView-CgAM3YfN.js +6 -0
  19. package/dist/client/assets/SettingsModal-DPDQyWim.css +1 -0
  20. package/dist/client/assets/SettingsModal-GZdRt8fX.js +31 -0
  21. package/dist/client/assets/{SettingsModal-CDWvhvrd.css → SettingsModal-YjpwLH2V.css} +1 -1
  22. package/dist/client/assets/{SettingsModal-CMRJwSFd.js → SettingsModal-fmRtzH8z.js} +1 -1
  23. package/dist/client/assets/{SetupWizardModal-BnPgyQho.js → SetupWizardModal-oRNpImWR.js} +1 -1
  24. package/dist/client/assets/{SkillsView-pHEyP-vg.js → SkillsView-BhwtL-0_.js} +1 -1
  25. package/dist/client/assets/TodoView-C1g65hJo.css +1 -0
  26. package/dist/client/assets/TodoView-CmhUBFNV.js +6 -0
  27. package/dist/client/assets/{folder-open-DJxjQmf1.js → folder-open-CrTagHrr.js} +1 -1
  28. package/dist/client/assets/index-BTeSa6vk.js +646 -0
  29. package/dist/client/assets/index-S9oR77v2.css +1 -0
  30. package/dist/client/assets/{list-checks-NjVTpQgK.js → list-checks-DR26h_Io.js} +1 -1
  31. package/dist/client/assets/star-CO_D42zy.js +6 -0
  32. package/dist/client/assets/{upload-BQA5FG0G.js → upload-BcrgS-iu.js} +1 -1
  33. package/dist/client/assets/{users-p7CqLoIz.js → users-4d8al5Sp.js} +1 -1
  34. package/dist/client/brands/hermes-logo.svg +1 -0
  35. package/dist/client/index.html +2 -2
  36. package/dist/client/version.json +1 -1
  37. package/dist/extension.js +2833 -625
  38. package/dist/pi-claude-cli/index.ts +12 -0
  39. package/dist/pi-claude-cli/package.json +1 -1
  40. package/dist/pi-claude-cli/src/__tests__/event-bridge.test.ts +40 -0
  41. package/dist/pi-claude-cli/src/__tests__/mcp-config.test.ts +17 -1
  42. package/dist/pi-claude-cli/src/__tests__/prompt-builder.test.ts +41 -0
  43. package/dist/pi-claude-cli/src/__tests__/tool-mapping.test.ts +1 -0
  44. package/dist/pi-claude-cli/src/prompt-builder.ts +8 -11
  45. package/dist/pi-claude-cli/src/provider.ts +17 -4
  46. package/package.json +5 -5
  47. package/dist/client/assets/AgentDetailView-C1b9PC5l.css +0 -1
  48. package/dist/client/assets/AgentDetailView-CnedHKqd.js +0 -23
  49. package/dist/client/assets/AgentsView-DETxUmHS.css +0 -1
  50. package/dist/client/assets/AgentsView-TCAMvB-N.js +0 -522
  51. package/dist/client/assets/ChatView-B7djAFGF.js +0 -1
  52. package/dist/client/assets/DevServerView-B_zgnvEn.js +0 -11
  53. package/dist/client/assets/DevServerView-ZeBGQkLI.css +0 -1
  54. package/dist/client/assets/DocumentsView-DV2DrCZb.css +0 -1
  55. package/dist/client/assets/DocumentsView-DzmbEKrl.js +0 -1
  56. package/dist/client/assets/PluginManager-DRiIqol2.css +0 -1
  57. package/dist/client/assets/PluginManager-OQhiY2zP.js +0 -1
  58. package/dist/client/assets/RoadmapsView-DwdewIMm.js +0 -6
  59. package/dist/client/assets/SettingsModal-Bmz_YrW5.js +0 -31
  60. package/dist/client/assets/SettingsModal-G0ESQXRD.css +0 -1
  61. package/dist/client/assets/TodoView-Cg-xDGeH.js +0 -1
  62. package/dist/client/assets/TodoView-DNi8blBB.css +0 -1
  63. package/dist/client/assets/index-B7TDbn3p.css +0 -1
  64. package/dist/client/assets/index-Cf4wCcWp.js +0 -631
@@ -0,0 +1,646 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-xterm-DzcZoU0P.js","assets/vendor-react-K0fH_qHe.js","assets/vendor-xterm-LZoznX6r.css","assets/addon-fit-C7jRorKK.js","assets/addon-web-links-CkJwd4cQ.js","assets/addon-webgl-BjvOw43o.js","assets/SetupWizardModal-oRNpImWR.js","assets/DirectoryPicker-CSp3G115.js","assets/folder-open-CrTagHrr.js","assets/DirectoryPicker-DzKVmxOf.css","assets/SetupWizardModal-BMa6p24b.css","assets/SettingsModal-GZdRt8fX.js","assets/SettingsModal-fmRtzH8z.js","assets/SettingsModal-DPDQyWim.css","assets/users-4d8al5Sp.js","assets/star-CO_D42zy.js","assets/SettingsModal-YjpwLH2V.css","assets/AgentsView-BkgNEbNs.js","assets/upload-BcrgS-iu.js","assets/AgentsView-D12CuIFc.css","assets/DocumentsView-DOe0E1WQ.js","assets/DocumentsView-BrhyOdeE.css","assets/InsightsView-DWZbS6z-.js","assets/InsightsView-Egu71gmh.css","assets/NodesView-DO9jxhM4.js","assets/NodesView-BYVG2yY-.css","assets/ChatView-LDte0TdV.js","assets/RoadmapsView-CgAM3YfN.js","assets/RoadmapsView-BOYnyMCh.css","assets/SkillsView-BhwtL-0_.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-BxnlhBoa.js","assets/MemoryView-DiajLXby.css","assets/DevServerView-AXznq3jv.js","assets/DevServerView-DlZpuAnj.css","assets/TodoView-CmhUBFNV.js","assets/list-checks-DR26h_Io.js","assets/TodoView-C1g65hJo.css"])))=>i.map(i=>d[i]);
2
+ import{r as a,j as t,R as Zr,a as qa,g as Eh,c as sg}from"./vendor-react-K0fH_qHe.js";import"./vendor-xterm-DzcZoU0P.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&i(l)}).observe(document,{childList:!0,subtree:!0});function s(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function i(r){if(r.ep)return;r.ep=!0;const o=s(r);fetch(r.href,o)}})();/**
3
+ * @license lucide-react v1.7.0 - ISC
4
+ *
5
+ * This source code is licensed under the ISC license.
6
+ * See the LICENSE file in the root directory of this source tree.
7
+ */const Mh=(...e)=>e.filter((n,s,i)=>!!n&&n.trim()!==""&&i.indexOf(n)===s).join(" ").trim();/**
8
+ * @license lucide-react v1.7.0 - ISC
9
+ *
10
+ * This source code is licensed under the ISC license.
11
+ * See the LICENSE file in the root directory of this source tree.
12
+ */const ig=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 ag=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(n,s,i)=>i?i.toUpperCase():s.toLowerCase());/**
18
+ * @license lucide-react v1.7.0 - ISC
19
+ *
20
+ * This source code is licensed under the ISC license.
21
+ * See the LICENSE file in the root directory of this source tree.
22
+ */const kd=e=>{const n=ag(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 Wo={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 rg=e=>{for(const n in e)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},og=a.createContext({}),lg=()=>a.useContext(og),cg=a.forwardRef(({color:e,size:n,strokeWidth:s,absoluteStrokeWidth:i,className:r="",children:o,iconNode:l,...c},u)=>{const{size:d=24,strokeWidth:m=2,absoluteStrokeWidth:h=!1,color:g="currentColor",className:p=""}=lg()??{},f=i??h?Number(s??m)*24/Number(n??d):s??m;return a.createElement("svg",{ref:u,...Wo,width:n??d??Wo.width,height:n??d??Wo.height,stroke:e??g,strokeWidth:f,className:Mh("lucide",p,r),...!o&&!rg(c)&&{"aria-hidden":"true"},...c},[...l.map(([x,v])=>a.createElement(x,v)),...Array.isArray(o)?o:[o]])});/**
33
+ * @license lucide-react v1.7.0 - ISC
34
+ *
35
+ * This source code is licensed under the ISC license.
36
+ * See the LICENSE file in the root directory of this source tree.
37
+ */const Ue=(e,n)=>{const s=a.forwardRef(({className:i,...r},o)=>a.createElement(cg,{ref:o,iconNode:n,className:Mh(`lucide-${ig(kd(e))}`,`lucide-${e}`,i),...r}));return s.displayName=kd(e),s};/**
38
+ * @license lucide-react v1.7.0 - ISC
39
+ *
40
+ * This source code is licensed under the ISC license.
41
+ * See the LICENSE file in the root directory of this source tree.
42
+ */const dg=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],Es=Ue("activity",dg);/**
43
+ * @license lucide-react v1.7.0 - ISC
44
+ *
45
+ * This source code is licensed under the ISC license.
46
+ * See the LICENSE file in the root directory of this source tree.
47
+ */const ug=[["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"}]],vo=Ue("archive",ug);/**
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 mg=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],cr=Ue("arrow-down",mg);/**
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 hg=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],ga=Ue("arrow-left",hg);/**
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 pg=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],dr=Ue("arrow-right",pg);/**
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 fg=[["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"}]],_h=Ue("arrow-up-down",fg);/**
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 gg=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Mi=Ue("arrow-up",gg);/**
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 xg=[["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"}]],bg=Ue("book-open",xg);/**
78
+ * @license lucide-react v1.7.0 - ISC
79
+ *
80
+ * This source code is licensed under the ISC license.
81
+ * See the LICENSE file in the root directory of this source tree.
82
+ */const vg=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],pn=Ue("bot",vg);/**
83
+ * @license lucide-react v1.7.0 - ISC
84
+ *
85
+ * This source code is licensed under the ISC license.
86
+ * See the LICENSE file in the root directory of this source tree.
87
+ */const yg=[["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"}]],Zl=Ue("box",yg);/**
88
+ * @license lucide-react v1.7.0 - ISC
89
+ *
90
+ * This source code is licensed under the ISC license.
91
+ * See the LICENSE file in the root directory of this source tree.
92
+ */const kg=[["path",{d:"M12 18V5",key:"adv99a"}],["path",{d:"M15 13a4.17 4.17 0 0 1-3-4 4.17 4.17 0 0 1-3 4",key:"1e3is1"}],["path",{d:"M17.598 6.5A3 3 0 1 0 12 5a3 3 0 1 0-5.598 1.5",key:"1gqd8o"}],["path",{d:"M17.997 5.125a4 4 0 0 1 2.526 5.77",key:"iwvgf7"}],["path",{d:"M18 18a4 4 0 0 0 2-7.464",key:"efp6ie"}],["path",{d:"M19.967 17.483A4 4 0 1 1 12 18a4 4 0 1 1-7.967-.517",key:"1gq6am"}],["path",{d:"M6 18a4 4 0 0 1-2-7.464",key:"k1g0md"}],["path",{d:"M6.003 5.125a4 4 0 0 0-2.526 5.77",key:"q97ue3"}]],eo=Ue("brain",kg);/**
93
+ * @license lucide-react v1.7.0 - ISC
94
+ *
95
+ * This source code is licensed under the ISC license.
96
+ * See the LICENSE file in the root directory of this source tree.
97
+ */const jg=[["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"}]],Ah=Ue("calendar",jg);/**
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 wg=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],Ng=Ue("check-check",wg);/**
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 Sg=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Rn=Ue("check",Sg);/**
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 Cg=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],qt=Ue("chevron-down",Cg);/**
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 Eg=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],yo=Ue("chevron-left",Eg);/**
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 Mg=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],mn=Ue("chevron-right",Mg);/**
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 _g=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],ni=Ue("chevron-up",_g);/**
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 Ag=[["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"}]],Zn=Ue("circle-alert",Ag);/**
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 Rg=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],un=Ue("circle-check-big",Rg);/**
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 Tg=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],ko=Ue("circle-dot",Tg);/**
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 Pg=[["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"}]],ec=Ue("circle-question-mark",Pg);/**
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 Ig=[["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"}]],ur=Ue("circle-x",Ig);/**
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 $g=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"M12 11h4",key:"1jrz19"}],["path",{d:"M12 16h4",key:"n85exb"}],["path",{d:"M8 11h.01",key:"1dfujw"}],["path",{d:"M8 16h.01",key:"18s6g9"}]],Dg=Ue("clipboard-list",$g);/**
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 Lg=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],hi=Ue("clock",Lg);/**
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 zg=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Rh=Ue("code",zg);/**
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 Fg=[["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"}]],Og=Ue("columns-3",Fg);/**
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 Ug=[["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"}]],Ai=Ue("copy",Ug);/**
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 Bg=[["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"}]],Hg=Ue("cpu",Bg);/**
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 qg=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],Vg=Ue("download",qg);/**
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 Wg=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]],Kg=Ue("ellipsis-vertical",Wg);/**
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 Gg=[["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"}]],tc=Ue("ellipsis",Gg);/**
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 Jg=[["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"}]],Yg=Ue("external-link",Jg);/**
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 Qg=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],nc=Ue("eye-off",Qg);/**
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 Xg=[["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"}]],sa=Ue("eye",Xg);/**
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 Zg=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}]],Ts=Ue("file-code",Zg);/**
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 ex=[["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"}]],Th=Ue("file-diff",ex);/**
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 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:"M9 15h6",key:"cctwl0"}]],nx=Ue("file-minus",tx);/**
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 sx=[["path",{d:"M12.659 22H18a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v9.34",key:"o6klzx"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10.378 12.622a1 1 0 0 1 3 3.003L8.36 20.637a2 2 0 0 1-.854.506l-2.867.837a.5.5 0 0 1-.62-.62l.836-2.869a2 2 0 0 1 .506-.853z",key:"zhnas1"}]],Ph=Ue("file-pen",sx);/**
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:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],ax=Ue("file-plus",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 rx=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M12 17h.01",key:"p32p05"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}]],ox=Ue("file-question-mark",rx);/**
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:"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"}]],Ri=Ue("file-text",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 cx=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"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"}]],dx=Ue("file-type",cx);/**
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 ux=[["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"}]],Ih=Ue("file",ux);/**
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 mx=[["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"}]],sc=Ue("folder-git-2",mx);/**
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:"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"}]],jd=Ue("folder-root",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 px=[["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"}]],Dn=Ue("folder",px);/**
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 fx=[["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"}]],to=Ue("funnel",fx);/**
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:"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"}]],Vs=Ue("git-branch",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 xx=[["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"}]],er=Ue("git-commit-horizontal",xx);/**
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 bx=[["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"}]],$h=Ue("git-merge",bx);/**
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 vx=[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v7",key:"1yeb86"}],["line",{x1:"6",x2:"6",y1:"9",y2:"21",key:"rroup"}]],hs=Ue("git-pull-request",vx);/**
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 yx=[["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"}]],jo=Ue("globe",yx);/**
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 kx=[["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"}]],Dh=Ue("grid-3x3",kx);/**
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 jx=[["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"}]],Lc=Ue("grip-vertical",jx);/**
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 wx=[["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"}]],Nx=Ue("hard-drive",wx);/**
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 Sx=[["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"}]],Cx=Ue("heart",Sx);/**
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 Ex=[["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"}]],tr=Ue("history",Ex);/**
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 Mx=[["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"}]],Va=Ue("inbox",Mx);/**
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 _x=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]],Lh=Ue("key",_x);/**
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 Ax=[["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"}]],Rx=Ue("keyboard",Ax);/**
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 Tx=[["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"}]],Ti=Ue("layers",Tx);/**
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 Px=[["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"}]],Pi=Ue("layout-grid",Px);/**
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 Ix=[["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"}]],Ws=Ue("lightbulb",Ix);/**
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 $x=[["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"}]],ia=Ue("link",$x);/**
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 Dx=[["path",{d:"M16 5H3",key:"m91uny"}],["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 19H3",key:"zzsher"}],["path",{d:"M18 9v6",key:"1twb98"}],["path",{d:"M21 12h-6",key:"bt1uis"}]],Lx=Ue("list-plus",Dx);/**
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 zx=[["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"}]],wo=Ue("list-tree",zx);/**
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 Fx=[["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"}]],ic=Ue("list",Fx);/**
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 Ox=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],rt=Ue("loader-circle",Ox);/**
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 Ux=[["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"}]],No=Ue("lock",Ux);/**
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 Bx=[["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"}]],aa=Ue("mail",Bx);/**
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 Hx=[["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"}]],ac=Ue("map",Hx);/**
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 qx=[["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"}]],So=Ue("maximize-2",qx);/**
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 Vx=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}],["path",{d:"M12 8v6",key:"1ib9pf"}],["path",{d:"M9 11h6",key:"1fldmi"}]],Wx=Ue("message-square-plus",Vx);/**
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 Kx=[["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"}]],ui=Ue("message-square",Kx);/**
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 Gx=[["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"}]],mr=Ue("minimize-2",Gx);/**
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 Jx=[["path",{d:"M5 12h14",key:"1ays0h"}]],Yx=Ue("minus",Jx);/**
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 Qx=[["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"}]],nr=Ue("monitor",Qx);/**
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 Xx=[["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"}]],Zx=Ue("move",Xx);/**
433
+ * @license lucide-react v1.7.0 - ISC
434
+ *
435
+ * This source code is licensed under the ISC license.
436
+ * See the LICENSE file in the root directory of this source tree.
437
+ */const eb=[["path",{d:"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"}]],rc=Ue("package",eb);/**
438
+ * @license lucide-react v1.7.0 - ISC
439
+ *
440
+ * This source code is licensed under the ISC license.
441
+ * See the LICENSE file in the root directory of this source tree.
442
+ */const tb=[["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"}]],nb=Ue("paperclip",tb);/**
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 sb=[["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"}]],qs=Ue("pause",sb);/**
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 ib=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],Qn=Ue("pencil",ib);/**
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 ab=[["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"}]],fn=Ue("play",ab);/**
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 rb=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Xt=Ue("plus",rb);/**
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 ob=[["path",{d:"M16.247 7.761a6 6 0 0 1 0 8.478",key:"1fwjs5"}],["path",{d:"M19.075 4.933a10 10 0 0 1 0 14.134",key:"ehdyv1"}],["path",{d:"M4.925 19.067a10 10 0 0 1 0-14.134",key:"1q22gi"}],["path",{d:"M7.753 16.239a6 6 0 0 1 0-8.478",key:"r2q7qm"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]],zh=Ue("radio",ob);/**
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 lb=[["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"}]],wn=Ue("refresh-cw",lb);/**
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 cb=[["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"}]],wd=Ue("rocket",cb);/**
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 db=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],ub=Ue("rotate-ccw",db);/**
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 mb=[["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"}]],Fh=Ue("save",mb);/**
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 hb=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],ea=Ue("search",hb);/**
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 pb=[["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"}]],Ei=Ue("send",pb);/**
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 fb=[["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"}]],no=Ue("server",fb);/**
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 gb=[["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"}]],Ja=Ue("settings",gb);/**
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 xb=[["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"}]],bb=Ue("shield-alert",xb);/**
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 vb=[["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"}]],yb=Ue("shield",vb);/**
518
+ * @license lucide-react v1.7.0 - ISC
519
+ *
520
+ * This source code is licensed under the ISC license.
521
+ * See the LICENSE file in the root directory of this source tree.
522
+ */const kb=[["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"}]],jb=Ue("skull",kb);/**
523
+ * @license lucide-react v1.7.0 - ISC
524
+ *
525
+ * This source code is licensed under the ISC license.
526
+ * See the LICENSE file in the root directory of this source tree.
527
+ */const wb=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],Vn=Ue("sparkles",wb);/**
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 Nb=[["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"}]],Oh=Ue("square-check-big",Nb);/**
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 Sb=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],ms=Ue("square",Sb);/**
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 Cb=[["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"}]],rs=Ue("target",Cb);/**
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 Eb=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],ei=Ue("terminal",Eb);/**
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 Mb=[["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"}]],so=Ue("text-wrap",Mb);/**
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 _b=[["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"}]],Jt=Ue("trash-2",_b);/**
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 Ab=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],Rb=Ue("trending-up",Ab);/**
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 Tb=[["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"}]],zc=Ue("triangle-alert",Tb);/**
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 Pb=[["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"}]],Nd=Ue("unlink",Pb);/**
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 Ib=[["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"}]],qi=Ue("user",Ib);/**
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 $b=[["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"}]],Uh=Ue("webhook",$b);/**
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 Db=[["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"}]],oc=Ue("workflow",Db);/**
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 Lb=[["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"}]],zb=Ue("wrench",Lb);/**
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 Fb=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],zt=Ue("x",Fb);/**
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 Ob=[["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"}]],In=Ue("zap",Ob),lc="fusion:version-reload",cc="fusion:version-update";function Ub(){try{if(sessionStorage.getItem(cc))return sessionStorage.removeItem(cc),!0}catch{}return!1}function Bh(e){if(sessionStorage.getItem(lc)){console.warn("[versionCheck] reload already attempted, suppressing",e);return}sessionStorage.setItem(lc,"1"),console.info("[versionCheck] reloading:",e),window.location.reload()}function Bb(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 Hb(e){return Bb(e)?(Bh(`chunk load error: ${e?.message??e}`),!0):!1}async function qb(){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 Ko=!1;async function Go(){if(!(Ko||document.visibilityState!=="visible")){Ko=!0;try{const e=await qb();if(e&&e!=="moi6ye0w-ca2a6431"){try{sessionStorage.setItem(cc,"1")}catch{}Bh(`build version changed: moi6ye0w-ca2a6431 -> ${e}`)}}finally{Ko=!1}}}function Vb(){window.setTimeout(()=>sessionStorage.removeItem(lc),5e3),document.addEventListener("visibilitychange",()=>{Go()}),window.addEventListener("focus",()=>{Go()}),window.setTimeout(()=>void Go(),2e3)}class Co extends a.Component{constructor(n){super(n),this.state={hasError:!1,error:null}}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,s){console.error("[ErrorBoundary]",n,s),!Hb(n)&&this.props.onError?.(n,s)}resetErrorBoundary=()=>{this.setState({hasError:!1,error:null})};render(){if(!this.state.hasError)return this.props.children;if(this.props.fallback)return this.props.fallback;const n=this.props.level??"page",i=n==="modal"?"This section encountered an error":"Something went wrong";return t.jsxs("div",{className:`error-boundary error-boundary--${n}`,children:[t.jsx("div",{className:"error-boundary__icon",children:t.jsx(zc,{size:40})}),t.jsx("div",{className:"error-boundary__title",children:i}),this.state.error&&t.jsx("pre",{className:"error-boundary__message",children:this.state.error.message}),t.jsxs("div",{className:"error-boundary__actions",children:[t.jsx("button",{className:"btn btn-primary",onClick:this.resetErrorBoundary,children:"Retry"}),t.jsx("button",{className:"btn",onClick:()=>window.location.reload(),children:"Reload page"})]})]})}}function Yn({children:e,onError:n}){return t.jsx(Co,{level:"page",onError:n,children:e})}function wi({children:e,onError:n}){return t.jsx(Co,{level:"modal",onError:n,children:e})}function Wb({children:e,onError:n}){return t.jsx(Co,{level:"root",onError:n,children:e})}const Kb="modulepreload",Gb=function(e){return"/"+e},Sd={},sn=function(n,s,i){let r=Promise.resolve();if(s&&s.length>0){let l=function(d){return Promise.all(d.map(m=>Promise.resolve(m).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),u=c?.nonce||c?.getAttribute("nonce");r=l(s.map(d=>{if(d=Gb(d),d in Sd)return;Sd[d]=!0;const m=d.endsWith(".css"),h=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${h}`))return;const g=document.createElement("link");if(g.rel=m?"stylesheet":Kb,m||(g.as="script"),g.crossOrigin="",g.href=d,u&&g.setAttribute("nonce",u),document.head.appendChild(g),m)return new Promise((p,f)=>{g.addEventListener("load",p),g.addEventListener("error",()=>f(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return r.then(l=>{for(const c of l||[])c.status==="rejected"&&o(c.reason);return n().catch(o)})},Fc="fn.authToken",Cd="token",Jb="fn_token";let ta,Ed=!1,io=!1;const dc="fn:auth-token-recovery-required";function Yb(){try{const e=window.localStorage.getItem(Fc);return e&&e.length>0?e:void 0}catch{return}}function Hh(e){try{window.localStorage.setItem(Fc,e)}catch{}}function Qb(){if(!(Ed||typeof window>"u")){Ed=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(Cd);if(!n)return;Hh(n),e.searchParams.delete(Cd);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function ra(){if(ta!==void 0)return ta;const e=Qb();if(e)return ta=e,e;const n=Yb();if(n)return ta=n,n}function Xb(e){ta=e,io=!1,Hh(e)}function Zb(){ta=void 0,io=!1;try{window.localStorage.removeItem(Fc)}catch{}}function Md(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function ev(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function tv(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!ev(e.protocol))return!1;const s=e.hostname===n.hostname,i=e.port===n.port,r=Md(e.protocol)===Md(n.protocol);return s&&i&&r}function nv(e){if(!(typeof window>"u"))try{const n=new URL(e,window.location.origin),s=e.startsWith("/");return{parsed:n,preserveRelativePath:s}}catch{return}}function Ks(e){const n=ra();if(!n||typeof window>"u")return e;const s=nv(e);return!s||!tv(s.parsed)?e:(s.parsed.searchParams.set(Jb,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function pi(e){const n=ra();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function sv(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function iv(){typeof window>"u"||io||(io=!0,window.dispatchEvent(new CustomEvent(dc)))}async function av(e){if(e.status===401)try{const n=e.clone();if(!(n.headers.get("content-type")??"").toLowerCase().includes("application/json"))return;const i=await n.json();sv(i)&&iv()}catch{}}function rv(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,ra();const e=window.fetch.bind(window);window.fetch=function(s,i){const r=ra(),o=typeof s=="string"?s:s instanceof URL?s.toString():s.url;if(!(()=>{try{const u=new URL(o,window.location.origin);return u.origin!==window.location.origin?!1:u.pathname.startsWith("/api/")||u.pathname==="/api"}catch{return o.startsWith("/api/")||o==="/api"}})())return e(s,i);const c=new Headers(i?.headers??(s instanceof Request?s.headers:void 0));return r&&!c.has("Authorization")&&c.set("Authorization",`Bearer ${r}`),e(s,{...i,headers:c}).then(u=>(av(u),u))}}class ov extends Error{status;details;constructor(n,s,i){super(n),this.name="ApiRequestError",this.status=s,this.details=i}}function lv(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function es(e){return`/api${e}`}async function D(e,n={}){const s=es(e),i=ra(),r=(()=>{if(i){const g=new Headers(n.headers??{});return g.has("Content-Type")||g.set("Content-Type","application/json"),pi(g)}if(!n.headers)return{"Content-Type":"application/json"};const h=new Headers(n.headers);return h.has("Content-Type")||h.set("Content-Type","application/json"),Object.fromEntries(h.entries())})(),o=await fetch(s,{...n,headers:r});if(o.status===204){if(!o.ok)throw new Error(`Request failed for ${s}: ${o.status} ${o.statusText}`);return}const l=o.headers.get("content-type")??"",c=await o.text(),u=l.includes("application/json");if(l.includes("text/html")||lv(c))throw new Error(`API returned HTML instead of JSON for ${s}. The endpoint may not be properly configured. (${o.status} ${o.statusText})`);if(!u){const h=c.length>160?`${c.slice(0,160)}...`:c;throw new Error(`API returned ${l||"an unknown content type"} instead of JSON for ${s}. (${o.status} ${o.statusText})${h?` Response: ${h}`:""}`)}let m;try{m=c?JSON.parse(c):null}catch{throw new Error(`API returned invalid JSON for ${s}. (${o.status} ${o.statusText})`)}if(!o.ok){const h=m;throw new ov(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return m}function xP(){return D("/health")}function bP(){return D("/updates/check")}function cv(e,n,s,i,r){const o=new URLSearchParams;s&&o.set("projectId",s),i&&o.set("q",i),r&&o.set("includeArchived","1");const l=o.size>0?`?${o.toString()}`:"";return D(`/tasks${l}`)}async function ao(e,n){const i=es(q(`/tasks/${e}`,n));for(let r=1;r<=2;r++){const o=await fetch(i,{headers:pi({"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 qh(e,n){const{title:s,description:i,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:u,modelPresetId:d,modelProvider:m,modelId:h,validatorModelProvider:g,validatorModelId:p,planningModelProvider:f,planningModelId:x,thinkingLevel:v,summarize:b,reviewLevel:y,executionMode:S,priority:k}=e;return D(q("/tasks",n),{method:"POST",body:JSON.stringify({title:s,description:i,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:u,modelPresetId:d,modelProvider:m,modelId:h,validatorModelProvider:g,validatorModelId:p,planningModelProvider:f,planningModelId:x,thinkingLevel:v,summarize:b,reviewLevel:y,executionMode:S,priority:k})})}function Zs(e,n,s){return D(q(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function dv(e,n,s,i,r,o,l,c){return D(q("/tasks/batch-update-models",c),{method:"POST",body:JSON.stringify({taskIds:e,modelProvider:n,modelId:s,validatorModelProvider:i,validatorModelId:r,planningModelProvider:o,planningModelId:l})})}function uv(e,n,s){return D(q(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n})})}function mv(e,n,s){const i=new URLSearchParams,r=i.size>0?`?${i.toString()}`:"";return D(q(`/tasks/${e}${r}`,n),{method:"DELETE"})}function hv(e,n){return D(q(`/tasks/${e}/merge`,n),{method:"POST"})}function pv(e,n){return D(q(`/tasks/${e}/retry`,n),{method:"POST"})}function fv(e,n){return D(q(`/tasks/${e}/duplicate`,n),{method:"POST"})}function Vh(e,n){return D(q(`/tasks/${e}/pause`,n),{method:"POST"})}function gv(e,n){return D(q(`/tasks/${e}/unpause`,n),{method:"POST"})}function xv(e,n){return D(q(`/tasks/${e}/archive`,n),{method:"POST"})}function bv(e,n){return D(q(`/tasks/${e}/unarchive`,n),{method:"POST"})}function vv(e){return D(q("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function yv(e,n){return D(q(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function kv(e,n){return D(q(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function jv(e){return D(q("/config",e))}function Eo(e){return D(q("/settings",e))}function _r(e,n){return D(q("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function wv(e){return D(q("/update-check",e))}function vP(e){return D(q("/remote/settings",e))}function yP(e,n){return D(q("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function kP(e){return D(q("/remote/status",e))}function jP(e,n){return D(q("/remote/provider/activate",n),{method:"POST",body:JSON.stringify({provider:e})})}function wP(e){return D(q("/remote/tunnel/start",e),{method:"POST"})}function NP(e){return D(q("/remote/tunnel/stop",e),{method:"POST"})}function SP(e){return D(q("/remote/token/persistent/regenerate",e),{method:"POST"})}function CP(e,n){return D(q("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function Wh(e,n,s){const i=new URLSearchParams;e&&i.set("format",e),i.set("tokenType",n),n==="short-lived"&&typeof s=="number"&&Number.isFinite(s)&&i.set("ttlMs",String(s));const r=i.toString();return r?`?${r}`:""}function EP(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:i}=e,r=Wh(null,s,i);return D(q(`/remote/url${r}`,n))}function MP(e="text",n={}){const{projectId:s,tokenType:i="persistent",ttlMs:r}=n,o=Wh(e,i,r);return D(q(`/remote/qr${o}`,s))}function _P(e){return D(q("/memory",e))}function AP(e,n){return D(q("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function RP(e){return D(q("/memory/files",e))}function TP(e,n){const s=`path=${encodeURIComponent(e)}`;return D(q(`/memory/file?${s}`,n))}function PP(e,n,s){return D(q("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function IP(e,n){let s,i=n;if(n!==void 0)s=e;else if(typeof e=="string"&&e.trim().length>0){const r=e.trim();r.includes("/")||r.endsWith(".md")||r.startsWith(".")?s=r:i=r}return D(q("/memory/compact",i),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function $P(e){return D(q("/memory/insights",e))}function DP(e,n){return D(q("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function LP(e){return D(q("/memory/extract",e),{method:"POST"})}function zP(e){return D(q("/memory/audit",e))}function FP(e){return D(q("/memory/stats",e))}function OP(e){return D(q("/memory/backend",e))}function UP(e){return D(q("/memory/install-qmd",e),{method:"POST"})}function BP(e,n){return D(q("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function Di(){return D("/settings/global")}function an(e){return D("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function HP(e){return D(q("/settings/scopes",e))}function qP(e){return D(q("/settings/pi-extensions",e))}function VP(e,n){return D(q("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function WP(e,n){return D(q("/settings/test-ntfy",n),{method:"POST",body:e?JSON.stringify(e):void 0})}function KP(){return D("/pi-settings")}async function GP(e){return D("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function JP(e){return D("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function YP(e){return D(q("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function sr(e,n,s){const i=new FormData;i.append("file",n);const r=await fetch(es(q(`/tasks/${e}/attachments`,s)),{method:"POST",headers:pi(),body:i}),o=await r.json();if(!r.ok)throw new Error(o.error||"Upload failed");return o}async function Nv(e,n,s){return D(q(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function _d(e,n,s){const i=new URLSearchParams;s?.limit!==void 0&&i.set("limit",String(s.limit)),s?.offset!==void 0&&i.set("offset",String(s.offset));const r=i.toString()?`?${i.toString()}`:"",o=q(`/tasks/${e}/logs${r}`,n),l=await fetch(es(o),{headers:pi()});if(!l.ok){const m=await l.json().catch(()=>({error:"Failed to fetch agent logs"}));throw new Error(m.error||`HTTP ${l.status}`)}const c=await l.json(),u=l.headers.has("X-Total-Count")?parseInt(l.headers.get("X-Total-Count"),10):c.length,d=l.headers.has("X-Has-More")?l.headers.get("X-Has-More")==="true":!1;return{entries:c,total:u,hasMore:d}}function Sv(e,n,s,i){return D(q(`/tasks/${e}/comments/${n}`,i),{method:"PATCH",body:JSON.stringify({text:s})})}function Cv(e,n,s){return D(q(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function Ev(e,n){return D(q(`/tasks/${e}/documents`,n))}function Mv(e,n,s){return D(q(`/tasks/${e}/documents/${n}/revisions`,s))}async function QP(e,n){const s=new URLSearchParams;e?.q&&s.set("q",e.q),e?.limit!==void 0&&s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset));const i=s.toString(),r=`/documents${i?`?${i}`:""}`;return D(q(r,n))}function XP(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const i=s.toString(),r=`/files/markdown-list${i?`?${i}`:""}`;return D(q(r,e))}function Ad(e,n,s,i,r){return D(q(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:i?.author,metadata:i?.metadata})})}function _v(e,n,s){return D(q(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function Av(e,n,s){return D(q(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function Rv(e,n,s){return D(q(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Tv(e,n){return D(q(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function Pv(e,n,s){return D(q(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function os(){return D("/models")}function Iv(){return D("/usage")}function $v(){return D("/providers/claude-cli/status")}async function ZP(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return D(`/providers/hermes/status${n}`)}async function eI(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return(await D(`/providers/hermes/profiles${n}`)).profiles??[]}async function tI(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return D(`/providers/openclaw/status${n}`)}async function nI(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),D(`/providers/paperclip/status?${n.toString()}`)}async function sI(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 iI(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 aI(e){return D("/providers/paperclip/cli-mint-key",{method:"POST",body:JSON.stringify(e)})}async function rI(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 Dv(e){return D("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function ir(){return D("/auth/status")}function Lv(e){return D("/auth/login",{method:"POST",body:JSON.stringify({provider:e})})}function zv(e){return D("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function Fv(e,n){return D("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function Ov(e){return D("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function Uv(e,n,s,i){return D("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:i})})}function Bv(e,n,s,i){return D(q("/github/issues/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function Hv(e,n,s){return D("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function qv(e,n,s,i){return D(q("/github/pulls/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function Vv(e){return D(q("/git/remotes",e))}function Wv(e){return D(q("/git/remotes/detailed",e))}function Kv(e,n,s){return D(q("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function Gv(e,n){return D(q(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Jv(e,n,s){return D(q(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function Yv(e,n,s){return D(q(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function Qv(e,n,s){return D(q(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function Xv(e,n){return D(q(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}async function Zv(e,n){return(await D(q("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:e})})).results}function Ar(e,n,s,i){return D(q("/terminal/sessions",i),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function Rd(e,n){return D(q(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function ey(e){return D(q("/terminal/sessions",e))}function Rs(e){return D(q("/git/status",e))}function ty(e,n){const s=e?`?limit=${e}`:"";return D(q(`/git/commits${s}`,n))}function ro(e,n){return D(q(`/git/commits/${e}/diff`,n))}function ny(e){return D(q("/git/commits/ahead",e))}function sy(e,n,s,i){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return D(q(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,i))}function Sa(e){return D(q("/git/branches",e))}function iy(e,n,s){const i=`?limit=${n}`;return D(q(`/git/branches/${encodeURIComponent(e)}/commits${i}`,s))}function ay(e){return D(q("/git/worktrees",e))}function ry(e,n,s){return D(q("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function oy(e,n){return D(q(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function Td(e,n,s){const i=n?"?force=true":"";return D(q(`/git/branches/${encodeURIComponent(e)}${i}`,s),{method:"DELETE"})}function ly(e,n){return D(q("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function cy(e){return D(q("/git/pull",e),{method:"POST"})}function dy(e){return D(q("/git/push",e),{method:"POST"})}function Rr(e){return D(q("/git/stashes",e))}function uy(e,n){return D(q("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function my(e,n,s){return D(q(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function hy(e,n){return D(q(`/git/stashes/${e}`,n),{method:"DELETE"})}function py(e,n,s){const i=new URLSearchParams;return i.set("path",e),i.set("staged",String(n)),D(q(`/git/diff/file?${i.toString()}`,s))}function Vi(e){return D(q("/git/changes",e))}function Pd(e,n){return D(q("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function fy(e,n){return D(q("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function Id(e,n){return D(q("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function gy(e,n){return D(q("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function xy(e){return D(q("/workspaces",e))}function by(e,n,s){const i=new URLSearchParams({workspace:e});return n&&i.set("path",n),s&&i.set("projectId",s),D(`/files?${i.toString()}`)}function vy(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),D(`/files/${encodeURIComponent(n)}?${i.toString()}`)}function yy(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),D(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function ky(e,n,s){const i=new URLSearchParams({q:e});return n&&i.set("workspace",n),s&&i.set("projectId",s),D(`/files/search?${i.toString()}`)}function jy(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),D(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function wy(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),D(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function Ny(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),D(`/files/${encodeURIComponent(n)}/delete?${i.toString()}`,{method:"POST"})}function Sy(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),D(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function Kh(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${i.toString()}`}function Cy(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${i.toString()}`}function Ey(e,n,s){return D(q("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function My(e,n,s,i){return D(q("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function _y(e,n,s){return D(q(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Gh(e,n,s){return D(q("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function Ay(e,n,s){return D(q("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Ry(e,n,s){return D(q("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Ty(e,n,s){return D(q("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const uc=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(uc))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function Py(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function hr(e,n,s={}){const i=s.maxReconnectAttempts??10;let r=null,o=!1,l=0,c=null,u=null,d=!1;const m=p=>{const f=p.lastEventId;if(!f)return!0;const x=Number.parseInt(f,10);return Number.isFinite(x)?u!==null&&x<=u?!1:(u=x,!0):!0},h=()=>{if(o)return;const p=Py(e,u),f=new EventSource(Ks(p));r=f,f.onopen=()=>{l=0,d=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},f.onmessage=x=>{const v=x;m(v)&&n.onMessage?.(v)};for(const[x,v]of Object.entries(n.events??{}))f.addEventListener(x,b=>{const y=b;m(y)&&v(y)});f.onerror=()=>{if(o||r!==f)return;if(f.readyState===EventSource.CONNECTING){d||(d=!0,s.onConnectionStateChange?.("reconnecting"));return}if(f.close(),l>=i){s.onFatalError?.("Connection lost");return}d=!0,s.onConnectionStateChange?.("reconnecting"),l+=1;const v=Math.min(1e3*2**(l-1),3e4);c=setTimeout(()=>{c=null,h()},v)}};h();const g={close:()=>{o=!0,c&&(clearTimeout(c),c=null),r?.close(),uc.delete(g)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return uc.add(g),g}function $d(e){const n=typeof e.source=="string"&&e.source.trim().length>0?e.source.trim():"root",s=n==="root"?".":n,i=e.name,r=typeof e.packagePath=="string"&&e.packagePath.trim().length>0?e.packagePath.trim():s,o=typeof e.confidence=="number"?e.confidence:1,l=n==="root"?"root":n,c=typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():"project";return{name:e.name,command:e.command,scriptName:i,packagePath:r,confidence:o,cwd:s,source:n,workspaceName:typeof e.packageName=="string"?e.packageName:void 0,label:`${c} · ${i} (${l})`}}function oa(e){const n=e.status,s=n==="starting"||n==="running"||n==="failed"||n==="stopped"?n:"stopped",i=typeof e.previewUrl=="string"?e.previewUrl:e.detectedUrl,r=typeof e.manualPreviewUrl=="string"?e.manualPreviewUrl:e.manualUrl;return{id:typeof e.id=="string"?e.id:"",name:typeof e.name=="string"&&e.name.length>0?e.name:"default",status:s,command:typeof e.command=="string"?e.command:"",scriptName:typeof e.scriptId=="string"?e.scriptId:"",cwd:typeof e.cwd=="string"?e.cwd:"",pid:e.pid,startedAt:e.startedAt,previewUrl:i,detectedUrl:typeof e.detectedUrl=="string"?e.detectedUrl:i,detectedPort:e.detectedPort,manualPreviewUrl:r,manualUrl:typeof e.manualUrl=="string"?e.manualUrl:r,logs:Array.isArray(e.logHistory)?e.logHistory:[],exitCode:e.exitCode}}function Iy(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 $y(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((i,r)=>Iy(i,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function Dy(e,n){const s=typeof n.maxLines=="number"&&Number.isFinite(n.maxLines)?Math.max(1,Math.floor(n.maxLines)):100,i=typeof n.offset=="number"&&Number.isFinite(n.offset)?Math.max(0,Math.floor(n.offset)):0,r=typeof n.lastEventId=="number"&&Number.isFinite(n.lastEventId)?Math.max(0,Math.floor(n.lastEventId)):null,o=e.length,l=e.map((d,m)=>({id:m+1,text:d,stream:"stdout",timestamp:""}));if(r!==null)return{lines:l.filter(d=>d.id>r).slice(0,s),totalLines:o};const c=Math.max(o-i,0),u=Math.max(c-s,0);return{lines:l.slice(u,c),totalLines:o}}function Dd(e){return Array.isArray(e)?e.map($d):(e.candidates??[]).map($d)}async function Ly(e){try{const n=await D(q("/dev-server/candidates",e));return Dd(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await D(q("/dev-server/detect",e));return Dd(s)}throw n}}function Oc(e){return D(q("/dev-server/status",e)).then(oa)}async function oI(e={},n){const s=new URLSearchParams;typeof e.maxLines=="number"&&Number.isFinite(e.maxLines)&&s.set("maxLines",String(Math.max(1,Math.floor(e.maxLines)))),typeof e.offset=="number"&&Number.isFinite(e.offset)&&s.set("offset",String(Math.max(0,Math.floor(e.offset)))),typeof e.lastEventId=="number"&&Number.isFinite(e.lastEventId)&&s.set("lastEventId",String(Math.max(0,Math.floor(e.lastEventId))));const i=s.size>0?`?${s.toString()}`:"";try{const r=await D(q(`/dev-server/logs/history${i}`,n));return $y(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await Oc(n);return Dy(o.logs,e)}throw r}}function zy(e,n){const s=e.cwd??e.packagePath??".",i=e.scriptName;return D(q("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:i,scriptId:i,cwd:s,packagePath:e.packagePath})}).then(oa)}function Fy(e){return D(q("/dev-server/stop",e),{method:"POST"}).then(oa)}function Oy(e){return D(q("/dev-server/restart",e),{method:"POST"}).then(oa)}async function Uy(e,n){const s=typeof e=="string"?{url:e}:e;try{const i=await D(q("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return oa(i)}catch(i){if(i instanceof Error&&/\/dev-server\/preview-url/.test(i.message)){const r=await D(q("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return oa(r)}throw i}}function lI(e){return es(q("/dev-server/logs/stream",e))}async function cI(e){try{return(await D(q("/devserver",e))).sessions??[]}catch{try{const n=await Oc(e);return[{config:{id:n.id??"default",name:n.name??"Dev Server",command:n.command??"",cwd:n.cwd??"."},status:n.status,runtime:n.pid?{pid:n.pid,startedAt:n.startedAt??new Date().toISOString(),exitCode:n.exitCode??void 0,previewUrl:n.previewUrl}:void 0,previewUrl:n.previewUrl??n.detectedUrl??void 0,logHistory:(n.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}]}catch{return[]}}}async function dI(e,n){try{return await D(q(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await Oc(n);return!e||e==="default"||e===s.id?{config:{id:s.id??"default",name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}:null}catch{return null}}}async function uI(e,n){try{return await D(q(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await zy({command:""},n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}}}async function mI(e,n){try{return await D(q(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await Fy(n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}}}async function hI(e,n){try{return await D(q(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await Oy(n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}}}async function pI(e,n,s){try{const i=await D(q(`/devserver/${encodeURIComponent(e)}/preview`,s),{method:"POST",body:JSON.stringify({url:n})});return{url:i.url??null,source:i.source??null}}catch{const i=await Uy({url:n},s);return{url:i.previewUrl??i.manualUrl??null,source:"manual"}}}async function fI(e){try{return(await D(q("/devserver/detect",e))).candidates??[]}catch{try{return(await Ly(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function gI(e,n){return es(q(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function pr(e,n,s=25e3){const i=setInterval(()=>{kj(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(i)}}}function By(e,n){return es(q(`/planning/${encodeURIComponent(e)}/stream`,n))}function Hy(e,n,s,i){const r=By(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},u=hr(r,{onOpen:()=>{c(),o=pr(e,n)},onMessage:d=>{d.data.startsWith(":")},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},question:d=>{try{s.onQuestion?.(JSON.parse(d.data))}catch(m){console.error("[planning] Failed to parse question event:",m)}},summary:d=>{try{s.onSummary?.(JSON.parse(d.data))}catch(m){console.error("[planning] Failed to parse summary event:",m)}},error:d=>{try{const m=JSON.parse(d.data);s.onError?.(m.message||m)}catch{s.onError?.(d.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{c(),s.onError?.(d)}});return l={close:()=>{c(),u.close()},isConnected:u.isConnected},l}function fr(e,n){const s=new URLSearchParams;n?.scope&&s.set("scope",n.scope),n?.projectId&&s.set("projectId",n.projectId);const i=s.toString();return i?`${e}?${i}`:e}function qy(e){return D(fr("/routines",e))}function Vy(e,n){return D(fr("/routines",n),{method:"POST",body:JSON.stringify(e)})}function Ld(e,n,s){return D(fr(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function Wy(e,n){await D(fr(`/routines/${e}`,n),{method:"DELETE"})}function Ky(e,n){return D(fr(`/routines/${e}/trigger`,n),{method:"POST"})}function zd(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 Gy(e){const n=q("/activity",e);return D(n,{method:"DELETE"})}function Mo(e){return D(q("/workflow-steps",e))}function Fd(e,n){return D(q("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function Jy(e,n,s){return D(q(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Yy(e,n){return D(q(`/workflow-steps/${e}`,n),{method:"DELETE"})}function Od(e,n){return D(q(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function Qy(e,n){return D(q(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function Xy(){return D("/workflow-step-templates")}function Zy(e,n){return D(q(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function ar(e){return D(q("/scripts",e))}function ek(e,n,s){return D(q("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function tk(e,n){return D(q(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function Jh(e,n,s){return(await D(q("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const Tr={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 Yh(e){if(!(e instanceof Error))return Tr.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?Tr.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?Tr.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:Tr.NETWORK}function nk(e,n){return D(q("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function sk(e,n,s){return D(q(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function ik(e,n){return es(q(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function ak(e,n,s,i){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=hr(ik(e,n),{onOpen:()=>{l(),r=pr(e,n)},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},subtasks:u=>{try{s.onSubtasks?.(JSON.parse(u.data))}catch(d){console.error("[subtasks] Failed to parse subtasks event:",d)}},error:u=>{try{const d=JSON.parse(u.data),m=typeof d=="string"&&d.length>0?d:null;s.onError?.(m||"Stream error")}catch{s.onError?.("Stream error")}o?.close()},complete:()=>{s.onComplete?.(),o?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{l(),s.onError?.(u)}});return o={close:()=>{l(),c.close()},isConnected:c.isConnected},o}function rk(e,n,s,i){return D(q("/subtasks/create-tasks",i),{method:"POST",body:JSON.stringify({sessionId:e,parentTaskId:s,subtasks:n.map(r=>({tempId:r.id,title:r.title,description:r.description,size:r.suggestedSize,dependsOn:r.dependsOn}))})})}function Qh(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 ok(e,n,s){if(!n||n===s)return e;const i="/api",r=e.startsWith(i)?e.slice(i.length):e;return`/proxy/${encodeURIComponent(n)}${r}`}function _o(e,n){const{nodeId:s,localNodeId:i,...r}=n??{},o=ok(e,s,i);return D(o,r)}function xa(e,n){const s=new URLSearchParams;e?.state&&s.set("state",e.state),e?.role&&s.set("role",e.role),e?.includeEphemeral===!0&&s.set("includeEphemeral","true"),n&&s.set("projectId",n);const i=s.size>0?`?${s.toString()}`:"";return D(`/agents${i}`)}function Xh(e,n){return D(q(`/agents/${encodeURIComponent(e)}`,n))}function lk(e,n){return D(q("/agents",n),{method:"POST",body:JSON.stringify(e)})}function ck(e,n,s){return D(q(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function xI(e,n,s){return D(q(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function bI(e,n,s){return D(q(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function vI(e,n,s){return D(q(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function yI(e,n){return D(q(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function kI(e,n,s){const i=`path=${encodeURIComponent(n)}`;return D(q(`/agents/${encodeURIComponent(e)}/memory/file?${i}`,s))}function jI(e,n,s,i){return D(q(`/agents/${encodeURIComponent(e)}/memory/file`,i),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function dk(e,n,s){return D(q(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function uk(e,n){return D(q(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function wI(e,n,s){const i=new URLSearchParams;i.set("limit",String(n)),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return D(`/agents/${encodeURIComponent(e)}/runs${r}`)}function NI(e,n,s){return D(q(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function SI(e,n,s){return D(q(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function CI(e,n,s){const i=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return D(q(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:i,triggerDetail:r})})}function EI(e,n){return D(q(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function mk(e){return D(q("/agents/stats",e))}function MI(e,n){return D(q(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function _I(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeEphemeral&&s.set("includeEphemeral","true");const i=s.toString();return D(`/agents/org-tree${i?`?${i}`:""}`)}function AI(e,n){return D(q(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function Ud(e,n,s){return D(q(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function RI(e,n){return D(q(`/agents/${encodeURIComponent(e)}/tasks`,n))}function TI(){return D("/agents/companies")}function PI(e,n){return D(q("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function II(e,n){return D(q("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function $I(e,n){return D(q(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function DI(e){return D(q("/backups",e))}function LI(e){return D(q("/backups",e),{method:"POST"})}function zI(e,n){const s=q("/settings/export",n),i=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return D(i)}function FI(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 Bd(){return D("/projects/across-nodes")}function Ya(e,n){D("/_perf/dashboard-load",{method:"POST",body:JSON.stringify({source:e,message:n})}).catch(()=>{})}function Hd(){return D("/nodes")}function hk(e){return D("/nodes",{method:"POST",body:JSON.stringify(e)})}function pk(e,n){return D(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function fk(e){return D(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function gk(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 OI(e,n,s,i){const r=s&&s!==i?s:void 0,o=new URLSearchParams;e&&o.set("path",e),n&&o.set("showHidden","true"),r&&o.set("nodeId",r);const l=ra();l&&o.set("fn_token",l);const c=o.toString(),u=`/browse-directory${c?`?${c}`:""}`;return D(u)}function xk(e){return D("/projects",{method:"POST",body:JSON.stringify(e)})}function Zh(e){return D(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function qd(e){return D(`/projects/${encodeURIComponent(e)}/health`)}function bk(e){return D(q("/executor/stats",e))}function vk(e){return D(q("/system-stats",e))}function yk(e){return D(q("/kill-vitest",e),{method:"POST"})}function Vd(e){const n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e.limit)),e?.since&&n.set("since",e.since),e?.projectId&&n.set("projectId",e.projectId),e?.type&&n.set("type",e.type);const s=n.size>0?`?${n.toString()}`:"";return D(`/activity-feed${s}`)}function kk(e){return D(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function jk(e){return D(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function UI(){return D("/global-concurrency")}function BI(e){return D("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function wk(e,n){return D(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function ep(e,n,s){const i=new URLSearchParams;n&&i.set("worktree",n),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return D(`/tasks/${encodeURIComponent(e)}/diff${r}`)}function Nk(e){return D(q("/missions",e))}function Sk(e,n){return D(q("/missions",n),{method:"POST",body:JSON.stringify(e)})}function tp(e,n){return D(q(`/missions/${encodeURIComponent(e)}`,n))}function Ck(e,n,s){return D(q(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Ek(e,n){return D(q(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Mk(e,n,s){const i=new URLSearchParams;i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset));const r=i.size>0?`?${i.toString()}`:"";return D(q(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function _k(e){return D(q("/missions/health",e))}function Ak(e,n,s){return D(q(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function Rk(e,n,s){return D(q(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Tk(e,n){return D(q(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Pk(e,n,s){return D(q(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function Ik(e,n,s){return D(q(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function $k(e,n){return D(q(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Dk(e,n){return D(q(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function Lk(e,n,s){return D(q(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function zk(e,n,s){return D(q(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Fk(e,n){return D(q(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Ok(e,n,s){return D(q(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function Uk(e,n){return D(q(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function Bk(e,n,s,i){return D(q(`/missions/features/${encodeURIComponent(e)}/triage`,i),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s})})}function Hk(e,n){return D(q(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST"})}function Jo(e,n){return D(q(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function qk(e,n,s){return D(q(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function Vk(e,n,s){return D(q(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Wk(e,n,s){return D(q(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function Kk(e,n,s){return D(q(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function Gk(e,n){return D(q(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function Yo(e,n){return D(q(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function Wd(e,n){return D(q(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function Jk(e,n){return D(q(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function Kd(e,n){return D(q(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function Yk(e,n,s){const i=new URLSearchParams;i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset));const r=i.size>0?`?${i.toString()}`:"";return D(q(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function Qk(e,n){return D(q(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function Xk(e,n){return D(q(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function Zk(e,n){return D(q(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function ej(e,n){return D(q(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function tj(e,n,s){return D(q(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function nj(e,n,s){return D(q("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function sj(e,n,s,i){return D(q("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function ij(e,n,s){return D(q(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function np(e,n,s){return D(q("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function aj(e,n,s){return D(q("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function rj(e,n,s,i){const r=es(q(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=hr(r,{onOpen:()=>{c(),o=pr(e,n)},onMessage:d=>{d.data.startsWith(":")},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},question:d=>{try{s.onQuestion?.(JSON.parse(d.data))}catch(m){console.error("[mission-interview] Failed to parse question event:",m)}},summary:d=>{try{s.onSummary?.(JSON.parse(d.data))}catch(m){console.error("[mission-interview] Failed to parse summary event:",m)}},error:d=>{try{const m=JSON.parse(d.data);s.onError?.(m.message||m)}catch{s.onError?.(d.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{c(),s.onError?.(d)}});return l={close:()=>{c(),u.close()},isConnected:u.isConnected},l}function gr(e,n,s){return q(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function xr(e,n,s){return q(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function oj(e,n){return D(gr(e,"/start",n),{method:"POST"})}function lj(e,n,s,i){return D(gr(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function cj(e,n,s,i){const r=es(gr(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=hr(r,{onOpen:()=>{c(),o=pr(e,n)},onMessage:d=>{d.data.startsWith(":")},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},question:d=>{try{s.onQuestion?.(JSON.parse(d.data))}catch(m){console.error("[milestone-interview] Failed to parse question event:",m)}},summary:d=>{try{s.onSummary?.(JSON.parse(d.data))}catch(m){console.error("[milestone-interview] Failed to parse summary event:",m)}},error:d=>{try{const m=JSON.parse(d.data);s.onError?.(m.message||m)}catch{s.onError?.(d.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{c(),s.onError?.(d)}});return l={close:()=>{c(),u.close()},isConnected:u.isConnected},l}function dj(e,n,s){return D(gr(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function uj(e,n){return D(gr(e,"/skip",n),{method:"POST"})}function mj(e,n){return D(xr(e,"/start",n),{method:"POST"})}function hj(e,n,s,i){return D(xr(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function pj(e,n,s,i){const r=es(xr(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=hr(r,{onOpen:()=>{c(),o=pr(e,n)},onMessage:d=>{d.data.startsWith(":")},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},question:d=>{try{s.onQuestion?.(JSON.parse(d.data))}catch(m){console.error("[slice-interview] Failed to parse question event:",m)}},summary:d=>{try{s.onSummary?.(JSON.parse(d.data))}catch(m){console.error("[slice-interview] Failed to parse summary event:",m)}},error:d=>{try{const m=JSON.parse(d.data);s.onError?.(m.message||m)}catch{s.onError?.(d.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{c(),s.onError?.(d)}});return l={close:()=>{c(),u.close()},isConnected:u.isConnected},l}function fj(e,n,s){return D(xr(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function gj(e,n){return D(xr(e,"/skip",n),{method:"POST"})}async function xj(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 HI(e){return D(q("/roadmaps",e))}function qI(e,n){return D(q("/roadmaps",n),{method:"POST",body:JSON.stringify(e)})}function VI(e,n){return D(q(`/roadmaps/${encodeURIComponent(e)}`,n))}function WI(e,n,s){return D(q(`/roadmaps/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function KI(e,n){return D(q(`/roadmaps/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function GI(e,n,s){return D(q(`/roadmaps/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function JI(e,n,s){return D(q(`/roadmaps/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function YI(e,n){return D(q(`/roadmaps/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function QI(e,n,s){return D(q(`/roadmaps/milestones/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function XI(e,n,s){return D(q(`/roadmaps/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function ZI(e,n){return D(q(`/roadmaps/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function e$(e,n,s){return D(q(`/roadmaps/${encodeURIComponent(e)}/milestones/reorder`,s),{method:"POST",body:JSON.stringify({orderedMilestoneIds:n})})}function t$(e,n,s){return D(q(`/roadmaps/milestones/${encodeURIComponent(e)}/features/reorder`,s),{method:"POST",body:JSON.stringify({orderedFeatureIds:n})})}function n$(e,n,s,i){return D(q(`/roadmaps/features/${encodeURIComponent(e)}/move`,i),{method:"POST",body:JSON.stringify({targetMilestoneId:n,targetIndex:s})})}function s$(e,n){return D(q(`/roadmaps/${encodeURIComponent(e)}/handoff`,n))}function i$(e,n,s,i){return D(q(`/roadmaps/${encodeURIComponent(e)}/suggestions/milestones`,i),{method:"POST",body:JSON.stringify({goalPrompt:n.trim(),...s!==void 0?{count:s}:{}})})}function a$(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 r$(e){return D(q("/todos",e))}function o$(e,n){const s={title:e};return D(q("/todos",n),{method:"POST",body:JSON.stringify(s)})}function l$(e,n,s){const i={title:n};return D(q(`/todos/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(i)})}function c$(e,n){return D(q(`/todos/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function d$(e,n,s){const i={text:n};return D(q(`/todos/${encodeURIComponent(e)}/items`,s),{method:"POST",body:JSON.stringify(i)})}function u$(e,n,s){const i=n;return D(q(`/todos/items/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(i)})}function m$(e,n){return D(q(`/todos/items/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function h$(e,n,s){return D(q(`/todos/${encodeURIComponent(e)}/items/reorder`,s),{method:"POST",body:JSON.stringify({itemIds:n})})}function la(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function Uc(e){const n=e?`?projectId=${encodeURIComponent(e)}`:"",s=await fetch(es(`/ai-sessions${n}`),{headers:pi()});return s.ok?(await s.json()).sessions??[]:[]}async function ti(e){const n=await fetch(es(`/ai-sessions/${encodeURIComponent(e)}`),{headers:pi()});return n.ok?n.json():null}async function bj(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 vj(e,n){return D(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function yj(e,n){return D(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function sp(e){await fetch(es(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:pi()})}function kj(e,n){return D(q(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function jj(e,n){const s=new URLSearchParams;s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),e?.unreadOnly&&s.set("unreadOnly","true"),e?.type&&s.set("type",e.type),n&&s.set("projectId",n);const i=s.size>0?`?${s.toString()}`:"";return D(`/messages/inbox${i}`)}function wj(e,n){const s=new URLSearchParams;s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),e?.type&&s.set("type",e.type),n&&s.set("projectId",n);const i=s.size>0?`?${s.toString()}`:"";return D(`/messages/outbox${i}`)}function ip(e){return D(q("/messages/unread-count",e))}function Nj(e,n){return D(q("/messages",n),{method:"POST",body:JSON.stringify(e)})}function Sj(e,n){return D(q(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function Cj(e){return D(q("/messages/read-all",e),{method:"POST"})}function Ej(e,n){return D(q(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Mj(e,n,s){const i=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return D(q(i,s))}function _j(e,n){return D(q(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function p$(e,n,s){const i=new URLSearchParams;i.set("limit",String(n)),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return D(`/agents/${encodeURIComponent(e)}/reflections${r}`)}function f$(e,n){return D(q(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function g$(e,n,s){const i=new URLSearchParams;s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return D(`/agents/${encodeURIComponent(e)}/performance${r}`)}function x$(e,n,s){const i=new URLSearchParams;i.set("limit",String(n.limit)),n?.category&&i.set("category",n.category),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return D(`/agents/${encodeURIComponent(e)}/ratings${r}`)}function b$(e,n,s){return D(q(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function v$(e,n){return D(q(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function y$(e,n,s){return D(q(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function k$(e,n){return D(q(`/agents/${encodeURIComponent(e)}/budget`,n))}function j$(e,n){return D(q(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function w$(e){return D(q("/plugins",e))}async function N$(e,n){return D(q("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function S$(e,n){return D(q(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function C$(e,n){return D(q(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function E$(e,n){return D(q(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function M$(e,n){return D(q(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function _$(e,n,s){return D(q(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function A$(e,n){return D(q(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function Aj(e){return D(q("/plugins/ui-slots",e))}async function R$(e){return D(q("/plugins/runtimes",e))}async function T$(e){return(await D(q("/skills/discovered",e))).skills}async function P$(e,n,s){return D(q("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function I$(e,n,s){const i=new URLSearchParams;e&&i.set("q",e),i.set("limit",String(n));const r=i.size>0?`?${i.toString()}`:"";return D(q(`/skills/catalog${r}`,s))}async function $$(e,n){return(await D(q(`/skills/${encodeURIComponent(e)}/content`,n))).content}function D$(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const i=s.toString();return D(`/chat/sessions${i?`?${i}`:""}`)}async function Rj(e,n){const s=e.agentId.trim();if(!s)throw new Error("agentId is required");const i=e.modelProvider?.trim(),r=e.modelId?.trim();if(i&&!r||!i&&r)throw new Error("Both modelProvider and modelId must be provided together, or neither should be provided");const o=new URLSearchParams;return o.set("lookup","resume"),o.set("agentId",s),n&&o.set("projectId",n),i&&r&&(o.set("modelProvider",i),o.set("modelId",r)),{session:(await D(`/chat/sessions?${o.toString()}`)).sessions[0]??null}}function Tj(e,n){return D(q("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function L$(e,n,s){return D(q(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function z$(e,n){return D(q(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Gd(e,n,s){const i=new URLSearchParams;n?.limit!==void 0&&i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset)),n?.before&&i.set("before",n.before);const r=i.toString();return D(q(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function Pj(e,n){return D(q(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function Ij(e,n,s,i,r){const o=es(q(`/chat/sessions/${encodeURIComponent(e)}/messages`,i)),l=new AbortController;let c=!1;const u=(d,m)=>{if(!(!d||!m))switch(d){case"thinking":try{s.onThinking?.(JSON.parse(m))}catch{s.onThinking?.(m)}break;case"text":try{s.onText?.(JSON.parse(m))}catch{s.onText?.(m)}break;case"tool_start":try{s.onToolStart?.(JSON.parse(m))}catch{}break;case"tool_end":try{s.onToolEnd?.(JSON.parse(m))}catch{}break;case"done":try{s.onDone?.(JSON.parse(m))}catch{s.onDone?.({messageId:""})}break;case"error":try{const h=JSON.parse(m);s.onError?.(h.message||h)}catch{s.onError?.(m||"Stream error")}break}};return(async()=>{try{const d=await fetch(o,{method:"POST",headers:pi({"Content-Type":"application/json"}),body:JSON.stringify({content:n}),signal:l.signal});if(!d.ok){const v=await d.text();let b=`Request failed: ${d.status}`;try{b=JSON.parse(v).error||b}catch{}s.onError?.(b);return}if(!d.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected");const m=d.body.getReader(),h=new TextDecoder;let g="",p="",f=[];const x=(v,b=!1)=>{g+=v;const y=g.split(`
603
+ `);g=y.pop()||"",b&&g.length>0&&(y.push(g),g="");for(const S of y){const k=S.endsWith("\r")?S.slice(0,-1):S;if(k.startsWith("event:"))p=k.slice(6).trim();else if(k.startsWith("data:")){const M=k.slice(5);f.push(M.startsWith(" ")?M.slice(1):M)}else if(k===""){const M=f.join(`
604
+ `);u(p,M),p="",f=[]}}if(b&&p&&f.length>0){const S=f.join(`
605
+ `);u(p,S),p="",f=[]}};for(;;){const{done:v,value:b}=await m.read();if(v){x(h.decode(),!0);break}x(h.decode(b,{stream:!0}))}}catch(d){if(d instanceof DOMException&&d.name==="AbortError"){c||s.onError?.("Connection aborted");return}if(c)return;s.onError?.(d instanceof Error?d.message:"Connection error")}})(),{close:()=>{c=!0,l.abort()},isConnected:()=>!c}}function F$(e={},n){const s=new URLSearchParams;e.category&&s.set("category",e.category),e.status&&s.set("status",e.status),e.runId&&s.set("runId",e.runId),e.limit!==void 0&&s.set("limit",String(e.limit)),e.offset!==void 0&&s.set("offset",String(e.offset));const i=s.size>0?`?${s.toString()}`:"";return D(q(`/insights${i}`,n))}function O$(e,n){return D(q(`/insights/${encodeURIComponent(e)}/dismiss`,n),{method:"POST"})}function U$(e="manual",n,s){return D(q("/insights/run",s),{method:"POST",body:JSON.stringify({trigger:e,inputMetadata:n})})}function B$(e){return D(q("/insights/runs",e))}function H$(e,n){return D(q(`/insights/${encodeURIComponent(e)}/create-task`,n),{method:"POST"})}function $j(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 Dj({node:e,showDetails:n=!1}){if(!e||e.type==="local")return t.jsx("div",{className:"node-status-indicator node-status-indicator--local",children:t.jsx("span",{className:"node-status-indicator__label",children:"Local"})});const{label:s,dotClass:i}=$j(e.status),r=e.status==="connecting";return t.jsxs("div",{className:"node-status-indicator node-status-indicator--remote",children:[t.jsx("span",{className:`node-status-indicator__dot ${i}`,children:r&&t.jsx("span",{className:"node-status-indicator__spinner"})}),t.jsx("span",{className:"node-status-indicator__name",children:e.name}),n&&t.jsxs("span",{className:"node-status-indicator__details",children:[e.type," · ",s]})]})}const Jd=new Map,Lj=6e4;function ap(e){const[n,s]=a.useState([]),[i,r]=a.useState(!0),[o,l]=a.useState(null),c=a.useRef(!1),u=a.useRef(!1),d=a.useCallback(m=>n.filter(h=>h.slot.slotId===m),[n]);return a.useEffect(()=>{const m=e??"default";let h=!1;async function g(){const p=Jd.get(m);if(p&&Date.now()<p.expiresAt){if(h||u.current)return;s(p.slots),r(!1);return}!c.current&&r(!0),l(null);try{const x=await Aj(e);if(h||u.current)return;Jd.set(m,{slots:x,expiresAt:Date.now()+Lj}),s(x),c.current=!0}catch(x){if(h||u.current)return;l(x instanceof Error?x.message:"Failed to fetch UI slots"),c.current=!0}finally{!h&&!u.current&&r(!1)}}return g(),()=>{h=!0}},[e]),a.useEffect(()=>{c.current=!1,u.current=!1},[e]),a.useEffect(()=>()=>{u.current=!0},[]),a.useMemo(()=>({slots:n,getSlotsForId:d,loading:i,error:o}),[n,d,i,o])}function Ao({slotId:e,projectId:n}){const{getSlotsForId:s,loading:i,error:r}=ap(n);if(i||r||!e)return null;const o=s(e);return o.length===0?null:t.jsx(Co,{level:"page",children:t.jsx(t.Fragment,{children:o.map(l=>t.jsx("div",{"data-plugin-slot":!0,"data-slot-id":l.slot.slotId,"data-plugin-id":l.pluginId,"data-component-path":l.slot.componentPath,"aria-label":l.slot.label},`${l.pluginId}-${l.slot.slotId}`))})})}function zj(){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 br(){const[e,n]=a.useState(zj);return a.useEffect(()=>{if(typeof window>"u")return;const s=window.matchMedia("(max-width: 768px)"),i=window.matchMedia("(min-width: 769px) and (max-width: 1024px)"),r=()=>{s.matches?n("mobile"):i.matches?n("tablet"):n("desktop")};return s.addEventListener("change",r),i.addEventListener("change",r),()=>{s.removeEventListener("change",r),i.removeEventListener("change",r)}},[]),e}const rp={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function Fj({projects:e,currentProject:n,onViewAll:s,onSelectProject:i}){const[r,o]=a.useState(!1),l=a.useRef(null);a.useEffect(()=>{if(!r)return;const u=d=>{l.current&&!l.current.contains(d.target)&&o(!1)};return document.addEventListener("mousedown",u),()=>document.removeEventListener("mousedown",u)},[r]),a.useEffect(()=>{if(!r)return;const u=d=>{d.key==="Escape"&&o(!1)};return document.addEventListener("keydown",u),()=>document.removeEventListener("keydown",u)},[r]);const c=a.useCallback(u=>{i?.(u),o(!1)},[i]);return t.jsx("div",{className:"project-selector",ref:l,children:e.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:`project-selector-trigger${r?" project-selector-trigger--open":""}`,onClick:()=>o(u=>!u),title:n?.name?`Switch project (current: ${n.name})`:"Switch project","aria-label":"Switch project","aria-expanded":r,"aria-haspopup":"listbox","data-testid":"project-selector-trigger",children:[t.jsx("span",{className:"project-selector-trigger-label",children:n?.name??"Projects"}),t.jsx(qt,{size:12,className:`project-selector-chevron${r?" project-selector-chevron--open":""}`})]}),r&&t.jsxs("div",{className:"project-selector-dropdown",role:"listbox","aria-label":"Select project","data-testid":"project-selector-dropdown",children:[e.map(u=>{const d=n?.id===u.id,m=rp[u.status]?.color;return t.jsxs("button",{className:`project-selector-item${d?" project-selector-item--current":""}`,onClick:()=>c(u),role:"option","aria-selected":d,children:[t.jsx("span",{className:"project-selector-dot",style:{backgroundColor:m||"var(--text-muted)"}}),t.jsxs("div",{className:"project-selector-info",children:[t.jsx("span",{className:"project-selector-name",children:u.name}),t.jsx("span",{className:"project-selector-path",children:u.path.split("/").slice(-2).join("/")})]}),d&&t.jsx(Rn,{size:14,className:"project-selector-check"})]},u.id)}),t.jsx("div",{className:"project-selector-divider",role:"presentation"}),t.jsx("button",{className:"project-selector-manage",onClick:()=>{s(),o(!1)},"data-testid":"manage-projects-action",children:"Manage Projects"})]})]})})}function Yd({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 Oj({onOpenSettings:e,onOpenGitHubImport:n,onOpenPlanning:s,onResumePlanning:i,activePlanningSessionCount:r=0,onOpenUsage:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:u,mailboxUnreadCount:d=0,onOpenSchedules:m,onOpenGitManager:h,onOpenNodes:g,showNodesButton:p,onOpenWorkflowSteps:f,onOpenScripts:x,onRunScript:v,onToggleTerminal:b,onOpenFiles:y,filesOpen:S,globalPaused:k,enginePaused:M,onToggleGlobalPause:w,onToggleEnginePause:_,view:N="board",onChangeView:L,showSkillsTab:T,showAgentsTab:I,searchQuery:z="",onSearchChange:K,projects:P=[],currentProject:E,onSelectProject:R,onViewAllProjects:B,projectId:G,isElectron:X=!1,mobileNavEnabled:C,availableNodes:$=[],currentNode:A,onSelectNode:j,isRemote:J=!1,experimentalFeatures:W}){const oe=br(),he=oe==="mobile",fe=he||oe==="tablet",U=he&&C,[Ne,ee]=a.useState(!1),[ve,ue]=a.useState(!1),[ye,ie]=a.useState(!1),[Me,ze]=a.useState(!1),[Be,Je]=a.useState(!1),[Ye,Ge]=a.useState(!1),[it,_e]=a.useState(!1),[Fe,ae]=a.useState(!1),[be,ne]=a.useState(!1),[Ie,Pe]=a.useState(!1),[ce,le]=a.useState(!1),[$e,at]=a.useState({}),[tt,V]=a.useState(!1),[de,Z]=a.useState(-1),[we,pe]=a.useState(null),[Te,Qe]=a.useState({}),[Ee,Re]=a.useState(!1),Le=a.useRef(null),ct=a.useRef(null),Se=a.useRef(null),mt=a.useRef(null),gt=a.useRef(null),wt=a.useRef(null),yt=a.useRef(!1),kt=a.useRef(null),Ct=a.useRef(null),Rt=a.useRef(null),Ft=a.useRef(null),Ut=a.useRef(null),St=a.useRef(null),Et=a.useRef(null),It=a.useRef(null),Mt=a.useRef(!1),Kt=a.useMemo(()=>$.filter(ke=>ke.type==="remote"),[$]),Ot=Kt.length>0,xe=a.useMemo(()=>Object.entries($e).sort(([ke],[nt])=>ke.localeCompare(nt)),[$e]),st=xe.length>0,Ve=xe.length+(st?1:0),Y=a.useMemo(()=>Object.entries(Te).sort(([ke],[nt])=>ke.localeCompare(nt)),[Te]),F=a.useMemo(()=>!!(W?.todoView||W?.insights||W?.roadmap||T||W?.memoryView||W?.devServerView),[W,T]),H=a.useCallback(()=>{const ke=window.visualViewport;return ke&&ke.width>0&&ke.height>0?{width:ke.width,height:ke.height,offsetTop:ke.offsetTop,offsetLeft:ke.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),ge=a.useCallback(()=>{const ke=Et.current;if(!ke)return;const nt=ke.getBoundingClientRect(),tn=It.current,{width:Pn,height:Nn,offsetTop:gn,offsetLeft:nn}=H(),_n=16,jn=16,Q=6,Oe=tn?.offsetWidth||Math.max(nt.width,260),Xe=Math.min(Oe,Math.max(Pn-_n*2,160)),Ze=tn?.offsetHeight||280,pt=Math.min(Ze,Math.max(Nn-jn*2,160)),Nt=nt.top-gn,At=nt.bottom-gn,xn=nt.right-nn,Qt=Nn-At,bt=Nt,Kn=Qt<pt&&bt>Qt,re=Math.min(Math.max(xn-Xe,_n),Pn-_n-Xe)+nn,Ae=Kn?Math.max(jn+gn,Nt-pt-Q+gn):Math.min(At+Q+gn,Nn+gn-jn-pt);pe({top:Ae,left:re,width:Xe})},[H]),me=a.useCallback((ke,nt)=>{v?.(ke,nt),le(!1),Z(-1)},[v]),We=a.useCallback(()=>{x?.(),le(!1),Z(-1)},[x]),dt=a.useCallback(ke=>{switch(ke.key){case"ArrowDown":ke.preventDefault(),Ve>0&&Z(nt=>nt<Ve-1?nt+1:0);break;case"ArrowUp":ke.preventDefault(),Ve>0&&Z(nt=>nt>0?nt-1:Ve-1);break;case"Enter":if(ke.preventDefault(),de>=0)if(de<xe.length){const[nt,tn]=xe[de];me(nt,tn)}else st&&de===xe.length&&We();break;case"Home":ke.preventDefault(),Ve>0&&Z(0);break;case"End":ke.preventDefault(),Ve>0&&Z(Ve-1);break}},[We,me,de,xe,st,Ve]);a.useEffect(()=>{yt.current=Be},[Be]),a.useEffect(()=>{Mt.current=ce},[ce]),a.useEffect(()=>{if(!Be||!fe)return;let ke=!1;return Re(!0),ar(G).then(nt=>{ke||Qe(nt)}).catch(()=>{ke||Qe({})}).finally(()=>{ke||Re(!1)}),()=>{ke=!0}},[Be,fe,G]),a.useEffect(()=>{if(!ce||fe)return;let ke=!1;return V(!0),ar(G).then(nt=>{ke||at(nt)}).catch(()=>{ke||at({})}).finally(()=>{ke||V(!1)}),()=>{ke=!0}},[ce,fe,G]),a.useEffect(()=>{if(!ce)return;const ke=nt=>{St.current&&!St.current.contains(nt.target)&&le(!1)};return document.addEventListener("mousedown",ke),()=>document.removeEventListener("mousedown",ke)},[ce]),a.useEffect(()=>{if(!ce)return;const ke=nt=>{nt.key==="Escape"&&(le(!1),Et.current?.focus())};return document.addEventListener("keydown",ke),()=>document.removeEventListener("keydown",ke)},[ce]),a.useEffect(()=>{if(ce){Z(-1);const ke=window.setTimeout(()=>It.current?.focus(),0);return()=>window.clearTimeout(ke)}pe(null)},[ce]),a.useEffect(()=>{if(!ce)return;const ke=requestAnimationFrame(()=>{ge()});return()=>cancelAnimationFrame(ke)},[ce,tt,xe.length,st,ge]),a.useEffect(()=>{if(!ce)return;const ke=()=>ge();window.addEventListener("resize",ke),window.addEventListener("scroll",ke,!0);const nt=window.visualViewport;return nt&&(nt.addEventListener("resize",ke),nt.addEventListener("scroll",ke)),()=>{window.removeEventListener("resize",ke),window.removeEventListener("scroll",ke,!0),nt&&(nt.removeEventListener("resize",ke),nt.removeEventListener("scroll",ke))}},[ce,ge]),a.useEffect(()=>{fe&&(le(!1),Z(-1))},[fe]);const _t=Ne||z.length>0,$t=(ve||z.length>0)&&!ye,vn=(N==="board"||N==="list")&&!he&&K&&!ye&&z.length===0,kn=(N==="board"||N==="list")&&!he&&K;a.useEffect(()=>{z===""&&ie(!1)},[z]),a.useEffect(()=>{if(!Me)return;const ke=nt=>{ct.current&&!ct.current.contains(nt.target)&&Le.current&&!Le.current.contains(nt.target)&&ze(!1)};return document.addEventListener("mousedown",ke),()=>document.removeEventListener("mousedown",ke)},[Me]),a.useEffect(()=>{if(!be)return;const ke=nt=>{mt.current&&!mt.current.contains(nt.target)&&Se.current&&!Se.current.contains(nt.target)&&ne(!1)};return document.addEventListener("mousedown",ke),()=>document.removeEventListener("mousedown",ke)},[be]),a.useEffect(()=>{if(!Ye)return;const ke=nt=>{kt.current&&!kt.current.contains(nt.target)&&Ge(!1)};return document.addEventListener("mousedown",ke),()=>document.removeEventListener("mousedown",ke)},[Ye]),a.useEffect(()=>{const ke=nt=>{if(nt.key==="Escape"){if(ae(!1),ne(!1),yt.current){Je(!1);return}if(Mt.current){le(!1),Et.current?.focus();return}ze(!1),ee(!1),Ge(!1),_e(!1)}};return document.addEventListener("keydown",ke),()=>document.removeEventListener("keydown",ke)},[]),a.useEffect(()=>{if(!it)return;const ke=nt=>{Ct.current&&!Ct.current.contains(nt.target)&&_e(!1)};return document.addEventListener("mousedown",ke),()=>document.removeEventListener("mousedown",ke)},[it]),a.useEffect(()=>{if(!Ie)return;const ke=nt=>{Ut.current&&!Ut.current.contains(nt.target)&&Pe(!1)};return document.addEventListener("mousedown",ke),()=>document.removeEventListener("mousedown",ke)},[Ie]),a.useEffect(()=>{if(!Ie)return;const ke=nt=>{nt.key==="Escape"&&Pe(!1)};return document.addEventListener("keydown",ke),()=>document.removeEventListener("keydown",ke)},[Ie]),a.useEffect(()=>{if(!Fe)return;const ke=nt=>{Rt.current&&!Rt.current.contains(nt.target)&&Ft.current&&!Ft.current.contains(nt.target)&&ae(!1)};return document.addEventListener("mousedown",ke),()=>document.removeEventListener("mousedown",ke)},[Fe]);const Yt=a.useCallback(()=>{ee(ke=>!ke)},[]),En=a.useCallback(()=>{ue(!0),ie(!1)},[]),on=a.useCallback(()=>{ue(!1),ie(!0),K&&K("")},[K]),Mn=a.useCallback(()=>{ze(ke=>!ke)},[]),Vt=a.useCallback(ke=>{ke&&ke(),ze(!1),Je(!1)},[]),hn=a.useCallback(()=>{ee(!1),K&&K("")},[K]);return t.jsxs("div",{className:"header-wrapper",children:[t.jsxs("header",{className:"header",children:[t.jsxs("div",{className:"header-left",children:[t.jsxs("div",{className:"header-brand",children:[t.jsxs("svg",{className:"header-logo",width:24,height:24,viewBox:"0 0 128 128",fill:"none","aria-label":"Fusion logo",role:"img",children:[t.jsx("circle",{cx:"64",cy:"64",r:"52",stroke:"currentColor",strokeWidth:"8"}),t.jsx("path",{d:"M26 101C44 82 62 64 82 45C90 37 98 30 104 24C96 35 89 47 81 60C70 79 57 95 43 108C38 112 32 108 26 101Z",fill:"currentColor"})]}),t.jsx("h1",{className:"logo",children:"Fusion"})]}),he&&P.length>=1&&R&&t.jsxs("div",{className:"mobile-project-switch",ref:Ct,children:[t.jsx("button",{className:`mobile-project-switch-trigger${it?" mobile-project-switch-trigger--open":""}`,onClick:()=>_e(ke=>!ke),title:"Switch project","aria-label":"Switch project","aria-expanded":it,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:t.jsx(qt,{size:14,className:`mobile-project-switch-chevron${it?" mobile-project-switch-chevron--open":""}`})}),it&&t.jsx("div",{className:"mobile-project-switch-dropdown",role:"listbox","aria-label":"Select project","data-testid":"mobile-project-switch-dropdown",children:P.map(ke=>{const nt=E?.id===ke.id,tn=rp[ke.status]?.color;return t.jsxs("button",{className:`mobile-project-switch-item${nt?" mobile-project-switch-item--current":""}`,onClick:()=>{R(ke),_e(!1)},role:"option","aria-selected":nt,"data-testid":`mobile-project-switch-item-${ke.id}`,children:[t.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:tn||"var(--text-muted)"}}),t.jsxs("div",{className:"mobile-project-switch-info",children:[t.jsx("span",{className:"mobile-project-switch-name",children:ke.name}),t.jsx("span",{className:"mobile-project-switch-path",children:ke.path.split("/").slice(-2).join("/")})]}),nt&&t.jsx(Rn,{size:14,className:"mobile-project-switch-check"})]},ke.id)})})]}),!fe&&P.length>=1&&B&&t.jsx(Fj,{projects:P,currentProject:E??null,onViewAll:B,onSelectProject:R}),Ot&&t.jsxs("div",{className:`header-node-selector${he?" header-node-selector--mobile":""}`,ref:he?void 0:kt,children:[t.jsx(Dj,{node:A??null,showDetails:!he}),!he&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:`btn-icon node-selector-trigger${Ye?" node-selector-trigger--open":""}`,onClick:()=>Ge(ke=>!ke),title:"Switch node","aria-label":"Switch node","aria-expanded":Ye,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:t.jsx(mn,{size:12,className:`node-selector-chevron${Ye?" node-selector-chevron--open":""}`})}),Ye&&t.jsxs("div",{className:"node-selector-dropdown",role:"listbox","aria-label":"Select node",children:[t.jsxs("button",{className:`node-selector-option${J?"":" node-selector-option--active"}`,onClick:()=>{j?.(null),Ge(!1)},role:"option","aria-selected":!J,"data-testid":"node-option-local",children:[t.jsx("span",{className:"node-selector-option-dot node-selector-option-dot--local"}),t.jsx("span",{className:"node-selector-option-label",children:"Local"})]}),Kt.map(ke=>t.jsxs("button",{className:`node-selector-option${A?.id===ke.id?" node-selector-option--active":""}`,onClick:()=>{j?.(ke),Ge(!1)},role:"option","aria-selected":A?.id===ke.id,"data-testid":`node-option-${ke.id}`,children:[t.jsx("span",{className:`node-selector-option-dot node-selector-option-dot--${ke.status}`}),t.jsx("span",{className:"node-selector-option-label",children:ke.name}),t.jsx("span",{className:"node-selector-option-status",children:ke.status})]},ke.id))]})]})]})]}),t.jsxs("div",{className:"header-actions",children:[U&&L&&(N==="board"||N==="list")&&t.jsxs("div",{className:"view-toggle","data-testid":"mobile-view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${N==="board"?" active":""}`,onClick:()=>L("board"),title:"Board view","aria-label":"Board view","aria-pressed":N==="board","data-testid":"mobile-view-toggle-board",children:t.jsx(Pi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${N==="list"?" active":""}`,onClick:()=>L("list"),title:"List view","aria-label":"List view","aria-pressed":N==="list","data-testid":"mobile-view-toggle-list",children:t.jsx(ic,{size:16})})]}),K&&he&&(U||N==="board"||N==="list")&&!_t&&t.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:Yt,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:t.jsx(ea,{size:16})}),vn&&t.jsx("button",{className:"btn-icon",onClick:En,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:t.jsx(ea,{size:16})}),he&&U&&o&&t.jsx("button",{className:"btn-icon",onClick:ke=>o(ke.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"mobile-header-usage-btn",children:t.jsx(Es,{size:16})}),!U&&L&&t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${N==="board"?" active":""}`,onClick:()=>L("board"),title:"Board view","aria-label":"Board view","aria-pressed":N==="board",children:t.jsx(Pi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${N==="list"?" active":""}`,onClick:()=>L("list"),title:"List view","aria-label":"List view","aria-pressed":N==="list",children:t.jsx(ic,{size:16})}),I&&t.jsx("button",{className:`view-toggle-btn${N==="agents"?" active":""}`,onClick:()=>L("agents"),title:"Agents view","aria-label":"Agents view","aria-pressed":N==="agents",children:t.jsx(pn,{size:16})}),t.jsx("button",{className:`view-toggle-btn${N==="missions"?" active":""}`,onClick:()=>L("missions"),title:"Missions view","aria-label":"Missions view","aria-pressed":N==="missions",children:t.jsx(rs,{size:16})}),t.jsx("button",{className:`view-toggle-btn${N==="chat"?" active":""}`,onClick:()=>L("chat"),title:"Chat view","aria-label":"Chat view","aria-pressed":N==="chat",children:t.jsx(ui,{size:16})}),t.jsx("button",{className:`view-toggle-btn${N==="documents"?" active":""}`,onClick:()=>L("documents"),title:"Documents view","aria-label":"Documents view","aria-pressed":N==="documents",children:t.jsx(Ri,{size:16})}),t.jsx("button",{className:`view-toggle-btn${N==="mailbox"?" active":""}`,onClick:()=>L("mailbox"),title:"Mailbox view","aria-label":"Mailbox view","aria-pressed":N==="mailbox",children:t.jsx(aa,{size:16})}),F&&t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:Ft,className:`view-toggle-btn${["skills","roadmaps","insights","memory","dev-server","devserver"].includes(N)||W?.todoView&&N==="todos"?" active":""}`,onClick:()=>ae(ke=>!ke),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":Fe,"data-testid":"view-toggle-overflow-trigger",children:t.jsx(qt,{size:12})}),Fe&&t.jsxs("div",{ref:Rt,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[W?.insights&&t.jsxs("button",{className:`view-toggle-overflow-item${N==="insights"?" active":""}`,onClick:()=>{L("insights"),ae(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[t.jsx(Vn,{size:14}),t.jsx("span",{children:"Insights"})]}),W?.roadmap&&t.jsxs("button",{className:`view-toggle-overflow-item${N==="roadmaps"?" active":""}`,onClick:()=>{L("roadmaps"),ae(!1)},role:"menuitem","data-testid":"view-overflow-roadmaps",children:[t.jsx(ac,{size:14}),t.jsx("span",{children:"Roadmaps"})]}),T&&t.jsxs("button",{className:`view-toggle-overflow-item${N==="skills"?" active":""}`,onClick:()=>{L("skills"),ae(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[t.jsx(In,{size:14}),t.jsx("span",{children:"Skills"})]}),W?.memoryView&&t.jsxs("button",{className:`view-toggle-overflow-item${N==="memory"?" active":""}`,onClick:()=>{L("memory"),ae(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[t.jsx(eo,{size:14}),t.jsx("span",{children:"Memory"})]}),W?.devServerView&&t.jsxs("button",{className:`view-toggle-overflow-item${N==="dev-server"||N==="devserver"?" active":""}`,onClick:()=>{L("devserver"),ae(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[t.jsx(nr,{size:14}),t.jsx("span",{children:"Dev Server"}),t.jsx("span",{className:"visually-hidden","data-testid":"view-toggle-dev-server"})]}),W?.todoView&&t.jsxs("button",{className:`view-toggle-overflow-item${N==="todos"?" active":""}`,onClick:()=>{L("todos"),ae(!1)},role:"menuitem","data-testid":"view-overflow-todos",children:[t.jsx(Oh,{size:14}),t.jsx("span",{children:"Todos"})]})]})]})]}),!fe&&o&&t.jsx("button",{className:"btn-icon",onClick:ke=>o(ke.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"desktop-header-usage-btn",children:t.jsx(Es,{size:16})}),!fe&&c&&t.jsx("button",{className:"btn-icon",onClick:c,title:"System Stats","data-testid":"desktop-header-system-stats-btn",children:t.jsx(nr,{size:16})}),!fe&&l&&t.jsx("button",{className:"btn-icon",onClick:l,title:"View Activity Log",children:t.jsx(tr,{size:16})}),!fe&&!X&&t.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:t.jsx(Yd,{size:16})}),!fe&&t.jsxs("button",{className:`btn-icon${r>0?" btn-icon--has-indicator":""}`,onClick:r>0&&i?i:s,title:r>0?"Resume planning session":"Create a task with AI planning","data-testid":"planning-btn",style:{position:"relative"},children:[t.jsx(Ws,{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})]}),!fe&&t.jsxs("div",{className:"terminal-split-btn",ref:St,children:[t.jsx("button",{className:"btn-icon btn-icon--terminal terminal-split-btn__main",onClick:b,title:"Open Terminal","data-testid":"terminal-toggle-btn",children:t.jsx(ei,{size:16})}),x&&v&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"terminal-split-btn__divider"}),t.jsx("button",{ref:Et,className:`btn-icon terminal-split-btn__chevron${ce?" btn-icon--active":""}`,onClick:()=>le(ke=>!ke),title:"Scripts","aria-haspopup":"listbox","aria-expanded":ce,"aria-label":"Quick scripts","data-testid":"scripts-btn",children:t.jsx(qt,{size:12,className:`quick-scripts-dropdown__trigger-chevron${ce?" rotate":""}`})}),ce&&t.jsx("div",{ref:It,tabIndex:-1,className:"quick-scripts-dropdown__menu",role:"listbox","aria-label":"Scripts",onKeyDown:dt,"data-testid":"quick-scripts-dropdown",style:we?{position:"fixed",top:`${we.top}px`,left:`${we.left}px`,width:`${we.width}px`,right:"auto"}:void 0,children:tt?t.jsxs("div",{className:"quick-scripts-dropdown__loading","data-testid":"quick-scripts-loading",children:[t.jsx(rt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts..."})]}):xe.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:We,children:"Add your first script"})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-scripts-dropdown__list",children:xe.map(([ke,nt],tn)=>t.jsxs("button",{className:`quick-scripts-dropdown__item ${de===tn?"highlighted":""}`,onClick:()=>me(ke,nt),role:"option","aria-selected":de===tn,"data-testid":`quick-script-item-${ke}`,children:[t.jsx(fn,{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:ke}),t.jsx("span",{className:"quick-scripts-dropdown__item-command",title:nt,children:nt.length>50?`${nt.slice(0,50)}...`:nt})]})]},ke))}),t.jsx("div",{className:"quick-scripts-dropdown__footer",children:t.jsxs("button",{className:`quick-scripts-dropdown__manage ${st&&de===xe.length?"highlighted":""}`,onClick:We,"data-testid":"quick-scripts-manage",children:[t.jsx(Ja,{size:14}),t.jsx("span",{children:"Manage Scripts..."})]})})]})})]})]}),!fe&&y&&t.jsx("button",{className:`btn-icon${S?" btn-icon--active":""}`,onClick:y,title:"Browse files","data-testid":"files-toggle-btn",children:t.jsx(Dn,{size:16})}),!fe&&h&&t.jsx("button",{className:"btn-icon",onClick:h,title:"Git Manager","data-testid":"git-manager-btn",children:t.jsx(Vs,{size:16})}),!fe&&f&&t.jsx("button",{className:"btn-icon",onClick:f,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:t.jsx(oc,{size:16})}),!fe&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{ref:Se,className:"btn-icon",onClick:()=>ne(ke=>!ke),title:"More actions","aria-label":"More actions","aria-expanded":be,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:t.jsx(tc,{size:16})}),be&&t.jsxs("div",{ref:mt,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[g&&p!==!1&&t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{g(),ne(!1)},role:"menuitem","data-testid":"desktop-overflow-nodes-btn",children:[t.jsx(no,{size:14}),t.jsx("span",{children:"Nodes"})]}),t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{Vt(m),ne(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[t.jsx(hi,{size:14}),t.jsx("span",{children:"Automation"})]})]})]}),t.jsxs("div",{className:"engine-control-split-btn",ref:Ut,children:[t.jsx("button",{className:`btn-icon engine-control-split-btn__main${k?" btn-icon--stopped":""}`,onClick:w,title:k?"Start AI engine":"Stop AI engine","data-testid":"engine-control-main-btn",children:k?t.jsx(fn,{size:16}):t.jsx(ms,{size:16})}),t.jsx("span",{className:"engine-control-split-btn__divider"}),t.jsx("button",{className:`btn-icon engine-control-split-btn__chevron${Ie?" btn-icon--active":""}`,onClick:()=>Pe(ke=>!ke),title:"Engine options","aria-haspopup":"menu","aria-expanded":Ie,"data-testid":"engine-control-chevron-btn",children:t.jsx(qt,{size:12})}),Ie&&t.jsx("div",{className:"engine-control-split-btn__menu",role:"menu",children:t.jsxs("button",{className:`engine-control-split-btn__menu-item${M?" engine-control-split-btn__menu-item--active":""}`,onClick:()=>{_?.(),Pe(!1)},role:"menuitem",title:M?"Resume scheduling":"Pause triage",disabled:!!k,"data-testid":"engine-control-pause-triage-btn",children:[M?t.jsx(fn,{size:14}):t.jsx(qs,{size:14}),t.jsx("span",{children:M?"Resume scheduling":"Pause triage"})]})})]}),!fe&&t.jsx("button",{className:"btn-icon",onClick:e,title:"Settings",children:t.jsx(Ja,{size:16})}),t.jsx(Ao,{slotId:"header-action",projectId:G}),fe&&!U&&t.jsx("button",{ref:Le,className:"btn-icon compact-overflow-trigger",onClick:Mn,title:"More header actions","aria-label":"More header actions","aria-expanded":Me,"aria-haspopup":"menu",children:t.jsx(tc,{size:16})}),fe&&!U&&Me&&t.jsxs("div",{ref:ct,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[P.length>=1&&B&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Vt(B),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[t.jsx(Dh,{size:16}),t.jsx("span",{children:"Projects"})]}),y&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Vt(y),role:"menuitem","data-testid":"overflow-files-btn",children:[t.jsx(Dn,{size:16}),t.jsx("span",{children:"Browse Files"})]}),t.jsxs("button",{className:`mobile-overflow-item${r>0?" mobile-overflow-item--has-indicator":""}`,onClick:()=>Vt(r>0&&i?i:s),role:"menuitem","data-testid":"overflow-planning-btn",children:[t.jsxs("span",{className:"mobile-overflow-icon-wrapper",children:[t.jsx(Ws,{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:()=>Vt(h),role:"menuitem","data-testid":"overflow-git-btn",children:[t.jsx(Vs,{size:16}),t.jsx("span",{children:"Git Manager"})]}),g&&p!==!1&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Vt(g),role:"menuitem","data-testid":"overflow-nodes-btn",children:[t.jsx(no,{size:16}),t.jsx("span",{children:"Nodes"})]}),!X&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Vt(n),role:"menuitem",children:[t.jsx(Yd,{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:()=>Vt(b),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:()=>Je(ke=>!ke),role:"menuitem","aria-expanded":Be,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:t.jsx(mn,{size:14,className:`mobile-overflow-chevron${Be?" mobile-overflow-chevron--open":""}`})})]}),Be&&t.jsx("div",{className:"mobile-overflow-submenu",role:"menu","aria-label":"Scripts submenu",children:Ee?t.jsxs("div",{className:"mobile-overflow-submenu-loading","data-testid":"overflow-scripts-loading",children:[t.jsx(rt,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):Y.length>0?t.jsxs(t.Fragment,{children:[Y.map(([ke,nt])=>t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{v&&v(ke,nt),ze(!1),Je(!1)},role:"menuitem","data-testid":`overflow-script-item-${ke}`,children:[t.jsx(fn,{size:14}),t.jsx("span",{children:ke})]},ke)),x&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>Vt(x),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(Ts,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):x&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>Vt(x),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(Ts,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Vt(m),role:"menuitem","data-testid":"overflow-schedules-btn",children:[t.jsx(hi,{size:16}),t.jsx("span",{children:"Automation"})]}),l&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Vt(l),role:"menuitem","data-testid":"overflow-activity-log-btn",children:[t.jsx(tr,{size:16}),t.jsx("span",{children:"View Activity Log"})]}),u&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Vt(u),role:"menuitem","data-testid":"overflow-mailbox-btn",children:[t.jsx(aa,{size:16}),t.jsxs("span",{children:["Mailbox",d>0?` (${d})`:""]})]}),o&&t.jsxs("button",{className:"mobile-overflow-item",onClick:ke=>Vt(()=>o(ke.currentTarget.getBoundingClientRect())),role:"menuitem","data-testid":"overflow-usage-btn",children:[t.jsx(Es,{size:16}),t.jsx("span",{children:"View Usage"})]}),f&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Vt(f),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[t.jsx(oc,{size:16}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Vt(e),role:"menuitem",children:[t.jsx(Ja,{size:16}),t.jsx("span",{children:"Settings"})]})]})]})]}),kn&&$t&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{className:"header-search",children:[t.jsx(ea,{size:14,className:"header-search-icon"}),t.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:z,onChange:ke=>K(ke.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:on,"aria-label":"Close search",children:t.jsx(zt,{size:14})})]})}),K&&he&&_t&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{ref:gt,className:"header-search mobile-search-expanded",children:[t.jsx(ea,{size:14,className:"header-search-icon"}),t.jsx("input",{ref:wt,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:z,onChange:ke=>K(ke.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:hn,"aria-label":"Close search",children:t.jsx(zt,{size:14})})]})})]})}const Uj={themeMode:"dark",colorTheme:"default",defaultProvider:void 0,defaultModelId:void 0,fallbackProvider:void 0,fallbackModelId:void 0,defaultThinkingLevel:void 0,ntfyEnabled:!1,ntfyTopic:void 0,ntfyBaseUrl:void 0,ntfyEvents:["in-review","merged","failed","awaiting-approval","awaiting-user-review","planning-awaiting-input"],ntfyDashboardHost:void 0,defaultProjectId:void 0,setupComplete:void 0,favoriteProviders:void 0,favoriteModels:void 0,openrouterModelSync:!0,updateCheckEnabled:!0,updateCheckFrequency:"daily",showGitHubStarButton:!0,modelOnboardingComplete:void 0,useClaudeCli:void 0,executionGlobalProvider:void 0,executionGlobalModelId:void 0,planningGlobalProvider:void 0,planningGlobalModelId:void 0,validatorGlobalProvider:void 0,validatorGlobalModelId:void 0,titleSummarizerGlobalProvider:void 0,titleSummarizerGlobalModelId:void 0,daemonToken:void 0,daemonPort:4040,daemonHost:"127.0.0.1",settingsSyncEnabled:!1,settingsSyncAuth:!1,settingsSyncInterval:9e5,settingsSyncConflictResolution:"last-write-wins",dashboardCurrentNodeId:void 0,dashboardCurrentProjectIdByNode:void 0,vitestAutoKillEnabled:!0,vitestKillThresholdPct:90},Bj={globalPause:!1,globalPauseReason:void 0,enginePaused:!1,maxConcurrent:2,maxTriageConcurrent:2,globalMaxConcurrent:4,maxWorktrees:4,pollIntervalMs:15e3,heartbeatMultiplier:1,groupOverlappingFiles:!0,overlapIgnorePaths:[],autoMerge:!0,mergeStrategy:"direct",pushAfterMerge:!1,pushRemote:"origin",worktreeInitCommand:void 0,testCommand:void 0,buildCommand:void 0,recycleWorktrees:!1,worktreeNaming:"random",taskPrefix:"FN",includeTaskIdInCommit:!0,commitAuthorEnabled:!0,commitAuthorName:"Fusion",commitAuthorEmail:"noreply@runfusion.ai",planningProvider:void 0,planningModelId:void 0,planningFallbackProvider:void 0,planningFallbackModelId:void 0,defaultProviderOverride:void 0,defaultModelIdOverride:void 0,executionProvider:void 0,executionModelId:void 0,validatorProvider:void 0,validatorModelId:void 0,validatorFallbackProvider:void 0,validatorFallbackModelId:void 0,modelPresets:[],autoSelectModelPreset:!1,defaultPresetBySize:{},autoResolveConflicts:!0,smartConflictResolution:!0,worktreeRebaseBeforeMerge:!0,worktreeRebaseRemote:"",strictScopeEnforcement:!1,buildRetryCount:0,verificationFixRetries:3,buildTimeoutMs:3e5,requirePlanApproval:!1,specStalenessEnabled:!1,specStalenessMaxAgeMs:360*60*1e3,taskStuckTimeoutMs:void 0,aiSessionTtlMs:10080*60*1e3,aiSessionCleanupIntervalMs:3600*1e3,autoUnpauseEnabled:!0,autoUnpauseBaseDelayMs:3e5,autoUnpauseMaxDelayMs:36e5,maxStuckKills:6,maxPostReviewFixes:1,maxSpawnedAgentsPerParent:5,maxSpawnedAgentsGlobal:20,maintenanceIntervalMs:9e5,autoArchiveDoneTasksEnabled:!0,autoArchiveDoneAfterMs:2880*60*1e3,archiveAgentLogMode:"compact",autoUpdatePrStatus:!1,autoCreatePr:!1,githubCommentOnDone:!1,githubCommentTemplate:void 0,autoBackupEnabled:!1,autoBackupSchedule:"0 2 * * *",autoBackupRetention:7,autoBackupDir:".fusion/backups",autoSummarizeTitles:!1,titleSummarizerProvider:void 0,titleSummarizerModelId:void 0,titleSummarizerFallbackProvider:void 0,titleSummarizerFallbackModelId:void 0,scripts:void 0,setupScript:void 0,insightExtractionEnabled:!1,insightExtractionSchedule:"0 2 * * *",insightExtractionMinIntervalMs:864e5,memoryEnabled:!0,memoryBackendType:"qmd",memoryAutoSummarizeEnabled:!1,memoryAutoSummarizeThresholdChars:5e4,memoryAutoSummarizeSchedule:"0 3 * * *",memoryDreamsEnabled:!1,memoryDreamsSchedule:"0 4 * * *",tokenCap:void 0,runStepsInNewSessions:!1,maxParallelSteps:2,missionStaleThresholdMs:6e5,missionMaxTaskRetries:3,missionHealthCheckIntervalMs:3e5,agentPrompts:void 0,promptOverrides:void 0,remoteAccess:{activeProvider:null,providers:{tailscale:{enabled:!1,hostname:"",targetPort:0,acceptRoutes:!1},cloudflare:{enabled:!1,quickTunnel:!1,tunnelName:"",tunnelToken:null,ingressUrl:""}},tokenStrategy:{persistent:{enabled:!0,token:null},shortLived:{enabled:!1,ttlMs:9e5,maxTtlMs:864e5}},lifecycle:{rememberLastRunning:!1,wasRunningOnShutdown:!1,lastRunningProvider:null}},reflectionEnabled:!1,reflectionIntervalMs:36e5,reflectionAfterTask:!0,reviewHandoffPolicy:"disabled",showQuickChatFAB:!1,experimentalFeatures:{}},Hj=Object.freeze(Object.keys(Uj)),qj=Object.freeze(Object.keys(Bj));function q$(e){return Hj.includes(e)}function V$(e){return qj.includes(e)}function je(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}const W$=["off","minimal","low","medium","high"],_i=["triage","todo","in-progress","in-review","done","archived"],Bc=["low","normal","high","urgent"],ps="normal",Vj=["default","ocean","forest","sunset","zen","berry","high-contrast","industrial","monochrome","slate","ash","graphite","silver","solarized","factory","ayu","one-dark","nord","dracula","gruvbox","tokyo-night","catppuccin-mocha","github-dark","everforest","rose-pine","kanagawa","night-owl","palenight","monokai-pro","slime","brutalist","neon-city","parchment","terminal","glass","horizon","vitesse","outrun","snazzy","porple","espresso","mars","poimandres","ember","rust","copper","foundry","carbon","sandstone","lagoon","frost","lavender","neon-bloom","sepia"],$n={triage:"Planning",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},Wj={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"},mc={triage:["todo"],todo:["in-progress","triage"],"in-progress":["in-review","todo","triage","done"],"in-review":["done","in-progress","todo"],done:["todo","triage","archived"],archived:["done"]};function Kj(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 Gj(e,n=1400){const s=a.useRef(null),[i,r]=a.useState(!1),o=a.useRef(null);return a.useEffect(()=>(s.current!==null&&e>s.current&&(r(!0),o.current=setTimeout(()=>r(!1),n)),s.current=e,()=>{o.current!==null&&clearTimeout(o.current)}),[e,n]),i}function Jj({isOpen:e,options:n,onConfirm:s,onCancel:i}){const r=a.useRef(null);return a.useEffect(()=>{if(!e)return;r.current?.focus();const o=l=>{l.key==="Escape"&&(l.preventDefault(),i())};return document.addEventListener("keydown",o),()=>document.removeEventListener("keydown",o)},[e,i]),!e||!n?null:t.jsx("div",{className:"modal-overlay open",onClick:i,children:t.jsxs("div",{className:"modal confirm-dialog",onClick:o=>o.stopPropagation(),role:"dialog","aria-modal":"true","aria-label":n.title,children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:n.title}),t.jsx("button",{className:"modal-close",onClick:i,"aria-label":"Close confirmation dialog",children:"×"})]}),t.jsx("div",{className:"confirm-dialog__body",children:n.message}),t.jsxs("div",{className:"modal-actions confirm-dialog__actions",children:[t.jsx("button",{ref:r,className:"btn",onClick:i,children:n.cancelLabel??"Cancel"}),t.jsx("button",{className:`btn ${n.danger?"btn-danger":"btn-primary"}`,onClick:s,children:n.confirmLabel??"Confirm"})]})]})})}const op=a.createContext(null);function Yj({children:e}){const[n,s]=a.useState([]),i=a.useRef([]),r=a.useCallback(d=>{s(m=>{const h=d(m);return i.current=h,h})},[]),o=a.useCallback(d=>new Promise(m=>{r(h=>[...h,{options:d,resolve:m}])}),[r]),l=a.useCallback(d=>{const m=i.current[0];m&&(m.resolve(d),r(h=>h.slice(1)))},[r]),c=n[0]??null,u=a.useMemo(()=>({confirm:o}),[o]);return Zr.createElement(op.Provider,{value:u},e,Zr.createElement(Jj,{isOpen:c!==null,options:c?.options??null,onConfirm:()=>l(!0),onCancel:()=>l(!1)}))}function Is(){const e=a.useContext(op);return e||{confirm:async n=>!1}}function Qj(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 lp({prInfo:e,issueInfo:n,onIssueRefresh:s}){const i=()=>{e?.url&&window.open(e.url,"_blank","noopener,noreferrer")},r=()=>{n?.url&&window.open(n.url,"_blank","noopener,noreferrer")};return t.jsxs(t.Fragment,{children:[e&&t.jsxs("span",{className:`card-github-badge card-github-badge--${e.status}`,title:`PR #${e.number}: ${e.title}`,onClick:i,children:[t.jsx(hs,{size:12}),t.jsxs("span",{children:["#",e.number]})]}),n&&t.jsxs("span",{className:`card-github-badge ${Qj(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,onClick:r,children:[t.jsx(ko,{size:12}),t.jsxs("span",{children:["#",n.number]})]})]})}function Pr(e,n){return`${e??"default"}:${n}`}class Xj{ws=null;listeners=new Set;badgeUpdates=new Map;subscriptionsByTask=new Map;reconnectTimeout=null;reconnectDelayMs=1e3;shouldReconnect=!1;isConnected=!1;projectId=null;snapshot={badgeUpdates:new Map,isConnected:!1};previousProjectIdRef=null;projectContextVersionRef=0;contextVersionAtStart=0;subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}getSnapshot(){return this.snapshot}setProjectId(n){if(this.projectId===n)return;this.previousProjectIdRef=this.projectId,this.projectContextVersionRef++,this.contextVersionAtStart=this.projectContextVersionRef;const s=this.subscriptionsByTask.size>0,i=[];for(const[r,o]of this.subscriptionsByTask){const l=r.split(":").slice(1).join(":");for(const c of o)i.push({hookId:c,taskId:l})}if(this.projectId=n,this.reset(),s){for(const{hookId:r,taskId:o}of i){const l=Pr(this.projectId,o);this.subscriptionsByTask.set(l,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const i=Pr(this.projectId,s),r=this.subscriptionsByTask.get(i)??new Set,o=!r.has(n);r.add(n),this.subscriptionsByTask.set(i,r),this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect(),o&&this.send({type:"subscribe",taskId:s,projectId:this.projectId})}unsubscribeTask(n,s){const i=Pr(this.projectId,s),r=this.subscriptionsByTask.get(i);r&&(r.delete(n),r.size===0&&(this.subscriptionsByTask.delete(i),this.badgeUpdates.delete(i),this.send({type:"unsubscribe",taskId:s,projectId:this.projectId}),this.emit()),this.shouldReconnect=this.subscriptionsByTask.size>0,this.shouldReconnect||this.disconnect())}cleanupHook(n){for(const s of[...this.subscriptionsByTask.keys()]){const i=s.split(":").slice(1).join(":");this.unsubscribeTask(n,i)}}reset(){this.disconnect(),this.badgeUpdates.clear(),this.subscriptionsByTask.clear(),this.shouldReconnect=!1,this.emit()}connect(){if(!this.shouldReconnect||typeof window>"u"||this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))return;const n=this.projectContextVersionRef;let i=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/ws`;this.projectId&&(i+=`?projectId=${encodeURIComponent(this.projectId)}`);const r=new WebSocket(Ks(i));this.ws=r,r.onopen=()=>{if(this.projectContextVersionRef!==n){r.close();return}this.isConnected=!0,this.reconnectDelayMs=1e3,this.emit();const o=new Set;for(const l of this.subscriptionsByTask.keys()){const c=l.split(":").slice(1).join(":");o.add(c)}for(const l of o)this.send({type:"subscribe",taskId:l,projectId:this.projectId})},r.onmessage=o=>{if(this.projectContextVersionRef===n)try{const l=JSON.parse(o.data);if(l.type!=="badge:updated"||l.projectId!==void 0&&l.projectId!==this.projectId)return;const c=Pr(this.projectId,l.taskId),u=this.badgeUpdates.get(c);this.badgeUpdates.set(c,{prInfo:Qd(l,"prInfo")?l.prInfo??null:u?.prInfo,issueInfo:Qd(l,"issueInfo")?l.issueInfo??null:u?.issueInfo,timestamp:l.timestamp}),this.emit()}catch{}},r.onclose=()=>{this.projectContextVersionRef===n&&(this.ws=null,this.isConnected&&(this.isConnected=!1,this.emit()),this.shouldReconnect&&this.scheduleReconnect(n))},r.onerror=()=>{}}disconnect(){if(this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.ws){const n=this.ws;this.ws=null,n.close()}this.isConnected&&(this.isConnected=!1,this.emit())}scheduleReconnect(n){if(this.reconnectTimeout)return;const s=n??this.projectContextVersionRef,i=Math.min(this.reconnectDelayMs,5e3);this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.projectContextVersionRef===s&&this.shouldReconnect&&this.connect()},i),this.reconnectDelayMs=Math.min(this.reconnectDelayMs*2,5e3)}send(n){!this.ws||this.ws.readyState!==WebSocket.OPEN||this.ws.send(JSON.stringify(n))}emit(){this.snapshot={badgeUpdates:new Map(this.badgeUpdates),isConnected:this.isConnected};for(const n of this.listeners)n()}}const Ni=new Xj;let Zj=0;function Qd(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function cp(e){const n=a.useRef(null);n.current===null&&(n.current=`badge-hook-${Zj++}`);const s=a.useSyncExternalStore(o=>Ni.subscribe(o),()=>Ni.getSnapshot(),()=>Ni.getSnapshot()),i=a.useCallback(o=>{Ni.subscribeTask(n.current,o)},[]),r=a.useCallback(o=>{Ni.unsubscribeTask(n.current,o)},[]);return a.useEffect(()=>{Ni.setProjectId(e??null)},[e]),a.useEffect(()=>()=>{Ni.cleanupHook(n.current)},[]),{badgeUpdates:s.badgeUpdates,isConnected:s.isConnected,subscribeToBadge:i,unsubscribeFromBadge:r}}function oo(e,n,s,i){return e===void 0||!n?s:!i||n>=i?e??void 0:s}function ew({taskId:e,prInfo:n,issueInfo:s,updatedAt:i,isInViewport:r,projectId:o}){const{badgeUpdates:l,subscribeToBadge:c,unsubscribeFromBadge:u}=cp(o),d=!!(n||s);a.useEffect(()=>{if(!d||!r){u(e);return}return c(e),()=>{u(e)}},[d,r,o,c,e,u]);const m=l.get(`${o??"default"}:${e}`),h=oo(m?.prInfo,m?.timestamp,n,n?.lastCheckedAt??i),g=oo(m?.issueInfo,m?.timestamp,s,s?.lastCheckedAt??i);return!h&&!g?null:t.jsx(lp,{prInfo:h,issueInfo:g})}const tw=a.memo(ew);tw.displayName="TaskCardBadge";const nw={sm:16,md:20,lg:24};function sw({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 Xd({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 Fs({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 iw({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 Zd({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 aw({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 Qo({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 eu({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 tu({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 nu({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 Ca({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 su({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 Xo({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 iu({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 Zo({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 rw({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 ow({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 au({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 el({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 lw({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 ru({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 tl({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 ou({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 nl({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 lu({size:e,color:n,label:s="Anthropic — via Claude CLI"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"claude-cli-icon","aria-label":s,children:[t.jsx("g",{transform:"translate(-1 -1.5) scale(0.82)",children:t.jsx("path",{d:"M17.3041 3.541h-3.6718l6.696 16.918H24Zm-10.6082 0L0 20.459h3.7442l1.3693-3.5527h7.0052l1.3693 3.5528h3.7442L10.5363 3.5409Zm-.3712 10.2232 2.2914-5.9456 2.2914 5.9456Z",fill:n})}),t.jsx("rect",{x:"13",y:"13",width:"10",height:"9",rx:"1.5",fill:n}),t.jsx("path",{d:"M15.2 16.2l1.6 1.4-1.6 1.4M18.6 19.6h2.4",stroke:"var(--provider-icon-contrast)",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})]})}const cw={anthropic:{component:sw,color:"var(--provider-anthropic)"},"claude-cli":{component:lu,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"pi-claude-cli":{component:lu,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},openai:{component:Xd,color:"var(--provider-openai)"},"openai-codex":{component:Xd,color:"var(--provider-openai)",label:"OpenAI Codex"},google:{component:Fs,color:"var(--provider-gemini)"},gemini:{component:Fs,color:"var(--provider-gemini)"},"google-antigravity":{component:Fs,color:"var(--provider-gemini)",label:"Google Gemini"},antigravity:{component:Fs,color:"var(--provider-gemini)",label:"Google Gemini"},"google-vertex":{component:Fs,color:"var(--provider-gemini)",label:"Google Vertex AI"},vertex:{component:Fs,color:"var(--provider-gemini)",label:"Google Vertex AI"},"google-cloud-code":{component:Fs,color:"var(--provider-gemini)",label:"Google Cloud Code"},"cloud-code":{component:Fs,color:"var(--provider-gemini)",label:"Google Cloud Code"},"google-gemini-cli":{component:Fs,color:"var(--provider-gemini)",label:"Google Gemini CLI"},"google-generative-ai":{component:Fs,color:"var(--provider-gemini)",label:"Google Generative AI"},ollama:{component:iw,color:"var(--text)"},github:{component:ru,color:"var(--text)"},"github-copilot":{component:ru,color:"var(--text)",label:"GitHub Copilot"},openrouter:{component:lw,color:"var(--provider-openrouter)"},minimax:{component:Zd,color:"var(--provider-minimax)"},"minimax-cn":{component:Zd,color:"var(--provider-minimax)",label:"MiniMax (CN)"},zai:{component:aw,color:"var(--provider-zai)"},kimi:{component:Qo,color:"var(--provider-kimi)"},moonshot:{component:Qo,color:"var(--provider-kimi)"},"kimi-coding":{component:Qo,color:"var(--provider-kimi)",label:"Kimi"},bedrock:{component:eu,color:"var(--provider-bedrock)"},"amazon-bedrock":{component:eu,color:"var(--provider-bedrock)",label:"Amazon Bedrock"},xai:{component:tu,color:"var(--text)"},grok:{component:tu,color:"var(--text)",label:"xAI"},opencode:{component:nu,color:"var(--provider-opencode)"},"opencode-go":{component:nu,color:"var(--provider-opencode)",label:"Opencode (Go)"},qwen:{component:Ca,color:"var(--provider-qwen)"},"qwen-ai":{component:Ca,color:"var(--provider-qwen)",label:"Qwen"},"qwen-coder":{component:Ca,color:"var(--provider-qwen)",label:"Qwen Coder"},alibaba:{component:Ca,color:"var(--provider-qwen)",label:"Qwen"},tongyi:{component:Ca,color:"var(--provider-qwen)",label:"Qwen"},lmstudio:{component:su,color:"var(--provider-lmstudio)",label:"LM Studio"},"lm-studio":{component:su,color:"var(--provider-lmstudio)",label:"LM Studio"},huggingface:{component:Xo,color:"var(--provider-huggingface)",label:"Hugging Face"},"hugging-face":{component:Xo,color:"var(--provider-huggingface)",label:"Hugging Face"},hf:{component:Xo,color:"var(--provider-huggingface)",label:"Hugging Face"},mistral:{component:iu,color:"var(--provider-mistral)",label:"Mistral AI"},"mistral-ai":{component:iu,color:"var(--provider-mistral)",label:"Mistral AI"},azure:{component:Zo,color:"var(--provider-azure)"},"azure-openai":{component:Zo,color:"var(--provider-azure)",label:"Azure OpenAI"},"azure-openai-responses":{component:Zo,color:"var(--provider-azure)",label:"Azure OpenAI"},fireworks:{component:el,color:"var(--provider-fireworks)",label:"Fireworks AI"},"fireworks-ai":{component:el,color:"var(--provider-fireworks)",label:"Fireworks AI"},fireworksai:{component:el,color:"var(--provider-fireworks)",label:"Fireworks AI"},cerebras:{component:rw,color:"var(--provider-cerebras)"},groq:{component:ow,color:"var(--provider-groq)"},vercel:{component:au,color:"var(--provider-vercel)"},"vercel-ai-gateway":{component:au,color:"var(--provider-vercel)",label:"Vercel AI Gateway"},hermes:{component:tl,color:"var(--provider-hermes)",label:"Hermes"},"hermes-agent":{component:tl,color:"var(--provider-hermes)",label:"Hermes"},hermesagent:{component:tl,color:"var(--provider-hermes)",label:"Hermes"},openclaw:{component:ou,color:"var(--provider-openclaw)",label:"OpenClaw"},"open-claw":{component:ou,color:"var(--provider-openclaw)",label:"OpenClaw"},paperclip:{component:nl,color:"var(--provider-paperclip)",label:"Paperclip"},paperclipai:{component:nl,color:"var(--provider-paperclip)",label:"Paperclip"},"paperclip-ai":{component:nl,color:"var(--provider-paperclip)",label:"Paperclip"}};function Tn({provider:e,size:n="sm"}){const s=e.toLowerCase(),i=cw[s],r=i?.component,o=i?.color??"var(--text-muted)",l=i?.label,c=nw[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(Hg,{size:c})})}const ws={data:new Map,pendingPromise:null,lastFetchTime:null},dw=5e3;function Yr(e,n){return n?`${n}::${e}`:e}function uw(e,n){const s=ws.data.get(Yr(e,n));if(!(!s||Date.now()-s.timestamp>dw))return s}function mw(e){const[n,s]=a.useState(!1),i=a.useRef(null),r=a.useCallback(async c=>{let d=null;for(let m=0;m<3;m++)try{return await Zv(c,e)}catch(h){d=h instanceof Error?h:new Error(String(h));const g=je(h);if(g?.includes("429")||g?.toLowerCase().includes("rate limit")){const p=Math.min(1e3*Math.pow(2,m),3e4);await new Promise(f=>setTimeout(f,p));continue}break}if(d)throw d;return{}},[e]),o=a.useCallback(async c=>{if(c.length===0)return;const d=Date.now()-5e3;if(c.every(g=>{const p=ws.data.get(Yr(g,e));return p&&p.timestamp>d})&&ws.lastFetchTime&&ws.lastFetchTime>d)return;if(i.current&&(clearTimeout(i.current),i.current=null),ws.pendingPromise){s(!0);try{await ws.pendingPromise}finally{s(!1)}return}s(!0);const h=r(c);ws.pendingPromise=h;try{const g=await h,p=Date.now();for(const[f,x]of Object.entries(g))ws.data.set(Yr(f,e),{result:x,timestamp:p});ws.lastFetchTime=p}catch{}finally{ws.pendingPromise=null,s(!1)}},[r,e]),l=a.useCallback(c=>ws.data.get(Yr(c,e)),[e]);return{fetchBatch:o,isLoading:n,lastFetchTime:ws.lastFetchTime,getBatchData:l}}const hc=new Map,hw=3e4;function dp(e,n,s,i){return`${e}:${n??""}:${s??""}:${i??""}`}function pw(e,n,s,i){const r=dp(e,n,s,i),o=hc.get(r);return o?Date.now()>o.expiresAt?(hc.delete(r),null):o.stats:null}function fw(e,n,s,i,r){const o=dp(e,n,s,i);hc.set(o,{stats:r,expiresAt:Date.now()+hw})}function gw(e,n,s,i,r={}){const o=r.enabled??!0,l=r.worktree,c=r.stepVersion,u=r.pollIntervalMs,[d,m]=a.useState(null),[h,g]=a.useState(!1);return a.useEffect(()=>{if(!o){m(null),g(!1);return}const p=n==="done"&&!!s,f=(n==="in-progress"||n==="in-review")&&!!l;if(!e||!p&&!f){m(null),g(!1);return}const x=f?l:void 0,v=c!==void 0?String(c):void 0;let b=!1;async function y(k=!1){if(!k){const M=pw(e,i,x,v);if(M){b||(m(M),g(!1));return}}g(!0);try{const M=await ep(e,x,i);b||(m(M.stats),fw(e,i,x,v,M.stats))}catch{b||m(null)}finally{b||g(!1)}}y();let S;return u&&f&&(S=setInterval(()=>{y(!0)},u)),()=>{b=!0,S&&clearInterval(S)}},[e,n,s,i,o,l,c,u]),{stats:d,loading:h}}const xw=new Set(["failed","stuck-killed"]);function lo(e,n,s){if(e.column!=="in-progress"||e.status&&xw.has(e.status)||!n||n<=0)return!1;const i=new Date(e.updatedAt).getTime();return(s??Date.now())-i>n}function bw(e){switch(e){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function vw(e){return e==="done"||e==="skipped"}function yw(e,n,s){const i=s?.get(e)?.trim();if(i)return i;const r=n?.workflowStepName?.trim();return r||e}function up(e,n){const s=(e.steps??[]).map((u,d)=>({id:`step-${d}`,name:u.name,status:u.status,source:"step",phase:"pre-merge"})),i=new Map((e.workflowStepResults??[]).map(u=>[u.workflowStepId,u])),r=(e.enabledWorkflowSteps??[]).map(u=>{const d=i.get(u);return{id:`workflow-${u}`,name:yw(u,d,n),status:d?bw(d.status):"pending",source:"workflow",phase:d?.phase??"pre-merge"}}),o=[...s,...r],l=o.length,c=o.filter(u=>vw(u.status)).length;return{total:l,completed:c,items:o}}function kw(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 mp(e){return e.filter(n=>{const s=typeof n.action=="string"?n.action:"",i=typeof n.outcome=="string"?n.outcome:"";return s.includes("[timing]")||i.includes("[timing]")}).map(n=>{const i=`${n.action??""}
606
+ ${n.outcome??""}`.match(/(\d+(?:\.\d+)?)ms\b/i),r=i?Number(i[1]):void 0;return{timestamp:n.timestamp,durationMs:Number.isFinite(r)?r:void 0,summary:kw(n)}})}function jw(e){if(!e||e.length===0)return null;let n=0,s=0;for(const i of mp(e))typeof i.durationMs=="number"&&(n+=i.durationMs,s+=1);return s>0?n:null}const pc=new Map;async function ww(e,n){const s=pc.get(e);if(s)return s;try{const i=await tp(e,n);return pc.set(e,i.title),i.title}catch{return e}}const cu=12;function Nw(e){return e.length<=cu?e:e.slice(0,cu-3)+"..."}const fc=new Map;async function Sw(e,n){const s=fc.get(e);if(s)return s;try{const i=await Xh(e,n);return fc.set(e,i.name),i.name}catch{return e}}function Cw(e){return typeof e=="string"&&Bc.includes(e)?e:ps}function Ew(e,n){return e.length<=n?e:e.slice(0,n-3)+"..."}const Mw=new Set(["triage","todo"]),du=new Set(["planning","researching","executing","finalizing","merging"]),_w={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"},Aw=new Set(["in-progress","done"]),Rw=3e4;function gc(e){if(!e)return null;const n=Date.parse(e);return Number.isFinite(n)?n:null}function Tw(e){const n=gc(e.columnMovedAt??e.updatedAt);if(n==null)return null;const s=Date.now();return n>s?null:n}function Pw(e,n){const s=e.workflowStepResults;if(!s||s.length===0)return null;let i=0,r=0;for(const o of s){if(!o.startedAt)continue;const l=gc(o.startedAt);if(l==null)continue;let c;if(o.completedAt){const u=gc(o.completedAt);if(u==null||u<l)continue;c=u}else c=Math.max(l,n);i+=c-l,r+=1}return r>0?i:null}function Iw(e,n){const s=typeof e.timedExecutionMs=="number"?e.timedExecutionMs:jw(e.log),i=Pw(e,n);return s==null&&i==null?null:(s??0)+(i??0)}function $w(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 uu(e,n){if(!e&&!n)return!0;if(!e||!n)return!1;const s=Object.keys(e),i=Object.keys(n);return s.length!==i.length?!1:s.every(r=>e[r]===n[r])}function Dw(e,n){return e.length!==n.length?!1:e.every((s,i)=>s.name===n[i]?.name&&s.status===n[i]?.status)}function Lw(e,n){return e.length!==n.length?!1:e.every((s,i)=>s===n[i])}function zw(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>s===n[i])}function Fw(e){if(!(e instanceof Error))return null;const n=e.details;if(n?.code==="TASK_HAS_DEPENDENTS"&&Array.isArray(n.dependentIds))return{dependentIds:n.dependentIds.filter(i=>typeof i=="string")};const s=e.message.match(/[A-Z]+-\d+/g)??[];return s.length>1?{dependentIds:[...new Set(s.slice(1))]}:null}function Ow(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>{const r=n[i];return r?s.workflowStepId===r.workflowStepId&&s.workflowStepName===r.workflowStepName&&s.phase===r.phase&&s.status===r.status&&s.output===r.output&&s.startedAt===r.startedAt&&s.completedAt===r.completedAt:!1})}function Uw(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>{const r=n[i];return r?s.filename===r.filename&&s.mimeType===r.mimeType&&s.size===r.size:!1})}function Bw(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>{const r=n[i];return r?s.author===r.author&&s.text===r.text&&s.createdAt===r.createdAt:!1})}function Hw(e,n){const s=e.task,i=n.task;return e.queued===n.queued&&e.projectId===n.projectId&&e.globalPaused===n.globalPaused&&e.taskStuckTimeoutMs===n.taskStuckTimeoutMs&&e.onOpenDetail===n.onOpenDetail&&e.addToast===n.addToast&&e.onUpdateTask===n.onUpdateTask&&e.onArchiveTask===n.onArchiveTask&&e.onUnarchiveTask===n.onUnarchiveTask&&e.onDeleteTask===n.onDeleteTask&&e.onOpenDetailWithTab===n.onOpenDetailWithTab&&e.onOpenMission===n.onOpenMission&&e.onMoveTask===n.onMoveTask&&e.workflowStepNameLookup===n.workflowStepNameLookup&&s.id===i.id&&s.title===i.title&&s.description===i.description&&s.column===i.column&&s.columnMovedAt===i.columnMovedAt&&s.updatedAt===i.updatedAt&&s.createdAt===i.createdAt&&s.status===i.status&&s.priority===i.priority&&s.executionMode===i.executionMode&&s.paused===i.paused&&s.error===i.error&&s.size===i.size&&s.blockedBy===i.blockedBy&&s.worktree===i.worktree&&s.baseBranch===i.baseBranch&&s.breakIntoSubtasks===i.breakIntoSubtasks&&s.currentStep===i.currentStep&&s.modelProvider===i.modelProvider&&s.modelId===i.modelId&&s.validatorModelProvider===i.validatorModelProvider&&s.validatorModelId===i.validatorModelId&&s.planningModelProvider===i.planningModelProvider&&s.planningModelId===i.planningModelId&&s.reviewLevel===i.reviewLevel&&s.missionId===i.missionId&&s.assignedAgentId===i.assignedAgentId&&s.mergeRetries===i.mergeRetries&&Uw(s.attachments,i.attachments)&&Bw(s.comments,i.comments)&&Lw(s.dependencies,i.dependencies)&&Dw(s.steps,i.steps)&&zw(s.enabledWorkflowSteps,i.enabledWorkflowSteps)&&Ow(s.workflowStepResults,i.workflowStepResults)&&uu(s.prInfo,i.prInfo)&&uu(s.issueInfo,i.issueInfo)}function qw({task:e,projectId:n,queued:s,onOpenDetail:i,addToast:r,globalPaused:o,onUpdateTask:l,onArchiveTask:c,onUnarchiveTask:u,onDeleteTask:d,onOpenDetailWithTab:m,taskStuckTimeoutMs:h,onOpenMission:g,onMoveTask:p,lastFetchTimeMs:f,workflowStepNameLookup:x}){const[v,b]=a.useState(!1),[y,S]=a.useState(!1),[k,M]=a.useState(!1),[w,_]=a.useState(e.description||""),[N,L]=a.useState(!1),[T,I]=a.useState(e.column==="in-progress"||e.column==="triage"&&e.steps.some(F=>F.status==="done"||F.status==="skipped")),[z,K]=a.useState(null),[P,E]=a.useState(null),[R,B]=a.useState(!1),[G,X]=a.useState(()=>Date.now()),C=a.useRef(null),$=a.useRef(!1),A=a.useRef(null),j=a.useRef(null),[J,W]=a.useState(!1),{badgeUpdates:oe,subscribeToBadge:he,unsubscribeFromBadge:se}=cp(n),{confirm:fe}=Is(),U=a.useRef(null),Ne=a.useRef(!1),ee=a.useCallback(F=>F instanceof Element?!!F.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);a.useEffect(()=>{_(e.description||"")},[e.id,e.description]),a.useEffect(()=>{if(!R)return;const F=H=>{j.current&&!j.current.contains(H.target)&&B(!1)};return document.addEventListener("click",F),()=>document.removeEventListener("click",F)},[R]),a.useEffect(()=>{if(!e.missionId){K(null);return}const F=pc.get(e.missionId);if(F){K(F);return}let H=!1;return ww(e.missionId,n).then(ge=>{H||K(ge)}),()=>{H=!0}},[e.missionId,n]),a.useEffect(()=>{if(!e.assignedAgentId){E(null);return}const F=fc.get(e.assignedAgentId);if(F){E(F);return}E(null);let H=!1;return Sw(e.assignedAgentId,n).then(ge=>{H||E(ge)}),()=>{H=!0}},[e.assignedAgentId,n]),a.useEffect(()=>{if(k&&C.current){const F=C.current;F.focus(),F.style.height="auto",F.style.height=F.scrollHeight+"px"}},[k]),a.useEffect(()=>{if(typeof IntersectionObserver>"u"){W(!0);return}const F=A.current;if(!F)return;const H=new IntersectionObserver(([ge])=>{W(ge?.isIntersecting??!0)},{rootMargin:"200px"});return H.observe(F),()=>H.disconnect()},[k,e.id]);const ve=a.useCallback(F=>{F.dataTransfer.setData("text/plain",e.id),F.dataTransfer.effectAllowed="move",b(!0)},[e.id]),ue=a.useCallback(()=>{b(!1)},[]),ye=a.useCallback(F=>F.dataTransfer.types.includes("Files"),[]),ie=a.useCallback(F=>{ye(F)&&(F.preventDefault(),F.stopPropagation(),F.dataTransfer.dropEffect="copy",S(!0))},[ye]),Me=a.useCallback(F=>{ye(F)&&(F.preventDefault(),F.stopPropagation(),S(!1))},[ye]),ze=a.useCallback(async F=>{if(!ye(F))return;F.preventDefault(),F.stopPropagation(),S(!1);const H=Array.from(F.dataTransfer.files);for(const ge of H)try{await sr(e.id,ge,n),r(`Attached ${ge.name} to ${e.id}`,"success")}catch(me){r(`Failed to attach ${ge.name}: ${je(me)}`,"error")}},[e.id,ye,r]),Be=a.useCallback(()=>{k||i(e)},[e,i,k]),Je=a.useCallback(F=>{if($.current){$.current=!1;return}ee(F.target)||Be()},[Be,ee]),Ye=a.useCallback(F=>{const H=F.touches[0];H&&(U.current={x:H.clientX,y:H.clientY,time:Date.now()},Ne.current=!1)},[]),Ge=a.useCallback(F=>{if(!U.current)return;const H=F.touches[0];if(!H)return;const ge=Math.abs(H.clientX-U.current.x),me=Math.abs(H.clientY-U.current.y);(ge>mu||me>mu)&&(Ne.current=!0)},[]),it=a.useCallback(F=>{if(ee(F.target)||!U.current)return;const ge=Date.now()-U.current.time<Vw,me=!Ne.current;ge&&me&&($.current=!0,Be()),U.current=null,Ne.current=!1},[Be,ee]),_e=a.useCallback(async(F,H)=>{F.stopPropagation();try{const ge=await ao(H,n);i(ge)}catch{r(`Failed to load dependency ${H}`,"error")}},[i,r]),Fe=e.status==="failed",ae=e.paused===!0,be=Cw(e.priority),ne=be!==ps,Ie=lo(e,h,f),Pe=e.column==="triage"&&e.status==="awaiting-approval",ce=e.column==="archived",le=!o&&!s&&!Fe&&!ae&&!Ie&&!Pe&&(e.column==="in-progress"||du.has(e.status)),$e=!s&&!ae&&!k&&!ce,at=Mw.has(e.column)&&!le&&!ae&&!s&&l,tt=!!(e.prInfo||e.issueInfo),V=!!(e.assignedAgentId&&P===null),de=a.useMemo(()=>{const F=[];return e.modelProvider&&F.push(e.modelProvider),e.validatorModelProvider&&!F.includes(e.validatorModelProvider)&&F.push(e.validatorModelProvider),e.planningModelProvider&&!F.includes(e.planningModelProvider)&&F.push(e.planningModelProvider),F},[e.modelProvider,e.validatorModelProvider,e.planningModelProvider]),Z=a.useMemo(()=>up(e,x),[e.steps,e.enabledWorkflowSteps,e.workflowStepResults,x]),we=Z.total>0&&(e.status==="executing"||e.column==="in-progress");a.useEffect(()=>{if(e.column!=="in-progress"||!(e.workflowStepResults??[]).some(ge=>ge.startedAt&&!ge.completedAt))return;X(Date.now());const H=window.setInterval(()=>{X(Date.now())},Rw);return()=>window.clearInterval(H)},[e.column,e.workflowStepResults]);const pe=a.useMemo(()=>{if(!Aw.has(e.column))return null;const F=Iw(e,G);if(F==null)return null;const H=$w(F);if(!H)return null;if(e.column==="in-progress")return{label:H,title:`Execution time ${H}`,ariaLabel:`Execution time ${H}`};const ge=Tw(e);if(ge==null)return{label:H,title:`Execution time ${H}`,ariaLabel:`Execution time ${H}`};const me=new Date(ge).toLocaleString();return{label:H,title:`Execution time ${H}. Completed ${me}`,ariaLabel:`Execution time ${H}. Completed ${me}`}},[e.column,e.columnMovedAt,e.updatedAt,e.workflowStepResults,e.log,G]);a.useEffect(()=>{if(!tt||!J){se(e.id);return}return he(e.id),()=>{se(e.id)}},[tt,J,he,e.id,se]);const Te=oe.get(`${n??"default"}:${e.id}`),Qe=e.column==="in-progress"||e.column==="in-review",Ee=a.useMemo(()=>e.steps.map(F=>`${F.name}:${F.status}`).join("|"),[e.steps]),{stats:Re}=gw(e.id,e.column,e.mergeDetails?.commitSha,n,{enabled:J,worktree:e.worktree,stepVersion:Qe?Ee:void 0,pollIntervalMs:Qe?3e4:void 0}),Le=a.useMemo(()=>uw(e.id,n),[e.id,n]),ct=a.useMemo(()=>{const F=Te?.prInfo,H=Te?.timestamp,ge=Le?.result?.prInfo,me=Le?.timestamp?new Date(Le.timestamp).toISOString():void 0,We=e.prInfo,dt=e.prInfo?.lastCheckedAt??e.updatedAt;let _t=oo(F,H,We,dt);const $t=H&&H>=dt?H:dt;return ge&&me&&(!$t||me>$t)&&(_t=ge),_t},[Te,Le,e.prInfo,e.updatedAt]),Se=a.useMemo(()=>{const F=Te?.issueInfo,H=Te?.timestamp,ge=Le?.result?.issueInfo,me=Le?.timestamp?new Date(Le.timestamp).toISOString():void 0,We=e.issueInfo,dt=e.issueInfo?.lastCheckedAt??e.updatedAt;let _t=oo(F,H,We,dt);const $t=H&&H>=dt?H:dt;return ge&&me&&(!$t||me>$t)&&(_t=ge),_t},[Te,Le,e.issueInfo,e.updatedAt]),mt=a.useCallback(F=>{F?.stopPropagation(),!(!at||N)&&(M(!0),_(e.description||""))},[at,N,e.description]),gt=a.useCallback(()=>{M(!1),_(e.description||"")},[e.description]),wt=a.useCallback(()=>w!==(e.description||""),[w,e.description]),yt=a.useCallback(async()=>{if(!(!l||N)){if(!wt()){gt();return}L(!0);try{await l(e.id,{description:w.trim()||void 0}),r(`Updated ${e.id}`,"success"),M(!1)}catch(F){r(`Failed to update ${e.id}: ${je(F)}`,"error")}finally{L(!1)}}},[l,e.id,w,N,wt,gt,r]),kt=a.useCallback(F=>{F.key==="Enter"&&!F.shiftKey?(F.preventDefault(),yt()):F.key==="Escape"&&(F.preventDefault(),gt())},[yt,gt]),Ct=a.useCallback(()=>{setTimeout(()=>{const F=document.activeElement;F===C.current||F?.closest(".card-editing-content")||(wt()?yt():gt())},0)},[wt,yt,gt]),Rt=a.useCallback(F=>{at&&(F.stopPropagation(),mt(F))},[at,mt]),Ft=a.useCallback(F=>{F.stopPropagation(),mt(F)},[mt]),Ut=a.useCallback(F=>{_(F.target.value);const H=F.target;H.style.height="auto",H.style.height=H.scrollHeight+"px"},[]),St=a.useCallback(F=>{F.stopPropagation(),c&&c(e.id).then(()=>{r(`Archived ${e.id}`,"success")}).catch(H=>{r(`Failed to archive ${e.id}: ${je(H)}`,"error")})},[r,c,e.id]),Et=a.useCallback(F=>{F.stopPropagation(),u&&u(e.id).then(()=>{r(`Unarchived ${e.id}`,"success")}).catch(H=>{r(`Failed to unarchive ${e.id}: ${je(H)}`,"error")})},[r,u,e.id]),It=a.useCallback(async F=>{if(F.stopPropagation(),!(!d||!await fe({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0})))try{await d(e.id),r(`Deleted ${e.id}`,"success")}catch(ge){const me=Fw(ge);if(!me||me.dependentIds.length===0){r(`Failed to delete ${e.id}: ${je(ge)}`,"error");return}const We=me.dependentIds.join(", ");if(!await fe({title:"Force Delete Task",message:`${e.id} is a dependency of ${We}.
607
+
608
+ Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await d(e.id,{removeDependencyReferences:!0}),r(`Deleted ${e.id} after removing dependency references`,"success")}catch(_t){r(`Failed to delete ${e.id}: ${je(_t)}`,"error")}}},[r,fe,d,e.id]),Mt=a.useCallback(F=>{F.stopPropagation(),m?.(e,"changes")},[e,m]),Kt=a.useCallback(F=>{F.stopPropagation(),I(H=>!H)},[]),Ot=a.useCallback(F=>{F.stopPropagation(),e.missionId&&g&&g(e.missionId)},[e.missionId,g]),xe=a.useCallback(F=>{F.stopPropagation(),B(H=>!H)},[]),st=a.useCallback((F,H)=>{F.stopPropagation(),B(!1),p&&p(e.id,H).then(()=>{r(`Moved ${e.id} to ${$n[H]}`,"success")}).catch(ge=>{r(`Failed to move ${e.id}: ${je(ge)}`,"error")})},[r,p,e.id]),Ve=`card${v?" dragging":""}${s?" queued":""}${le?" agent-active":""}${Fe?" failed":""}${ae?" paused":""}${Ie?" stuck":""}${Pe?" awaiting-approval":""}${y?" file-drop-target":""}${k?" card-editing":""}${N?" card-saving":""}`,Y=(()=>{if(e.worktree&&e.column==="in-progress"){const F=Re?.filesChanged;return F==null||F===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:Mt,disabled:!m,children:[t.jsx(Dn,{size:12}),t.jsxs("span",{children:[F," ",F===1?"file":"files"," changed"]})]})}if(e.column==="in-review"){const F=Re?.filesChanged,H=F==null?e.modifiedFiles?.length:void 0,ge=F??H;return ge==null||ge===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:Mt,disabled:!m,children:[t.jsx(Dn,{size:12}),t.jsxs("span",{children:[ge," ",ge===1?"file":"files"," changed"]})]})}if(e.column==="done"){const F=Re?.filesChanged,H=e.mergeDetails?.filesChanged,ge=F??H;if(ge!=null&&ge>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:Mt,disabled:!m,children:[t.jsx(Dn,{size:12}),t.jsxs("span",{children:[ge," ",ge===1?"file":"files"," changed"]})]});const me=e.modifiedFiles?.length;if(me!=null&&me>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:Mt,disabled:!m,children:[t.jsx(Dn,{size:12}),t.jsxs("span",{children:[me," ",me===1?"file":"files"," changed"]})]})}return null})();return k?t.jsx("div",{ref:A,className:Ve,"data-id":e.id,onDoubleClick:Rt,children:t.jsxs("div",{className:"card-editing-content",children:[t.jsx("textarea",{ref:C,className:"card-edit-desc-textarea",placeholder:"Task description",value:w,onChange:Ut,onKeyDown:kt,onBlur:Ct,disabled:N,rows:4}),N&&t.jsxs("div",{className:"card-edit-loading",children:[t.jsx("span",{className:"card-edit-loading-spinner"}),t.jsx("span",{className:"card-edit-loading-text",children:"Saving..."})]})]})}):t.jsxs("div",{ref:A,className:Ve,"data-id":e.id,draggable:$e,onDragStart:$e?ve:void 0,onDragEnd:$e?ue:void 0,onDragOver:ie,onDragLeave:Me,onDrop:ze,onClick:Je,onTouchStart:Ye,onTouchMove:Ge,onTouchEnd:it,onDoubleClick:Rt,children:[t.jsxs("div",{className:"card-header",children:[t.jsx("span",{className:"card-id",children:e.id}),ae&&t.jsx("span",{className:"card-status-badge paused",children:"paused"}),!ae&&e.status&&e.status!=="queued"&&t.jsx("span",{className:`card-status-badge card-status-badge--${e.column}${Pe?" awaiting-approval":""}${du.has(e.status)?" pulsing":""}${Fe?" failed":""}${Ie?" stuck":""}`,children:Ie?"Stuck":Pe?"Awaiting Approval":e.status}),Ie&&(ae||!e.status||e.status==="queued")&&t.jsx("span",{className:"card-status-badge stuck",children:"Stuck"}),tt&&t.jsx(lp,{prInfo:ct,issueInfo:Se}),ne&&t.jsx("span",{className:`card-priority-badge card-priority-badge--${be}`,children:be}),e.executionMode==="fast"&&t.jsx("span",{className:"card-execution-mode-badge card-execution-mode-badge--fast",children:"Fast"}),e.missionId&&t.jsxs("span",{className:"card-mission-badge",onClick:Ot,title:`Mission: ${z??e.missionId}`,role:g?"button":void 0,tabIndex:g?0:void 0,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[t.jsx(rs,{size:11}),Nw(z??e.missionId)]}),t.jsxs("div",{className:"card-header-actions",children:[at&&t.jsx("button",{className:"card-edit-btn",onClick:Ft,title:"Edit task","aria-label":"Edit task",children:t.jsx(Qn,{size:12})}),e.column==="triage"&&d&&t.jsx("button",{className:"card-delete-btn",onClick:It,title:"Delete task","aria-label":"Delete task",children:t.jsx(Jt,{size:12})}),e.column==="done"&&c&&t.jsx("button",{className:"card-archive-btn",onClick:St,title:"Archive task","aria-label":"Archive task",children:"Archive"}),e.column==="archived"&&u&&t.jsx("button",{className:"card-unarchive-btn",onClick:Et,title:"Unarchive task","aria-label":"Unarchive task",children:"Unarchive"}),e.column==="in-progress"&&p&&t.jsxs("div",{className:"card-send-back",ref:j,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:xe,title:"Send back","aria-label":"Send back","aria-haspopup":"menu","aria-expanded":R,children:["Send back",t.jsx(qt,{size:10})]}),R&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:mc["in-progress"].filter(F=>F!=="in-review").map(F=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:H=>st(H,F),children:$n[F]},F))})]}),e.column==="in-review"&&p&&t.jsxs("div",{className:"card-send-back",ref:j,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:xe,title:"Move task","aria-label":"Move task","aria-haspopup":"menu","aria-expanded":R,children:["Move",t.jsx(qt,{size:10})]}),R&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:mc["in-review"].map(F=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:H=>st(H,F),children:F==="done"?"Done (no merge)":$n[F]},F))})]}),e.size&&t.jsx("span",{className:`card-size-badge size-${e.size.toLowerCase()}`,children:e.size})]})]}),Fe&&e.error&&t.jsxs("div",{className:"card-error",title:e.error,children:[t.jsx("span",{className:"card-error-icon",children:"⚠"}),t.jsx("span",{className:"card-error-text",children:e.error.length>60?e.error.slice(0,60)+"…":e.error})]}),t.jsx("div",{className:"card-title",title:e.title||e.description||void 0,children:pu(e.title,hu)||pu(e.description,hu)||e.id}),we&&(()=>{const F=Z.completed/Z.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:`${F}%`,backgroundColor:_w[e.column]}})}),t.jsxs("span",{className:"card-progress-label",children:[Z.completed,"/",Z.total]})]}),t.jsxs("button",{type:"button",className:"card-steps-toggle",onClick:Kt,"aria-expanded":T,"aria-label":T?"Hide steps":"Show steps",children:[t.jsxs("span",{children:[Z.total," step",Z.total===1?"":"s"]}),t.jsx(qt,{size:14,className:`card-steps-toggle-icon${T?" expanded":""}`})]}),T&&t.jsx("div",{className:"card-steps-list",children:Z.items.map(H=>{const ge=H.source==="workflow"&&H.status==="failed";return t.jsxs("div",{className:"card-step-item",children:[t.jsx("span",{className:`card-step-dot card-step-dot--${H.status}${ge?" card-step-dot--workflow-failed":""}`,"aria-hidden":"true"}),t.jsx("span",{className:`card-step-name${H.status==="done"?" completed":""}`,children:H.name}),H.source==="workflow"&&t.jsx("span",{className:`card-step-workflow-badge card-step-workflow-badge--${H.phase}`,title:"Workflow check",children:"workflow"})]},H.id)})})]})})(),(Y||pe)&&t.jsxs("div",{className:"card-footer-row",children:[Y,pe&&t.jsxs("span",{className:"card-time-indicator",title:pe.title,"aria-label":pe.ariaLabel,children:[t.jsx(hi,{size:12}),t.jsx("span",{children:pe.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(F=>t.jsxs("span",{className:"card-dep-badge clickable",onClick:H=>void _e(H,F),title:`Click to view ${F}`,children:[t.jsx(ia,{size:12,style:{verticalAlign:"middle"}})," ",F]},F))}),e.blockedBy&&t.jsxs("span",{className:"card-scope-badge","data-tooltip":`Blocked by ${e.blockedBy} (file overlap)`,children:[t.jsx(Ti,{size:12,style:{verticalAlign:"middle"}})," ",e.blockedBy]}),(s||e.status==="queued")&&e.column!=="in-progress"&&t.jsxs("span",{className:"queued-badge",children:[t.jsx(hi,{size:12,style:{verticalAlign:"middle"}})," Queued"]})]}),(e.assignedAgentId||de.length>0)&&t.jsxs("div",{className:"card-agent-row",children:[de.length>0&&t.jsx("span",{className:"card-provider-icons","data-testid":"card-provider-icons",children:de.map(F=>t.jsx(Tn,{provider:F,size:"sm"},F))}),e.assignedAgentId&&t.jsxs("span",{className:`card-agent-badge${V?" card-agent-badge--loading":""}`,title:`Assigned to ${P??e.assignedAgentId}`,children:[t.jsx(pn,{size:11}),t.jsx("span",{className:"card-agent-badge-text",children:Ew(P??e.assignedAgentId,15)})]})]}),t.jsx(Ao,{slotId:"task-card-badge",projectId:n})]})}const mu=10,Vw=300,hu=140;function pu(e,n){return e?e.length>n?e.slice(0,n)+"…":e:""}const co=a.memo(qw,Hw);co.displayName="TaskCard";function Ww({label:e,activeTasks:n,queuedTasks:s,projectId:i,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onOpenDetailWithTab:u,taskStuckTimeoutMs:d,onOpenMission:m,lastFetchTimeMs:h,workflowStepNameLookup:g}){return t.jsxs("div",{className:"worktree-group",children:[t.jsxs("div",{className:"worktree-group-header",children:[t.jsx("span",{className:"worktree-icon",children:e==="Up Next"||e==="Unassigned"?t.jsx(Dg,{size:14}):t.jsx(Vs,{size:14})}),t.jsx("span",{className:"worktree-label",children:e})]}),n.map(p=>t.jsx(co,{task:p,projectId:i,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onOpenDetailWithTab:u,taskStuckTimeoutMs:d,onOpenMission:m,lastFetchTimeMs:h,workflowStepNameLookup:g},p.id)),s.map(p=>t.jsx(co,{task:p,projectId:i,queued:!0,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onOpenDetailWithTab:u,taskStuckTimeoutMs:d,onOpenMission:m,lastFetchTimeMs:h,workflowStepNameLookup:g},p.id))]})}const hp=a.memo(Ww);hp.displayName="WorktreeGroup";function fu(e){return e.toLowerCase().replace(/[-_./]/g,"")}function Kw(e,n){let s=0;for(let i=0;i<n.length&&s<e.length;i++)e[s]===n[i]&&s++;return s===e.length}function Gw(e,n,s){const i=e.length,r=n.length;if(i===0)return!0;if(r===0)return!1;let o=new Array(r+1).fill(0),l=new Array(r+1).fill(0);for(let c=1;c<=i;c++){const u=new Array(r+1);u[0]=c;for(let d=1;d<=r;d++){const m=e[c-1]===n[d-1]?0:1;u[d]=Math.min(l[d]+1,u[d-1]+1,l[d-1]+m),c>=2&&d>=2&&e[c-1]===n[d-2]&&e[c-2]===n[d-1]&&(u[d]=Math.min(u[d],o[d-2]+1))}o=l,l=u}for(let c=0;c<=r;c++)if(l[c]<=s)return!0;return!1}function Jw(e,n){const s=fu(e),i=fu(n);if(s.length===0||i.includes(s))return!0;const r=i.split(/\s+/).filter(Boolean);for(const o of r)if(s.length>=3&&Kw(s,o)||s.length>=4&&Gw(s,o,1))return!0;return!1}function Yw(e,n){const s=n.toLowerCase().trim().split(/\s+/).filter(Boolean);return s.length===0?e:e.filter(i=>{const r=`${i.provider} ${i.id} ${i.name}`;return s.every(o=>Jw(o,r))})}function Ln({models:e,value:n,onChange:s,placeholder:i="Select a model…",disabled:r=!1,id:o,label:l,favoriteProviders:c=[],onToggleFavorite:u,favoriteModels:d=[],onToggleModelFavorite:m,noChangeValue:h,noChangeLabel:g="No change"}){const[p,f]=a.useState(!1),[x,v]=a.useState(""),[b,y]=a.useState(0),[S,k]=a.useState(null),[M,w]=a.useState(null),_=a.useRef(null),N=a.useRef(null),L=a.useRef(null),T=a.useRef(null),I=a.useRef(null),z=a.useMemo(()=>Yw(e,x),[e,x]),K=a.useMemo(()=>z.reduce((ee,ve)=>((ee[ve.provider]??=[]).push(ve),ee),{}),[z]),P=a.useMemo(()=>{const ee=[];for(const ve of d){const ue=ve.indexOf("/");if(ue===-1)continue;const ye=ve.slice(0,ue),ie=ve.slice(ue+1),Me=z.find(ze=>ze.provider===ye&&ze.id===ie);Me&&ee.push({model:Me,fullId:ve})}return ee},[d,z]),E=a.useMemo(()=>{const ee=Object.entries(K),ve=new Set(c);return ee.sort(([ue],[ye])=>{const ie=ve.has(ue),Me=ve.has(ye);if(ie&&!Me)return-1;if(!ie&&Me)return 1;if(ie&&Me){const ze=c.indexOf(ue),Be=c.indexOf(ye);if(ze!==Be)return ze-Be}return ue.localeCompare(ye)})},[K,c]),R=typeof h=="string"&&h.length>0,B=a.useMemo(()=>{if(!n||R&&n===h)return null;const ee=n.indexOf("/");return ee===-1?null:n.slice(0,ee)},[R,h,n]),G=a.useMemo(()=>{const ee=[];return R&&ee.push({type:"no-change",value:h,label:g}),ee.push({type:"default",value:"",label:"Use default"}),ee},[R,g,h]),X=a.useMemo(()=>{const ee=[...G];for(const{model:ve,fullId:ue}of P)ee.push({type:"favorite",value:ue,label:ve.name,provider:ve.provider});return E.forEach(([ve,ue])=>{ee.push({type:"provider",value:`__group_${ve}`,label:ve,provider:ve}),ue.forEach(ye=>{ee.push({type:"model",value:`${ye.provider}/${ye.id}`,label:ye.name,provider:ye.provider})})}),ee},[P,E,G]),C=a.useMemo(()=>{if(R&&n===h)return g;if(!n)return"Use default";const ee=n.indexOf("/");if(ee===-1)return n;const ve=n.slice(0,ee),ue=n.slice(ee+1);return e.find(ie=>ie.provider===ve&&ie.id===ue)?.name||n},[R,g,h,n,e]),$=a.useMemo(()=>X.findIndex(ee=>ee.value===n),[X,n]),A=a.useCallback(()=>{const ee=window.visualViewport;return ee&&ee.height>0&&ee.width>0?{width:ee.width,height:ee.height,offsetTop:ee.offsetTop,offsetLeft:ee.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),j=a.useCallback(()=>{const{height:ee}=A(),ve=typeof window.matchMedia=="function",ue=ve?window.matchMedia("(max-width: 640px)").matches:!1,ye=ve?window.matchMedia("(max-width: 768px)").matches:!1;return ee<=0?320:ue?Math.min(ee*.6,360):ye?Math.min(ee*.7,420):320},[A]),J=a.useCallback(()=>{const ee=N.current;if(!ee)return;const ve=ee.getBoundingClientRect(),{width:ue,height:ye,offsetTop:ie,offsetLeft:Me}=A(),ze=16,Be=16,Je=4,Ye=j(),Ge=ve.bottom-ie,it=ve.top-ie,_e=ve.left-Me,Fe=ye-Ge,ae=it,be=Math.max(Fe-Be-Je,160),ne=Math.max(ae-Be-Je,160),Ie=Fe<Ye&&ae>Fe,Pe=Math.max(Math.min(Ie?ne:be,Ye),160),ce=Math.min(ve.width,ue-ze*2),le=Math.min(Math.max(_e,ze),ue-ze-ce)+Me,$e=Ie?Math.max(Be+ie,it-Pe-Je+ie):Math.min(Ge+Je+ie,ye+ie-Be-Pe);k({top:$e,left:le,width:ce,maxHeight:Pe})},[A,j]);a.useEffect(()=>{w(document.body)},[]);const W=a.useRef(!1);a.useEffect(()=>{if(!p){W.current=!1;return}if(W.current||X.length===0)return;const ee=X.findIndex((ve,ue)=>ue>=($>=0?$:0)&&ve.type!=="provider");y(ee>=0?ee:0),W.current=!0},[p,X,$]),a.useEffect(()=>{p&&W.current&&(y(0),I.current&&(I.current.scrollTop=0))},[x,p]),a.useEffect(()=>{if(!p)return;J();const ee=requestAnimationFrame(()=>T.current?.focus());return()=>cancelAnimationFrame(ee)},[p,J]),a.useEffect(()=>{if(!p)return;const ee=()=>J();window.addEventListener("resize",ee),window.addEventListener("scroll",ee,!0);const ve=window.visualViewport;return ve&&(ve.addEventListener("resize",ee),ve.addEventListener("scroll",ee)),()=>{window.removeEventListener("resize",ee),window.removeEventListener("scroll",ee,!0),ve&&(ve.removeEventListener("resize",ee),ve.removeEventListener("scroll",ee))}},[p,J]),a.useEffect(()=>{if(!p)return;const ee=ve=>{const ue=ve.target,ye=_.current?.contains(ue),ie=L.current?.contains(ue);!ye&&!ie&&(f(!1),v(""))};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[p]);const oe=a.useCallback(ee=>{switch(ee.key){case"ArrowDown":if(ee.preventDefault(),!p)f(!0);else{let ve=b;for(let ue=1;ue<=X.length;ue++){const ye=(b+ue)%X.length;if(X[ye]?.type!=="provider"){ve=ye;break}}y(ve)}break;case"ArrowUp":if(ee.preventDefault(),p){let ve=b;for(let ue=1;ue<=X.length;ue++){const ye=(b-ue+X.length)%X.length;if(X[ye]?.type!=="provider"){ve=ye;break}}y(ve)}break;case"Enter":if(ee.preventDefault(),p){const ve=X[b];ve&&ve.type!=="provider"&&ve.type!=="favorite"&&(s(ve.value),f(!1),v(""))}else f(!0);break;case"Escape":ee.preventDefault(),f(!1),v("");break;case"Tab":p&&(f(!1),v(""));break}},[p,b,X,s]),he=a.useCallback(ee=>{s(ee),f(!1),v("")},[s]),se=a.useCallback(()=>{v(""),T.current?.focus()},[]),fe=a.useCallback(()=>{r||f(ee=>!ee)},[r]);a.useEffect(()=>{if(p&&I.current){const ee=I.current.querySelector(`[data-index="${b}"]`);ee&&typeof ee.scrollIntoView=="function"&&ee.scrollIntoView({block:"nearest"})}},[b,p]);const U=x.length>0,Ne=p&&S?t.jsxs("div",{ref:L,className:"model-combobox-dropdown model-combobox-dropdown--portal",role:"listbox","data-testid":"model-combobox-portal",onKeyDown:oe,style:{top:`${S.top}px`,left:`${S.left}px`,width:`${S.width}px`,maxHeight:`${S.maxHeight}px`},children:[t.jsxs("div",{className:"model-combobox-search-wrapper",children:[t.jsx("input",{ref:T,type:"text",className:"model-combobox-search",placeholder:"Filter models…",value:x,onChange:ee=>v(ee.target.value),onClick:ee=>ee.stopPropagation()}),U&&t.jsx("button",{type:"button",className:"model-combobox-clear",onClick:se,"aria-label":"Clear filter",children:"×"})]}),t.jsxs("div",{className:"model-combobox-results-count",children:[z.length," model",z.length!==1?"s":""]}),t.jsxs("div",{ref:I,className:"model-combobox-list",children:[G.map((ee,ve)=>t.jsx("div",{"data-index":ve,className:`model-combobox-option ${b===ve?"model-combobox-option--highlighted":""} ${n===ee.value?"model-combobox-option--selected":""}`,onClick:()=>he(ee.value),onMouseEnter:()=>y(ve),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}`)),P.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"model-combobox-divider"}),P.map(({model:ee,fullId:ve},ue)=>{const ye=ue+G.length,ie=b===ye,Me=n===ve;return t.jsxs("div",{"data-index":ye,className:`model-combobox-option model-combobox-option--favorite ${ie?"model-combobox-option--highlighted":""} ${Me?"model-combobox-option--selected":""}`,onClick:()=>he(ve),onMouseEnter:()=>y(ye),role:"option","aria-selected":Me,children:[t.jsxs("span",{className:"model-combobox-option-main",children:[t.jsx("span",{className:"model-combobox-option-icon",children:t.jsx(Tn,{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:ze=>{ze.stopPropagation(),m(ve)},title:"Remove from favorites","aria-label":`Remove ${ee.name} from favorites`,children:"★"})]},ve)}),t.jsx("div",{className:"model-combobox-divider"})]}),E.map(([ee,ve])=>{const ue=X.findIndex(Me=>Me.value===`__group_${ee}`),ye=c.includes(ee),ie=ve.filter(Me=>{const ze=`${Me.provider}/${Me.id}`;return!d.includes(ze)});return ie.length===0?null:t.jsxs("div",{className:"model-combobox-group",children:[t.jsxs("div",{className:"model-combobox-optgroup","data-index":ue,children:[t.jsx(Tn,{provider:ee,size:"sm"}),t.jsx("span",{className:"model-combobox-optgroup-text",children:ee}),u&&t.jsx("button",{type:"button",className:`model-combobox-optgroup-favorite ${ye?"model-combobox-optgroup-favorite--active":""}`,onClick:Me=>{Me.stopPropagation(),u(ee)},title:ye?"Remove from favorites":"Add to favorites","aria-label":ye?`Remove ${ee} from favorites`:`Add ${ee} to favorites`,children:"★"})]}),ie.map(Me=>{const ze=`${Me.provider}/${Me.id}`,Be=X.findIndex(it=>it.value===ze),Je=b===Be,Ye=n===ze,Ge=d.includes(ze);return t.jsxs("div",{"data-index":Be,className:`model-combobox-option ${Je?"model-combobox-option--highlighted":""} ${Ye?"model-combobox-option--selected":""}`,onClick:()=>he(ze),onMouseEnter:()=>y(Be),role:"option","aria-selected":Ye,children:[t.jsx("span",{className:"model-combobox-option-text",children:Me.name}),t.jsx("span",{className:"model-combobox-option-id",children:Me.id}),m&&t.jsx("button",{type:"button",className:`model-combobox-option-favorite ${Ge?"model-combobox-option-favorite--active":""}`,onClick:it=>{it.stopPropagation(),m(ze)},title:Ge?"Remove from favorites":"Add to favorites","aria-label":Ge?`Remove ${Me.name} from favorites`:`Add ${Me.name} to favorites`,children:Ge?"★":"☆"})]},ze)})]},ee)}),z.length===0&&U&&t.jsxs("div",{className:"model-combobox-no-results",children:["No models match '",x,"'"]})]})]}):null;return t.jsxs(t.Fragment,{children:[t.jsx("div",{ref:_,className:"model-combobox",onKeyDown:oe,children:t.jsxs("button",{ref:N,type:"button",id:o,className:"model-combobox-trigger",onClick:fe,disabled:r,"aria-haspopup":"listbox","aria-expanded":p,"aria-label":l,children:[B&&t.jsx("span",{className:"model-combobox-trigger-icon",children:t.jsx(Tn,{provider:B,size:"sm"})}),t.jsx("span",{className:"model-combobox-trigger-text",children:C||i}),t.jsx("span",{className:"model-combobox-trigger-arrow",children:"▼"})]})}),M&&Ne?qa.createPortal(Ne,M):null]})}function Hc(e,n){return typeof n!="string"||n.length===0?e:`kb:${n}:${e}`}function zn(e,n){return typeof window>"u"?null:window.localStorage.getItem(Hc(e,n))}function as(e,n,s){typeof window>"u"||window.localStorage.setItem(Hc(e,s),n)}function rr(e,n){typeof window>"u"||window.localStorage.removeItem(Hc(e,n))}const Ea="kb-quick-entry-text",Qw=["image/png","image/jpeg","image/gif","image/webp"];function sl(e,n){return e&&n?`${e}/${n}`:""}function il(e){if(!e)return{provider:void 0,modelId:void 0};const n=e.indexOf("/");return n===-1?{provider:void 0,modelId:void 0}:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function pp({onCreate:e,addToast:n,tasks:s=[],availableModels:i,onPlanningMode:r,onSubtaskBreakdown:o,projectId:l,autoExpand:c=!0,favoriteProviders:u,favoriteModels:d,onToggleFavorite:m,onToggleModelFavorite:h}){const[g,p]=a.useState(()=>typeof window<"u"&&zn(Ea,l)||""),[f,x]=a.useState(!1),[v,b]=a.useState(!1),[y,S]=a.useState(!1),k=a.useRef(null),M=a.useRef(null),w=a.useRef(!1),_=a.useRef(l),[N,L]=a.useState([]),T=a.useRef([]),[I,z]=a.useState([]),[K,P]=a.useState(!1),[E,R]=a.useState(""),[B,G]=a.useState(null),[X,C]=a.useState([]),[$,A]=a.useState(void 0),[j,J]=a.useState(!1),[W,oe]=a.useState(!1),[he,se]=a.useState(!1),[fe,U]=a.useState(null),[Ne,ee]=a.useState(void 0),[ve,ue]=a.useState(void 0),[ye,ie]=a.useState(void 0),[Me,ze]=a.useState(void 0),[Be,Je]=a.useState(void 0),[Ye,Ge]=a.useState(void 0),it=a.useRef(null),_e=a.useRef(null),Fe=a.useRef(null),ae=a.useRef(null),[be,ne]=a.useState(null),[Ie,Pe]=a.useState(null),ce=a.useRef(null),le=a.useRef(null),[$e,at]=a.useState(null),[tt]=a.useState(()=>typeof document<"u"?document.body:null),[V,de]=a.useState(!1),[Z,we]=a.useState(null),[pe,Te]=a.useState(i??[]),[Qe,Ee]=a.useState([]),[Re,Le]=a.useState([]),[ct,Se]=a.useState(null),[mt,gt]=a.useState(void 0),[wt,yt]=a.useState(!1),[kt,Ct]=a.useState(!1),[Rt,Ft]=a.useState(!1),Ut=a.useRef(null),St=a.useRef(null),[Et,It]=a.useState(null),Mt=u??Qe,Kt=d??Re,Ot=!e;a.useEffect(()=>{if(i)Te(i),de(!1),we(null);else{let re=!1;return de(!0),we(null),os().then(Ae=>{re||(Te(Ae.models),u||Ee(Ae.favoriteProviders),d||Le(Ae.favoriteModels))}).catch(Ae=>{re||we(je(Ae)||"Failed to load models")}).finally(()=>{re||de(!1)}),Eo(l).then(Ae=>{re||Se(Ae)}).catch(()=>{}),()=>{re=!0}}},[i,u,d,l]);const xe=sl(Ne,ve),st=sl(ye,Me),Ve=sl(Be,Ye),Y=!!(Ne&&ve),F=!!(ye&&Me),H=!!(Be&&Ye),ge=Number(Y)+Number(F)+Number(H),me=mt?ct?.modelPresets?.find(re=>re.id===mt)?.name??"Models":ge>0?`${ge} model${ge===1?"":"s"}`:"Models",We=a.useCallback((re,Ae)=>{if(!re||!Ae)return"Using default";const lt=pe.find(vt=>vt.provider===re&&vt.id===Ae);return lt?`${lt.provider}/${lt.id}`:`${re}/${Ae}`},[pe]);a.useEffect(()=>{p(zn(Ea,l)||"")},[l]),a.useEffect(()=>{typeof window<"u"&&as(Ea,g,l)},[g,l]),a.useEffect(()=>{_.current!==l&&(_.current=l,C([]),A(void 0),G(null),J(!1),ne(null))},[l]),a.useEffect(()=>{typeof window<"u"&&localStorage.removeItem("kb-quick-entry-expanded")},[]),a.useEffect(()=>{T.current=N},[N]),a.useEffect(()=>()=>{T.current.forEach(re=>URL.revokeObjectURL(re.previewUrl))},[]);const dt=a.useCallback(()=>{const re=k.current;if(!re)return;re.style.height="auto";const Ae=Math.min(re.scrollHeight,200);re.style.height=`${Ae}px`},[]);a.useEffect(()=>{v&&dt()},[g,v,dt]),a.useEffect(()=>{if(!f&&g===""&&k.current){const re=setTimeout(()=>{k.current?.focus()},0);return()=>clearTimeout(re)}},[f,g]),a.useEffect(()=>{K||R("")},[K]),a.useEffect(()=>{if(!kt)return;const re=Ae=>{const lt=Ae.target,vt=Ut.current?.contains(lt),xt=St.current?.contains(lt);!vt&&!xt&&Ct(!1)};return document.addEventListener("mousedown",re),()=>document.removeEventListener("mousedown",re)},[kt]),a.useEffect(()=>{if(!he)return;const re=Ae=>{const lt=Ae.target,vt=it.current?.contains(lt),xt=_e.current?.contains(lt),Zt=lt instanceof Element&&lt.closest?.(".model-combobox-dropdown--portal")!=null;!vt&&!xt&&!Zt&&(se(!1),U(null))};return document.addEventListener("mousedown",re),()=>document.removeEventListener("mousedown",re)},[he]),a.useEffect(()=>{if(!j)return;const re=Ae=>{const lt=Ae.target;Fe.current?.contains(lt)||ae.current?.contains(lt)||(J(!1),ne(null))};return document.addEventListener("mousedown",re),()=>document.removeEventListener("mousedown",re)},[j]);const _t=a.useCallback(()=>{N.forEach(re=>URL.revokeObjectURL(re.previewUrl)),L([]),M.current&&(M.current.value=""),p(""),z([]),G(null),J(!1),ne(null),ee(void 0),ue(void 0),ie(void 0),ze(void 0),Je(void 0),Ge(void 0),gt(void 0),yt(!1),P(!1),se(!1),Pe(null),U(null),Ct(!1),Ft(!1),b(!1),S(!1),w.current=!0,k.current&&(k.current.style.height="auto"),typeof window<"u"&&rr(Ea,l)},[N,l]),$t=a.useCallback(re=>{if(!re||re.length===0)return;const Ae=[];for(let lt=0;lt<re.length;lt++){const vt=re[lt];Qw.includes(vt.type)&&Ae.push({file:vt,previewUrl:URL.createObjectURL(vt)})}Ae.length>0&&L(lt=>[...lt,...Ae])},[]),vn=a.useCallback(re=>{f||$t(re.clipboardData?.files)},[$t,f]),kn=a.useCallback(re=>{L(Ae=>{const lt=Ae[re];return lt&&URL.revokeObjectURL(lt.previewUrl),Ae.filter((vt,xt)=>xt!==re)})},[]),Yt=a.useCallback(async()=>{const re=g.trim();if(!(!re||f||!e)){x(!0);try{const Ae=await e({description:re,column:"triage",dependencies:I.length?I:void 0,...B?{assignedAgentId:B}:{},modelPresetId:mt,modelProvider:Y?Ne:void 0,modelId:Y?ve:void 0,validatorModelProvider:F?ye:void 0,validatorModelId:F?Me:void 0,planningModelProvider:H?Be:void 0,planningModelId:H?Ye:void 0,...wt?{executionMode:"fast"}:{}});if(Ae&&N.length>0){const lt=[];for(const vt of N)try{await sr(Ae.id,vt.file,l)}catch{lt.push(vt.file.name)}lt.length>0&&n(`Failed to upload: ${lt.join(", ")}`,"error")}_t()}catch(Ae){n(je(Ae)||"Failed to create task","error")}finally{x(!1)}}},[g,f,e,I,B,Y,Ne,ve,F,ye,Me,H,Be,Ye,N,l,n,_t,wt]),En=a.useCallback(re=>{if(re.key==="Enter"){if(re.shiftKey&&v)return;re.preventDefault(),Yt()}else if(re.key==="Escape"){if(re.preventDefault(),fe){U(null);return}if(he){se(!1),Pe(null);return}if(K){P(!1);return}if(kt){Ct(!1);return}if(j){J(!1),ne(null);return}g.trim()&&(p(""),k.current&&(k.current.style.height="auto"),typeof window<"u"&&rr(Ea,l)),b(!1),S(!1),k.current?.blur()}},[Yt,g,v,K,j,he,fe,kt,l,S]),on=a.useCallback(()=>{w.current&&(w.current=!1)},[]),Mn=a.useCallback(()=>{c&&b(!0)},[c]),Vt=a.useCallback(re=>{z(Ae=>Ae.includes(re)?Ae.filter(lt=>lt!==re):[...Ae,re])},[]),hn=a.useCallback(()=>{const re=window.visualViewport;return re&&re.width>0&&re.height>0?{width:re.width,height:re.height,offsetTop:re.offsetTop,offsetLeft:re.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),ke=a.useCallback(()=>{const re=it.current;if(!re)return;const Ae=re.getBoundingClientRect(),{width:lt,height:vt,offsetTop:xt,offsetLeft:Zt}=hn(),ot=16,Ht=16,en=4,An=lt<=768,yn=Math.min(An?vt*.6:vt*.5,360),xs=An?Math.min(lt-ot*2,360):Math.max(Ae.width,240),Gn=Math.min(xs,Math.max(lt-ot*2,200)),ts=Ae.top-xt,Jn=Ae.bottom-xt,ns=Ae.left-Zt,Sn=vt-Jn,ss=ts,_s=Math.max(Sn-Ht-en,160),Ys=Math.max(ss-Ht-en,160),bs=Sn<yn&&ss>Sn,On=Math.max(Math.min(bs?Ys:_s,yn),160),cs=Math.min(Math.max(ns,ot),lt-ot-Gn)+Zt,ds=bs?Math.max(Ht+xt,ts-On-en+xt):Math.min(Jn+en+xt,vt+xt-Ht-On);Pe({top:ds,left:cs,width:Gn,maxHeight:On})},[hn]),nt=a.useCallback(()=>{const re=Ut.current?.querySelector(".refine-button");if(!re)return;const Ae=re.getBoundingClientRect(),{width:lt,height:vt,offsetTop:xt,offsetLeft:Zt}=hn(),ot=8,Ht=12,en=4,An=Math.min(200,Math.max(vt-Ht*2,160)),yn=Math.min(200,lt-ot*2),xs=Ae.top-xt,Gn=Ae.bottom-xt,ts=Ae.left-Zt,Jn=vt-Gn,ns=xs,Sn=Jn<An&&ns>Jn,ss=Math.min(Math.max(ts,ot),lt-ot-yn)+Zt,_s=Sn?Math.max(Ht+xt,xs-An-en+xt):Math.min(Gn+en+xt,vt+xt-Ht-An);It({top:_s,left:ss})},[hn]),tn=a.useCallback(()=>{const re=ce.current;if(!re)return;const Ae=re.getBoundingClientRect(),{width:lt,height:vt,offsetTop:xt,offsetLeft:Zt}=hn(),ot=16,Ht=16,en=4,An=lt<=768,yn=Math.min(An?vt*.6:vt*.5,320),xs=An?Math.min(lt-ot*2,360):Math.max(Ae.width,280),Gn=Math.min(xs,Math.max(lt-ot*2,240)),ts=Ae.top-xt,Jn=Ae.bottom-xt,ns=Ae.left-Zt,Sn=vt-Jn,ss=ts,_s=Math.max(Sn-Ht-en,200),Ys=Math.max(ss-Ht-en,200),bs=Sn<yn&&ss>Sn,On=Math.max(Math.min(bs?Ys:_s,yn),200),cs=Math.min(Math.max(ns,ot),lt-ot-Gn)+Zt,ds=bs?Math.max(Ht+xt,ts-On-en+xt):Math.min(Jn+en+xt,vt+xt-Ht-On);at({top:ds,left:cs,width:Gn,maxHeight:On})},[hn]),Pn=a.useCallback(()=>{const re=Fe.current?.querySelector("button");if(!re)return;const Ae=re.getBoundingClientRect(),{width:lt,height:vt,offsetTop:xt,offsetLeft:Zt}=hn(),ot=16,Ht=16,en=4,An=lt<=768,yn=Math.min(An?vt*.6:vt*.5,320),xs=An?Math.min(lt-ot*2,280):Math.max(Ae.width,240),Gn=Math.min(xs,Math.max(lt-ot*2,200)),ts=Ae.top-xt,Jn=Ae.bottom-xt,ns=Ae.left-Zt,Sn=vt-Jn,ss=ts,_s=Math.max(Sn-Ht-en,160),Ys=Math.max(ss-Ht-en,160),bs=Sn<yn&&ss>Sn,On=Math.max(Math.min(bs?Ys:_s,yn),160),cs=Math.min(Math.max(ns,ot),lt-ot-Gn)+Zt,ds=bs?Math.max(Ht+xt,ts-On-en+xt):Math.min(Jn+en+xt,vt+xt-Ht-On);ne({top:ds,left:cs,width:Gn,maxHeight:On})},[hn]);a.useEffect(()=>{if(!he)return;const re=()=>ke();window.addEventListener("resize",re),window.addEventListener("scroll",re,!0);const Ae=window.visualViewport;return Ae&&(Ae.addEventListener("resize",re),Ae.addEventListener("scroll",re)),()=>{window.removeEventListener("resize",re),window.removeEventListener("scroll",re,!0),Ae&&(Ae.removeEventListener("resize",re),Ae.removeEventListener("scroll",re))}},[he,ke]),a.useEffect(()=>{if(!kt)return;const re=()=>nt();window.addEventListener("resize",re),window.addEventListener("scroll",re,!0);const Ae=window.visualViewport;return Ae&&(Ae.addEventListener("resize",re),Ae.addEventListener("scroll",re)),()=>{window.removeEventListener("resize",re),window.removeEventListener("scroll",re,!0),Ae&&(Ae.removeEventListener("resize",re),Ae.removeEventListener("scroll",re))}},[kt,nt]),a.useEffect(()=>{if(!K)return;const re=()=>tn();window.addEventListener("resize",re),window.addEventListener("scroll",re,!0);const Ae=window.visualViewport;return Ae&&(Ae.addEventListener("resize",re),Ae.addEventListener("scroll",re)),()=>{window.removeEventListener("resize",re),window.removeEventListener("scroll",re,!0),Ae&&(Ae.removeEventListener("resize",re),Ae.removeEventListener("scroll",re))}},[K,tn]),a.useEffect(()=>{if(!j)return;const re=()=>Pn();window.addEventListener("resize",re),window.addEventListener("scroll",re,!0);const Ae=window.visualViewport;return Ae&&(Ae.addEventListener("resize",re),Ae.addEventListener("scroll",re)),()=>{window.removeEventListener("resize",re),window.removeEventListener("scroll",re,!0),Ae&&(Ae.removeEventListener("resize",re),Ae.removeEventListener("scroll",re))}},[j,Pn]);const Nn=a.useCallback(re=>{const Ae=il(re);Je(Ae.provider),Ge(Ae.modelId)},[]),gn=a.useCallback(re=>{const Ae=il(re);ee(Ae.provider),ue(Ae.modelId)},[]),nn=a.useCallback(re=>{const Ae=il(re);ie(Ae.provider),ze(Ae.modelId)},[]),_n=a.useCallback(async re=>{if(m){m(re);return}const Ae=Qe,vt=Ae.includes(re)?Ae.filter(xt=>xt!==re):[re,...Ae];Ee(vt);try{await an({favoriteProviders:vt,favoriteModels:Re})}catch{Ee(Ae)}},[Qe,Re,m]),jn=a.useCallback(async re=>{if(h){h(re);return}const Ae=Re,vt=Ae.includes(re)?Ae.filter(xt=>xt!==re):[re,...Ae];Le(vt);try{await an({favoriteProviders:Qe,favoriteModels:vt})}catch{Le(Ae)}},[Re,Qe,h]),Q=a.useCallback(()=>{const re=g.trim();if(!re){n("Enter a description first","error");return}r?.(re),_t()},[g,r,n,_t]),Oe=a.useCallback(()=>{const re=g.trim();if(!re){n("Enter a description first","error");return}o?.(re),_t()},[g,o,n,_t]),Xe=a.useCallback(()=>{Yt()},[Yt]),Ze=a.useCallback(async re=>{const Ae=g.trim();if(!(!Ae||Rt)){Ct(!1),Ft(!0);try{const lt=await Jh(Ae,re,l);p(lt),n("Description refined with AI","success"),k.current&&(k.current.style.height="auto",k.current.style.height=`${Math.min(k.current.scrollHeight,200)}px`)}catch(lt){const vt=Yh(lt);n(vt,"error")}finally{Ft(!1)}}},[g,Rt,n,l]),pt=(re,Ae)=>re.length>Ae?re.slice(0,Ae)+"…":re,Nt=a.useCallback(async()=>{if(i){Te(i),we(null),de(!1);return}de(!0),we(null);try{const re=await os();Te(re.models),u||Ee(re.favoriteProviders),d||Le(re.favoriteModels)}catch(re){we(je(re)||"Failed to load models")}finally{de(!1)}},[i,u,d]),At=a.useCallback(async()=>{if(X.length>0&&$===l){J(!0),Pn();return}oe(!0);try{const re=await xa(void 0,l);C(re),A(l),J(!0),Pn()}catch(re){const Ae=je(re);n(Ae?`Failed to load agents: ${Ae}`:"Failed to load agents","error"),J(!1)}finally{oe(!1)}},[X.length,$,l,n,Pn]),Qt=(B?X.find(re=>re.id===B):void 0)?.name??B,bt=y,Kn=a.useCallback(()=>{S(re=>{const Ae=!re;return b(Ae),Ae})},[]);return t.jsxs("div",{className:`quick-entry-box ${y?"quick-entry-box--expanded":"quick-entry-box--collapsed"}`,"data-testid":"quick-entry-box",children:[t.jsx("div",{className:"description-with-refine",children:t.jsxs("div",{className:"quick-entry-main-row",children:[t.jsx("div",{className:"quick-entry-textarea-wrap",children:t.jsx("textarea",{ref:k,className:`quick-entry-input ${v?"quick-entry-input--expanded":""}`,placeholder:f?"Creating...":"Add a task...",value:g,onChange:re=>p(re.target.value),onKeyDown:En,onPaste:vn,onFocus:Mn,onBlur:on,disabled:f||Ot,"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:Kn,"aria-expanded":y,"aria-controls":"quick-entry-controls","data-testid":"quick-entry-toggle",title:y?"Collapse":"Expand",children:y?t.jsx(ni,{size:14}):t.jsx(qt,{size:14})})]})}),t.jsxs("div",{id:"quick-entry-controls",className:"quick-entry-controls",hidden:!bt,"aria-hidden":!bt,children:[bt&&!f&&t.jsxs("div",{className:"quick-entry-actions","data-testid":"quick-entry-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:Q,onMouseDown:re=>re.preventDefault(),disabled:!g.trim(),"data-testid":"plan-button",title:"Open planning mode with current description",children:[t.jsx(Ws,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Plan"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:Oe,onMouseDown:re=>re.preventDefault(),disabled:!g.trim(),"data-testid":"subtask-button",title:"Break down into AI-generated subtasks",children:[t.jsx(wo,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Subtask"]}),t.jsxs("div",{className:"refine-trigger-wrap",ref:Ut,children:[t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${Rt?"refine-button--loading":""}`,onClick:()=>{Ct(re=>{const Ae=!re;return Ae?nt():It(null),Ae})},disabled:!g.trim()||Rt,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(Vn,{size:12,style:{verticalAlign:"middle"}}),Rt?"Refining...":"Refine"]}),kt&&tt&&Et&&qa.createPortal(t.jsxs("div",{ref:St,className:"refine-menu refine-menu--portal",onMouseDown:re=>re.preventDefault(),style:{position:"fixed",top:`${Et.top}px`,left:`${Et.left}px`},children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>Ze("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:()=>Ze("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:()=>Ze("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:()=>Ze("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"})]})]}),tt)]}),t.jsx("div",{className:"dep-trigger-wrap",children:t.jsxs("button",{ref:ce,type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-deps",onClick:()=>{P(re=>{const Ae=!re;return Ae?(se(!1),Pe(null),U(null),J(!1),tn()):at(null),Ae})},children:[t.jsx(ia,{size:12,style:{verticalAlign:"middle"}}),I.length>0?`${I.length} deps`:"Deps"]})}),K&&tt&&$e&&(()=>{const re=E.toLowerCase(),Ae=(re?s.filter(lt=>lt.id.toLowerCase().includes(re)||lt.title&&lt.title.toLowerCase().includes(re)||lt.description&&lt.description.toLowerCase().includes(re)):[...s]).sort((lt,vt)=>{const xt=vt.createdAt.localeCompare(lt.createdAt);if(xt!==0)return xt;const Zt=parseInt(lt.id.slice(lt.id.lastIndexOf("-")+1),10)||0;return(parseInt(vt.id.slice(vt.id.lastIndexOf("-")+1),10)||0)-Zt});return qa.createPortal(t.jsxs("div",{ref:le,className:"dep-dropdown dep-dropdown--portal",onMouseDown:lt=>lt.preventDefault(),style:{position:"fixed",top:`${$e.top}px`,left:`${$e.left}px`,width:`${$e.width}px`,maxHeight:$e.maxHeight?`${$e.maxHeight}px`:void 0,overflowY:$e.maxHeight?"auto":void 0},children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:E,onChange:lt=>R(lt.target.value),onClick:lt=>lt.stopPropagation()}),Ae.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No existing tasks"}):Ae.map(lt=>t.jsxs("div",{className:`dep-dropdown-item${I.includes(lt.id)?" selected":""}`,onMouseDown:vt=>vt.preventDefault(),onClick:()=>Vt(lt.id),children:[t.jsx("span",{className:"dep-dropdown-id",children:lt.id}),t.jsx("span",{className:"dep-dropdown-title",children:pt(lt.title||lt.description||lt.id,60)})]},lt.id))]}),tt)})(),t.jsxs("button",{type:"button",className:"btn btn-sm","data-testid":"quick-entry-attach",onClick:()=>M.current?.click(),children:[t.jsx(nb,{size:12,style:{verticalAlign:"middle"}}),N.length>0?`Attach (${N.length})`:"Attach"]}),t.jsxs("button",{ref:it,type:"button",className:"btn btn-sm","data-testid":"quick-entry-models",onClick:()=>{P(!1),J(!1),U(null),se(!0),ke()},children:[t.jsx(eo,{size:12,style:{verticalAlign:"middle"}}),me]}),t.jsx("div",{className:"agent-trigger-wrap",ref:Fe,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{j?(J(!1),ne(null)):At()},"data-testid":"quick-entry-agent-button",children:[t.jsx(pn,{size:12,style:{verticalAlign:"middle"}}),Qt?` ${Qt}`:" Agent"]})}),j&&tt&&be&&qa.createPortal(t.jsxs("div",{ref:ae,className:"dep-dropdown agent-picker-dropdown agent-picker-dropdown--portal",onMouseDown:re=>re.preventDefault(),style:{position:"fixed",top:`${be.top}px`,left:`${be.left}px`,width:`${be.width}px`,maxHeight:be.maxHeight?`${be.maxHeight}px`:void 0,overflowY:be.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),W&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!W&&X.filter(re=>re.state!=="terminated").map(re=>t.jsxs("div",{className:`dep-dropdown-item${B===re.id?" selected":""}`,onMouseDown:Ae=>Ae.preventDefault(),onClick:()=>{G(re.id===B?null:re.id),J(!1),ne(null)},children:[t.jsx(pn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:re.role}),t.jsx("span",{className:"dep-dropdown-title",children:re.name})]},re.id)),!W&&X.filter(re=>re.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),B&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:re=>re.preventDefault(),onClick:()=>{G(null),J(!1),ne(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]}),tt),t.jsx("button",{type:"button",className:`btn btn-sm ${wt?"btn-primary":""}`,onClick:()=>yt(re=>!re),onMouseDown:re=>re.preventDefault(),"aria-pressed":wt,"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:Xe,onMouseDown:re=>re.preventDefault(),disabled:!g.trim()||f,"data-testid":"quick-entry-save",title:"Create task",children:[t.jsx(Fh,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Save"]})]}),N.length>0&&t.jsx("div",{className:"inline-create-previews",children:N.map((re,Ae)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:re.previewUrl,alt:re.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>kn(Ae),disabled:f,title:"Remove image","data-testid":`quick-entry-preview-remove-${Ae}`,children:"×"})]},re.previewUrl))}),he&&tt&&Ie&&qa.createPortal(t.jsx("div",{ref:_e,className:"model-nested-menu model-nested-menu--portal",onMouseDown:re=>re.preventDefault(),"data-testid":"model-nested-menu",style:{position:"fixed",top:`${Ie.top}px`,left:`${Ie.left}px`,width:`${Ie.width}px`,maxHeight:Ie.maxHeight?`${Ie.maxHeight}px`:void 0,overflowY:Ie.maxHeight?"auto":void 0},children:fe===null?t.jsxs("div",{className:"model-menu-items",children:[t.jsxs("button",{type:"button",className:`model-menu-item ${H?"model-menu-item--active":""}`,onClick:()=>U("plan"),"data-testid":"model-menu-plan",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(Ws,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Plan"]}),t.jsx("span",{className:"model-menu-item-value",children:H?We(Be,Ye):"Using default"}),t.jsx(mn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${Y?"model-menu-item--active":""}`,onClick:()=>U("executor"),"data-testid":"model-menu-executor",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(Vn,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Executor"]}),t.jsx("span",{className:"model-menu-item-value",children:Y?We(Ne,ve):"Using default"}),t.jsx(mn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${F?"model-menu-item--active":""}`,onClick:()=>U("validator"),"data-testid":"model-menu-validator",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(eo,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Reviewer"]}),t.jsx("span",{className:"model-menu-item-value",children:F?We(ye,Me):"Using default"}),t.jsx(mn,{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:()=>U(null),"data-testid":"model-submenu-back",children:[t.jsx(qt,{size:12,style:{transform:"rotate(90deg)",marginRight:4}}),"Back"]}),t.jsxs("div",{className:"model-submenu-header",children:[fe==="plan"&&"Plan Model",fe==="executor"&&"Executor Model",fe==="validator"&&"Reviewer Model"]}),t.jsx(Ln,{models:pe,value:fe==="plan"?Ve:fe==="executor"?xe:st,onChange:fe==="plan"?Nn:fe==="executor"?gn:nn,placeholder:"Using default",disabled:V,id:`model-${fe}-select`,label:`${fe} model`,favoriteProviders:Mt,onToggleFavorite:_n,favoriteModels:Kt,onToggleModelFavorite:jn}),Z&&t.jsxs("div",{className:"model-submenu-error",children:[t.jsx("span",{children:Z}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:Nt,children:"Retry"})]})]})}),tt)]}),t.jsx("input",{ref:M,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:re=>{$t(re.target.files),re.currentTarget.value=""},"data-testid":"quick-entry-file-input"}),t.jsx("div",{className:"quick-entry-hint",children:"Enter to create · Esc to cancel"})]})}function Xw(e){const n=e.replace(/\/+$/,"").split("/");return n[n.length-1]||e}function Zw(e){const n=new Map(e.map(l=>[l.id,l])),s=[],i=new Set,r=new Set;function o(l){if(i.has(l)||r.has(l))return;r.add(l);const c=n.get(l);if(c)for(const u of c.dependencies||[])n.has(u)&&o(u);r.delete(l),i.add(l),s.push(l)}for(const l of e)o(l.id);return s}function eN(e,n,s){const i=e.filter(f=>f.worktree),r=e.filter(f=>!f.worktree),o=new Map;for(const f of i){const x=f.worktree,v=o.get(x)||[];v.push(f),o.set(x,v)}const l=new Map(n.map(f=>[f.id,f])),u=n.filter(f=>f.column==="todo").filter(f=>!f.paused&&(f.dependencies||[]).every(x=>{const v=l.get(x);return v&&(v.column==="done"||v.column==="in-review"||v.column==="archived")})),m=Zw(u).map(f=>l.get(f)).filter(f=>f!==void 0&&u.includes(f)),h=[],g=Array.from(o.keys());for(const f of g)h.push({label:Xw(f),activeTasks:o.get(f),queuedTasks:[]});r.length>0&&h.push({label:"Unassigned",activeTasks:r,queuedTasks:[]});const p=m.slice(0,s);return p.length>0&&h.push({label:"Up Next",activeTasks:[],queuedTasks:p}),h}const gu=100,al=50,xu=25;function tN({column:e,tasks:n,projectId:s,maxConcurrent:i,onMoveTask:r,onPauseTask:o,onOpenDetail:l,addToast:c,onQuickCreate:u,onNewTask:d,autoMerge:m,onToggleAutoMerge:h,globalPaused:g,onUpdateTask:p,onArchiveTask:f,onUnarchiveTask:x,onDeleteTask:v,onArchiveAllDone:b,collapsed:y,onToggleCollapse:S,allTasks:k,availableModels:M,onPlanningMode:w,onSubtaskBreakdown:_,onOpenDetailWithTab:N,favoriteProviders:L,favoriteModels:T,onToggleFavorite:I,onToggleModelFavorite:z,isSearchActive:K,taskStuckTimeoutMs:P,onOpenMission:E,lastFetchTimeMs:R,workflowStepNameLookup:B}){const[G,X]=a.useState(!1),[C,$]=a.useState(al),[A,j]=a.useState(!1),[J,W]=a.useState(!1),[oe,he]=a.useState(!1),[se,fe]=a.useState(!1),U=a.useRef(null),Ne=Gj(n.length),{confirm:ee}=Is();a.useEffect(()=>{if(!A)return;function ce($e){U.current?.contains($e.target)||j(!1)}function le($e){$e.key==="Escape"&&j(!1)}return document.addEventListener("mousedown",ce),document.addEventListener("keydown",le),()=>{document.removeEventListener("mousedown",ce),document.removeEventListener("keydown",le)}},[A]);const ve=e==="archived",ue=ve&&y,ye=!ve&&!K&&e!=="in-progress"&&n.length>gu;a.useEffect(()=>{$(ce=>e==="in-progress"||ve||n.length<=gu?al:Math.min(Math.max(ce,al),n.length))},[e,ve,n.length]);const ie=a.useCallback(ce=>{ve||(ce.preventDefault(),ce.dataTransfer.dropEffect="move",X(!0))},[ve]),Me=a.useCallback(ce=>{ce.currentTarget.contains(ce.relatedTarget)||X(!1)},[]),ze=a.useCallback(async ce=>{ce.preventDefault(),X(!1);const le=ce.dataTransfer.getData("text/plain");if(!le)return;const $e=n.find(at=>at.id===le);if(!($e&&$e.column===e))try{await r(le,e)}catch(at){c(je(at),"error")}},[e,r,c,n]),Be=a.useMemo(()=>e!=="in-progress"?[]:eN(n,n,i),[e,n,i]),Je=a.useMemo(()=>ye?n.slice(0,C):n,[ye,n,C]),Ye=Math.max(0,n.length-Je.length),Ge=a.useCallback(()=>{$(ce=>Math.min(ce+xu,n.length))},[n.length]),it=a.useCallback(async()=>{if(j(!1),!(n.length===0||!await ee({title:"Replan All Tasks",message:`Move all ${n.length} todo task${n.length===1?"":"s"} back to planning to be replanned?`}))){W(!0);try{const le=await Promise.allSettled(n.map(tt=>r(tt.id,"triage"))),$e=le.filter(tt=>tt.status==="rejected").length,at=le.length-$e;$e===0?c(`Moved ${at} task${at===1?"":"s"} to planning for replanning`,"success"):c(`Moved ${at} of ${le.length} tasks; ${$e} failed`,"error")}finally{W(!1)}}},[n,r,c,ee]),_e=a.useMemo(()=>n.filter(ce=>!ce.paused),[n]),Fe=_e.length,ae=e==="todo"||e==="in-progress"||e==="in-review",be=J||oe||se,ne=a.useCallback(async()=>{if(!(!o||(j(!1),Fe===0)||!await ee({title:"Stop All Tasks",message:`Stop all ${Fe} ${$n[e].toLowerCase()} task${Fe===1?"":"s"}?`,danger:!0}))){he(!0);try{const le=await Promise.allSettled(_e.map(tt=>o(tt.id))),$e=le.filter(tt=>tt.status==="rejected").length,at=le.length-$e;$e===0?c(`Stopped ${at} task${at===1?"":"s"}`,"success"):c(`Stopped ${at} of ${le.length} tasks; ${$e} failed`,"error")}finally{he(!1)}}},[o,Fe,e,_e,c,ee]),Ie=a.useCallback(async()=>{if(j(!1),!(n.length===0||!await ee({title:"Move All to Todo",message:`Move all ${n.length} ${$n[e].toLowerCase()} task${n.length===1?"":"s"} to Todo?`}))){fe(!0);try{const le=await Promise.allSettled(n.map(tt=>r(tt.id,"todo"))),$e=le.filter(tt=>tt.status==="rejected").length,at=le.length-$e;$e===0?c(`Moved ${at} task${at===1?"":"s"} to Todo`,"success"):c(`Moved ${at} of ${le.length} tasks to Todo; ${$e} failed`,"error")}finally{fe(!1)}}},[n,e,r,c,ee]),Pe=a.useCallback(async()=>{if(!(!b||n.length===0||!await ee({title:"Archive All Done",message:`Archive all ${n.length} done tasks?`,danger:!0})))try{const le=await b();c(`Archived ${le.length} tasks`,"success")}catch(le){c(je(le)||"Failed to archive tasks","error")}},[b,n.length,c,ee]);return t.jsxs("div",{className:`column${G?" drag-over":""}${ve?" column-archived":""}${ue?" column-collapsed":""}`,"data-column":e,onDragOver:ie,onDragLeave:Me,onDrop:ze,children:[t.jsxs("div",{className:"column-header",children:[t.jsx("div",{className:`column-dot dot-${e}`}),t.jsx("h2",{children:$n[e]}),t.jsx("span",{className:`column-count${Ne?" count-flash":""}`,children:n.length}),e==="in-review"&&h&&t.jsxs("label",{className:"auto-merge-toggle",title:m?"Auto-merge enabled":"Auto-merge disabled",children:[t.jsx("input",{type:"checkbox",checked:!!m,onChange:h}),t.jsx("span",{className:"toggle-slider"}),t.jsx("span",{className:"toggle-label",children:"Auto-merge"})]}),d&&t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:d,children:"+ New Task"}),e==="done"&&b&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:Pe,disabled:n.length===0,title:"Archive all done tasks","aria-label":"Archive all done tasks",children:t.jsx(vo,{size:16})}),ve&&S&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:S,title:y?"Expand archived tasks":"Collapse archived tasks","aria-label":y?"Expand archived tasks":"Collapse archived tasks",children:y?t.jsx(qt,{size:16}):t.jsx(ni,{size:16})}),ae&&t.jsxs("div",{className:"column-menu",ref:U,children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>j(ce=>!ce),"aria-haspopup":"menu","aria-expanded":A,"aria-label":`${$n[e]} column actions`,title:"Column actions",disabled:be,children:t.jsx(Kg,{size:16})}),A&&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 it(),disabled:n.length===0||J,children:["Replan All",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Planning"]})]}),(e==="in-progress"||e==="in-review")&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void ne(),disabled:Fe===0||oe||!o,children:["Stop All",t.jsx("span",{className:"column-menu-item-hint",children:n.length===0?"No tasks in this column":Fe===0?"All tasks are already paused":`Pause ${Fe} active task${Fe===1?"":"s"}`})]}),t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Ie(),disabled:n.length===0||se,children:["Move All to Todo",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Todo"]})]})]})]})]})]}),!ue&&t.jsx("p",{className:"column-desc",children:Wj[e]}),!ue&&t.jsxs("div",{className:"column-body",children:[e==="triage"&&u&&t.jsx(pp,{onCreate:u,addToast:c,tasks:k??[],availableModels:M,onPlanningMode:w,onSubtaskBreakdown:_,projectId:s,autoExpand:!1,favoriteProviders:L,favoriteModels:T,onToggleFavorite:I,onToggleModelFavorite:z}),e==="in-progress"?Be.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):Be.map(ce=>t.jsx(hp,{label:ce.label,activeTasks:ce.activeTasks,queuedTasks:ce.queuedTasks,projectId:s,onOpenDetail:l,addToast:c,globalPaused:g,onUpdateTask:p,onOpenDetailWithTab:N,taskStuckTimeoutMs:P,onOpenMission:E,lastFetchTimeMs:R,workflowStepNameLookup:B},ce.label)):n.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):t.jsxs(t.Fragment,{children:[Je.map(ce=>t.jsx(co,{task:ce,projectId:s,onOpenDetail:l,addToast:c,globalPaused:g,onUpdateTask:p,onArchiveTask:f,onUnarchiveTask:x,onDeleteTask:v,onOpenDetailWithTab:N,taskStuckTimeoutMs:P,onOpenMission:E,onMoveTask:r,lastFetchTimeMs:R,workflowStepNameLookup:B},ce.id)),ye&&Ye>0&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ge,children:["Load ",Math.min(xu,Ye)," more (",Ye," remaining)"]})]}),t.jsx(Ao,{slotId:"board-column-footer",projectId:s})]})]})}const fp=a.memo(tN);fp.displayName="Column";function nN(e){return[...e].sort((n,s)=>n.columnMovedAt&&s.columnMovedAt?s.columnMovedAt.localeCompare(n.columnMovedAt):n.columnMovedAt&&!s.columnMovedAt?-1:!n.columnMovedAt&&s.columnMovedAt?1:n.createdAt.localeCompare(s.createdAt))}function sN(e,n){return e.length!==n.length?!1:e.every((s,i)=>s===n[i])}const bu=new Map;function iN(e,n){if(e.size!==n.size)return!1;for(const[s,i]of e)if(n.get(s)!==i)return!1;return!0}function aN({tasks:e,projectId:n,maxConcurrent:s,onMoveTask:i,onPauseTask:r,onOpenDetail:o,addToast:l,onQuickCreate:c,onNewTask:u,autoMerge:d,onToggleAutoMerge:m,globalPaused:h,onUpdateTask:g,onArchiveTask:p,onUnarchiveTask:f,onDeleteTask:x,onArchiveAllDone:v,onLoadArchivedTasks:b,searchQuery:y="",availableModels:S,onPlanningMode:k,onSubtaskBreakdown:M,onOpenDetailWithTab:w,favoriteProviders:_,favoriteModels:N,onToggleFavorite:L,onToggleModelFavorite:T,taskStuckTimeoutMs:I,onOpenMission:z,lastFetchTimeMs:K}){const[P,E]=a.useState(!0),R=a.useRef(!1),{fetchBatch:B}=mw(n),G=a.useRef(null),[X,C]=a.useState(bu),$=y.trim()!=="",A=a.useRef({triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]}),j=a.useCallback(()=>{E(oe=>{const he=!oe;return!he&&!R.current&&b&&(R.current=!0,b()),he})},[b]),J=a.useMemo(()=>{const oe=Object.fromEntries(_i.map(fe=>[fe,[]]));for(const fe of e)oe[fe.column].push(fe);const he=A.current,se={};for(const fe of _i){const U=nN(oe[fe]);se[fe]=sN(he[fe],U)?he[fe]:U}return A.current=se,se},[e]);a.useEffect(()=>{let oe=!1;return Mo(n).then(he=>{if(oe)return;const se=new Map(he.map(fe=>[fe.id,fe.name]));C(fe=>iN(fe,se)?fe:se)}).catch(()=>{oe||C(he=>he.size===0?he:bu)}),()=>{oe=!0}},[n]);const W=a.useMemo(()=>e.filter(oe=>oe.prInfo||oe.issueInfo).map(oe=>oe.id),[e]);return a.useEffect(()=>{if(W.length!==0)return G.current&&clearTimeout(G.current),G.current=setTimeout(()=>{const oe=[];for(let he=0;he<W.length;he+=50)oe.push(W.slice(he,he+50));oe.forEach(he=>{B(he)})},500),()=>{G.current&&clearTimeout(G.current)}},[W,B]),t.jsx(t.Fragment,{children:t.jsx("main",{className:"board",id:"board",children:_i.map(oe=>t.jsx(fp,{column:oe,tasks:J[oe],projectId:n,maxConcurrent:s,onMoveTask:i,onPauseTask:r,onOpenDetail:o,addToast:l,globalPaused:h,onUpdateTask:g,onArchiveTask:p,onUnarchiveTask:f,onDeleteTask:x,allTasks:e,availableModels:S,onOpenDetailWithTab:w,favoriteProviders:_,favoriteModels:N,onToggleFavorite:L,onToggleModelFavorite:T,isSearchActive:$,taskStuckTimeoutMs:I,onOpenMission:z,lastFetchTimeMs:K,workflowStepNameLookup:X,...oe==="triage"?{onQuickCreate:c,onNewTask:u,onPlanningMode:k,onSubtaskBreakdown:M}:{},...oe==="in-review"?{autoMerge:d,onToggleAutoMerge:m}:{},...oe==="done"?{onArchiveAllDone:v}:{},...oe==="archived"?{collapsed:P,onToggleCollapse:j}:{}},oe))})})}const Ma={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-secondary)"},vu=new Set(["planning","researching","executing","finalizing","merging"]),xc=["id","title","status","column","dependencies","progress"];function yu(e){try{const n=zn("kb-dashboard-list-columns",e);if(n){const i=JSON.parse(n).filter(r=>xc.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set(xc)}function ku(e){try{const n=zn("kb-dashboard-hide-done",e);if(n!==null)return n==="true"}catch{}return!1}function ju(e){try{const n=zn("kb-dashboard-list-collapsed",e);if(n){const i=JSON.parse(n).filter(r=>_i.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set}function wu(e){try{const n=zn("kb-dashboard-selected-tasks",e);if(n){const s=JSON.parse(n);return new Set(s)}}catch{}return new Set}function rN(e){return e.status==="executing"||e.column==="in-progress"}function Nu(e){const n=up(e);return n.total===0||!rN(e)?{label:"-",percent:0,hasProgress:!1}:{label:`${n.completed}/${n.total}`,percent:n.completed/n.total*100,hasProgress:!0}}function oN({tasks:e,onMoveTask:n,onOpenDetail:s,addToast:i,globalPaused:r,onNewTask:o,onQuickCreate:l,availableModels:c,favoriteProviders:u=[],favoriteModels:d=[],onToggleFavorite:m,onToggleModelFavorite:h,onPlanningMode:g,onSubtaskBreakdown:p,onTasksUpdated:f,projectId:x,projectName:v,taskStuckTimeoutMs:b,searchQuery:y="",lastFetchTimeMs:S}){const[k,M]=a.useState("id"),[w,_]=a.useState("desc"),[N,L]=a.useState(null),[T,I]=a.useState(null),[z,K]=a.useState(null),E=br()==="mobile",[R,B]=a.useState(()=>yu(x)),[G,X]=a.useState(()=>ku(x)),[C,$]=a.useState(()=>ju(x));a.useEffect(()=>{typeof window<"u"&&as("kb-dashboard-list-columns",JSON.stringify([...R]),x)},[x,R]),a.useEffect(()=>{typeof window<"u"&&as("kb-dashboard-hide-done",G.toString(),x)},[G,x]),a.useEffect(()=>{typeof window<"u"&&as("kb-dashboard-list-collapsed",JSON.stringify([...C]),x)},[C,x]);const[A,j]=a.useState(!1),J=a.useRef(null),[W,oe]=a.useState(()=>wu(x));a.useEffect(()=>{B(yu(x)),X(ku(x)),$(ju(x)),oe(wu(x))},[x]),a.useEffect(()=>{typeof window<"u"&&as("kb-dashboard-selected-tasks",JSON.stringify([...W]),x)},[x,W]);const he=a.useCallback(V=>{oe(de=>{const Z=new Set(de);return Z.has(V)?Z.delete(V):Z.add(V),Z})},[]),se=a.useCallback(()=>{oe(new Set)},[]),fe=a.useCallback(V=>{B(de=>{const Z=new Set(de);return Z.has(V)?Z.size>1&&Z.delete(V):Z.add(V),Z})},[]);a.useEffect(()=>{if(!A)return;const V=Z=>{J.current&&!J.current.contains(Z.target)&&j(!1)},de=Z=>{Z.key==="Escape"&&j(!1)};return document.addEventListener("mousedown",V),document.addEventListener("keydown",de),()=>{document.removeEventListener("mousedown",V),document.removeEventListener("keydown",de)}},[A]);const U={id:"ID",title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},Ne=a.useCallback(V=>{k===V?_(de=>de==="asc"?"desc":"asc"):(M(V),_("asc"))},[k]),ee=a.useCallback(V=>{K(de=>de===V?null:V)},[]),ve=a.useCallback(V=>{$(de=>{const Z=new Set(de);return Z.has(V)?Z.delete(V):Z.add(V),Z})},[]),ue=a.useCallback(()=>{K(null)},[]),ye=a.useMemo(()=>{let V=y?e.filter(pe=>pe.id.toLowerCase().includes(y.toLowerCase())||pe.title&&pe.title.toLowerCase().includes(y.toLowerCase())||pe.description.toLowerCase().includes(y.toLowerCase())):[...e];G&&!z&&(V=V.filter(pe=>pe.column!=="done"&&pe.column!=="archived"));const Z=[...z?V.filter(pe=>pe.column===z):V].sort((pe,Te)=>{let Qe=0;switch(k){case"id":Qe=pe.id.localeCompare(Te.id);break;case"title":Qe=(pe.title||pe.description).localeCompare(Te.title||Te.description);break;case"status":Qe=(pe.status||"").localeCompare(Te.status||"");break;case"column":Qe=pe.column.localeCompare(Te.column);break}return w==="asc"?Qe:-Qe}),we={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};return Z.forEach(pe=>we[pe.column].push(pe)),we},[e,y,k,w,G,z]),ie=a.useMemo(()=>Object.values(ye).reduce((V,de)=>V+de.length,0),[ye]),Me=a.useMemo(()=>e.filter(V=>V.column==="done"||V.column==="archived").length,[e]),ze=a.useMemo(()=>G?Me:0,[G,Me]),Be=a.useCallback(()=>{const V=Object.values(ye).flat().filter(de=>de.column!=="archived").map(de=>de.id);oe(de=>{if(V.every(we=>de.has(we))){const we=new Set(de);return V.forEach(pe=>we.delete(pe)),we}else return new Set([...de,...V])})},[ye]),Je=a.useMemo(()=>{const V=Object.values(ye).flat().filter(de=>de.column!=="archived");return V.length===0?!1:V.every(de=>W.has(de.id))},[ye,W]),Ye=a.useMemo(()=>{const V=Object.values(ye).flat().filter(Z=>Z.column!=="archived");if(V.length===0)return!1;const de=V.filter(Z=>W.has(Z.id)).length;return de>0&&de<V.length},[ye,W]),[Ge,it]=a.useState("__no_change__"),[_e,Fe]=a.useState("__no_change__"),[ae,be]=a.useState(!1),ne=a.useCallback(async()=>{if(W.size===0)return;const V=Array.from(W).filter(Z=>{const we=e.find(pe=>pe.id===Z);return we&&we.column!=="archived"});if(V.length===0){i("No valid tasks to update (archived tasks cannot be modified)","error");return}const de={taskIds:V};if(Ge!=="__no_change__")if(Ge==="")de.modelProvider=null,de.modelId=null;else{const Z=Ge.indexOf("/");Z!==-1&&(de.modelProvider=Ge.slice(0,Z),de.modelId=Ge.slice(Z+1))}if(_e!=="__no_change__")if(_e==="")de.validatorModelProvider=null,de.validatorModelId=null;else{const Z=_e.indexOf("/");Z!==-1&&(de.validatorModelProvider=_e.slice(0,Z),de.validatorModelId=_e.slice(Z+1))}if(Object.keys(de).length===1){i("No changes to apply","info");return}be(!0);try{const Z=await dv(de.taskIds,de.modelProvider,de.modelId,de.validatorModelProvider,de.validatorModelId,void 0,void 0,x);f&&Z.updated.length>0&&f(Z.updated),i(`Updated ${Z.count} task${Z.count===1?"":"s"}`,"success"),se(),it("__no_change__"),Fe("__no_change__")}catch(Z){i(je(Z)||"Failed to update models","error")}finally{be(!1)}},[W,e,Ge,_e,x,i,se,f]),Ie=a.useCallback(V=>{s(V)},[s]),Pe=a.useCallback((V,de)=>{if(de.paused){V.preventDefault();return}V.dataTransfer.setData("text/plain",de.id),V.dataTransfer.effectAllowed="move",L(de.id)},[]),ce=a.useCallback(()=>{L(null),I(null)},[]),le=a.useCallback((V,de)=>{V.preventDefault(),V.dataTransfer.dropEffect="move",I(de)},[]),$e=a.useCallback(()=>{I(null)},[]),at=a.useCallback(async(V,de)=>{V.preventDefault(),I(null);const Z=V.dataTransfer.getData("text/plain");if(Z){if(de==="archived"){i("Tasks can only be archived via the archive button","error");return}try{await n(Z,de)}catch(we){i(je(we),"error")}}},[n,i]),tt=V=>k!==V?t.jsx(_h,{size:14,className:"sort-icon"}):w==="asc"?t.jsx(Mi,{size:14,className:"sort-icon active"}):t.jsx(cr,{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:J,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>j(V=>!V),"aria-expanded":A,"aria-haspopup":"menu",children:[t.jsx(Og,{size:14}),"Columns"]}),A&&t.jsx("div",{className:"list-column-dropdown",role:"menu",children:xc.map(V=>{const de=R.has(V),Z=de&&R.size===1;return t.jsxs("label",{className:`list-column-dropdown-item${Z?" disabled":""}`,role:"menuitem",title:Z?"At least one column must be visible":"",children:[t.jsx("input",{type:"checkbox",checked:de,onChange:()=>fe(V),disabled:Z}),t.jsx("span",{children:U[V]})]},V)})})]}),t.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>X(V=>!V),"aria-pressed":G,title:G?"Show done tasks":"Hide done tasks",children:[G?t.jsx(sa,{size:14}):t.jsx(nc,{size:14}),G?"Show Done":"Hide Done"]}),t.jsxs("div",{className:"list-stats",children:[z?`${ie} of ${e.length} tasks in ${$n[z]}`:`${ie} of ${e.length} tasks`,ze>0&&!z&&t.jsxs("span",{className:"list-stats-hidden",children:[" (",ze," hidden)"]}),z&&t.jsx("button",{className:"btn btn-sm",onClick:ue,"aria-label":"Clear column filter",style:{marginLeft:"8px"},children:"Clear"})]}),W.size>0&&t.jsxs("div",{className:"list-selection-stats",children:[t.jsxs("span",{className:"selection-count",children:[W.size," selected"]}),t.jsx("button",{className:"btn btn-sm btn-link",onClick:se,children:"Clear"})]}),W.size>0&&c&&c.length>0&&t.jsxs("div",{className:"bulk-edit-toolbar",children:[t.jsx("span",{className:"bulk-edit-label",children:"Bulk Edit Models:"}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx(Ln,{models:c,value:Ge,onChange:it,label:"Executor Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:u,onToggleFavorite:m,favoriteModels:d,onToggleModelFavorite:h})}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx(Ln,{models:c,value:_e,onChange:Fe,label:"Reviewer Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:u,onToggleFavorite:m,favoriteModels:d,onToggleModelFavorite:h})}),t.jsx("button",{className:"btn btn-primary btn-sm bulk-edit-apply-btn",onClick:ne,disabled:ae||Ge==="__no_change__"&&_e==="__no_change__",children:ae?"Applying...":"Apply"})]}),o?t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:o,children:"+ New Task"}):null]}),t.jsx("div",{className:"list-drop-zones",children:_i.map(V=>{const de=e.filter(Te=>Te.column===V).length,Z=V==="done"||V==="archived",we=G&&Z?0:de,pe=G&&Z&&de>0;return t.jsxs("div",{className:`list-drop-zone${T===V?" drag-over":""}${z===V?" active":""}`,onClick:()=>ee(V),onDragOver:Te=>le(Te,V),onDragLeave:$e,onDrop:Te=>at(Te,V),"data-column":V,children:[t.jsx("span",{className:"drop-zone-dot",style:{background:Ma[V]}}),t.jsx("span",{className:"drop-zone-label",children:$n[V]}),t.jsx("span",{className:"drop-zone-count",children:pe?`${we} of ${de}`:de})]},V)})}),t.jsxs("div",{className:"list-table-container",children:[t.jsx("div",{className:"list-quick-entry-above-table",children:t.jsx(pp,{onCreate:l??(async()=>i("Task creation not available","error")),addToast:i,tasks:e,availableModels:c,onPlanningMode:g,onSubtaskBreakdown:p,projectId:x,autoExpand:!1,favoriteProviders:u,favoriteModels:d,onToggleFavorite:m,onToggleModelFavorite:h})}),ie===0?t.jsx("div",{className:"list-empty",children:y?"No tasks match your filter":"No tasks yet"}):E?t.jsx("div",{className:"list-cards",children:_i.map(V=>{if(z&&V!==z||G&&(V==="done"||V==="archived")&&!z)return null;const de=ye[V],Z=de.length===0;if(y&&Z)return null;const we=C.has(V);return t.jsxs(a.Fragment,{children:[t.jsxs("div",{className:`list-card-section-header${we?" list-section-header--collapsed":""}`,onClick:()=>ve(V),"aria-expanded":!we,role:"button",tabIndex:0,onKeyDown:pe=>{(pe.key==="Enter"||pe.key===" ")&&(pe.preventDefault(),ve(V))},children:[t.jsx(mn,{size:14,className:`list-section-chevron${we?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${V}`}),t.jsx("span",{className:"list-section-title",children:$n[V]}),t.jsx("span",{className:"list-section-count",children:de.length})]}),!we&&t.jsx(t.Fragment,{children:Z?t.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):de.map(pe=>{const Te=pe.status==="failed",Qe=pe.paused===!0,Ee=lo(pe,b,S),Re=!r&&!Te&&!Qe&&!Ee&&(pe.column==="in-progress"||vu.has(pe.status)),Le=typeof pe.status=="string"&&pe.status.trim().length>0,ct=!!(pe.dependencies&&pe.dependencies.length>0),Se=Nu(pe),mt=Se.hasProgress,gt=W.size>0;return t.jsxs("div",{className:`list-card${Re?" agent-active":""}${gt?" list-card--selectable":""}`,onClick:()=>Ie(pe),"data-id":pe.id,children:[gt&&t.jsx("label",{className:"list-card-checkbox",onClick:wt=>wt.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:W.has(pe.id),onChange:wt=>{wt.stopPropagation(),he(pe.id)},onClick:wt=>wt.stopPropagation(),disabled:pe.column==="archived","aria-label":`Select ${pe.id}`})}),t.jsxs("div",{className:"list-card-row",children:[t.jsx("span",{className:"list-card-id",children:pe.id}),pe.executionMode==="fast"&&t.jsx("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",children:"Fast"}),t.jsx("span",{className:"list-card-spacer"}),Ee?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):Le?t.jsx("span",{className:`list-status-badge list-status-badge--${pe.column}${Te?" failed":""}${Re?" pulsing":""}`,children:pe.status}):null]}),t.jsx("div",{className:"list-card-row",children:t.jsx("div",{className:"list-card-title",children:pe.title||pe.description})}),(ct||mt)&&t.jsxs("div",{className:"list-card-row list-card-meta",children:[ct&&t.jsxs("span",{className:"list-dep-badge",title:pe.dependencies.join(", "),children:[t.jsx(ia,{size:12})," ",pe.dependencies.length]}),mt&&t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${Se.percent}%`,backgroundColor:Ma[pe.column]}})}),t.jsx("span",{className:"list-progress-label",children:Se.label})]})]})]},pe.id)})})]},V)})}):t.jsxs("table",{className:"list-table",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{className:"list-header-cell list-header-checkbox",children:t.jsx("input",{type:"checkbox",checked:Je,ref:V=>{V&&(V.indeterminate=Ye)},onChange:Be,"aria-label":"Select all visible tasks"})}),R.has("id")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Ne("id"),children:["ID ",tt("id")]}),R.has("title")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Ne("title"),children:["Title ",tt("title")]}),R.has("status")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Ne("status"),children:["Status ",tt("status")]}),R.has("column")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Ne("column"),children:["Column ",tt("column")]}),R.has("dependencies")&&t.jsx("th",{className:"list-header-cell",children:"Dependencies"}),R.has("progress")&&t.jsx("th",{className:"list-header-cell",children:"Progress"})]})}),t.jsx("tbody",{children:_i.map(V=>{if(z&&V!==z||G&&(V==="done"||V==="archived")&&!z)return null;const de=ye[V],Z=de.length===0;if(y&&Z)return null;const we=C.has(V);return t.jsxs(a.Fragment,{children:[t.jsx("tr",{className:`list-section-header${we?" list-section-header--collapsed":""}`,onClick:()=>ve(V),"aria-expanded":!we,children:t.jsxs("th",{colSpan:R.size+1,className:"list-section-cell",children:[t.jsx(mn,{size:14,className:`list-section-chevron${we?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${V}`}),t.jsx("span",{className:"list-section-title",children:$n[V]}),t.jsx("span",{className:"list-section-count",children:de.length})]})}),!we&&t.jsx(t.Fragment,{children:Z?t.jsx("tr",{className:"list-section-empty",children:t.jsx("td",{colSpan:R.size+1,className:"list-empty-cell",children:"No tasks"})}):de.map(pe=>{const Te=pe.status==="failed",Qe=pe.paused===!0,Ee=lo(pe,b,S),Re=!r&&!Te&&!Qe&&!Ee&&(pe.column==="in-progress"||vu.has(pe.status)),Le=N===pe.id;return t.jsxs("tr",{className:`list-row${Te?" failed":""}${Qe?" paused":""}${Ee?" stuck":""}${Re?" agent-active":""}${Le?" dragging":""}`,onClick:()=>Ie(pe),draggable:!Qe,onDragStart:ct=>Pe(ct,pe),onDragEnd:ce,"data-id":pe.id,children:[t.jsx("td",{className:"list-cell list-cell-checkbox",children:t.jsx("input",{type:"checkbox",checked:W.has(pe.id),onChange:ct=>{ct.stopPropagation(),he(pe.id)},onClick:ct=>ct.stopPropagation(),disabled:pe.column==="archived","aria-label":`Select ${pe.id}`})}),R.has("id")&&t.jsx("td",{className:"list-cell list-cell-id",children:pe.id}),R.has("title")&&t.jsx("td",{className:"list-cell list-cell-title",children:t.jsxs("div",{className:"list-title-content",children:[pe.executionMode==="fast"&&t.jsx("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",children:"Fast"}),t.jsx("span",{className:"list-title-text",children:pe.title||pe.description})]})}),R.has("status")&&t.jsx("td",{className:"list-cell",children:Ee?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):pe.status?t.jsx("span",{className:`list-status-badge list-status-badge--${pe.column}${Te?" failed":""}${Re?" pulsing":""}`,children:pe.status}):t.jsx("span",{className:"list-status-badge",children:"-"})}),R.has("column")&&t.jsx("td",{className:"list-cell",children:t.jsx("span",{className:"list-column-badge",style:{background:`${Ma[pe.column]}20`,color:Ma[pe.column]},children:$n[pe.column]})}),R.has("dependencies")&&t.jsx("td",{className:"list-cell list-cell-deps",children:pe.dependencies&&pe.dependencies.length>0?t.jsxs("span",{className:"list-dep-badge",title:pe.dependencies.join(", "),children:[t.jsx(ia,{size:12})," ",pe.dependencies.length]}):"-"}),R.has("progress")&&t.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const ct=Nu(pe);return ct.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:`${ct.percent}%`,backgroundColor:Ma[pe.column]}})}),t.jsx("span",{className:"list-progress-label",children:ct.label})]}):"-"})()})]},pe.id)})})]},V)})})]})]})]})}const lN={active:{label:"Active",color:"var(--success)",icon:fn},paused:{label:"Paused",color:"var(--warning)",icon:qs},errored:{label:"Error",color:"var(--color-error)",icon:Zn},initializing:{label:"Initializing",color:"var(--info)",icon:rt}};function cN(e){if(!e)return"Never";const n=new Date(e),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),o=Math.floor(i/36e5),l=Math.floor(i/864e5);return r<1?"Just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString()}function dN(e,n=40){if(e.length<=n)return e;const s=e.slice(0,Math.floor(n/2)-2),i=e.slice(-Math.floor(n/2)+2);return`${s}...${i}`}function uN(e,n){if(e.project.id!==n.project.id||e.project.status!==n.project.status||e.project.name!==n.project.name||e.project.path!==n.project.path||e.project.lastActivityAt!==n.project.lastActivityAt||e.isLoading!==n.isLoading)return!1;const s=e.health,i=n.health;if(!s&&!i)return!0;if(!s||!i||s.activeTaskCount!==i.activeTaskCount||s.inFlightAgentCount!==i.inFlightAgentCount||s.totalTasksCompleted!==i.totalTasksCompleted||s.totalTasksFailed!==i.totalTasksFailed||s.status!==i.status)return!1;const r=e.node,o=n.node;return!r&&!o?e.nodeNameFallback===n.nodeNameFallback:!r||!o?!1:r.id===o.id&&r.name===o.name&&r.status===o.status&&r.type===o.type}function mN({project:e,health:n,onSelect:s,onPause:i,onResume:r,onRemove:o,node:l,nodeNameFallback:c,isLoading:u=!1}){const[d,m]=a.useState(!1),h=lN[e.status],g=h.icon,p=a.useCallback(()=>{s(e)},[s,e]),f=a.useCallback(k=>{k.stopPropagation(),i(e)},[i,e]),x=a.useCallback(k=>{k.stopPropagation(),r(e)},[r,e]),v=a.useCallback(k=>{if(k.stopPropagation(),!d){m(!0);return}o(e),m(!1)},[d,o,e]),b=e.status==="paused",y=e.status==="errored",S=e.status==="initializing";return t.jsxs("div",{className:`project-card ${u?"project-card-loading":""} ${y?"project-card-errored":""}`,onClick:p,"data-project-id":e.id,role:"button",tabIndex:0,onKeyDown:k=>{(k.key==="Enter"||k.key===" ")&&(k.preventDefault(),p())},children:[t.jsxs("div",{className:"project-card-header",children:[t.jsx("div",{className:"project-card-icon",children:t.jsx(Dn,{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:dN(e.path)})]}),t.jsxs("div",{className:"project-card-status-badge",style:{color:h.color,borderColor:h.color},children:[t.jsx(g,{size:12,className:S?"animate-spin":""}),t.jsx("span",{children:h.label})]})]}),t.jsxs("div",{className:"project-card-health",children:[n&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.activeTaskCount}),t.jsx("span",{className:"project-card-metric-label",children:"Active Tasks"})]}),t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.inFlightAgentCount}),t.jsx("span",{className:"project-card-metric-label",children:"Agents"})]}),t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.totalTasksCompleted}),t.jsx("span",{className:"project-card-metric-label",children:"Completed"})]})]}),!n&&t.jsx("div",{className:"project-card-metric project-card-metric-empty",children:t.jsx("span",{className:"project-card-metric-label",children:"No health data available"})})]}),t.jsxs("div",{className:"project-card-footer",children:[t.jsxs("div",{className:"project-card-activity",children:[t.jsx("span",{className:"project-card-activity-label",children:"Last activity:"}),t.jsx("span",{className:"project-card-activity-time",children:cN(e.lastActivityAt||n?.lastActivityAt)})]}),t.jsxs("div",{className:"project-card-actions",children:[b?t.jsxs("button",{className:"project-card-action project-card-action-resume",onClick:x,disabled:u,title:"Resume project","aria-label":"Resume project",children:[t.jsx(fn,{size:14}),t.jsx("span",{children:"Resume"})]}):t.jsxs("button",{className:"project-card-action project-card-action-pause",onClick:f,disabled:u||S,title:S?"Cannot pause while initializing":"Pause project","aria-label":"Pause project",children:[t.jsx(qs,{size:14}),t.jsx("span",{children:"Pause"})]}),t.jsxs("button",{className:"project-card-action project-card-action-open",onClick:p,disabled:u,title:"Open project","aria-label":"Open project",children:[t.jsx(dr,{size:14}),t.jsx("span",{children:"Open"})]}),t.jsxs("button",{className:`project-card-action project-card-action-remove ${d?"is-armed":""}`,onClick:v,disabled:u,title:d?"Confirm remove":"Remove project","aria-label":d?"Confirm remove project":"Remove project",children:[t.jsx(Jt,{size:14}),t.jsx("span",{children:d?"Confirm":""})]})]})]})]})}const hN=a.memo(mN,uN);function pN(){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(Dn,{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(Es,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(un,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(Zn,{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 fN=1e4,Su=5;function gN(e){const[n,s]=a.useState({}),[i,r]=a.useState(!0),[o,l]=a.useState(null),c=a.useRef(null),u=a.useRef(null),d=a.useRef(!1),m=a.useCallback(async()=>{if(e.length===0){s({}),d.current||(d.current=!0),r(!1);return}u.current&&u.current.abort(),u.current=new AbortController,!d.current&&r(!0),l(null);try{const p={};for(let f=0;f<e.length;f+=Su){const x=e.slice(f,f+Su),v=await Promise.allSettled(x.map(async b=>{try{return await qd(b)}catch{return null}}));if(x.forEach((b,y)=>{const S=v[y];p[b]=S.status==="fulfilled"?S.value:null}),u.current?.signal.aborted)return}s(p),d.current=!0}catch(p){if(p instanceof Error&&p.name==="AbortError")return;l(p instanceof Error?p.message:"Failed to fetch health data"),d.current=!0}finally{r(!1)}},[e]),h=a.useCallback(async g=>{try{const p=await qd(g);s(f=>({...f,[g]:p}))}catch(p){console.error(`Failed to fetch health for project ${g}:`,p)}},[]);return a.useEffect(()=>(d.current=!1,m(),()=>{u.current&&u.current.abort()}),[m]),a.useEffect(()=>{if(e.length!==0)return c.current&&clearInterval(c.current),c.current=setInterval(()=>{m()},fN),()=>{c.current&&(clearInterval(c.current),c.current=null)}},[m,e.length]),{healthMap:n,loading:i,error:o,refresh:m,refreshProject:h}}function xN({projects:e,loading:n=!1,onSelectProject:s,onAddProject:i,onPauseProject:r,onResumeProject:o,onRemoveProject:l,nodes:c=[]}){const[u,d]=a.useState("all"),[m,h]=a.useState(null),[g,p]=a.useState("activity"),[f,x]=a.useState("desc");a.useEffect(()=>{if(typeof window>"u")return;const K=localStorage.getItem("kb-dashboard-recent-projects");if(K)try{const P=JSON.parse(K);b(P)}catch{}},[]);const[v,b]=a.useState([]),y=a.useMemo(()=>e.map(K=>K.id),[e]),{healthMap:S,loading:k}=gN(y),M=a.useMemo(()=>e.map(K=>({project:K,health:S[K.id]||null})),[e,S]),w=a.useMemo(()=>{let K=[...M];return u!=="all"&&(K=K.filter(({project:P})=>P.status===u)),m!==null&&(K=K.filter(({project:P})=>P.nodeId===m)),K},[M,u,m]),_=a.useMemo(()=>{const K=[...w];return K.sort((P,E)=>{let R=0;switch(g){case"name":R=P.project.name.localeCompare(E.project.name);break;case"activity":{const B=P.project.lastActivityAt||P.health?.lastActivityAt||P.project.updatedAt,G=E.project.lastActivityAt||E.health?.lastActivityAt||E.project.updatedAt;R=new Date(G).getTime()-new Date(B).getTime();break}case"status":{const B={errored:0,initializing:1,paused:2,active:3};R=B[P.project.status]-B[E.project.status];break}}return f==="asc"?R:-R}),K},[w,g,f]),N=a.useMemo(()=>{const K=e.length,P=e.filter($=>$.status==="active").length,E=e.filter($=>$.status==="errored").length,R=new Set;e.forEach($=>{$.nodeId&&R.add($.nodeId)});const B=R.size||(K>0?1:0);let G=0,X=0,C=0;return Object.values(S).forEach($=>{$&&(G+=$.activeTaskCount,X+=$.totalTasksCompleted,C+=$.inFlightAgentCount)}),{totalProjects:K,activeProjects:P,erroredProjects:E,totalNodes:B,totalActiveTasks:G,totalCompletedTasks:X,totalInFlightAgents:C}},[e,S]),L=a.useMemo(()=>({all:e.length,active:e.filter(K=>K.status==="active").length,paused:e.filter(K=>K.status==="paused").length,errored:e.filter(K=>K.status==="errored").length}),[e]),T=a.useMemo(()=>{const K=new Map;return e.forEach(P=>{const E=P.nodeId,R=K.get(E);if(R)R.count++;else{const G=c.find(X=>X.id===E)?.name??P._sourceNodeName??"Local";K.set(E,{name:G,count:1})}}),Array.from(K.entries()).map(([P,{name:E,count:R}])=>({nodeId:P??null,name:E,count:R}))},[e,c]),I=a.useCallback(K=>{const P=[K.id,...v.filter(E=>E!==K.id)].slice(0,3);b(P),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify(P)),s(K)},[s,v]);return n||k&&e.length>0&&Object.keys(S).length===0?t.jsx(pN,{}):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(Va,{size:48})}),t.jsx("h2",{className:"project-empty-state__title",children:"No Projects Found"}),t.jsx("p",{className:"project-empty-state__description",children:"Get started by adding your first project. Projects allow you to organize and track tasks across multiple repositories."}),t.jsxs("button",{className:"btn btn-primary project-empty-state__cta",onClick:i,children:[t.jsx(Xt,{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(Pi,{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(Dn,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:N.totalProjects}),t.jsx("span",{className:"project-stat__label",children:"Total"})]})]}),t.jsxs("div",{className:"project-stat project-stat--active",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Es,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:N.totalActiveTasks}),t.jsx("span",{className:"project-stat__label",children:"Active Tasks"})]})]}),t.jsxs("div",{className:"project-stat project-stat--completed",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(un,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:N.totalCompletedTasks}),t.jsx("span",{className:"project-stat__label",children:"Completed"})]})]}),N.erroredProjects>0&&t.jsxs("div",{className:"project-stat project-stat--error",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Zn,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:N.erroredProjects}),t.jsx("span",{className:"project-stat__label",children:"Errored"})]})]}),N.totalNodes>1&&t.jsxs("div",{className:"project-stat project-stat--nodes",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(no,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:N.totalNodes}),t.jsx("span",{className:"project-stat__label",children:"Nodes"})]})]})]}),t.jsxs("button",{className:"btn btn-primary project-overview__add-btn",onClick:i,children:[t.jsx(Xt,{size:16}),"Add Project"]})]}),t.jsxs("div",{className:"project-overview__filters",children:[t.jsxs("div",{className:"project-filter-tabs",children:[t.jsxs("button",{className:`project-filter-tab ${u==="all"?"active":""}`,onClick:()=>d("all"),children:["All",t.jsx("span",{className:"project-filter-count",children:L.all})]}),t.jsxs("button",{className:`project-filter-tab ${u==="active"?"active":""}`,onClick:()=>d("active"),children:["Active",t.jsx("span",{className:"project-filter-count",children:L.active})]}),t.jsxs("button",{className:`project-filter-tab ${u==="paused"?"active":""}`,onClick:()=>d("paused"),children:["Paused",t.jsx("span",{className:"project-filter-count",children:L.paused})]}),t.jsxs("button",{className:`project-filter-tab ${u==="errored"?"active":""} ${L.errored>0?"has-errors":""}`,onClick:()=>d("errored"),children:["Errored",t.jsx("span",{className:"project-filter-count",children:L.errored})]})]}),T.length>1&&t.jsxs("div",{className:"project-node-filter",children:[t.jsx(no,{size:14}),t.jsxs("select",{value:m??"",onChange:K=>{h(K.target.value||null)},className:"project-node-filter-select","aria-label":"Filter by node",children:[t.jsx("option",{value:"",children:"All Nodes"}),T.map(({nodeId:K,name:P,count:E})=>t.jsxs("option",{value:K??"",children:[P," (",E,")"]},K??"local"))]})]}),t.jsxs("div",{className:"project-sort",children:[t.jsx(to,{size:14}),t.jsxs("select",{value:`${g}-${f}`,onChange:K=>{const[P,E]=K.target.value.split("-");p(P),x(E)},className:"project-sort-select","aria-label":"Sort projects",children:[t.jsx("option",{value:"activity-desc",children:"Last Activity (Newest)"}),t.jsx("option",{value:"activity-asc",children:"Last Activity (Oldest)"}),t.jsx("option",{value:"name-asc",children:"Name (A-Z)"}),t.jsx("option",{value:"name-desc",children:"Name (Z-A)"}),t.jsx("option",{value:"status-asc",children:"Status (Error → Active)"}),t.jsx("option",{value:"status-desc",children:"Status (Active → Error)"})]}),t.jsx(_h,{size:14})]})]}),t.jsx("div",{className:"project-grid",children:_.map(({project:K,health:P})=>{const E=c.find(B=>B.id===K.nodeId),R=E?void 0:K._sourceNodeName;return t.jsx(hN,{project:K,health:P,node:E,nodeNameFallback:R,onSelect:I,onPause:r,onResume:o,onRemove:l},K.id)})}),_.length===0&&t.jsxs("div",{className:"project-overview__no-results",children:[t.jsx(to,{size:32}),t.jsx("p",{children:"No projects match the current filter"}),t.jsx("button",{className:"btn btn-secondary",onClick:()=>d("all"),children:"Show All Projects"})]})]})}const bN=45e3,vN=3e3,yN=2e3,kN=1500,Cu="fusion:sse-client-id";let Wi=null;const mi=new Map;function Eu(){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 gp(){if(!(typeof window>"u")){if(Wi)return Wi;try{const e=window.sessionStorage.getItem(Cu);if(e)return Wi=e,e;const n=Eu();return window.sessionStorage.setItem(Cu,n),Wi=n,n}catch{return Wi=Eu(),Wi}}}function xp(e){if(!(typeof window>"u"))try{return{parsed:new URL(e,window.location.origin),preserveRelativePath:e.startsWith("/")}}catch{return}}function bp(e){return e.origin===window.location.origin&&e.pathname==="/api/events"}function jN(e){const n=gp();if(!n)return e;const s=xp(e);return!s||!bp(s.parsed)?e:(s.parsed.searchParams.set("clientId",n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function qc(e,n){const s=gp();if(!s)return;const i=xp(e);if(!i||!bp(i.parsed))return;const r=new URL(`/api/events/${n}`,window.location.origin);r.searchParams.set("clientId",s);const o=i.parsed.searchParams.get("projectId");return o&&r.searchParams.set("projectId",o),Ks(`${r.pathname}${r.search}${r.hash}`)}function wN(e){if(typeof window>"u")return;const n=qc(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 Ro(e){e.keepaliveTimer&&(clearInterval(e.keepaliveTimer),e.keepaliveTimer=null)}function Mu(e){if(typeof window>"u"||typeof window.fetch!="function")return;const n=qc(e.url,"keepalive");if(!n)return;const s=typeof AbortController<"u"?new AbortController:null,i=s?window.setTimeout(()=>s.abort(),kN):null;window.fetch(n,{method:"POST",cache:"no-store",signal:s?.signal}).catch(()=>{}).finally(()=>{i!==null&&window.clearTimeout(i)})}function NN(e){Ro(e),qc(e.url,"keepalive")&&(Mu(e),e.keepaliveTimer=window.setInterval(()=>{Mu(e)},yN))}if(typeof window<"u"){const e=()=>{for(const s of Array.from(mi.values()))if(!s.closed){if(Ro(s),wN(s),s.es){try{s.es.close()}catch{}s.es=null}s.closed=!0}},n=s=>{if(s.persisted)for(const i of Array.from(mi.values()))i.subscribers.size!==0&&(i.closed=!1,Vc(i))};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e),window.addEventListener("pageshow",n)}function Wa(e){e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),e.heartbeatTimer=setTimeout(()=>{vp(e)},bN)}function vp(e){if(e.heartbeatTimer&&(clearTimeout(e.heartbeatTimer),e.heartbeatTimer=null),e.es&&(e.es.close(),e.es=null),Ro(e),e.nativeListeners.clear(),e.closed||e.subscribers.size===0||e.reconnectTimer)return;const n=mi.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=mi.get(e.url);s&&s===e&&e.subscribers.size>0&&Vc(e)},vN)}}function Vc(e){if(e.es||e.closed)return;e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=null);const n=new EventSource(Ks(jN(e.url)));e.es=n,NN(e),n.addEventListener("open",()=>{Wa(e);const s=e.hasOpenedOnce;e.hasOpenedOnce=!0;for(const i of e.subscribers)i.onOpen?.(),s&&i.onReconnect?.()}),n.addEventListener("error",s=>{for(const i of e.subscribers)i.onError?.(s);vp(e)}),n.addEventListener("message",()=>Wa(e)),n.addEventListener("heartbeat",()=>Wa(e)),yp(e),Wa(e)}function yp(e){if(!e.es)return;const n=new Set;for(const s of e.subscribers)for(const i of s.events.keys())n.add(i);for(const s of n){if(e.nativeListeners.has(s))continue;const i=r=>{Wa(e);const o=r;for(const l of e.subscribers){const c=l.events.get(s);if(c)for(const u of c)u(o)}};e.nativeListeners.set(s,i),e.es.addEventListener(s,i)}}function SN(e){e.closed=!0,e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),Ro(e),e.reconnectTimer&&clearTimeout(e.reconnectTimer),e.es&&e.es.close(),e.es=null,e.nativeListeners.clear(),mi.delete(e.url)}function $s(e,n={}){let s=mi.get(e);s||(s={url:e,es:null,subscribers:new Set,nativeListeners:new Map,heartbeatTimer:null,keepaliveTimer:null,reconnectTimer:null,hasOpenedOnce:!1,closed:!1},mi.set(e,s));const i={events:new Map,onOpen:n.onOpen,onReconnect:n.onReconnect,onError:n.onError};if(n.events)for(const[o,l]of Object.entries(n.events)){let c=i.events.get(o);c||(c=new Set,i.events.set(o,c)),c.add(l)}s.subscribers.add(i),Vc(s),yp(s);let r=!0;return()=>{if(!r)return;r=!1;const o=mi.get(e);o&&(o.subscribers.delete(i),o.subscribers.size===0&&SN(o))}}const Wc="kb-planning-last-description",Kc="kb-subtask-last-description",Gc="kb-mission-last-goal";function CN(e,n){as(Wc,e,n)}function EN(e){return zn(Wc,e)||""}function Ki(e){rr(Wc,e)}function MN(e,n){as(Kc,e,n)}function _N(e){return zn(Kc,e)||""}function rl(e){rr(Kc,e)}function AN(e,n){as(Gc,e,n)}function RN(e){return zn(Gc,e)||""}function li(e){rr(Gc,e)}function TN(e){const{question:n,response:s}=e;if(!n)return s;if(s&&typeof s=="object"&&!Array.isArray(s)){const i=s;if(n.id in i)return i[n.id]}return s}function PN(e,n){switch(e.type){case"text":return typeof n=="string"?n:n==null?"":String(n);case"single_select":return typeof n=="string"?e.options?.find(i=>i.id===n)?.label??n:n==null?"":String(n);case"multi_select":return Array.isArray(n)?n.map(s=>typeof s!="string"?String(s):e.options?.find(r=>r.id===s)?.label??s).join(", "):n==null?"":String(n);case"confirm":return n===!0?"Yes":n===!1?"No":n==null?"":String(n);default:return n==null?"":JSON.stringify(n)}}function IN(e){let n=0;const s=[];for(const i of e){if(i.question){n+=1,s.push({...i,questionNumber:n});continue}i.thinkingOutput&&s.push({...i,questionNumber:null})}return s}function Ms({entries:e,defaultShowThinking:n=!1}){const[s,i]=a.useState({}),r=IN(e);return r.length===0?null:t.jsx("div",{className:"conversation-history","data-testid":"conversation-history",children:r.map((o,l)=>{const c=!!o.question,u=!!o.thinkingOutput,d=s[l]??n,m=c?TN(o):void 0,h=o.question&&m!==void 0?PN(o.question,m):"";return t.jsxs("div",{className:"conversation-entry",children:[c?t.jsxs("div",{className:"conversation-entry-question",children:[t.jsxs("span",{className:"conversation-entry-question-label",children:["Q",o.questionNumber]}),t.jsx("p",{children:o.question?.question})]}):t.jsx("div",{className:"conversation-entry-question",children:t.jsx("span",{className:"conversation-entry-question-label",children:"AI Reasoning"})}),c&&t.jsxs("div",{className:"conversation-entry-response",children:[t.jsx("strong",{children:"Your response"}),t.jsx("p",{children:h||"—"})]}),u&&t.jsxs("div",{className:"conversation-entry-thinking",children:[t.jsxs("button",{type:"button",className:"conversation-thinking-toggle",onClick:()=>{i(g=>({...g,[l]:!d}))},"aria-expanded":d,children:[t.jsx("span",{"aria-hidden":"true",children:d?"▾":"▸"}),d?`Hide ${c?"AI thinking":"AI reasoning"}`:`Show ${c?"AI thinking":"AI reasoning"}`]}),d&&t.jsx("pre",{children:o.thinkingOutput})]})]},`${o.question?.id??"thinking"}-${l}`)})})}const _u="fusion-tab-id";function $N(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Li(){if(typeof window>"u")return"server-tab";const e=window.sessionStorage.getItem(_u);if(e)return e;const n=$N();return window.sessionStorage.setItem(_u,n),n}function To(e){const n=a.useMemo(()=>Li(),[]),[s,i]=a.useState(!1),[r,o]=a.useState(null),[l,c]=a.useState(!1);a.useEffect(()=>{if(!e){i(!1),o(null),c(!1);return}let d=!0;return c(!0),Promise.resolve(bj(e,n)).then(m=>{if(d){if(m.acquired){i(!1),o(null);return}i(!0),o(m.currentHolder)}}).catch(()=>{d&&(i(!1),o(null))}).finally(()=>{d&&c(!1)}),()=>{d=!1;try{const m=vj(e,n);m&&typeof m.catch=="function"&&m.catch(()=>{})}catch{}}},[e,n]),a.useEffect(()=>{if(!e||typeof window>"u")return;const d=()=>{if(typeof navigator.sendBeacon!="function")return;const m=Ks(`/api/ai-sessions/${encodeURIComponent(e)}/lock/beacon?tabId=${encodeURIComponent(n)}`);navigator.sendBeacon(m)};return window.addEventListener("beforeunload",d),()=>{window.removeEventListener("beforeunload",d)}},[e,n]),a.useEffect(()=>!e||typeof EventSource>"u"?void 0:$s("/api/events",{events:{"ai_session:updated":m=>{try{const h=JSON.parse(m.data);if(h.id!==e)return;const g=h.lockedByTab??null;o(g),i(!!(g&&g!==n))}catch{}}}}),[e,n]);const u=a.useCallback(async()=>{if(e){c(!0);try{await Promise.resolve(yj(e,n)),i(!1),o(null)}finally{c(!1)}}},[e,n]);return{isLockedByOther:s,currentHolder:r,takeControl:u,isLoading:l}}const DN="fusion:ai-session-sync",Au="fusion:ai-session-sync",LN=3e4,zN=6e4;function Os(){return Date.now()}function FN(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Ru(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 ON{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=FN(),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:Os()})}broadcastUpdate(n){const s=n.timestamp??Os();this.applySessionUpdate({sessionId:n.sessionId,status:n.status,needsInput:n.needsInput??n.status==="awaiting_input",owningTabId:n.owningTabId,type:n.type,title:n.title,projectId:n.projectId,updatedAt:n.updatedAt},s),this.publish({type:"session:updated",sessionId:n.sessionId,status:n.status,needsInput:n.needsInput,owningTabId:n.owningTabId,sessionType:n.type,title:n.title,projectId:n.projectId,updatedAt:n.updatedAt,timestamp:s})}broadcastCompleted(n){const s=n.status??"complete",i=n.timestamp??Os();this.applySessionUpdate({sessionId:n.sessionId,status:s,needsInput:!1,owningTabId:null},i),this.ownershipBySession.delete(n.sessionId),this.ownedSessions.delete(n.sessionId),this.emit(),this.publish({type:"session:completed",sessionId:n.sessionId,status:s,timestamp:i})}broadcastLock(n,s){const i=Os();this.applyTabOwnership(n,s,i),this.ownedSessions.set(n,s),this.publish({type:"tab:active",tabId:s,sessionId:n,timestamp:i})}broadcastUnlock(n,s){const i=Os();this.releaseTabOwnership(n,s,i),this.ownedSessions.delete(n),this.publish({type:"tab:inactive",tabId:s,sessionId:n,timestamp:i})}broadcastHeartbeat(n){const s=Os();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(DN),this.channel.onmessage=s=>{const i=Ru(s.data);i&&this.handleIncomingMessage(i)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==Au||!s.newValue))try{const i=JSON.parse(s.newValue),r=Ru(i.message);r&&this.handleIncomingMessage(r)}catch{}};window.addEventListener("storage",n),this.cleanupStorageListener=()=>{window.removeEventListener("storage",n)}}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{const n=Os();this.updateHeartbeat(this.tabId,n),this.publish({type:"tab:heartbeat",tabId:this.tabId,timestamp:n})},LN)}startStaleSweep(){this.staleSweepInterval=setInterval(()=>{this.emit()},1e4)}setupBeforeUnloadCleanup(){const n=()=>{for(const[s,i]of this.ownedSessions.entries()){const r=Os();this.publish({type:"tab:inactive",tabId:i,sessionId:s,timestamp:r})}};window.addEventListener("beforeunload",n),this.cleanupBeforeUnload=()=>{window.removeEventListener("beforeunload",n)}}publish(n){const s={...n,senderTabId:this.tabId};if(this.channel){this.channel.postMessage(s);return}if(this.usingStorageFallback)try{const i={id:`${s.type}-${s.timestamp}-${Math.random().toString(36).slice(2,8)}`,message:s};window.localStorage.setItem(Au,JSON.stringify(i))}catch{}}handleIncomingMessage(n){switch(n.type){case"session:updated":{this.applySessionUpdate({sessionId:n.sessionId,status:n.status,needsInput:n.needsInput,owningTabId:n.owningTabId,type:n.sessionType,title:n.title,projectId:n.projectId,updatedAt:n.updatedAt},n.timestamp);return}case"session:completed":{this.applySessionUpdate({sessionId:n.sessionId,status:n.status??"complete",needsInput:!1,owningTabId:null},n.timestamp),this.ownershipBySession.delete(n.sessionId),this.emit();return}case"tab:active":{this.applyTabOwnership(n.sessionId,n.tabId,n.timestamp);return}case"tab:inactive":{this.releaseTabOwnership(n.sessionId,n.tabId,n.timestamp);return}case"tab:heartbeat":{this.updateHeartbeat(n.tabId,n.timestamp);return}case"sync:request":{if(n.tabId===this.tabId)return;const s=[...this.sessionStates.values()].map(o=>{const l=this.ownershipBySession.get(o.sessionId);return{...o,owningTabId:l?.tabId??o.owningTabId??null}}),i=[...this.ownershipBySession.entries()].map(([o,l])=>({sessionId:o,tabId:l.tabId,timestamp:l.timestamp})),r=[...this.heartbeatByTab.entries()].map(([o,l])=>({tabId:o,timestamp:l}));this.publish({type:"sync:response",tabId:n.tabId,sessions:s,locks:i,heartbeats:r,timestamp:Os()});return}case"sync:response":{if(n.tabId!==this.tabId)return;for(const s of n.sessions)this.applySessionUpdate({sessionId:s.sessionId,status:s.status,needsInput:s.needsInput,owningTabId:s.owningTabId,type:s.type,title:s.title,projectId:s.projectId,updatedAt:s.updatedAt},s.lastEventTimestamp,!1);for(const s of n.locks??[])this.applyTabOwnership(s.sessionId,s.tabId,s.timestamp,!1);for(const s of n.heartbeats??[])this.updateHeartbeat(s.tabId,s.timestamp,!1);this.emit();return}default:return}}applySessionUpdate(n,s,i=!0){const r=this.sessionStates.get(n.sessionId);if(r&&s<r.lastEventTimestamp)return;const o=this.ownershipBySession.get(n.sessionId),l={sessionId:n.sessionId,status:n.status,needsInput:n.needsInput??n.status==="awaiting_input",lastEventTimestamp:s,owningTabId:n.owningTabId??o?.tabId??r?.owningTabId??null,type:n.type??r?.type,title:n.title??r?.title,projectId:n.projectId??r?.projectId,updatedAt:n.updatedAt??new Date(s).toISOString()};this.sessionStates.set(n.sessionId,l),n.owningTabId!==void 0&&(n.owningTabId?this.applyTabOwnership(n.sessionId,n.owningTabId,s,!1):this.ownershipBySession.delete(n.sessionId)),i&&this.emit()}applyTabOwnership(n,s,i,r=!0){const o=this.ownershipBySession.get(n);if(o&&i<o.timestamp)return;this.ownershipBySession.set(n,{tabId:s,timestamp:i}),this.updateHeartbeat(s,i,!1);const l=this.sessionStates.get(n);l&&i>=l.lastEventTimestamp&&this.sessionStates.set(n,{...l,owningTabId:s,lastEventTimestamp:i}),r&&this.emit()}releaseTabOwnership(n,s,i,r=!0){const o=this.ownershipBySession.get(n);if(!o||o.tabId!==s||i<o.timestamp)return;this.ownershipBySession.delete(n);const l=this.sessionStates.get(n);l&&i>=l.lastEventTimestamp&&this.sessionStates.set(n,{...l,owningTabId:null,lastEventTimestamp:i}),r&&this.emit()}updateHeartbeat(n,s,i=!0){const r=this.heartbeatByTab.get(n);r!==void 0&&s<r||(this.heartbeatByTab.set(n,s),i&&this.emit())}emit(){const n=Os(),s=new Map;for(const[r,o]of this.sessionStates.entries()){const l=this.ownershipBySession.get(r);s.set(r,{...o,owningTabId:l?.tabId??o.owningTabId??null})}const i=new Map;for(const[r,o]of this.ownershipBySession.entries()){const l=this.heartbeatByTab.get(o.tabId)??o.timestamp,c=n-l>zN;i.set(r,{sessionId:r,tabId:o.tabId,lastHeartbeatTimestamp:l,lastLockTimestamp:o.timestamp,stale:c})}this.snapshot={tabId:this.tabId,sessions:s,activeTabMap:i};for(const r of this.listeners)r()}}const Us=new ON;function ba(){const e=a.useSyncExternalStore(c=>Us.subscribe(c),()=>Us.getSnapshot(),()=>Us.getSnapshot());a.useEffect(()=>{Us.requestSync()},[]);const n=a.useCallback(c=>{Us.broadcastUpdate(c)},[]),s=a.useCallback(c=>{Us.broadcastCompleted(c)},[]),i=a.useCallback((c,u)=>{Us.broadcastLock(c,u)},[]),r=a.useCallback((c,u)=>{Us.broadcastUnlock(c,u)},[]),o=a.useCallback(c=>{Us.broadcastHeartbeat(c)},[]),l=a.useCallback(()=>{Us.requestSync()},[]);return{tabId:e.tabId,sessions:e.sessions,activeTabMap:e.activeTabMap,broadcastUpdate:n,broadcastCompleted:s,broadcastLock:i,broadcastUnlock:r,broadcastHeartbeat:o,requestSync:l}}function UN(e,n){return e&&n?`${e}/${n}`:""}function BN(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 HN=["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 qN({isOpen:e,onClose:n,onMissionCreated:s,projectId:i,initialGoal:r,resumeSessionId:o}){const[l,c]=a.useState(""),[u,d]=a.useState({type:"initial"}),[m,h]=a.useState(null),[g,p]=a.useState([]),[f,x]=a.useState([]),[v,b]=a.useState(null),[y,S]=a.useState(!1),k=a.useRef(!1),[M,w]=a.useState(""),[_,N]=a.useState(!0),[L,T]=a.useState(!1),[I,z]=a.useState(!1),[K,P]=a.useState(!1),E=a.useRef(null),R=a.useRef(null),B=a.useRef(null),G=a.useRef(null),[X,C]=a.useState(o??null),$=a.useMemo(()=>Li(),[]),{isLockedByOther:A,takeControl:j,isLoading:J}=To(e?X:null),{activeTabMap:W,broadcastUpdate:oe,broadcastCompleted:he,broadcastLock:se,broadcastUnlock:fe,broadcastHeartbeat:U}=ba(),{confirm:Ne}=Is(),[ee,ve]=a.useState(void 0),[ue,ye]=a.useState(void 0),[ie,Me]=a.useState([]),[ze,Be]=a.useState(!0),[Je,Ye]=a.useState(null),[Ge,it]=a.useState([]),[_e,Fe]=a.useState([]),ae=UN(ee,ue);a.useEffect(()=>{(async()=>{try{Be(!0);const Re=await os();Me(Re.models),it(Re.favoriteProviders),Fe(Re.favoriteModels)}catch(Re){Ye(je(Re)||"Failed to load models")}finally{Be(!1)}})()},[]);const be=a.useCallback(Ee=>{it(Re=>{const Le=Re,Se=Le.includes(Ee)?Le.filter(mt=>mt!==Ee):[Ee,...Le];return an({favoriteProviders:Se,favoriteModels:_e}).catch(()=>{it(Le)}),Se})},[_e]),ne=a.useCallback(Ee=>{Fe(Re=>{const Le=Re,Se=Le.includes(Ee)?Le.filter(mt=>mt!==Ee):[Ee,...Le];return an({favoriteProviders:Ge,favoriteModels:Se}).catch(()=>{Fe(Le)}),Se})},[Ge]),Ie=a.useCallback((Ee,Re)=>{if(!Ee||!Re)return"Using default";const Le=ie.find(ct=>ct.provider===Ee&&ct.id===Re);return Le?`${Le.provider}/${Le.id}`:`${Ee}/${Re}`},[ie]),Pe=a.useCallback(Ee=>{R.current?.close();const Re=rj(Ee,i,{onThinking:Le=>{w(ct=>ct+Le),oe({sessionId:Ee,status:"generating",needsInput:!1,owningTabId:$,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onQuestion:Le=>{T(!1),z(!1),li(i),d({type:"question",sessionId:Ee,question:Le}),w(""),S(!0),oe({sessionId:Ee,status:"awaiting_input",needsInput:!0,owningTabId:$,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onSummary:Le=>{T(!1),z(!1),li(i),d({type:"summary",sessionId:Ee,summary:Le}),b(Le),w(""),S(!0),oe({sessionId:Ee,status:"complete",needsInput:!1,owningTabId:$,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onError:Le=>{const ct=Le||"Session failed while contacting the AI.";T(!1),z(!1),h(null),d({type:"error",sessionId:Ee,errorMessage:ct}),w(""),S(!0),B.current=Ee,oe({sessionId:Ee,status:"error",needsInput:!1,owningTabId:$,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null}),he({sessionId:Ee,status:"error"})},onComplete:()=>{T(!1),z(!1),B.current=null,he({sessionId:Ee,status:"complete"})},onConnectionStateChange:Le=>{T(Le==="reconnecting")}});R.current=Re},[he,oe,l,i,$]),ce=a.useCallback(async Ee=>{const Re=Ee??l;if(Re.trim()){h(null),w(""),p([]),x([]),T(!1),d({type:"loading"});try{const{sessionId:Le}=await nj(Re.trim(),i,ee&&ue?{modelProvider:ee,modelId:ue}:void 0);B.current=Le,C(Le),li(i),Pe(Le),p([])}catch(Le){T(!1),h(je(Le)||"Failed to start interview session"),d({type:"initial"}),B.current=null,C(null)}}},[Pe,l,ee,ue,i]);a.useEffect(()=>{e&&u.type==="initial"&&E.current?.focus()},[e,u.type]),a.useEffect(()=>{if(e&&r&&!k.current&&u.type==="initial"){c(r);const Ee=setTimeout(()=>{k.current=!0,ce(r)},0);return()=>clearTimeout(Ee)}else if(e&&!r&&!k.current&&u.type==="initial"){const Ee=RN(i);Ee&&c(Ee)}},[e,r,u.type,ce]),a.useEffect(()=>{e||(k.current=!1,T(!1),z(!1),C(null))},[e]),a.useEffect(()=>{if(!e||!o||u.type!=="initial")return;let Ee=!1;return ti(o).then(Re=>{if(Ee||!Re)return;const Le=la(Re.conversationHistory);if(x(Le),C(Re.id),p(Le.map(ct=>ct.response).filter(ct=>!!(ct&&typeof ct=="object"&&!Array.isArray(ct)))),Re.status==="awaiting_input"&&Re.currentQuestion)try{li(i);const ct=JSON.parse(Re.currentQuestion);B.current=Re.id,S(!0),d({type:"question",sessionId:Re.id,question:ct})}catch{h("Failed to restore session question.")}else if(Re.status==="complete"&&Re.result)try{li(i);const ct=JSON.parse(Re.result);B.current=Re.id,S(!0),b(ct),d({type:"summary",sessionId:Re.id,summary:ct})}catch{h("Failed to restore session result.")}else Re.status==="generating"?(B.current=Re.id,S(!0),Re.thinkingOutput&&w(Re.thinkingOutput),d({type:"loading"}),Pe(Re.id)):Re.status==="error"&&(B.current=Re.id,S(!0),h(null),d({type:"error",sessionId:Re.id,errorMessage:Re.error??"The session encountered an error."}))}).catch(()=>{Ee||h("Failed to resume session.")}),()=>{Ee=!0}},[Pe,e,o,u.type,i]),a.useEffect(()=>{if(!e){G.current&&(fe(G.current,$),G.current=null);return}if(X&&G.current!==X){G.current&&fe(G.current,$),se(X,$),G.current=X;return}!X&&G.current&&(fe(G.current,$),G.current=null)},[se,fe,e,X,$]),a.useEffect(()=>{if(!e||!X||G.current!==X)return;U($);const Ee=setInterval(()=>{U($)},3e4);return()=>{clearInterval(Ee)}},[U,e,X,$]),a.useEffect(()=>()=>{R.current?.close(),R.current=null,G.current&&(fe(G.current,$),G.current=null)},[fe,$]),a.useEffect(()=>{if(!e)return;const Ee=Re=>{(u.type==="question"||u.type==="summary")&&(Re.preventDefault(),Re.returnValue=""),R.current?.close()};return window.addEventListener("beforeunload",Ee),()=>window.removeEventListener("beforeunload",Ee)},[e,u]);const le=a.useCallback(()=>{R.current?.close(),R.current=null,n()},[n]),$e=a.useCallback(async()=>{if(l&&AN(l,i),!(y&&!await Ne({title:"Close Interview",message:"Are you sure you want to close? Your interview progress will be lost.",danger:!0}))){if(R.current?.close(),R.current=null,u.type==="question"||u.type==="summary"||u.type==="error")try{await np(u.sessionId,i,$)}catch{}c(""),d({type:"initial"}),h(null),p([]),x([]),b(null),w(""),T(!1),z(!1),S(!1),P(!1),ve(void 0),ye(void 0),B.current=null,C(null),n()}},[l,y,u,n,i,$,Ne]);a.useEffect(()=>{if(!e)return;const Ee=Re=>{Re.key==="Escape"&&$e()};return document.addEventListener("keydown",Ee),()=>document.removeEventListener("keydown",Ee)},[e,$e]);const at=a.useCallback(async Ee=>{if(u.type!=="question")return;const{sessionId:Re}=u;h(null),p(Le=>[...Le,Ee]),x(Le=>[...Le,{question:u.question,response:Ee}]),d({type:"loading"}),w("");try{Pe(Re),await sj(Re,Ee,i,$),S(!0)}catch(Le){R.current?.close(),R.current=null,h(je(Le)||"Failed to submit response"),d({type:"question",sessionId:Re,question:u.question})}},[u,i,$,Pe]),tt=a.useCallback(async()=>{if(u.type!=="error")return;const Ee=u.sessionId;h(null),z(!0),w(""),d({type:"loading"}),Pe(Ee);try{B.current=Ee,C(Ee),await ij(Ee,i,$)}catch(Re){let Le=Re;if((je(Re)||"").includes("not in an error state"))try{const Se=await ti(Ee);if(!Se)throw new Error("Failed to refresh interview session.");const mt=la(Se.conversationHistory);if(x(mt),p(mt.map(gt=>gt.response).filter(gt=>!!(gt&&typeof gt=="object"&&!Array.isArray(gt)))),B.current=Se.id,C(Se.id),S(!0),Se.status==="generating")w(Se.thinkingOutput??""),d({type:"loading"}),R.current?.isConnected()||Pe(Se.id);else if(Se.status==="awaiting_input"){if(!Se.currentQuestion)throw new Error("Interview session is awaiting input but has no current question.");li(i);const gt=JSON.parse(Se.currentQuestion);d({type:"question",sessionId:Se.id,question:gt}),R.current?.isConnected()||Pe(Se.id)}else if(Se.status==="complete"){if(!Se.result)throw new Error("Interview session is complete but has no result.");li(i);const gt=JSON.parse(Se.result);b(gt),d({type:"summary",sessionId:Se.id,summary:gt})}else Se.status==="error"&&d({type:"error",sessionId:Se.id,errorMessage:Se.error??"Retry failed. Please try again."});T(!1);return}catch(Se){Le=Se}R.current?.close(),R.current=null,d({type:"error",sessionId:Ee,errorMessage:je(Le)||"Retry failed. Please try again."}),T(!1)}finally{z(!1)}},[Pe,i,$,u]),V=a.useCallback(async()=>{if(u.type==="summary"){h(null),P(!0);try{const Ee=await aj(u.sessionId,v||void 0,i);s(Ee),li(i),R.current?.close(),R.current=null,c(""),d({type:"initial"}),h(null),p([]),x([]),b(null),w(""),T(!1),z(!1),S(!1),P(!1),B.current=null,C(null),n()}catch(Ee){h(je(Ee)||"Failed to create mission"),P(!1)}}},[u,v,s,n,i]),de=()=>u.type==="question"?Math.min(g.length+1,6):6,Z=u.type==="loading"||u.type==="question"||u.type==="summary"||u.type==="error",we=X?W.get(X):null,pe=we&&we.tabId!==$,Te=!!(pe&&!we.stale),Qe=A&&(!pe||we.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Ee=>Ee.target===Ee.currentTarget&&$e(),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(rs,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Plan Mission with AI"})]}),t.jsxs("div",{className:"modal-header-actions",children:[Z&&t.jsx("button",{className:"modal-send-to-background",onClick:le,title:"Send to background","aria-label":"Send to background",children:t.jsx(mr,{size:16})}),t.jsx("button",{className:"modal-close",onClick:$e,"aria-label":"Close",children:t.jsx(zt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[m&&t.jsx("div",{className:"form-error planning-error",children:m}),L&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Te&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),u.type==="initial"&&t.jsxs("div",{className:"planning-initial",children:[t.jsxs("div",{className:"planning-view-scroll",children:[t.jsxs("div",{className:"planning-intro",children:[t.jsx(Vn,{size:32,className:"icon-triage-lg"}),t.jsx("h4",{children:"Transform your vision into a structured mission"}),t.jsx("p",{className:"text-muted",children:"Describe what you want to build. The AI will interview you to understand scope, constraints, and requirements, then produce a structured plan with milestones, slices, and features."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"mission-goal",children:"What do you want to build?"}),t.jsx("textarea",{ref:E,id:"mission-goal",rows:4,className:"planning-textarea",placeholder:"e.g., Build a real-time collaborative document editor with presence, comments, and version history...",value:l,onChange:Ee=>c(Ee.target.value),onKeyDown:Ee=>{Ee.key==="Enter"&&!Ee.shiftKey&&l.trim()&&(Ee.preventDefault(),ce())}})]}),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:HN.map((Ee,Re)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>c(Ee),children:Ee.length>45?Ee.slice(0,45)+"...":Ee},Re))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"mission-interview-modal-model",className:"form-label",children:["Planning Model",ze&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(Ln,{id:"mission-interview-modal-model",label:"Planning Model",value:ae,onChange:Ee=>{const{provider:Re,modelId:Le}=BN(Ee);ve(Re),ye(Le)},models:ie,disabled:ze,favoriteProviders:Ge,onToggleFavorite:be,favoriteModels:_e,onToggleModelFavorite:ne}),Je&&t.jsxs("div",{className:"form-hint form-hint-error",children:[Je," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{Be(!0);const Ee=await os();Me(Ee.models),it(Ee.favoriteProviders),Fe(Ee.favoriteModels),Ye(null)}catch(Ee){Ye(je(Ee)||"Failed to load models")}finally{Be(!1)}})()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${ee&&ue?"model-badge-custom":"model-badge-default"}`,children:Ie(ee,ue)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>ce(),disabled:!l.trim(),children:[t.jsx(rs,{size:16,className:"icon-mr-8"}),"Start Interview"]})})]}),u.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(rt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:M?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>N(!_),type:"button",children:_?"Hide thinking":"Show thinking"}),_&&M&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:M})})]})]}),u.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[f.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ms,{entries:f}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:u.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void tt(),disabled:I,children:[I?t.jsx(rt,{size:14,className:"spin"}):t.jsx(wn,{size:14}),t.jsx("span",{className:"icon-ml-6",children:I?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:$e,disabled:I,children:"Cancel"})]})]})]})}),u.type==="question"&&t.jsx(VN,{question:u.question,progress:de(),historyEntries:f,onSubmit:at}),u.type==="summary"&&v&&t.jsx(WN,{summary:v,historyEntries:f,onSummaryChange:b,onApprove:V,onStartOver:()=>{d({type:"initial"}),S(!1),b(null),p([]),x([]),C(null),R.current?.close(),R.current=null},isCreating:K}),A&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(No,{size:16}),t.jsx("span",{children:Qe?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),Qe&&t.jsx("button",{type:"button",onClick:()=>{j()},disabled:J,className:"btn btn-primary session-lock-take-control",children:J?"Taking control...":"Take Control"})]})})]})]})}):null}function VN({question:e,progress:n,historyEntries:s,onSubmit:i}){const[r,o]=a.useState({}),[l,c]=a.useState(""),u=a.useCallback(()=>{e.type==="text"?i({[e.id]:l}):e.type==="confirm"?i({[e.id]:r[e.id]===!0}):i(r)},[e,r,l,i]);a.useEffect(()=>{o({}),c("")},[e.id]);const d=()=>{switch(e.type){case"text":return l.trim().length>0;case"single_select":return r[e.id]!==void 0;case"multi_select":return Array.isArray(r[e.id])&&r[e.id].length>0;case"confirm":return r[e.id]!==void 0;default:return!0}};return t.jsxs("div",{className:"planning-question-form",children:[t.jsxs("div",{className:"planning-view-scroll planning-question-scroll",children:[s.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ms,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3,4,5,6].map(m=>t.jsx("div",{className:`planning-progress-step ${m<=n?"active":""}`},m))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~6"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:l,onChange:m=>c(m.target.value),onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&l.trim()&&(m.preventDefault(),u())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(m=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:m.id,checked:r[e.id]===m.id,onChange:()=>o({[e.id]:m.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(m=>{const h=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:m.id,checked:h.includes(m.id),onChange:g=>{const p=g.target.checked?[...h,m.id]:h.filter(f=>f!==m.id);o({[e.id]:p})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!0?"selected":""}`,onClick:()=>o({[e.id]:!0}),children:[t.jsx(un,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(zt,{size:18}),"No"]})]})]})]})]})]}),t.jsx("div",{className:"planning-actions",children:t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:u,disabled:!d(),children:["Continue",t.jsx(dr,{size:16,className:"icon-ml-4"})]})})]})}function WN({summary:e,historyEntries:n,onSummaryChange:s,onApprove:i,onStartOver:r,isCreating:o}){const[l,c]=a.useState(()=>new Set(e.milestones.map((k,M)=>M))),[u,d]=a.useState(()=>{const k=new Set;return e.milestones.forEach((M,w)=>{M.slices.forEach((_,N)=>k.add(`${w}-${N}`))}),k}),m=k=>{c(M=>{const w=new Set(M);return w.has(k)?w.delete(k):w.add(k),w})},h=k=>{d(M=>{const w=new Set(M);return w.has(k)?w.delete(k):w.add(k),w})},g=(k,M)=>{const w=[...e.milestones];w[k]={...w[k],...M},s({...e,milestones:w})},p=(k,M,w)=>{const _=[...e.milestones],N=[..._[k].slices];N[M]={...N[M],...w},_[k]={..._[k],slices:N},s({...e,milestones:_})},f=(k,M,w,_)=>{const N=[...e.milestones],L=[...N[k].slices],T=[...L[M].features];T[w]={...T[w],..._},L[M]={...L[M],features:T},N[k]={...N[k],slices:L},s({...e,milestones:N})},x=k=>{const M=e.milestones.filter((w,_)=>_!==k);s({...e,milestones:M})},v=(k,M)=>{const w=[...e.milestones];w[k]={...w[k],slices:w[k].slices.filter((_,N)=>N!==M)},s({...e,milestones:w})},b=(k,M,w)=>{const _=[...e.milestones],N=[..._[k].slices];N[M]={...N[M],features:N[M].features.filter((L,T)=>T!==w)},_[k]={..._[k],slices:N},s({...e,milestones:_})},y=(k,M)=>{const w=[...e.milestones],_=[...w[k].slices];_[M]={..._[M],features:[..._[M].features,{title:"New feature",description:""}]},w[k]={...w[k],slices:_},s({...e,milestones:w})},S=e.milestones.reduce((k,M)=>k+M.slices.reduce((w,_)=>w+_.features.length,0),0);return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ms,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(un,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Mission Plan Ready"}),t.jsxs("p",{className:"text-muted",children:[e.milestones.length," milestones, ",S," features. Review and edit before approving."]})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Mission Title"}),t.jsx("input",{type:"text",className:"form-input",value:e.missionTitle||"",onChange:k=>s({...e,missionTitle:k.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Mission Description"}),t.jsx("textarea",{className:"planning-textarea",rows:3,value:e.missionDescription||"",onChange:k=>s({...e,missionDescription:k.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Roadmap"}),t.jsx("div",{className:"roadmap-list",children:e.milestones.map((k,M)=>t.jsxs("div",{className:"roadmap-card",children:[t.jsxs("div",{className:"roadmap-card-header",onClick:()=>m(M),children:[l.has(M)?t.jsx(qt,{size:16,className:"icon-text-secondary"}):t.jsx(mn,{size:16,className:"icon-text-secondary"}),t.jsx(Ti,{size:16,className:"icon-milestone"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-title",value:k.title,onChange:w=>g(M,{title:w.target.value}),onClick:w=>w.stopPropagation()}),e.milestones.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:w=>{w.stopPropagation(),x(M)},title:"Remove milestone",children:t.jsx(Jt,{size:14,className:"icon-text-secondary"})})]}),l.has(M)&&t.jsxs("div",{className:"roadmap-card-body",children:[t.jsx("textarea",{className:"planning-textarea roadmap-textarea-md",rows:2,placeholder:"Milestone description...",value:k.description||"",onChange:w=>g(M,{description:w.target.value})}),t.jsxs("div",{className:"roadmap-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Verification Criteria"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-sm",rows:2,placeholder:"How to confirm this milestone is complete...",value:k.verification||"",onChange:w=>g(M,{verification:w.target.value})})]}),k.slices.map((w,_)=>{const N=`${M}-${_}`;return t.jsxs("div",{className:"roadmap-slice-card",children:[t.jsxs("div",{className:"roadmap-slice-header",onClick:()=>h(N),children:[u.has(N)?t.jsx(qt,{size:14,className:"icon-text-secondary"}):t.jsx(mn,{size:14,className:"icon-text-secondary"}),t.jsx(rc,{size:14,className:"icon-slice"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:w.title,onChange:L=>p(M,_,{title:L.target.value}),onClick:L=>L.stopPropagation()}),k.slices.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:L=>{L.stopPropagation(),v(M,_)},title:"Remove slice",children:t.jsx(Jt,{size:12,className:"icon-text-secondary"})})]}),u.has(N)&&t.jsxs("div",{className:"roadmap-slice-body",children:[t.jsxs("div",{className:"roadmap-slice-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Slice Verification"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-xs",rows:1,placeholder:"How to confirm this slice is done...",value:w.verification||"",onChange:L=>p(M,_,{verification:L.target.value})})]}),w.features.map((L,T)=>t.jsxs("div",{className:"roadmap-feature-row",children:[t.jsx(Zl,{size:12,className:"icon-feature"}),t.jsxs("div",{className:"roadmap-feature-content",children:[t.jsx("input",{type:"text",className:"form-input roadmap-input-feature",value:L.title,onChange:I=>f(M,_,T,{title:I.target.value})}),L.description&&t.jsx("p",{className:"roadmap-feature-text",children:L.description}),L.acceptanceCriteria&&t.jsxs("p",{className:"roadmap-feature-text--italic",children:["AC: ",L.acceptanceCriteria]})]}),t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:()=>b(M,_,T),title:"Remove feature",children:t.jsx(Jt,{size:12,className:"icon-text-secondary"})})]},T)),t.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>y(M,_),children:[t.jsx(Xt,{size:12}),"Add Feature"]})]})]},_)})]})]},M))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:r,disabled:o,children:[t.jsx(ga,{size:16,className:"icon-mr-4"}),"Start Over"]}),t.jsx("button",{className:"btn btn-primary",onClick:i,disabled:o||e.milestones.length===0,children:o?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:16,className:"spin icon-mr-8"}),"Creating Mission..."]}):t.jsxs(t.Fragment,{children:[t.jsx(un,{size:16,className:"icon-mr-8"}),"Approve Plan"]})})]})]})}function KN({isOpen:e,onClose:n,onApplied:s,targetType:i,targetId:r,targetTitle:o,missionContext:l,projectId:c,resumeSessionId:u}){const[d,m]=a.useState({type:"initial"}),[h,g]=a.useState(null),[p,f]=a.useState([]),[x,v]=a.useState([]),[b,y]=a.useState(null),[S,k]=a.useState(""),[M,w]=a.useState(!0),[_,N]=a.useState(!1),[L,T]=a.useState(!1),I=a.useRef(null),z=a.useRef(null),K=a.useRef(null),P=a.useRef(null),[E,R]=a.useState(null),B=a.useMemo(()=>Li(),[]);To(e?E:null);const{activeTabMap:G,broadcastUpdate:X,broadcastCompleted:C,broadcastLock:$,broadcastUnlock:A,broadcastHeartbeat:j}=ba(),J=i==="milestone"?oj:mj,W=i==="milestone"?lj:hj,oe=i==="milestone"?cj:pj,he=i==="milestone"?dj:fj,se=i==="milestone"?uj:gj,fe=i==="milestone"?"Milestone":"Slice",U=i==="milestone"?"milestone_interview":"slice_interview",Ne=a.useCallback(_e=>{z.current?.close();const Fe=oe(_e,c,{onThinking:ae=>{k(be=>be+ae),X({sessionId:_e,status:"generating",needsInput:!1,owningTabId:B,type:U,title:o,projectId:c??null})},onQuestion:ae=>{N(!1),ee(),m({type:"question",sessionId:_e,question:ae}),k(""),X({sessionId:_e,status:"awaiting_input",needsInput:!0,owningTabId:B,type:U,title:o,projectId:c??null})},onSummary:ae=>{N(!1),ee(),m({type:"summary",sessionId:_e,summary:ae}),y(ae),k(""),X({sessionId:_e,status:"complete",needsInput:!1,owningTabId:B,type:U,title:o,projectId:c??null})},onError:ae=>{const be=ae||"Session failed while contacting the AI.";N(!1),g(null),m({type:"error",sessionId:_e,errorMessage:be}),k(""),K.current=_e,X({sessionId:_e,status:"error",needsInput:!1,owningTabId:B,type:U,title:o,projectId:c??null}),C({sessionId:_e,status:"error"})},onComplete:()=>{N(!1),K.current=null,C({sessionId:_e,status:"complete"})},onConnectionStateChange:ae=>{N(ae==="reconnecting")}});z.current=Fe},[C,X,oe,U,c,B,o]),ee=()=>{y(null),f([]),v([]),k("")},ve=a.useCallback(async()=>{g(null),ee(),N(!1),m({type:"loading"});try{const{sessionId:_e}=await J(r,c);K.current=_e,R(_e),Ne(_e)}catch(_e){N(!1),g(je(_e)||`Failed to start ${fe.toLowerCase()} interview`),m({type:"initial"}),K.current=null,R(null)}},[Ne,c,J,r,fe]),ue=a.useCallback(async()=>{g(null),T(!0);try{await se(r,c),s(),m({type:"applied"})}catch(_e){g(je(_e)||`Failed to skip ${fe.toLowerCase()} interview`),T(!1)}},[s,c,se,r,fe]);a.useEffect(()=>{e&&d.type==="initial"&&I.current?.focus()},[e,d.type]),a.useEffect(()=>{if(!e||!u||d.type!=="initial")return;let _e=!1;return ti(u).then(Fe=>{if(_e||!Fe)return;const ae=la(Fe.conversationHistory);if(v(ae),R(Fe.id),f(ae.map(be=>be.response).filter(be=>!!(be&&typeof be=="object"&&!Array.isArray(be)))),Fe.status==="awaiting_input"&&Fe.currentQuestion)try{const be=JSON.parse(Fe.currentQuestion);K.current=Fe.id,m({type:"question",sessionId:Fe.id,question:be})}catch{g("Failed to restore session question.")}else if(Fe.status==="complete"&&Fe.result)try{const be=JSON.parse(Fe.result);K.current=Fe.id,y(be),m({type:"summary",sessionId:Fe.id,summary:be})}catch{g("Failed to restore session result.")}else Fe.status==="generating"?(K.current=Fe.id,Fe.thinkingOutput&&k(Fe.thinkingOutput),m({type:"loading"}),Ne(Fe.id)):Fe.status==="error"&&(K.current=Fe.id,g(null),m({type:"error",sessionId:Fe.id,errorMessage:Fe.error??"The session encountered an error."}))}).catch(()=>{_e||g("Failed to resume session.")}),()=>{_e=!0}},[Ne,e,u,d.type]),a.useEffect(()=>{e||(N(!1),R(null))},[e]),a.useEffect(()=>{if(!(!e||!E)){if(P.current!==E){P.current&&A(P.current,B),$(E,B),P.current=E;return}!E&&P.current&&(A(P.current,B),P.current=null)}},[$,A,e,E,B]),a.useEffect(()=>{if(!e||!E||P.current!==E)return;j(B);const _e=setInterval(()=>{j(B)},3e4);return()=>{clearInterval(_e)}},[j,e,E,B]),a.useEffect(()=>()=>{z.current?.close(),z.current=null,P.current&&(A(P.current,B),P.current=null)},[A,B]);const ye=a.useCallback(()=>{z.current?.close(),z.current=null,n()},[n]),ie=a.useCallback(async()=>{z.current?.close(),z.current=null,ee(),m({type:"initial"}),g(null),K.current=null,R(null),n()},[n]),Me=a.useCallback(async _e=>{if(d.type!=="question")return;const{sessionId:Fe}=d;g(null),f(ae=>[...ae,_e]),v(ae=>[...ae,{question:d.question,response:_e}]),m({type:"loading"}),k("");try{Ne(Fe),await W(Fe,_e,c,B)}catch(ae){z.current?.close(),z.current=null,g(je(ae)||"Failed to submit response"),m({type:"question",sessionId:Fe,question:d.question})}},[Ne,c,W,B,d]),ze=a.useCallback(async()=>{if(d.type==="summary"){g(null),T(!0);try{await he(d.sessionId,b||void 0,c),s(),m({type:"applied"})}catch(_e){g(je(_e)||"Failed to apply interview results"),T(!1)}}},[he,b,s,c,d]),Be=()=>d.type==="question"?Math.min(p.length+1,6):6,Je=d.type==="loading"||d.type==="question"||d.type==="summary"||d.type==="error",Ye=E?G.get(E):null,it=!!(Ye&&Ye.tabId!==B&&!Ye.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:_e=>_e.target===_e.currentTarget&&ie(),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(Vn,{size:20,className:"icon-triage"}),t.jsxs("h3",{children:["Plan ",fe,": ",o]})]}),t.jsxs("div",{className:"modal-header-actions",children:[Je&&t.jsx("button",{className:"modal-send-to-background",onClick:ye,title:"Send to background","aria-label":"Send to background",children:t.jsx(mr,{size:16})}),t.jsx("button",{className:"modal-close",onClick:ie,"aria-label":"Close",children:t.jsx(zt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[h&&t.jsx("div",{className:"form-error planning-error",children:h}),_&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),it&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),d.type==="initial"&&t.jsxs("div",{className:"planning-initial",children:[t.jsx("div",{className:"planning-view-scroll",children:t.jsxs("div",{className:"planning-intro",children:[t.jsx(Vn,{size:32,className:"icon-triage-lg"}),t.jsxs("h4",{children:["Refine ",fe," scope with AI"]}),t.jsxs("p",{className:"text-muted",children:["The AI will interview you to refine the ",i,"'s scope, acceptance criteria, and verification methods. Each ",i," can have its own refined plan or inherit context from the mission level."]}),l&&t.jsxs("div",{className:"planning-context-info",children:[t.jsx("span",{className:"planning-context-label",children:"Mission context:"}),t.jsx("span",{className:"planning-context-text",children:l})]})]})}),t.jsxs("div",{className:"planning-view-footer",children:[t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>void ve(),children:[t.jsx(Vn,{size:16,className:"icon-mr-8"}),"Start Interview"]}),t.jsxs("button",{className:"btn planning-use-context-btn",onClick:()=>void ue(),disabled:L,children:[L?t.jsx(rt,{size:16,className:"spin"}):null,"Use Mission Context"]}),t.jsx("button",{className:"btn",onClick:ie,children:"Cancel"})]})]}),d.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(rt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:S?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>w(!M),type:"button",children:M?"Hide thinking":"Show thinking"}),M&&S&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:S})})]})]}),d.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[x.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ms,{entries:x}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:d.errorMessage}),t.jsx("div",{className:"ai-error-actions",children:t.jsx("button",{className:"btn",onClick:ie,children:"Cancel"})})]})]})}),d.type==="question"&&t.jsx(GN,{question:d.question,progress:Be(),historyEntries:x,onSubmit:Me}),d.type==="summary"&&b&&t.jsx(JN,{summary:b,historyEntries:x,onSummaryChange:y,onApply:ze,onCancel:ie,isApplying:L}),d.type==="applied"&&t.jsxs("div",{className:"planning-summary planning-applied",children:[t.jsx("div",{className:"planning-view-scroll",children:t.jsxs("div",{className:"planning-applied-content",children:[t.jsx(un,{size:48,className:"icon-success"}),t.jsxs("h4",{children:[fe," Updated"]}),t.jsxs("p",{className:"text-muted",children:["The ",i,"'s scope and verification have been ",d.type==="applied"?"applied":"updated","."]})]})}),t.jsx("div",{className:"planning-view-footer",children:t.jsx("button",{className:"btn btn-primary",onClick:s,children:"Done"})})]})]})]})}):null}function GN({question:e,progress:n,historyEntries:s,onSubmit:i}){const[r,o]=a.useState({}),[l,c]=a.useState(""),u=a.useCallback(()=>{e.type==="text"?i({[e.id]:l}):e.type==="confirm"?i({[e.id]:r[e.id]===!0}):i(r)},[e,r,l,i]);a.useEffect(()=>{o({}),c("")},[e.id]);const d=()=>{switch(e.type){case"text":return l.trim().length>0;case"single_select":return r[e.id]!==void 0;case"multi_select":return Array.isArray(r[e.id])&&r[e.id].length>0;case"confirm":return r[e.id]!==void 0;default:return!0}};return t.jsxs("div",{className:"planning-question-form",children:[t.jsxs("div",{className:"planning-view-scroll planning-question-scroll",children:[s.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ms,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3,4,5,6].map(m=>t.jsx("div",{className:`planning-progress-step ${m<=n?"active":""}`},m))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~6"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:l,onChange:m=>c(m.target.value),onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&l.trim()&&(m.preventDefault(),u())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(m=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:m.id,checked:r[e.id]===m.id,onChange:()=>o({[e.id]:m.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(m=>{const h=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:m.id,checked:h.includes(m.id),onChange:g=>{const p=g.target.checked?[...h,m.id]:h.filter(f=>f!==m.id);o({[e.id]:p})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!0?"selected":""}`,onClick:()=>o({[e.id]:!0}),children:[t.jsx(un,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(zt,{size:18}),"No"]})]})]})]})]})]}),t.jsx("div",{className:"planning-actions",children:t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:u,disabled:!d(),children:["Continue",t.jsx(dr,{size:16,className:"icon-ml-4"})]})})]})}function JN({summary:e,historyEntries:n,onSummaryChange:s,onApply:i,onCancel:r,isApplying:o}){const[l,c]=a.useState(e),[u,d]=a.useState(!0),m=(h,g)=>{const p={...l,[h]:g};c(p),s(p)};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ms,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-panel",children:[t.jsx("div",{className:"planning-summary-header",children:t.jsxs("button",{className:"planning-summary-toggle",onClick:()=>d(!u),"aria-expanded":u,children:[u?t.jsx(qt,{size:16}):t.jsx(mn,{size:16}),t.jsx("span",{children:"Refined Scope"})]})}),u&&t.jsxs("div",{className:"planning-summary-content",children:[l.description&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:l.description,onChange:h=>m("description",h.target.value)})]}),l.planningNotes&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Planning Notes"}),t.jsx("textarea",{rows:3,value:l.planningNotes,onChange:h=>m("planningNotes",h.target.value)})]}),l.verification&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Verification Criteria"}),t.jsx("textarea",{rows:2,value:l.verification,onChange:h=>m("verification",h.target.value)})]}),!l.description&&!l.planningNotes&&!l.verification&&t.jsx("p",{className:"text-muted planning-summary-empty",children:"No additional details were generated for this item."})]})]})]}),t.jsxs("div",{className:"planning-view-footer",children:[t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:i,disabled:o,children:[o?t.jsx(rt,{size:16,className:"spin"}):null,"Apply"]}),t.jsx("button",{className:"btn",onClick:r,disabled:o,children:"Cancel"})]})]})}const _a={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)"}},Tu={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)"}},Pu={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)"}},Ir={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)"}},$r={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)"}},Dr={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)"}},Iu={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)"}},YN=3;function QN(e){return e==="completed"?"planned":e==="needs_update"?"needs_update":"not_started"}function $u({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 Du(e){return e?e.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const ol={title:"",description:"",status:"planning",autopilotEnabled:!1},ll={title:"",description:"",status:"planning",dependencies:[]},cl={title:"",description:"",status:"pending"},dl={title:"",description:"",acceptanceCriteria:"",status:"defined"},XN=3600*1e3;function uo(e){if(!e)return"—";const n=new Date(e).getTime();if(Number.isNaN(n))return"—";const s=Date.now()-n;if(s<0)return"just now";const i=Math.floor(s/(60*1e3));if(i<1)return"just now";if(i<60)return`${i}m ago`;const r=Math.floor(i/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function ZN(e){if(!e)return"healthy";const n=typeof e.lastErrorAt=="string"&&Date.now()-new Date(e.lastErrorAt).getTime()<=XN,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 e1(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 t1(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 ul(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 kp=["feature_triaged","feature_completed"],jp=["slice_activated","slice_completed","milestone_completed"],wp=["mission_started","mission_paused","mission_resumed","mission_completed"],Np=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function Lu(e,n){switch(n){case"errors":return e==="error"||e==="warning";case"state_changes":return wp.includes(e);case"tasks":return kp.includes(e);case"slices":return jp.includes(e);case"autopilot":return Np.includes(e);default:return!0}}function n1(e){return e==="error"||e==="warning"?"mission-event__type--error":wp.includes(e)?"mission-event__type--state":kp.includes(e)?"mission-event__type--task":jp.includes(e)?"mission-event__type--slice":Np.includes(e)?"mission-event__type--autopilot":"mission-event__type--default"}function s1(e){return e.replace(/_/g," ")}function i1(e,n){return n?e==="watching"?`Watching since ${uo(n)}`:`Last activation ${uo(n)}`:null}function a1({isOpen:e,isInline:n=!1,onClose:s,addToast:i,projectId:r,onSelectTask:o,availableTasks:l=[],resumeSessionId:c,targetMissionId:u,milestoneSliceResumeSessionId:d,onMilestoneSliceResumeFetchError:m}){const h=n||e,[g,p]=a.useState([]),[f,x]=a.useState(null),[v,b]=a.useState(!0),[y,S]=a.useState(!1),[k,M]=a.useState(!1),[w,_]=a.useState(null),[N,L]=a.useState(ol),[T,I]=a.useState(!1),[z,K]=a.useState(new Set),[P,E]=a.useState(new Set),[R,B]=a.useState(null),[G,X]=a.useState(ll),[C,$]=a.useState(!1),[A,j]=a.useState(null),[J,W]=a.useState(cl),[oe,he]=a.useState(!1),[se,fe]=a.useState(null),[U,Ne]=a.useState(null),[ee,ve]=a.useState(dl),[ue,ye]=a.useState(!1),[ie,Me]=a.useState(null),[ze,Be]=a.useState(null),[Je,Ye]=a.useState(""),[Ge,it]=a.useState(!1),[_e,Fe]=a.useState([]),[ae,be]=a.useState(void 0),ne=ae??c,[Ie,Pe]=a.useState(null),[ce,le]=a.useState(null),[$e,at]=a.useState(null);a.useEffect(()=>{h&&ne&&it(!0)},[h,ne]),a.useEffect(()=>{if(!h||ne)return;let O=!1;return Uc(r).then(Ce=>{if(O)return;const De=Ce.filter(ht=>ht.type==="mission_interview"&&(ht.status==="awaiting_input"||ht.status==="error"));Fe(De)}).catch(Ce=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",Ce)}),()=>{O=!0}},[h,r,ne]),a.useEffect(()=>{if(!h||!d)return;let O=!1;return ti(d).then(Ce=>{if(!(O||!Ce))try{const De=JSON.parse(Ce.inputPayload||"{}");De.targetId&&De.targetType&&Pe({type:De.targetType,id:De.targetId,title:De.targetTitle||Ce.title,resumeSessionId:d})}catch{Pe({type:"milestone",id:"",title:Ce.title,resumeSessionId:d})}}).catch(Ce=>{O||(console.warn("[MissionManager] Failed to fetch session for milestone/slice resume:",Ce),m?.())}),()=>{O=!0}},[h,d,m]);const[tt,V]=a.useState(null),[de,Z]=a.useState(new Map),[we,pe]=a.useState(null),[Te,Qe]=a.useState({title:"",assertion:"",status:"pending"}),[Ee,Re]=a.useState(!1),[Le,ct]=a.useState(null),[Se,mt]=a.useState(new Map),[gt,wt]=a.useState(new Set),[yt,kt]=a.useState(new Set),[Ct,Rt]=a.useState(null),[Ft,Ut]=a.useState(new Map),[St,Et]=a.useState(null),[It,Mt]=a.useState(null),[Kt,Ot]=a.useState(!0),[xe,st]=a.useState(new Set),[Ve,Y]=a.useState(new Map),[F,H]=a.useState(null),[ge,me]=a.useState(new Map),[We,dt]=a.useState(null),[_t,$t]=a.useState(new Map),[vn,kn]=a.useState(new Map),[Yt,En]=a.useState("structure"),[on,Mn]=a.useState([]),Vt=a.useRef([]),hn=a.useRef([]),ke=a.useRef(null),nt=a.useRef(null),tn=a.useRef("structure"),Pn=a.useRef("all"),[Nn,gn]=a.useState(!1),[nn,_n]=a.useState(0),[jn,Q]=a.useState("all"),[Oe,Xe]=a.useState(new Set),Ze=a.useRef(null),pt=a.useRef(null);hn.current=g,ke.current=f,nt.current=St,tn.current=Yt,Pn.current=jn;const Nt=a.useCallback((O="auto")=>{const Ce=pt.current;if(Ce&&typeof Ce.scrollIntoView=="function"){Ce.scrollIntoView({block:"end",behavior:O});return}const De=Ze.current;De&&(De.scrollTop=De.scrollHeight)},[]),At=a.useCallback(()=>{const O=Ze.current;return O?O.scrollHeight-O.scrollTop-O.clientHeight<=100:!0},[]),xn=a.useCallback(async O=>{if(O.length===0){kn(new Map);return}const Ce=await _k(r);kn(De=>{const ht=new Map(De);for(const[ln,Tt]of Object.entries(Ce))e1(Tt)&&ht.set(ln,Tt);return ht})},[r]),Qt=a.useCallback(async()=>{try{b(!0);const O=await Nk(r);p(O),xn(O)}catch(O){i(je(O)||"Failed to load missions","error")}finally{b(!1)}},[i,r,xn]),bt=a.useCallback(async O=>{try{S(!0);const Ce=await tp(O,r);if(x(Ce),Ce.milestones.length>0){const De=Ce.milestones[0].id;Et(De),Ot(!0),K(new Set([De])),Jo(De,r).then(ht=>{Z(ln=>{const Tt=new Map(ln);return Tt.set(De,ht),Tt})}).catch(()=>{}),Yo(De,r).then(ht=>{Ut(ln=>{const Tt=new Map(ln);return Tt.set(De,ht),Tt})}).catch(()=>{}),Ce.milestones[0].slices.length>0&&E(new Set([Ce.milestones[0].slices[0].id]))}else Et(null),Mt(null)}catch(Ce){i(je(Ce)||"Failed to load mission details","error")}finally{S(!1)}},[i,r]);a.useEffect(()=>{if(!h||!St){Mt(null);return}let O=!1;return Mt(null),Wd(St,r).then(Ce=>{if(!O){if(!ul(Ce)){Mt(null);return}Mt(Ce),Ut(De=>{const ht=new Map(De);return ht.set(St,Ce.rollup),ht})}}).catch(()=>{O||Mt(null)}),()=>{O=!0}},[h,St,r]),a.useEffect(()=>{Ot(!0)},[St]);const Kn=a.useCallback(O=>{!O||O!==nt.current||Wd(O,r).then(Ce=>{nt.current!==O||!ul(Ce)||(Mt(Ce),Ut(De=>{const ht=new Map(De);return ht.set(O,Ce.rollup),ht}))}).catch(()=>{})},[r]),re=a.useCallback(async(O,Ce)=>{const De=Ce?.append??!1,ht=De?Vt.current.length:0;De||(gn(!0),Xe(new Set));try{const ln=await Mk(O,{limit:50,offset:ht,eventType:void 0},r),Tt=ln.events.filter(Gt=>Lu(Gt.eventType,jn));Mn(Gt=>{if(!De)return Tt;const He=new Set(Gt.map(ft=>ft.id)),qe=[...Gt];for(const ft of Tt)He.has(ft.id)||qe.push(ft);return qe}),_n(ln.total),De||requestAnimationFrame(()=>{Nt("auto")})}catch(ln){i(je(ln)||"Failed to load mission activity","error")}finally{De||gn(!1)}},[i,jn,r,Nt]);a.useEffect(()=>{Vt.current=on},[on]),a.useEffect(()=>{h&&(Qt(),x(null),Et(null),Mt(null),Mn([]),_n(0),En("structure"),Q("all"),Xe(new Set))},[h,Qt]);const Ae=a.useRef(null);a.useEffect(()=>{h&&u&&Ae.current!==u&&g.length>0&&(Ae.current=u,bt(u))},[h,u,g,bt]),a.useEffect(()=>{h||(Ae.current=null)},[h]),a.useEffect(()=>{!h||!f||Yt!=="activity"||re(f.id)},[Yt,h,re,f,jn]),a.useEffect(()=>{if(!h||typeof EventSource>"u")return;const O=new URLSearchParams;r&&O.set("projectId",r);const Ce=`/api/events${O.size>0?`?${O.toString()}`:""}`,De=()=>{xn(hn.current)},ht=Fn=>{De();const bn=Fn;if(bn.data)try{const Lt=JSON.parse(bn.data);Lt?.id&&p(ji=>ji.map(js=>js.id===Lt.id?{...js,...Lt}:js))}catch{}ke.current&&bt(ke.current.id)},ln=Fn=>{De(),ke.current&&bt(ke.current.id)},Tt=()=>{De(),ke.current&&bt(ke.current.id)},Gt=Fn=>{De(),ke.current&&bt(ke.current.id)},He=Fn=>{const bn=Fn;if(bn.data)try{const Lt=JSON.parse(bn.data);Lt&&Lt.featureId&&(Un(Lt.featureId),Bn(Lt.featureId),Lt.milestoneId&&Kn(Lt.milestoneId))}catch{}},qe=Fn=>{const bn=Fn;if(bn.data)try{const Lt=JSON.parse(bn.data);Lt&&Lt.featureId&&(Un(Lt.featureId),Bn(Lt.featureId),Lt.milestoneId&&Kn(Lt.milestoneId),ke.current&&bt(ke.current.id))}catch{}},ft=Fn=>{const bn=Fn;if(bn.data)try{const Lt=JSON.parse(bn.data);Lt&&Lt.milestoneId&&(ri(Lt.milestoneId),Kn(Lt.milestoneId))}catch{}},cn=Fn=>{const bn=Fn;if(bn.data)try{const Lt=JSON.parse(bn.data);Lt&&Lt.milestoneId&&(bi(Lt.milestoneId),ri(Lt.milestoneId),Kn(Lt.milestoneId))}catch{}};return $s(Ce,{events:{"mission:updated":ht,"slice:updated":ln,"feature:updated":Tt,"milestone:updated":Gt,"mission:event":Fn=>{De();const bn=ke.current;if(!bn||tn.current!=="activity")return;const Lt=At(),ji=Fn;if(ji.data)try{const js=JSON.parse(ji.data);if(!t1(js)||js.missionId!==bn.id||!Lu(js.eventType,Pn.current))return;Mn(Qs=>{const qo=Qs.filter(Vo=>Vo.id!==js.id);return[js,...qo].slice(0,100)}),_n(Qs=>Qs+1),Lt&&requestAnimationFrame(()=>{const Qs=Ze.current;Qs&&(Qs.scrollTop=0)})}catch{}},"validator-run:started":He,"validator-run:completed":qe,"milestone:validation:updated":ft,"assertion:created":cn,"assertion:updated":cn,"assertion:deleted":cn,"assertion:linked":cn,"assertion:unlinked":cn,"fix-feature:created":Fn=>{const bn=Fn;if(bn.data)try{const Lt=JSON.parse(bn.data);if(Lt&&Lt.sourceFeatureId){Un(Lt.sourceFeatureId);const ji=Lt?.feature?.sliceId,js=ke.current;if(ji&&js){const Qs=js.milestones.find(qo=>qo.slices.some(Vo=>Vo.id===ji));Qs&&Kn(Qs.id)}ke.current&&bt(ke.current.id)}}catch{}}}})},[h,At,bt,xn,r,Kn]);const lt=a.useCallback(()=>{M(!0),_(null),L(ol)},[]),vt=a.useCallback(O=>{_(O.id),M(!1),L({title:O.title,description:O.description||"",status:O.status,autopilotEnabled:O.autopilotEnabled??!1})},[]),xt=a.useCallback(()=>{_(null),M(!1),L(ol)},[]),Zt=a.useCallback(async()=>{if(!N.title.trim()){i("Mission title is required","error");return}try{if(I(!0),k)await Sk({title:N.title.trim(),description:N.description.trim()||void 0,autopilotEnabled:N.autopilotEnabled},r),i("Mission created","success");else if(w){const O={title:N.title.trim(),description:N.description.trim()||void 0,status:N.status,autopilotEnabled:N.autopilotEnabled};N.autopilotEnabled&&(O.autoAdvance=!0),await Ck(w,O,r),i("Mission updated","success"),f?.id===w&&await bt(w)}await Qt(),xt()}catch(O){i(je(O)||"Failed to save mission","error")}finally{I(!1)}},[N,k,w,i,Qt,bt,f,xt,r]),ot=a.useCallback(async O=>{try{await Ek(O,r),i("Mission deleted","success"),f?.id===O&&x(null),await Qt(),V(null)}catch(Ce){i(je(Ce)||"Failed to delete mission","error")}},[i,Qt,f,r]),Ht=a.useCallback(()=>{$(!0),B(null),X(ll)},[]),en=a.useCallback(O=>{B(O.id),$(!1),X({title:O.title,description:O.description||"",status:O.status,dependencies:O.dependencies})},[]),An=a.useCallback(()=>{B(null),$(!1),X(ll)},[]),yn=a.useCallback(async()=>{if(!G.title.trim()){i("Milestone title is required","error");return}try{I(!0),C&&f?(await Ak(f.id,{title:G.title.trim(),description:G.description.trim()||void 0,dependencies:G.dependencies},r),i("Milestone created","success")):R&&(await Rk(R,{title:G.title.trim(),description:G.description.trim()||void 0,status:G.status,dependencies:G.dependencies},r),i("Milestone updated","success")),await bt(f.id),An()}catch(O){i(je(O)||"Failed to save milestone","error")}finally{I(!1)}},[G,C,R,f,i,bt,An,N.title,r]),xs=a.useCallback(async O=>{try{await Tk(O,r),i("Milestone deleted","success"),await bt(f.id),V(null)}catch(Ce){i(je(Ce)||"Failed to delete milestone","error")}},[i,bt,f,r]),Gn=a.useCallback(O=>{Et(O),Ot(!0),K(Ce=>{const De=new Set(Ce);return!De.has(O)?(De.add(O),Jo(O,r).then(ln=>{Z(Tt=>{const Gt=new Map(Tt);return Gt.set(O,ln),Gt})}).catch(()=>{}),Yo(O,r).then(ln=>{Ut(Tt=>{const Gt=new Map(Tt);return Gt.set(O,ln),Gt})}).catch(()=>{})):De.delete(O),De})},[r]),ts=a.useCallback(O=>{fe(O),he(!0),j(null),W(cl)},[]),Jn=a.useCallback(O=>{j(O.id),he(!1),W({title:O.title,description:O.description||"",status:O.status})},[]),ns=a.useCallback(()=>{j(null),he(!1),fe(null),W(cl)},[]),Sn=a.useCallback(async()=>{if(!J.title.trim()){i("Slice title is required","error");return}try{I(!0),oe&&se?(await Pk(se,{title:J.title.trim(),description:J.description.trim()||void 0},r),i("Slice created","success")):A&&(await Ik(A,{title:J.title.trim(),description:J.description.trim()||void 0,status:J.status},r),i("Slice updated","success")),await bt(f.id),ns()}catch(O){i(je(O)||"Failed to save slice","error")}finally{I(!1)}},[J,oe,A,se,f,i,bt,ns,r]),ss=a.useCallback(async O=>{try{await $k(O,r),i("Slice deleted","success"),await bt(f.id),V(null)}catch(Ce){i(je(Ce)||"Failed to delete slice","error")}},[i,bt,f,r]),_s=a.useCallback(async O=>{try{await Dk(O,r),i("Slice activated","success"),await bt(f.id)}catch(Ce){i(je(Ce)||"Failed to activate slice","error")}},[i,bt,f,r]),Ys=a.useCallback(O=>{E(Ce=>{const De=new Set(Ce);return De.has(O)?De.delete(O):De.add(O),De})},[]),bs=a.useCallback(O=>{Me(O),ye(!0),Ne(null),ve(dl)},[]),On=a.useCallback(O=>{Ne(O.id),ye(!1),ve({title:O.title,description:O.description||"",acceptanceCriteria:O.acceptanceCriteria||"",status:O.status})},[]),cs=a.useCallback(()=>{Ne(null),ye(!1),Me(null),ve(dl)},[]),ds=a.useCallback(async()=>{if(!ee.title.trim()){i("Feature title is required","error");return}try{I(!0),ue&&ie?(await Lk(ie,{title:ee.title.trim(),description:ee.description.trim()||void 0,acceptanceCriteria:ee.acceptanceCriteria.trim()||void 0},r),i("Feature created","success")):U&&(await zk(U,{title:ee.title.trim(),description:ee.description.trim()||void 0,acceptanceCriteria:ee.acceptanceCriteria.trim()||void 0,status:ee.status},r),i("Feature updated","success")),await bt(f.id),cs()}catch(O){i(je(O)||"Failed to save feature","error")}finally{I(!1)}},[ee,ue,U,ie,f,i,bt,cs,r]),zo=a.useCallback(async O=>{try{await Fk(O,r),i("Feature deleted","success"),await bt(f.id),V(null)}catch(Ce){i(je(Ce)||"Failed to delete feature","error")}},[i,bt,f,r]),xi=a.useCallback(async()=>{if(!ze||!Je.trim()){i("Task ID is required","error");return}try{await Ok(ze,Je.trim(),r),i("Feature linked to task","success"),await bt(f.id),Be(null),Ye("")}catch(O){i(je(O)||"Failed to link feature to task","error")}},[ze,Je,i,bt,f,r]),ka=a.useCallback(async O=>{try{await Uk(O,r),i("Feature unlinked from task","success"),await bt(f.id)}catch(Ce){i(je(Ce)||"Failed to unlink feature","error")}},[i,bt,f,r]),Fi=a.useCallback(async O=>{try{I(!0),await Bk(O,void 0,void 0,r),i("Feature triaged — task created","success"),await bt(f.id)}catch(Ce){i(je(Ce)||"Failed to triage feature","error")}finally{I(!1)}},[i,bt,f,r]),Fo=a.useCallback(async O=>{at(O);try{const Ce=await xj(O,r);le({featureId:O,enrichedDescription:Ce.description})}catch{await Fi(O)}finally{at(null)}},[Fi,r]),jr=a.useCallback(async()=>{ce&&(le(null),await Fi(ce.featureId))},[Fi,ce]),wr=a.useCallback(()=>{le(null)},[]),Nr=a.useCallback(async O=>{try{I(!0);const Ce=await Hk(O,r);i(`Triaged ${Ce.count} feature${Ce.count!==1?"s":""}`,"success"),await bt(f.id)}catch(Ce){i(je(Ce)||"Failed to triage slice features","error")}finally{I(!1)}},[i,bt,f,r]),bi=a.useCallback(async O=>{try{const Ce=await Jo(O,r);Z(De=>{const ht=new Map(De);return ht.set(O,Ce),ht})}catch{}},[r]),ri=a.useCallback(async O=>{try{const Ce=await Yo(O,r);Ut(De=>{const ht=new Map(De);return ht.set(O,Ce),ht})}catch{}},[r]),Sr=a.useCallback(async O=>{if(!Te.title.trim()||!Te.assertion.trim()){i("Title and assertion text are required","error");return}try{I(!0),await qk(O,{title:Te.title.trim(),assertion:Te.assertion.trim(),status:Te.status},r),i("Assertion created","success"),await bi(O),await ri(O),Re(!1),Qe({title:"",assertion:"",status:"pending"})}catch(Ce){i(je(Ce)||"Failed to create assertion","error")}finally{I(!1)}},[Te,i,bi,ri,r]),vs=a.useCallback(O=>{pe(O.id),Qe({title:O.title,assertion:O.assertion,status:O.status})},[]),oi=a.useCallback(()=>{pe(null),Re(!1),Qe({title:"",assertion:"",status:"pending"})},[]),Oi=a.useCallback(async(O,Ce)=>{if(!Te.title.trim()||!Te.assertion.trim()){i("Title and assertion text are required","error");return}try{I(!0),await Vk(O,{title:Te.title.trim(),assertion:Te.assertion.trim(),status:Te.status},r),i("Assertion updated","success"),await bi(Ce),await ri(Ce),oi()}catch(De){i(je(De)||"Failed to update assertion","error")}finally{I(!1)}},[Te,i,bi,ri,oi,r]),Ds=a.useCallback(async O=>{try{const Ce=await Gk(O,r);mt(De=>{const ht=new Map(De);return ht.set(O,Ce),ht})}catch{}},[r]),ja=a.useCallback(async O=>{const Ce=Le!==O;ct(De=>De===O?null:O),Ce&&await Ds(O)},[Le,Ds]),te=a.useCallback(O=>{ct(O),Ds(O),requestAnimationFrame(()=>{const Ce=document.querySelector(`[data-mission-assertion-id="${O}"]`);Ce instanceof HTMLElement&&typeof Ce.scrollIntoView=="function"&&Ce.scrollIntoView({behavior:"smooth",block:"center"})})},[Ds]),Ke=a.useCallback(async(O,Ce)=>{try{wt(De=>new Set(De).add(Ce)),await Wk(O,Ce,r),i("Feature linked to assertion","success"),await Ds(Ce),Rt(null)}catch(De){i(je(De)||"Failed to link feature","error")}finally{wt(De=>{const ht=new Set(De);return ht.delete(Ce),ht})}},[i,Ds,r]),ut=a.useCallback(async(O,Ce)=>{const De=`${O}-${Ce}`;try{kt(ht=>new Set(ht).add(De)),await Kk(O,Ce,r),i("Feature unlinked from assertion","success"),await Ds(Ce)}catch(ht){i(je(ht)||"Failed to unlink feature","error")}finally{kt(ht=>{const ln=new Set(ht);return ln.delete(De),ln})}},[i,Ds,r]),Dt=a.useCallback(async O=>{try{st(De=>new Set(De).add(O)),await Jk(O,r),i("Validation triggered","success");const Ce=await Kd(O,r);Y(De=>{const ht=new Map(De);return ht.set(O,Ce),ht})}catch(Ce){i(je(Ce)||"Failed to trigger validation","error")}finally{st(Ce=>{const De=new Set(Ce);return De.delete(O),De})}},[i,r]),Un=a.useCallback(async O=>{try{const Ce=await Kd(O,r);Y(De=>{const ht=new Map(De);return ht.set(O,Ce),ht})}catch{}},[r]),Bn=a.useCallback(async O=>{try{const Ce=await Yk(O,{limit:10},r);me(De=>{const ht=new Map(De);return ht.set(O,Ce),ht})}catch{}},[r]),Ui=a.useCallback(O=>{const Ce=ke.current;if(Ce){for(const De of Ce.milestones)for(const ht of De.slices)if(ht.features.find(Tt=>Tt.id===O)){K(Tt=>{const Gt=new Set(Tt);return Gt.add(De.id),Gt}),E(Tt=>{const Gt=new Set(Tt);return Gt.add(ht.id),Gt}),H(O),Et(De.id),Un(O),Bn(O),requestAnimationFrame(()=>{const Tt=document.querySelector(`[data-mission-feature-id="${O}"]`);Tt instanceof HTMLElement&&typeof Tt.scrollIntoView=="function"&&Tt.scrollIntoView({behavior:"smooth",block:"center"})});return}}},[Un,Bn]),wa=a.useCallback(async O=>{try{const Ce=await Qk(O,r);$t(De=>{const ht=new Map(De);return ht.set(O,Ce),ht})}catch{}},[r]),Oo=a.useCallback(async O=>{F===O?H(null):(H(O),await Un(O),await Bn(O))},[F,Un,Bn]),Uo=a.useCallback(async O=>{We===O?dt(null):(dt(O),await wa(O))},[We,wa]),Cr=a.useCallback(async O=>{try{await Xk(O,r),i("Mission resumed","success"),await bt(O),Qt()}catch(Ce){i(je(Ce)||"Failed to resume mission","error")}},[i,bt,Qt,r]),Er=a.useCallback(async O=>{try{const De=(await Zk(O,r)).pausedTaskIds?.length??0;i(`Mission stopped (${De} task${De!==1?"s":""} paused)`,"success"),await bt(O),Qt()}catch(Ce){i(je(Ce)||"Failed to stop mission","error")}},[i,bt,Qt,r]),Mr=a.useCallback(async O=>{try{await ej(O,r),i("Mission started — first slice activated","success"),await bt(O),Qt()}catch(Ce){i(je(Ce)||"Failed to start mission","error")}},[i,bt,Qt,r]),Na=a.useCallback(async(O,Ce)=>{try{await tj(O,{enabled:Ce},r),i(Ce?"Autopilot enabled":"Autopilot disabled","success"),await bt(O),Qt()}catch(De){i(je(De)||"Failed to update autopilot","error")}},[i,bt,Qt,r]),Bi=a.useCallback(O=>{En("structure"),Et(null),Mt(null),Mn([]),_n(0),Q("all"),Xe(new Set),bt(O.id)},[bt]),Hi=a.useCallback(()=>{x(null),Et(null),Mt(null),En("structure"),Mn([]),_n(0),Q("all"),Xe(new Set),Qt()},[Qt]),vi=on.length<nn,yi=f?.autopilotState??"inactive",Bo=yi==="watching"||yi==="activating",ys=i1(yi,f?.lastAutopilotActivityAt),As=a.useMemo(()=>!It||!St||!ul(It)?null:It.rollup.milestoneId===St?It:null,[St,It]),Ls=a.useMemo(()=>{const O=new Map;for(const Ce of As?.validationTelemetry.validationRounds??[]){const De=O.get(Ce.featureId);(!De||Ce.startedAt>De.startedAt)&&O.set(Ce.featureId,Ce)}return O},[As]),zs=a.useCallback(()=>{!f||Nn||!vi||re(f.id,{append:!0})},[Nn,vi,re,f]),pd=a.useCallback(O=>{Xe(Ce=>{const De=new Set(Ce);return De.has(O)?De.delete(O):De.add(O),De})},[]),Ho=a.useCallback(O=>{O.key==="Enter"&&!O.shiftKey&&(O.preventDefault(),Zt())},[Zt]),fd=a.useCallback(O=>{O.key==="Enter"&&!O.shiftKey&&(O.preventDefault(),yn())},[yn]),gd=a.useCallback(O=>{O.key==="Enter"&&!O.shiftKey&&(O.preventDefault(),Sn())},[Sn]),xd=a.useCallback(O=>{O.key==="Enter"&&!O.shiftKey&&(O.preventDefault(),ds())},[ds]),ng=a.useRef(null);if(a.useEffect(()=>{if(!h)return;const O=Ce=>{Ce.key==="Escape"&&s()};return document.addEventListener("keydown",O),()=>document.removeEventListener("keydown",O)},[h,s]),!h)return null;const bd=t.jsxs("div",{ref:ng,className:`mission-manager${n?" mission-manager--inline":""}`,role:n?void 0:"dialog","aria-modal":n?void 0:!0,"aria-label":n?void 0:"Mission Manager","data-testid":"mission-manager-dialog",children:[t.jsxs("div",{className:`mission-manager__header${n?" mission-manager__header--inline":""}`,children:[t.jsxs("div",{className:"mission-manager__header-title",children:[f?t.jsx("button",{className:"mission-manager__back-btn",onClick:Hi,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:t.jsx(yo,{size:18})}):null,t.jsx(rs,{size:18,className:"mission-manager__header-icon"}),t.jsx("h2",{className:"mission-manager__title",children:f?f.title:"Missions"})]}),!n&&t.jsx("button",{className:"modal-close",onClick:s,title:"Close","aria-label":"Close Mission Manager","data-testid":"mission-close-btn",children:t.jsx(zt,{size:18})})]}),t.jsx("div",{className:"mission-manager__body",children:v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(rt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(rt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):f?t.jsxs("div",{className:"mission-detail",children:[t.jsxs("div",{className:"mission-detail__header",children:[t.jsxs("div",{className:"mission-detail__title-row",children:[t.jsxs("div",{className:"mission-detail__title-text",children:[Bo&&t.jsx("span",{className:"mission-detail__autopilot-dot",title:"Autopilot watching"}),t.jsx("h3",{className:"mission-detail__title",children:f.title})]}),t.jsx("span",{className:"mission-status-badge",style:{backgroundColor:(_a[f.status]||_a.planning).bg,color:(_a[f.status]||_a.planning).text},children:f.status})]}),f.description&&t.jsx("p",{className:"mission-detail__description",children:f.description}),t.jsx("div",{className:"mission-detail__meta",children:t.jsxs("span",{className:"mission-detail__meta-info",children:[f.milestones.length," milestones"]})}),t.jsxs("div",{className:"mission-detail__autopilot",children:[t.jsxs("div",{className:"mission-detail__autopilot-toggle",children:[t.jsxs("label",{className:"mission-toggle","data-testid":"mission-autopilot-toggle",children:[t.jsx("input",{type:"checkbox",checked:f.autopilotEnabled??!1,onChange:O=>Na(f.id,O.target.checked),"aria-label":"Autopilot"}),t.jsx("span",{className:"mission-toggle__track","aria-hidden":"true",children:t.jsx("span",{className:"mission-toggle__thumb"})}),t.jsxs("span",{className:"mission-toggle__label",children:[t.jsx(In,{size:14,className:"mission-detail__autopilot-icon"}),"Autopilot"]})]}),t.jsxs("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:($r[yi]||$r.inactive).bg,color:($r[yi]||$r.inactive).text},"data-testid":"autopilot-state-badge",children:[Bo&&t.jsx("span",{className:"mission-detail__autopilot-pulse"}),yi]})]}),ys&&t.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:ys})]}),t.jsxs("div",{className:"mission-detail__actions",children:[f.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Er(f.id),title:"Stop mission","aria-label":"Stop mission",children:t.jsx(ms,{size:14})}),f.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Cr(f.id),title:"Resume mission","aria-label":"Resume mission",children:t.jsx(fn,{size:14})}),f.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Mr(f.id),title:"Start mission","aria-label":"Start mission",children:t.jsx(fn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>vt(f),title:"Edit mission","aria-label":"Edit mission",children:t.jsx(Qn,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>V({type:"mission",id:f.id}),title:"Delete mission","aria-label":"Delete mission",children:t.jsx(Jt,{size:14})})]})]}),w===f.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:N.title,onChange:O=>L({...N,title:O.target.value}),onKeyDown:Ho,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:N.description,onChange:O=>L({...N,description:O.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:N.status,onChange:O=>L({...N,status:O.target.value}),children:[t.jsx("option",{value:"planning",children:"Planning"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"blocked",children:"Blocked"}),t.jsx("option",{value:"complete",children:"Complete"}),t.jsx("option",{value:"archived",children:"Archived"})]}),t.jsxs("label",{className:"mission-checkbox",children:[t.jsx("input",{type:"checkbox",checked:N.autopilotEnabled,onChange:O=>L({...N,autopilotEnabled:O.target.checked})}),t.jsx(In,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Zt,disabled:T,children:[T?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Rn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:xt,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-detail__tabs",role:"tablist","aria-label":"Mission detail tabs",children:[t.jsx("button",{className:`mission-btn ${Yt==="structure"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>En("structure"),role:"tab","aria-selected":Yt==="structure","data-testid":"mission-tab-structure",children:"Structure"}),t.jsxs("button",{className:`mission-btn ${Yt==="activity"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>En("activity"),role:"tab","aria-selected":Yt==="activity","data-testid":"mission-tab-activity",children:["Activity (",nn,")"]})]}),Yt==="structure"?t.jsxs("div",{className:"mission-detail__milestones",children:[f.milestones.map(O=>{const Ce=As?.rollup.milestoneId===O.id?As:null,De=Ce?.rollup??Ft.get(O.id),ht=Ce?.validationTelemetry.validationRounds??[],ln=Ce?.fixFeatures??[],Tt=Iu[De?.state??"not_started"]??Iu.not_started,Gt=De&&(De.state==="blocked"||De.state==="failed")?Ce?.validationTelemetry.validationRounds.find(He=>He.blockedReason)?.blockedReason:void 0;return t.jsxs("div",{className:"mission-milestone",children:[t.jsxs("div",{className:"mission-milestone__header",onClick:()=>Gn(O.id),children:[t.jsx("button",{className:"mission-milestone__expand",children:z.has(O.id)?t.jsx(qt,{size:16}):t.jsx(mn,{size:16})}),t.jsx(Ti,{size:16,className:"mission-milestone__icon"}),t.jsx("span",{className:"mission-milestone__title",children:O.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Tu[O.status].bg,color:Tu[O.status].text},children:O.status}),t.jsxs("span",{className:"mission-milestone__count",children:[O.slices.length," slices"]}),t.jsx($u,{state:QN(O.interviewState)}),De&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Tt.bg,color:Tt.text},title:"Validation state",children:Du(De.state)}),De.totalAssertions>0&&t.jsx("div",{className:"mission-milestone__coverage-bar",title:`${De.passedAssertions??0} of ${De.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-milestone__coverage-bar-fill",style:{width:`${(De.passedAssertions??0)/De.totalAssertions*100}%`,backgroundColor:(De.passedAssertions??0)===De.totalAssertions?"var(--color-success)":"var(--color-warning)"}})})]}),O.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Pe({type:"milestone",id:O.id,title:O.title}),title:"Plan milestone","aria-label":"Plan milestone",children:t.jsx(Ri,{size:14})}),t.jsxs("div",{className:"mission-milestone__actions",onClick:He=>He.stopPropagation(),children:[t.jsx("button",{className:"mission-icon-btn",onClick:()=>ts(O.id),title:"Add slice",children:t.jsx(Xt,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>en(O),title:"Edit milestone",children:t.jsx(Qn,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>V({type:"milestone",id:O.id}),title:"Delete milestone",children:t.jsx(Jt,{size:14})})]})]}),z.has(O.id)&&t.jsxs("div",{className:"mission-milestone__body",children:[(C||R===O.id)&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:G.title,onChange:He=>X({...G,title:He.target.value}),onKeyDown:fd,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:G.description,onChange:He=>X({...G,description:He.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:yn,disabled:T,children:[T?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Rn,{size:14}),R?"Update":"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:An,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}`:""]})]}),Gt&&t.jsxs("div",{className:"mission-blocked-reason",children:[t.jsx("strong",{children:"Blocked reason:"})," ",Gt]}),ht.length>0&&t.jsxs("div",{className:"mission-validation-rounds",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm mission-validation-rounds__toggle",onClick:()=>Ot(He=>!He),title:Kt?"Hide validation rounds":"Show validation rounds",children:[Kt?t.jsx(qt,{size:12}):t.jsx(mn,{size:12}),"Validation rounds (",ht.length,")"]}),Kt&&t.jsx("div",{className:"mission-validation-rounds__list",children:ht.map(He=>t.jsxs("div",{className:"mission-validation-round",children:[t.jsxs("div",{className:"mission-validation-round__header",children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-validation-round__status mission-validation-round__status--${He.validatorStatus}`,children:He.validatorStatus}),t.jsx("span",{className:"mission-validation-round__feature",children:He.featureTitle}),t.jsxs("span",{className:"mission-validation-round__attempts",children:["impl #",He.implementationAttempt," · reviewer #",He.validatorAttempt]})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),He.failedAssertionIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:He.failedAssertionIds.map(qe=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>te(qe),title:`Jump to assertion ${qe}`,children:qe},`${He.roundId}-${qe}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Generated fix features:"}),He.generatedFixFeatureIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:He.generatedFixFeatureIds.map(qe=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Ui(qe),title:`Jump to fix feature ${qe}`,children:qe},`${He.roundId}-${qe}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),He.blockedReason&&t.jsx("div",{className:"mission-validation-round__blocked-reason",children:He.blockedReason})]},He.roundId))})]}),ln.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:ln.map(He=>t.jsxs("div",{className:"mission-fix-feature",children:[t.jsxs("div",{className:"mission-fix-feature__header",children:[t.jsx("button",{className:"mission-fix-feature__title",onClick:()=>Ui(He.id),title:`Jump to feature ${He.id}`,children:He.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Ir[He.status].bg,color:Ir[He.status].text},children:He.status}),He.loopState&&t.jsx("span",{className:`mission-loop-state mission-loop-state--${He.loopState}`,children:He.loopState})]}),t.jsxs("div",{className:"mission-fix-feature__meta",children:[t.jsx("span",{children:"Source:"}),t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Ui(He.sourceFeatureId),title:`Jump to source feature ${He.sourceFeatureId}`,children:He.sourceFeatureId}),t.jsx("span",{children:"Run:"}),t.jsx("span",{className:"mission-fix-feature__run",children:He.runId})]}),He.failedAssertionIds.length>0&&t.jsxs("div",{className:"mission-fix-feature__assertions",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),t.jsx("div",{className:"mission-validation-round__chip-list",children:He.failedAssertionIds.map(qe=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>te(qe),title:`Jump to assertion ${qe}`,children:qe},`${He.id}-${qe}`))})]})]},He.id))})]})]}),t.jsxs("div",{className:"mission-slices",children:[O.slices.map(He=>t.jsxs("div",{className:"mission-slice",children:[t.jsxs("div",{className:"mission-slice__header",onClick:()=>Ys(He.id),children:[t.jsx("button",{className:"mission-slice__expand",children:P.has(He.id)?t.jsx(qt,{size:16}):t.jsx(mn,{size:16})}),t.jsx(rc,{size:16,className:"mission-slice__icon"}),t.jsx("span",{className:"mission-slice__title",children:He.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Pu[He.status].bg,color:Pu[He.status].text},children:He.status}),t.jsxs("span",{className:"mission-slice__count",children:[He.features?.length||0," features"]}),t.jsx($u,{state:He.planState??"not_started"}),He.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Pe({type:"slice",id:He.id,title:He.title}),title:"Plan slice","aria-label":"Plan slice",children:t.jsx(Ri,{size:14})}),t.jsxs("div",{className:"mission-slice__actions",onClick:qe=>qe.stopPropagation(),children:[He.status==="pending"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>_s(He.id),title:"Activate slice",children:t.jsx(fn,{size:14})}),He.status==="active"&&He.features?.some(qe=>qe.status==="defined")&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Nr(He.id),title:"Triage all features",disabled:T,children:T?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(In,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>bs(He.id),title:"Add feature",children:t.jsx(Xt,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Jn(He),title:"Edit slice",children:t.jsx(Qn,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>V({type:"slice",id:He.id}),title:"Delete slice",children:t.jsx(Jt,{size:14})})]})]}),P.has(He.id)&&t.jsxs("div",{className:"mission-slice__body",children:[oe&&se===O.id&&!A&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:J.title,onChange:qe=>W({...J,title:qe.target.value}),onKeyDown:gd,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:J.description,onChange:qe=>W({...J,description:qe.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Sn,disabled:T,children:[T?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Rn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ns,children:"Cancel"})]})]}),A===He.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:J.title,onChange:qe=>W({...J,title:qe.target.value}),onKeyDown:gd,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:J.description,onChange:qe=>W({...J,description:qe.target.value}),rows:2}),t.jsxs("select",{value:J.status,onChange:qe=>W({...J,status:qe.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:Sn,disabled:T,children:[T?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Rn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ns,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-features",children:[He.features?.map(qe=>t.jsxs("div",{className:"mission-feature","data-mission-feature-id":qe.id,children:[t.jsxs("div",{className:"mission-feature__header",children:[t.jsx("button",{className:"mission-feature__expand",onClick:()=>Oo(qe.id),title:F===qe.id?"Collapse details":"Expand to show run history",children:F===qe.id?t.jsx(qt,{size:14}):t.jsx(mn,{size:14})}),t.jsx(Zl,{size:14,className:"mission-feature__icon"}),t.jsx("span",{className:"mission-feature__title",children:qe.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Ir[qe.status].bg,color:Ir[qe.status].text},children:qe.status}),qe.loopState&&qe.loopState!=="idle"&&t.jsxs("span",{className:`mission-loop-state mission-loop-state--${qe.loopState}`,title:`Loop state: ${qe.loopState}`,children:[qe.loopState==="implementing"&&"⏳",qe.loopState==="validating"&&"🔄",qe.loopState==="needs_fix"&&"🔧",qe.loopState==="passed"&&"✅",qe.loopState==="blocked"&&"🚫"]}),qe.generatedFromFeatureId&&t.jsx("button",{className:"mission-feature__lineage",onClick:()=>Ui(qe.generatedFromFeatureId),title:`Generated from feature: ${qe.generatedFromFeatureId}`,children:"🔗 Fix"}),(qe.loopState==="validating"||qe.loopState==="needs_fix")&&(()=>{const ft=Ve.get(qe.id),cn=Ls.get(qe.id),ks=ft?.implementationAttemptCount??cn?.implementationAttempt??qe.implementationAttemptCount??0,ki=ft?.retryBudgetRemaining??Math.max(0,YN-ks);return t.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",ks," · ",ki," ",ki===1?"retry":"retries"," left"]})})(),qe.loopState==="implementing"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>Dt(qe.id),title:"Validate feature",disabled:xe.has(qe.id),children:xe.has(qe.id)?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Vn,{size:14})}),qe.taskId&&t.jsx("span",{className:"mission-feature__task-link",onClick:()=>o?.(qe.taskId),title:"Click to view task",children:qe.taskId}),t.jsxs("div",{className:"mission-feature__actions",children:[qe.status==="defined"&&!qe.taskId&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Fo(qe.id),title:"Triage — create task",disabled:T||$e===qe.id,children:$e===qe.id?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(In,{size:14})}),qe.taskId?t.jsx("button",{className:"mission-icon-btn",onClick:()=>ka(qe.id),title:"Unlink task",children:t.jsx(Nd,{size:14})}):qe.status!=="defined"?t.jsx("button",{className:"mission-icon-btn",onClick:()=>Be(qe.id),title:"Link to task",children:t.jsx(ia,{size:14})}):null,t.jsx("button",{className:"mission-icon-btn",onClick:()=>On(qe),title:"Edit feature",children:t.jsx(Qn,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>V({type:"feature",id:qe.id}),title:"Delete feature",children:t.jsx(Jt,{size:14})})]})]}),qe.description&&t.jsx("p",{className:"mission-feature__description",children:qe.description}),qe.acceptanceCriteria&&t.jsxs("p",{className:"mission-feature__criteria",children:[t.jsx("strong",{children:"Acceptance:"})," ",qe.acceptanceCriteria]}),ce?.featureId===qe.id&&t.jsxs("div",{className:"mission-triage-preview",children:[t.jsx("div",{className:"mission-triage-preview__header",children:"Enriched Description Preview"}),t.jsx("div",{className:"mission-triage-preview__content",children:ce.enrichedDescription}),t.jsxs("div",{className:"mission-triage-preview__actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:jr,disabled:T,children:[T?t.jsx(rt,{size:14,className:"spinner"}):null,"Create Task"]}),t.jsx("button",{className:"btn",onClick:wr,disabled:T,children:"Cancel"})]})]}),U===qe.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:ee.title,onChange:ft=>ve({...ee,title:ft.target.value}),onKeyDown:xd,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:ee.description,onChange:ft=>ve({...ee,description:ft.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:ee.acceptanceCriteria,onChange:ft=>ve({...ee,acceptanceCriteria:ft.target.value}),rows:2}),t.jsxs("select",{value:ee.status,onChange:ft=>ve({...ee,status:ft.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:ds,disabled:T,children:[T?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Rn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:cs,children:"Cancel"})]})]}),F===qe.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"})}),(ge.get(qe.id)??[]).map(ft=>t.jsxs("div",{className:"mission-run",children:[t.jsxs("div",{className:"mission-run__header",onClick:()=>Uo(ft.id),children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-run__status mission-run__status--${ft.status}`,title:ft.status,children:ft.status}),t.jsx("span",{className:"mission-run__time",children:new Date(ft.startedAt).toLocaleString()}),ft.completedAt&&t.jsxs("span",{className:"mission-run__duration",children:[Math.round((new Date(ft.completedAt).getTime()-new Date(ft.startedAt).getTime())/1e3),"s"]}),ft.triggerType&&t.jsx("span",{className:"mission-run__trigger",children:ft.triggerType}),t.jsx("button",{className:"mission-icon-btn",title:We===ft.id?"Hide details":"Show details",children:We===ft.id?t.jsx(qt,{size:12}):t.jsx(mn,{size:12})})]}),We===ft.id&&_t.get(ft.id)&&t.jsxs("div",{className:"mission-run__details",children:[ft.summary&&t.jsx("p",{className:"mission-run__summary",children:ft.summary}),ft.blockedReason&&t.jsxs("p",{className:"mission-run__blocked-reason",children:[t.jsx("strong",{children:"Blocked:"})," ",ft.blockedReason]}),_t.get(ft.id)?.failures&&_t.get(ft.id).failures.length>0&&t.jsxs("div",{className:"mission-run__failures",children:[t.jsx("span",{className:"mission-run__failures-title",children:"Failed Assertions:"}),_t.get(ft.id).failures.map(cn=>t.jsxs("div",{className:"mission-run__failure",children:[t.jsx("span",{className:"mission-run__failure-message",children:cn.message}),cn.expected&&t.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",cn.expected]}),cn.actual&&t.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",cn.actual]})]},cn.id))]}),(!_t.get(ft.id)?.failures||_t.get(ft.id).failures.length===0)&&t.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},ft.id)),(!ge.get(qe.id)||ge.get(qe.id).length===0)&&t.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},qe.id)),ue&&ie===He.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:ee.title,onChange:qe=>ve({...ee,title:qe.target.value}),onKeyDown:xd,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:ee.description,onChange:qe=>ve({...ee,description:qe.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:ee.acceptanceCriteria,onChange:qe=>ve({...ee,acceptanceCriteria:qe.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:ds,disabled:T,children:[T?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Rn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:cs,children:"Cancel"})]})]}),!ue&&(!He.features||He.features.length===0)&&t.jsxs("div",{className:"mission-manager__empty mission-features__empty",children:[t.jsx(Zl,{size:16}),t.jsx("span",{children:"No fix features generated."})]})]})]})]},He.id)),O.slices.length===0&&!oe&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(rc,{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"}),De&&t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Tt.bg,color:Tt.text},children:Du(De.state)}),De&&De.totalAssertions>0&&t.jsx("div",{className:"mission-assertions__coverage-bar",title:`${De.passedAssertions??0} of ${De.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-assertions__coverage-bar-fill",style:{width:`${(De.passedAssertions??0)/De.totalAssertions*100}%`,backgroundColor:(De.passedAssertions??0)===De.totalAssertions?"var(--color-success)":"var(--color-warning)"}})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>{Re(!0),pe(null),Qe({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:t.jsx(Xt,{size:14})})]}),Ee&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:Te.title,onChange:He=>Qe({...Te,title:He.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:Te.assertion,onChange:He=>Qe({...Te,assertion:He.target.value}),rows:2}),t.jsxs("select",{value:Te.status,onChange:He=>Qe({...Te,status:He.target.value}),children:[t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"passed",children:"Passed"}),t.jsx("option",{value:"failed",children:"Failed"}),t.jsx("option",{value:"blocked",children:"Blocked"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:()=>Sr(O.id),disabled:T,children:[T?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Rn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:oi,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-assertions__list",children:[(Array.isArray(de.get(O.id))?de.get(O.id):[]).map(He=>t.jsxs("div",{className:"mission-assertion","data-mission-assertion-id":He.id,children:[t.jsx("div",{className:"mission-assertion__header",children:we===He.id?t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:Te.title,onChange:qe=>Qe({...Te,title:qe.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text",value:Te.assertion,onChange:qe=>Qe({...Te,assertion:qe.target.value}),rows:2}),t.jsxs("select",{value:Te.status,onChange:qe=>Qe({...Te,status:qe.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:()=>Oi(He.id,O.id),disabled:T,children:[T?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Rn,{size:14}),"Save"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:oi,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(Dr[He.status]??Dr.pending).bg,color:(Dr[He.status]??Dr.pending).text},children:He.status}),t.jsx("span",{className:"mission-assertion__title",children:He.title}),(()=>{const ft=Se.get(He.id)?.length??0;return ft>0?t.jsxs("span",{className:"mission-assertion__linked-count",title:`${ft} linked feature${ft!==1?"s":""}`,children:["(",ft," linked)"]}):null})(),t.jsx("button",{className:"mission-icon-btn",onClick:()=>ja(He.id),title:"Toggle details",children:Le===He.id?t.jsx(qt,{size:14}):t.jsx(mn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>vs(He),title:"Edit assertion",children:t.jsx(Qn,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>V({type:"assertion",id:He.id}),title:"Delete assertion",children:t.jsx(Jt,{size:14})})]})}),Le===He.id&&t.jsxs("div",{className:"mission-assertion__body",children:[t.jsx("p",{className:"mission-assertion__text",children:He.assertion}),t.jsxs("div",{className:"mission-assertion__linked-features",children:[t.jsxs("div",{className:"mission-assertion__linked-features-header",children:[t.jsx("span",{className:"mission-assertion__linked-features-label",children:"Linked Features"}),t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:async()=>{Le!==He.id&&await ja(He.id),Rt(Ct===He.id?null:He.id)},title:"Link a feature",children:[t.jsx(ia,{size:12}),"Link Feature"]})]}),Ct===He.id&&t.jsx("div",{className:"mission-assertion__feature-picker",children:t.jsx("div",{className:"mission-assertion__feature-picker-dropdown",children:(()=>{const qe=new Set((Se.get(He.id)??[]).map(cn=>cn.id)),ft=[];return f?.milestones.forEach(cn=>cn.slices.forEach(ks=>ft.push(...ks.features.filter(ki=>!qe.has(ki.id))))),ft.length===0?t.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):ft.map(cn=>t.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>Ke(cn.id,He.id),disabled:gt.has(He.id),children:[t.jsx("span",{className:"mission-assertion__feature-picker-title",children:cn.title}),gt.has(He.id)&&t.jsx(rt,{size:12,className:"spinner"})]},cn.id))})()})}),(()=>{const qe=Se.get(He.id)??[];return qe.length===0?t.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):qe.map(ft=>{const cn=`${ft.id}-${He.id}`,ks=yt.has(cn);return t.jsxs("div",{className:"mission-assertion__linked-feature",children:[t.jsx("span",{className:"mission-assertion__linked-feature-title",children:ft.title}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ut(ft.id,He.id),disabled:ks,title:"Unlink feature",children:ks?t.jsx(rt,{size:12,className:"spinner"}):t.jsx(Nd,{size:12})})]},ft.id)})})()]})]})]},He.id)),(!de.get(O.id)||de.get(O.id)?.length===0)&&!Ee&&t.jsx("div",{className:"mission-manager__empty mission-assertions__empty",children:t.jsx("span",{children:"No assertions defined. Add one to define completion criteria."})})]})]})]})]})]},O.id)}),f&&!C&&R===null&&t.jsxs("button",{className:"mission-add-btn",onClick:Ht,children:[t.jsx(Xt,{size:16}),"Add Milestone"]}),C&&R===null&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:G.title,onChange:O=>X({...G,title:O.target.value}),onKeyDown:fd,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:G.description,onChange:O=>X({...G,description:O.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:yn,disabled:T,children:[T?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Rn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:An,children:"Cancel"})]})]}),f.milestones.length===0&&!C&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Ti,{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:jn,onChange:O=>Q(O.target.value),"data-testid":"mission-activity-filter",children:[t.jsx("option",{value:"all",children:"All events"}),t.jsx("option",{value:"errors",children:"Errors & warnings"}),t.jsx("option",{value:"state_changes",children:"State changes"}),t.jsx("option",{value:"tasks",children:"Task events"}),t.jsx("option",{value:"slices",children:"Slice & milestone events"}),t.jsx("option",{value:"autopilot",children:"Autopilot events"})]})]}),t.jsxs("span",{className:"mission-detail__activity-count",children:[on.length," of ",nn]})]}),!Nn&&vi&&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:zs,"data-testid":"mission-activity-load-more",children:"Load more"})}),Nn?t.jsxs("div",{className:"mission-manager__loading mission-detail__activity-loading",children:[t.jsx(rt,{size:18,className:"spinner"}),t.jsx("span",{children:"Loading mission activity..."})]}):on.length===0?t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Es,{size:18}),t.jsx("span",{children:"No events yet."})]}):t.jsxs("div",{ref:Ze,className:"mission-events","data-testid":"mission-activity-events",children:[on.map(O=>{const Ce=!!(O.metadata&&Object.keys(O.metadata).length>0),De=Oe.has(O.id);return t.jsxs("div",{className:"mission-event",children:[t.jsxs("div",{className:"mission-event__header",children:[t.jsx("span",{className:`mission-event__type ${n1(O.eventType)}`,children:s1(O.eventType)}),t.jsx("span",{className:"mission-event__time",children:uo(O.timestamp)})]}),t.jsx("p",{className:"mission-event__description",children:O.description}),t.jsx("span",{className:"mission-event__timestamp",children:new Date(O.timestamp).toLocaleString()}),Ce&&t.jsxs("div",{className:"mission-event__metadata",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>pd(O.id),"data-testid":`mission-event-metadata-${O.id}`,children:[De?"Hide":"Show"," metadata"]}),De&&t.jsx("pre",{className:"mission-event__metadata-content",children:JSON.stringify(O.metadata,null,2)})]})]},O.id)}),t.jsx("div",{ref:pt})]})]})]}):t.jsxs("div",{className:"mission-list",children:[k&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:N.title,onChange:O=>L({...N,title:O.target.value}),onKeyDown:Ho,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:N.description,onChange:O=>L({...N,description:O.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Zt,disabled:T,children:[T?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Rn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:xt,children:"Cancel"})]})]}),g.map(O=>{const Ce=O,De=f,ht=De&&De.id===Ce.id,ln=_a[Ce.status]||{bg:"",text:""},Tt=Ce.summary,Gt=vn.get(Ce.id),He=ZN(Gt),qe=!!(Tt&&(Tt.totalMilestones>0||Tt.totalFeatures>0)),ft=Gt?.totalTasks??0,cn=Gt?.tasksCompleted??0,ks=Gt?.tasksFailed??0,ki=Gt?.estimatedCompletionPercent??Tt?.progressPercent??0,Fn=qe||ft>0||ks>0||!!Gt?.lastActivityAt,bn=Ce.status==="active"&&(Gt?.currentMilestoneId||Gt?.currentSliceId)?"Current milestone/slice in progress":null;return t.jsxs("div",{className:`mission-list__item ${ht?"mission-list__item--selected":""}`,onClick:()=>Bi(O),children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(rs,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{className:"mission-list__item-title",children:Ce.title}),O.autopilotEnabled&&t.jsx("span",{title:"Autopilot enabled",children:t.jsx(In,{size:12,className:"mission-list__item-autopilot-icon"})}),t.jsx("span",{className:`mission-health-badge mission-health-badge--${He}`,"data-testid":`mission-health-badge-${Ce.id}`,"aria-label":`Mission health: ${He}`}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:ln.bg,color:ln.text},children:Ce.status})]}),Ce.description&&t.jsx("p",{className:"mission-list__item-description",children:Ce.description}),bn&&t.jsxs("p",{className:"mission-list__item-active-slice",children:["Active: ",bn]}),Fn&&t.jsxs("div",{className:"mission-list__item-summary",children:[qe&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"mission-list__item-stat",children:[Tt.completedMilestones,"/",Tt.totalMilestones," milestones"]}),t.jsxs("span",{className:"mission-list__item-stat",children:[Tt.completedFeatures,"/",Tt.totalFeatures," features"]})]}),t.jsxs("span",{className:"mission-list__item-stat","data-testid":`mission-task-stats-${Ce.id}`,children:[cn,"/",ft," tasks"]}),ks>0&&t.jsxs("button",{className:"mission-list__item-failed",onClick:Lt=>{Lt.stopPropagation(),Bi(O)},"data-testid":`mission-failed-${Ce.id}`,title:"View mission failures",children:[ks," failed"]}),t.jsxs("span",{className:"mission-relative-time","data-testid":`mission-last-activity-${Ce.id}`,children:["Activity ",uo(Gt?.lastActivityAt)]}),t.jsx("div",{className:`mission-list__item-progress mission-list__item-progress--${He}`,children:t.jsx("div",{className:"mission-list__item-progress-bar",style:{width:`${ki}%`}})})]})]}),t.jsxs("div",{className:"mission-list__item-actions",onClick:Lt=>Lt.stopPropagation(),children:[Ce.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Er(Ce.id),title:"Stop mission",children:t.jsx(ms,{size:14})}),Ce.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Cr(Ce.id),title:"Resume mission",children:t.jsx(fn,{size:14})}),Ce.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Mr(Ce.id),title:"Start mission",children:t.jsx(fn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>vt(O),title:"Edit mission",children:t.jsx(Qn,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>V({type:"mission",id:Ce.id}),title:"Delete mission",children:t.jsx(Jt,{size:14})})]})]},Ce.id)}),w&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:N.title,onChange:O=>L({...N,title:O.target.value}),onKeyDown:Ho,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:N.description,onChange:O=>L({...N,description:O.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:N.status,onChange:O=>L({...N,status:O.target.value}),children:[t.jsx("option",{value:"planning",children:"Planning"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"blocked",children:"Blocked"}),t.jsx("option",{value:"complete",children:"Complete"}),t.jsx("option",{value:"archived",children:"Archived"})]}),t.jsxs("label",{className:"mission-checkbox",children:[t.jsx("input",{type:"checkbox",checked:N.autopilotEnabled,onChange:O=>L({...N,autopilotEnabled:O.target.checked})}),t.jsx(In,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Zt,disabled:T,children:[T?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Rn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:xt,children:"Cancel"})]})]}),g.length===0&&!k&&t.jsxs("div",{className:"mission-manager__empty mission-manager__empty--large",children:[t.jsx(rs,{size:32}),t.jsx("span",{children:"No missions yet. Create one to start planning."})]}),!k&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[_e.length>0&&t.jsxs("div",{className:"mission-resume-prompt",children:[t.jsx(Zn,{size:16}),t.jsx("span",{children:_e.length===1?`Resume "${_e[0].title}"?`:`${_e.length} interview sessions pending`}),t.jsx("div",{style:{display:"flex",gap:"4px",marginLeft:"auto"},children:_e.map(O=>t.jsxs("button",{className:"mission-add-btn",onClick:()=>{be(O.id),it(!0),Fe([])},children:[O.status==="error"?t.jsx(wn,{size:14}):t.jsx(Vn,{size:14}),O.status==="error"?"Retry":"Resume"]},O.id))})]}),t.jsxs("div",{style:{display:"flex",gap:"8px"},children:[t.jsxs("button",{className:"mission-add-btn",onClick:()=>it(!0),children:[t.jsx(Vn,{size:16}),"Plan with AI"]}),t.jsxs("button",{className:"mission-add-btn",onClick:lt,children:[t.jsx(Xt,{size:16}),"New Mission"]})]})]})]})}),tt&&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 ",tt.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()=>{tt.type==="mission"?await ot(tt.id):tt.type==="milestone"?await xs(tt.id):tt.type==="slice"?await ss(tt.id):tt.type==="feature"&&await zo(tt.id)},children:"Delete"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>V(null),children:"Cancel"})]})]})}),ze&&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:Je,onChange:O=>Ye(O.target.value),autoFocus:!0}),l.length>0&&t.jsxs("div",{className:"mission-task-suggestions",children:[t.jsx("small",{children:"Or select:"}),t.jsx("div",{className:"mission-task-suggestions__list",children:l.slice(0,5).map(O=>t.jsxs("button",{className:"mission-task-suggestions__item",onClick:()=>Ye(O.id),children:[O.id,": ",O.title||"Untitled"]},O.id))})]}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--primary",onClick:xi,children:"Link"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>{Be(null),Ye("")},children:"Cancel"})]})]})})]}),vd=t.jsx(qN,{isOpen:Ge,onClose:()=>it(!1),onMissionCreated:()=>{Qt(),i("Mission created from AI interview","success")},projectId:r,resumeSessionId:ne}),yd=Ie?t.jsx(KN,{isOpen:!0,onClose:()=>Pe(null),onApplied:()=>{Pe(null),f&&bt(f.id)},targetType:Ie.type,targetId:Ie.id,targetTitle:Ie.title,missionContext:f?.title,projectId:r,resumeSessionId:Ie.resumeSessionId}):null;return n?t.jsxs(t.Fragment,{children:[bd,vd,yd]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mission-manager-overlay open",onClick:O=>O.target===O.currentTarget&&s(),"data-testid":"mission-manager-overlay",role:"dialog","aria-modal":"true",children:bd}),vd,yd]})}const Lr=2e3;function zu({recipient:e,replyContext:n,agents:s=[],projectId:i,onSend:r,onCancel:o,addToast:l,isLoadingAgents:c=!1}){const[u,d]=a.useState(e?.id??""),[m,h]=a.useState(e?.type??"agent"),[g,p]=a.useState(""),[f,x]=a.useState(!1),[v,b]=a.useState(null),y=u.trim()!==""&&g.trim().length>0&&g.length<=Lr,S=a.useCallback(async()=>{if(!(!y||f)){x(!0),b(null);try{const M=m==="agent"?"user-to-agent":"system";await Nj({toId:u.trim(),toType:m,content:g.trim(),type:M,...n?{metadata:{replyTo:{messageId:n.messageId}}}:{}},i),r()}catch(M){const w=je(M)||"Failed to send message";b(w),l?.(w,"error")}finally{x(!1)}}},[y,f,u,m,g,n,i,r,l]),k=a.useCallback(M=>{d(M),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(zt,{size:16})})]}),t.jsxs("div",{className:"message-composer-body",children:[!e&&t.jsxs("div",{className:"message-composer-field",children:[t.jsx("label",{className:"message-composer-label",htmlFor:"message-recipient",children:"To:"}),t.jsxs("select",{id:"message-recipient",className:"message-composer-select",value:u,onChange:M=>k(M.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(M=>t.jsx("option",{value:M.id,children:M.name||M.id},M.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(pn,{size:14}),e.id]})]}),n&&t.jsxs("div",{className:"message-composer-field","data-testid":"message-composer-reply-context",children:[t.jsx("span",{className:"message-composer-label",children:"Replying to:"}),t.jsx("span",{className:"message-composer-recipient-fixed",children:n.preview?.trim()?n.preview:`Message ${n.messageId}`})]}),t.jsxs("div",{className:"message-composer-field message-composer-field--content",children:[t.jsx("label",{className:"message-composer-label",htmlFor:"message-content",children:"Message:"}),t.jsx("textarea",{id:"message-content",className:"message-composer-textarea",placeholder:"Type your message…",value:g,onChange:M=>p(M.target.value),maxLength:Lr,rows:4,"data-testid":"message-composer-content"}),t.jsx("div",{className:"message-composer-charcount","data-testid":"message-composer-charcount",children:t.jsxs("span",{className:g.length>Lr?"over-limit":"",children:[g.length,"/",Lr]})})]}),v&&t.jsxs("div",{className:"message-composer-error","data-testid":"message-composer-error",children:[t.jsx(Zn,{size:14}),t.jsx("span",{children:v})]})]}),t.jsxs("div",{className:"message-composer-footer",children:[t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:o,"data-testid":"message-composer-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:S,disabled:!y||f,"data-testid":"message-composer-send",children:f?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:14,className:"spin"}),t.jsx("span",{children:"Sending…"})]}):t.jsxs(t.Fragment,{children:[t.jsx(Ei,{size:14}),t.jsx("span",{children:"Send"})]})})]})]})}function Gi(e){const n=new Date(e),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),o=Math.floor(i/36e5),l=Math.floor(i/864e5);return r<1?"Just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function r1(e,n,s){if(n==="user")return e==="dashboard"?"You":`User: ${e}`;if(n==="agent"){const i=s?.get(e)?.trim();return i?i===e?`Agent: ${e}`:`Agent: ${i} (${e})`:`Agent: ${e}`}return"System"}function o1(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 Fu(e,n=80){return e.length<=n?e:`${e.slice(0,n)}…`}function l1(e){const n=new Map;for(const s of e){const i=`${s.fromType}:${s.fromId}`,r=n.get(i);r?(r.messages.push(s),new Date(s.createdAt)>new Date(r.latestMessage.createdAt)&&(r.latestMessage=s),s.read||r.unreadCount++):n.set(i,{key:i,fromId:s.fromId,fromType:s.fromType,latestMessage:s,messages:[s],unreadCount:s.read?0:1})}return Array.from(n.values()).sort((s,i)=>new Date(i.latestMessage.createdAt).getTime()-new Date(s.latestMessage.createdAt).getTime())}function c1({projectId:e,addToast:n,onUnreadCountChange:s}){const[i,r]=a.useState("inbox"),[o,l]=a.useState(null),[c,u]=a.useState(null),[d,m]=a.useState(0),[h,g]=a.useState(!1),[p,f]=a.useState(null),[x,v]=a.useState([]),[b,y]=a.useState(!1),[S,k]=a.useState(null),[M,w]=a.useState(null),[_,N]=a.useState(null),[L,T]=a.useState("inbox"),[I,z]=a.useState(null),[K,P]=a.useState([]),E=a.useMemo(()=>new Map(K.map(ie=>[ie.id,ie.name??""])),[K]),R=a.useCallback((ie,Me)=>r1(ie,Me,E),[E]),G=br()==="mobile",X=!G,C=a.useCallback(async()=>{g(!0);try{const ie=await jj({limit:50},e);l(ie),m(ie.unreadCount),s?.(ie.unreadCount)}catch{}finally{g(!1)}},[e,s]),$=a.useCallback(async()=>{g(!0);try{const ie=await wj({limit:50},e);u(ie)}catch{}finally{g(!1)}},[e]),A=a.useCallback(async ie=>{g(!0);try{const Me=await _j(ie,e);z(Me)}catch{}finally{g(!1)}},[e]),j=a.useCallback(async()=>{try{const ie=await xa(void 0,e);P(ie)}catch{}},[e]),J=a.useCallback(async()=>{try{const ie=await ip(e);m(ie.unreadCount),s?.(ie.unreadCount)}catch{}},[e,s]);a.useEffect(()=>{i==="inbox"?C():i==="outbox"?$():i==="agents"&&j()},[i,C,$,j]),a.useEffect(()=>{_&&A(_)},[_,A]),a.useEffect(()=>{J()},[J]),a.useEffect(()=>{j()},[j]),a.useEffect(()=>{if(typeof EventSource>"u")return;const ie=e?`?projectId=${encodeURIComponent(e)}`:"",Me=()=>{J(),i==="inbox"?C():i==="outbox"&&$(),_&&A(_)};return $s(`/api/events${ie}`,{events:{"message:sent":Me,"message:received":Me,"message:read":Me,"message:deleted":Me}})},[e,i,_,J,C,$,A]);const W=a.useCallback(async ie=>{if(f(ie),!ie.read)try{const Me=await Sj(ie.id,e);Me&&l(Be=>Be&&{...Be,messages:Be.messages.map(Je=>Je.id===Me.id?Me:Je),unreadCount:Math.max(0,Be.unreadCount-1)});const ze=Math.max(0,d-1);m(ze),s?.(ze)}catch{}try{const Me=await Mj(ie.fromId,ie.fromType,e);v(Me)}catch{v([ie])}},[e,d,s]),oe=a.useCallback(()=>{f(null),v([])},[]),he=a.useCallback(async()=>{try{const ie=await Cj(e);m(0),s?.(0),l(Me=>Me&&{...Me,messages:Me.messages.map(ze=>({...ze,read:!0})),unreadCount:0}),n?.(`Marked ${ie.markedAsRead} messages as read`,"success")}catch{n?.("Failed to mark messages as read","error")}},[e,n,s]),se=a.useCallback(async ie=>{try{await Ej(ie,e),f(null),v([]),i==="inbox"?C():i==="outbox"?$():_&&A(_),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[e,i,_,C,$,A,n]),fe=a.useCallback(ie=>{k({id:ie.fromId,type:ie.fromType}),w({messageId:ie.id,preview:Fu(ie.content,120)}),y(!0)},[]),U=a.useCallback(()=>{y(!1),k(null),w(null),n?.("Message sent","success"),i==="outbox"?$():i==="agents"&&_&&A(_),J()},[i,$,_,A,n,J]),Ne=a.useCallback(()=>{k(i==="agents"&&_?{id:_,type:"agent"}:null),w(null),y(!0)},[i,_]),ee=a.useCallback(()=>{y(!1),k(null),w(null)},[]),ve=()=>!p||b?null:t.jsxs("div",{className:"mailbox-message-detail","data-testid":"mailbox-message-detail",children:[t.jsxs("div",{className:"mailbox-message-detail-header",children:[G&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:oe,"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:o1(p.type)}),t.jsx("span",{className:"mailbox-message-time",children:Gi(p.createdAt)})]}),t.jsxs("div",{className:"mailbox-message-detail-actions",children:[p.fromType==="agent"&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>fe(p),"data-testid":"mailbox-reply",children:[t.jsx(ui,{size:14}),t.jsx("span",{children:"Reply"})]}),t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>se(p.id),"data-testid":"mailbox-delete",children:[t.jsx(Jt,{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(pn,{size:14}):t.jsx(qi,{size:14}),R(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(pn,{size:14}):t.jsx(qi,{size:14}),R(p.toId,p.toType)]})]})]}),x.length>1&&t.jsxs("div",{className:"mailbox-conversation","data-testid":"mailbox-conversation",children:[t.jsx("div",{className:"mailbox-conversation-label",children:"Conversation"}),x.map(ie=>{const Me=ie.metadata?.replyTo?.messageId,ze=Me?x.find(Be=>Be.id===Me):void 0;return t.jsxs("div",{className:`mailbox-conversation-msg ${ie.id===p.id?"current":""}`,children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:R(ie.fromId,ie.fromType)}),t.jsx("span",{className:"mailbox-message-time",children:Gi(ie.createdAt)})]}),Me&&t.jsxs("div",{className:"mailbox-reply-context","data-testid":`mailbox-reply-context-${ie.id}`,children:["↪ Replying to ",ze?Fu(ze.content,60):`message ${Me}`]}),t.jsx("div",{className:"mailbox-conversation-msg-body",children:ie.content})]},ie.id)})]}),x.length<=1&&t.jsxs(t.Fragment,{children:[p.metadata?.replyTo?.messageId&&t.jsxs("div",{className:"mailbox-reply-context","data-testid":"mailbox-selected-reply-context",children:["↪ Replying to message ",p.metadata.replyTo.messageId]}),t.jsx("div",{className:"mailbox-message-body","data-testid":"mailbox-message-body",children:p.content})]})]}),ue=()=>t.jsxs(t.Fragment,{children:[i==="inbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[h&&!o&&t.jsx(ml,{}),o&&o.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-inbox-empty",children:[t.jsx(Va,{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:l1(o.messages).map(ie=>t.jsxs("div",{className:`mailbox-conversation-group ${ie.unreadCount>0?"unread":""}`,onClick:()=>W(ie.latestMessage),"data-testid":`mailbox-conversation-${ie.key}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ie.fromType==="agent"?t.jsx(pn,{size:16}):t.jsx(qi,{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:R(ie.fromId,ie.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:Gi(ie.latestMessage.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ie.latestMessage.content.slice(0,80),ie.latestMessage.content.length>80?"…":""]})]}),ie.unreadCount>0&&t.jsx("div",{className:"mailbox-group-unread-badge","data-testid":`mailbox-unread-badge-${ie.key}`,children:ie.unreadCount>9?"9+":ie.unreadCount})]},ie.key))})]}),i==="outbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-outbox-list",children:[h&&!c&&t.jsx(ml,{}),c&&c.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-outbox-empty",children:[t.jsx(Ei,{size:32}),t.jsx("p",{children:"No sent messages"})]}),c?.messages.map(ie=>t.jsxs("div",{className:"mailbox-item",onClick:()=>W(ie),"data-testid":`mailbox-item-${ie.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ie.toType==="agent"?t.jsx(pn,{size:16}):t.jsx(qi,{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: ",R(ie.toId,ie.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:Gi(ie.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ie.content.slice(0,80),ie.content.length>80?"…":""]})]})]},ie.id))]}),i==="agents"&&t.jsx("div",{className:"mailbox-agents","data-testid":"mailbox-agents",children:K.length===0?t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(pn,{size:32}),t.jsx("p",{children:"No agents found"})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"mailbox-agents-header",children:[t.jsx("div",{className:"mailbox-agents-dropdown",children:t.jsxs("select",{className:"message-composer-select mailbox-agent-select",value:_??"",onChange:ie=>{N(ie.target.value||null),T("inbox")},"data-testid":"mailbox-agent-select",children:[t.jsx("option",{value:"",children:"Select an agent…"}),K.map(ie=>t.jsx("option",{value:ie.id,children:ie.name||ie.id},ie.id))]})}),t.jsxs("button",{className:"btn btn-sm btn-secondary mailbox-compose-btn",onClick:Ne,"data-testid":"mailbox-compose-btn",children:[t.jsx(ui,{size:14}),t.jsx("span",{children:"Compose"})]})]}),_&&t.jsxs("div",{className:"mailbox-agent-subtabs","data-testid":"mailbox-agent-subtabs",children:[t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${L==="inbox"?"active":""}`,onClick:()=>T("inbox"),"data-testid":"mailbox-agent-subtab-inbox",children:[t.jsx(Va,{size:12}),t.jsx("span",{children:"Inbox"}),I&&I.unreadCount>0&&t.jsx("span",{className:"mailbox-tab-badge",children:I.unreadCount})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${L==="outbox"?"active":""}`,onClick:()=>T("outbox"),"data-testid":"mailbox-agent-subtab-outbox",children:[t.jsx(Ei,{size:12}),t.jsx("span",{children:"Outbox"})]})]}),t.jsxs("div",{className:"mailbox-agents-content",children:[!_&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(pn,{size:32}),t.jsx("p",{children:"Select an agent to view their mailbox"})]}),_&&h&&!I&&t.jsx(ml,{}),_&&I&&L==="inbox"&&I.inbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Va,{size:32}),t.jsx("p",{children:"No received messages for this agent"})]}),_&&I&&L==="outbox"&&I.outbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Ei,{size:32}),t.jsx("p",{children:"No sent messages for this agent"})]}),_&&I&&L==="inbox"&&I.inbox.map(ie=>t.jsxs("div",{className:`mailbox-item ${ie.read?"":"unread"}`,onClick:()=>W(ie),"data-testid":`mailbox-item-${ie.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ie.fromType==="agent"?t.jsx(pn,{size:16}):t.jsx(qi,{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:R(ie.fromId,ie.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:Gi(ie.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ie.content.slice(0,80),ie.content.length>80?"…":""]})]})]},ie.id)),_&&I&&L==="outbox"&&I.outbox.map(ie=>t.jsxs("div",{className:"mailbox-item",onClick:()=>W(ie),"data-testid":`mailbox-item-${ie.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ie.toType==="agent"?t.jsx(pn,{size:16}):t.jsx(qi,{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: ",R(ie.toId,ie.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:Gi(ie.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ie.content.slice(0,80),ie.content.length>80?"…":""]})]})]},ie.id))]})]})})]}),ye=()=>b?t.jsx(zu,{recipient:S,replyContext:M,agents:K,projectId:e,onSend:U,onCancel:ee,addToast:n}):p?ve():t.jsxs("div",{className:"mailbox-split-empty","data-testid":"mailbox-split-empty",children:[t.jsx(aa,{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(aa,{size:18}),t.jsx("span",{children:"Mailbox"}),d>0&&t.jsx("span",{className:"mailbox-unread-badge","data-testid":"mailbox-unread-badge",children:d})]}),t.jsxs("div",{className:"mailbox-header-actions",children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:Ne,title:"Compose message","data-testid":"mailbox-header-compose",children:[t.jsx(ui,{size:14}),t.jsx("span",{children:"Compose"})]}),i==="inbox"&&d>0&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:he,title:"Mark all as read","data-testid":"mailbox-mark-all-read",children:[t.jsx(Ng,{size:14}),t.jsx("span",{children:"Mark all read"})]}),t.jsx("button",{className:"btn-icon",onClick:()=>{i==="inbox"?C():i==="outbox"?$():_&&A(_)},disabled:h,title:"Refresh","data-testid":"mailbox-refresh",children:h?t.jsx(rt,{size:14,className:"spin"}):t.jsx(wn,{size:14})})]})]}),t.jsxs("div",{className:"mailbox-tabs","data-testid":"mailbox-tabs",children:[t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="inbox"?"active":""}`,onClick:()=>{r("inbox"),f(null)},"data-testid":"mailbox-tab-inbox",children:[t.jsx(Va,{size:14}),t.jsx("span",{children:"Inbox"}),d>0&&t.jsx("span",{className:"mailbox-tab-badge",children:d})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="outbox"?"active":""}`,onClick:()=>{r("outbox"),f(null)},"data-testid":"mailbox-tab-outbox",children:[t.jsx(Ei,{size:14}),t.jsx("span",{children:"Outbox"})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="agents"?"active":""}`,onClick:()=>{r("agents"),f(null)},"data-testid":"mailbox-tab-agents",children:[t.jsx(pn,{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:ue()}),t.jsx("div",{className:"mailbox-split-detail-pane","data-testid":"mailbox-split-detail-pane",children:ye()})]}):t.jsxs(t.Fragment,{children:[ve(),b&&t.jsx(zu,{recipient:S,replyContext:M,agents:K,projectId:e,onSend:U,onCancel:ee,addToast:n}),!p&&!b&&ue()]})})]})}function ml(){return t.jsx("div",{className:"mailbox-skeleton","data-testid":"mailbox-skeleton",children:Array.from({length:5}).map((e,n)=>t.jsxs("div",{className:"mailbox-skeleton-item",children:[t.jsx("div",{className:"mailbox-skeleton-avatar"}),t.jsxs("div",{className:"mailbox-skeleton-content",children:[t.jsx("div",{className:"mailbox-skeleton-line mailbox-skeleton-line--short"}),t.jsx("div",{className:"mailbox-skeleton-line mailbox-skeleton-line--long"})]})]},n))})}function Gs(e,n,s){a.useEffect(()=>{if(!n)return;const i=e.current;if(!i)return;try{const u=localStorage.getItem(s);if(u){const{width:d,height:m}=JSON.parse(u);typeof d=="number"&&d>0&&(i.style.width=`${d}px`),typeof m=="number"&&m>0&&(i.style.height=`${m}px`)}}catch{}if(typeof ResizeObserver>"u")return;let r=i.offsetWidth,o=i.offsetHeight,l=null;const c=new ResizeObserver(()=>{const u=i.offsetWidth,d=i.offsetHeight;u===r&&d===o||(r=u,o=d,l&&clearTimeout(l),l=setTimeout(()=>{try{localStorage.setItem(s,JSON.stringify({width:u,height:d}))}catch{}},200))});return c.observe(i),()=>{c.disconnect(),l&&clearTimeout(l)}},[e,n,s])}function fi(e){const n=a.useRef(!1),s=a.useCallback(r=>{n.current=r.target===r.currentTarget},[]),i=a.useCallback(r=>{const o=n.current&&r.target===r.currentTarget;n.current=!1,o&&e()},[e]);return{onMouseDown:s,onMouseUp:i}}function d1(e,n){const s={};return(e[e.length-1]===""?[...e,""]:e).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const u1=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,m1=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,h1={};function Ou(e,n){return(h1.jsx?m1:u1).test(e)}const p1=/[ \t\n\f\r]/g;function f1(e){return typeof e=="object"?e.type==="text"?Uu(e.value):!1:Uu(e)}function Uu(e){return e.replace(p1,"")===""}class vr{constructor(n,s,i){this.normal=s,this.property=n,i&&(this.space=i)}}vr.prototype.normal={};vr.prototype.property={};vr.prototype.space=void 0;function Sp(e,n){const s={},i={};for(const r of e)Object.assign(s,r.property),Object.assign(i,r.normal);return new vr(s,i,n)}function bc(e){return e.toLowerCase()}class ls{constructor(n,s){this.attribute=s,this.property=n}}ls.prototype.attribute="";ls.prototype.booleanish=!1;ls.prototype.boolean=!1;ls.prototype.commaOrSpaceSeparated=!1;ls.prototype.commaSeparated=!1;ls.prototype.defined=!1;ls.prototype.mustUseProperty=!1;ls.prototype.number=!1;ls.prototype.overloadedBoolean=!1;ls.prototype.property="";ls.prototype.spaceSeparated=!1;ls.prototype.space=void 0;let g1=0;const Pt=zi(),Cn=zi(),vc=zi(),et=zi(),dn=zi(),na=zi(),us=zi();function zi(){return 2**++g1}const yc=Object.freeze(Object.defineProperty({__proto__:null,boolean:Pt,booleanish:Cn,commaOrSpaceSeparated:us,commaSeparated:na,number:et,overloadedBoolean:vc,spaceSeparated:dn},Symbol.toStringTag,{value:"Module"})),hl=Object.keys(yc);class Jc extends ls{constructor(n,s,i,r){let o=-1;if(super(n,s),Bu(this,"space",r),typeof i=="number")for(;++o<hl.length;){const l=hl[o];Bu(this,hl[o],(i&yc[l])===yc[l])}}}Jc.prototype.defined=!0;function Bu(e,n,s){s&&(e[n]=s)}function va(e){const n={},s={};for(const[i,r]of Object.entries(e.properties)){const o=new Jc(i,e.transform(e.attributes||{},i),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(i)&&(o.mustUseProperty=!0),n[i]=o,s[bc(i)]=i,s[bc(o.attribute)]=i}return new vr(n,s,e.space)}const Cp=va({properties:{ariaActiveDescendant:null,ariaAtomic:Cn,ariaAutoComplete:null,ariaBusy:Cn,ariaChecked:Cn,ariaColCount:et,ariaColIndex:et,ariaColSpan:et,ariaControls:dn,ariaCurrent:null,ariaDescribedBy:dn,ariaDetails:null,ariaDisabled:Cn,ariaDropEffect:dn,ariaErrorMessage:null,ariaExpanded:Cn,ariaFlowTo:dn,ariaGrabbed:Cn,ariaHasPopup:null,ariaHidden:Cn,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:dn,ariaLevel:et,ariaLive:null,ariaModal:Cn,ariaMultiLine:Cn,ariaMultiSelectable:Cn,ariaOrientation:null,ariaOwns:dn,ariaPlaceholder:null,ariaPosInSet:et,ariaPressed:Cn,ariaReadOnly:Cn,ariaRelevant:null,ariaRequired:Cn,ariaRoleDescription:dn,ariaRowCount:et,ariaRowIndex:et,ariaRowSpan:et,ariaSelected:Cn,ariaSetSize:et,ariaSort:null,ariaValueMax:et,ariaValueMin:et,ariaValueNow:et,ariaValueText:null,role:null},transform(e,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function Ep(e,n){return n in e?e[n]:n}function Mp(e,n){return Ep(e,n.toLowerCase())}const x1=va({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:na,acceptCharset:dn,accessKey:dn,action:null,allow:null,allowFullScreen:Pt,allowPaymentRequest:Pt,allowUserMedia:Pt,alt:null,as:null,async:Pt,autoCapitalize:null,autoComplete:dn,autoFocus:Pt,autoPlay:Pt,blocking:dn,capture:null,charSet:null,checked:Pt,cite:null,className:dn,cols:et,colSpan:null,content:null,contentEditable:Cn,controls:Pt,controlsList:dn,coords:et|na,crossOrigin:null,data:null,dateTime:null,decoding:null,default:Pt,defer:Pt,dir:null,dirName:null,disabled:Pt,download:vc,draggable:Cn,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:Pt,formTarget:null,headers:dn,height:et,hidden:vc,high:et,href:null,hrefLang:null,htmlFor:dn,httpEquiv:dn,id:null,imageSizes:null,imageSrcSet:null,inert:Pt,inputMode:null,integrity:null,is:null,isMap:Pt,itemId:null,itemProp:dn,itemRef:dn,itemScope:Pt,itemType:dn,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:Pt,low:et,manifest:null,max:null,maxLength:et,media:null,method:null,min:null,minLength:et,multiple:Pt,muted:Pt,name:null,nonce:null,noModule:Pt,noValidate:Pt,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:Pt,optimum:et,pattern:null,ping:dn,placeholder:null,playsInline:Pt,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:Pt,referrerPolicy:null,rel:dn,required:Pt,reversed:Pt,rows:et,rowSpan:et,sandbox:dn,scope:null,scoped:Pt,seamless:Pt,selected:Pt,shadowRootClonable:Pt,shadowRootDelegatesFocus:Pt,shadowRootMode:null,shape:null,size:et,sizes:null,slot:null,span:et,spellCheck:Cn,src:null,srcDoc:null,srcLang:null,srcSet:null,start:et,step:null,style:null,tabIndex:et,target:null,title:null,translate:null,type:null,typeMustMatch:Pt,useMap:null,value:Cn,width:et,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:dn,axis:null,background:null,bgColor:null,border:et,borderColor:null,bottomMargin:et,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:Pt,declare:Pt,event:null,face:null,frame:null,frameBorder:null,hSpace:et,leftMargin:et,link:null,longDesc:null,lowSrc:null,marginHeight:et,marginWidth:et,noResize:Pt,noHref:Pt,noShade:Pt,noWrap:Pt,object:null,profile:null,prompt:null,rev:null,rightMargin:et,rules:null,scheme:null,scrolling:Cn,standby:null,summary:null,text:null,topMargin:et,valueType:null,version:null,vAlign:null,vLink:null,vSpace:et,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:Pt,disableRemotePlayback:Pt,prefix:null,property:null,results:et,security:null,unselectable:null},space:"html",transform:Mp}),b1=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:us,accentHeight:et,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:et,amplitude:et,arabicForm:null,ascent:et,attributeName:null,attributeType:null,azimuth:et,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:et,by:null,calcMode:null,capHeight:et,className:dn,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:et,diffuseConstant:et,direction:null,display:null,dur:null,divisor:et,dominantBaseline:null,download:Pt,dx:null,dy:null,edgeMode:null,editable:null,elevation:et,enableBackground:null,end:null,event:null,exponent:et,externalResourcesRequired:null,fill:null,fillOpacity:et,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:na,g2:na,glyphName:na,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:et,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:et,horizOriginX:et,horizOriginY:et,id:null,ideographic:et,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:et,k:et,k1:et,k2:et,k3:et,k4:et,kernelMatrix:us,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:et,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:et,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:et,overlineThickness:et,paintOrder:null,panose1:null,path:null,pathLength:et,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:dn,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:et,pointsAtY:et,pointsAtZ:et,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:us,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:us,rev:us,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:us,requiredFeatures:us,requiredFonts:us,requiredFormats:us,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:et,specularExponent:et,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:et,strikethroughThickness:et,string:null,stroke:null,strokeDashArray:us,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:et,strokeOpacity:et,strokeWidth:null,style:null,surfaceScale:et,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:us,tabIndex:et,tableValues:null,target:null,targetX:et,targetY:et,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:us,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:et,underlineThickness:et,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:et,values:null,vAlphabetic:et,vMathematical:et,vectorEffect:null,vHanging:et,vIdeographic:et,version:null,vertAdvY:et,vertOriginX:et,vertOriginY:et,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:et,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Ep}),_p=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()}}),Ap=va({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Mp}),Rp=va({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,n){return"xml:"+n.slice(3).toLowerCase()}}),v1={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"},y1=/[A-Z]/g,Hu=/-[a-z]/g,k1=/^data[-\w.:]+$/i;function j1(e,n){const s=bc(n);let i=n,r=ls;if(s in e.normal)return e.property[e.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&k1.test(n)){if(n.charAt(4)==="-"){const o=n.slice(5).replace(Hu,N1);i="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=n.slice(4);if(!Hu.test(o)){let l=o.replace(y1,w1);l.charAt(0)!=="-"&&(l="-"+l),n="data"+l}}r=Jc}return new r(i,n)}function w1(e){return"-"+e.toLowerCase()}function N1(e){return e.charAt(1).toUpperCase()}const S1=Sp([Cp,x1,_p,Ap,Rp],"html"),Yc=Sp([Cp,b1,_p,Ap,Rp],"svg");function C1(e){return e.join(" ").trim()}var Ji={},pl,qu;function E1(){if(qu)return pl;qu=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,n=/\n/g,s=/^\s*/,i=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,r=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,l=/^[;\s]*/,c=/^\s+|\s+$/g,u=`
609
+ `,d="/",m="*",h="",g="comment",p="declaration";function f(v,b){if(typeof v!="string")throw new TypeError("First argument must be a string");if(!v)return[];b=b||{};var y=1,S=1;function k(P){var E=P.match(n);E&&(y+=E.length);var R=P.lastIndexOf(u);S=~R?P.length-R:S+P.length}function M(){var P={line:y,column:S};return function(E){return E.position=new w(P),L(),E}}function w(P){this.start=P,this.end={line:y,column:S},this.source=b.source}w.prototype.content=v;function _(P){var E=new Error(b.source+":"+y+":"+S+": "+P);if(E.reason=P,E.filename=b.source,E.line=y,E.column=S,E.source=v,!b.silent)throw E}function N(P){var E=P.exec(v);if(E){var R=E[0];return k(R),v=v.slice(R.length),E}}function L(){N(s)}function T(P){var E;for(P=P||[];E=I();)E!==!1&&P.push(E);return P}function I(){var P=M();if(!(d!=v.charAt(0)||m!=v.charAt(1))){for(var E=2;h!=v.charAt(E)&&(m!=v.charAt(E)||d!=v.charAt(E+1));)++E;if(E+=2,h===v.charAt(E-1))return _("End of comment missing");var R=v.slice(2,E-2);return S+=2,k(R),v=v.slice(E),S+=2,P({type:g,comment:R})}}function z(){var P=M(),E=N(i);if(E){if(I(),!N(r))return _("property missing ':'");var R=N(o),B=P({type:p,property:x(E[0].replace(e,h)),value:R?x(R[0].replace(e,h)):h});return N(l),B}}function K(){var P=[];T(P);for(var E;E=z();)E!==!1&&(P.push(E),T(P));return P}return L(),K()}function x(v){return v?v.replace(c,h):h}return pl=f,pl}var Vu;function M1(){if(Vu)return Ji;Vu=1;var e=Ji&&Ji.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Ji,"__esModule",{value:!0}),Ji.default=s;const n=e(E1());function s(i,r){let o=null;if(!i||typeof i!="string")return o;const l=(0,n.default)(i),c=typeof r=="function";return l.forEach(u=>{if(u.type!=="declaration")return;const{property:d,value:m}=u;c?r(d,m,u):m&&(o=o||{},o[d]=m)}),o}return Ji}var Aa={},Wu;function _1(){if(Wu)return Aa;Wu=1,Object.defineProperty(Aa,"__esModule",{value:!0}),Aa.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,n=/-([a-z])/g,s=/^[^-]+$/,i=/^-(webkit|moz|ms|o|khtml)-/,r=/^-(ms)-/,o=function(d){return!d||s.test(d)||e.test(d)},l=function(d,m){return m.toUpperCase()},c=function(d,m){return"".concat(m,"-")},u=function(d,m){return m===void 0&&(m={}),o(d)?d:(d=d.toLowerCase(),m.reactCompat?d=d.replace(r,c):d=d.replace(i,c),d.replace(n,l))};return Aa.camelCase=u,Aa}var Ra,Ku;function A1(){if(Ku)return Ra;Ku=1;var e=Ra&&Ra.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},n=e(M1()),s=_1();function i(r,o){var l={};return!r||typeof r!="string"||(0,n.default)(r,function(c,u){c&&u&&(l[(0,s.camelCase)(c,o)]=u)}),l}return i.default=i,Ra=i,Ra}var R1=A1();const T1=Eh(R1),Tp=Pp("end"),Qc=Pp("start");function Pp(e){return n;function n(s){const i=s&&s.position&&s.position[e]||{};if(typeof i.line=="number"&&i.line>0&&typeof i.column=="number"&&i.column>0)return{line:i.line,column:i.column,offset:typeof i.offset=="number"&&i.offset>-1?i.offset:void 0}}}function P1(e){const n=Qc(e),s=Tp(e);if(n&&s)return{start:n,end:s}}function Qa(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Gu(e.position):"start"in e||"end"in e?Gu(e):"line"in e||"column"in e?kc(e):""}function kc(e){return Ju(e&&e.line)+":"+Ju(e&&e.column)}function Gu(e){return kc(e&&e.start)+"-"+kc(e&&e.end)}function Ju(e){return e&&typeof e=="number"?e:1}class Wn extends Error{constructor(n,s,i){super(),typeof s=="string"&&(i=s,s=void 0);let r="",o={},l=!1;if(s&&("line"in s&&"column"in s?o={place:s}:"start"in s&&"end"in s?o={place:s}:"type"in s?o={ancestors:[s],place:s.position}:o={...s}),typeof n=="string"?r=n:!o.cause&&n&&(l=!0,r=n.message,o.cause=n),!o.ruleId&&!o.source&&typeof i=="string"){const u=i.indexOf(":");u===-1?o.ruleId=i:(o.source=i.slice(0,u),o.ruleId=i.slice(u+1))}if(!o.place&&o.ancestors&&o.ancestors){const u=o.ancestors[o.ancestors.length-1];u&&(o.place=u.position)}const c=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=c?c.column:void 0,this.fatal=void 0,this.file="",this.message=r,this.line=c?c.line:void 0,this.name=Qa(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}}Wn.prototype.file="";Wn.prototype.name="";Wn.prototype.reason="";Wn.prototype.message="";Wn.prototype.stack="";Wn.prototype.column=void 0;Wn.prototype.line=void 0;Wn.prototype.ancestors=void 0;Wn.prototype.cause=void 0;Wn.prototype.fatal=void 0;Wn.prototype.place=void 0;Wn.prototype.ruleId=void 0;Wn.prototype.source=void 0;const Xc={}.hasOwnProperty,I1=new Map,$1=/[A-Z]/g,D1=new Set(["table","tbody","thead","tfoot","tr"]),L1=new Set(["td","th"]),Ip="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function z1(e,n){if(!n||n.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const s=n.filePath||void 0;let i;if(n.development){if(typeof n.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");i=W1(s,n.jsxDEV)}else{if(typeof n.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof n.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");i=V1(s,n.jsx,n.jsxs)}const r={Fragment:n.Fragment,ancestors:[],components:n.components||{},create:i,elementAttributeNameCase:n.elementAttributeNameCase||"react",evaluater:n.createEvaluater?n.createEvaluater():void 0,filePath:s,ignoreInvalidStyle:n.ignoreInvalidStyle||!1,passKeys:n.passKeys!==!1,passNode:n.passNode||!1,schema:n.space==="svg"?Yc:S1,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},o=$p(r,e,void 0);return o&&typeof o!="string"?o:r.create(e,r.Fragment,{children:o||void 0},void 0)}function $p(e,n,s){if(n.type==="element")return F1(e,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return O1(e,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return B1(e,n,s);if(n.type==="mdxjsEsm")return U1(e,n);if(n.type==="root")return H1(e,n,s);if(n.type==="text")return q1(e,n)}function F1(e,n,s){const i=e.schema;let r=i;n.tagName.toLowerCase()==="svg"&&i.space==="html"&&(r=Yc,e.schema=r),e.ancestors.push(n);const o=Lp(e,n.tagName,!1),l=K1(e,n);let c=ed(e,n);return D1.has(n.tagName)&&(c=c.filter(function(u){return typeof u=="string"?!f1(u):!0})),Dp(e,l,o,n),Zc(l,c),e.ancestors.pop(),e.schema=i,e.create(n,o,l,s)}function O1(e,n){if(n.data&&n.data.estree&&e.evaluater){const i=n.data.estree.body[0];return i.type,e.evaluater.evaluateExpression(i.expression)}or(e,n.position)}function U1(e,n){if(n.data&&n.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(n.data.estree);or(e,n.position)}function B1(e,n,s){const i=e.schema;let r=i;n.name==="svg"&&i.space==="html"&&(r=Yc,e.schema=r),e.ancestors.push(n);const o=n.name===null?e.Fragment:Lp(e,n.name,!0),l=G1(e,n),c=ed(e,n);return Dp(e,l,o,n),Zc(l,c),e.ancestors.pop(),e.schema=i,e.create(n,o,l,s)}function H1(e,n,s){const i={};return Zc(i,ed(e,n)),e.create(n,e.Fragment,i,s)}function q1(e,n){return n.value}function Dp(e,n,s,i){typeof s!="string"&&s!==e.Fragment&&e.passNode&&(n.node=i)}function Zc(e,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(e.children=s)}}function V1(e,n,s){return i;function i(r,o,l,c){const d=Array.isArray(l.children)?s:n;return c?d(o,l,c):d(o,l)}}function W1(e,n){return s;function s(i,r,o,l){const c=Array.isArray(o.children),u=Qc(i);return n(r,o,l,c,{columnNumber:u?u.column-1:void 0,fileName:e,lineNumber:u?u.line:void 0},void 0)}}function K1(e,n){const s={};let i,r;for(r in n.properties)if(r!=="children"&&Xc.call(n.properties,r)){const o=J1(e,r,n.properties[r]);if(o){const[l,c]=o;e.tableCellAlignToStyle&&l==="align"&&typeof c=="string"&&L1.has(n.tagName)?i=c:s[l]=c}}if(i){const o=s.style||(s.style={});o[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=i}return s}function G1(e,n){const s={};for(const i of n.attributes)if(i.type==="mdxJsxExpressionAttribute")if(i.data&&i.data.estree&&e.evaluater){const o=i.data.estree.body[0];o.type;const l=o.expression;l.type;const c=l.properties[0];c.type,Object.assign(s,e.evaluater.evaluateExpression(c.argument))}else or(e,n.position);else{const r=i.name;let o;if(i.value&&typeof i.value=="object")if(i.value.data&&i.value.data.estree&&e.evaluater){const c=i.value.data.estree.body[0];c.type,o=e.evaluater.evaluateExpression(c.expression)}else or(e,n.position);else o=i.value===null?!0:i.value;s[r]=o}return s}function ed(e,n){const s=[];let i=-1;const r=e.passKeys?new Map:I1;for(;++i<n.children.length;){const o=n.children[i];let l;if(e.passKeys){const u=o.type==="element"?o.tagName:o.type==="mdxJsxFlowElement"||o.type==="mdxJsxTextElement"?o.name:void 0;if(u){const d=r.get(u)||0;l=u+"-"+d,r.set(u,d+1)}}const c=$p(e,o,l);c!==void 0&&s.push(c)}return s}function J1(e,n,s){const i=j1(e.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=i.commaSeparated?d1(s):C1(s)),i.property==="style"){let r=typeof s=="object"?s:Y1(e,String(s));return e.stylePropertyNameCase==="css"&&(r=Q1(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&i.space?v1[i.property]||i.property:i.attribute,s]}}function Y1(e,n){try{return T1(n,{reactCompat:!0})}catch(s){if(e.ignoreInvalidStyle)return{};const i=s,r=new Wn("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:i,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw r.file=e.filePath||void 0,r.url=Ip+"#cannot-parse-style-attribute",r}}function Lp(e,n,s){let i;if(!s)i={type:"Literal",value:n};else if(n.includes(".")){const r=n.split(".");let o=-1,l;for(;++o<r.length;){const c=Ou(r[o])?{type:"Identifier",name:r[o]}:{type:"Literal",value:r[o]};l=l?{type:"MemberExpression",object:l,property:c,computed:!!(o&&c.type==="Literal"),optional:!1}:c}i=l}else i=Ou(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(i.type==="Literal"){const r=i.value;return Xc.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(i);or(e)}function or(e,n){const s=new Wn("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:n,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw s.file=e.filePath||void 0,s.url=Ip+"#cannot-handle-mdx-estrees-without-createevaluater",s}function Q1(e){const n={};let s;for(s in e)Xc.call(e,s)&&(n[X1(s)]=e[s]);return n}function X1(e){let n=e.replace($1,Z1);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function Z1(e){return"-"+e.toLowerCase()}const fl={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"]},e0={};function td(e,n){const s=e0,i=typeof s.includeImageAlt=="boolean"?s.includeImageAlt:!0,r=typeof s.includeHtml=="boolean"?s.includeHtml:!0;return zp(e,i,r)}function zp(e,n,s){if(t0(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 Yu(e.children,n,s)}return Array.isArray(e)?Yu(e,n,s):""}function Yu(e,n,s){const i=[];let r=-1;for(;++r<e.length;)i[r]=zp(e[r],n,s);return i.join("")}function t0(e){return!!(e&&typeof e=="object")}const Qu=document.createElement("i");function nd(e){const n="&"+e+";";Qu.innerHTML=n;const s=Qu.textContent;return s.charCodeAt(s.length-1)===59&&e!=="semi"||s===n?!1:s}function fs(e,n,s,i){const r=e.length;let o=0,l;if(n<0?n=-n>r?0:r+n:n=n>r?r:n,s=s>0?s:0,i.length<1e4)l=Array.from(i),l.unshift(n,s),e.splice(...l);else for(s&&e.splice(n,s);o<i.length;)l=i.slice(o,o+1e4),l.unshift(n,0),e.splice(...l),o+=1e4,n+=1e4}function Ss(e,n){return e.length>0?(fs(e,e.length,0,n),e):n}const Xu={}.hasOwnProperty;function Fp(e){const n={};let s=-1;for(;++s<e.length;)n0(n,e[s]);return n}function n0(e,n){let s;for(s in n){const r=(Xu.call(e,s)?e[s]:void 0)||(e[s]={}),o=n[s];let l;if(o)for(l in o){Xu.call(r,l)||(r[l]=[]);const c=o[l];s0(r[l],Array.isArray(c)?c:c?[c]:[])}}}function s0(e,n){let s=-1;const i=[];for(;++s<n.length;)(n[s].add==="after"?e:i).push(n[s]);fs(e,0,0,i)}function Op(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 Ps(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Xn=gi(/[A-Za-z]/),qn=gi(/[\dA-Za-z]/),i0=gi(/[#-'*+\--9=?A-Z^-~]/);function mo(e){return e!==null&&(e<32||e===127)}const jc=gi(/\d/),a0=gi(/[\dA-Fa-f]/),r0=gi(/[!-/:-@[-`{-~]/);function jt(e){return e!==null&&e<-2}function rn(e){return e!==null&&(e<0||e===32)}function Bt(e){return e===-2||e===-1||e===32}const Po=gi(/\p{P}|\p{S}/u),Ii=gi(/\s/);function gi(e){return n;function n(s){return s!==null&&s>-1&&e.test(String.fromCharCode(s))}}function ya(e){const n=[];let s=-1,i=0,r=0;for(;++s<e.length;){const o=e.charCodeAt(s);let l="";if(o===37&&qn(e.charCodeAt(s+1))&&qn(e.charCodeAt(s+2)))r=2;else if(o<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(o))||(l=String.fromCharCode(o));else if(o>55295&&o<57344){const c=e.charCodeAt(s+1);o<56320&&c>56319&&c<57344?(l=String.fromCharCode(o,c),r=1):l="�"}else l=String.fromCharCode(o);l&&(n.push(e.slice(i,s),encodeURIComponent(l)),i=s+r+1,l=""),r&&(s+=r,r=0)}return n.join("")+e.slice(i)}function Wt(e,n,s,i){const r=i?i-1:Number.POSITIVE_INFINITY;let o=0;return l;function l(u){return Bt(u)?(e.enter(s),c(u)):n(u)}function c(u){return Bt(u)&&o++<r?(e.consume(u),c):(e.exit(s),n(u))}}const o0={tokenize:l0};function l0(e){const n=e.attempt(this.parser.constructs.contentInitial,i,r);let s;return n;function i(c){if(c===null){e.consume(c);return}return e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),Wt(e,n,"linePrefix")}function r(c){return e.enter("paragraph"),o(c)}function o(c){const u=e.enter("chunkText",{contentType:"text",previous:s});return s&&(s.next=u),s=u,l(c)}function l(c){if(c===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(c);return}return jt(c)?(e.consume(c),e.exit("chunkText"),o):(e.consume(c),l)}}const c0={tokenize:d0},Zu={tokenize:u0};function d0(e){const n=this,s=[];let i=0,r,o,l;return c;function c(S){if(i<s.length){const k=s[i];return n.containerState=k[1],e.attempt(k[0].continuation,u,d)(S)}return d(S)}function u(S){if(i++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,r&&y();const k=n.events.length;let M=k,w;for(;M--;)if(n.events[M][0]==="exit"&&n.events[M][1].type==="chunkFlow"){w=n.events[M][1].end;break}b(i);let _=k;for(;_<n.events.length;)n.events[_][1].end={...w},_++;return fs(n.events,M+1,0,n.events.slice(k)),n.events.length=_,d(S)}return c(S)}function d(S){if(i===s.length){if(!r)return g(S);if(r.currentConstruct&&r.currentConstruct.concrete)return f(S);n.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return n.containerState={},e.check(Zu,m,h)(S)}function m(S){return r&&y(),b(i),g(S)}function h(S){return n.parser.lazy[n.now().line]=i!==s.length,l=n.now().offset,f(S)}function g(S){return n.containerState={},e.attempt(Zu,p,f)(S)}function p(S){return i++,s.push([n.currentConstruct,n.containerState]),g(S)}function f(S){if(S===null){r&&y(),b(0),e.consume(S);return}return r=r||n.parser.flow(n.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:o}),x(S)}function x(S){if(S===null){v(e.exit("chunkFlow"),!0),b(0),e.consume(S);return}return jt(S)?(e.consume(S),v(e.exit("chunkFlow")),i=0,n.interrupt=void 0,c):(e.consume(S),x)}function v(S,k){const M=n.sliceStream(S);if(k&&M.push(null),S.previous=o,o&&(o.next=S),o=S,r.defineSkip(S.start),r.write(M),n.parser.lazy[S.start.line]){let w=r.events.length;for(;w--;)if(r.events[w][1].start.offset<l&&(!r.events[w][1].end||r.events[w][1].end.offset>l))return;const _=n.events.length;let N=_,L,T;for(;N--;)if(n.events[N][0]==="exit"&&n.events[N][1].type==="chunkFlow"){if(L){T=n.events[N][1].end;break}L=!0}for(b(i),w=_;w<n.events.length;)n.events[w][1].end={...T},w++;fs(n.events,N+1,0,n.events.slice(_)),n.events.length=w}}function b(S){let k=s.length;for(;k-- >S;){const M=s[k];n.containerState=M[1],M[0].exit.call(n,e)}s.length=S}function y(){r.write([null]),o=void 0,r=void 0,n.containerState._closeFlow=void 0}}function u0(e,n,s){return Wt(e,e.attempt(this.parser.constructs.document,n,s),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function ca(e){if(e===null||rn(e)||Ii(e))return 1;if(Po(e))return 2}function Io(e,n,s){const i=[];let r=-1;for(;++r<e.length;){const o=e[r].resolveAll;o&&!i.includes(o)&&(n=o(n,s),i.push(o))}return n}const wc={name:"attention",resolveAll:m0,tokenize:h0};function m0(e,n){let s=-1,i,r,o,l,c,u,d,m;for(;++s<e.length;)if(e[s][0]==="enter"&&e[s][1].type==="attentionSequence"&&e[s][1]._close){for(i=s;i--;)if(e[i][0]==="exit"&&e[i][1].type==="attentionSequence"&&e[i][1]._open&&n.sliceSerialize(e[i][1]).charCodeAt(0)===n.sliceSerialize(e[s][1]).charCodeAt(0)){if((e[i][1]._close||e[s][1]._open)&&(e[s][1].end.offset-e[s][1].start.offset)%3&&!((e[i][1].end.offset-e[i][1].start.offset+e[s][1].end.offset-e[s][1].start.offset)%3))continue;u=e[i][1].end.offset-e[i][1].start.offset>1&&e[s][1].end.offset-e[s][1].start.offset>1?2:1;const h={...e[i][1].end},g={...e[s][1].start};em(h,-u),em(g,u),l={type:u>1?"strongSequence":"emphasisSequence",start:h,end:{...e[i][1].end}},c={type:u>1?"strongSequence":"emphasisSequence",start:{...e[s][1].start},end:g},o={type:u>1?"strongText":"emphasisText",start:{...e[i][1].end},end:{...e[s][1].start}},r={type:u>1?"strong":"emphasis",start:{...l.start},end:{...c.end}},e[i][1].end={...l.start},e[s][1].start={...c.end},d=[],e[i][1].end.offset-e[i][1].start.offset&&(d=Ss(d,[["enter",e[i][1],n],["exit",e[i][1],n]])),d=Ss(d,[["enter",r,n],["enter",l,n],["exit",l,n],["enter",o,n]]),d=Ss(d,Io(n.parser.constructs.insideSpan.null,e.slice(i+1,s),n)),d=Ss(d,[["exit",o,n],["enter",c,n],["exit",c,n],["exit",r,n]]),e[s][1].end.offset-e[s][1].start.offset?(m=2,d=Ss(d,[["enter",e[s][1],n],["exit",e[s][1],n]])):m=0,fs(e,i-1,s-i+3,d),s=i+d.length-m-2;break}}for(s=-1;++s<e.length;)e[s][1].type==="attentionSequence"&&(e[s][1].type="data");return e}function h0(e,n){const s=this.parser.constructs.attentionMarkers.null,i=this.previous,r=ca(i);let o;return l;function l(u){return o=u,e.enter("attentionSequence"),c(u)}function c(u){if(u===o)return e.consume(u),c;const d=e.exit("attentionSequence"),m=ca(u),h=!m||m===2&&r||s.includes(u),g=!r||r===2&&m||s.includes(i);return d._open=!!(o===42?h:h&&(r||!g)),d._close=!!(o===42?g:g&&(m||!h)),n(u)}}function em(e,n){e.column+=n,e.offset+=n,e._bufferIndex+=n}const p0={name:"autolink",tokenize:f0};function f0(e,n,s){let i=0;return r;function r(p){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),o}function o(p){return Xn(p)?(e.consume(p),l):p===64?s(p):d(p)}function l(p){return p===43||p===45||p===46||qn(p)?(i=1,c(p)):d(p)}function c(p){return p===58?(e.consume(p),i=0,u):(p===43||p===45||p===46||qn(p))&&i++<32?(e.consume(p),c):(i=0,d(p))}function u(p){return p===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.exit("autolink"),n):p===null||p===32||p===60||mo(p)?s(p):(e.consume(p),u)}function d(p){return p===64?(e.consume(p),m):i0(p)?(e.consume(p),d):s(p)}function m(p){return qn(p)?h(p):s(p)}function h(p){return p===46?(e.consume(p),i=0,m):p===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.exit("autolink"),n):g(p)}function g(p){if((p===45||qn(p))&&i++<63){const f=p===45?g:h;return e.consume(p),f}return s(p)}}const yr={partial:!0,tokenize:g0};function g0(e,n,s){return i;function i(o){return Bt(o)?Wt(e,r,"linePrefix")(o):r(o)}function r(o){return o===null||jt(o)?n(o):s(o)}}const Up={continuation:{tokenize:b0},exit:v0,name:"blockQuote",tokenize:x0};function x0(e,n,s){const i=this;return r;function r(l){if(l===62){const c=i.containerState;return c.open||(e.enter("blockQuote",{_container:!0}),c.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(l),e.exit("blockQuoteMarker"),o}return s(l)}function o(l){return Bt(l)?(e.enter("blockQuotePrefixWhitespace"),e.consume(l),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),n):(e.exit("blockQuotePrefix"),n(l))}}function b0(e,n,s){const i=this;return r;function r(l){return Bt(l)?Wt(e,o,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l):o(l)}function o(l){return e.attempt(Up,n,s)(l)}}function v0(e){e.exit("blockQuote")}const Bp={name:"characterEscape",tokenize:y0};function y0(e,n,s){return i;function i(o){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(o),e.exit("escapeMarker"),r}function r(o){return r0(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),n):s(o)}}const Hp={name:"characterReference",tokenize:k0};function k0(e,n,s){const i=this;let r=0,o,l;return c;function c(h){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(h),e.exit("characterReferenceMarker"),u}function u(h){return h===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(h),e.exit("characterReferenceMarkerNumeric"),d):(e.enter("characterReferenceValue"),o=31,l=qn,m(h))}function d(h){return h===88||h===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(h),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),o=6,l=a0,m):(e.enter("characterReferenceValue"),o=7,l=jc,m(h))}function m(h){if(h===59&&r){const g=e.exit("characterReferenceValue");return l===qn&&!nd(i.sliceSerialize(g))?s(h):(e.enter("characterReferenceMarker"),e.consume(h),e.exit("characterReferenceMarker"),e.exit("characterReference"),n)}return l(h)&&r++<o?(e.consume(h),m):s(h)}}const tm={partial:!0,tokenize:w0},nm={concrete:!0,name:"codeFenced",tokenize:j0};function j0(e,n,s){const i=this,r={partial:!0,tokenize:M};let o=0,l=0,c;return u;function u(w){return d(w)}function d(w){const _=i.events[i.events.length-1];return o=_&&_[1].type==="linePrefix"?_[2].sliceSerialize(_[1],!0).length:0,c=w,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),m(w)}function m(w){return w===c?(l++,e.consume(w),m):l<3?s(w):(e.exit("codeFencedFenceSequence"),Bt(w)?Wt(e,h,"whitespace")(w):h(w))}function h(w){return w===null||jt(w)?(e.exit("codeFencedFence"),i.interrupt?n(w):e.check(tm,x,k)(w)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),g(w))}function g(w){return w===null||jt(w)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),h(w)):Bt(w)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),Wt(e,p,"whitespace")(w)):w===96&&w===c?s(w):(e.consume(w),g)}function p(w){return w===null||jt(w)?h(w):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),f(w))}function f(w){return w===null||jt(w)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),h(w)):w===96&&w===c?s(w):(e.consume(w),f)}function x(w){return e.attempt(r,k,v)(w)}function v(w){return e.enter("lineEnding"),e.consume(w),e.exit("lineEnding"),b}function b(w){return o>0&&Bt(w)?Wt(e,y,"linePrefix",o+1)(w):y(w)}function y(w){return w===null||jt(w)?e.check(tm,x,k)(w):(e.enter("codeFlowValue"),S(w))}function S(w){return w===null||jt(w)?(e.exit("codeFlowValue"),y(w)):(e.consume(w),S)}function k(w){return e.exit("codeFenced"),n(w)}function M(w,_,N){let L=0;return T;function T(E){return w.enter("lineEnding"),w.consume(E),w.exit("lineEnding"),I}function I(E){return w.enter("codeFencedFence"),Bt(E)?Wt(w,z,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(E):z(E)}function z(E){return E===c?(w.enter("codeFencedFenceSequence"),K(E)):N(E)}function K(E){return E===c?(L++,w.consume(E),K):L>=l?(w.exit("codeFencedFenceSequence"),Bt(E)?Wt(w,P,"whitespace")(E):P(E)):N(E)}function P(E){return E===null||jt(E)?(w.exit("codeFencedFence"),_(E)):N(E)}}}function w0(e,n,s){const i=this;return r;function r(l){return l===null?s(l):(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),o)}function o(l){return i.parser.lazy[i.now().line]?s(l):n(l)}}const gl={name:"codeIndented",tokenize:S0},N0={partial:!0,tokenize:C0};function S0(e,n,s){const i=this;return r;function r(d){return e.enter("codeIndented"),Wt(e,o,"linePrefix",5)(d)}function o(d){const m=i.events[i.events.length-1];return m&&m[1].type==="linePrefix"&&m[2].sliceSerialize(m[1],!0).length>=4?l(d):s(d)}function l(d){return d===null?u(d):jt(d)?e.attempt(N0,l,u)(d):(e.enter("codeFlowValue"),c(d))}function c(d){return d===null||jt(d)?(e.exit("codeFlowValue"),l(d)):(e.consume(d),c)}function u(d){return e.exit("codeIndented"),n(d)}}function C0(e,n,s){const i=this;return r;function r(l){return i.parser.lazy[i.now().line]?s(l):jt(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),r):Wt(e,o,"linePrefix",5)(l)}function o(l){const c=i.events[i.events.length-1];return c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?n(l):jt(l)?r(l):s(l)}}const E0={name:"codeText",previous:_0,resolve:M0,tokenize:A0};function M0(e){let n=e.length-4,s=3,i,r;if((e[s][1].type==="lineEnding"||e[s][1].type==="space")&&(e[n][1].type==="lineEnding"||e[n][1].type==="space")){for(i=s;++i<n;)if(e[i][1].type==="codeTextData"){e[s][1].type="codeTextPadding",e[n][1].type="codeTextPadding",s+=2,n-=2;break}}for(i=s-1,n++;++i<=n;)r===void 0?i!==n&&e[i][1].type!=="lineEnding"&&(r=i):(i===n||e[i][1].type==="lineEnding")&&(e[r][1].type="codeTextData",i!==r+2&&(e[r][1].end=e[i-1][1].end,e.splice(r+2,i-r-2),n-=i-r-2,i=r+2),r=void 0);return e}function _0(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function A0(e,n,s){let i=0,r,o;return l;function l(h){return e.enter("codeText"),e.enter("codeTextSequence"),c(h)}function c(h){return h===96?(e.consume(h),i++,c):(e.exit("codeTextSequence"),u(h))}function u(h){return h===null?s(h):h===32?(e.enter("space"),e.consume(h),e.exit("space"),u):h===96?(o=e.enter("codeTextSequence"),r=0,m(h)):jt(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),u):(e.enter("codeTextData"),d(h))}function d(h){return h===null||h===32||h===96||jt(h)?(e.exit("codeTextData"),u(h)):(e.consume(h),d)}function m(h){return h===96?(e.consume(h),r++,m):r===i?(e.exit("codeTextSequence"),e.exit("codeText"),n(h)):(o.type="codeTextData",d(h))}}class R0{constructor(n){this.left=n?[...n]:[],this.right=[]}get(n){if(n<0||n>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+n+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return n<this.left.length?this.left[n]:this.right[this.right.length-n+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(n,s){const i=s??Number.POSITIVE_INFINITY;return i<this.left.length?this.left.slice(n,i):n>this.left.length?this.right.slice(this.right.length-i+this.left.length,this.right.length-n+this.left.length).reverse():this.left.slice(n).concat(this.right.slice(this.right.length-i+this.left.length).reverse())}splice(n,s,i){const r=s||0;this.setCursor(Math.trunc(n));const o=this.right.splice(this.right.length-r,Number.POSITIVE_INFINITY);return i&&Ta(this.left,i),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(n){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(n)}pushMany(n){this.setCursor(Number.POSITIVE_INFINITY),Ta(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),Ta(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);Ta(this.right,s.reverse())}else{const s=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);Ta(this.left,s.reverse())}}}function Ta(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 qp(e){const n={};let s=-1,i,r,o,l,c,u,d;const m=new R0(e);for(;++s<m.length;){for(;s in n;)s=n[s];if(i=m.get(s),s&&i[1].type==="chunkFlow"&&m.get(s-1)[1].type==="listItemPrefix"&&(u=i[1]._tokenizer.events,o=0,o<u.length&&u[o][1].type==="lineEndingBlank"&&(o+=2),o<u.length&&u[o][1].type==="content"))for(;++o<u.length&&u[o][1].type!=="content";)u[o][1].type==="chunkText"&&(u[o][1]._isInFirstContentOfListItem=!0,o++);if(i[0]==="enter")i[1].contentType&&(Object.assign(n,T0(m,s)),s=n[s],d=!0);else if(i[1]._container){for(o=s,r=void 0;o--;)if(l=m.get(o),l[1].type==="lineEnding"||l[1].type==="lineEndingBlank")l[0]==="enter"&&(r&&(m.get(r)[1].type="lineEndingBlank"),l[1].type="lineEnding",r=o);else if(!(l[1].type==="linePrefix"||l[1].type==="listItemIndent"))break;r&&(i[1].end={...m.get(r)[1].start},c=m.slice(r,s),c.unshift(i),m.splice(r,s-r+1,c))}}return fs(e,0,Number.POSITIVE_INFINITY,m.slice(0)),!d}function T0(e,n){const s=e.get(n)[1],i=e.get(n)[2];let r=n-1;const o=[];let l=s._tokenizer;l||(l=i.parser[s.contentType](s.start),s._contentTypeTextTrailing&&(l._contentTypeTextTrailing=!0));const c=l.events,u=[],d={};let m,h,g=-1,p=s,f=0,x=0;const v=[x];for(;p;){for(;e.get(++r)[1]!==p;);o.push(r),p._tokenizer||(m=i.sliceStream(p),p.next||m.push(null),h&&l.defineSkip(p.start),p._isInFirstContentOfListItem&&(l._gfmTasklistFirstContentOfListItem=!0),l.write(m),p._isInFirstContentOfListItem&&(l._gfmTasklistFirstContentOfListItem=void 0)),h=p,p=p.next}for(p=s;++g<c.length;)c[g][0]==="exit"&&c[g-1][0]==="enter"&&c[g][1].type===c[g-1][1].type&&c[g][1].start.line!==c[g][1].end.line&&(x=g+1,v.push(x),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(l.events=[],p?(p._tokenizer=void 0,p.previous=void 0):v.pop(),g=v.length;g--;){const b=c.slice(v[g],v[g+1]),y=o.pop();u.push([y,y+b.length-1]),e.splice(y,2,b)}for(u.reverse(),g=-1;++g<u.length;)d[f+u[g][0]]=f+u[g][1],f+=u[g][1]-u[g][0]-1;return d}const P0={resolve:$0,tokenize:D0},I0={partial:!0,tokenize:L0};function $0(e){return qp(e),e}function D0(e,n){let s;return i;function i(c){return e.enter("content"),s=e.enter("chunkContent",{contentType:"content"}),r(c)}function r(c){return c===null?o(c):jt(c)?e.check(I0,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 L0(e,n,s){const i=this;return r;function r(l){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),Wt(e,o,"linePrefix")}function o(l){if(l===null||jt(l))return s(l);const c=i.events[i.events.length-1];return!i.parser.constructs.disable.null.includes("codeIndented")&&c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?n(l):e.interrupt(i.parser.constructs.flow,s,n)(l)}}function Vp(e,n,s,i,r,o,l,c,u){const d=u||Number.POSITIVE_INFINITY;let m=0;return h;function h(b){return b===60?(e.enter(i),e.enter(r),e.enter(o),e.consume(b),e.exit(o),g):b===null||b===32||b===41||mo(b)?s(b):(e.enter(i),e.enter(l),e.enter(c),e.enter("chunkString",{contentType:"string"}),x(b))}function g(b){return b===62?(e.enter(o),e.consume(b),e.exit(o),e.exit(r),e.exit(i),n):(e.enter(c),e.enter("chunkString",{contentType:"string"}),p(b))}function p(b){return b===62?(e.exit("chunkString"),e.exit(c),g(b)):b===null||b===60||jt(b)?s(b):(e.consume(b),b===92?f:p)}function f(b){return b===60||b===62||b===92?(e.consume(b),p):p(b)}function x(b){return!m&&(b===null||b===41||rn(b))?(e.exit("chunkString"),e.exit(c),e.exit(l),e.exit(i),n(b)):m<d&&b===40?(e.consume(b),m++,x):b===41?(e.consume(b),m--,x):b===null||b===32||b===40||mo(b)?s(b):(e.consume(b),b===92?v:x)}function v(b){return b===40||b===41||b===92?(e.consume(b),x):x(b)}}function Wp(e,n,s,i,r,o){const l=this;let c=0,u;return d;function d(p){return e.enter(i),e.enter(r),e.consume(p),e.exit(r),e.enter(o),m}function m(p){return c>999||p===null||p===91||p===93&&!u||p===94&&!c&&"_hiddenFootnoteSupport"in l.parser.constructs?s(p):p===93?(e.exit(o),e.enter(r),e.consume(p),e.exit(r),e.exit(i),n):jt(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||jt(p)||c++>999?(e.exit("chunkString"),m(p)):(e.consume(p),u||(u=!Bt(p)),p===92?g:h)}function g(p){return p===91||p===92||p===93?(e.consume(p),c++,h):h(p)}}function Kp(e,n,s,i,r,o){let l;return c;function c(g){return g===34||g===39||g===40?(e.enter(i),e.enter(r),e.consume(g),e.exit(r),l=g===40?41:g,u):s(g)}function u(g){return g===l?(e.enter(r),e.consume(g),e.exit(r),e.exit(i),n):(e.enter(o),d(g))}function d(g){return g===l?(e.exit(o),u(l)):g===null?s(g):jt(g)?(e.enter("lineEnding"),e.consume(g),e.exit("lineEnding"),Wt(e,d,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),m(g))}function m(g){return g===l||g===null||jt(g)?(e.exit("chunkString"),d(g)):(e.consume(g),g===92?h:m)}function h(g){return g===l||g===92?(e.consume(g),m):m(g)}}function Xa(e,n){let s;return i;function i(r){return jt(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),s=!0,i):Bt(r)?Wt(e,i,s?"linePrefix":"lineSuffix")(r):n(r)}}const z0={name:"definition",tokenize:O0},F0={partial:!0,tokenize:U0};function O0(e,n,s){const i=this;let r;return o;function o(p){return e.enter("definition"),l(p)}function l(p){return Wp.call(i,e,c,s,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function c(p){return r=Ps(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)),p===58?(e.enter("definitionMarker"),e.consume(p),e.exit("definitionMarker"),u):s(p)}function u(p){return rn(p)?Xa(e,d)(p):d(p)}function d(p){return Vp(e,m,s,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function m(p){return e.attempt(F0,h,h)(p)}function h(p){return Bt(p)?Wt(e,g,"whitespace")(p):g(p)}function g(p){return p===null||jt(p)?(e.exit("definition"),i.parser.defined.push(r),n(p)):s(p)}}function U0(e,n,s){return i;function i(c){return rn(c)?Xa(e,r)(c):s(c)}function r(c){return Kp(e,o,s,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function o(c){return Bt(c)?Wt(e,l,"whitespace")(c):l(c)}function l(c){return c===null||jt(c)?n(c):s(c)}}const B0={name:"hardBreakEscape",tokenize:H0};function H0(e,n,s){return i;function i(o){return e.enter("hardBreakEscape"),e.consume(o),r}function r(o){return jt(o)?(e.exit("hardBreakEscape"),n(o)):s(o)}}const q0={name:"headingAtx",resolve:V0,tokenize:W0};function V0(e,n){let s=e.length-2,i=3,r,o;return e[i][1].type==="whitespace"&&(i+=2),s-2>i&&e[s][1].type==="whitespace"&&(s-=2),e[s][1].type==="atxHeadingSequence"&&(i===s-1||s-4>i&&e[s-2][1].type==="whitespace")&&(s-=i+1===s?2:4),s>i&&(r={type:"atxHeadingText",start:e[i][1].start,end:e[s][1].end},o={type:"chunkText",start:e[i][1].start,end:e[s][1].end,contentType:"text"},fs(e,i,s-i+1,[["enter",r,n],["enter",o,n],["exit",o,n],["exit",r,n]])),e}function W0(e,n,s){let i=0;return r;function r(m){return e.enter("atxHeading"),o(m)}function o(m){return e.enter("atxHeadingSequence"),l(m)}function l(m){return m===35&&i++<6?(e.consume(m),l):m===null||rn(m)?(e.exit("atxHeadingSequence"),c(m)):s(m)}function c(m){return m===35?(e.enter("atxHeadingSequence"),u(m)):m===null||jt(m)?(e.exit("atxHeading"),n(m)):Bt(m)?Wt(e,c,"whitespace")(m):(e.enter("atxHeadingText"),d(m))}function u(m){return m===35?(e.consume(m),u):(e.exit("atxHeadingSequence"),c(m))}function d(m){return m===null||m===35||rn(m)?(e.exit("atxHeadingText"),c(m)):(e.consume(m),d)}}const K0=["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"],sm=["pre","script","style","textarea"],G0={concrete:!0,name:"htmlFlow",resolveTo:Q0,tokenize:X0},J0={partial:!0,tokenize:eS},Y0={partial:!0,tokenize:Z0};function Q0(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 X0(e,n,s){const i=this;let r,o,l,c,u;return d;function d(j){return m(j)}function m(j){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(j),h}function h(j){return j===33?(e.consume(j),g):j===47?(e.consume(j),o=!0,x):j===63?(e.consume(j),r=3,i.interrupt?n:C):Xn(j)?(e.consume(j),l=String.fromCharCode(j),v):s(j)}function g(j){return j===45?(e.consume(j),r=2,p):j===91?(e.consume(j),r=5,c=0,f):Xn(j)?(e.consume(j),r=4,i.interrupt?n:C):s(j)}function p(j){return j===45?(e.consume(j),i.interrupt?n:C):s(j)}function f(j){const J="CDATA[";return j===J.charCodeAt(c++)?(e.consume(j),c===J.length?i.interrupt?n:z:f):s(j)}function x(j){return Xn(j)?(e.consume(j),l=String.fromCharCode(j),v):s(j)}function v(j){if(j===null||j===47||j===62||rn(j)){const J=j===47,W=l.toLowerCase();return!J&&!o&&sm.includes(W)?(r=1,i.interrupt?n(j):z(j)):K0.includes(l.toLowerCase())?(r=6,J?(e.consume(j),b):i.interrupt?n(j):z(j)):(r=7,i.interrupt&&!i.parser.lazy[i.now().line]?s(j):o?y(j):S(j))}return j===45||qn(j)?(e.consume(j),l+=String.fromCharCode(j),v):s(j)}function b(j){return j===62?(e.consume(j),i.interrupt?n:z):s(j)}function y(j){return Bt(j)?(e.consume(j),y):T(j)}function S(j){return j===47?(e.consume(j),T):j===58||j===95||Xn(j)?(e.consume(j),k):Bt(j)?(e.consume(j),S):T(j)}function k(j){return j===45||j===46||j===58||j===95||qn(j)?(e.consume(j),k):M(j)}function M(j){return j===61?(e.consume(j),w):Bt(j)?(e.consume(j),M):S(j)}function w(j){return j===null||j===60||j===61||j===62||j===96?s(j):j===34||j===39?(e.consume(j),u=j,_):Bt(j)?(e.consume(j),w):N(j)}function _(j){return j===u?(e.consume(j),u=null,L):j===null||jt(j)?s(j):(e.consume(j),_)}function N(j){return j===null||j===34||j===39||j===47||j===60||j===61||j===62||j===96||rn(j)?M(j):(e.consume(j),N)}function L(j){return j===47||j===62||Bt(j)?S(j):s(j)}function T(j){return j===62?(e.consume(j),I):s(j)}function I(j){return j===null||jt(j)?z(j):Bt(j)?(e.consume(j),I):s(j)}function z(j){return j===45&&r===2?(e.consume(j),R):j===60&&r===1?(e.consume(j),B):j===62&&r===4?(e.consume(j),$):j===63&&r===3?(e.consume(j),C):j===93&&r===5?(e.consume(j),X):jt(j)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(J0,A,K)(j)):j===null||jt(j)?(e.exit("htmlFlowData"),K(j)):(e.consume(j),z)}function K(j){return e.check(Y0,P,A)(j)}function P(j){return e.enter("lineEnding"),e.consume(j),e.exit("lineEnding"),E}function E(j){return j===null||jt(j)?K(j):(e.enter("htmlFlowData"),z(j))}function R(j){return j===45?(e.consume(j),C):z(j)}function B(j){return j===47?(e.consume(j),l="",G):z(j)}function G(j){if(j===62){const J=l.toLowerCase();return sm.includes(J)?(e.consume(j),$):z(j)}return Xn(j)&&l.length<8?(e.consume(j),l+=String.fromCharCode(j),G):z(j)}function X(j){return j===93?(e.consume(j),C):z(j)}function C(j){return j===62?(e.consume(j),$):j===45&&r===2?(e.consume(j),C):z(j)}function $(j){return j===null||jt(j)?(e.exit("htmlFlowData"),A(j)):(e.consume(j),$)}function A(j){return e.exit("htmlFlow"),n(j)}}function Z0(e,n,s){const i=this;return r;function r(l){return jt(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),o):s(l)}function o(l){return i.parser.lazy[i.now().line]?s(l):n(l)}}function eS(e,n,s){return i;function i(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(yr,n,s)}}const tS={name:"htmlText",tokenize:nS};function nS(e,n,s){const i=this;let r,o,l;return c;function c(C){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(C),u}function u(C){return C===33?(e.consume(C),d):C===47?(e.consume(C),M):C===63?(e.consume(C),S):Xn(C)?(e.consume(C),N):s(C)}function d(C){return C===45?(e.consume(C),m):C===91?(e.consume(C),o=0,f):Xn(C)?(e.consume(C),y):s(C)}function m(C){return C===45?(e.consume(C),p):s(C)}function h(C){return C===null?s(C):C===45?(e.consume(C),g):jt(C)?(l=h,B(C)):(e.consume(C),h)}function g(C){return C===45?(e.consume(C),p):h(C)}function p(C){return C===62?R(C):C===45?g(C):h(C)}function f(C){const $="CDATA[";return C===$.charCodeAt(o++)?(e.consume(C),o===$.length?x:f):s(C)}function x(C){return C===null?s(C):C===93?(e.consume(C),v):jt(C)?(l=x,B(C)):(e.consume(C),x)}function v(C){return C===93?(e.consume(C),b):x(C)}function b(C){return C===62?R(C):C===93?(e.consume(C),b):x(C)}function y(C){return C===null||C===62?R(C):jt(C)?(l=y,B(C)):(e.consume(C),y)}function S(C){return C===null?s(C):C===63?(e.consume(C),k):jt(C)?(l=S,B(C)):(e.consume(C),S)}function k(C){return C===62?R(C):S(C)}function M(C){return Xn(C)?(e.consume(C),w):s(C)}function w(C){return C===45||qn(C)?(e.consume(C),w):_(C)}function _(C){return jt(C)?(l=_,B(C)):Bt(C)?(e.consume(C),_):R(C)}function N(C){return C===45||qn(C)?(e.consume(C),N):C===47||C===62||rn(C)?L(C):s(C)}function L(C){return C===47?(e.consume(C),R):C===58||C===95||Xn(C)?(e.consume(C),T):jt(C)?(l=L,B(C)):Bt(C)?(e.consume(C),L):R(C)}function T(C){return C===45||C===46||C===58||C===95||qn(C)?(e.consume(C),T):I(C)}function I(C){return C===61?(e.consume(C),z):jt(C)?(l=I,B(C)):Bt(C)?(e.consume(C),I):L(C)}function z(C){return C===null||C===60||C===61||C===62||C===96?s(C):C===34||C===39?(e.consume(C),r=C,K):jt(C)?(l=z,B(C)):Bt(C)?(e.consume(C),z):(e.consume(C),P)}function K(C){return C===r?(e.consume(C),r=void 0,E):C===null?s(C):jt(C)?(l=K,B(C)):(e.consume(C),K)}function P(C){return C===null||C===34||C===39||C===60||C===61||C===96?s(C):C===47||C===62||rn(C)?L(C):(e.consume(C),P)}function E(C){return C===47||C===62||rn(C)?L(C):s(C)}function R(C){return C===62?(e.consume(C),e.exit("htmlTextData"),e.exit("htmlText"),n):s(C)}function B(C){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),G}function G(C){return Bt(C)?Wt(e,X,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(C):X(C)}function X(C){return e.enter("htmlTextData"),l(C)}}const sd={name:"labelEnd",resolveAll:rS,resolveTo:oS,tokenize:lS},sS={tokenize:cS},iS={tokenize:dS},aS={tokenize:uS};function rS(e){let n=-1;const s=[];for(;++n<e.length;){const i=e[n][1];if(s.push(e[n]),i.type==="labelImage"||i.type==="labelLink"||i.type==="labelEnd"){const r=i.type==="labelImage"?4:2;i.type="data",n+=r}}return e.length!==s.length&&fs(e,0,e.length,s),e}function oS(e,n){let s=e.length,i=0,r,o,l,c;for(;s--;)if(r=e[s][1],o){if(r.type==="link"||r.type==="labelLink"&&r._inactive)break;e[s][0]==="enter"&&r.type==="labelLink"&&(r._inactive=!0)}else if(l){if(e[s][0]==="enter"&&(r.type==="labelImage"||r.type==="labelLink")&&!r._balanced&&(o=s,r.type!=="labelLink")){i=2;break}}else r.type==="labelEnd"&&(l=s);const u={type:e[o][1].type==="labelLink"?"link":"image",start:{...e[o][1].start},end:{...e[e.length-1][1].end}},d={type:"label",start:{...e[o][1].start},end:{...e[l][1].end}},m={type:"labelText",start:{...e[o+i+2][1].end},end:{...e[l-2][1].start}};return c=[["enter",u,n],["enter",d,n]],c=Ss(c,e.slice(o+1,o+i+3)),c=Ss(c,[["enter",m,n]]),c=Ss(c,Io(n.parser.constructs.insideSpan.null,e.slice(o+i+4,l-3),n)),c=Ss(c,[["exit",m,n],e[l-2],e[l-1],["exit",d,n]]),c=Ss(c,e.slice(l+1)),c=Ss(c,[["exit",u,n]]),fs(e,o,e.length,c),e}function lS(e,n,s){const i=this;let r=i.events.length,o,l;for(;r--;)if((i.events[r][1].type==="labelImage"||i.events[r][1].type==="labelLink")&&!i.events[r][1]._balanced){o=i.events[r][1];break}return c;function c(g){return o?o._inactive?h(g):(l=i.parser.defined.includes(Ps(i.sliceSerialize({start:o.end,end:i.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(g),e.exit("labelMarker"),e.exit("labelEnd"),u):s(g)}function u(g){return g===40?e.attempt(sS,m,l?m:h)(g):g===91?e.attempt(iS,m,l?d:h)(g):l?m(g):h(g)}function d(g){return e.attempt(aS,m,h)(g)}function m(g){return n(g)}function h(g){return o._balanced=!0,s(g)}}function cS(e,n,s){return i;function i(h){return e.enter("resource"),e.enter("resourceMarker"),e.consume(h),e.exit("resourceMarker"),r}function r(h){return rn(h)?Xa(e,o)(h):o(h)}function o(h){return h===41?m(h):Vp(e,l,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function l(h){return rn(h)?Xa(e,u)(h):m(h)}function c(h){return s(h)}function u(h){return h===34||h===39||h===40?Kp(e,d,s,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):m(h)}function d(h){return rn(h)?Xa(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 dS(e,n,s){const i=this;return r;function r(c){return Wp.call(i,e,o,l,"reference","referenceMarker","referenceString")(c)}function o(c){return i.parser.defined.includes(Ps(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)))?n(c):s(c)}function l(c){return s(c)}}function uS(e,n,s){return i;function i(o){return e.enter("reference"),e.enter("referenceMarker"),e.consume(o),e.exit("referenceMarker"),r}function r(o){return o===93?(e.enter("referenceMarker"),e.consume(o),e.exit("referenceMarker"),e.exit("reference"),n):s(o)}}const mS={name:"labelStartImage",resolveAll:sd.resolveAll,tokenize:hS};function hS(e,n,s){const i=this;return r;function r(c){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(c),e.exit("labelImageMarker"),o}function o(c){return c===91?(e.enter("labelMarker"),e.consume(c),e.exit("labelMarker"),e.exit("labelImage"),l):s(c)}function l(c){return c===94&&"_hiddenFootnoteSupport"in i.parser.constructs?s(c):n(c)}}const pS={name:"labelStartLink",resolveAll:sd.resolveAll,tokenize:fS};function fS(e,n,s){const i=this;return r;function r(l){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(l),e.exit("labelMarker"),e.exit("labelLink"),o}function o(l){return l===94&&"_hiddenFootnoteSupport"in i.parser.constructs?s(l):n(l)}}const xl={name:"lineEnding",tokenize:gS};function gS(e,n){return s;function s(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),Wt(e,n,"linePrefix")}}const Qr={name:"thematicBreak",tokenize:xS};function xS(e,n,s){let i=0,r;return o;function o(d){return e.enter("thematicBreak"),l(d)}function l(d){return r=d,c(d)}function c(d){return d===r?(e.enter("thematicBreakSequence"),u(d)):i>=3&&(d===null||jt(d))?(e.exit("thematicBreak"),n(d)):s(d)}function u(d){return d===r?(e.consume(d),i++,u):(e.exit("thematicBreakSequence"),Bt(d)?Wt(e,c,"whitespace")(d):c(d))}}const is={continuation:{tokenize:kS},exit:wS,name:"list",tokenize:yS},bS={partial:!0,tokenize:NS},vS={partial:!0,tokenize:jS};function yS(e,n,s){const i=this,r=i.events[i.events.length-1];let o=r&&r[1].type==="linePrefix"?r[2].sliceSerialize(r[1],!0).length:0,l=0;return c;function c(p){const f=i.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(f==="listUnordered"?!i.containerState.marker||p===i.containerState.marker:jc(p)){if(i.containerState.type||(i.containerState.type=f,e.enter(f,{_container:!0})),f==="listUnordered")return e.enter("listItemPrefix"),p===42||p===45?e.check(Qr,s,d)(p):d(p);if(!i.interrupt||p===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),u(p)}return s(p)}function u(p){return jc(p)&&++l<10?(e.consume(p),u):(!i.interrupt||l<2)&&(i.containerState.marker?p===i.containerState.marker:p===41||p===46)?(e.exit("listItemValue"),d(p)):s(p)}function d(p){return e.enter("listItemMarker"),e.consume(p),e.exit("listItemMarker"),i.containerState.marker=i.containerState.marker||p,e.check(yr,i.interrupt?s:m,e.attempt(bS,g,h))}function m(p){return i.containerState.initialBlankLine=!0,o++,g(p)}function h(p){return Bt(p)?(e.enter("listItemPrefixWhitespace"),e.consume(p),e.exit("listItemPrefixWhitespace"),g):s(p)}function g(p){return i.containerState.size=o+i.sliceSerialize(e.exit("listItemPrefix"),!0).length,n(p)}}function kS(e,n,s){const i=this;return i.containerState._closeFlow=void 0,e.check(yr,r,o);function r(c){return i.containerState.furtherBlankLines=i.containerState.furtherBlankLines||i.containerState.initialBlankLine,Wt(e,n,"listItemIndent",i.containerState.size+1)(c)}function o(c){return i.containerState.furtherBlankLines||!Bt(c)?(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,l(c)):(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,e.attempt(vS,n,l)(c))}function l(c){return i.containerState._closeFlow=!0,i.interrupt=void 0,Wt(e,e.attempt(is,n,s),"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function jS(e,n,s){const i=this;return Wt(e,r,"listItemIndent",i.containerState.size+1);function r(o){const l=i.events[i.events.length-1];return l&&l[1].type==="listItemIndent"&&l[2].sliceSerialize(l[1],!0).length===i.containerState.size?n(o):s(o)}}function wS(e){e.exit(this.containerState.type)}function NS(e,n,s){const i=this;return Wt(e,r,"listItemPrefixWhitespace",i.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function r(o){const l=i.events[i.events.length-1];return!Bt(o)&&l&&l[1].type==="listItemPrefixWhitespace"?n(o):s(o)}}const im={name:"setextUnderline",resolveTo:SS,tokenize:CS};function SS(e,n){let s=e.length,i,r,o;for(;s--;)if(e[s][0]==="enter"){if(e[s][1].type==="content"){i=s;break}e[s][1].type==="paragraph"&&(r=s)}else e[s][1].type==="content"&&e.splice(s,1),!o&&e[s][1].type==="definition"&&(o=s);const l={type:"setextHeading",start:{...e[i][1].start},end:{...e[e.length-1][1].end}};return e[r][1].type="setextHeadingText",o?(e.splice(r,0,["enter",l,n]),e.splice(o+1,0,["exit",e[i][1],n]),e[i][1].end={...e[o][1].end}):e[i][1]=l,e.push(["exit",l,n]),e}function CS(e,n,s){const i=this;let r;return o;function o(d){let m=i.events.length,h;for(;m--;)if(i.events[m][1].type!=="lineEnding"&&i.events[m][1].type!=="linePrefix"&&i.events[m][1].type!=="content"){h=i.events[m][1].type==="paragraph";break}return!i.parser.lazy[i.now().line]&&(i.interrupt||h)?(e.enter("setextHeadingLine"),r=d,l(d)):s(d)}function l(d){return e.enter("setextHeadingLineSequence"),c(d)}function c(d){return d===r?(e.consume(d),c):(e.exit("setextHeadingLineSequence"),Bt(d)?Wt(e,u,"lineSuffix")(d):u(d))}function u(d){return d===null||jt(d)?(e.exit("setextHeadingLine"),n(d)):s(d)}}const ES={tokenize:MS};function MS(e){const n=this,s=e.attempt(yr,i,e.attempt(this.parser.constructs.flowInitial,r,Wt(e,e.attempt(this.parser.constructs.flow,r,e.attempt(P0,r)),"linePrefix")));return s;function i(o){if(o===null){e.consume(o);return}return e.enter("lineEndingBlank"),e.consume(o),e.exit("lineEndingBlank"),n.currentConstruct=void 0,s}function r(o){if(o===null){e.consume(o);return}return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),n.currentConstruct=void 0,s}}const _S={resolveAll:Jp()},AS=Gp("string"),RS=Gp("text");function Gp(e){return{resolveAll:Jp(e==="text"?TS:void 0),tokenize:n};function n(s){const i=this,r=this.parser.constructs[e],o=s.attempt(r,l,c);return l;function l(m){return d(m)?o(m):c(m)}function c(m){if(m===null){s.consume(m);return}return s.enter("data"),s.consume(m),u}function u(m){return d(m)?(s.exit("data"),o(m)):(s.consume(m),u)}function d(m){if(m===null)return!0;const h=r[m];let g=-1;if(h)for(;++g<h.length;){const p=h[g];if(!p.previous||p.previous.call(i,i.previous))return!0}return!1}}}function Jp(e){return n;function n(s,i){let r=-1,o;for(;++r<=s.length;)o===void 0?s[r]&&s[r][1].type==="data"&&(o=r,r++):(!s[r]||s[r][1].type!=="data")&&(r!==o+2&&(s[o][1].end=s[r-1][1].end,s.splice(o+2,r-o-2),r=o+2),o=void 0);return e?e(s,i):s}}function TS(e,n){let s=0;for(;++s<=e.length;)if((s===e.length||e[s][1].type==="lineEnding")&&e[s-1][1].type==="data"){const i=e[s-1][1],r=n.sliceStream(i);let o=r.length,l=-1,c=0,u;for(;o--;){const d=r[o];if(typeof d=="string"){for(l=d.length;d.charCodeAt(l-1)===32;)c++,l--;if(l)break;l=-1}else if(d===-2)u=!0,c++;else if(d!==-1){o++;break}}if(n._contentTypeTextTrailing&&s===e.length&&(c=0),c){const d={type:s===e.length||u||c<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:o?l:i.start._bufferIndex+l,_index:i.start._index+o,line:i.end.line,column:i.end.column-c,offset:i.end.offset-c},end:{...i.end}};i.end={...d.start},i.start.offset===i.end.offset?Object.assign(i,d):(e.splice(s,0,["enter",d,n],["exit",d,n]),s+=2)}s++}return e}const PS={42:is,43:is,45:is,48:is,49:is,50:is,51:is,52:is,53:is,54:is,55:is,56:is,57:is,62:Up},IS={91:z0},$S={[-2]:gl,[-1]:gl,32:gl},DS={35:q0,42:Qr,45:[im,Qr],60:G0,61:im,95:Qr,96:nm,126:nm},LS={38:Hp,92:Bp},zS={[-5]:xl,[-4]:xl,[-3]:xl,33:mS,38:Hp,42:wc,60:[p0,tS],91:pS,92:[B0,Bp],93:sd,95:wc,96:E0},FS={null:[wc,_S]},OS={null:[42,95]},US={null:[]},BS=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:OS,contentInitial:IS,disable:US,document:PS,flow:DS,flowInitial:$S,insideSpan:FS,string:LS,text:zS},Symbol.toStringTag,{value:"Module"}));function HS(e,n,s){let i={_bufferIndex:-1,_index:0,line:s&&s.line||1,column:s&&s.column||1,offset:s&&s.offset||0};const r={},o=[];let l=[],c=[];const u={attempt:_(M),check:_(w),consume:y,enter:S,exit:k,interrupt:_(w,{interrupt:!0})},d={code:null,containerState:{},defineSkip:x,events:[],now:f,parser:e,previous:null,sliceSerialize:g,sliceStream:p,write:h};let m=n.tokenize.call(d,u);return n.resolveAll&&o.push(n),d;function h(I){return l=Ss(l,I),v(),l[l.length-1]!==null?[]:(N(n,0),d.events=Io(o,d.events,d),d.events)}function g(I,z){return VS(p(I),z)}function p(I){return qS(l,I)}function f(){const{_bufferIndex:I,_index:z,line:K,column:P,offset:E}=i;return{_bufferIndex:I,_index:z,line:K,column:P,offset:E}}function x(I){r[I.line]=I.column,T()}function v(){let I;for(;i._index<l.length;){const z=l[i._index];if(typeof z=="string")for(I=i._index,i._bufferIndex<0&&(i._bufferIndex=0);i._index===I&&i._bufferIndex<z.length;)b(z.charCodeAt(i._bufferIndex));else b(z)}}function b(I){m=m(I)}function y(I){jt(I)?(i.line++,i.column=1,i.offset+=I===-3?2:1,T()):I!==-1&&(i.column++,i.offset++),i._bufferIndex<0?i._index++:(i._bufferIndex++,i._bufferIndex===l[i._index].length&&(i._bufferIndex=-1,i._index++)),d.previous=I}function S(I,z){const K=z||{};return K.type=I,K.start=f(),d.events.push(["enter",K,d]),c.push(K),K}function k(I){const z=c.pop();return z.end=f(),d.events.push(["exit",z,d]),z}function M(I,z){N(I,z.from)}function w(I,z){z.restore()}function _(I,z){return K;function K(P,E,R){let B,G,X,C;return Array.isArray(P)?A(P):"tokenize"in P?A([P]):$(P);function $(oe){return he;function he(se){const fe=se!==null&&oe[se],U=se!==null&&oe.null,Ne=[...Array.isArray(fe)?fe:fe?[fe]:[],...Array.isArray(U)?U:U?[U]:[]];return A(Ne)(se)}}function A(oe){return B=oe,G=0,oe.length===0?R:j(oe[G])}function j(oe){return he;function he(se){return C=L(),X=oe,oe.partial||(d.currentConstruct=oe),oe.name&&d.parser.constructs.disable.null.includes(oe.name)?W():oe.tokenize.call(z?Object.assign(Object.create(d),z):d,u,J,W)(se)}}function J(oe){return I(X,C),E}function W(oe){return C.restore(),++G<B.length?j(B[G]):R}}}function N(I,z){I.resolveAll&&!o.includes(I)&&o.push(I),I.resolve&&fs(d.events,z,d.events.length-z,I.resolve(d.events.slice(z),d)),I.resolveTo&&(d.events=I.resolveTo(d.events,d))}function L(){const I=f(),z=d.previous,K=d.currentConstruct,P=d.events.length,E=Array.from(c);return{from:P,restore:R};function R(){i=I,d.previous=z,d.currentConstruct=K,d.events.length=P,c=E,T()}}function T(){i.line in r&&i.column<2&&(i.column=r[i.line],i.offset+=r[i.line]-1)}}function qS(e,n){const s=n.start._index,i=n.start._bufferIndex,r=n.end._index,o=n.end._bufferIndex;let l;if(s===r)l=[e[s].slice(i,o)];else{if(l=e.slice(s,r),i>-1){const c=l[0];typeof c=="string"?l[0]=c.slice(i):l.shift()}o>0&&l.push(e[r].slice(0,o))}return l}function VS(e,n){let s=-1;const i=[];let r;for(;++s<e.length;){const o=e[s];let l;if(typeof o=="string")l=o;else switch(o){case-5:{l="\r";break}case-4:{l=`
610
+ `;break}case-3:{l=`\r
611
+ `;break}case-2:{l=n?" ":" ";break}case-1:{if(!n&&r)continue;l=" ";break}default:l=String.fromCharCode(o)}r=o===-2,i.push(l)}return i.join("")}function WS(e){const i={constructs:Fp([BS,...(e||{}).extensions||[]]),content:r(o0),defined:[],document:r(c0),flow:r(ES),lazy:{},string:r(AS),text:r(RS)};return i;function r(o){return l;function l(c){return HS(i,o,c)}}}function KS(e){for(;!qp(e););return e}const am=/[\0\t\n\r]/g;function GS(){let e=1,n="",s=!0,i;return r;function r(o,l,c){const u=[];let d,m,h,g,p;for(o=n+(typeof o=="string"?o.toString():new TextDecoder(l||void 0).decode(o)),h=0,n="",s&&(o.charCodeAt(0)===65279&&h++,s=void 0);h<o.length;){if(am.lastIndex=h,d=am.exec(o),g=d&&d.index!==void 0?d.index:o.length,p=o.charCodeAt(g),!d){n=o.slice(h);break}if(p===10&&h===g&&i)u.push(-3),i=void 0;else switch(i&&(u.push(-5),i=void 0),h<g&&(u.push(o.slice(h,g)),e+=g-h),p){case 0:{u.push(65533),e++;break}case 9:{for(m=Math.ceil(e/4)*4,u.push(-2);e++<m;)u.push(-1);break}case 10:{u.push(-4),e=1;break}default:i=!0,e=1}h=g+1}return c&&(i&&u.push(-5),n&&u.push(n),u.push(null)),u}}const JS=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function YS(e){return e.replace(JS,QS)}function QS(e,n,s){if(n)return n;if(s.charCodeAt(0)===35){const r=s.charCodeAt(1),o=r===120||r===88;return Op(s.slice(o?2:1),o?16:10)}return nd(s)||e}const Yp={}.hasOwnProperty;function XS(e,n,s){return n&&typeof n=="object"&&(s=n,n=void 0),ZS(s)(KS(WS(s).document().write(GS()(e,n,!0))))}function ZS(e){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(Be),autolinkProtocol:L,autolinkEmail:L,atxHeading:o(ye),blockQuote:o(U),characterEscape:L,characterReference:L,codeFenced:o(Ne),codeFencedFenceInfo:l,codeFencedFenceMeta:l,codeIndented:o(Ne,l),codeText:o(ee,l),codeTextData:L,data:L,codeFlowValue:L,definition:o(ve),definitionDestinationString:l,definitionLabelString:l,definitionTitleString:l,emphasis:o(ue),hardBreakEscape:o(ie),hardBreakTrailing:o(ie),htmlFlow:o(Me,l),htmlFlowData:L,htmlText:o(Me,l),htmlTextData:L,image:o(ze),label:l,link:o(Be),listItem:o(Ye),listItemValue:g,listOrdered:o(Je,h),listUnordered:o(Je),paragraph:o(Ge),reference:j,referenceString:l,resourceDestinationString:l,resourceTitleString:l,setextHeading:o(ye),strong:o(it),thematicBreak:o(Fe)},exit:{atxHeading:u(),atxHeadingSequence:M,autolink:u(),autolinkEmail:fe,autolinkProtocol:se,blockQuote:u(),characterEscapeValue:T,characterReferenceMarkerHexadecimal:W,characterReferenceMarkerNumeric:W,characterReferenceValue:oe,characterReference:he,codeFenced:u(v),codeFencedFence:x,codeFencedFenceInfo:p,codeFencedFenceMeta:f,codeFlowValue:T,codeIndented:u(b),codeText:u(E),codeTextData:T,data:T,definition:u(),definitionDestinationString:k,definitionLabelString:y,definitionTitleString:S,emphasis:u(),hardBreakEscape:u(z),hardBreakTrailing:u(z),htmlFlow:u(K),htmlFlowData:T,htmlText:u(P),htmlTextData:T,image:u(B),label:X,labelText:G,lineEnding:I,link:u(R),listItem:u(),listOrdered:u(),listUnordered:u(),paragraph:u(),referenceString:J,resourceDestinationString:C,resourceTitleString:$,resource:A,setextHeading:u(N),setextHeadingLineSequence:_,setextHeadingText:w,strong:u(),thematicBreak:u()}};Qp(n,(e||{}).mdastExtensions||[]);const s={};return i;function i(ae){let be={type:"root",children:[]};const ne={stack:[be],tokenStack:[],config:n,enter:c,exit:d,buffer:l,resume:m,data:s},Ie=[];let Pe=-1;for(;++Pe<ae.length;)if(ae[Pe][1].type==="listOrdered"||ae[Pe][1].type==="listUnordered")if(ae[Pe][0]==="enter")Ie.push(Pe);else{const ce=Ie.pop();Pe=r(ae,ce,Pe)}for(Pe=-1;++Pe<ae.length;){const ce=n[ae[Pe][0]];Yp.call(ce,ae[Pe][1].type)&&ce[ae[Pe][1].type].call(Object.assign({sliceSerialize:ae[Pe][2].sliceSerialize},ne),ae[Pe][1])}if(ne.tokenStack.length>0){const ce=ne.tokenStack[ne.tokenStack.length-1];(ce[1]||rm).call(ne,void 0,ce[0])}for(be.position={start:ci(ae.length>0?ae[0][1].start:{line:1,column:1,offset:0}),end:ci(ae.length>0?ae[ae.length-2][1].end:{line:1,column:1,offset:0})},Pe=-1;++Pe<n.transforms.length;)be=n.transforms[Pe](be)||be;return be}function r(ae,be,ne){let Ie=be-1,Pe=-1,ce=!1,le,$e,at,tt;for(;++Ie<=ne;){const V=ae[Ie];switch(V[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{V[0]==="enter"?Pe++:Pe--,tt=void 0;break}case"lineEndingBlank":{V[0]==="enter"&&(le&&!tt&&!Pe&&!at&&(at=Ie),tt=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:tt=void 0}if(!Pe&&V[0]==="enter"&&V[1].type==="listItemPrefix"||Pe===-1&&V[0]==="exit"&&(V[1].type==="listUnordered"||V[1].type==="listOrdered")){if(le){let de=Ie;for($e=void 0;de--;){const Z=ae[de];if(Z[1].type==="lineEnding"||Z[1].type==="lineEndingBlank"){if(Z[0]==="exit")continue;$e&&(ae[$e][1].type="lineEndingBlank",ce=!0),Z[1].type="lineEnding",$e=de}else if(!(Z[1].type==="linePrefix"||Z[1].type==="blockQuotePrefix"||Z[1].type==="blockQuotePrefixWhitespace"||Z[1].type==="blockQuoteMarker"||Z[1].type==="listItemIndent"))break}at&&(!$e||at<$e)&&(le._spread=!0),le.end=Object.assign({},$e?ae[$e][1].start:V[1].end),ae.splice($e||Ie,0,["exit",le,V[2]]),Ie++,ne++}if(V[1].type==="listItemPrefix"){const de={type:"listItem",_spread:!1,start:Object.assign({},V[1].start),end:void 0};le=de,ae.splice(Ie,0,["enter",de,V[2]]),Ie++,ne++,at=void 0,tt=!0}}}return ae[be][1]._spread=ce,ne}function o(ae,be){return ne;function ne(Ie){c.call(this,ae(Ie),Ie),be&&be.call(this,Ie)}}function l(){this.stack.push({type:"fragment",children:[]})}function c(ae,be,ne){this.stack[this.stack.length-1].children.push(ae),this.stack.push(ae),this.tokenStack.push([be,ne||void 0]),ae.position={start:ci(be.start),end:void 0}}function u(ae){return be;function be(ne){ae&&ae.call(this,ne),d.call(this,ne)}}function d(ae,be){const ne=this.stack.pop(),Ie=this.tokenStack.pop();if(Ie)Ie[0].type!==ae.type&&(be?be.call(this,ae,Ie[0]):(Ie[1]||rm).call(this,ae,Ie[0]));else throw new Error("Cannot close `"+ae.type+"` ("+Qa({start:ae.start,end:ae.end})+"): it’s not open");ne.position.end=ci(ae.end)}function m(){return td(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function g(ae){if(this.data.expectingFirstListItemValue){const be=this.stack[this.stack.length-2];be.start=Number.parseInt(this.sliceSerialize(ae),10),this.data.expectingFirstListItemValue=void 0}}function p(){const ae=this.resume(),be=this.stack[this.stack.length-1];be.lang=ae}function f(){const ae=this.resume(),be=this.stack[this.stack.length-1];be.meta=ae}function x(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function v(){const ae=this.resume(),be=this.stack[this.stack.length-1];be.value=ae.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function b(){const ae=this.resume(),be=this.stack[this.stack.length-1];be.value=ae.replace(/(\r?\n|\r)$/g,"")}function y(ae){const be=this.resume(),ne=this.stack[this.stack.length-1];ne.label=be,ne.identifier=Ps(this.sliceSerialize(ae)).toLowerCase()}function S(){const ae=this.resume(),be=this.stack[this.stack.length-1];be.title=ae}function k(){const ae=this.resume(),be=this.stack[this.stack.length-1];be.url=ae}function M(ae){const be=this.stack[this.stack.length-1];if(!be.depth){const ne=this.sliceSerialize(ae).length;be.depth=ne}}function w(){this.data.setextHeadingSlurpLineEnding=!0}function _(ae){const be=this.stack[this.stack.length-1];be.depth=this.sliceSerialize(ae).codePointAt(0)===61?1:2}function N(){this.data.setextHeadingSlurpLineEnding=void 0}function L(ae){const ne=this.stack[this.stack.length-1].children;let Ie=ne[ne.length-1];(!Ie||Ie.type!=="text")&&(Ie=_e(),Ie.position={start:ci(ae.start),end:void 0},ne.push(Ie)),this.stack.push(Ie)}function T(ae){const be=this.stack.pop();be.value+=this.sliceSerialize(ae),be.position.end=ci(ae.end)}function I(ae){const be=this.stack[this.stack.length-1];if(this.data.atHardBreak){const ne=be.children[be.children.length-1];ne.position.end=ci(ae.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(be.type)&&(L.call(this,ae),T.call(this,ae))}function z(){this.data.atHardBreak=!0}function K(){const ae=this.resume(),be=this.stack[this.stack.length-1];be.value=ae}function P(){const ae=this.resume(),be=this.stack[this.stack.length-1];be.value=ae}function E(){const ae=this.resume(),be=this.stack[this.stack.length-1];be.value=ae}function R(){const ae=this.stack[this.stack.length-1];if(this.data.inReference){const be=this.data.referenceType||"shortcut";ae.type+="Reference",ae.referenceType=be,delete ae.url,delete ae.title}else delete ae.identifier,delete ae.label;this.data.referenceType=void 0}function B(){const ae=this.stack[this.stack.length-1];if(this.data.inReference){const be=this.data.referenceType||"shortcut";ae.type+="Reference",ae.referenceType=be,delete ae.url,delete ae.title}else delete ae.identifier,delete ae.label;this.data.referenceType=void 0}function G(ae){const be=this.sliceSerialize(ae),ne=this.stack[this.stack.length-2];ne.label=YS(be),ne.identifier=Ps(be).toLowerCase()}function X(){const ae=this.stack[this.stack.length-1],be=this.resume(),ne=this.stack[this.stack.length-1];if(this.data.inReference=!0,ne.type==="link"){const Ie=ae.children;ne.children=Ie}else ne.alt=be}function C(){const ae=this.resume(),be=this.stack[this.stack.length-1];be.url=ae}function $(){const ae=this.resume(),be=this.stack[this.stack.length-1];be.title=ae}function A(){this.data.inReference=void 0}function j(){this.data.referenceType="collapsed"}function J(ae){const be=this.resume(),ne=this.stack[this.stack.length-1];ne.label=be,ne.identifier=Ps(this.sliceSerialize(ae)).toLowerCase(),this.data.referenceType="full"}function W(ae){this.data.characterReferenceType=ae.type}function oe(ae){const be=this.sliceSerialize(ae),ne=this.data.characterReferenceType;let Ie;ne?(Ie=Op(be,ne==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Ie=nd(be);const Pe=this.stack[this.stack.length-1];Pe.value+=Ie}function he(ae){const be=this.stack.pop();be.position.end=ci(ae.end)}function se(ae){T.call(this,ae);const be=this.stack[this.stack.length-1];be.url=this.sliceSerialize(ae)}function fe(ae){T.call(this,ae);const be=this.stack[this.stack.length-1];be.url="mailto:"+this.sliceSerialize(ae)}function U(){return{type:"blockquote",children:[]}}function Ne(){return{type:"code",lang:null,meta:null,value:""}}function ee(){return{type:"inlineCode",value:""}}function ve(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function ue(){return{type:"emphasis",children:[]}}function ye(){return{type:"heading",depth:0,children:[]}}function ie(){return{type:"break"}}function Me(){return{type:"html",value:""}}function ze(){return{type:"image",title:null,url:"",alt:null}}function Be(){return{type:"link",title:null,url:"",children:[]}}function Je(ae){return{type:"list",ordered:ae.type==="listOrdered",start:null,spread:ae._spread,children:[]}}function Ye(ae){return{type:"listItem",spread:ae._spread,checked:null,children:[]}}function Ge(){return{type:"paragraph",children:[]}}function it(){return{type:"strong",children:[]}}function _e(){return{type:"text",value:""}}function Fe(){return{type:"thematicBreak"}}}function ci(e){return{line:e.line,column:e.column,offset:e.offset}}function Qp(e,n){let s=-1;for(;++s<n.length;){const i=n[s];Array.isArray(i)?Qp(e,i):eC(e,i)}}function eC(e,n){let s;for(s in n)if(Yp.call(n,s))switch(s){case"canContainEols":{const i=n[s];i&&e[s].push(...i);break}case"transforms":{const i=n[s];i&&e[s].push(...i);break}case"enter":case"exit":{const i=n[s];i&&Object.assign(e[s],i);break}}}function rm(e,n){throw e?new Error("Cannot close `"+e.type+"` ("+Qa({start:e.start,end:e.end})+"): a different token (`"+n.type+"`, "+Qa({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+Qa({start:n.start,end:n.end})+") is still open")}function tC(e){const n=this;n.parser=s;function s(i){return XS(i,{...n.data("settings"),...e,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function nC(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 sC(e,n){const s={type:"element",tagName:"br",properties:{},children:[]};return e.patch(n,s),[e.applyData(n,s),{type:"text",value:`
612
+ `}]}function iC(e,n){const s=n.value?n.value+`
613
+ `:"",i={},r=n.lang?n.lang.split(/\s+/):[];r.length>0&&(i.className=["language-"+r[0]]);let o={type:"element",tagName:"code",properties:i,children:[{type:"text",value:s}]};return n.meta&&(o.data={meta:n.meta}),e.patch(n,o),o=e.applyData(n,o),o={type:"element",tagName:"pre",properties:{},children:[o]},e.patch(n,o),o}function aC(e,n){const s={type:"element",tagName:"del",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function rC(e,n){const s={type:"element",tagName:"em",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function oC(e,n){const s=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=String(n.identifier).toUpperCase(),r=ya(i.toLowerCase()),o=e.footnoteOrder.indexOf(i);let l,c=e.footnoteCounts.get(i);c===void 0?(c=0,e.footnoteOrder.push(i),l=e.footnoteOrder.length):l=o+1,c+=1,e.footnoteCounts.set(i,c);const u={type:"element",tagName:"a",properties:{href:"#"+s+"fn-"+r,id:s+"fnref-"+r+(c>1?"-"+c:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(l)}]};e.patch(n,u);const d={type:"element",tagName:"sup",properties:{},children:[u]};return e.patch(n,d),e.applyData(n,d)}function lC(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 cC(e,n){if(e.options.allowDangerousHtml){const s={type:"raw",value:n.value};return e.patch(n,s),e.applyData(n,s)}}function Xp(e,n){const s=n.referenceType;let i="]";if(s==="collapsed"?i+="[]":s==="full"&&(i+="["+(n.label||n.identifier)+"]"),n.type==="imageReference")return[{type:"text",value:"!["+n.alt+i}];const r=e.all(n),o=r[0];o&&o.type==="text"?o.value="["+o.value:r.unshift({type:"text",value:"["});const l=r[r.length-1];return l&&l.type==="text"?l.value+=i:r.push({type:"text",value:i}),r}function dC(e,n){const s=String(n.identifier).toUpperCase(),i=e.definitionById.get(s);if(!i)return Xp(e,n);const r={src:ya(i.url||""),alt:n.alt};i.title!==null&&i.title!==void 0&&(r.title=i.title);const o={type:"element",tagName:"img",properties:r,children:[]};return e.patch(n,o),e.applyData(n,o)}function uC(e,n){const s={src:ya(n.url)};n.alt!==null&&n.alt!==void 0&&(s.alt=n.alt),n.title!==null&&n.title!==void 0&&(s.title=n.title);const i={type:"element",tagName:"img",properties:s,children:[]};return e.patch(n,i),e.applyData(n,i)}function mC(e,n){const s={type:"text",value:n.value.replace(/\r?\n|\r/g," ")};e.patch(n,s);const i={type:"element",tagName:"code",properties:{},children:[s]};return e.patch(n,i),e.applyData(n,i)}function hC(e,n){const s=String(n.identifier).toUpperCase(),i=e.definitionById.get(s);if(!i)return Xp(e,n);const r={href:ya(i.url||"")};i.title!==null&&i.title!==void 0&&(r.title=i.title);const o={type:"element",tagName:"a",properties:r,children:e.all(n)};return e.patch(n,o),e.applyData(n,o)}function pC(e,n){const s={href:ya(n.url)};n.title!==null&&n.title!==void 0&&(s.title=n.title);const i={type:"element",tagName:"a",properties:s,children:e.all(n)};return e.patch(n,i),e.applyData(n,i)}function fC(e,n,s){const i=e.all(n),r=s?gC(s):Zp(n),o={},l=[];if(typeof n.checked=="boolean"){const m=i[0];let h;m&&m.type==="element"&&m.tagName==="p"?h=m:(h={type:"element",tagName:"p",properties:{},children:[]},i.unshift(h)),h.children.length>0&&h.children.unshift({type:"text",value:" "}),h.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:n.checked,disabled:!0},children:[]}),o.className=["task-list-item"]}let c=-1;for(;++c<i.length;){const m=i[c];(r||c!==0||m.type!=="element"||m.tagName!=="p")&&l.push({type:"text",value:`
614
+ `}),m.type==="element"&&m.tagName==="p"&&!r?l.push(...m.children):l.push(m)}const u=i[i.length-1];u&&(r||u.type!=="element"||u.tagName!=="p")&&l.push({type:"text",value:`
615
+ `});const d={type:"element",tagName:"li",properties:o,children:l};return e.patch(n,d),e.applyData(n,d)}function gC(e){let n=!1;if(e.type==="list"){n=e.spread||!1;const s=e.children;let i=-1;for(;!n&&++i<s.length;)n=Zp(s[i])}return n}function Zp(e){const n=e.spread;return n??e.children.length>1}function xC(e,n){const s={},i=e.all(n);let r=-1;for(typeof n.start=="number"&&n.start!==1&&(s.start=n.start);++r<i.length;){const l=i[r];if(l.type==="element"&&l.tagName==="li"&&l.properties&&Array.isArray(l.properties.className)&&l.properties.className.includes("task-list-item")){s.className=["contains-task-list"];break}}const o={type:"element",tagName:n.ordered?"ol":"ul",properties:s,children:e.wrap(i,!0)};return e.patch(n,o),e.applyData(n,o)}function bC(e,n){const s={type:"element",tagName:"p",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function vC(e,n){const s={type:"root",children:e.wrap(e.all(n))};return e.patch(n,s),e.applyData(n,s)}function yC(e,n){const s={type:"element",tagName:"strong",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function kC(e,n){const s=e.all(n),i=s.shift(),r=[];if(i){const l={type:"element",tagName:"thead",properties:{},children:e.wrap([i],!0)};e.patch(n.children[0],l),r.push(l)}if(s.length>0){const l={type:"element",tagName:"tbody",properties:{},children:e.wrap(s,!0)},c=Qc(n.children[1]),u=Tp(n.children[n.children.length-1]);c&&u&&(l.position={start:c,end:u}),r.push(l)}const o={type:"element",tagName:"table",properties:{},children:e.wrap(r,!0)};return e.patch(n,o),e.applyData(n,o)}function jC(e,n,s){const i=s?s.children:void 0,o=(i?i.indexOf(n):1)===0?"th":"td",l=s&&s.type==="table"?s.align:void 0,c=l?l.length:n.children.length;let u=-1;const d=[];for(;++u<c;){const h=n.children[u],g={},p=l?l[u]:void 0;p&&(g.align=p);let f={type:"element",tagName:o,properties:g,children:[]};h&&(f.children=e.all(h),e.patch(h,f),f=e.applyData(h,f)),d.push(f)}const m={type:"element",tagName:"tr",properties:{},children:e.wrap(d,!0)};return e.patch(n,m),e.applyData(n,m)}function wC(e,n){const s={type:"element",tagName:"td",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}const om=9,lm=32;function NC(e){const n=String(e),s=/\r?\n|\r/g;let i=s.exec(n),r=0;const o=[];for(;i;)o.push(cm(n.slice(r,i.index),r>0,!0),i[0]),r=i.index+i[0].length,i=s.exec(n);return o.push(cm(n.slice(r),r>0,!1)),o.join("")}function cm(e,n,s){let i=0,r=e.length;if(n){let o=e.codePointAt(i);for(;o===om||o===lm;)i++,o=e.codePointAt(i)}if(s){let o=e.codePointAt(r-1);for(;o===om||o===lm;)r--,o=e.codePointAt(r-1)}return r>i?e.slice(i,r):""}function SC(e,n){const s={type:"text",value:NC(String(n.value))};return e.patch(n,s),e.applyData(n,s)}function CC(e,n){const s={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(n,s),e.applyData(n,s)}const EC={blockquote:nC,break:sC,code:iC,delete:aC,emphasis:rC,footnoteReference:oC,heading:lC,html:cC,imageReference:dC,image:uC,inlineCode:mC,linkReference:hC,link:pC,listItem:fC,list:xC,paragraph:bC,root:vC,strong:yC,table:kC,tableCell:wC,tableRow:jC,text:SC,thematicBreak:CC,toml:zr,yaml:zr,definition:zr,footnoteDefinition:zr};function zr(){}const ef=-1,$o=0,Za=1,ho=2,id=3,ad=4,rd=5,od=6,tf=7,nf=8,dm=typeof self=="object"?self:globalThis,MC=(e,n)=>{const s=(r,o)=>(e.set(o,r),r),i=r=>{if(e.has(r))return e.get(r);const[o,l]=n[r];switch(o){case $o:case ef:return s(l,r);case Za:{const c=s([],r);for(const u of l)c.push(i(u));return c}case ho:{const c=s({},r);for(const[u,d]of l)c[i(u)]=i(d);return c}case id:return s(new Date(l),r);case ad:{const{source:c,flags:u}=l;return s(new RegExp(c,u),r)}case rd:{const c=s(new Map,r);for(const[u,d]of l)c.set(i(u),i(d));return c}case od:{const c=s(new Set,r);for(const u of l)c.add(i(u));return c}case tf:{const{name:c,message:u}=l;return s(new dm[c](u),r)}case nf: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 dm[o](l),r)};return i},um=e=>MC(new Map,e)(0),Yi="",{toString:_C}={},{keys:AC}=Object,Pa=e=>{const n=typeof e;if(n!=="object"||!e)return[$o,n];const s=_C.call(e).slice(8,-1);switch(s){case"Array":return[Za,Yi];case"Object":return[ho,Yi];case"Date":return[id,Yi];case"RegExp":return[ad,Yi];case"Map":return[rd,Yi];case"Set":return[od,Yi];case"DataView":return[Za,s]}return s.includes("Array")?[Za,s]:s.includes("Error")?[tf,s]:[ho,s]},Fr=([e,n])=>e===$o&&(n==="function"||n==="symbol"),RC=(e,n,s,i)=>{const r=(l,c)=>{const u=i.push(l)-1;return s.set(c,u),u},o=l=>{if(s.has(l))return s.get(l);let[c,u]=Pa(l);switch(c){case $o:{let m=l;switch(u){case"bigint":c=nf,m=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+u);m=null;break;case"undefined":return r([ef],l)}return r([c,m],l)}case Za:{if(u){let g=l;return u==="DataView"?g=new Uint8Array(l.buffer):u==="ArrayBuffer"&&(g=new Uint8Array(l)),r([u,[...g]],l)}const m=[],h=r([c,m],l);for(const g of l)m.push(o(g));return h}case ho:{if(u)switch(u){case"BigInt":return r([u,l.toString()],l);case"Boolean":case"Number":case"String":return r([u,l.valueOf()],l)}if(n&&"toJSON"in l)return o(l.toJSON());const m=[],h=r([c,m],l);for(const g of AC(l))(e||!Fr(Pa(l[g])))&&m.push([o(g),o(l[g])]);return h}case id:return r([c,l.toISOString()],l);case ad:{const{source:m,flags:h}=l;return r([c,{source:m,flags:h}],l)}case rd:{const m=[],h=r([c,m],l);for(const[g,p]of l)(e||!(Fr(Pa(g))||Fr(Pa(p))))&&m.push([o(g),o(p)]);return h}case od:{const m=[],h=r([c,m],l);for(const g of l)(e||!Fr(Pa(g)))&&m.push(o(g));return h}}const{message:d}=l;return r([c,{name:u,message:d}],l)};return o},mm=(e,{json:n,lossy:s}={})=>{const i=[];return RC(!(n||s),!!n,new Map,i)(e),i},po=typeof structuredClone=="function"?(e,n)=>n&&("json"in n||"lossy"in n)?um(mm(e,n)):structuredClone(e):(e,n)=>um(mm(e,n));function TC(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 PC(e,n){return"Back to reference "+(e+1)+(n>1?"-"+n:"")}function IC(e){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=e.options.footnoteBackContent||TC,i=e.options.footnoteBackLabel||PC,r=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",l=e.options.footnoteLabelProperties||{className:["sr-only"]},c=[];let u=-1;for(;++u<e.footnoteOrder.length;){const d=e.footnoteById.get(e.footnoteOrder[u]);if(!d)continue;const m=e.all(d),h=String(d.identifier).toUpperCase(),g=ya(h.toLowerCase());let p=0;const f=[],x=e.footnoteCounts.get(h);for(;x!==void 0&&++p<=x;){f.length>0&&f.push({type:"text",value:" "});let y=typeof s=="string"?s:s(u,p);typeof y=="string"&&(y={type:"text",value:y}),f.push({type:"element",tagName:"a",properties:{href:"#"+n+"fnref-"+g+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof i=="string"?i:i(u,p),className:["data-footnote-backref"]},children:Array.isArray(y)?y:[y]})}const v=m[m.length-1];if(v&&v.type==="element"&&v.tagName==="p"){const y=v.children[v.children.length-1];y&&y.type==="text"?y.value+=" ":v.children.push({type:"text",value:" "}),v.children.push(...f)}else m.push(...f);const b={type:"element",tagName:"li",properties:{id:n+"fn-"+g},children:e.wrap(m,!0)};e.patch(d,b),c.push(b)}if(c.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...po(l),id:"footnote-label"},children:[{type:"text",value:r}]},{type:"text",value:`
616
+ `},{type:"element",tagName:"ol",properties:{},children:e.wrap(c,!0)},{type:"text",value:`
617
+ `}]}}const Do=(function(e){if(e==null)return zC;if(typeof e=="function")return Lo(e);if(typeof e=="object")return Array.isArray(e)?$C(e):DC(e);if(typeof e=="string")return LC(e);throw new Error("Expected function, string, or object as test")});function $C(e){const n=[];let s=-1;for(;++s<e.length;)n[s]=Do(e[s]);return Lo(i);function i(...r){let o=-1;for(;++o<n.length;)if(n[o].apply(this,r))return!0;return!1}}function DC(e){const n=e;return Lo(s);function s(i){const r=i;let o;for(o in e)if(r[o]!==n[o])return!1;return!0}}function LC(e){return Lo(n);function n(s){return s&&s.type===e}}function Lo(e){return n;function n(s,i,r){return!!(FC(s)&&e.call(this,s,typeof i=="number"?i:void 0,r||void 0))}}function zC(){return!0}function FC(e){return e!==null&&typeof e=="object"&&"type"in e}const sf=[],OC=!0,Nc=!1,UC="skip";function af(e,n,s,i){let r;typeof n=="function"&&typeof s!="function"?(i=s,s=n):r=n;const o=Do(r),l=i?-1:1;c(e,void 0,[])();function c(u,d,m){const h=u&&typeof u=="object"?u:{};if(typeof h.type=="string"){const p=typeof h.tagName=="string"?h.tagName:typeof h.name=="string"?h.name:void 0;Object.defineProperty(g,"name",{value:"node ("+(u.type+(p?"<"+p+">":""))+")"})}return g;function g(){let p=sf,f,x,v;if((!n||o(u,d,m[m.length-1]||void 0))&&(p=BC(s(u,m)),p[0]===Nc))return p;if("children"in u&&u.children){const b=u;if(b.children&&p[0]!==UC)for(x=(i?b.children.length:-1)+l,v=m.concat(b);x>-1&&x<b.children.length;){const y=b.children[x];if(f=c(y,x,v)(),f[0]===Nc)return f;x=typeof f[1]=="number"?f[1]:x+l}}return p}}}function BC(e){return Array.isArray(e)?e:typeof e=="number"?[OC,e]:e==null?sf:[e]}function ld(e,n,s,i){let r,o,l;typeof n=="function"&&typeof s!="function"?(o=void 0,l=n,r=s):(o=n,l=s,r=i),af(e,o,c,r);function c(u,d){const m=d[d.length-1],h=m?m.children.indexOf(u):void 0;return l(u,h,m)}}const Sc={}.hasOwnProperty,HC={};function qC(e,n){const s=n||HC,i=new Map,r=new Map,o=new Map,l={...EC,...s.handlers},c={all:d,applyData:WC,definitionById:i,footnoteById:r,footnoteCounts:o,footnoteOrder:[],handlers:l,one:u,options:s,patch:VC,wrap:GC};return ld(e,function(m){if(m.type==="definition"||m.type==="footnoteDefinition"){const h=m.type==="definition"?i:r,g=String(m.identifier).toUpperCase();h.has(g)||h.set(g,m)}}),c;function u(m,h){const g=m.type,p=c.handlers[g];if(Sc.call(c.handlers,g)&&p)return p(c,m,h);if(c.options.passThrough&&c.options.passThrough.includes(g)){if("children"in m){const{children:x,...v}=m,b=po(v);return b.children=c.all(m),b}return po(m)}return(c.options.unknownHandler||KC)(c,m,h)}function d(m){const h=[];if("children"in m){const g=m.children;let p=-1;for(;++p<g.length;){const f=c.one(g[p],m);if(f){if(p&&g[p-1].type==="break"&&(!Array.isArray(f)&&f.type==="text"&&(f.value=hm(f.value)),!Array.isArray(f)&&f.type==="element")){const x=f.children[0];x&&x.type==="text"&&(x.value=hm(x.value))}Array.isArray(f)?h.push(...f):h.push(f)}}}return h}}function VC(e,n){e.position&&(n.position=P1(e))}function WC(e,n){let s=n;if(e&&e.data){const i=e.data.hName,r=e.data.hChildren,o=e.data.hProperties;if(typeof i=="string")if(s.type==="element")s.tagName=i;else{const l="children"in s?s.children:[s];s={type:"element",tagName:i,properties:{},children:l}}s.type==="element"&&o&&Object.assign(s.properties,po(o)),"children"in s&&s.children&&r!==null&&r!==void 0&&(s.children=r)}return s}function KC(e,n){const s=n.data||{},i="value"in n&&!(Sc.call(s,"hProperties")||Sc.call(s,"hChildren"))?{type:"text",value:n.value}:{type:"element",tagName:"div",properties:{},children:e.all(n)};return e.patch(n,i),e.applyData(n,i)}function GC(e,n){const s=[];let i=-1;for(n&&s.push({type:"text",value:`
618
+ `});++i<e.length;)i&&s.push({type:"text",value:`
619
+ `}),s.push(e[i]);return n&&e.length>0&&s.push({type:"text",value:`
620
+ `}),s}function hm(e){let n=0,s=e.charCodeAt(n);for(;s===9||s===32;)n++,s=e.charCodeAt(n);return e.slice(n)}function pm(e,n){const s=qC(e,n),i=s.one(e,void 0),r=IC(s),o=Array.isArray(i)?{type:"root",children:i}:i||{type:"root",children:[]};return r&&o.children.push({type:"text",value:`
621
+ `},r),o}function JC(e,n){return e&&"run"in e?async function(s,i){const r=pm(s,{file:i,...n});await e.run(r,i)}:function(s,i){return pm(s,{file:i,...e||n})}}function fm(e){if(e)throw e}var bl,gm;function YC(){if(gm)return bl;gm=1;var e=Object.prototype.hasOwnProperty,n=Object.prototype.toString,s=Object.defineProperty,i=Object.getOwnPropertyDescriptor,r=function(d){return typeof Array.isArray=="function"?Array.isArray(d):n.call(d)==="[object Array]"},o=function(d){if(!d||n.call(d)!=="[object Object]")return!1;var m=e.call(d,"constructor"),h=d.constructor&&d.constructor.prototype&&e.call(d.constructor.prototype,"isPrototypeOf");if(d.constructor&&!m&&!h)return!1;var g;for(g in d);return typeof g>"u"||e.call(d,g)},l=function(d,m){s&&m.name==="__proto__"?s(d,m.name,{enumerable:!0,configurable:!0,value:m.newValue,writable:!0}):d[m.name]=m.newValue},c=function(d,m){if(m==="__proto__")if(e.call(d,m)){if(i)return i(d,m).value}else return;return d[m]};return bl=function u(){var d,m,h,g,p,f,x=arguments[0],v=1,b=arguments.length,y=!1;for(typeof x=="boolean"&&(y=x,x=arguments[1]||{},v=2),(x==null||typeof x!="object"&&typeof x!="function")&&(x={});v<b;++v)if(d=arguments[v],d!=null)for(m in d)h=c(x,m),g=c(d,m),x!==g&&(y&&g&&(o(g)||(p=r(g)))?(p?(p=!1,f=h&&r(h)?h:[]):f=h&&o(h)?h:{},l(x,{name:m,newValue:u(y,f,g)})):typeof g<"u"&&l(x,{name:m,newValue:g}));return x},bl}var QC=YC();const vl=Eh(QC);function Cc(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 XC(){const e=[],n={run:s,use:i};return n;function s(...r){let o=-1;const l=r.pop();if(typeof l!="function")throw new TypeError("Expected function as last argument, not "+l);c(null,...r);function c(u,...d){const m=e[++o];let h=-1;if(u){l(u);return}for(;++h<r.length;)(d[h]===null||d[h]===void 0)&&(d[h]=r[h]);r=d,m?ZC(m,c)(...d):l(null,...d)}}function i(r){if(typeof r!="function")throw new TypeError("Expected `middelware` to be a function, not "+r);return e.push(r),n}}function ZC(e,n){let s;return i;function i(...l){const c=e.length>l.length;let u;c&&l.push(r);try{u=e.apply(this,l)}catch(d){const m=d;if(c&&s)throw m;return r(m)}c||(u&&u.then&&typeof u.then=="function"?u.then(o,r):u instanceof Error?r(u):o(u))}function r(l,...c){s||(s=!0,n(l,...c))}function o(l){r(null,l)}}const Bs={basename:e2,dirname:t2,extname:n2,join:s2,sep:"/"};function e2(e,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');kr(e);let s=0,i=-1,r=e.length,o;if(n===void 0||n.length===0||n.length>e.length){for(;r--;)if(e.codePointAt(r)===47){if(o){s=r+1;break}}else i<0&&(o=!0,i=r+1);return i<0?"":e.slice(s,i)}if(n===e)return"";let l=-1,c=n.length-1;for(;r--;)if(e.codePointAt(r)===47){if(o){s=r+1;break}}else l<0&&(o=!0,l=r+1),c>-1&&(e.codePointAt(r)===n.codePointAt(c--)?c<0&&(i=r):(c=-1,i=l));return s===i?i=l:i<0&&(i=e.length),e.slice(s,i)}function t2(e){if(kr(e),e.length===0)return".";let n=-1,s=e.length,i;for(;--s;)if(e.codePointAt(s)===47){if(i){n=s;break}}else i||(i=!0);return n<0?e.codePointAt(0)===47?"/":".":n===1&&e.codePointAt(0)===47?"//":e.slice(0,n)}function n2(e){kr(e);let n=e.length,s=-1,i=0,r=-1,o=0,l;for(;n--;){const c=e.codePointAt(n);if(c===47){if(l){i=n+1;break}continue}s<0&&(l=!0,s=n+1),c===46?r<0?r=n:o!==1&&(o=1):r>-1&&(o=-1)}return r<0||s<0||o===0||o===1&&r===s-1&&r===i+1?"":e.slice(r,s)}function s2(...e){let n=-1,s;for(;++n<e.length;)kr(e[n]),e[n]&&(s=s===void 0?e[n]:s+"/"+e[n]);return s===void 0?".":i2(s)}function i2(e){kr(e);const n=e.codePointAt(0)===47;let s=a2(e,!n);return s.length===0&&!n&&(s="."),s.length>0&&e.codePointAt(e.length-1)===47&&(s+="/"),n?"/"+s:s}function a2(e,n){let s="",i=0,r=-1,o=0,l=-1,c,u;for(;++l<=e.length;){if(l<e.length)c=e.codePointAt(l);else{if(c===47)break;c=47}if(c===47){if(!(r===l-1||o===1))if(r!==l-1&&o===2){if(s.length<2||i!==2||s.codePointAt(s.length-1)!==46||s.codePointAt(s.length-2)!==46){if(s.length>2){if(u=s.lastIndexOf("/"),u!==s.length-1){u<0?(s="",i=0):(s=s.slice(0,u),i=s.length-1-s.lastIndexOf("/")),r=l,o=0;continue}}else if(s.length>0){s="",i=0,r=l,o=0;continue}}n&&(s=s.length>0?s+"/..":"..",i=2)}else s.length>0?s+="/"+e.slice(r+1,l):s=e.slice(r+1,l),i=l-r-1;r=l,o=0}else c===46&&o>-1?o++:o=-1}return s}function kr(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const r2={cwd:o2};function o2(){return"/"}function Ec(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function l2(e){if(typeof e=="string")e=new URL(e);else if(!Ec(e)){const n=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw n.code="ERR_INVALID_ARG_TYPE",n}if(e.protocol!=="file:"){const n=new TypeError("The URL must be of scheme file");throw n.code="ERR_INVALID_URL_SCHEME",n}return c2(e)}function c2(e){if(e.hostname!==""){const i=new TypeError('File URL host must be "localhost" or empty on darwin');throw i.code="ERR_INVALID_FILE_URL_HOST",i}const n=e.pathname;let s=-1;for(;++s<n.length;)if(n.codePointAt(s)===37&&n.codePointAt(s+1)===50){const i=n.codePointAt(s+2);if(i===70||i===102){const r=new TypeError("File URL path must not include encoded / characters");throw r.code="ERR_INVALID_FILE_URL_PATH",r}}return decodeURIComponent(n)}const yl=["history","path","basename","stem","extname","dirname"];class rf{constructor(n){let s;n?Ec(n)?s={path:n}:typeof n=="string"||d2(n)?s={value:n}:s=n:s={},this.cwd="cwd"in s?"":r2.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let i=-1;for(;++i<yl.length;){const o=yl[i];o in s&&s[o]!==void 0&&s[o]!==null&&(this[o]=o==="history"?[...s[o]]:s[o])}let r;for(r in s)yl.includes(r)||(this[r]=s[r])}get basename(){return typeof this.path=="string"?Bs.basename(this.path):void 0}set basename(n){jl(n,"basename"),kl(n,"basename"),this.path=Bs.join(this.dirname||"",n)}get dirname(){return typeof this.path=="string"?Bs.dirname(this.path):void 0}set dirname(n){xm(this.basename,"dirname"),this.path=Bs.join(n||"",this.basename)}get extname(){return typeof this.path=="string"?Bs.extname(this.path):void 0}set extname(n){if(kl(n,"extname"),xm(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=Bs.join(this.dirname,this.stem+(n||""))}get path(){return this.history[this.history.length-1]}set path(n){Ec(n)&&(n=l2(n)),jl(n,"path"),this.path!==n&&this.history.push(n)}get stem(){return typeof this.path=="string"?Bs.basename(this.path,this.extname):void 0}set stem(n){jl(n,"stem"),kl(n,"stem"),this.path=Bs.join(this.dirname||"",n+(this.extname||""))}fail(n,s,i){const r=this.message(n,s,i);throw r.fatal=!0,r}info(n,s,i){const r=this.message(n,s,i);return r.fatal=void 0,r}message(n,s,i){const r=new Wn(n,s,i);return this.path&&(r.name=this.path+":"+r.name,r.file=this.path),r.fatal=!1,this.messages.push(r),r}toString(n){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(n||void 0).decode(this.value)}}function kl(e,n){if(e&&e.includes(Bs.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+Bs.sep+"`")}function jl(e,n){if(!e)throw new Error("`"+n+"` cannot be empty")}function xm(e,n){if(!e)throw new Error("Setting `"+n+"` requires `path` to be set too")}function d2(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const u2=(function(e){const i=this.constructor.prototype,r=i[e],o=function(){return r.apply(o,arguments)};return Object.setPrototypeOf(o,i),o}),m2={}.hasOwnProperty;class cd extends u2{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=XC()}copy(){const n=new cd;let s=-1;for(;++s<this.attachers.length;){const i=this.attachers[s];n.use(...i)}return n.data(vl(!0,{},this.namespace)),n}data(n,s){return typeof n=="string"?arguments.length===2?(Sl("data",this.frozen),this.namespace[n]=s,this):m2.call(this.namespace,n)&&this.namespace[n]||void 0:n?(Sl("data",this.frozen),this.namespace=n,this):this.namespace}freeze(){if(this.frozen)return this;const n=this;for(;++this.freezeIndex<this.attachers.length;){const[s,...i]=this.attachers[this.freezeIndex];if(i[0]===!1)continue;i[0]===!0&&(i[0]=void 0);const r=s.call(n,...i);typeof r=="function"&&this.transformers.use(r)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(n){this.freeze();const s=Or(n),i=this.parser||this.Parser;return wl("parse",i),i(String(s),s)}process(n,s){const i=this;return this.freeze(),wl("process",this.parser||this.Parser),Nl("process",this.compiler||this.Compiler),s?r(void 0,s):new Promise(r);function r(o,l){const c=Or(n),u=i.parse(c);i.run(u,c,function(m,h,g){if(m||!h||!g)return d(m);const p=h,f=i.stringify(p,g);f2(f)?g.value=f:g.result=f,d(m,g)});function d(m,h){m||!h?l(m):o?o(h):s(void 0,h)}}}processSync(n){let s=!1,i;return this.freeze(),wl("processSync",this.parser||this.Parser),Nl("processSync",this.compiler||this.Compiler),this.process(n,r),vm("processSync","process",s),i;function r(o,l){s=!0,fm(o),i=l}}run(n,s,i){bm(n),this.freeze();const r=this.transformers;return!i&&typeof s=="function"&&(i=s,s=void 0),i?o(void 0,i):new Promise(o);function o(l,c){const u=Or(s);r.run(n,u,d);function d(m,h,g){const p=h||n;m?c(m):l?l(p):i(void 0,p,g)}}}runSync(n,s){let i=!1,r;return this.run(n,s,o),vm("runSync","run",i),r;function o(l,c){fm(l),r=c,i=!0}}stringify(n,s){this.freeze();const i=Or(s),r=this.compiler||this.Compiler;return Nl("stringify",r),bm(n),r(n,i)}use(n,...s){const i=this.attachers,r=this.namespace;if(Sl("use",this.frozen),n!=null)if(typeof n=="function")u(n,s);else if(typeof n=="object")Array.isArray(n)?c(n):l(n);else throw new TypeError("Expected usable value, not `"+n+"`");return this;function o(d){if(typeof d=="function")u(d,[]);else if(typeof d=="object")if(Array.isArray(d)){const[m,...h]=d;u(m,h)}else l(d);else throw new TypeError("Expected usable value, not `"+d+"`")}function l(d){if(!("plugins"in d)&&!("settings"in d))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");c(d.plugins),d.settings&&(r.settings=vl(!0,r.settings,d.settings))}function c(d){let m=-1;if(d!=null)if(Array.isArray(d))for(;++m<d.length;){const h=d[m];o(h)}else throw new TypeError("Expected a list of plugins, not `"+d+"`")}function u(d,m){let h=-1,g=-1;for(;++h<i.length;)if(i[h][0]===d){g=h;break}if(g===-1)i.push([d,...m]);else if(m.length>0){let[p,...f]=m;const x=i[g][1];Cc(x)&&Cc(p)&&(p=vl(!0,x,p)),i[g]=[d,p,...f]}}}}const h2=new cd().freeze();function wl(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Nl(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Sl(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 bm(e){if(!Cc(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function vm(e,n,s){if(!s)throw new Error("`"+e+"` finished async. Use `"+n+"` instead")}function Or(e){return p2(e)?e:new rf(e)}function p2(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function f2(e){return typeof e=="string"||g2(e)}function g2(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const x2="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",ym=[],km={allowDangerousHtml:!0},b2=/^(https?|ircs?|mailto|xmpp)$/i,v2=[{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 si(e){const n=y2(e),s=k2(e);return j2(n.runSync(n.parse(s),s),e)}function y2(e){const n=e.rehypePlugins||ym,s=e.remarkPlugins||ym,i=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...km}:km;return h2().use(tC).use(s).use(JC,i).use(n)}function k2(e){const n=e.children||"",s=new rf;return typeof n=="string"&&(s.value=n),s}function j2(e,n){const s=n.allowedElements,i=n.allowElement,r=n.components,o=n.disallowedElements,l=n.skipHtml,c=n.unwrapDisallowed,u=n.urlTransform||w2;for(const m of v2)Object.hasOwn(n,m.from)&&(""+m.from+(m.to?"use `"+m.to+"` instead":"remove it")+x2+m.id,void 0);return ld(e,d),z1(e,{Fragment:t.Fragment,components:r,ignoreInvalidStyle:!0,jsx:t.jsx,jsxs:t.jsxs,passKeys:!0,passNode:!0});function d(m,h,g){if(m.type==="raw"&&g&&typeof h=="number")return l?g.children.splice(h,1):g.children[h]={type:"text",value:m.value},h;if(m.type==="element"){let p;for(p in fl)if(Object.hasOwn(fl,p)&&Object.hasOwn(m.properties,p)){const f=m.properties[p],x=fl[p];(x===null||x.includes(m.tagName))&&(m.properties[p]=u(String(f||""),p,m))}}if(m.type==="element"){let p=s?!s.includes(m.tagName):o?o.includes(m.tagName):!1;if(!p&&i&&typeof h=="number"&&(p=!i(m,h,g)),p&&g&&typeof h=="number")return c&&m.children?g.children.splice(h,1,...m.children):g.children.splice(h,1),h}}}function w2(e){const n=e.indexOf(":"),s=e.indexOf("?"),i=e.indexOf("#"),r=e.indexOf("/");return n===-1||r!==-1&&n>r||s!==-1&&n>s||i!==-1&&n>i||b2.test(e.slice(0,n))?e:""}function jm(e,n){const s=String(e);if(typeof n!="string")throw new TypeError("Expected character");let i=0,r=s.indexOf(n);for(;r!==-1;)i++,r=s.indexOf(n,r+n.length);return i}function N2(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function S2(e,n,s){const r=Do((s||{}).ignore||[]),o=C2(n);let l=-1;for(;++l<o.length;)af(e,"text",c);function c(d,m){let h=-1,g;for(;++h<m.length;){const p=m[h],f=g?g.children:void 0;if(r(p,f?f.indexOf(p):void 0,g))return;g=p}if(g)return u(d,m)}function u(d,m){const h=m[m.length-1],g=o[l][0],p=o[l][1];let f=0;const v=h.children.indexOf(d);let b=!1,y=[];g.lastIndex=0;let S=g.exec(d.value);for(;S;){const k=S.index,M={index:S.index,input:S.input,stack:[...m,d]};let w=p(...S,M);if(typeof w=="string"&&(w=w.length>0?{type:"text",value:w}:void 0),w===!1?g.lastIndex=k+1:(f!==k&&y.push({type:"text",value:d.value.slice(f,k)}),Array.isArray(w)?y.push(...w):w&&y.push(w),f=k+S[0].length,b=!0),!g.global)break;S=g.exec(d.value)}return b?(f<d.value.length&&y.push({type:"text",value:d.value.slice(f)}),h.children.splice(v,1,...y)):y=[d],v+y.length}}function C2(e){const n=[];if(!Array.isArray(e))throw new TypeError("Expected find and replace tuple or list of tuples");const s=!e[0]||Array.isArray(e[0])?e:[e];let i=-1;for(;++i<s.length;){const r=s[i];n.push([E2(r[0]),M2(r[1])])}return n}function E2(e){return typeof e=="string"?new RegExp(N2(e),"g"):e}function M2(e){return typeof e=="function"?e:function(){return e}}const Cl="phrasing",El=["autolink","link","image","label"];function _2(){return{transforms:[D2],enter:{literalAutolink:R2,literalAutolinkEmail:Ml,literalAutolinkHttp:Ml,literalAutolinkWww:Ml},exit:{literalAutolink:$2,literalAutolinkEmail:I2,literalAutolinkHttp:T2,literalAutolinkWww:P2}}}function A2(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Cl,notInConstruct:El},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Cl,notInConstruct:El},{character:":",before:"[ps]",after:"\\/",inConstruct:Cl,notInConstruct:El}]}}function R2(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function Ml(e){this.config.enter.autolinkProtocol.call(this,e)}function T2(e){this.config.exit.autolinkProtocol.call(this,e)}function P2(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 I2(e){this.config.exit.autolinkEmail.call(this,e)}function $2(e){this.exit(e)}function D2(e){S2(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,L2],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,z2]],{ignore:["link","linkReference"]})}function L2(e,n,s,i,r){let o="";if(!of(r)||(/^w/i.test(n)&&(s=n+s,n="",o="http://"),!F2(s)))return!1;const l=O2(s+i);if(!l[0])return!1;const c={type:"link",title:null,url:o+n+l[0],children:[{type:"text",value:n+l[0]}]};return l[1]?[c,{type:"text",value:l[1]}]:c}function z2(e,n,s,i){return!of(i,!0)||/[-\d_]$/.test(s)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+s,children:[{type:"text",value:n+"@"+s}]}}function F2(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 O2(e){const n=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!n)return[e,void 0];e=e.slice(0,n.index);let s=n[0],i=s.indexOf(")");const r=jm(e,"(");let o=jm(e,")");for(;i!==-1&&r>o;)e+=s.slice(0,i+1),s=s.slice(i+1),i=s.indexOf(")"),o++;return[e,s]}function of(e,n){const s=e.input.charCodeAt(e.index-1);return(e.index===0||Ii(s)||Po(s))&&(!n||s!==47)}lf.peek=J2;function U2(){this.buffer()}function B2(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function H2(){this.buffer()}function q2(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function V2(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=Ps(this.sliceSerialize(e)).toLowerCase(),s.label=n}function W2(e){this.exit(e)}function K2(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=Ps(this.sliceSerialize(e)).toLowerCase(),s.label=n}function G2(e){this.exit(e)}function J2(){return"["}function lf(e,n,s,i){const r=s.createTracker(i);let o=r.move("[^");const l=s.enter("footnoteReference"),c=s.enter("reference");return o+=r.move(s.safe(s.associationId(e),{after:"]",before:o})),c(),l(),o+=r.move("]"),o}function Y2(){return{enter:{gfmFootnoteCallString:U2,gfmFootnoteCall:B2,gfmFootnoteDefinitionLabelString:H2,gfmFootnoteDefinition:q2},exit:{gfmFootnoteCallString:V2,gfmFootnoteCall:W2,gfmFootnoteDefinitionLabelString:K2,gfmFootnoteDefinition:G2}}}function Q2(e){let n=!1;return e&&e.firstLineBlank&&(n=!0),{handlers:{footnoteDefinition:s,footnoteReference:lf},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function s(i,r,o,l){const c=o.createTracker(l);let u=c.move("[^");const d=o.enter("footnoteDefinition"),m=o.enter("label");return u+=c.move(o.safe(o.associationId(i),{before:u,after:"]"})),m(),u+=c.move("]:"),i.children&&i.children.length>0&&(c.shift(4),u+=c.move((n?`
622
+ `:" ")+o.indentLines(o.containerFlow(i,c.current()),n?cf:X2))),d(),u}}function X2(e,n,s){return n===0?e:cf(e,n,s)}function cf(e,n,s){return(s?"":" ")+e}const Z2=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];df.peek=iE;function eE(){return{canContainEols:["delete"],enter:{strikethrough:nE},exit:{strikethrough:sE}}}function tE(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:Z2}],handlers:{delete:df}}}function nE(e){this.enter({type:"delete",children:[]},e)}function sE(e){this.exit(e)}function df(e,n,s,i){const r=s.createTracker(i),o=s.enter("strikethrough");let l=r.move("~~");return l+=s.containerPhrasing(e,{...r.current(),before:l,after:"~"}),l+=r.move("~~"),o(),l}function iE(){return"~"}function aE(e){return e.length}function rE(e,n){const s=n||{},i=(s.align||[]).concat(),r=s.stringLength||aE,o=[],l=[],c=[],u=[];let d=0,m=-1;for(;++m<e.length;){const x=[],v=[];let b=-1;for(e[m].length>d&&(d=e[m].length);++b<e[m].length;){const y=oE(e[m][b]);if(s.alignDelimiters!==!1){const S=r(y);v[b]=S,(u[b]===void 0||S>u[b])&&(u[b]=S)}x.push(y)}l[m]=x,c[m]=v}let h=-1;if(typeof i=="object"&&"length"in i)for(;++h<d;)o[h]=wm(i[h]);else{const x=wm(i);for(;++h<d;)o[h]=x}h=-1;const g=[],p=[];for(;++h<d;){const x=o[h];let v="",b="";x===99?(v=":",b=":"):x===108?v=":":x===114&&(b=":");let y=s.alignDelimiters===!1?1:Math.max(1,u[h]-v.length-b.length);const S=v+"-".repeat(y)+b;s.alignDelimiters!==!1&&(y=v.length+y+b.length,y>u[h]&&(u[h]=y),p[h]=y),g[h]=S}l.splice(1,0,g),c.splice(1,0,p),m=-1;const f=[];for(;++m<l.length;){const x=l[m],v=c[m];h=-1;const b=[];for(;++h<d;){const y=x[h]||"";let S="",k="";if(s.alignDelimiters!==!1){const M=u[h]-(v[h]||0),w=o[h];w===114?S=" ".repeat(M):w===99?M%2?(S=" ".repeat(M/2+.5),k=" ".repeat(M/2-.5)):(S=" ".repeat(M/2),k=S):k=" ".repeat(M)}s.delimiterStart!==!1&&!h&&b.push("|"),s.padding!==!1&&!(s.alignDelimiters===!1&&y==="")&&(s.delimiterStart!==!1||h)&&b.push(" "),s.alignDelimiters!==!1&&b.push(S),b.push(y),s.alignDelimiters!==!1&&b.push(k),s.padding!==!1&&b.push(" "),(s.delimiterEnd!==!1||h!==d-1)&&b.push("|")}f.push(s.delimiterEnd===!1?b.join("").replace(/ +$/,""):b.join(""))}return f.join(`
623
+ `)}function oE(e){return e==null?"":String(e)}function wm(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 lE(e,n,s,i){const r=s.enter("blockquote"),o=s.createTracker(i);o.move("> "),o.shift(2);const l=s.indentLines(s.containerFlow(e,o.current()),cE);return r(),l}function cE(e,n,s){return">"+(s?"":" ")+e}function dE(e,n){return Nm(e,n.inConstruct,!0)&&!Nm(e,n.notInConstruct,!1)}function Nm(e,n,s){if(typeof n=="string"&&(n=[n]),!n||n.length===0)return s;let i=-1;for(;++i<n.length;)if(e.includes(n[i]))return!0;return!1}function Sm(e,n,s,i){let r=-1;for(;++r<s.unsafe.length;)if(s.unsafe[r].character===`
624
+ `&&dE(s.stack,s.unsafe[r]))return/[ \t]/.test(i.before)?"":" ";return`\\
625
+ `}function uE(e,n){const s=String(e);let i=s.indexOf(n),r=i,o=0,l=0;if(typeof n!="string")throw new TypeError("Expected substring");for(;i!==-1;)i===r?++o>l&&(l=o):o=1,r=i+n.length,i=s.indexOf(n,r);return l}function mE(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 hE(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 pE(e,n,s,i){const r=hE(s),o=e.value||"",l=r==="`"?"GraveAccent":"Tilde";if(mE(e,s)){const h=s.enter("codeIndented"),g=s.indentLines(o,fE);return h(),g}const c=s.createTracker(i),u=r.repeat(Math.max(uE(o,r)+1,3)),d=s.enter("codeFenced");let m=c.move(u);if(e.lang){const h=s.enter(`codeFencedLang${l}`);m+=c.move(s.safe(e.lang,{before:m,after:" ",encode:["`"],...c.current()})),h()}if(e.lang&&e.meta){const h=s.enter(`codeFencedMeta${l}`);m+=c.move(" "),m+=c.move(s.safe(e.meta,{before:m,after:`
626
+ `,encode:["`"],...c.current()})),h()}return m+=c.move(`
627
+ `),o&&(m+=c.move(o+`
628
+ `)),m+=c.move(u),d(),m}function fE(e,n,s){return(s?"":" ")+e}function dd(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 gE(e,n,s,i){const r=dd(s),o=r==='"'?"Quote":"Apostrophe",l=s.enter("definition");let c=s.enter("label");const u=s.createTracker(i);let d=u.move("[");return d+=u.move(s.safe(s.associationId(e),{before:d,after:"]",...u.current()})),d+=u.move("]: "),c(),!e.url||/[\0- \u007F]/.test(e.url)?(c=s.enter("destinationLiteral"),d+=u.move("<"),d+=u.move(s.safe(e.url,{before:d,after:">",...u.current()})),d+=u.move(">")):(c=s.enter("destinationRaw"),d+=u.move(s.safe(e.url,{before:d,after:e.title?" ":`
629
+ `,...u.current()}))),c(),e.title&&(c=s.enter(`title${o}`),d+=u.move(" "+r),d+=u.move(s.safe(e.title,{before:d,after:r,...u.current()})),d+=u.move(r),c()),l(),d}function xE(e){const n=e.options.emphasis||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize emphasis with `"+n+"` for `options.emphasis`, expected `*`, or `_`");return n}function lr(e){return"&#x"+e.toString(16).toUpperCase()+";"}function fo(e,n,s){const i=ca(e),r=ca(n);return i===void 0?r===void 0?s==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:r===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:i===1?r===void 0?{inside:!1,outside:!1}:r===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:r===void 0?{inside:!1,outside:!1}:r===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}uf.peek=bE;function uf(e,n,s,i){const r=xE(s),o=s.enter("emphasis"),l=s.createTracker(i),c=l.move(r);let u=l.move(s.containerPhrasing(e,{after:r,before:c,...l.current()}));const d=u.charCodeAt(0),m=fo(i.before.charCodeAt(i.before.length-1),d,r);m.inside&&(u=lr(d)+u.slice(1));const h=u.charCodeAt(u.length-1),g=fo(i.after.charCodeAt(0),h,r);g.inside&&(u=u.slice(0,-1)+lr(h));const p=l.move(r);return o(),s.attentionEncodeSurroundingInfo={after:g.outside,before:m.outside},c+u+p}function bE(e,n,s){return s.options.emphasis||"*"}function vE(e,n){let s=!1;return ld(e,function(i){if("value"in i&&/\r?\n|\r/.test(i.value)||i.type==="break")return s=!0,Nc}),!!((!e.depth||e.depth<3)&&td(e)&&(n.options.setext||s))}function yE(e,n,s,i){const r=Math.max(Math.min(6,e.depth||1),1),o=s.createTracker(i);if(vE(e,s)){const m=s.enter("headingSetext"),h=s.enter("phrasing"),g=s.containerPhrasing(e,{...o.current(),before:`
630
+ `,after:`
631
+ `});return h(),m(),g+`
632
+ `+(r===1?"=":"-").repeat(g.length-(Math.max(g.lastIndexOf("\r"),g.lastIndexOf(`
633
+ `))+1))}const l="#".repeat(r),c=s.enter("headingAtx"),u=s.enter("phrasing");o.move(l+" ");let d=s.containerPhrasing(e,{before:"# ",after:`
634
+ `,...o.current()});return/^[\t ]/.test(d)&&(d=lr(d.charCodeAt(0))+d.slice(1)),d=d?l+" "+d:l,s.options.closeAtx&&(d+=" "+l),u(),c(),d}mf.peek=kE;function mf(e){return e.value||""}function kE(){return"<"}hf.peek=jE;function hf(e,n,s,i){const r=dd(s),o=r==='"'?"Quote":"Apostrophe",l=s.enter("image");let c=s.enter("label");const u=s.createTracker(i);let d=u.move("![");return d+=u.move(s.safe(e.alt,{before:d,after:"]",...u.current()})),d+=u.move("]("),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=s.enter("destinationLiteral"),d+=u.move("<"),d+=u.move(s.safe(e.url,{before:d,after:">",...u.current()})),d+=u.move(">")):(c=s.enter("destinationRaw"),d+=u.move(s.safe(e.url,{before:d,after:e.title?" ":")",...u.current()}))),c(),e.title&&(c=s.enter(`title${o}`),d+=u.move(" "+r),d+=u.move(s.safe(e.title,{before:d,after:r,...u.current()})),d+=u.move(r),c()),d+=u.move(")"),l(),d}function jE(){return"!"}pf.peek=wE;function pf(e,n,s,i){const r=e.referenceType,o=s.enter("imageReference");let l=s.enter("label");const c=s.createTracker(i);let u=c.move("![");const d=s.safe(e.alt,{before:u,after:"]",...c.current()});u+=c.move(d+"]["),l();const m=s.stack;s.stack=[],l=s.enter("reference");const h=s.safe(s.associationId(e),{before:u,after:"]",...c.current()});return l(),s.stack=m,o(),r==="full"||!d||d!==h?u+=c.move(h+"]"):r==="shortcut"?u=u.slice(0,-1):u+=c.move("]"),u}function wE(){return"!"}ff.peek=NE;function ff(e,n,s){let i=e.value||"",r="`",o=-1;for(;new RegExp("(^|[^`])"+r+"([^`]|$)").test(i);)r+="`";for(/[^ \r\n]/.test(i)&&(/^[ \r\n]/.test(i)&&/[ \r\n]$/.test(i)||/^`|`$/.test(i))&&(i=" "+i+" ");++o<s.unsafe.length;){const l=s.unsafe[o],c=s.compilePattern(l);let u;if(l.atBreak)for(;u=c.exec(i);){let d=u.index;i.charCodeAt(d)===10&&i.charCodeAt(d-1)===13&&d--,i=i.slice(0,d)+" "+i.slice(u.index+1)}}return r+i+r}function NE(){return"`"}function gf(e,n){const s=td(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))}xf.peek=SE;function xf(e,n,s,i){const r=dd(s),o=r==='"'?"Quote":"Apostrophe",l=s.createTracker(i);let c,u;if(gf(e,s)){const m=s.stack;s.stack=[],c=s.enter("autolink");let h=l.move("<");return h+=l.move(s.containerPhrasing(e,{before:h,after:">",...l.current()})),h+=l.move(">"),c(),s.stack=m,h}c=s.enter("link"),u=s.enter("label");let d=l.move("[");return d+=l.move(s.containerPhrasing(e,{before:d,after:"](",...l.current()})),d+=l.move("]("),u(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(u=s.enter("destinationLiteral"),d+=l.move("<"),d+=l.move(s.safe(e.url,{before:d,after:">",...l.current()})),d+=l.move(">")):(u=s.enter("destinationRaw"),d+=l.move(s.safe(e.url,{before:d,after:e.title?" ":")",...l.current()}))),u(),e.title&&(u=s.enter(`title${o}`),d+=l.move(" "+r),d+=l.move(s.safe(e.title,{before:d,after:r,...l.current()})),d+=l.move(r),u()),d+=l.move(")"),c(),d}function SE(e,n,s){return gf(e,s)?"<":"["}bf.peek=CE;function bf(e,n,s,i){const r=e.referenceType,o=s.enter("linkReference");let l=s.enter("label");const c=s.createTracker(i);let u=c.move("[");const d=s.containerPhrasing(e,{before:u,after:"]",...c.current()});u+=c.move(d+"]["),l();const m=s.stack;s.stack=[],l=s.enter("reference");const h=s.safe(s.associationId(e),{before:u,after:"]",...c.current()});return l(),s.stack=m,o(),r==="full"||!d||d!==h?u+=c.move(h+"]"):r==="shortcut"?u=u.slice(0,-1):u+=c.move("]"),u}function CE(){return"["}function ud(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 EE(e){const n=ud(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 ME(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 vf(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 _E(e,n,s,i){const r=s.enter("list"),o=s.bulletCurrent;let l=e.ordered?ME(s):ud(s);const c=e.ordered?l==="."?")":".":EE(s);let u=n&&s.bulletLastUsed?l===s.bulletLastUsed:!1;if(!e.ordered){const m=e.children?e.children[0]:void 0;if((l==="*"||l==="-")&&m&&(!m.children||!m.children[0])&&s.stack[s.stack.length-1]==="list"&&s.stack[s.stack.length-2]==="listItem"&&s.stack[s.stack.length-3]==="list"&&s.stack[s.stack.length-4]==="listItem"&&s.indexStack[s.indexStack.length-1]===0&&s.indexStack[s.indexStack.length-2]===0&&s.indexStack[s.indexStack.length-3]===0&&(u=!0),vf(s)===l&&m){let h=-1;for(;++h<e.children.length;){const g=e.children[h];if(g&&g.type==="listItem"&&g.children&&g.children[0]&&g.children[0].type==="thematicBreak"){u=!0;break}}}}u&&(l=c),s.bulletCurrent=l;const d=s.containerFlow(e,i);return s.bulletLastUsed=l,s.bulletCurrent=o,r(),d}function AE(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 RE(e,n,s,i){const r=AE(s);let o=s.bulletCurrent||ud(s);n&&n.type==="list"&&n.ordered&&(o=(typeof n.start=="number"&&n.start>-1?n.start:1)+(s.options.incrementListMarker===!1?0:n.children.indexOf(e))+o);let l=o.length+1;(r==="tab"||r==="mixed"&&(n&&n.type==="list"&&n.spread||e.spread))&&(l=Math.ceil(l/4)*4);const c=s.createTracker(i);c.move(o+" ".repeat(l-o.length)),c.shift(l);const u=s.enter("listItem"),d=s.indentLines(s.containerFlow(e,c.current()),m);return u(),d;function m(h,g,p){return g?(p?"":" ".repeat(l))+h:(p?o:o+" ".repeat(l-o.length))+h}}function TE(e,n,s,i){const r=s.enter("paragraph"),o=s.enter("phrasing"),l=s.containerPhrasing(e,i);return o(),r(),l}const PE=Do(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function IE(e,n,s,i){return(e.children.some(function(l){return PE(l)})?s.containerPhrasing:s.containerFlow).call(s,e,i)}function $E(e){const n=e.options.strong||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize strong with `"+n+"` for `options.strong`, expected `*`, or `_`");return n}yf.peek=DE;function yf(e,n,s,i){const r=$E(s),o=s.enter("strong"),l=s.createTracker(i),c=l.move(r+r);let u=l.move(s.containerPhrasing(e,{after:r,before:c,...l.current()}));const d=u.charCodeAt(0),m=fo(i.before.charCodeAt(i.before.length-1),d,r);m.inside&&(u=lr(d)+u.slice(1));const h=u.charCodeAt(u.length-1),g=fo(i.after.charCodeAt(0),h,r);g.inside&&(u=u.slice(0,-1)+lr(h));const p=l.move(r+r);return o(),s.attentionEncodeSurroundingInfo={after:g.outside,before:m.outside},c+u+p}function DE(e,n,s){return s.options.strong||"*"}function LE(e,n,s,i){return s.safe(e.value,i)}function zE(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 FE(e,n,s){const i=(vf(s)+(s.options.ruleSpaces?" ":"")).repeat(zE(s));return s.options.ruleSpaces?i.slice(0,-1):i}const kf={blockquote:lE,break:Sm,code:pE,definition:gE,emphasis:uf,hardBreak:Sm,heading:yE,html:mf,image:hf,imageReference:pf,inlineCode:ff,link:xf,linkReference:bf,list:_E,listItem:RE,paragraph:TE,root:IE,strong:yf,text:LE,thematicBreak:FE};function OE(){return{enter:{table:UE,tableData:Cm,tableHeader:Cm,tableRow:HE},exit:{codeText:qE,table:BE,tableData:_l,tableHeader:_l,tableRow:_l}}}function UE(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 BE(e){this.exit(e),this.data.inTable=void 0}function HE(e){this.enter({type:"tableRow",children:[]},e)}function _l(e){this.exit(e)}function Cm(e){this.enter({type:"tableCell",children:[]},e)}function qE(e){let n=this.resume();this.data.inTable&&(n=n.replace(/\\([\\|])/g,VE));const s=this.stack[this.stack.length-1];s.type,s.value=n,this.exit(e)}function VE(e,n){return n==="|"?n:e}function WE(e){const n=e||{},s=n.tableCellPadding,i=n.tablePipeAlign,r=n.stringLength,o=s?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
635
+ `,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:g,table:l,tableCell:u,tableRow:c}};function l(p,f,x,v){return d(m(p,x,v),p.align)}function c(p,f,x,v){const b=h(p,x,v),y=d([b]);return y.slice(0,y.indexOf(`
636
+ `))}function u(p,f,x,v){const b=x.enter("tableCell"),y=x.enter("phrasing"),S=x.containerPhrasing(p,{...v,before:o,after:o});return y(),b(),S}function d(p,f){return rE(p,{align:f,alignDelimiters:i,padding:s,stringLength:r})}function m(p,f,x){const v=p.children;let b=-1;const y=[],S=f.enter("table");for(;++b<v.length;)y[b]=h(v[b],f,x);return S(),y}function h(p,f,x){const v=p.children;let b=-1;const y=[],S=f.enter("tableRow");for(;++b<v.length;)y[b]=u(v[b],p,f,x);return S(),y}function g(p,f,x){let v=kf.inlineCode(p,f,x);return x.stack.includes("tableCell")&&(v=v.replace(/\|/g,"\\$&")),v}}function KE(){return{exit:{taskListCheckValueChecked:Em,taskListCheckValueUnchecked:Em,paragraph:JE}}}function GE(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:YE}}}function Em(e){const n=this.stack[this.stack.length-2];n.type,n.checked=e.type==="taskListCheckValueChecked"}function JE(e){const n=this.stack[this.stack.length-2];if(n&&n.type==="listItem"&&typeof n.checked=="boolean"){const s=this.stack[this.stack.length-1];s.type;const i=s.children[0];if(i&&i.type==="text"){const r=n.children;let o=-1,l;for(;++o<r.length;){const c=r[o];if(c.type==="paragraph"){l=c;break}}l===s&&(i.value=i.value.slice(1),i.value.length===0?s.children.shift():s.position&&i.position&&typeof i.position.start.offset=="number"&&(i.position.start.column++,i.position.start.offset++,s.position.start=Object.assign({},i.position.start)))}}this.exit(e)}function YE(e,n,s,i){const r=e.children[0],o=typeof e.checked=="boolean"&&r&&r.type==="paragraph",l="["+(e.checked?"x":" ")+"] ",c=s.createTracker(i);o&&c.move(l);let u=kf.listItem(e,n,s,{...i,...c.current()});return o&&(u=u.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,d)),u;function d(m){return m+l}}function QE(){return[_2(),Y2(),eE(),OE(),KE()]}function XE(e){return{extensions:[A2(),Q2(e),tE(),WE(e),GE()]}}const ZE={tokenize:aM,partial:!0},jf={tokenize:rM,partial:!0},wf={tokenize:oM,partial:!0},Nf={tokenize:lM,partial:!0},eM={tokenize:cM,partial:!0},Sf={name:"wwwAutolink",tokenize:sM,previous:Ef},Cf={name:"protocolAutolink",tokenize:iM,previous:Mf},ai={name:"emailAutolink",tokenize:nM,previous:_f},Js={};function tM(){return{text:Js}}let Si=48;for(;Si<123;)Js[Si]=ai,Si++,Si===58?Si=65:Si===91&&(Si=97);Js[43]=ai;Js[45]=ai;Js[46]=ai;Js[95]=ai;Js[72]=[ai,Cf];Js[104]=[ai,Cf];Js[87]=[ai,Sf];Js[119]=[ai,Sf];function nM(e,n,s){const i=this;let r,o;return l;function l(h){return!Mc(h)||!_f.call(i,i.previous)||md(i.events)?s(h):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(h))}function c(h){return Mc(h)?(e.consume(h),c):h===64?(e.consume(h),u):s(h)}function u(h){return h===46?e.check(eM,m,d)(h):h===45||h===95||qn(h)?(o=!0,e.consume(h),u):m(h)}function d(h){return e.consume(h),r=!0,u}function m(h){return o&&r&&Xn(i.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),n(h)):s(h)}}function sM(e,n,s){const i=this;return r;function r(l){return l!==87&&l!==119||!Ef.call(i,i.previous)||md(i.events)?s(l):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(ZE,e.attempt(jf,e.attempt(wf,o),s),s)(l))}function o(l){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),n(l)}}function iM(e,n,s){const i=this;let r="",o=!1;return l;function l(h){return(h===72||h===104)&&Mf.call(i,i.previous)&&!md(i.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),r+=String.fromCodePoint(h),e.consume(h),c):s(h)}function c(h){if(Xn(h)&&r.length<5)return r+=String.fromCodePoint(h),e.consume(h),c;if(h===58){const g=r.toLowerCase();if(g==="http"||g==="https")return e.consume(h),u}return s(h)}function u(h){return h===47?(e.consume(h),o?d:(o=!0,u)):s(h)}function d(h){return h===null||mo(h)||rn(h)||Ii(h)||Po(h)?s(h):e.attempt(jf,e.attempt(wf,m),s)(h)}function m(h){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),n(h)}}function aM(e,n,s){let i=0;return r;function r(l){return(l===87||l===119)&&i<3?(i++,e.consume(l),r):l===46&&i===3?(e.consume(l),o):s(l)}function o(l){return l===null?s(l):n(l)}}function rM(e,n,s){let i,r,o;return l;function l(d){return d===46||d===95?e.check(Nf,u,c)(d):d===null||rn(d)||Ii(d)||d!==45&&Po(d)?u(d):(o=!0,e.consume(d),l)}function c(d){return d===95?i=!0:(r=i,i=void 0),e.consume(d),l}function u(d){return r||i||!o?s(d):n(d)}}function oM(e,n){let s=0,i=0;return r;function r(l){return l===40?(s++,e.consume(l),r):l===41&&i<s?o(l):l===33||l===34||l===38||l===39||l===41||l===42||l===44||l===46||l===58||l===59||l===60||l===63||l===93||l===95||l===126?e.check(Nf,n,o)(l):l===null||rn(l)||Ii(l)?n(l):(e.consume(l),r)}function o(l){return l===41&&i++,e.consume(l),r}}function lM(e,n,s){return i;function i(c){return c===33||c===34||c===39||c===41||c===42||c===44||c===46||c===58||c===59||c===63||c===95||c===126?(e.consume(c),i):c===38?(e.consume(c),o):c===93?(e.consume(c),r):c===60||c===null||rn(c)||Ii(c)?n(c):s(c)}function r(c){return c===null||c===40||c===91||rn(c)||Ii(c)?n(c):i(c)}function o(c){return Xn(c)?l(c):s(c)}function l(c){return c===59?(e.consume(c),i):Xn(c)?(e.consume(c),l):s(c)}}function cM(e,n,s){return i;function i(o){return e.consume(o),r}function r(o){return qn(o)?s(o):n(o)}}function Ef(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||rn(e)}function Mf(e){return!Xn(e)}function _f(e){return!(e===47||Mc(e))}function Mc(e){return e===43||e===45||e===46||e===95||qn(e)}function md(e){let n=e.length,s=!1;for(;n--;){const i=e[n][1];if((i.type==="labelLink"||i.type==="labelImage")&&!i._balanced){s=!0;break}if(i._gfmAutolinkLiteralWalkedInto){s=!1;break}}return e.length>0&&!s&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),s}const dM={tokenize:bM,partial:!0};function uM(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:fM,continuation:{tokenize:gM},exit:xM}},text:{91:{name:"gfmFootnoteCall",tokenize:pM},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:mM,resolveTo:hM}}}}function mM(e,n,s){const i=this;let r=i.events.length;const o=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);let l;for(;r--;){const u=i.events[r][1];if(u.type==="labelImage"){l=u;break}if(u.type==="gfmFootnoteCall"||u.type==="labelLink"||u.type==="label"||u.type==="image"||u.type==="link")break}return c;function c(u){if(!l||!l._balanced)return s(u);const d=Ps(i.sliceSerialize({start:l.end,end:i.now()}));return d.codePointAt(0)!==94||!o.includes(d.slice(1))?s(u):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(u),e.exit("gfmFootnoteCallLabelMarker"),n(u))}}function hM(e,n){let s=e.length;for(;s--;)if(e[s][1].type==="labelImage"&&e[s][0]==="enter"){e[s][1];break}e[s+1][1].type="data",e[s+3][1].type="gfmFootnoteCallLabelMarker";const i={type:"gfmFootnoteCall",start:Object.assign({},e[s+3][1].start),end:Object.assign({},e[e.length-1][1].end)},r={type:"gfmFootnoteCallMarker",start:Object.assign({},e[s+3][1].end),end:Object.assign({},e[s+3][1].end)};r.end.column++,r.end.offset++,r.end._bufferIndex++;const o={type:"gfmFootnoteCallString",start:Object.assign({},r.end),end:Object.assign({},e[e.length-1][1].start)},l={type:"chunkString",contentType:"string",start:Object.assign({},o.start),end:Object.assign({},o.end)},c=[e[s+1],e[s+2],["enter",i,n],e[s+3],e[s+4],["enter",r,n],["exit",r,n],["enter",o,n],["enter",l,n],["exit",l,n],["exit",o,n],e[e.length-2],e[e.length-1],["exit",i,n]];return e.splice(s,e.length-s+1,...c),e}function pM(e,n,s){const i=this,r=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);let o=0,l;return c;function c(h){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),u}function u(h){return h!==94?s(h):(e.enter("gfmFootnoteCallMarker"),e.consume(h),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",d)}function d(h){if(o>999||h===93&&!l||h===null||h===91||rn(h))return s(h);if(h===93){e.exit("chunkString");const g=e.exit("gfmFootnoteCallString");return r.includes(Ps(i.sliceSerialize(g)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),n):s(h)}return rn(h)||(l=!0),o++,e.consume(h),h===92?m:d}function m(h){return h===91||h===92||h===93?(e.consume(h),o++,d):d(h)}}function fM(e,n,s){const i=this,r=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);let o,l=0,c;return u;function u(f){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionLabelMarker"),d}function d(f){return f===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",m):s(f)}function m(f){if(l>999||f===93&&!c||f===null||f===91||rn(f))return s(f);if(f===93){e.exit("chunkString");const x=e.exit("gfmFootnoteDefinitionLabelString");return o=Ps(i.sliceSerialize(x)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),g}return rn(f)||(c=!0),l++,e.consume(f),f===92?h:m}function h(f){return f===91||f===92||f===93?(e.consume(f),l++,m):m(f)}function g(f){return f===58?(e.enter("definitionMarker"),e.consume(f),e.exit("definitionMarker"),r.includes(o)||r.push(o),Wt(e,p,"gfmFootnoteDefinitionWhitespace")):s(f)}function p(f){return n(f)}}function gM(e,n,s){return e.check(yr,n,e.attempt(dM,n,s))}function xM(e){e.exit("gfmFootnoteDefinition")}function bM(e,n,s){const i=this;return Wt(e,r,"gfmFootnoteDefinitionIndent",5);function r(o){const l=i.events[i.events.length-1];return l&&l[1].type==="gfmFootnoteDefinitionIndent"&&l[2].sliceSerialize(l[1],!0).length===4?n(o):s(o)}}function vM(e){let s=(e||{}).singleTilde;const i={name:"strikethrough",tokenize:o,resolveAll:r};return s==null&&(s=!0),{text:{126:i},insideSpan:{null:[i]},attentionMarkers:{null:[126]}};function r(l,c){let u=-1;for(;++u<l.length;)if(l[u][0]==="enter"&&l[u][1].type==="strikethroughSequenceTemporary"&&l[u][1]._close){let d=u;for(;d--;)if(l[d][0]==="exit"&&l[d][1].type==="strikethroughSequenceTemporary"&&l[d][1]._open&&l[u][1].end.offset-l[u][1].start.offset===l[d][1].end.offset-l[d][1].start.offset){l[u][1].type="strikethroughSequence",l[d][1].type="strikethroughSequence";const m={type:"strikethrough",start:Object.assign({},l[d][1].start),end:Object.assign({},l[u][1].end)},h={type:"strikethroughText",start:Object.assign({},l[d][1].end),end:Object.assign({},l[u][1].start)},g=[["enter",m,c],["enter",l[d][1],c],["exit",l[d][1],c],["enter",h,c]],p=c.parser.constructs.insideSpan.null;p&&fs(g,g.length,0,Io(p,l.slice(d+1,u),c)),fs(g,g.length,0,[["exit",h,c],["enter",l[u][1],c],["exit",l[u][1],c],["exit",m,c]]),fs(l,d-1,u-d+3,g),u=d+g.length-2;break}}for(u=-1;++u<l.length;)l[u][1].type==="strikethroughSequenceTemporary"&&(l[u][1].type="data");return l}function o(l,c,u){const d=this.previous,m=this.events;let h=0;return g;function g(f){return d===126&&m[m.length-1][1].type!=="characterEscape"?u(f):(l.enter("strikethroughSequenceTemporary"),p(f))}function p(f){const x=ca(d);if(f===126)return h>1?u(f):(l.consume(f),h++,p);if(h<2&&!s)return u(f);const v=l.exit("strikethroughSequenceTemporary"),b=ca(f);return v._open=!b||b===2&&!!x,v._close=!x||x===2&&!!b,c(f)}}}class yM{constructor(){this.map=[]}add(n,s,i){kM(this,n,s,i)}consume(n){if(this.map.sort(function(o,l){return o[0]-l[0]}),this.map.length===0)return;let s=this.map.length;const i=[];for(;s>0;)s-=1,i.push(n.slice(this.map[s][0]+this.map[s][1]),this.map[s][2]),n.length=this.map[s][0];i.push(n.slice()),n.length=0;let r=i.pop();for(;r;){for(const o of r)n.push(o);r=i.pop()}this.map.length=0}}function kM(e,n,s,i){let r=0;if(!(s===0&&i.length===0)){for(;r<e.map.length;){if(e.map[r][0]===n){e.map[r][1]+=s,e.map[r][2].push(...i);return}r+=1}e.map.push([n,s,i])}}function jM(e,n){let s=!1;const i=[];for(;n<e.length;){const r=e[n];if(s){if(r[0]==="enter")r[1].type==="tableContent"&&i.push(e[n+1][1].type==="tableDelimiterMarker"?"left":"none");else if(r[1].type==="tableContent"){if(e[n-1][1].type==="tableDelimiterMarker"){const o=i.length-1;i[o]=i[o]==="left"?"center":"right"}}else if(r[1].type==="tableDelimiterRow")break}else r[0]==="enter"&&r[1].type==="tableDelimiterRow"&&(s=!0);n+=1}return i}function wM(){return{flow:{null:{name:"table",tokenize:NM,resolveAll:SM}}}}function NM(e,n,s){const i=this;let r=0,o=0,l;return c;function c(T){let I=i.events.length-1;for(;I>-1;){const P=i.events[I][1].type;if(P==="lineEnding"||P==="linePrefix")I--;else break}const z=I>-1?i.events[I][1].type:null,K=z==="tableHead"||z==="tableRow"?w:u;return K===w&&i.parser.lazy[i.now().line]?s(T):K(T)}function u(T){return e.enter("tableHead"),e.enter("tableRow"),d(T)}function d(T){return T===124||(l=!0,o+=1),m(T)}function m(T){return T===null?s(T):jt(T)?o>1?(o=0,i.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(T),e.exit("lineEnding"),p):s(T):Bt(T)?Wt(e,m,"whitespace")(T):(o+=1,l&&(l=!1,r+=1),T===124?(e.enter("tableCellDivider"),e.consume(T),e.exit("tableCellDivider"),l=!0,m):(e.enter("data"),h(T)))}function h(T){return T===null||T===124||rn(T)?(e.exit("data"),m(T)):(e.consume(T),T===92?g:h)}function g(T){return T===92||T===124?(e.consume(T),h):h(T)}function p(T){return i.interrupt=!1,i.parser.lazy[i.now().line]?s(T):(e.enter("tableDelimiterRow"),l=!1,Bt(T)?Wt(e,f,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(T):f(T))}function f(T){return T===45||T===58?v(T):T===124?(l=!0,e.enter("tableCellDivider"),e.consume(T),e.exit("tableCellDivider"),x):M(T)}function x(T){return Bt(T)?Wt(e,v,"whitespace")(T):v(T)}function v(T){return T===58?(o+=1,l=!0,e.enter("tableDelimiterMarker"),e.consume(T),e.exit("tableDelimiterMarker"),b):T===45?(o+=1,b(T)):T===null||jt(T)?k(T):M(T)}function b(T){return T===45?(e.enter("tableDelimiterFiller"),y(T)):M(T)}function y(T){return T===45?(e.consume(T),y):T===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(T),e.exit("tableDelimiterMarker"),S):(e.exit("tableDelimiterFiller"),S(T))}function S(T){return Bt(T)?Wt(e,k,"whitespace")(T):k(T)}function k(T){return T===124?f(T):T===null||jt(T)?!l||r!==o?M(T):(e.exit("tableDelimiterRow"),e.exit("tableHead"),n(T)):M(T)}function M(T){return s(T)}function w(T){return e.enter("tableRow"),_(T)}function _(T){return T===124?(e.enter("tableCellDivider"),e.consume(T),e.exit("tableCellDivider"),_):T===null||jt(T)?(e.exit("tableRow"),n(T)):Bt(T)?Wt(e,_,"whitespace")(T):(e.enter("data"),N(T))}function N(T){return T===null||T===124||rn(T)?(e.exit("data"),_(T)):(e.consume(T),T===92?L:N)}function L(T){return T===92||T===124?(e.consume(T),N):N(T)}}function SM(e,n){let s=-1,i=!0,r=0,o=[0,0,0,0],l=[0,0,0,0],c=!1,u=0,d,m,h;const g=new yM;for(;++s<e.length;){const p=e[s],f=p[1];p[0]==="enter"?f.type==="tableHead"?(c=!1,u!==0&&(Mm(g,n,u,d,m),m=void 0,u=0),d={type:"table",start:Object.assign({},f.start),end:Object.assign({},f.end)},g.add(s,0,[["enter",d,n]])):f.type==="tableRow"||f.type==="tableDelimiterRow"?(i=!0,h=void 0,o=[0,0,0,0],l=[0,s+1,0,0],c&&(c=!1,m={type:"tableBody",start:Object.assign({},f.start),end:Object.assign({},f.end)},g.add(s,0,[["enter",m,n]])),r=f.type==="tableDelimiterRow"?2:m?3:1):r&&(f.type==="data"||f.type==="tableDelimiterMarker"||f.type==="tableDelimiterFiller")?(i=!1,l[2]===0&&(o[1]!==0&&(l[0]=l[1],h=Ur(g,n,o,r,void 0,h),o=[0,0,0,0]),l[2]=s)):f.type==="tableCellDivider"&&(i?i=!1:(o[1]!==0&&(l[0]=l[1],h=Ur(g,n,o,r,void 0,h)),o=l,l=[o[1],s,0,0])):f.type==="tableHead"?(c=!0,u=s):f.type==="tableRow"||f.type==="tableDelimiterRow"?(u=s,o[1]!==0?(l[0]=l[1],h=Ur(g,n,o,r,s,h)):l[1]!==0&&(h=Ur(g,n,l,r,s,h)),r=0):r&&(f.type==="data"||f.type==="tableDelimiterMarker"||f.type==="tableDelimiterFiller")&&(l[3]=s)}for(u!==0&&Mm(g,n,u,d,m),g.consume(n.events),s=-1;++s<n.events.length;){const p=n.events[s];p[0]==="enter"&&p[1].type==="table"&&(p[1]._align=jM(n.events,s))}return e}function Ur(e,n,s,i,r,o){const l=i===1?"tableHeader":i===2?"tableDelimiter":"tableData",c="tableContent";s[0]!==0&&(o.end=Object.assign({},Zi(n.events,s[0])),e.add(s[0],0,[["exit",o,n]]));const u=Zi(n.events,s[1]);if(o={type:l,start:Object.assign({},u),end:Object.assign({},u)},e.add(s[1],0,[["enter",o,n]]),s[2]!==0){const d=Zi(n.events,s[2]),m=Zi(n.events,s[3]),h={type:c,start:Object.assign({},d),end:Object.assign({},m)};if(e.add(s[2],0,[["enter",h,n]]),i!==2){const g=n.events[s[2]],p=n.events[s[3]];if(g[1].end=Object.assign({},p[1].end),g[1].type="chunkText",g[1].contentType="text",s[3]>s[2]+1){const f=s[2]+1,x=s[3]-s[2]-1;e.add(f,x,[])}}e.add(s[3]+1,0,[["exit",h,n]])}return r!==void 0&&(o.end=Object.assign({},Zi(n.events,r)),e.add(r,0,[["exit",o,n]]),o=void 0),o}function Mm(e,n,s,i,r){const o=[],l=Zi(n.events,s);r&&(r.end=Object.assign({},l),o.push(["exit",r,n])),i.end=Object.assign({},l),o.push(["exit",i,n]),e.add(s+1,0,o)}function Zi(e,n){const s=e[n],i=s[0]==="enter"?"start":"end";return s[1][i]}const CM={name:"tasklistCheck",tokenize:MM};function EM(){return{text:{91:CM}}}function MM(e,n,s){const i=this;return r;function r(u){return i.previous!==null||!i._gfmTasklistFirstContentOfListItem?s(u):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(u),e.exit("taskListCheckMarker"),o)}function o(u){return rn(u)?(e.enter("taskListCheckValueUnchecked"),e.consume(u),e.exit("taskListCheckValueUnchecked"),l):u===88||u===120?(e.enter("taskListCheckValueChecked"),e.consume(u),e.exit("taskListCheckValueChecked"),l):s(u)}function l(u){return u===93?(e.enter("taskListCheckMarker"),e.consume(u),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),c):s(u)}function c(u){return jt(u)?n(u):Bt(u)?e.check({tokenize:_M},n,s)(u):s(u)}}function _M(e,n,s){return Wt(e,i,"whitespace");function i(r){return r===null?s(r):n(r)}}function AM(e){return Fp([tM(),uM(),vM(e),wM(),EM()])}const RM={};function ii(e){const n=this,s=e||RM,i=n.data(),r=i.micromarkExtensions||(i.micromarkExtensions=[]),o=i.fromMarkdownExtensions||(i.fromMarkdownExtensions=[]),l=i.toMarkdownExtensions||(i.toMarkdownExtensions=[]);r.push(AM(s)),o.push(QE()),l.push(XE(s))}const _m=500,Am=100;function Al(e){return e.length>_m?e.slice(-_m):e}function Af(e,n,s){const[i,r]=a.useState([]),[o,l]=a.useState(!1),[c,u]=a.useState(!1),[d,m]=a.useState(null),[h,g]=a.useState(!1),p=a.useRef(null),f=a.useRef(!1),x=a.useRef(0),v=a.useRef(e),b=a.useRef(s),y=a.useRef(n),S=a.useRef(0);(v.current!==e||b.current!==s||y.current!==n)&&(v.current=e,b.current=s,y.current=n,x.current++,f.current=!0,r([]),l(!1),u(!1),m(null),g(!1),p.current&&(p.current(),p.current=null)),a.useEffect(()=>{if(!e||!n){p.current&&(p.current(),p.current=null);return}const _=x.current,N=++S.current;f.current=!1;const L=e,T=s;async function I(){if(!L)return;l(!0),g(!1);try{const K=await _d(L,T,{limit:Am});if(f.current||x.current!==_||S.current!==N)return;r(Al(K.entries)),u(K.hasMore),m(K.total)}catch{if(f.current||x.current!==_||S.current!==N)return;r([]),u(!1),m(null)}finally{!f.current&&x.current===_&&S.current===N&&l(!1)}const z=T?`?projectId=${encodeURIComponent(T)}`:"";p.current=$s(`/api/tasks/${L}/logs/stream${z}`,{events:{"agent:log":K=>{if(!(f.current||x.current!==_))try{const P=JSON.parse(K.data);r(E=>Al([...E,P])),m(E=>E!==null?E+1:null)}catch{}}}})}return I(),()=>{f.current=!0,p.current&&(p.current(),p.current=null)}},[e,n,s]);const M=a.useCallback(async()=>{if(!e||h)return;const _=x.current,N=i.length,L=e;g(!0);try{const T=await _d(L,s,{limit:Am,offset:N});if(f.current||x.current!==_)return;r(I=>{const z=[...T.entries,...I];return Al(z)}),u(T.hasMore),m(T.total)}catch{}finally{g(!1)}},[e,s,i.length,h]),w=a.useCallback(()=>r([]),[]);return{entries:i,loading:o,clear:w,loadMore:M,hasMore:c,total:d,loadingMore:h}}function TM(e){const n=new Date(e),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),o=Math.floor(r/60),l=Math.floor(o/24);return r<1?"just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString()}const Rm={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})},Rf=50,PM={triage:"Plan"};function Tm(e){return e.scrollHeight-(e.scrollTop+e.clientHeight)<=Rf}function _c(e){return[e.taskId,e.timestamp,e.agent??"",e.type,e.text,e.detail??""].join("|")}function IM(e){const n=new Map;return e.map(s=>{const i=_c(s),r=n.get(i)??0;return n.set(i,r+1),`${i}|${r}`})}function $M(e){return e==="tool"||e==="tool_result"||e==="tool_error"}function DM(e,n){return e.agent?$M(e.type)?!0:!n||n.agent!==e.agent||n.type!==e.type:!1}function LM(e,n){const s=[];for(let i=0;i<e.length;i+=1){const r=e[i],o=n[i]??`${_c(r)}|fallback`,l=i>0?e[i-1]:void 0,c=DM(r,l);if(r.type==="text"||r.type==="thinking"){const u=[r];let d=i+1;for(;d<e.length;){const h=e[d];if(h.type!==r.type||h.agent!==r.agent)break;u.push(h),d+=1}const m=n[d-1]??`${_c(e[d-1])}|fallback`;s.push({kind:r.type,entries:u,key:`${o}->${m}`,showBadge:c}),i=d-1;continue}s.push({kind:"single",entry:r,key:o,showBadge:c})}return s}function zM({entries:e,loading:n,executorModel:s,validatorModel:i,planningModel:r,hasMore:o=!1,onLoadMore:l,loadingMore:c=!1,totalCount:u=null}){const d=a.useRef(null),m=a.useRef(0),h=a.useRef(0),g=a.useRef(null),p=a.useRef(null),[f,x]=a.useState(!0),[v,b]=a.useState(!1),[y,S]=a.useState(!1),[k,M]=a.useState(!0),w=a.useMemo(()=>IM(e),[e]),_=a.useMemo(()=>LM(e,w),[e,w]);a.useLayoutEffect(()=>{const E=d.current;if(!E)return;const R=e.length,B=m.current,G=h.current||E.scrollHeight,X=w[0]??null,C=w[w.length-1]??null,$=g.current!==X,A=p.current!==C;if(R>B)if(B===0)E.scrollTop=E.scrollHeight;else{const j=G-(E.scrollTop+E.clientHeight)<=Rf,J=A&&!$,W=$&&!A;if(J&&j&&(E.scrollTop=E.scrollHeight),W){const oe=E.scrollHeight-G;oe>0&&(E.scrollTop+=oe)}}m.current=R,h.current=E.scrollHeight,g.current=X,p.current=C,M(Tm(E))},[e,w]);const N=a.useCallback(()=>{const E=d.current;E&&M(Tm(E))},[]),L=a.useCallback(()=>{const E=d.current;E&&(E.scrollTop=E.scrollHeight,M(!0))},[]),T=a.useCallback(E=>{E.key==="Escape"&&v&&b(!1)},[v]);a.useEffect(()=>{if(v)return document.addEventListener("keydown",T),()=>{document.removeEventListener("keydown",T)}},[v,T]);const I=s?.provider&&s?.modelId,z=i?.provider&&i?.modelId,K=r?.provider&&r?.modelId,P=a.useMemo(()=>{const E=[];return I&&E.push({role:"Executor",provider:s.provider,modelId:s.modelId}),z&&E.push({role:"Reviewer",provider:i.provider,modelId:i.modelId}),K&&E.push({role:"Planning",provider:r.provider,modelId:r.modelId}),E},[I,s,z,i,K,r]);return n&&e.length===0?t.jsx("div",{className:"agent-log-viewer","data-testid":"agent-log-viewer",children:t.jsx("div",{className:"agent-log-loading",children:"Loading agent logs…"})}):e.length===0?t.jsx("div",{className:"agent-log-viewer","data-testid":"agent-log-viewer",children:t.jsx("div",{className:"agent-log-empty",children:"No agent output yet."})}):t.jsxs("div",{className:`agent-log-viewer agent-log-viewer--streaming${v?" agent-log-viewer--fullscreen":""}`,"data-testid":"agent-log-viewer",children:[t.jsxs("div",{className:"agent-log-model-header","data-testid":"agent-log-model-header",children:[t.jsxs("div",{className:"agent-log-model-icons",children:[P.map(E=>t.jsx(Tn,{provider:E.provider,size:"sm"},`${E.role}-${E.provider}-${E.modelId??"default"}`)),t.jsx("button",{className:"agent-log-model-expand-btn",onClick:()=>S(E=>!E),"aria-label":y?"Collapse model details":"Expand model details","aria-expanded":y,"aria-controls":"agent-log-model-details","data-testid":"agent-log-model-expand",children:y?t.jsx(qt,{size:14}):t.jsx(mn,{size:14})})]}),t.jsxs("div",{className:"agent-log-model-header-toggle",children:[t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>x(E=>!E),"aria-label":f?"Switch to plain text mode":"Switch to markdown mode","aria-pressed":f,"data-testid":"agent-log-mode-toggle",title:f?"Show raw text":"Show formatted markdown",children:f?"Markdown":"Plain"}),t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>b(E=>!E),"aria-label":v?"Exit full screen":"Expand agent log to full screen","data-testid":"agent-log-fullscreen-toggle",title:v?"Exit full screen":"Expand agent log to full screen",children:v?t.jsx(mr,{size:14}):t.jsx(So,{size:14})})]}),y&&t.jsxs("div",{id:"agent-log-model-details",className:"agent-log-model-details",children:[t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Executor:"}),I?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Tn,{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:"}),z?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Tn,{provider:i.provider,size:"sm"}),t.jsxs("span",{children:[i.provider,"/",i.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]}),t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Planning:"}),K?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Tn,{provider:r.provider,size:"sm"}),t.jsxs("span",{children:[r.provider,"/",r.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]})]})]}),t.jsxs("div",{ref:d,className:"agent-log-viewer-scroll",onScroll:N,children:[u!==null&&t.jsxs("div",{className:"agent-log-summary","data-testid":"agent-log-summary",children:["Showing ",e.length," of ",u," entries"]}),o&&l&&t.jsx("div",{className:"agent-log-load-more","data-testid":"agent-log-load-more",children:t.jsx("button",{className:"agent-log-mode-toggle",onClick:l,disabled:c,"data-testid":"agent-log-load-more-button",children:c?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:14,className:"animate-spin"}),"Loading…"]}):"Load More"})}),_.map(E=>{const R=E.kind==="single"?E.entry:E.entries[0],B=E.showBadge?t.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:TM(R.timestamp)}):null,G=E.showBadge?t.jsxs("span",{className:"agent-log-badge-row",children:[t.jsxs("span",{className:"agent-log-agent-badge",children:["[",PM[R.agent]??R.agent,"]"]}),B]}):null;if(E.kind==="single"){const{entry:C}=E;if(C.type==="tool")return t.jsxs("div",{className:"agent-log-tool",children:[G,"⚡ ",C.text,C.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",C.detail]})]},E.key);if(C.type==="tool_result")return t.jsxs("div",{className:"agent-log-tool-result",children:[G,"✓ ",C.text,C.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",C.detail]})]},E.key);if(C.type==="tool_error")return t.jsxs("div",{className:"agent-log-tool-error",children:[G,"✗ ",C.text,C.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",C.detail]})]},E.key)}const X=E.kind==="single"?R.text:E.entries.map(C=>C.text).join("");return E.kind==="thinking"?t.jsxs("div",{className:"agent-log-thinking",children:[G,f?t.jsx("div",{className:"markdown-body",children:t.jsx(si,{remarkPlugins:[ii],components:Rm,children:X})}):X]},E.key):t.jsxs("div",{className:"agent-log-text",children:[G,f?t.jsx("div",{className:"markdown-body",children:t.jsx(si,{remarkPlugins:[ii],components:Rm,children:X})}):X]},E.key)}),!k&&t.jsxs("button",{type:"button",className:"agent-log-return-to-live",onClick:L,"data-testid":"agent-log-return-to-live",children:[t.jsx(qt,{size:12}),t.jsx("span",{children:"Live"})]})]})]})}function da(e){return e??void 0}function Br(e){return{provider:da(e.modelProvider),modelId:da(e.modelId)}}function Hr(e){return{provider:da(e.validatorModelProvider),modelId:da(e.validatorModelId)}}function qr(e){return{provider:da(e.planningModelProvider),modelId:da(e.planningModelId)}}function FM(e,n){return e.modelProvider&&e.modelId?{provider:e.modelProvider,modelId:e.modelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function OM(e,n){return e.validatorModelProvider&&e.validatorModelId?{provider:e.validatorModelProvider,modelId:e.validatorModelId}:n?.validatorProvider&&n.validatorModelId?{provider:n.validatorProvider,modelId:n.validatorModelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function UM(e,n){return e.planningModelProvider&&e.planningModelId?{provider:e.planningModelProvider,modelId:e.planningModelId}:n?.planningProvider&&n.planningModelId?{provider:n.planningProvider,modelId:n.planningModelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function Rl(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 Tl(e){return e.provider&&e.modelId?`${e.provider}/${e.modelId}`:""}function Pl(e,n){return e.provider===n.provider&&e.modelId===n.modelId}function BM(e,n){const i={executor:"Executor",validator:"Reviewer",planning:"Planning"}[e]||e;return!n.provider||!n.modelId?`${i} model set to default`:`${i} model set to ${n.provider}/${n.modelId}`}function HM({task:e,addToast:n,onTaskUpdated:s,settings:i}){const[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState([]),[m,h]=a.useState(!1),[g,p]=a.useState(null),[f,x]=a.useState(()=>Br(e)),[v,b]=a.useState(()=>Br(e)),[y,S]=a.useState(()=>Hr(e)),[k,M]=a.useState(()=>Hr(e)),[w,_]=a.useState(()=>qr(e)),[N,L]=a.useState(()=>qr(e)),[T,I]=a.useState(()=>e.thinkingLevel??null),[z,K]=a.useState(()=>e.thinkingLevel??null),[P,E]=a.useState(null),R=a.useRef(e.id);a.useEffect(()=>{h(!0),p(null),os().then(ue=>{o(ue.models),c(ue.favoriteProviders),d(ue.favoriteModels)}).catch(ue=>{p(ue.message||"Failed to load models")}).finally(()=>{h(!1)})},[]);const B=a.useCallback(async ue=>{const ye=l,Me=ye.includes(ue)?ye.filter(ze=>ze!==ue):[ue,...ye];c(Me);try{await an({favoriteProviders:Me,favoriteModels:u})}catch{c(ye),n("Failed to update favorites","error")}},[l,u,n]),G=a.useCallback(async ue=>{const ye=u,Me=ye.includes(ue)?ye.filter(ze=>ze!==ue):[ue,...ye];d(Me);try{await an({favoriteProviders:l,favoriteModels:Me})}catch{d(ye),n("Failed to update model favorites","error")}},[u,l,n]);a.useEffect(()=>{R.current=e.id;const ue=Br(e),ye=Hr(e),ie=qr(e);x(ue),b(ue),S(ye),M(ye),_(ie),L(ie);const Me=e.thinkingLevel??null;I(Me),K(Me),E(null)},[e.id,e.modelProvider,e.modelId,e.validatorModelProvider,e.validatorModelId,e.planningModelProvider,e.planningModelId,e.thinkingLevel]);const X=a.useMemo(()=>Tl(f),[f]),C=a.useMemo(()=>Tl(y),[y]),$=a.useMemo(()=>Tl(w),[w]),A=a.useMemo(()=>FM(e,i),[e,i]),j=a.useMemo(()=>OM(e,i),[e,i]),J=a.useMemo(()=>UM(e,i),[e,i]),W=P!==null,oe=a.useCallback(async(ue,ye)=>{const ie=e.id,Me=v,ze=k,Be=N;E(ue);try{const Je=s?ue==="executor"?{modelProvider:ye.provider??null,modelId:ye.modelId??null}:ue==="validator"?{validatorModelProvider:ye.provider??null,validatorModelId:ye.modelId??null}:{planningModelProvider:ye.provider??null,planningModelId:ye.modelId??null}:{modelProvider:(ue==="executor"?ye:v).provider??null,modelId:(ue==="executor"?ye:v).modelId??null,validatorModelProvider:(ue==="validator"?ye:k).provider??null,validatorModelId:(ue==="validator"?ye:k).modelId??null,planningModelProvider:(ue==="planning"?ye:N).provider??null,planningModelId:(ue==="planning"?ye:N).modelId??null},Ye=await Zs(ie,Je);if(R.current!==ie)return;const Ge=Br(Ye),it=Hr(Ye),_e=qr(Ye);b(Ge),x(Ge),M(it),S(it),L(_e),_(_e),s?.(Ye),n(BM(ue,{executor:Ge,validator:it,planning:_e}[ue]),"success")}catch(Je){if(R.current!==ie)return;ue==="executor"?x(Me):ue==="validator"?S(ze):_(Be),n(je(Je)||"Failed to save model settings","error")}finally{R.current===ie&&E(null)}},[e.id,v,k,N,n,s]),he=a.useCallback(ue=>{const ye=Rl(ue);x(ye),!Pl(ye,v)&&oe("executor",ye)},[v,oe]),se=a.useCallback(ue=>{const ye=Rl(ue);S(ye),!Pl(ye,k)&&oe("validator",ye)},[k,oe]),fe=a.useCallback(ue=>{const ye=Rl(ue);_(ye),!Pl(ye,N)&&oe("planning",ye)},[N,oe]),U=a.useCallback(async ue=>{const ye=e.id,ie=z,Me=ue===""?null:ue;I(Me),E("thinking");try{const ze=await Zs(ye,{thinkingLevel:Me});if(R.current!==ye)return;const Be=ze.thinkingLevel??null;K(Be),I(Be),s?.(ze);const Je=i?.defaultThinkingLevel??"off";n(Be===null?`Thinking level set to default (${Je})`:`Thinking level set to ${Be}`,"success")}catch(ze){if(R.current!==ye)return;I(ie),n(je(ze)||"Failed to save thinking level","error")}finally{R.current===ye&&E(null)}},[e.id,z,i,n,s]),Ne=!v.provider&&!v.modelId,ee=!k.provider&&!k.modelId,ve=!N.provider&&!N.modelId;return t.jsxs("div",{className:"model-selector-tab",children:[t.jsx("h4",{children:"Model Configuration"}),t.jsx("p",{className:"model-selector-intro",children:"Override the AI models used for this task. When not specified, project or global defaults are used."}),m?t.jsx("div",{className:"model-selector-loading",children:"Loading available models…"}):g?t.jsxs("div",{className:"model-selector-error",children:["Error loading models: ",g,t.jsx("button",{className:"btn btn-sm",onClick:()=>{h(!0),p(null),os().then(ue=>{o(ue.models),c(ue.favoriteProviders),d(ue.favoriteModels)}).catch(ue=>p(ue.message)).finally(()=>h(!1))},style:{marginLeft:"8px"},children:"Retry"})]}):r.length===0?t.jsx("div",{className:"model-selector-empty",children:"No models available. Configure authentication in Settings to enable model selection."}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"executorModel",children:"Executor Model"}),t.jsx("div",{className:"model-selector-current",children:Ne?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",A.provider&&A.modelId?` (${A.provider}/${A.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[v.provider&&t.jsx(Tn,{provider:v.provider,size:"sm"}),v.provider,"/",v.modelId]})}),t.jsx(Ln,{id:"executorModel",label:"Executor Model",value:X,onChange:he,models:r,disabled:W,placeholder:"Select executor model…",favoriteProviders:l,onToggleFavorite:B,favoriteModels:u,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:[k.provider&&t.jsx(Tn,{provider:k.provider,size:"sm"}),k.provider,"/",k.modelId]})}),t.jsx(Ln,{id:"validatorModel",label:"Reviewer Model",value:C,onChange:se,models:r,disabled:W,placeholder:"Select reviewer model…",favoriteProviders:l,onToggleFavorite:B,favoriteModels:u,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:ve?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(Tn,{provider:N.provider,size:"sm"}),N.provider,"/",N.modelId]})}),t.jsx(Ln,{id:"planningModel",label:"Planning Model",value:$,onChange:fe,models:r,disabled:W,placeholder:"Select planning model…",favoriteProviders:l,onToggleFavorite:B,favoriteModels:u,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:z===null?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default (",i?.defaultThinkingLevel??"off",")"]}):t.jsx("span",{className:"model-badge model-badge-custom",children:z})}),t.jsxs("select",{id:"thinkingLevel",value:T??"",onChange:ue=>U(ue.target.value),disabled:W,className:"thinking-level-select",children:[t.jsxs("option",{value:"",children:["Default (",i?.defaultThinkingLevel??"off",")"]}),t.jsx("option",{value:"off",children:"Off"}),t.jsx("option",{value:"minimal",children:"Minimal"}),t.jsx("option",{value:"low",children:"Low"}),t.jsx("option",{value:"medium",children:"Medium"}),t.jsx("option",{value:"high",children:"High"})]}),t.jsx("small",{children:"Controls the reasoning effort for the AI agent. Higher levels use more tokens."})]}),t.jsx("div",{className:"model-selector-status",children:Ne&&ee&&ve&&z===null?"Using project or global default models.":"Model settings are up to date."})]})]})}const qM={open:t.jsx(ko,{size:16}),closed:t.jsx(ur,{size:16}),merged:t.jsx($h,{size:16})};function VM({taskId:e,projectId:n,prInfo:s,automationStatus:i,autoMerge:r=!1,prAuthAvailable:o,onPrCreated:l,onPrUpdated:c,addToast:u}){const[d,m]=a.useState(!1),[h,g]=a.useState(""),[p,f]=a.useState(""),[x,v]=a.useState(!1),[b,y]=a.useState(!1),[S,k]=a.useState(null),M=a.useCallback(async()=>{if(h.trim()){v(!0);try{const L=await Qv(e,{title:h.trim(),body:p.trim()||void 0},n);l(L),m(!1),g(""),f(""),u(`Created PR #${L.number}`,"success")}catch(L){u(je(L)||"Failed to create PR","error")}finally{v(!1)}}},[e,h,p,n,l,u]),w=a.useCallback(async()=>{if(s){y(!0);try{const L=await Xv(e,n);k(L),c(L.prInfo),u("PR status refreshed","success")}catch(L){u(je(L)||"Failed to refresh PR","error")}finally{y(!1)}}},[e,s,n,c,u]);if(!s)return i==="creating-pr"?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(hs,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsx("div",{className:"pr-hint pr-hint--muted",children:"fn is creating a pull request automatically for this task."})]}):r?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(hs,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsx("div",{className:"pr-hint pr-hint--muted",children:"Auto-merge will handle this task automatically."})]}):d?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(hs,{size:16,className:"pr-section-icon"}),"Create Pull Request"]}),t.jsxs("div",{className:"pr-form",children:[t.jsx("input",{type:"text",placeholder:"PR title",value:h,onChange:L=>g(L.target.value),disabled:x,className:"pr-input"}),t.jsx("textarea",{placeholder:"PR description (optional)",value:p,onChange:L=>f(L.target.value),disabled:x,className:"pr-textarea",rows:3}),t.jsxs("div",{className:"pr-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>m(!1),disabled:x,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:M,disabled:!h.trim()||x,children:x?"Creating…":"Create PR"})]})]})]}):t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(hs,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>m(!0),disabled:!o,title:o?"Create a PR for this task":"PR auth unavailable — run 'gh auth login'",children:[t.jsx(Xt,{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 _=qM[s.status]??t.jsx(ko,{size:16}),N=S?.blockingReasons??[];return t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(hs,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsxs("div",{className:`pr-card pr-card--status-${s.status}`,children:[t.jsxs("div",{className:"pr-header",children:[t.jsx("span",{className:"pr-status-icon",children:_}),t.jsx("span",{className:`pr-status-badge pr-status-badge--${s.status}`,children:s.status}),t.jsxs("span",{className:"pr-number",children:["#",s.number]}),t.jsx("div",{className:"pr-spacer"}),t.jsx("button",{className:"btn btn-sm pr-refresh-btn",onClick:w,disabled:b,title:"Refresh PR status",children:t.jsx(wn,{size:14,style:{verticalAlign:"middle",opacity:b?.5:1}})})]}),t.jsx("div",{className:"pr-title",children:s.title}),t.jsxs("div",{className:"pr-meta",children:[t.jsx("span",{children:s.headBranch}),t.jsx("span",{className:"pr-meta-arrow",children:"→"}),t.jsx("span",{children:s.baseBranch})]}),i==="merging-pr"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:"fn is merging this pull request automatically."}),i==="awaiting-pr-checks"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:N.length>0?`Waiting for: ${N.join("; ")}`:"Waiting for required checks or review feedback before auto-merge."}),s.status==="merged"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:"This PR is merged. fn will finish local cleanup and move the task to Done."}),t.jsxs("div",{className:"pr-footer",children:[s.commentCount>0&&t.jsxs("span",{className:"pr-comments",children:[t.jsx(ui,{size:14}),s.commentCount]}),t.jsxs("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"pr-link",children:[t.jsx(Yg,{size:14}),"View on GitHub"]})]})]})]})}const Pm=2e3;function WM(e){const n=e.updatedAt||e.createdAt,s=new Date(n).toLocaleString();return e.updatedAt?`${s} (edited)`:s}function KM(e){return e==="agent"||e==="system"}function GM({task:e,onTaskUpdated:n,addToast:s,currentAuthor:i="user",projectId:r}){const[o,l]=a.useState(""),[c,u]=a.useState(null),[d,m]=a.useState(""),[h,g]=a.useState(!1),[p,f]=a.useState(null),x=a.useMemo(()=>[...e.comments||[]].sort((_,N)=>new Date(N.createdAt).getTime()-new Date(_.createdAt).getTime()),[e.comments]),v=o.length>Pm;async function b(){const _=o.trim();if(_){g(!0);try{const N=await Av(e.id,_,r);l(""),n?.(N),s("Comment added","success")}catch(N){s(je(N)||"Failed to add comment","error")}finally{g(!1)}}}async function y(_){const N=d.trim();if(N){g(!0);try{const L=await Sv(e.id,_,N,r);u(null),m(""),n?.(L),s("Comment updated","success")}catch(L){s(je(L)||"Failed to update comment","error")}finally{g(!1)}}}async function S(_){f(_);try{const N=await Cv(e.id,_,r);n?.(N),s("Comment deleted","success")}catch(N){s(je(N)||"Failed to delete comment","error")}finally{f(null)}}function k(_){_.key==="Enter"&&(_.ctrlKey||_.metaKey)&&(_.preventDefault(),b())}return t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Comments"}),x.length===0?t.jsx("div",{className:"detail-log-empty",children:"No comments yet."}):t.jsx("div",{className:"detail-activity-list",children:x.map(_=>{const N=_.author===i,L=c===_.id,T=KM(_.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?t.jsx("span",{className:"ai-guidance-badge","data-testid":"ai-guidance-badge",children:"AI Guidance"}):t.jsx("strong",{children:_.author}),t.jsx("span",{className:"detail-log-timestamp",children:WM(_)})]}),N&&!L?t.jsxs("div",{className:"comments-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{u(_.id),m(_.text)},children:"Edit"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void S(_.id),disabled:p===_.id,children:p===_.id?"Deleting…":"Delete"})]}):null]}),L?t.jsxs("div",{className:"comments-edit-form",children:[t.jsx("textarea",{value:d,onChange:I=>m(I.target.value),rows:3,className:"comments-textarea"}),t.jsxs("div",{className:"comments-edit-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{u(null),m("")},disabled:h,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void y(_.id),disabled:h||!d.trim(),children:"Save"})]})]}):t.jsx("div",{className:"detail-log-outcome comments-outcome-text",children:_.text})]},_.id)})}),t.jsxs("div",{className:"comments-compose-form",children:[t.jsx("textarea",{value:o,onChange:_=>l(_.target.value),onKeyDown:k,rows:3,placeholder:"Add a comment",className:"comments-textarea"}),t.jsxs("div",{className:"comments-footer-row",children:[t.jsxs("span",{className:`comments-char-count${v?" comments-char-count--over":""}`,children:[o.length," / ",Pm]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void b(),disabled:h||!o.trim()||v,children:h?"Posting…":"Add Comment"})]})]})]})}function JM(e){return e?e.slice(0,7):"Unknown"}function YM({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:JM(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 Tf(e){return e.split(`
637
+ `).map((s,i)=>{let r="";return s.startsWith("+")&&!s.startsWith("+++")?r="diff-add":s.startsWith("-")&&!s.startsWith("---")?r="diff-del":s.startsWith("@@")&&(r="diff-hunk"),r?t.jsx("span",{className:r,children:`${s}
638
+ `},i):t.jsx(Zr.Fragment,{children:`${s}
639
+ `},i)})}function Im(e,n=60){if(!e||e.length<=n)return e;if(n<4)return e.slice(0,n);const s="...",i=e.lastIndexOf("/");if(i===-1){const m=Math.max(1,n-s.length);return e.slice(0,m)+s}const r=[];for(let m=1;m<e.length;m++)e[m]==="/"&&r.push(m);const o=n-s.length;let l=null,c=-1;for(let m=r.length-1;m>=0;m--){const h=r[m],g=e.slice(h);if(g.length>o)continue;const p=o-g.length;for(let f=0;f<r.length;f++){const x=r[f],v=e.slice(0,x);v.length<=p&&v.length+s.length+g.length<=n&&v.length+g.length>c&&(c=v.length+g.length,l=v+s+g)}}if(l)return l;const u=e.slice(i);if(s.length+u.length<=n)return s+u;const d=n-s.length;return s+e.slice(e.length-d)}function QM(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function XM({isOpen:e,taskId:n,files:s,stats:i,mergeDetails:r,column:o,onClose:l,onRefresh:c}){const[u,d]=a.useState(null),[m,h]=a.useState(!0),g=a.useRef(null);Gs(g,e,"fusion:changes-diff-modal-size");const p=fi(l);a.useEffect(()=>{s.length>0&&u===null&&d(0)},[s,u]);const f=a.useCallback(()=>{d(y=>y!==null&&y>0?y-1:y)},[]),x=a.useCallback(()=>{d(y=>y!==null&&y<s.length-1?y+1:y)},[]);if(a.useEffect(()=>{if(!e)return;const y=S=>{if(S.key==="Escape"){l();return}S.key==="ArrowUp"&&(S.metaKey||S.ctrlKey)&&(S.preventDefault(),f()),S.key==="ArrowDown"&&(S.metaKey||S.ctrlKey)&&(S.preventDefault(),x())};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[e,l,f,x]),!e)return null;const v=u!==null?s[u]:null,b=o==="done";return t.jsx("div",{className:"modal-overlay open",...p,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal changes-diff-modal",ref:g,children:[t.jsxs("div",{className:"modal-header changes-diff-modal-header",children:[t.jsxs("div",{className:"changes-diff-header-title",children:[t.jsx(Ts,{size:18}),t.jsxs("span",{children:["Changes — ",n]}),t.jsxs("span",{className:"changes-stat-summary",children:[t.jsxs("span",{className:"diff-add",children:["+",i.additions]})," ",t.jsxs("span",{className:"diff-del",children:["-",i.deletions]})]})]}),t.jsxs("div",{className:"changes-diff-header-actions",children:[s.length>0&&t.jsxs("div",{className:"changes-nav",children:[t.jsx("button",{className:"btn btn-sm btn-icon",onClick:f,disabled:u===null||u<=0,title:"Previous file (Ctrl+↑)","aria-label":"Previous file",children:t.jsx(yo,{size:14})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:u!==null?`${u+1}/${s.length}`:`—/${s.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:x,disabled:u===null||u>=s.length-1,title:"Next file (Ctrl+↓)","aria-label":"Next file",children:t.jsx(mn,{size:14})})]}),t.jsx("button",{className:`btn btn-sm ${m?"btn-primary":""}`,onClick:()=>h(y=>!y),title:m?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(so,{size:14})}),c&&t.jsxs("button",{className:"btn btn-sm",onClick:c,children:[t.jsx(wn,{size:14}),"Refresh"]}),t.jsx("button",{className:"modal-close",onClick:l,"aria-label":"Close",children:t.jsx(zt,{size:20})})]})]}),t.jsxs("div",{className:"changes-diff-body",children:[t.jsxs("div",{className:"changes-diff-sidebar",children:[b&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(er,{size:14}),t.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergeCommitMessage&&t.jsx("div",{className:"commit-diff-message",children:r.mergeCommitMessage}),r.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),t.jsx("div",{className:"changes-diff-file-list",children:s.map((y,S)=>t.jsxs("button",{className:`changes-diff-file-item ${u===S?"selected":""}`,onClick:()=>d(S),title:y.path,children:[t.jsx("span",{className:`changes-file-status changes-file-status--${y.status}`,children:QM(y.status)}),t.jsx("span",{className:"changes-diff-file-path",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:Tf(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(Ts,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to view its diff"})]})})]})]})})}function $m(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function ZM({taskId:e,worktree:n,projectId:s,column:i,mergeDetails:r,modifiedFiles:o}){const[l,c]=a.useState([]),[u,d]=a.useState({filesChanged:0,additions:0,deletions:0}),[m,h]=a.useState(!0),[g,p]=a.useState(null),[f,x]=a.useState(new Set),[v,b]=a.useState(null),[y,S]=a.useState(!0),[k,M]=a.useState(!1),w=i==="done",_=w&&!!r?.commitSha,N=i==="in-progress"||i==="in-review"||_,L=a.useCallback(async()=>{if(!N){h(!1);return}try{h(!0),p(null);const P=await ep(e,void 0,s),E=P.files.map(R=>({path:R.path,status:R.status,additions:R.additions,deletions:R.deletions,patch:R.patch}));c(E),d(P.stats),E.length>0&&(x(new Set([E[0].path])),b(0))}catch(P){p(je(P)||"Failed to load diff")}finally{h(!1)}},[e,s,N]);a.useEffect(()=>{L()},[L]);const T=P=>{x(E=>{const R=new Set(E);if(R.has(P))R.delete(P);else{R.add(P);const B=l.findIndex(G=>G.path===P);B!==-1&&b(B)}return R})},I=P=>{if(P<0||P>=l.length)return;const E=l[P].path;x(new Set([E])),b(P)},z=v!==null&&v>0,K=v!==null&&v<l.length-1;if(m)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--loading",children:[t.jsx("div",{className:"loading-spinner"}),t.jsx("span",{children:"Loading changes..."})]})});if(g)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--error",children:[t.jsx(Zn,{size:16}),t.jsxs("span",{children:["Error loading changes: ",g]})]})});if(!w&&!n)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Ts,{size:24}),t.jsx("p",{children:"No worktree available for this task."}),t.jsx("span",{className:"task-changes-state-hint",children:"Changes will be shown once the task is in progress."})]})});if(w&&!_){const P=r?.filesChanged,E=r?.insertions,R=r?.deletions,B=P!=null||E!=null||R!=null;return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Ts,{size:24}),t.jsx("p",{children:"Detailed file changes unavailable."}),t.jsx("span",{className:"task-changes-state-hint",children:B?`Merge summary: ${P??0} file${(P??0)===1?"":"s"} changed, +${E??0} additions, -${R??0} deletions.`:"No merge commit was recorded for this task."})]})})}return l.length===0?w&&o&&o.length>0?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(er,{size:14}),t.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Ts,{size:24}),t.jsxs("p",{children:[o.length," file",o.length===1?"":"s"," modified during execution."]}),t.jsx("span",{className:"task-changes-state-hint",children:"The recorded merge commit has no diff (likely collapsed into a squash on main). Showing file paths only — patches unavailable."})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:o.map(P=>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:$m("unknown")}),t.jsx("span",{className:"changes-file-path",title:P,children:Im(P)})]})},P))})]}):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Ts,{size:24}),t.jsx("p",{children:"No files modified."}),t.jsx("span",{className:"task-changes-state-hint",children: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(er,{size:14}),t.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergeCommitMessage&&t.jsx("div",{className:"commit-diff-message",children:r.mergeCommitMessage}),r.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),t.jsxs("div",{className:"changes-header",children:[t.jsxs("div",{className:"task-changes-header-title",children:[t.jsxs("h4",{children:[t.jsx(Ts,{size:16}),"Files Changed (",u.filesChanged,")"]}),t.jsxs("span",{className:"task-changes-stats changes-stat-summary",children:[t.jsxs("span",{className:"diff-add",children:["+",u.additions]})," ",t.jsxs("span",{className:"diff-del",children:["-",u.deletions]})]})]}),t.jsxs("div",{className:"changes-header-actions-wrapper",children:[t.jsxs("div",{className:"changes-header-actions",children:[l.length>0&&t.jsxs("div",{className:"changes-nav",children:[t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>z&&I(v-1),disabled:!z,title:"Previous file","aria-label":"Previous file",children:t.jsx(yo,{size:14})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:v!==null?`${v+1}/${l.length}`:`—/${l.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>K&&I(v+1),disabled:!K,title:"Next file","aria-label":"Next file",children:t.jsx(mn,{size:14})})]}),t.jsx("button",{className:`btn btn-sm ${y?"btn-primary":""}`,onClick:()=>S(P=>!P),title:y?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(so,{size:14})})]}),t.jsxs("div",{className:"changes-header-actions-secondary",children:[t.jsx("button",{className:"btn btn-sm",onClick:L,disabled:m,children:"Refresh"}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>M(!0),title:"Expand to full-screen diff view","aria-label":"Expand diff view",children:t.jsx(So,{size:14})})]})]})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:l.map(P=>{const E=f.has(P.path);return t.jsxs("div",{className:`changes-file-item ${E?"expanded":""}`,children:[t.jsxs("button",{className:"changes-file-header",onClick:()=>T(P.path),children:[t.jsx("span",{className:"changes-file-toggle",children:E?t.jsx(qt,{size:14}):t.jsx(mn,{size:14})}),t.jsx("span",{className:`changes-file-status changes-file-status--${P.status}`,title:P.status,children:$m(P.status)}),t.jsx("span",{className:"changes-file-path",title:P.path,children:Im(P.path)}),t.jsxs("span",{className:"changes-file-stat",title:`+${P.additions} -${P.deletions}`,children:["+",P.additions," -",P.deletions]})]}),E&&P.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:Tf(P.patch)})})})]},P.path)})}),t.jsx(XM,{isOpen:k,taskId:e,files:l,stats:u,mergeDetails:r,column:i,onClose:()=>M(!1),onRefresh:L})]})}function Dm(e){return{executorValue:e?.executorProvider&&e?.executorModelId?`${e.executorProvider}/${e.executorModelId}`:"",validatorValue:e?.validatorProvider&&e?.validatorModelId?`${e.validatorProvider}/${e.validatorModelId}`:""}}function e_(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function K$(e,n){const s=e_(e),i=new Set(n.map(c=>c.id));if(!i.has(s))return s;const r=30;let o=s,l=1;for(;i.has(o)&&l<100;){const c=`-${l}`;o=`${s.slice(0,r-c.length)}${c}`,l++}return o}const Lm=["image/png","image/jpeg","image/gif","image/webp"];function t_(e,n,s){const i=e==="post-merge"?"phase-badge--post-merge":"phase-badge--pre-merge";return t.jsx("span",{className:`phase-badge ${i}`,"data-testid":`${s}-${n}`,children:e==="post-merge"?"Post-merge":"Pre-merge"})}function Pf({mode:e,description:n,onDescriptionChange:s,title:i,onTitleChange:r,dependencies:o,onDependenciesChange:l,priority:c,onPriorityChange:u,executorModel:d,onExecutorModelChange:m,validatorModel:h,onValidatorModelChange:g,planningModel:p,onPlanningModelChange:f,thinkingLevel:x,onThinkingLevelChange:v,presetMode:b,onPresetModeChange:y,selectedPresetId:S,onSelectedPresetIdChange:k,selectedWorkflowSteps:M,onWorkflowStepsChange:w,onDefaultOnApplied:_,pendingImages:N,onImagesChange:L,tasks:T,projectId:I,disabled:z=!1,addToast:K,isActive:P=!0,onAutoSaveDescription:E,onPlanningMode:R,onSubtaskBreakdown:B,onClose:G,renderBelowPrimary:X,renderBelowModelConfiguration:C,hideDependencies:$,autoExpandMoreOptionsOnSelection:A=!0,reviewLevel:j,onReviewLevelChange:J,executionMode:W,onExecutionModeChange:oe}){const he=($?!1:o.length>0)||N.length>0||M.length>0||b!=="default"||(c??ps)!==ps||d!==""||h!==""||(p||"")!==""||(x||"")!==""||j!==void 0||W==="fast",[se,fe]=a.useState(!1),[U,Ne]=a.useState(A?he:!1),[ee,ve]=a.useState(""),[ue,ye]=a.useState([]),[ie,Me]=a.useState([]),[ze,Be]=a.useState([]),[Je,Ye]=a.useState(!1),[Ge,it]=a.useState(null),[_e,Fe]=a.useState([]),[ae,be]=a.useState("idle"),[ne,Ie]=a.useState(!1),[Pe,ce]=a.useState(!1),[le,$e]=a.useState(!1),at=a.useRef(null),tt=a.useRef(null),V=a.useRef(null),de=a.useRef(null),Z=a.useRef(null),we=a.useRef(null),pe=a.useRef(null),Te=a.useRef(!1),Qe=a.useRef(he),Ee=a.useRef(n.trim()),Re=a.useRef(n.trim());a.useEffect(()=>{P&&(Ye(!0),os().then(Y=>{ye(Y.models),Me(Y.favoriteProviders),Be(Y.favoriteModels)}).catch(()=>{}).finally(()=>Ye(!1)),Eo(I).then(Y=>it(Y)).catch(()=>it(null)),Mo(I).then(Y=>Fe(Y.filter(F=>F.enabled))).catch(()=>Fe([])))},[P,I]);const Le=Ge?.modelPresets||[],ct=Le.find(Y=>Y.id===S),Se=($?!1:o.length>0)||N.length>0||M.length>0||b!=="default"||(c??ps)!==ps||d!==""||h!==""||(p||"")!==""||(x||"")!==""||j!==void 0||W==="fast";a.useEffect(()=>{if(e!=="create"||!P||!Ge?.autoSelectModelPreset)return;const Y=(Ge.defaultPresetBySize,void 0);if(Y){const F=Dm(Y);k(Y.id),y("preset"),m(F.executorValue),g(F.validatorValue)}},[P,Ge,Le,e]);const mt=a.useRef(!1);a.useEffect(()=>{if(e!=="create"||!P||mt.current||_e.length===0)return;const Y=_e.filter(H=>H.defaultOn);if(Y.length===0)return;mt.current=!0;const F=Y.map(H=>H.id);w(F),_?.(F)},[e,P,_e]),a.useEffect(()=>{P||(mt.current=!1)},[P]),a.useEffect(()=>{if(!A){Qe.current=Se;return}Se&&!Qe.current&&Ne(!0),Qe.current=Se},[Se,A]),a.useEffect(()=>{U||(fe(!1),ve(""))},[U]),a.useEffect(()=>{e!=="edit"||!P||de.current&&(de.current.focus(),de.current.select())},[e,P]),a.useEffect(()=>{if(!se)return;const Y=F=>{tt.current&&!tt.current.contains(F.target)&&fe(!1)};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[se]),a.useEffect(()=>{(e!=="edit"||z)&&$e(!1)},[e,z]),a.useEffect(()=>{if(e!=="edit"){be("idle");return}const Y=n.trim();Ee.current=Y,Re.current=Y,be("idle")},[e]),a.useEffect(()=>{if(e!=="edit"||!E||!P)return;const Y=n.trim(),F=Ee.current;if(Y===F||Y===Re.current){we.current&&(clearTimeout(we.current),we.current=null),Te.current||be("idle");return}return we.current&&clearTimeout(we.current),we.current=setTimeout(async()=>{if(!Te.current){Te.current=!0,be("saving");try{await E(Y),Re.current=Y,be("saved"),pe.current&&clearTimeout(pe.current),pe.current=setTimeout(()=>{be("idle"),pe.current=null},2e3)}catch{be("idle")}finally{Te.current=!1,we.current=null}}},1500),()=>{we.current&&(clearTimeout(we.current),we.current=null)}},[e,n,E,P]),a.useEffect(()=>()=>{we.current&&clearTimeout(we.current),pe.current&&clearTimeout(pe.current)},[]),a.useEffect(()=>{if(!ne)return;const Y=F=>{at.current&&!at.current.contains(F.target)&&Ie(!1)};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[ne]);const gt=a.useCallback(Y=>{const F=Y.clipboardData?.items;if(F)for(let H=0;H<F.length;H++){const ge=F[H];if(ge.type.startsWith("image/")){const me=ge.getAsFile();if(me&&Lm.includes(me.type)){Y.preventDefault(),L([...N,{file:me,previewUrl:URL.createObjectURL(me)}]);return}}}},[N,L]),wt=a.useCallback(Y=>{Y.preventDefault();const F=Y.dataTransfer.files;for(let H=0;H<F.length;H++){const ge=F[H];if(Lm.includes(ge.type)){L([...N,{file:ge,previewUrl:URL.createObjectURL(ge)}]);return}}},[N,L]),yt=a.useCallback(Y=>{const F=N[Y];F&&URL.revokeObjectURL(F.previewUrl),L(N.filter((H,ge)=>ge!==Y))},[N,L]),kt=a.useCallback(Y=>{l(o.includes(Y)?o.filter(F=>F!==Y):[...o,Y])},[o,l]),Ct=(Y,F)=>Y.length>F?Y.slice(0,F)+"…":Y,Rt=a.useCallback(Y=>{s(Y.target.value);const F=Y.target;F.style.height="auto",F.style.height=F.scrollHeight+"px"},[s]),Ft=a.useCallback(()=>{$e(Y=>!Y)},[]),Ut=a.useCallback(Y=>{!le||Y.key!=="Escape"||(Y.preventDefault(),Y.stopPropagation(),$e(!1))},[le]),St=a.useCallback(async Y=>{const F=n.trim();if(!(!F||Pe)){ce(!0);try{const H=await Jh(F,Y,I);s(H),Ie(!1),K("Description refined with AI","success"),V.current&&(V.current.style.height="auto",V.current.style.height=V.current.scrollHeight+"px")}catch(H){const ge=Yh(H);K(ge,"error")}finally{ce(!1)}}},[n,Pe,K,s,I]),Et=a.useCallback(async Y=>{const F=ie,ge=F.includes(Y)?F.filter(me=>me!==Y):[Y,...F];Me(ge);try{await an({favoriteProviders:ge,favoriteModels:ze})}catch{Me(F)}},[ie,ze]),It=a.useCallback(async Y=>{const F=ze,ge=F.includes(Y)?F.filter(me=>me!==Y):[Y,...F];Be(ge);try{await an({favoriteProviders:ie,favoriteModels:ge})}catch{Be(F)}},[ze,ie]),Mt=a.useCallback(Y=>{if(Y<=0)return;const F=[...M];[F[Y-1],F[Y]]=[F[Y],F[Y-1]],w(F)},[M,w]),Kt=a.useCallback(Y=>{if(Y>=M.length-1)return;const F=[...M];[F[Y],F[Y+1]]=[F[Y+1],F[Y]],w(F)},[M,w]),Ot=a.useCallback(Y=>{w(M.filter(F=>F!==Y))},[M,w]),xe=new Map;for(const Y of _e)xe.set(Y.id,{name:Y.name,description:Y.description});const st=T.filter(Y=>!o.includes(Y.id)).sort((Y,F)=>{const H=F.createdAt.localeCompare(Y.createdAt);if(H!==0)return H;const ge=parseInt(Y.id.slice(Y.id.lastIndexOf("-")+1),10)||0;return(parseInt(F.id.slice(F.id.lastIndexOf("-")+1),10)||0)-ge}),Ve=ee?st.filter(Y=>Y.id.toLowerCase().includes(ee.toLowerCase())||Y.title&&Y.title.toLowerCase().includes(ee.toLowerCase())||Y.description&&Y.description.toLowerCase().includes(ee.toLowerCase())):st;return t.jsxs("div",{className:"task-form",onDrop:wt,onDragOver:Y=>Y.preventDefault(),onPaste:gt,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:de,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:"Task title",value:i||"",onChange:Y=>r(Y.target.value),disabled:z})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:"task-form-description",className:"description-label-row",children:[t.jsx("span",{children:"Description"}),t.jsx("span",{className:`description-auto-save-status${ae==="idle"?"":" is-visible"}`,"aria-live":"polite",children:ae==="saving"?"Saving...":ae==="saved"?"Saved":""})]}),t.jsxs("div",{className:`description-with-refine${le?" description--fullscreen":""}`,ref:at,onKeyDown:Ut,children:[le&&t.jsxs("div",{className:"description-fullscreen-header",children:[t.jsx("span",{children:"Editing Description"}),t.jsx("button",{type:"button",className:"btn btn-sm description-expand-btn",onClick:Ft,"aria-label":"Collapse description",title:"Collapse description",children:t.jsx(mr,{size:14})})]}),t.jsx("textarea",{ref:V,autoFocus:e==="create",id:"task-form-description",value:n,onChange:Rt,placeholder:"What needs to be done?",rows:e==="edit"?8:5,disabled:z||Pe}),(()=>{const Y=!!n.trim()&&!z;return t.jsxs(t.Fragment,{children:[!le&&t.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${Y?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:Ft,"aria-label":"Expand description",title:"Expand description",children:t.jsx(So,{size:14})}),Y&&t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${Pe?"refine-button--loading":""}`,onClick:()=>Ie(F=>!F),disabled:Pe,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(Vn,{size:12,style:{verticalAlign:"middle"}}),Pe?"Refining...":"Refine"]})]})})(),ne&&t.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:Y=>Y.preventDefault(),children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>St("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:()=>St("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:()=>St("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:()=>St("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"&&(R||B)&&t.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[R&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const Y=n.trim();if(!Y){K("Enter a description first","error");return}G?.(),R(Y)},disabled:z||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),B&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const Y=n.trim();if(!Y){K("Enter a description first","error");return}G?.(),B(Y)},disabled:z||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),X,t.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>Ne(Y=>!Y),"aria-expanded":U,"aria-controls":"task-form-more-options",disabled:z,"data-testid":"task-form-more-options-toggle",children:[t.jsx("span",{children:"More options"}),U?t.jsx(ni,{size:14}):t.jsx(qt,{size:14})]}),t.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${U?"":" collapsed"}`,"aria-hidden":!U,hidden:!U,"data-testid":"task-form-more-options",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Attachments"}),N.length>0&&t.jsx("div",{className:"inline-create-previews",children:N.map((Y,F)=>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:()=>yt(F),disabled:z,title:"Remove image",children:"×"})]},Y.previewUrl))}),t.jsx("input",{ref:Z,type:"file",accept:"image/*",onChange:Y=>{const F=Y.target.files?.[0];F&&(L([...N,{file:F,previewUrl:URL.createObjectURL(F)}]),Y.target.value="")},style:{display:"none"}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>Z.current?.click(),disabled:z,children:"Attach Screenshot"}),t.jsx("small",{children:"You can also paste images or drag & drop"})]}),!$&&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:tt,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>fe(Y=>!Y),disabled:z,children:o.length>0?`${o.length} selected`:"Add dependencies"}),se&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:ee,onChange:Y=>ve(Y.target.value),onClick:Y=>Y.stopPropagation()}),Ve.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Ve.map(Y=>t.jsxs("div",{className:`dep-dropdown-item${o.includes(Y.id)?" selected":""}`,onClick:()=>kt(Y.id),onMouseDown:F=>F.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:Y.id}),t.jsx("span",{className:"dep-dropdown-title",children:Ct(Y.title||Y.description||Y.id,30)})]},Y.id))]})]}),o.length>0&&t.jsx("div",{className:"selected-deps",children:o.map(Y=>t.jsxs("span",{className:"dep-chip",children:[Y,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>kt(Y),disabled:z,children:"×"})]},Y))})]})}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Model Configuration"}),u&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"task-priority",className:"model-select-label",children:"Priority"}),t.jsx("select",{id:"task-priority","data-testid":"task-priority-select",value:c??ps,onChange:Y=>u(Y.target.value),disabled:z,children:Bc.map(Y=>t.jsx("option",{value:Y,children:Y[0].toUpperCase()+Y.slice(1)},Y))})]}),oe&&W!==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:W,onChange:Y=>oe(Y.target.value),disabled:z,children:[t.jsx("option",{value:"standard",children:"Standard"}),t.jsx("option",{value:"fast",children:"Fast"})]})]}),Je?t.jsx("div",{className:"model-selector-loading",children:"Loading models…"}):ue.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:b==="preset"?S:b,onChange:Y=>{const F=Y.target.value;if(F==="default"){y("default"),k(""),m(""),g("");return}if(F==="custom"){y("custom"),k("");return}const H=Le.find(me=>me.id===F),ge=Dm(H);y("preset"),k(F),m(ge.executorValue),g(ge.validatorValue)},disabled:z,children:[t.jsx("option",{value:"default",children:"Use default"}),Le.length>0?t.jsx("option",{disabled:!0,children:"──────────"}):null,Le.map(Y=>t.jsx("option",{value:Y.id,children:Y.name},Y.id)),t.jsx("option",{value:"custom",children:"Custom"})]})]}),b==="preset"&&ct?t.jsxs("small",{children:["Using preset: ",ct.name]}):null,b==="preset"?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>y("custom"),disabled:z,children:"Override"}):null,t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"executor-model",className:"model-select-label",children:"Executor"}),t.jsx(Ln,{id:"executor-model",label:"Executor Model",value:d,onChange:Y=>{y("custom"),k(""),m(Y)},models:ue,disabled:z||b==="preset",favoriteProviders:ie,onToggleFavorite:Et,favoriteModels:ze,onToggleModelFavorite:It})]}),t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"validator-model",className:"model-select-label",children:"Reviewer"}),t.jsx(Ln,{id:"validator-model",label:"Reviewer Model",value:h,onChange:Y=>{y("custom"),k(""),g(Y)},models:ue,disabled:z||b==="preset",favoriteProviders:ie,onToggleFavorite:Et,favoriteModels:ze,onToggleModelFavorite:It})]}),f&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"planning-model",className:"model-select-label",children:"Planning"}),t.jsx(Ln,{id:"planning-model",label:"Planning Model",value:p||"",onChange:Y=>{y("custom"),k(""),f(Y)},models:ue,disabled:z||b==="preset",favoriteProviders:ie,onToggleFavorite:Et,favoriteModels:ze,onToggleModelFavorite:It})]}),v&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"thinking-level",className:"model-select-label",children:"Thinking"}),t.jsxs("select",{id:"thinking-level",value:x||"",onChange:Y=>v(Y.target.value),disabled:z||b==="preset",children:[t.jsxs("option",{value:"",children:["Default (",Ge?.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"})]})]}),J&&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:j??"",onChange:Y=>J(Y.target.value===""?void 0:parseInt(Y.target.value,10)),disabled:z,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"})]})]})]})]}),C,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:_e.length>0&&_e.map(Y=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${Y.id}`,children:[t.jsx("input",{type:"checkbox",checked:M.includes(Y.id),onChange:F=>{w(F.target.checked?[...M,Y.id]:M.filter(H=>H!==Y.id))},disabled:z}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[Y.name,t_(Y.phase||"pre-merge",Y.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:Y.description})]})]},Y.id))})]}),M.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),M.map((Y,F)=>{const H=xe.get(Y);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${Y}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:F+1}),t.jsx("span",{className:"workflow-step-order-name",children:H?.name||Y}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Mt(F),disabled:z||F===0,"data-testid":`workflow-step-move-up-${Y}`,title:"Move up",children:t.jsx(ni,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Kt(F),disabled:z||F===M.length-1,"data-testid":`workflow-step-move-down-${Y}`,title:"Move down",children:t.jsx(qt,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Ot(Y),disabled:z,"data-testid":`workflow-step-remove-${Y}`,title:"Remove",children:t.jsx(zt,{size:14})})]})]},Y)})]})]})]})]})}const zm={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 n_(e){switch(e){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return e}}function s_(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 i_(e){return e?new Date(e).toLocaleString():null}function a_(e){const n=e.split(`
640
+ `);return n.length<=1?e:`${n.length} lines`}function Vr(e,n,s){const i=e==="post-merge"?"phase-badge--post-merge":"phase-badge--pre-merge";return t.jsx("span",{className:`phase-badge ${i}`,"data-testid":`${s}-${n}`,children:e==="post-merge"?"Post-merge":"Pre-merge"})}function r_({entries:e,startedAt:n,stepId:s}){const i=a.useRef(null),r=new Date(n).getTime(),o=e.filter(l=>new Date(l.timestamp).getTime()>=r);return a.useEffect(()=>{const l=i.current;l&&(l.scrollTop=l.scrollHeight)},[o.length]),e.length===0?t.jsx("div",{className:"workflow-live-log","data-testid":`workflow-live-log-${s}`,children:t.jsx("div",{className:"workflow-live-log-empty",children:"Waiting for agent output…"})}):t.jsx("div",{ref:i,className:"workflow-live-log","data-testid":`workflow-live-log-${s}`,children:o.map((l,c)=>l.type==="tool"?t.jsxs("div",{className:"workflow-live-log-tool",children:["⚡ ",l.text,l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",l.detail]})]},c):l.type==="tool_result"?t.jsxs("div",{className:"workflow-live-log-tool-result",children:["✓ ",l.text,l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",l.detail]})]},c):l.type==="tool_error"?t.jsxs("div",{className:"workflow-live-log-tool-error",children:["✗ ",l.text,l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",l.detail]})]},c):l.type==="thinking"?t.jsx("div",{className:"workflow-live-log-thinking",children:l.text},c):t.jsx("span",{className:"workflow-live-log-text",children:l.text},c))})}function o_({taskId:e,results:n,loading:s,enabledWorkflowSteps:i,canEdit:r,projectId:o,isTaskInProgress:l,onWorkflowStepsChange:c}){const[u,d]=a.useState({}),[m,h]=a.useState({}),[g,p]=a.useState(null),[f,x]=a.useState([]),[v,b]=a.useState(!1),y=n.some(j=>j.status==="pending"),{entries:S}=Af(e,!!l&&y,o);a.useEffect(()=>{let j=!1;return Mo(o).then(J=>{j||x(J.filter(W=>W.enabled))}).catch(()=>{j||x([])}),()=>{j=!0}},[o]);const k=i??[],M=a.useMemo(()=>f.map(j=>({id:j.id,name:j.name,description:j.description,phase:j.phase||"pre-merge"})),[f]),w=a.useMemo(()=>new Map(M.map(j=>[j.id,j])),[M]),_=j=>{d(J=>({...J,[j]:!J[j]}))},N=j=>{h(J=>{const W=J[j]??"markdown";return{...J,[j]:W==="markdown"?"plain":"markdown"}})},L=j=>{p(j)},T=()=>{p(null)};a.useEffect(()=>{if(!g)return;const j=J=>{J.key==="Escape"&&T()};return document.addEventListener("keydown",j),()=>{document.removeEventListener("keydown",j)}},[g]);const I=a.useCallback((j,J)=>{if(c){if(J){if(k.includes(j)){c(k);return}c([...k,j]);return}c(k.filter(W=>W!==j))}},[c,k]),z=a.useCallback(j=>{if(!c||j<=0)return;const J=[...k];[J[j-1],J[j]]=[J[j],J[j-1]],c(J)},[c,k]),K=a.useCallback(j=>{if(!c||j>=k.length-1)return;const J=[...k];[J[j],J[j+1]]=[J[j+1],J[j]],c(J)},[c,k]),P=a.useCallback(j=>{c&&c(k.filter(J=>J!==j))},[c,k]),E=n.length>0,R=k.length>0;a.useEffect(()=>{r||b(!1)},[r]);const B=a.useMemo(()=>k.map(j=>{const J=w.get(j);return{id:j,name:J?.name||j,description:J?.description||"Step definition not found.",phase:J?.phase||"pre-merge"}}),[k,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:M.map(j=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${j.id}`,children:[t.jsx("input",{type:"checkbox",checked:k.includes(j.id),onChange:J=>I(j.id,J.target.checked)}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[j.name,Vr(j.phase,j.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:j.description})]})]},j.id))})]}),k.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),k.map((j,J)=>{const W=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:J+1}),t.jsx("span",{className:"workflow-step-order-name",children:W?.name||j}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>z(J),disabled:J===0,"data-testid":`workflow-step-move-up-${j}`,title:"Move up",children:t.jsx(ni,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>K(J),disabled:J===k.length-1,"data-testid":`workflow-step-move-down-${j}`,title:"Move down",children:t.jsx(qt,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>P(j),"data-testid":`workflow-step-remove-${j}`,title:"Remove",children:t.jsx(zt,{size:14})})]})]},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(!E)return t.jsxs("div",{className:"workflow-results-empty","data-testid":"workflow-results-empty",children:[t.jsx("p",{children:"No workflow steps configured for this task."}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."})]});const j=n.filter(se=>se.status==="passed").length,J=n.filter(se=>se.status==="failed").length,W=n.filter(se=>se.status==="skipped").length,oe=n.filter(se=>se.status==="pending").length,he=[`${n.length} step${n.length!==1?"s":""}`];return j>0&&he.push(`${j} passed`),J>0&&he.push(`${J} failed`),W>0&&he.push(`${W} skipped`),oe>0&&he.push(`${oe} 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:he.join(" · ")}),n.map((se,fe)=>{const U=se.phase||"pre-merge",Ne=u[se.workflowStepId]??!1;return t.jsxs("div",{className:`workflow-result-item workflow-result-item--${se.status}`,"data-testid":`workflow-result-item-${se.workflowStepId}`,children:[t.jsxs("div",{className:"workflow-result-header",children:[t.jsxs("div",{className:"workflow-result-name",children:[se.workflowStepName,Vr(U,se.workflowStepId,"workflow-result-phase")]}),t.jsx("span",{className:`workflow-result-badge workflow-result-badge--${se.status}`,"data-testid":`workflow-result-badge-${se.workflowStepId}`,children:n_(se.status)})]}),t.jsxs("div",{className:"workflow-result-meta",children:[se.startedAt&&t.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",i_(se.startedAt)]}),se.completedAt&&t.jsx("span",{className:"workflow-result-duration",children:s_(se.startedAt,se.completedAt)})]}),se.status==="pending"&&se.startedAt?t.jsx(r_,{entries:S,startedAt:se.startedAt,stepId:se.workflowStepId}):se.output?t.jsxs("div",{className:"workflow-result-output-section",children:[t.jsxs("div",{className:"workflow-result-output-header",children:[t.jsx("span",{className:"workflow-result-output-label",children:"Output:"}),t.jsx("button",{className:"workflow-result-toggle",onClick:()=>_(se.workflowStepId),"data-testid":`workflow-result-toggle-${se.workflowStepId}`,children:Ne?"Hide output":"Show output"}),!Ne&&t.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${se.workflowStepId}`,children:a_(se.output)}),Ne&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>N(se.workflowStepId),"data-testid":`workflow-result-mode-toggle-${se.workflowStepId}`,title:(m[se.workflowStepId]??"markdown")==="markdown"?"Switch to plain text":"Switch to markdown",children:(m[se.workflowStepId]??"markdown")==="markdown"?"Markdown":"Plain"}),t.jsx("button",{className:"workflow-result-expand-toggle",onClick:()=>L(se.workflowStepId),"data-testid":`workflow-result-expand-${se.workflowStepId}`,title:"Expand output",children:t.jsx(So,{size:12})})]})]}),Ne&&t.jsx("div",{className:`workflow-result-output${(m[se.workflowStepId]??"markdown")==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":`workflow-result-output-${se.workflowStepId}`,children:(m[se.workflowStepId]??"markdown")==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(si,{remarkPlugins:[ii],components:zm,children:se.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:se.output})})]}):null]},`${se.workflowStepId}-${fe}`)})]})},C=r?t.jsx("button",{type:"button",className:"modal-edit-btn workflow-results-edit-toggle",onClick:()=>b(j=>!j),"data-testid":"workflow-steps-edit-toggle","aria-label":v?"Done editing workflow steps":"Edit workflow steps",title:v?"Done":"Edit",children:v?t.jsxs(t.Fragment,{children:[t.jsx(Rn,{size:14}),"Done"]}):t.jsxs(t.Fragment,{children:[t.jsx(Qn,{size:14}),"Edit"]})}):null,$=!s&&!E&&R,A=r&&E;return t.jsxs("div",{className:"workflow-results-tab","data-task-id":e,children:[$?t.jsxs("div",{className:"workflow-configured-steps","data-testid":"workflow-configured-steps",children:[t.jsxs("div",{className:"workflow-configured-header","data-testid":"workflow-configured-header",children:[t.jsxs("div",{className:"workflow-configured-title-row",children:[t.jsx("h4",{children:"Configured Workflow Steps"}),t.jsxs("span",{className:"workflow-configured-count","data-testid":"workflow-configured-count",children:[B.length," step",B.length===1?"":"s"]})]}),C]}),t.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:B.map(j=>t.jsxs("div",{className:"workflow-configured-item","data-testid":`workflow-configured-step-${j.id}`,children:[t.jsxs("div",{className:"workflow-configured-name",children:[j.name,Vr(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:[A&&t.jsxs("div",{className:"workflow-results-edit-header","data-testid":"workflow-results-edit-header",children:[t.jsx("h4",{children:"Workflow Steps"}),C]}),X(),G()]}),g&&(()=>{const j=n.find(oe=>oe.workflowStepId===g);if(!j)return null;const J=m[j.workflowStepId]??"markdown",W=j.phase||"pre-merge";return t.jsx("div",{className:"workflow-output-modal-overlay",onClick:oe=>{oe.target===oe.currentTarget&&T()},"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}),Vr(W,j.workflowStepId,"workflow-output-modal-phase")]}),t.jsxs("div",{className:"workflow-output-modal-controls",children:[t.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>N(j.workflowStepId),"data-testid":"workflow-output-modal-mode-toggle",title:J==="markdown"?"Switch to plain text":"Switch to markdown",children:J==="markdown"?"Markdown":"Plain"}),t.jsx("button",{className:"workflow-output-modal-close",onClick:T,"data-testid":"workflow-output-modal-close","aria-label":"Close",children:t.jsx(zt,{size:16})})]})]}),t.jsx("div",{className:"workflow-output-modal-body",children:t.jsx("div",{className:`workflow-result-output workflow-result-output--expanded${J==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":"workflow-output-modal-content",children:J==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(si,{remarkPlugins:[ii],components:zm,children:j.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:j.output})})})]})})})()]})}const l_=/^[a-zA-Z0-9_-]{1,64}$/,c_=200;function Fm(e){return e?new Date(e).toLocaleString():""}function d_(e,n=c_){return e.length<=n?e:e.substring(0,n)+"…"}function u_({taskId:e,addToast:n,onTaskUpdated:s,projectId:i,canEdit:r=!1}){const[o,l]=a.useState([]),[c,u]=a.useState(!0),[d,m]=a.useState(null),[h,g]=a.useState(""),[p,f]=a.useState(null),[x,v]=a.useState(""),[b,y]=a.useState(null),[S,k]=a.useState([]),[M,w]=a.useState(!1),[_,N]=a.useState(!1),[L,T]=a.useState(""),[I,z]=a.useState(""),[K,P]=a.useState(!1),[E,R]=a.useState(null),[B,G]=a.useState(null),[X,C]=a.useState(!1),$=a.useCallback(async()=>{try{const U=await Ev(e,i);l(U)}catch(U){n(je(U)||"Failed to load documents","error")}finally{u(!1)}},[e,i,n]);a.useEffect(()=>{$()},[$]);async function A(U){d===U.key?(m(null),g(""),f(null),v(""),y(null),k([]),C(!1)):(m(U.key),g(U.content),f(null),v(""),y(null),k([]),C(!1))}async function j(U){if(b===U)y(null),k([]);else{y(U),w(!0);try{const Ne=await Mv(e,U,i);k(Ne)}catch(Ne){n(je(Ne)||"Failed to load revisions","error")}finally{w(!1)}}}function J(){d&&(f(d),v(h))}function W(){f(null),v("")}async function oe(){if(!(!p||!x.trim())){P(!0);try{await Ad(e,p,x,{},i),f(null),v(""),await $();const U=o.find(Ne=>Ne.key===p);U&&g(U.content),n("Document saved","success")}catch(U){n(je(U)||"Failed to save document","error")}finally{P(!1)}}}async function he(){const U=L.trim(),Ne=I.trim();if(!U){n("Document key is required","error");return}if(!l_.test(U)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!Ne){n("Content is required","error");return}P(!0);try{await Ad(e,U,Ne,{},i),N(!1),T(""),z(""),await $(),n("Document created","success")}catch(ee){n(je(ee)||"Failed to create document","error")}finally{P(!1)}}async function se(U){R(U);try{await _v(e,U,i),G(null),R(null),d===U&&(m(null),g("")),b===U&&(y(null),k([])),await $(),n("Document deleted","success")}catch(Ne){n(je(Ne)||"Failed to delete document","error")}finally{R(null)}}function fe(U){g(U.content),f(null),v("")}return c?t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),t.jsx("div",{className:"detail-log-empty",children:"Loading documents…"})]}):t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),_&&t.jsxs("div",{className:"task-document-create-form",children:[t.jsx("h5",{children:"New Document"}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-key",children:"Key"}),t.jsx("input",{id:"doc-key",type:"text",className:"task-document-key-input",value:L,onChange:U=>T(U.target.value),placeholder:"e.g., plan, notes, research",disabled:K}),t.jsx("span",{className:"form-hint",children:"Alphanumeric, hyphens, underscores (1-64 chars)"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-content",children:"Content"}),t.jsx("textarea",{id:"doc-content",value:I,onChange:U=>z(U.target.value),rows:6,placeholder:"Enter document content…",disabled:K})]}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{N(!1),T(""),z("")},disabled:K,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void he(),disabled:K||!L.trim()||!I.trim(),children:K?"Creating…":"Create"})]})]}),o.length===0&&!_?t.jsx("div",{className:"detail-log-empty",children:"No documents yet."}):t.jsx("div",{className:"task-documents-list",children:o.map(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(Ri,{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:Fm(U.updatedAt||U.createdAt)})]})]}),d===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:()=>C(Ne=>!Ne),"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(si,{remarkPlugins:[ii],children:h})})}):t.jsx("pre",{className:"task-document-content-text",children:h})}),b===U.key&&t.jsxs("div",{className:"task-document-revisions",children:[t.jsx("h5",{children:"Revision History"}),M?t.jsx("div",{className:"detail-log-empty",children:"Loading…"}):S.length<=1?t.jsx("div",{className:"detail-log-empty",children:"No previous revisions."}):t.jsx("div",{className:"task-document-revision-list",children:S.filter(Ne=>Ne.revision<U.revision).sort((Ne,ee)=>ee.revision-Ne.revision).map(Ne=>t.jsxs("div",{className:"task-document-revision-item",onClick:()=>fe(Ne),children:[t.jsxs("div",{className:"revision-header",children:[t.jsxs("span",{className:"revision-badge",children:["v",Ne.revision]}),t.jsx("span",{className:"revision-author",children:Ne.author}),t.jsx("span",{className:"revision-timestamp",children:Fm(Ne.createdAt)})]}),t.jsx("div",{className:"revision-preview",children:d_(Ne.content,100)})]},Ne.id))})]})]}),p===U.key&&t.jsxs("div",{className:"task-document-edit-form",children:[t.jsx("textarea",{value:x,onChange:Ne=>v(Ne.target.value),rows:10,disabled:K}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:W,disabled:K,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void oe(),disabled:K||!x.trim(),children:K?"Saving…":"Save"})]})]}),t.jsxs("div",{className:"task-document-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>void A(U),children:d===U.key?t.jsxs(t.Fragment,{children:[t.jsx(ni,{size:14})," Collapse"]}):t.jsxs(t.Fragment,{children:[t.jsx(qt,{size:14})," Expand"]})}),d===U.key&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>void j(U.key),children:[t.jsx(tr,{size:14})," History"]}),r&&p!==U.key&&t.jsx("button",{className:"btn btn-sm",onClick:J,children:"Edit"}),r&&(B===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 se(U.key),disabled:E===U.key,children:E===U.key?"…":"Yes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>G(null),disabled:E===U.key,children:"No"})]}):t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>G(U.key),children:t.jsx(Jt,{size:14})}))]})]})]},U.key))}),r&&!_&&t.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>N(!0),children:[t.jsx(Xt,{size:14})," New Document"]})]})}function Wr(e){return e.toLocaleString()}function Il(e){const n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString()}function Ia(e){if(e<1e3)return`${Math.round(e)} ms`;const n=e/1e3;if(n<60)return`${n.toFixed(1)} s`;const s=Math.floor(n/60),i=Math.round(n%60);return`${s}m ${i}s`}function m_(e){const n=Date.now(),s=e.map(o=>{if(!o.startedAt)return null;const l=new Date(o.startedAt).getTime();if(Number.isNaN(l))return null;let c;if(o.completedAt){const u=new Date(o.completedAt).getTime();if(Number.isNaN(u)||u<l)return null;c=u}else c=Math.max(l,n);return{name:o.workflowStepName||o.workflowStepId,durationMs:c-l}}).filter(o=>o!==null),i=s.reduce((o,l)=>o+l.durationMs,0),r=s.reduce((o,l)=>!o||l.durationMs>o.durationMs?l:o,void 0);return{timedStepCount:s.length,totalDurationMs:i,longestStep:r}}function h_({tokenUsage:e,loading:n,task:s}){const i=mp(s?.log??[]),r=i.filter(d=>typeof d.durationMs=="number"),o=r.reduce((d,m)=>d+(m.durationMs??0),0),l=r.reduce((d,m)=>!d||(m.durationMs??0)>(d.durationMs??0)?m:d,void 0),c=m_(s?.workflowStepResults??[]),u=s?.steps?.length??0;return t.jsxs("section",{className:"task-token-stats-panel","aria-label":"Task execution statistics",children:[t.jsx("h4",{children:"Execution & Token Stats"}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Execution Timing"}),t.jsxs("div",{className:"task-token-stats-panel__grid",role:"list","aria-label":"Execution timing metrics",children:[t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Timing events"}),t.jsx("span",{className:"task-token-stats-panel__value",children:i.length.toLocaleString()})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Timed duration"}),t.jsx("span",{className:"task-token-stats-panel__value",children:Ia(o)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Workflow timed steps"}),t.jsx("span",{className:"task-token-stats-panel__value",children:c.timedStepCount.toLocaleString()})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Workflow runtime"}),t.jsx("span",{className:"task-token-stats-panel__value",children:Ia(c.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:Ia(o+c.totalDurationMs)})]})]}),t.jsxs("dl",{className:"task-token-stats-panel__timestamps",children:[t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Longest timing event"}),t.jsx("dd",{children:l?.durationMs?`${l.summary} (${Ia(l.durationMs)})`:"No timed events recorded yet."})]}),t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Longest workflow step"}),t.jsx("dd",{children:c.longestStep?`${c.longestStep.name} (${Ia(c.longestStep.durationMs)})`:"No completed workflow step timings yet."})]})]})]}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Execution Details"}),t.jsxs("dl",{className:"task-token-stats-panel__details",children:[t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Execution mode"}),t.jsx("dd",{children:s?.executionMode==="fast"?"Fast":"Standard"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Runtime status"}),t.jsx("dd",{children:s?.status??"Not set"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Paused"}),t.jsx("dd",{children:s?.paused?"Yes":"No"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Step progress"}),t.jsx("dd",{children:u>0?`${Math.min((s?.currentStep??0)+1,u)} / ${u}`:"No steps"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Retries (recovery / workflow / merge / task_done)"}),t.jsx("dd",{children:`${s?.recoveryRetryCount??0} / ${s?.workflowStepRetries??0} / ${s?.mergeRetries??0} / ${s?.taskDoneRetryCount??0}`})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Recovery state"}),t.jsx("dd",{children:s?.nextRecoveryAt?`Next recovery at ${Il(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:Wr(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:Wr(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:Wr(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:Wr(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:Il(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:Il(e.lastUsedAt)})})]})]})]}):t.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:"No token usage recorded for this task yet."})]})]})}function p_(e,n){return e.modelProvider&&e.modelId?{provider:e.modelProvider,modelId:e.modelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function f_(e,n){return e.validatorModelProvider&&e.validatorModelId?{provider:e.validatorModelProvider,modelId:e.validatorModelId}:n?.validatorProvider&&n.validatorModelId?{provider:n.validatorProvider,modelId:n.validatorModelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function g_(e){let n=null;for(const s of e){if(s.agent!=="triage"||s.type!=="text")continue;const i=s.text.match(/^Triage using model: (.+?)\/(.+)$/);i&&(n={provider:i[1],modelId:i[2]})}return n}function x_(e,n,s){if(e.planningModelProvider&&e.planningModelId)return{provider:e.planningModelProvider,modelId:e.planningModelId};const i=g_(n);return i||(s?.planningProvider&&s.planningModelId?{provider:s.planningProvider,modelId:s.planningModelId}:s?.defaultProvider&&s.defaultModelId?{provider:s.defaultProvider,modelId:s.defaultModelId}:{})}function b_(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 v_(e){const n=new Date(e),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),o=Math.floor(r/60),l=Math.floor(o/24);return r<1?"just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString()}function y_(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function k_(e){if(!(e instanceof Error))return null;const n=e.details;if(n?.code==="TASK_HAS_DEPENDENTS"&&Array.isArray(n.dependentIds))return{dependentIds:n.dependentIds.filter(i=>typeof i=="string")};const s=e.message.match(/[A-Z]+-\d+/g)??[];return s.length>1?{dependentIds:[...new Set(s.slice(1))]}:null}function Om(e,n){return e.length>n?e.slice(0,n)+"…":e}function Um(e=[],n=[]){return e.length===n.length&&e.every((s,i)=>s===n[i])}function $l(e){const n=e.indexOf("/");return!e||n===-1?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function Dl(e){return e.trim()}function j_(e){const n=e.trim();return n.length>0?n:void 0}function $a(e){return typeof e=="string"&&Bc.includes(e)?e:ps}function Da(e){return e==="fast"?"fast":"standard"}const Ll=200,w_=new Set(["triage","todo"]);function N_({task:e,projectId:n,tasks:s=[],onClose:i,onOpenDetail:r,onMoveTask:o,onDeleteTask:l,onMergeTask:c,onRetryTask:u,onDuplicateTask:d,onTaskUpdated:m,addToast:h,prAuthAvailable:g,initialTab:p="definition"}){const[f,x]=a.useState(p),[v,b]=a.useState(()=>"prompt"in e?e:null),[y,S]=a.useState(()=>!("prompt"in e));a.useEffect(()=>{if("prompt"in e){b(e),S(!1);return}let te=!1;return S(!0),b(null),ao(e.id,n).then(Ke=>{te||(b(Ke),S(!1))}).catch(()=>{te||S(!1)}),()=>{te=!0}},[e.id,n]);const k=v?{...v,...e,prompt:v.prompt,log:v.log}:{...e,prompt:""},M=e.status==="failed"||e.status==="stuck-killed"||e.status==="planning"||e.status==="needs-replan"||(e.stuckKillCount??0)>0||(e.recoveryRetryCount??0)>0||!!e.nextRecoveryAt;a.useEffect(()=>{x(p)},[p]),a.useEffect(()=>{L(!1)},[e.id]);const[w,_]=a.useState("activity"),[N,L]=a.useState(!1),[T,I]=a.useState(e.attachments||[]),[z,K]=a.useState(!1),[P,E]=a.useState(e.dependencies||[]),[R,B]=a.useState(!1),[G,X]=a.useState(""),[C,$]=a.useState(null),[A,j]=a.useState([]),[J,W]=a.useState(!1),[oe,he]=a.useState(!1),[se,fe]=a.useState(!1),[U,Ne]=a.useState(!1),[ee,ve]=a.useState(!1),[ue,ye]=a.useState(k.prompt||""),[ie,Me]=a.useState(""),[ze,Be]=a.useState(!1),[Je,Ye]=a.useState(""),[Ge,it]=a.useState(!1),[_e,Fe]=a.useState(!1),[ae,be]=a.useState(e.title||""),[ne,Ie]=a.useState(e.description||""),[Pe,ce]=a.useState(e.dependencies||[]),[le,$e]=a.useState(""),[at,tt]=a.useState(""),[V,de]=a.useState(""),[Z,we]=a.useState(""),[pe,Te]=a.useState("default"),[Qe,Ee]=a.useState(void 0),[Re,Le]=a.useState(ps),[ct,Se]=a.useState(Da(e.executionMode)),[mt,gt]=a.useState(""),[wt,yt]=a.useState(e.enabledWorkflowSteps||[]),[kt,Ct]=a.useState(e.sourceIssue?.provider??""),[Rt,Ft]=a.useState(e.sourceIssue?.repository??""),[Ut,St]=a.useState(e.sourceIssue?.externalIssueId??""),[Et,It]=a.useState(e.sourceIssue?.url??""),[Mt,Kt]=a.useState([]),[Ot,xe]=a.useState(!1),st=a.useRef(!1),[Ve,Y]=a.useState(!1),[F,H]=a.useState(!1),ge=a.useRef(null),me=a.useRef(null),We=a.useRef(null);Gs(We,!0,"fusion:task-detail-modal-size");const{getSlotsForId:dt}=ap(n),_t=dt("task-detail-tab");a.useEffect(()=>(st.current=!0,()=>{st.current=!1}),[]);const[$t,vn]=a.useState(void 0),[kn,Yt]=a.useState([]),[En,on]=a.useState(!1),[Mn,Vt]=a.useState(e.enabledWorkflowSteps||[]);a.useEffect(()=>{be(e.title||""),Ie(e.description||""),Ct(e.sourceIssue?.provider??""),Ft(e.sourceIssue?.repository??""),St(e.sourceIssue?.externalIssueId??""),It(e.sourceIssue?.url??""),Se(Da(e.executionMode)),Fe(!1)},[e.id,e.title,e.description,e.sourceIssue,e.executionMode]),a.useEffect(()=>{Vt(e.enabledWorkflowSteps||[])},[e.id,e.enabledWorkflowSteps]),a.useEffect(()=>{let te=!1;return Eo(n).then(Ke=>{te||vn(Ke)}).catch(()=>{}),()=>{te=!0}},[n]),a.useEffect(()=>{if(f!=="workflow")return;let te=!1;return on(!0),Qy(e.id,n).then(Ke=>{te||Yt(Ke)}).catch(Ke=>{te||h(`Failed to load workflow results: ${je(Ke)}`,"error")}).finally(()=>{te||on(!1)}),()=>{te=!0}},[f,e.id,n,h]),a.useEffect(()=>{if(f!=="workflow")return;const te=n?`?projectId=${encodeURIComponent(n)}`:"",Ke=ut=>{try{const Dt=JSON.parse(ut.data);Dt.id===e.id&&Array.isArray(Dt.workflowStepResults)&&Yt(Dt.workflowStepResults)}catch{}};return $s(`/api/events${te}`,{events:{"task:updated":Ke}})},[f,e.id,n]),a.useEffect(()=>{R||X("")},[R]),a.useEffect(()=>{if(!e.assignedAgentId){$(null);return}const te=A.find(ut=>ut.id===e.assignedAgentId);if(te){$(te);return}let Ke=!1;return Xh(e.assignedAgentId,n).then(ut=>{Ke||$(ut)}).catch(()=>{Ke||$(null)}),()=>{Ke=!0}},[e.assignedAgentId,n,A]),a.useEffect(()=>{W(!1)},[e.id]),a.useEffect(()=>{if(!(Ve||F))return;const Ke=ut=>{const Dt=ut.target,Un=ge.current?.contains(Dt),Bn=me.current?.contains(Dt);!Un&&Ve&&Y(!1),!Bn&&F&&H(!1)};return document.addEventListener("mousedown",Ke),()=>document.removeEventListener("mousedown",Ke)},[Ve,F]),a.useEffect(()=>{if(!(Ve||F))return;const Ke=ut=>{ut.key==="Escape"&&(ut.stopPropagation(),Ve&&Y(!1),F&&H(!1))};return document.addEventListener("keydown",Ke),()=>document.removeEventListener("keydown",Ke)},[Ve,F]),a.useEffect(()=>{ve(!1),ye(k.prompt||""),Me("")},[e.id,k.prompt]);const hn=w_.has(e.column)&&!Ot,ke=a.useCallback(()=>{if(!hn)return;Fe(!0),be(e.title||""),Ie(e.description||""),ce(e.dependencies||[]);const te=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"",Ke=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"",ut=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";$e(te),tt(Ke),de(ut),we(e.thinkingLevel??""),Te(te||Ke||ut?"custom":"default"),gt(""),yt(e.enabledWorkflowSteps||[]),Se(Da(e.executionMode)),Ct(e.sourceIssue?.provider??""),Ft(e.sourceIssue?.repository??""),St(e.sourceIssue?.externalIssueId??""),It(e.sourceIssue?.url??""),Kt([]),Ee(e.reviewLevel),Le($a(e.priority))},[hn,e]),nt=a.useCallback(()=>{Fe(!1),be(e.title||""),Ie(e.description||""),ce(e.dependencies||[]),Ct(e.sourceIssue?.provider??""),Ft(e.sourceIssue?.repository??""),St(e.sourceIssue?.externalIssueId??""),It(e.sourceIssue?.url??""),Le($a(e.priority)),Se(Da(e.executionMode)),Mt.forEach(te=>URL.revokeObjectURL(te.previewUrl)),Kt([])},[e.title,e.description,e.dependencies,e.priority,e.executionMode,Mt]),tn=a.useCallback(async()=>{xe(!0);try{const te={},Ke=ae.trim(),ut=ne.trim();Ke&&Ke!==(e.title??"")&&(te.title=Ke),ut&&ut!==(e.description??"")&&(te.description=ut),Um(Pe,e.dependencies??[])||(te.dependencies=Pe),Um(wt,e.enabledWorkflowSteps??[])||(te.enabledWorkflowSteps=wt);const Dt=$l(le),Un=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"";le!==Un&&(te.modelProvider=Dt?.provider??null,te.modelId=Dt?.modelId??null);const Bn=$l(at),Ui=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"";at!==Ui&&(te.validatorModelProvider=Bn?.provider??null,te.validatorModelId=Bn?.modelId??null);const wa=$l(V),Oo=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";V!==Oo&&(te.planningModelProvider=wa?.provider??null,te.planningModelId=wa?.modelId??null);const Uo=e.thinkingLevel??"";Z!==Uo&&(te.thinkingLevel=Z!==""?Z:null);const Cr=e.reviewLevel;Qe!==Cr&&(te.reviewLevel=Qe);const Er=$a(e.priority);Re!==Er&&(te.priority=Re);const Mr=Da(e.executionMode);ct!==Mr&&(te.executionMode=ct==="fast"?"fast":null);const Na=Dl(kt),Bi=Dl(Rt),Hi=Dl(Ut),vi=j_(Et);if(Na.length===0&&Bi.length===0&&Hi.length===0&&!vi)e.sourceIssue&&(te.sourceIssue=null);else{if(!Na||!Bi||!Hi){h("Source issue provider, repository, and issue identifier are required","error"),xe(!1);return}const ys=Number.parseInt(Hi,10),As=e.sourceIssue?.issueNumber??ys;if(!Number.isFinite(As)||As<=0){h("Source issue identifier must be numeric for new metadata","error"),xe(!1);return}const Ls={provider:Na,repository:Bi,externalIssueId:Hi,issueNumber:As,...vi?{url:vi}:{}},zs=e.sourceIssue;(!zs||zs.provider!==Ls.provider||zs.repository!==Ls.repository||zs.externalIssueId!==Ls.externalIssueId||zs.issueNumber!==Ls.issueNumber||(zs.url??void 0)!==Ls.url)&&(te.sourceIssue=Ls)}if(Object.keys(te).length>0){const ys=await Zs(e.id,te,n);m?.(ys)}if(Mt.length>0){const ys=[];for(const As of Mt)try{const Ls=await sr(e.id,As.file,n);I(zs=>[...zs,Ls])}catch{ys.push(As.file.name)}ys.length>0&&h(`Failed to upload: ${ys.join(", ")}`,"error")}Mt.forEach(ys=>URL.revokeObjectURL(ys.previewUrl)),Kt([]),h(`Updated ${e.id}`,"success"),Fe(!1)}catch(te){h(`Failed to update ${e.id}: ${je(te)}`,"error")}finally{st.current&&xe(!1)}},[e,ae,ne,Pe,le,at,V,Z,Qe,Re,ct,wt,kt,Rt,Ut,Et,Mt,h,n,m]),Pn=a.useCallback(async te=>{try{await Zs(e.id,{description:te},n),h("Description saved","success")}catch(Ke){h(`Failed to save: ${je(Ke)}`,"error")}},[e.id,h,n]),Nn=a.useCallback(te=>{_e&&(te.key==="Escape"?(te.preventDefault(),nt()):te.key==="Enter"&&(te.ctrlKey||te.metaKey)&&(te.preventDefault(),tn()))},[_e,nt,tn]);a.useEffect(()=>{if(_e)return document.addEventListener("keydown",Nn),()=>document.removeEventListener("keydown",Nn)},[_e,Nn]);const gn=a.useRef(null),{confirm:nn}=Is(),{entries:_n,loading:jn,loadMore:Q,hasMore:Oe,total:Xe,loadingMore:Ze}=Af(e.id,f==="logs"&&w==="agent-log",n);a.useEffect(()=>{const te=Ke=>{Ke.key==="Escape"&&!_e&&i()};return document.addEventListener("keydown",te),()=>document.removeEventListener("keydown",te)},[i,_e]);const pt=fi(i),Nt=a.useCallback(async te=>{try{await o(e.id,te),i(),h(`Moved to ${$n[te]}`,"success")}catch(Ke){h(je(Ke),"error")}},[e.id,o,i,h]),At=a.useCallback(async()=>{if(await nn({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0}))try{await l(e.id),i(),h(`Deleted ${e.id}`,"info")}catch(Ke){const ut=k_(Ke);if(!ut||ut.dependentIds.length===0){h(je(Ke),"error");return}const Dt=ut.dependentIds.join(", ");if(!await nn({title:"Force Delete Task",message:`${e.id} is a dependency of ${Dt}.
641
+
642
+ Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await l(e.id,{removeDependencyReferences:!0}),i(),h(`Deleted ${e.id} after removing dependency references`,"info")}catch(Bn){h(je(Bn),"error")}}},[e.id,l,i,h,nn]),xn=a.useCallback(async()=>{await nn({title:"Merge Task",message:`Merge ${e.id} into the current branch?`})&&(i(),h(`Merging ${e.id}...`,"info"),c(e.id).then(Ke=>{const ut=Ke.merged?`Merged ${e.id} (branch: ${Ke.branch})`:`Closed ${e.id} (${Ke.error||"no branch to merge"})`;h(ut,"success")}).catch(Ke=>{h(je(Ke),"error")}))},[e.id,c,i,h,nn]),Qt=a.useCallback(()=>{u&&(i(),u(e.id).then(()=>{h(`Retried ${e.id}`,"success")}).catch(te=>{h(je(te),"error")}))},[e.id,u,i,h]),bt=a.useCallback(async()=>{if(!(!d||!await nn({title:"Duplicate Task",message:`Duplicate ${e.id}? This will create a new task in Triage with the same description and prompt.`})))try{const Ke=await d(e.id);i(),h(`Duplicated ${e.id} → ${Ke.id}`,"success")}catch(Ke){h(je(Ke),"error")}},[e.id,d,i,h,nn]),Kn=a.useCallback(async()=>{try{e.paused?(await gv(e.id,n),h(`Unpaused ${e.id}`,"success")):(await Vh(e.id,n),h(`Paused ${e.id}`,"success")),i()}catch(te){h(je(te),"error")}},[e.id,e.paused,i,h]),re=a.useCallback(async()=>{try{await yv(e.id,n),h(`Plan approved — ${e.id} moved to Todo`,"success"),i()}catch(te){h(je(te),"error")}},[e.id,i,h]),Ae=a.useCallback(async()=>{if(await nn({title:"Reject Plan",message:"Reject this plan? The specification will be discarded and regenerated.",danger:!0}))try{await kv(e.id,n),h(`Plan rejected — ${e.id} returned to Planning for replanning`,"info"),i()}catch(Ke){h(je(Ke),"error")}},[e.id,i,h,nn]),lt=a.useCallback(async()=>{if(await nn({title:"Rebuild Plan",message:"Rebuild the plan for this task? The task will move to planning for replanning."}))try{await Tv(e.id,n),i(),h(`Replanning ${e.id}...`,"info")}catch(Ke){h(je(Ke),"error")}},[e.id,n,i,h,nn]),vt=a.useCallback(()=>{Be(!0),Ye("")},[]),xt=a.useCallback(()=>{Y(!1),H(!1)},[]),Zt=a.useCallback(te=>{xt(),Nt(te)},[xt]),ot=a.useCallback(te=>{xt(),te()},[xt]),Ht=a.useCallback(()=>{xt(),xn()},[xt,xn]),en=a.useCallback(()=>{Be(!1),Ye(""),it(!1)},[]),An=a.useCallback(async()=>{if(!Je.trim()){h("Please enter feedback describing what needs refinement","error");return}if(Je.length>2e3){h("Feedback must be 2000 characters or less","error");return}it(!0);try{const te=await Pv(e.id,Je.trim(),n);h(`Refinement task created: ${te.id}`,"success"),i()}catch(te){h(je(te),"error")}finally{it(!1)}},[e.id,Je,h,i]),yn=a.useCallback(async te=>{K(!0);try{const Ke=await sr(e.id,te,n);I(ut=>[...ut,Ke]),h("Screenshot attached","success")}catch(Ke){h(je(Ke),"error")}finally{K(!1)}},[e.id,h]),xs=a.useCallback(async te=>{const Ke=te.target.files?.[0];Ke&&(await yn(Ke),gn.current&&(gn.current.value=""))},[yn]);a.useEffect(()=>{const te=Ke=>{const ut=Ke.clipboardData?.items;if(ut)for(let Dt=0;Dt<ut.length;Dt++){const Un=ut[Dt];if(Un.type.startsWith("image/")){const Bn=Un.getAsFile();if(Bn){Ke.preventDefault(),yn(Bn);return}}}};return document.addEventListener("paste",te),()=>document.removeEventListener("paste",te)},[yn]);const Gn=a.useCallback(te=>{te.preventDefault()},[]),ts=a.useCallback(te=>{te.preventDefault();const Ke=te.dataTransfer.files;for(let ut=0;ut<Ke.length;ut++){const Dt=Ke[ut];if(Dt.type.startsWith("image/")){yn(Dt);return}}},[yn]),Jn=a.useCallback(async te=>{try{await Nv(e.id,te,n),I(Ke=>Ke.filter(ut=>ut.filename!==te)),h("Attachment deleted","info")}catch(Ke){h(je(Ke),"error")}},[e.id,h]),ns=a.useCallback(async te=>{const Ke=Mn;Vt(te);try{const ut=await Zs(e.id,{enabledWorkflowSteps:te},n);h("Workflow steps updated","success"),m?.(ut)}catch(ut){Vt(Ke),h(`Failed to update workflow steps: ${je(ut)}`,"error")}},[e.id,n,Mn,m,h]),Sn=a.useCallback(async()=>{he(!0);try{const te=await xa(void 0,n);j(te),W(!0)}catch(te){h(`Failed to load agents: ${je(te)}`,"error"),W(!1)}finally{he(!1)}},[n,h]),ss=a.useCallback(async te=>{try{const Ke=await Ud(e.id,te,n),ut=A.find(Dt=>Dt.id===te)??null;$(ut||(Dt=>Dt?.id===te?Dt:null)),W(!1),m?.(Ke),h("Assigned agent updated","success")}catch(Ke){h(`Failed to assign agent: ${je(Ke)}`,"error")}},[e.id,n,A,m,h]),_s=a.useCallback(async()=>{try{const te=await Ud(e.id,null,n);$(null),W(!1),m?.(te),h("Agent unassigned","success")}catch(te){h(`Failed to unassign agent: ${je(te)}`,"error")}},[e.id,n,m,h]),Ys=a.useCallback(async te=>{const Ke=[...P,te];E(Ke);try{await Zs(e.id,{dependencies:Ke},n)}catch(ut){E(P),h(je(ut),"error")}},[e.id,P,h]),bs=a.useCallback(async(te,Ke)=>{te.stopPropagation();const ut=P.filter(Dt=>Dt!==Ke);E(ut);try{await Zs(e.id,{dependencies:ut},n)}catch(Dt){E(P),h(je(Dt),"error")}},[e.id,P,h]),On=a.useCallback(async te=>{try{const Ke=await ao(te,n);r(Ke)}catch{h(`Failed to load dependency ${te}`,"error")}},[r,h]),cs=a.useCallback(async te=>{fe(!0);try{await Zs(k.id,{prompt:te},n),h("Spec updated","success"),v&&(v.prompt=te)}catch(Ke){throw h(je(Ke),"error"),Ke}finally{fe(!1)}},[k,v,h]),ds=a.useCallback(async te=>{Ne(!0);try{await Rv(e.id,te,n),h("AI revision requested. Task moved to planning.","success"),i()}catch(Ke){const ut=je(Ke);ut.includes("in-review")||ut.includes("done")?h("Cannot request revision: Task must be in 'todo' or 'in-progress' column.","error"):h(ut,"error")}finally{Ne(!1)}},[e.id,h,i]),zo=a.useCallback(()=>{ve(!0),ye(k.prompt||""),Me("")},[k.prompt]),xi=a.useCallback(()=>{ve(!1),ye(k.prompt||""),Me("")},[k.prompt]),ka=a.useCallback(async()=>{if(ue===(k.prompt||"")){xi();return}await cs(ue),ve(!1)},[ue,k.prompt,cs,xi]),Fi=a.useCallback(async()=>{ie.trim()&&await ds(ie.trim())},[ie,ds]),Fo=a.useCallback(te=>{te.key==="Escape"?(te.preventDefault(),xi()):te.key==="Enter"&&(te.ctrlKey||te.metaKey)&&(te.preventDefault(),ka())},[xi,ka]),jr=s.filter(te=>te.id!==e.id&&!P.includes(te.id)).sort((te,Ke)=>{const ut=Ke.createdAt.localeCompare(te.createdAt);if(ut!==0)return ut;const Dt=parseInt(te.id.slice(te.id.lastIndexOf("-")+1),10)||0;return(parseInt(Ke.id.slice(Ke.id.lastIndexOf("-")+1),10)||0)-Dt}),wr=C?.name??e.assignedAgentId??null,Nr=a.useMemo(()=>{const te=[];return k.modelProvider&&te.push(k.modelProvider),k.validatorModelProvider&&!te.includes(k.validatorModelProvider)&&te.push(k.validatorModelProvider),k.planningModelProvider&&!te.includes(k.planningModelProvider)&&te.push(k.planningModelProvider),te},[k.modelProvider,k.validatorModelProvider,k.planningModelProvider]),bi=mc[e.column]||[],ri=["todo","in-progress"],Sr=e.column==="in-review"?ri:bi,vs=Sr[0],oi=Sr.slice(1),Oi=oi.length>0,Ds={"creating-pr":"Creating PR…","awaiting-pr-checks":"Awaiting PR checks","merging-pr":"Merging PR…"},ja=e.status?Ds[e.status]:void 0;return t.jsx("div",{className:"modal-overlay open",...pt,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg task-detail-modal",ref:We,onDragOver:Gn,onDrop:ts,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx("span",{className:"detail-id",children:e.id}),t.jsx("span",{className:`detail-column-badge badge-${e.column}`,children:$n[e.column]})]}),t.jsxs("div",{className:"modal-header-actions",children:[!_e&&hn&&t.jsx("button",{className:"modal-edit-btn",onClick:ke,title:"Edit task","aria-label":"Edit task",children:t.jsx(Qn,{size:14})}),t.jsx("button",{className:"modal-close",onClick:i,"aria-label":"Close",children:"×"})]})]}),t.jsxs("div",{className:`detail-body${f==="logs"&&w==="agent-log"&&!_e?" detail-body--agent-log":""}`,children:[_e?t.jsx("div",{className:"modal-edit-form",children:t.jsx(Pf,{mode:"edit",title:ae,onTitleChange:be,description:ne,onDescriptionChange:Ie,dependencies:Pe,onDependenciesChange:ce,executorModel:le,onExecutorModelChange:$e,validatorModel:at,onValidatorModelChange:tt,planningModel:V,onPlanningModelChange:de,thinkingLevel:Z,onThinkingLevelChange:we,presetMode:pe,onPresetModeChange:Te,selectedPresetId:mt,onSelectedPresetIdChange:gt,selectedWorkflowSteps:wt,onWorkflowStepsChange:yt,pendingImages:Mt,onImagesChange:Kt,tasks:s.filter(te=>te.id!==e.id),projectId:n,disabled:Ot,addToast:h,isActive:_e,onAutoSaveDescription:Pn,reviewLevel:Qe,onReviewLevelChange:Ee,priority:Re,onPriorityChange:Le,executionMode:ct,onExecutionModeChange:Se,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:kt,onChange:te=>Ct(te.target.value),disabled:Ot,"data-testid":"task-source-provider-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Repository (e.g. owner/repo)",value:Rt,onChange:te=>Ft(te.target.value),disabled:Ot,"data-testid":"task-source-repository-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Issue identifier",value:Ut,onChange:te=>St(te.target.value),disabled:Ot,"data-testid":"task-source-external-id-input"}),t.jsx("input",{type:"url",className:"modal-edit-input",placeholder:"Issue URL",value:Et,onChange:te=>It(te.target.value),disabled:Ot,"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 te=e.title||e.description||e.id,Ke=!N&&te.length>Ll;return t.jsxs(t.Fragment,{children:[t.jsx("h2",{className:"detail-title",children:Ke?te.slice(0,Ll)+"…":te}),te.length>Ll&&t.jsx("button",{className:"detail-description-toggle",onClick:()=>L(!N),children:N?"Show less":"Show more"})]})})(),t.jsxs("div",{className:"detail-meta",children:["Created ",new Date(e.createdAt).toLocaleDateString()," · Updated"," ",new Date(e.updatedAt).toLocaleDateString()," ·",t.jsxs("span",{className:`detail-priority-chip detail-priority-chip--${$a(e.priority)}`,children:["Priority: ",$a(e.priority)]})]})]}),e.status==="failed"&&e.error&&t.jsxs("div",{className:"detail-error-alert",children:[t.jsx("span",{className:"detail-error-icon",children:"⚠"}),t.jsxs("div",{className:"detail-error-content",children:[t.jsx("div",{className:"detail-error-title",children:"Task Failed"}),t.jsx("div",{className:"detail-error-message",children:e.error})]})]}),!_e&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"detail-tabs",children:[t.jsx("button",{className:`detail-tab${f==="definition"?" detail-tab-active":""}`,onClick:()=>x("definition"),children:"Definition"}),t.jsx("button",{className:`detail-tab${f==="logs"?" detail-tab-active":""}`,onClick:()=>x("logs"),children:"Logs"}),(e.column==="in-progress"||e.column==="in-review"||e.column==="done")&&t.jsx("button",{className:`detail-tab${f==="changes"?" detail-tab-active":""}`,onClick:()=>x("changes"),children:"Changes"}),t.jsx("button",{className:`detail-tab${f==="comments"?" detail-tab-active":""}`,onClick:()=>x("comments"),children:"Comments"}),t.jsx("button",{className:`detail-tab${f==="documents"?" detail-tab-active":""}`,onClick:()=>x("documents"),children:"Documents"}),t.jsx("button",{className:`detail-tab${f==="model"?" detail-tab-active":""}`,onClick:()=>x("model"),children:"Model"}),t.jsx("button",{className:`detail-tab${f==="workflow"?" detail-tab-active":""}`,onClick:()=>x("workflow"),children:"Workflow"}),t.jsx("button",{className:`detail-tab${f==="stats"?" detail-tab-active":""}`,onClick:()=>x("stats"),children:"Stats"}),_t.map((te,Ke)=>{const ut=`plugin-${Ke}`;return t.jsx("button",{className:`detail-tab${f===ut?" detail-tab-active":""}`,onClick:()=>x(ut),children:te.slot.label},`plugin-tab-${te.pluginId}`)})]}),f==="workflow"?t.jsx("div",{className:"detail-section",children:t.jsx(o_,{taskId:e.id,results:kn,loading:En,enabledWorkflowSteps:Mn,canEdit:hn,projectId:n,isTaskInProgress:e.column==="in-progress"&&e.status!=="paused",onWorkflowStepsChange:ns})}):f==="model"?t.jsx("div",{className:"detail-section",children:t.jsx(HM,{task:e,addToast:h,onTaskUpdated:m,settings:$t})}):f==="logs"?t.jsxs("div",{className:`detail-section${w==="agent-log"?" detail-section--agent-log":""}`,children:[t.jsxs("div",{className:"log-subview-toggle",children:[t.jsx("button",{className:`log-subview-btn${w==="activity"?" log-subview-btn-active":""}`,onClick:()=>_("activity"),children:"Activity"}),t.jsx("button",{className:`log-subview-btn${w==="agent-log"?" log-subview-btn-active":""}`,onClick:()=>_("agent-log"),children:"Agent Log"})]}),w==="agent-log"?t.jsx(zM,{entries:_n,loading:jn,executorModel:p_(e,$t),validatorModel:f_(e,$t),planningModel:x_(e,_n,$t),hasMore:Oe,onLoadMore:Q,loadingMore:Ze,totalCount:Xe}):t.jsxs("div",{className:"detail-activity",children:[t.jsx("h4",{children:"Activity"}),k.activityLogTruncatedCount?t.jsxs("div",{className:"detail-log-truncated",children:["Showing the most recent ",k.log.length," activity entries."]}):null,k.log&&k.log.length>0?t.jsx("div",{className:"detail-activity-list",children:[...k.log].reverse().map((te,Ke)=>t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-timestamp",children:v_(te.timestamp)}),t.jsx("span",{className:"detail-log-action",children:te.action})]}),te.outcome&&t.jsx("div",{className:"detail-log-outcome",children:te.outcome})]},Ke))}):t.jsx("div",{className:"detail-log-empty",children:"(no activity)"})]})]}):f==="changes"?t.jsx(ZM,{taskId:e.id,worktree:e.worktree,projectId:n,column:e.column,mergeDetails:e.mergeDetails,modifiedFiles:e.modifiedFiles}):f==="comments"?t.jsx(GM,{task:e,addToast:h,projectId:n,onTaskUpdated:m}):f==="documents"?t.jsx(u_,{taskId:e.id,addToast:h,projectId:n,onTaskUpdated:m,canEdit:hn}):typeof f=="string"&&f.startsWith("plugin-")?t.jsx("div",{className:"detail-section",children:t.jsx(Ao,{slotId:"task-detail-tab",projectId:n})}):f==="stats"?t.jsx("div",{className:"detail-section",children:t.jsx(h_,{tokenUsage:k.tokenUsage,loading:y,task:k})}):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(si,{remarkPlugins:[ii],children:e.summary})})]}),t.jsx(YM,{task:e}),e.sourceIssue&&t.jsxs("div",{className:"detail-section detail-source-section",children:[t.jsx("h4",{children:"Source Issue"}),t.jsxs("dl",{className:"detail-source-grid",children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Provider"}),t.jsx("dd",{children:e.sourceIssue.provider})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Repository"}),t.jsx("dd",{children:e.sourceIssue.repository})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Issue Identifier"}),t.jsx("dd",{children:e.sourceIssue.externalIssueId})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"URL"}),t.jsx("dd",{children:e.sourceIssue.url?t.jsx("a",{className:"detail-source-link",href:e.sourceIssue.url,target:"_blank",rel:"noopener noreferrer",children:e.sourceIssue.url}):t.jsx("span",{className:"detail-source-empty",children:"(none)"})})]})]})]}),t.jsx("div",{className:"detail-section detail-agent-section",children:t.jsxs("div",{className:"detail-meta-row",children:[t.jsxs("div",{className:"detail-meta-left",children:[Nr.length>0&&t.jsx("span",{className:"detail-provider-icons","data-testid":"detail-provider-icons",children:Nr.map(te=>t.jsx(Tn,{provider:te,size:"sm"},te))}),t.jsxs("span",{className:"detail-meta-label",children:[t.jsx(pn,{size:14,style:{verticalAlign:"middle",marginRight:6}}),"Agent"]})]}),t.jsxs("div",{className:"detail-agent-actions",children:[wr?t.jsxs("span",{className:"detail-agent-chip",children:[t.jsx(pn,{size:14}),wr,t.jsx("button",{className:"detail-agent-clear",onClick:()=>void _s(),title:"Unassign agent",children:t.jsx(zt,{size:12})})]}):t.jsx("button",{className:"btn btn-sm",onClick:()=>{J?W(!1):Sn()},children:"Assign Agent"}),J&&t.jsxs("div",{className:"agent-picker-dropdown",children:[oe&&t.jsx("div",{className:"agent-picker-loading",children:"Loading agents..."}),!oe&&A.filter(te=>te.state!=="terminated").map(te=>t.jsxs("button",{className:`agent-picker-item${e.assignedAgentId===te.id?" selected":""}`,onClick:()=>void ss(te.id),children:[t.jsx(pn,{size:14}),t.jsx("span",{className:"agent-picker-name",children:te.name}),t.jsx("span",{className:"agent-picker-role",children:te.role})]},te.id)),!oe&&A.filter(te=>te.state!=="terminated").length===0&&t.jsx("div",{className:"agent-picker-empty",children:"No agents available"})]})]})]})}),t.jsxs("div",{className:"detail-section detail-step-progress",children:[t.jsx("h4",{children:"Progress"}),k.steps&&k.steps.length>0?t.jsxs("div",{className:"step-progress-wrapper",children:[t.jsx("div",{className:"step-progress-bar",children:k.steps.map((te,Ke)=>t.jsx("div",{className:`step-progress-segment step-progress-segment--${te.status}`,"data-tooltip":`${te.name} (${te.status})`,style:{backgroundColor:b_(te.status)}},Ke))}),t.jsxs("span",{className:"step-progress-label",children:[k.steps.filter(te=>te.status==="done").length,"/",k.steps.length," step",k.steps.length===1?"":"s"]})]}):t.jsx("div",{className:"step-progress-empty",children:"(no steps defined)"})]}),t.jsxs("div",{className:"detail-section",children:[!ee&&t.jsx("div",{className:"detail-spec-edit-trigger",children:t.jsx("button",{className:"btn btn-sm",onClick:zo,children:"Edit"})}),ee?t.jsxs("div",{className:"spec-editor-edit-mode",children:[t.jsx("textarea",{className:"spec-editor-textarea",value:ue,onChange:te=>ye(te.target.value),onKeyDown:Fo,disabled:se,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:xi,disabled:se,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void ka(),disabled:ue===(k.prompt||"")||se,children:se?"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:ie,onChange:te=>Me(te.target.value),placeholder:"e.g., 'Add more details about error handling', 'Split this into smaller steps', 'Include tests for the API endpoints'...",disabled:U,rows:4,maxLength:2e3}),t.jsxs("div",{className:"spec-editor-revision-actions",children:[t.jsxs("span",{className:"spec-editor-char-count",children:[ie.length,"/2000"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Fi(),disabled:!ie.trim()||U,children:U?"Requesting…":"Request AI Revision"})]})]})]}):y?t.jsx("div",{className:"spec-loading",children:"Loading specification…"}):k.prompt?t.jsx("div",{className:"markdown-body",children:t.jsx(si,{remarkPlugins:[ii],children:k.prompt.replace(/^#\s+[^\n]*\n+/,"")})}):t.jsx("div",{className:"detail-prompt",children:"(no prompt)"})]}),t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Attachments"}),T.length>0?t.jsx("div",{className:"detail-attachments-grid",children:T.map(te=>{const Ke=Ks(`/api/tasks/${e.id}/attachments/${te.filename}`);return t.jsxs("div",{className:"detail-attachment-card",children:[t.jsx("a",{className:"detail-attachment-link",href:Ke,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{src:Ke,alt:te.originalName,className:"detail-attachment-image"})}),t.jsxs("div",{className:"detail-attachment-meta",children:[te.originalName," (",y_(te.size),")"]}),t.jsx("button",{className:"detail-attachment-delete",onClick:()=>Jn(te.filename),title:"Delete attachment",children:"×"})]},te.filename)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no attachments)"}),t.jsx("input",{className:"detail-hidden-file-input",ref:gn,type:"file",accept:"image/*",onChange:xs}),t.jsx("button",{className:"btn btn-sm",onClick:()=>gn.current?.click(),disabled:z,children:z?"Uploading…":"Attach Screenshot"})]}),t.jsxs("div",{className:"detail-deps",children:[t.jsx("h4",{children:"Dependencies"}),P.length>0?t.jsx("ul",{className:"detail-dep-list",children:P.map(te=>{const Ke=s.find(Dt=>Dt.id===te),ut=Ke?.title||Ke?.description||te;return t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>On(te),onKeyDown:Dt=>{(Dt.key==="Enter"||Dt.key===" ")&&(Dt.preventDefault(),On(te))},role:"link",tabIndex:0,title:`Click to view ${te}`,children:[t.jsx("span",{className:"detail-dep-id",children:te}),t.jsx("span",{className:"detail-dep-label",children:Om(ut,40)})]}),t.jsx("button",{className:"dep-remove-btn",onClick:Dt=>bs(Dt,te),title:`Remove dependency ${te}`,children:"×"})]},te)})}):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:()=>{R&&X(""),B(te=>!te)},children:"Add Dependency"}),R&&(()=>{const te=G.toLowerCase(),Ke=te?jr.filter(ut=>ut.id.toLowerCase().includes(te)||ut.title&&ut.title.toLowerCase().includes(te)||ut.description&&ut.description.toLowerCase().includes(te)):jr;return t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:G,onChange:ut=>X(ut.target.value),onClick:ut=>ut.stopPropagation()}),Ke.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Ke.map(ut=>t.jsxs("div",{className:"dep-dropdown-item",onClick:()=>{Ys(ut.id),B(!1)},children:[t.jsx("span",{className:"dep-dropdown-id",children:ut.id}),t.jsx("span",{className:"dep-dropdown-title",children:Om(ut.title||ut.description||ut.id,30)})]},ut.id))]})})()]})]}),e.column==="in-review"&&t.jsx(VM,{taskId:e.id,projectId:n,prInfo:e.prInfo,automationStatus:e.status??null,autoMerge:$t?.autoMerge??!1,prAuthAvailable:g??!1,onPrCreated:te=>{e.prInfo=te,h(`PR #${te.number} created`,"success")},onPrUpdated:te=>{e.prInfo=te},addToast:h})]})]})]}),t.jsx("div",{className:"modal-actions",children:_e?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:nt,disabled:Ot,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:tn,disabled:Ot,children:Ot?"Saving…":"Save"})]}):t.jsxs(t.Fragment,{children:[e.column==="triage"&&e.status==="awaiting-approval"&&k.prompt&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:re,children:"Approve Plan"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:Ae,children:"Reject Plan"})]}),e.column==="triage"&&e.status!=="awaiting-approval"&&!M&&t.jsx("button",{className:"btn btn-sm btn-danger",onClick:At,"aria-label":"Delete task",title:"Delete task",children:"Delete"}),(e.column!=="triage"||e.status==="awaiting-approval"||M)&&t.jsxs("div",{className:"detail-actions-dropdown",ref:me,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>{H(te=>!te),Y(!1)},"aria-haspopup":"menu","aria-expanded":F,children:["Actions",t.jsx(qt,{size:12})]}),F&&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:()=>ot(At),children:"Delete"}),d&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ot(bt),children:"Duplicate"}),(e.column==="done"||e.column==="in-review")&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ot(vt),children:"Refine"}),t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ot(lt),children:"Respecify"}),M&&u&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ot(Qt),children:"Retry"}),e.column!=="done"&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ot(Kn),children:e.paused?"Unpause":"Pause"})]})]}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("div",{className:"detail-move-dropdown",ref:ge,children:e.column==="in-review"?t.jsxs("div",{className:"detail-move-actions-in-review",children:[t.jsxs("div",{className:"detail-move-split-btn",children:[t.jsxs("button",{className:"btn btn-primary btn-sm detail-move-split-btn__main",onClick:()=>vs&&Zt(vs),disabled:!vs,children:["Move to ",vs?$n[vs]:""]}),Oi&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"detail-move-split-btn__divider","aria-hidden":"true"}),t.jsx("button",{className:"btn btn-primary btn-sm detail-move-split-btn__chevron",onClick:()=>{Y(te=>!te),H(!1)},"aria-label":"More move options","aria-haspopup":"menu","aria-expanded":Ve,children:t.jsx(qt,{size:12})})]}),Ve&&Oi&&t.jsx("div",{className:"detail-move-menu detail-move-split-btn__menu",role:"menu",children:oi.map(te=>t.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>Zt(te),children:te==="in-progress"?"Back to In Progress":`Move to ${$n[te]}`},te))})]}),ja?t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!0,children:ja}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Ht,children:"Merge & Close"})]}):t.jsxs("div",{className:"detail-move-split-btn",children:[t.jsxs("button",{className:"btn btn-primary btn-sm detail-move-split-btn__main",onClick:()=>vs&&Zt(vs),disabled:!vs,children:["Move to ",vs?$n[vs]:""]}),Oi&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"detail-move-split-btn__divider","aria-hidden":"true"}),t.jsx("button",{className:"btn btn-primary btn-sm detail-move-split-btn__chevron",onClick:()=>{Y(te=>!te),H(!1)},"aria-label":"More move options","aria-haspopup":"menu","aria-expanded":Ve,children:t.jsx(qt,{size:12})})]}),Ve&&Oi&&t.jsx("div",{className:"detail-move-menu detail-move-split-btn__menu",role:"menu",children:oi.map(te=>t.jsxs("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>Zt(te),children:["Move to ",$n[te]]},te))})]})})]})}),ze&&t.jsx("div",{className:"modal-overlay open detail-refine-overlay",onClick:en,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal detail-refine-modal",onClick:te=>te.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:en,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"detail-body",children:[t.jsx("p",{className:"detail-refine-help",children:"Describe what needs to be refined or improved..."}),t.jsx("textarea",{className:"detail-refine-textarea",value:Je,onChange:te=>Ye(te.target.value),placeholder:"Enter your feedback here...",rows:6,maxLength:2e3,autoFocus:!0}),t.jsxs("div",{className:"detail-refine-input-group",children:[t.jsxs("div",{className:"detail-refine-char-count",children:[Je.length,"/2000 characters"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:An,disabled:!Je.trim()||Ge,children:Ge?"Creating...":"Create Refinement Task"})]})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:en,disabled:Ge,children:"Cancel"})})]})})]})})}const S_=640;function C_({isOpen:e,onClose:n,onImport:s,tasks:i,projectId:r}){const[o,l]=a.useState(""),[c,u]=a.useState(""),[d,m]=a.useState(""),[h,g]=a.useState(!1),[p,f]=a.useState("issues"),[x,v]=a.useState([]),[b,y]=a.useState(null),[S,k]=a.useState([]),[M,w]=a.useState(null),[_,N]=a.useState(null),[L,T]=a.useState(!1),[I,z]=a.useState([]),[K,P]=a.useState(!1),[E,R]=a.useState(""),B=a.useRef(!1),G=a.useRef(null);Gs(G,e,"fusion:github-modal-size");const X=fi(n),[C,$]=a.useState(!1),[A,j]=a.useState("list"),J=a.useRef(null),W=new Set;for(const ce of i){const le=ce.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);le&&W.add(le[1]);const $e=ce.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);$e&&W.add($e[1])}a.useEffect(()=>{if(e)return l(""),u(""),m(""),v([]),y(null),k([]),w(null),f("issues"),N(null),T(!1),z([]),P(!0),R(""),J.current=null,B.current=!0,Vv().then(ce=>{if(B.current)if(z(ce),P(!1),ce.length===1){const le=ce[0];l(le.owner),u(le.repo),R(le.name)}else ce.length>1&&(l(""),u(""),R(""))}).catch(()=>{B.current&&P(!1)}),()=>{B.current=!1}},[e]);const oe=a.useCallback(ce=>{if(R(ce),ce==="")l(""),u("");else{const le=I.find($e=>$e.name===ce);le&&(l(le.owner),u(le.repo))}},[I]),he=a.useCallback(async()=>{if(!o.trim()||!c.trim()){N("Repository must be selected");return}g(!0),N(null),v([]),y(null);try{const ce=d.split(",").map($e=>$e.trim()).filter(Boolean),le=await Uv(o.trim(),c.trim(),30,ce.length>0?ce:void 0);v(le),le.length===0&&N("No open issues found")}catch(ce){N(je(ce)||"Failed to fetch issues")}finally{g(!1)}},[o,c,d]),se=a.useCallback(async()=>{if(!o.trim()||!c.trim()){N("Repository must be selected");return}g(!0),N(null),k([]),w(null);try{const ce=await Hv(o.trim(),c.trim(),30);k(ce),ce.length===0&&N("No open pull requests found")}catch(ce){N(je(ce)||"Failed to fetch pull requests")}finally{g(!1)}},[o,c]);a.useEffect(()=>{if(!e||!o.trim()||!c.trim()||h||L)return;const ce={owner:o.trim(),repo:c.trim(),labels:d.trim(),tab:p};J.current?.owner===ce.owner&&J.current?.repo===ce.repo&&J.current?.labels===ce.labels&&J.current?.tab===ce.tab||(J.current=ce,p==="issues"?he():se())},[o,c,d,p,e,h,L,he,se]),a.useEffect(()=>{if(!e)return;const ce=le=>{le.key==="Escape"&&n()};return document.addEventListener("keydown",ce),()=>document.removeEventListener("keydown",ce)},[e,n]),a.useEffect(()=>{if(!e)return;const ce=()=>{$(window.innerWidth<=S_)};return ce(),window.addEventListener("resize",ce),()=>window.removeEventListener("resize",ce)},[e]);const fe=a.useCallback(ce=>{y(ce),C&&j("preview")},[C]),U=a.useCallback(ce=>{w(ce),C&&j("preview")},[C]),Ne=a.useCallback(()=>{j("list")},[]),ee=a.useCallback(async()=>{if(p==="issues"){if(b===null)return;T(!0),N(null);try{const ce=await Bv(o.trim(),c.trim(),b,r);s(ce),n()}catch(ce){const le=je(ce);le?.includes("already imported")?N(le):N(le||"Failed to import issue")}finally{T(!1)}}else{if(M===null)return;T(!0),N(null);try{const ce=await qv(o.trim(),c.trim(),M,r);s(ce),n()}catch(ce){const le=je(ce);le?.includes("already imported")?N(le):N(le||"Failed to import pull request")}finally{T(!1)}}},[p,b,M,o,c,s,n]),ve=x.find(ce=>ce.number===b),ue=S.find(ce=>ce.number===M);if(!e)return null;const ye=I.length>0,ie=I.length===1,Me=x.filter(ce=>W.has(ce.html_url)).length,ze=S.filter(ce=>W.has(ce.html_url)).length,Be=_==="No open issues found",Je=_==="No open pull requests found",Ye=p==="issues"?Be:Je,Ge=!!_&&!Be&&x.length===0&&!h,it=!!_&&!Je&&S.length===0&&!h,_e=p==="issues"?Ge:it,Fe=h||x.length>0||Be||Ge,ae=h||S.length>0||Je||it,be=p==="issues"?Fe:ae,ne=!!_&&x.length>0&&!Be,Ie=!!_&&S.length>0&&!Je,Pe=p==="issues"?ne:Ie;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:()=>{f("issues"),w(null)},disabled:h||L,children:[t.jsx(ko,{size:16}),t.jsx("span",{children:"Issues"})]}),t.jsxs("button",{role:"tab","aria-selected":p==="pulls","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="pulls"?"active":""}`,onClick:()=>{f("pulls"),y(null)},disabled:h||L,children:[t.jsx(hs,{size:16}),t.jsx("span",{children:"Pull Requests"})]})]}),t.jsxs("div",{className:"github-import-toolbar","data-testid":"github-import-toolbar",role:"toolbar","aria-label":"GitHub import controls",children:[t.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--remote",children:K?t.jsxs("div",{className:"github-import-toolbar__loading",role:"status","aria-live":"polite",children:[t.jsx(rt,{size:16,className:"spin"}),t.jsx("span",{children:"Detecting…"})]}):ye?ie?t.jsxs("div",{className:"github-import-remote-pill","data-testid":"github-import-single-remote",children:[t.jsx("span",{className:"github-import-remote-pill__name",children:I[0].name}),t.jsxs("span",{className:"github-import-remote-pill__repo",children:[I[0].owner,"/",I[0].repo]})]}):t.jsxs("div",{className:"github-import-remote-select",children:[t.jsx("label",{htmlFor:"gh-remote",className:"visually-hidden",children:"Repository"}),t.jsxs("select",{id:"gh-remote",value:E,onChange:ce=>oe(ce.target.value),disabled:h||L,"aria-label":"Select Git remote",children:[t.jsx("option",{value:"",children:"Select remote…"}),I.map(ce=>t.jsxs("option",{value:ce.name,children:[ce.name," (",ce.owner,"/",ce.repo,")"]},ce.name))]})]}):t.jsx("span",{className:"github-import-toolbar__no-remote",children:"No remotes"})}),t.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--filter",children:p==="issues"?t.jsxs(t.Fragment,{children:[t.jsx("label",{htmlFor:"gh-labels",className:"visually-hidden",children:"Filter by labels"}),t.jsx("input",{id:"gh-labels",type:"text",placeholder:"Filter: bug,enhancement…",value:d,onChange:ce=>m(ce.target.value),onKeyDown:ce=>ce.key==="Enter"&&he(),disabled:h||L||!ye,"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"?he:se,disabled:h||L||!o.trim()||!c.trim(),"aria-label":h?`Loading ${p}`:`Load ${p} from repository`,title:h?"Loading…":`Load ${p}`,children:[h?t.jsx(rt,{size:14,className:"spin"}):t.jsx(wn,{size:14}),t.jsx("span",{children:h?"Loading…":"Load"})]})})]}),!K&&!ye&&t.jsxs("div",{className:"github-import-state github-import-state--warning",role:"alert",children:[t.jsxs("div",{children:[t.jsx("strong",{children:"No GitHub remotes detected"}),t.jsx("span",{children:"Add a GitHub remote to this repository, then reopen the modal."})]}),t.jsx("code",{className:"github-import-command",children:"git remote add origin https://github.com/owner/repo.git"})]}),Pe&&t.jsx("div",{className:"form-error github-import-banner",role:"alert",children:_}),t.jsxs("div",{className:"github-import-workspace",children:[t.jsxs("section",{className:`github-import-list-pane ${C?"mobile":""} ${A==="list"?"active":""}`,"data-testid":"github-import-list-pane","aria-labelledby":"github-import-results-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[t.jsx("h4",{id:"github-import-results-heading",children:p==="issues"?"Issues":"Pull Requests"}),p==="issues"&&x.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[x.length," issue",x.length===1?"":"s"]}),t.jsxs("span",{children:[Me," imported"]})]}),p==="pulls"&&S.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[S.length," pull request",S.length===1?"":"s"]}),t.jsxs("span",{children:[ze," imported"]})]})]}),t.jsxs("div",{className:"github-import-pane-content",children:[!be&&t.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-results-idle",children:t.jsxs("div",{children:[t.jsx("strong",{children:"Nothing loaded yet"}),t.jsx("span",{children:"Select a repository and click Load to start reviewing import candidates."})]})}),h&&t.jsxs("div",{className:"github-import-state github-import-state--loading",role:"status","aria-live":"polite",children:[t.jsx(rt,{size:16,className:"spin"}),t.jsxs("div",{children:[t.jsxs("strong",{children:["Loading open ",p==="issues"?"issues":"pull requests","…"]}),t.jsx("span",{children:"Fetching the latest list from GitHub."})]})]}),_e&&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:_})]})}),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"&&x.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:x.map(ce=>{const le=W.has(ce.html_url);return t.jsxs("div",{className:`issue-item ${b===ce.number?"selected":""} ${le?"imported":""}`,onClick:()=>!le&&fe(ce.number),children:[t.jsx("input",{type:"radio",name:"issue",checked:b===ce.number,onChange:()=>fe(ce.number),disabled:le,"aria-label":`Select issue #${ce.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",ce.number]}),t.jsx("span",{className:"issue-title",children:ce.title})]}),ce.labels.length>0&&t.jsx("span",{className:"issue-labels",children:ce.labels.map($e=>t.jsx("span",{className:"label-chip",children:$e.name},$e.name))})]}),le&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},ce.number)})}),p==="pulls"&&S.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:S.map(ce=>{const le=W.has(ce.html_url);return t.jsxs("div",{className:`issue-item ${M===ce.number?"selected":""} ${le?"imported":""}`,onClick:()=>!le&&U(ce.number),children:[t.jsx("input",{type:"radio",name:"pull",checked:M===ce.number,onChange:()=>U(ce.number),disabled:le,"aria-label":`Select pull request #${ce.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",ce.number]}),t.jsx("span",{className:"issue-title",children:ce.title})]}),t.jsxs("span",{className:"pull-branch-info",children:[ce.headBranch," → ",ce.baseBranch]})]}),le&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},ce.number)})})]})]}),t.jsxs("section",{className:`github-import-preview-pane ${C?"mobile":""} ${A==="preview"?"active":""}`,"data-testid":"github-import-preview-pane","aria-labelledby":"github-import-preview-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[C&&t.jsxs("button",{className:"github-import-back-button",onClick:Ne,"data-testid":"github-import-back-button","aria-label":`Back to ${p==="issues"?"issues":"pull requests"} list`,children:[t.jsx(ga,{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"&&ve?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Issue #",ve.number]}),t.jsx("div",{className:"preview-title",children:ve.title}),t.jsx("div",{className:"preview-body",children:ve.body?ve.body.slice(0,200)+(ve.body.length>200?"…":""):"(no description)"})]}):p==="issues"?t.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-preview-empty",children:t.jsxs("div",{children:[t.jsx("strong",{children:"No issue selected"}),t.jsx("span",{children:"Choose an issue from the list to inspect its title and description."})]})}):null,p==="pulls"&&ue?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Pull Request #",ue.number]}),t.jsx("div",{className:"preview-title",children:ue.title}),t.jsxs("div",{className:"preview-branch",children:[t.jsx("strong",{children:"Branch:"})," ",ue.headBranch," → ",ue.baseBranch]}),t.jsx("div",{className:"preview-body",children:ue.body?ue.body.slice(0,200)+(ue.body.length>200?"…":""):"(no description)"})]}):p==="pulls"?t.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-preview-empty",children:t.jsxs("div",{children:[t.jsx("strong",{children:"No pull request selected"}),t.jsx("span",{children:"Choose a pull request from the list to inspect its details."})]})}):null]})]})]})]}),t.jsxs("div",{className:"modal-actions github-import-modal__actions",children:[t.jsx("button",{className:"btn",onClick:n,disabled:L,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:ee,disabled:(p==="issues"?b===null:M===null)||L,children:L?t.jsx(rt,{size:14,className:"spin"}):"Import"})]})]})})}const E_=["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 M_(e,n){return e&&n?`${e}/${n}`:""}function __(e){if(!e)return{provider:void 0,modelId:void 0};const n=e.indexOf("/");return n===-1?{provider:void 0,modelId:void 0}:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function A_({isOpen:e,onClose:n,onTaskCreated:s,onTasksCreated:i,tasks:r,initialPlan:o,projectId:l,resumeSessionId:c}){const[u,d]=a.useState(""),[m,h]=a.useState({type:"initial"}),[g,p]=a.useState(null),[f,x]=a.useState([]),[v,b]=a.useState([]),[y,S]=a.useState(null),k=a.useRef(!1),M=a.useRef(!1),[w,_]=a.useState(""),[N,L]=a.useState(!0),[T,I]=a.useState(!1),[z,K]=a.useState(!1),P=a.useRef(null),E=a.useRef(null),R=a.useRef(null),B=a.useRef(null),[G,X]=a.useState(c??null),C=a.useMemo(()=>Li(),[]),{isLockedByOther:$,takeControl:A,isLoading:j}=To(e?G:null),{activeTabMap:J,broadcastUpdate:W,broadcastCompleted:oe,broadcastLock:he,broadcastUnlock:se,broadcastHeartbeat:fe}=ba(),[U,Ne]=a.useState(void 0),[ee,ve]=a.useState(void 0),[ue,ye]=a.useState([]),[ie,Me]=a.useState(!1),[ze,Be]=a.useState(null),[Je,Ye]=a.useState([]),[Ge,it]=a.useState([]),_e=a.useRef(null),[Fe,ae]=a.useState([]),[be,ne]=a.useState(!1),[Ie,Pe]=a.useState(c??null),[ce,le]=a.useState(!!c),[$e,at]=a.useState(null),tt=a.useRef(!1),V=a.useRef(null);Gs(E,e,"fusion:planning-modal-size"),a.useEffect(()=>{const xe=V.current;if(!xe)return;xe.scrollHeight-xe.scrollTop-xe.clientHeight<32&&(xe.scrollTop=xe.scrollHeight)},[w]);const de=a.useCallback(()=>{d(""),h({type:"initial"}),p(null),x([]),b([]),S(null),_(""),I(!1),K(!1),Ne(void 0),ve(void 0),B.current=null,X(null)},[]),Z=M_(U,ee),we=a.useCallback((xe,st)=>{if(!xe||!st)return"Using default";const Ve=ue.find(Y=>Y.provider===xe&&Y.id===st);return Ve?`${Ve.provider}/${Ve.id}`:`${xe}/${st}`},[ue]),pe=a.useCallback(async()=>{Me(!0),Be(null);try{const xe=await os();ye(xe.models),Ye(xe.favoriteProviders),it(xe.favoriteModels)}catch(xe){Be(je(xe)||"Failed to load models")}finally{Me(!1)}},[]),Te=a.useCallback(xe=>{Ye(st=>{const Ve=st,F=Ve.includes(xe)?Ve.filter(H=>H!==xe):[xe,...Ve];return an({favoriteProviders:F,favoriteModels:Ge}).catch(()=>{Ye(Ve)}),F})},[Ge]),Qe=a.useCallback(xe=>{it(st=>{const Ve=st,F=Ve.includes(xe)?Ve.filter(H=>H!==xe):[xe,...Ve];return an({favoriteProviders:Je,favoriteModels:F}).catch(()=>{it(Ve)}),F})},[Je]),Ee=a.useCallback(xe=>{R.current?.close();const st=Hy(xe,l,{onThinking:Ve=>{_(Y=>Y+Ve),W({sessionId:xe,status:"generating",needsInput:!1,owningTabId:C,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onQuestion:Ve=>{I(!1),K(!1),Ki(l),h({type:"question",session:{sessionId:xe,currentQuestion:Ve,summary:null}}),_(""),W({sessionId:xe,status:"awaiting_input",needsInput:!0,owningTabId:C,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onSummary:Ve=>{I(!1),K(!1),Ki(l),h({type:"summary",session:{sessionId:xe,currentQuestion:null,summary:Ve},summary:Ve}),S(Ve),_(""),W({sessionId:xe,status:"complete",needsInput:!1,owningTabId:C,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onError:Ve=>{const Y=Ve||"Session failed while contacting the AI.";I(!0),(async()=>{try{const F=await ti(xe);if(F&&(F.status==="generating"||F.status==="awaiting_input")){Ee(xe);return}}catch{}I(!1),K(!1),p(null),h(F=>F.type==="question"||F.type==="summary"||F.type==="error"?{type:"error",session:F.session,errorMessage:Y}:{type:"error",session:{sessionId:xe,currentQuestion:null,summary:null},errorMessage:Y}),_(""),B.current=xe,W({sessionId:xe,status:"error",needsInput:!1,owningTabId:C,type:"planning",title:u.trim()||"Planning session",projectId:l??null}),oe({sessionId:xe,status:"error"})})()},onComplete:()=>{I(!1),K(!1),B.current=null,oe({sessionId:xe,status:"complete"})},onConnectionStateChange:Ve=>{I(Ve==="reconnecting")}});R.current=st},[oe,W,u,l,C]),Re=a.useCallback(async xe=>{const st=xe??u;if(st.trim()){p(null),_(""),b([]),x([]),I(!1),h({type:"loading"});try{const Ve=U&&ee?{planningModelProvider:U,planningModelId:ee}:void 0,{sessionId:Y}=await Ey(st.trim(),l,Ve);B.current=Y,X(Y),Pe(Y),Ee(Y),x([])}catch(Ve){I(!1),p(je(Ve)||"Failed to start planning session"),h({type:"initial"}),B.current=null,X(null)}}},[Ee,u,ee,U,l]);a.useEffect(()=>{e&&m.type==="initial"&&P.current?.focus()},[e,m.type]),a.useEffect(()=>{e&&pe()},[e,pe]),a.useEffect(()=>{if(e&&o&&!k.current&&m.type==="initial"){d(o);const xe=setTimeout(()=>{k.current=!0,Re(o)},0);return()=>clearTimeout(xe)}else if(e&&!o&&!k.current&&!M.current&&m.type==="initial"){M.current=!0;const xe=EN(l);xe&&d(xe)}},[e,o,m.type,Re,l]);const Le=a.useCallback(async xe=>{R.current?.close(),R.current=null,p(null),_(""),x([]),b([]),S(null),K(!1),h({type:"loading"});try{const st=await ti(xe);if(!st){Pe(null),le(!1),h({type:"initial"});return}B.current=xe,X(xe);const Ve=la(st.conversationHistory);if(b(Ve),x(Ve.map(Y=>Y.response).filter(Y=>!!(Y&&typeof Y=="object"&&!Array.isArray(Y)))),st.status==="awaiting_input"&&st.currentQuestion){Ki(l);const Y=JSON.parse(st.currentQuestion);h({type:"question",session:{sessionId:xe,currentQuestion:Y,summary:null}}),st.thinkingOutput&&_(st.thinkingOutput),Ee(xe)}else if(st.status==="complete"&&st.result){Ki(l);const Y=JSON.parse(st.result);h({type:"summary",session:{sessionId:xe,currentQuestion:null,summary:Y},summary:Y}),S(Y)}else st.status==="generating"?(h({type:"loading"}),st.thinkingOutput&&_(st.thinkingOutput),Ee(xe)):st.status==="error"&&h({type:"error",session:{sessionId:xe,currentQuestion:null,summary:null},errorMessage:st.error||"Session failed"})}catch{p("Failed to load session"),h({type:"initial"})}},[Ee,l]);a.useEffect(()=>{!e||!c||B.current!==c&&(Pe(c),le(!0),Le(c))},[e,c,Le]),a.useEffect(()=>{e&&Ie&&(c&&c===Ie||R.current?.isConnected()||Le(Ie))},[e]);const ct=a.useCallback(async()=>{ne(!0);try{const st=(await Uc(l)).filter(Ve=>Ve.type==="planning").sort((Ve,Y)=>Date.parse(Y.updatedAt)-Date.parse(Ve.updatedAt));ae(st)}catch{}finally{ne(!1)}},[l]);a.useEffect(()=>{e&&ct()},[e,ct]),a.useEffect(()=>{if(!e)return;const xe=l?`?projectId=${encodeURIComponent(l)}`:"",st=Y=>{try{const F=JSON.parse(Y.data);if(F.type!=="planning")return;ae(H=>{const ge=H.findIndex(We=>We.id===F.id);return(ge>=0?[...H.slice(0,ge),F,...H.slice(ge+1)]:[F,...H]).sort((We,dt)=>Date.parse(dt.updatedAt)-Date.parse(We.updatedAt))})}catch{}},Ve=Y=>{try{const F=JSON.parse(Y.data);ae(H=>H.filter(ge=>ge.id!==F))}catch{}};return $s(`/api/events${xe}`,{events:{"ai_session:updated":st,"ai_session:deleted":Ve},onReconnect:()=>{ct()}})},[e,l,ct]);const Se=a.useCallback(xe=>{if(Ie===xe){le(!0);return}Pe(xe),le(!0),Le(xe)},[Le,Ie]),mt=a.useCallback(()=>{R.current?.close(),R.current=null,de(),Pe(null),le(!0)},[de]),gt=a.useCallback(()=>{le(!1)},[]),wt=a.useCallback(async xe=>{const st=Y=>Y==="generating"||Y==="awaiting_input",Ve=Fe.find(Y=>Y.id===xe);if(Ve&&st(Ve.status))try{await Gh(xe,l,C)}catch{}try{await sp(xe)}catch{}oe({sessionId:xe,status:"complete",timestamp:Date.now()}),ae(Y=>Y.filter(F=>F.id!==xe)),Ie===xe&&(R.current?.close(),R.current=null,de(),Pe(null),le(!1)),at(null)},[oe,Fe,l,de,Ie,C]);a.useEffect(()=>{e||(k.current=!1,M.current=!1,I(!1),K(!1),X(null))},[e]),a.useEffect(()=>{if(!e){_e.current&&(se(_e.current,C),_e.current=null);return}if(G&&_e.current!==G){_e.current&&se(_e.current,C),he(G,C),_e.current=G;return}!G&&_e.current&&(se(_e.current,C),_e.current=null)},[he,se,e,G,C]),a.useEffect(()=>{if(!e||!G||_e.current!==G)return;fe(C);const xe=setInterval(()=>{fe(C)},3e4);return()=>{clearInterval(xe)}},[fe,e,G,C]),a.useEffect(()=>()=>{R.current?.close(),R.current=null,_e.current&&(se(_e.current,C),_e.current=null)},[se,C]),a.useEffect(()=>{if(!e)return;const xe=()=>{R.current?.close(),R.current=null};return window.addEventListener("beforeunload",xe),()=>window.removeEventListener("beforeunload",xe)},[e]);const yt=a.useCallback(()=>{u&&m.type==="initial"&&CN(u,l),R.current?.close(),R.current=null,I(!1),K(!1),n()},[u,n,l,m.type]);a.useEffect(()=>{if(!e)return;const xe=st=>{st.key==="Escape"&&yt()};return document.addEventListener("keydown",xe),()=>document.removeEventListener("keydown",xe)},[e,yt]);const kt=a.useCallback(async xe=>{if(m.type!=="question")return;const{session:st}=m,Ve=st.sessionId,Y=st.currentQuestion;if(!Y){p("No active question in session");return}p(null),x(F=>[...F,xe]),b(F=>[...F,{question:Y,response:xe}]),h({type:"loading"}),_("");try{await My(Ve,xe,l,C)}catch(F){p(je(F)||"Failed to submit response"),h({type:"question",session:st})}},[l,C,m]),Ct=a.useCallback(async()=>{if(m.type!=="error")return;const xe=m.session;p(null),K(!0),_(""),h({type:"loading"}),Ee(xe.sessionId);try{B.current=xe.sessionId,X(xe.sessionId),await _y(xe.sessionId,l,C)}catch(st){let Ve=st;if((je(st)||"").includes("not in an error state"))try{const F=await ti(xe.sessionId);if(!F)throw new Error("Failed to refresh planning session.");if(B.current=F.id,X(F.id),F.status==="generating")_(F.thinkingOutput??""),h({type:"loading"});else if(F.status==="awaiting_input"){if(!F.currentQuestion)throw new Error("Planning session is awaiting input but has no current question.");const H=JSON.parse(F.currentQuestion);Ki(l),h({type:"question",session:{sessionId:F.id,currentQuestion:H,summary:null}}),R.current?.isConnected()||Ee(F.id)}else if(F.status==="complete"){if(!F.result)throw new Error("Planning session is complete but has no result.");const H=JSON.parse(F.result);Ki(l),h({type:"summary",session:{sessionId:F.id,currentQuestion:null,summary:H},summary:H}),S(H)}else F.status==="error"&&h({type:"error",session:{sessionId:F.id,currentQuestion:null,summary:null},errorMessage:F.error||"Retry failed. Please try again."});I(!1);return}catch(F){Ve=F}R.current?.close(),R.current=null,h({type:"error",session:xe,errorMessage:je(Ve)||"Retry failed. Please try again."}),I(!1)}finally{K(!1)}},[Ee,l,C,m]),Rt=a.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const xe=m.session.sessionId,st=await Ay(xe,y??void 0,l);s(st),Pe(null),ae(Ve=>Ve.filter(Y=>Y.id!==xe)),oe({sessionId:xe,status:"complete",timestamp:Date.now()}),yt()}catch(xe){p(je(xe)||"Failed to create task"),h({type:"summary",session:m.session,summary:m.summary})}}},[oe,y,m,l,s,yt]),Ft=a.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const xe=await Ry(m.session.sessionId,y??void 0,l);X(xe.sessionId),h({type:"breakdown",sessionId:xe.sessionId,subtasks:xe.subtasks,dirty:!1})}catch(xe){p(je(xe)||"Failed to start breakdown"),h({type:"summary",session:m.session,summary:m.summary})}}},[y,m,l]),Ut=a.useCallback(async()=>{if(m.type==="breakdown"){p(null),h({type:"creating"});try{const xe=m.sessionId,st=await Ty(xe,m.subtasks,l);i(st.tasks),ae(Ve=>Ve.filter(Y=>Y.id!==xe)),oe({sessionId:xe,status:"complete",timestamp:Date.now()}),d(""),h({type:"initial"}),p(null),x([]),b([]),S(null),_(""),Ne(void 0),ve(void 0),B.current=null,X(null),Pe(null),n()}catch(xe){p(je(xe)||"Failed to create tasks"),h({type:"breakdown",sessionId:m.sessionId,subtasks:m.subtasks,dirty:m.dirty})}}},[oe,m,i,n,l]),St=a.useCallback(()=>{if(m.type==="question"&&f.length>0){const xe=f.slice(0,-1);x(xe),h({type:"question",session:m.session})}},[m,f]),Et=()=>m.type==="question"?Math.min(f.length+1,3):3,It=G?J.get(G):null,Mt=It&&It.tabId!==C,Kt=!!(Mt&&!It.stale),Ot=$&&(!Mt||It.stale);return e?t.jsx("div",{className:"modal-overlay open",onMouseDown:xe=>{tt.current=xe.target===xe.currentTarget},onClick:xe=>{xe.target===xe.currentTarget&&tt.current&&yt(),tt.current=!1},role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",ref:E,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[ce&&t.jsx("button",{className:"modal-back planning-mobile-back",onClick:gt,"aria-label":"Back to sessions",title:"Back to sessions",children:t.jsx(yo,{size:18})}),t.jsx(Ws,{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:yt,"aria-label":"Close",children:t.jsx(zt,{size:20})})})]}),t.jsxs("div",{className:`planning-modal-body planning-modal-body--split ${ce?"planning-modal-body--show-detail":"planning-modal-body--show-list"}`,children:[t.jsx($_,{sessions:Fe,loading:be,selectedSessionId:Ie,pendingDeleteId:$e,onSelectSession:Se,onNewSession:mt,onRequestDelete:at,onConfirmDelete:xe=>void wt(xe),onCancelDelete:()=>at(null)}),t.jsxs("div",{className:"planning-detail",children:[g&&t.jsx("div",{className:"form-error planning-error",children:g}),T&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Kt&&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(Vn,{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:P,id:"initial-plan",rows:4,className:"planning-textarea",placeholder:"e.g., Build a user authentication system with login, signup, and password reset...",value:u,onChange:xe=>d(xe.target.value),onKeyDown:xe=>{xe.key==="Enter"&&!xe.shiftKey&&u.trim()&&(xe.preventDefault(),Re())}})]}),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:E_.map((xe,st)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>d(xe),children:xe.length>40?xe.slice(0,40)+"...":xe},st))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"planning-modal-model",className:"form-label",children:["Planning Model",ie&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(Ln,{id:"planning-modal-model",label:"Planning Model",value:Z,onChange:xe=>{const{provider:st,modelId:Ve}=__(xe);Ne(st),ve(Ve)},models:ue,disabled:ie,favoriteProviders:Je,onToggleFavorite:Te,favoriteModels:Ge,onToggleModelFavorite:Qe}),ze&&t.jsxs("div",{className:"form-hint form-hint-error",children:[ze," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{pe()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${U&&ee?"model-badge-custom":"model-badge-default"}`,children:we(U,ee)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>Re(),disabled:!u.trim(),children:[t.jsx(Ws,{size:16,className:"icon-mr-8"}),"Start Planning"]})})]}),m.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(rt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:w?"AI is thinking...":"Generating next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>L(!N),type:"button",children:N?"Hide thinking":"Show thinking"}),N&&w&&t.jsx("div",{className:"planning-thinking-output",ref:V,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(Ms,{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 Ct(),disabled:z,children:[z?t.jsx(rt,{size:14,className:"spin"}):t.jsx(wn,{size:14}),t.jsx("span",{className:"icon-ml-6",children:z?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:yt,disabled:z,children:"Dismiss"})]})]})]})}),m.type==="creating"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(rt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:"Creating tasks..."})]}),m.type==="question"&&m.session.currentQuestion&&t.jsx("div",{className:"planning-question",children:t.jsx(R_,{question:m.session.currentQuestion,progress:Et(),historyEntries:v,onSubmit:kt,onBack:f.length>0?St:void 0})}),m.type==="summary"&&y&&t.jsx(T_,{summary:y,historyEntries:v,onSummaryChange:S,tasks:r,onCreateTask:Rt,onBreakIntoTasks:Ft,onRefine:()=>{h({type:"question",session:m.session})},isLoading:!1}),m.type==="breakdown"&&t.jsx(I_,{subtasks:m.subtasks,dirty:m.dirty,isLoading:!1,onUpdateSubtasks:xe=>h({...m,subtasks:xe,dirty:!0}),onCreateTasks:Ut,onBack:()=>{const st={sessionId:m.sessionId,currentQuestion:null,summary:y??null};y&&h({type:"summary",session:st,summary:y})}})]}),$&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(No,{size:16}),t.jsx("span",{children:Ot?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),Ot&&t.jsx("button",{type:"button",onClick:()=>{A()},disabled:j,className:"btn btn-primary session-lock-take-control",children:j?"Taking control...":"Take Control"})]})})]})]})}):null}function R_({question:e,progress:n,historyEntries:s,onSubmit:i,onBack:r}){const[o,l]=a.useState({}),[c,u]=a.useState(""),d=a.useCallback(()=>{e.type==="text"?i({[e.id]:c}):e.type==="confirm"?i({[e.id]:o[e.id]===!0}):i(o)},[e,o,c,i]);a.useEffect(()=>{l({}),u("")},[e.id]);const m=()=>{switch(e.type){case"text":return c.trim().length>0;case"single_select":return o[e.id]!==void 0;case"multi_select":return Array.isArray(o[e.id])&&o[e.id].length>0;case"confirm":return o[e.id]!==void 0;default:return!0}};return t.jsxs("div",{className:"planning-question-form",children:[t.jsxs("div",{className:"planning-view-scroll planning-question-scroll",children:[s.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ms,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3].map(h=>t.jsx("div",{className:`planning-progress-step ${h<=n?"active":""}`},h))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~3"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:c,onChange:h=>u(h.target.value),onKeyDown:h=>{h.key==="Enter"&&!h.shiftKey&&c.trim()&&(h.preventDefault(),d())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(h=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:h.id,checked:o[e.id]===h.id,onChange:()=>l({[e.id]:h.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:h.label}),h.description&&t.jsx("span",{className:"planning-option-desc",children:h.description})]})]},h.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(h=>{const g=o[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:h.id,checked:g.includes(h.id),onChange:p=>{const f=p.target.checked?[...g,h.id]:g.filter(x=>x!==h.id);l({[e.id]:f})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:h.label}),h.description&&t.jsx("span",{className:"planning-option-desc",children:h.description})]})]},h.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!0?"selected":""}`,onClick:()=>l({[e.id]:!0}),children:[t.jsx(un,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!1?"selected":""}`,onClick:()=>l({[e.id]:!1}),children:[t.jsx(zt,{size:18}),"No"]})]})]})]})]})]}),t.jsxs("div",{className:"planning-actions",children:[r&&t.jsxs("button",{className:"btn",onClick:r,children:[t.jsx(ga,{size:16,className:"icon-mr-4"}),"Back"]}),t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:d,disabled:!m(),children:["Continue",t.jsx(dr,{size:16,className:"icon-ml-4"})]})]})]})}function T_({summary:e,historyEntries:n,onSummaryChange:s,tasks:i,onCreateTask:r,onBreakIntoTasks:o,onRefine:l,isLoading:c}){const[u,d]=a.useState(!1),[m,h]=a.useState(e.suggestedDependencies),g=p=>{const f=m.includes(p)?m.filter(x=>x!==p):[...m,p];h(f),s({...e,suggestedDependencies:f})};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ms,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(un,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Planning Complete!"}),t.jsx("p",{className:"text-muted",children:"Review and refine your task before creating it."})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{children:["Description",t.jsx("button",{type:"button",className:"planning-expand-btn",onClick:()=>d(!u),children:u?"Collapse":"Expand"})]}),t.jsx("textarea",{className:`planning-textarea ${u?"expanded":""}`,rows:u?10:4,value:e.description,onChange:p=>s({...e,description:p.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Suggested Size"}),t.jsxs("select",{className:"planning-size-select",value:e.suggestedSize,onChange:p=>s({...e,suggestedSize:p.target.value}),disabled:c,children:[t.jsx("option",{value:"S",children:"S (Small)"}),t.jsx("option",{value:"M",children:"M (Medium)"}),t.jsx("option",{value:"L",children:"L (Large)"})]})]}),i.length>0&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Suggested Dependencies"}),t.jsx("div",{className:"planning-deps-list",children:i.map(p=>t.jsxs("label",{className:`planning-dep-chip ${m.includes(p.id)?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:m.includes(p.id),onChange:()=>g(p.id)}),t.jsx("span",{className:"planning-dep-id",children:p.id}),t.jsx("span",{className:"planning-dep-title",children:p.title||p.description.slice(0,30)})]},p.id))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Key Deliverables"}),t.jsx("ul",{className:"planning-deliverables",children:e.keyDeliverables.map((p,f)=>t.jsx("li",{children:p},f))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:l,disabled:c,children:[t.jsx(ga,{size:16,className:"icon-mr-4"}),"Refine Further"]}),t.jsxs("div",{className:"planning-summary-actions-right",children:[t.jsx("button",{className:"btn",onClick:o,disabled:c,title:"Break the plan into multiple tasks with dependencies",children:c?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:16,className:"spin icon-mr-8"}),"Breaking down..."]}):t.jsxs(t.Fragment,{children:[t.jsx(wo,{size:16,className:"icon-mr-8"}),"Break into Tasks"]})}),t.jsx("button",{className:"btn btn-primary",onClick:r,disabled:c,children:c?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:16,className:"spin icon-mr-8"}),"Creating..."]}):t.jsxs(t.Fragment,{children:[t.jsx(un,{size:16,className:"icon-mr-8"}),"Create Task"]})})]})]})]})}function Bm(e){const n=new Map(e.map(o=>[o.id,o.dependsOn])),s=new Set,i=new Set,r=o=>{if(s.has(o))return!0;if(i.has(o))return!1;s.add(o);for(const l of n.get(o)??[])if(n.has(l)&&r(l))return!0;return s.delete(o),i.add(o),!1};return e.some(o=>r(o.id))}function P_(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function I_({subtasks:e,dirty:n,isLoading:s,onUpdateSubtasks:i,onCreateTasks:r,onBack:o}){const[l,c]=a.useState(null),[u,d]=a.useState(null),[m,h]=a.useState(null),g=a.useRef([]),p=a.useMemo(()=>e.length===0||e.some(_=>!_.title.trim())?!0:Bm(e),[e]),f=a.useCallback((_,N)=>{i(e.map(L=>L.id===_?{...L,...N}:L))},[e,i]),x=a.useCallback(()=>{i([...e,P_(e.length+1)])},[e,i]),v=a.useCallback(_=>{i(e.filter(N=>N.id!==_).map(N=>({...N,dependsOn:N.dependsOn.filter(L=>L!==_)})))},[e,i]),b=a.useCallback((_,N)=>{if(N<0||N>=e.length)return;const L=[...e],[T]=L.splice(_,1);L.splice(N,0,T),i(L)},[e,i]),y=a.useCallback(_=>N=>{c(_),N.dataTransfer.setData("text/plain",_),N.dataTransfer.effectAllowed="move"},[]),S=a.useCallback(()=>{c(null),d(null),h(null)},[]),k=a.useCallback(_=>N=>{if(N.preventDefault(),_===l)return;const L=N.currentTarget.getBoundingClientRect(),T=L.top+L.height/2,I=N.clientY<T?"before":"after";d(_),h(I)},[l]),M=a.useCallback(_=>N=>{N.preventDefault();const L=N.dataTransfer.getData("text/plain");if(!L||L===_){S();return}const T=e.findIndex(E=>E.id===L),I=e.findIndex(E=>E.id===_);if(T===-1||I===-1){S();return}const z=[...e],[K]=z.splice(T,1);let P=I;m==="after"&&T<I&&P--,m==="after"&&P++,z.splice(P,0,K),i(z),S()},[e,m,i,S]),w=a.useCallback(_=>{const N=_.currentTarget.getBoundingClientRect(),L=_.clientX,T=_.clientY;(L<N.left||L>N.right||T<N.top||T>N.bottom)&&(d(null),h(null))},[]);return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(wo,{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((_,N)=>{const L=l===_.id,T=u===_.id,I=["task-detail-section","subtask-item",L?"subtask-item-dragging":"",T?"subtask-item-drop-target":"",T&&m==="before"?"subtask-item-drop-before":"",T&&m==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:I,"data-testid":`subtask-item-${N}`,draggable:!s,onDragStart:y(_.id),onDragEnd:S,onDragOver:k(_.id),onDrop:M(_.id),onDragLeave:w,children:[t.jsxs("div",{className:"detail-title-row subtask-item-header subtask-item-header--between",children:[t.jsxs("div",{className:"subtask-drag-handle",title:"Drag to reorder",children:[t.jsx(Lc,{size:16}),t.jsx("strong",{children:_.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>b(N,N-1),disabled:s||N===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(Mi,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>b(N,N+1),disabled:s||N===e.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(cr,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>v(_.id),disabled:s,children:[t.jsx(Jt,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:z=>{g.current[N]=z},value:_.title,onChange:z=>f(_.id,{title:z.target.value}),onKeyDown:z=>{z.key==="Enter"&&(z.preventDefault(),N<e.length-1&&g.current[N+1]?.focus())},disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:_.description,onChange:z=>f(_.id,{description:z.target.value}),disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Size"}),t.jsxs("select",{className:"planning-size-select",value:_.suggestedSize,onChange:z=>f(_.id,{suggestedSize:z.target.value}),disabled:s,children:[t.jsx("option",{value:"S",children:"S"}),t.jsx("option",{value:"M",children:"M"}),t.jsx("option",{value:"L",children:"L"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"planning-deps-list",children:[e.slice(0,N).filter(z=>z.id!==_.id).map(z=>{const K=_.dependsOn.includes(z.id);return t.jsxs("label",{className:`planning-dep-chip ${K?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:K,onChange:()=>{const P=K?_.dependsOn.filter(E=>E!==z.id):[..._.dependsOn,z.id];f(_.id,{dependsOn:P})},disabled:s}),t.jsx("span",{className:"planning-dep-id",children:z.id}),t.jsx("span",{className:"planning-dep-title",children:z.title||"Untitled"})]},z.id)}),N===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),N>0&&e.slice(0,N).filter(z=>z.id!==_.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},_.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:x,disabled:s,children:[t.jsx(Xt,{size:16,className:"icon-mr-6"})," Add subtask"]}),Bm(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(ga,{size:16,className:"icon-mr-4"}),"Back to Summary"]}),t.jsx("button",{className:"btn btn-primary",onClick:r,disabled:s||p,children:s?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]})}function $_({sessions:e,loading:n,selectedSessionId:s,pendingDeleteId:i,onSelectSession:r,onNewSession:o,onRequestDelete:l,onConfirmDelete:c,onCancelDelete:u}){return t.jsxs("aside",{className:"planning-sidebar","aria-label":"Planning sessions",children:[t.jsx("div",{className:"planning-sidebar-header",children:t.jsxs("button",{className:`planning-sidebar-new ${s===null?"active":""}`,onClick:o,type:"button",children:[t.jsx(Wx,{size:16}),t.jsx("span",{children:"New session"})]})}),t.jsxs("div",{className:"planning-sidebar-list",children:[e.length===0&&!n&&t.jsx("div",{className:"planning-sidebar-empty text-muted",children:"No saved sessions yet. Start one on the right to see it here."}),e.map(d=>{const m=d.id===s,h=i===d.id;return t.jsxs("div",{className:`planning-sidebar-item ${m?"selected":""} ${h?"pending-delete":""}`,children:[t.jsxs("button",{type:"button",className:"planning-sidebar-item-button",onClick:()=>r(d.id),children:[t.jsx(D_,{status:d.status}),t.jsxs("span",{className:"planning-sidebar-item-body",children:[t.jsx("span",{className:"planning-sidebar-item-title",children:d.title||"Untitled session"}),t.jsxs("span",{className:"planning-sidebar-item-meta",children:[t.jsx(L_,{status:d.status}),t.jsx("span",{"aria-hidden":!0,children:" · "}),t.jsx("span",{children:z_(d.updatedAt)})]})]})]}),h?t.jsxs("div",{className:"planning-sidebar-confirm",children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-danger",onClick:()=>c(d.id),children:"Delete"}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:u,children:"Cancel"})]}):t.jsx("button",{type:"button",className:"planning-sidebar-item-delete",onClick:g=>{g.stopPropagation(),l(d.id)},"aria-label":"Delete session",title:"Delete session",children:t.jsx(Jt,{size:14})})]},d.id)})]})]})}function D_({status:e}){switch(e){case"generating":return t.jsx(rt,{size:14,className:"spin planning-sidebar-status-icon planning-sidebar-status-generating"});case"awaiting_input":return t.jsx(ec,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-awaiting"});case"complete":return t.jsx(un,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-complete"});case"error":return t.jsx(Zn,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-error"});default:return t.jsx(hi,{size:14,className:"planning-sidebar-status-icon"})}}function L_({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 z_(e){const n=Date.now()-Date.parse(e);if(!Number.isFinite(n)||n<0)return"";const s=Math.floor(n/1e3);if(s<60)return"just now";const i=Math.floor(s/60);if(i<60)return`${i}m ago`;const r=Math.floor(i/60);if(r<24)return`${r}h ago`;const o=Math.floor(r/24);if(o<7)return`${o}d ago`;const l=Math.floor(o/7);return l<4?`${l}w ago`:new Date(e).toLocaleDateString()}function F_(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function Hm(e){const n=new Map(e.map(o=>[o.id,o.dependsOn])),s=new Set,i=new Set,r=o=>{if(s.has(o))return!0;if(i.has(o))return!1;s.add(o);for(const l of n.get(o)??[])if(n.has(l)&&r(l))return!0;return s.delete(o),i.add(o),!1};return e.some(o=>r(o.id))}function O_({isOpen:e,onClose:n,initialDescription:s,onTasksCreated:i,parentTaskId:r,projectId:o,resumeSessionId:l}){const[c,u]=a.useState({type:"initial"}),[d,m]=a.useState([]),[h,g]=a.useState([]),[p,f]=a.useState(""),[x,v]=a.useState(!0),[b,y]=a.useState(!1),[S,k]=a.useState(!1),[M,w]=a.useState(s),[_,N]=a.useState(null),[L,T]=a.useState(!1),[I,z]=a.useState(null),[K,P]=a.useState(null),[E,R]=a.useState(null),B=a.useRef(null),G=a.useRef([]),X=a.useRef(!1),C=a.useRef(null),$=c.type==="generating"||c.type==="editing"||c.type==="creating"||c.type==="error"?c.sessionId:null,A=a.useMemo(()=>Li(),[]),{isLockedByOther:j,takeControl:J,isLoading:W}=To(e?$:null),{activeTabMap:oe,broadcastUpdate:he,broadcastCompleted:se,broadcastLock:fe,broadcastUnlock:U,broadcastHeartbeat:Ne}=ba(),ee=a.useMemo(()=>d.length===0||d.some(V=>!V.title.trim())?!0:Hm(d),[d]),ve=c.type==="generating"||c.type==="editing"||c.type==="error",ue=$?oe.get($):null,{confirm:ye}=Is(),ie=ue&&ue.tabId!==A,Me=!!(ie&&!ue.stale),ze=j&&(!ie||ue.stale),Be=a.useCallback(()=>{M&&MN(M,o),B.current?.close(),B.current=null,u({type:"initial"}),m([]),g([]),f(""),v(!0),y(!1),k(!1),N(null),T(!1),X.current=!1},[M,o]),Je=a.useCallback(()=>{B.current?.close(),B.current=null,n()},[n]),Ye=a.useCallback(async()=>{if(!((L||c.type==="editing"||c.type==="creating")&&!await ye({title:"Discard Changes",message:"Close subtask breakdown? Unsaved changes will be lost.",danger:!0}))){if($)try{await Qh($,o,A)}catch{}Be(),n()}},[L,n,Be,$,A,c.type,o,ye]),Ge=a.useCallback(V=>{B.current?.close(),B.current=ak(V,o,{onThinking:de=>{f(Z=>Z+de),he({sessionId:V,status:"generating",needsInput:!1,owningTabId:A,type:"subtask",title:M.trim()||"Subtask breakdown",projectId:o??null})},onSubtasks:de=>{y(!1),k(!1),rl(o),m(de),u({type:"editing",sessionId:V}),T(!1),he({sessionId:V,status:"awaiting_input",needsInput:!0,owningTabId:A,type:"subtask",title:M.trim()||"Subtask breakdown",projectId:o??null})},onError:de=>{const Z=de||"Session failed while contacting the AI.";y(!1),k(!1),N(null),u({type:"error",sessionId:V,errorMessage:Z}),he({sessionId:V,status:"error",needsInput:!1,owningTabId:A,type:"subtask",title:M.trim()||"Subtask breakdown",projectId:o??null}),se({sessionId:V,status:"error"})},onComplete:()=>{se({sessionId:V,status:"complete"})},onConnectionStateChange:de=>{y(de==="reconnecting")}})},[se,he,M,o,A]),it=a.useCallback(async()=>{if(M.trim()){N(null),g([]),f(""),y(!1);try{const{sessionId:V}=await nk(M.trim(),o);u({type:"generating",sessionId:V}),Ge(V)}catch(V){N(je(V)||"Failed to start subtask breakdown"),u({type:"initial"})}}},[Ge,M,o]);a.useEffect(()=>{if(!e){Be();return}if(e&&s&&!X.current)w(s),X.current=!0,it();else if(e&&!s&&!X.current){const V=_N(o);V&&w(V)}},[e,s,it,Be]),a.useEffect(()=>{!e||!l||c.type!=="initial"||(async()=>{try{const V=await ti(l);if(!V)return;const de=la(V.conversationHistory);if(g(de),V.status==="generating"||V.status==="awaiting_input")f(V.thinkingOutput??""),u({type:"generating",sessionId:l}),Ge(l);else if(V.status==="complete"&&V.result){rl(o);const Z=JSON.parse(V.result);m(Z),u({type:"editing",sessionId:l})}else V.status==="error"&&(N(null),u({type:"error",sessionId:l,errorMessage:V.error??"Session encountered an error"}))}catch(V){N(je(V)||"Failed to resume session")}})()},[Ge,e,l,c.type,o]),a.useEffect(()=>{if(!e){C.current&&(U(C.current,A),C.current=null);return}if($&&C.current!==$){C.current&&U(C.current,A),fe($,A),C.current=$;return}!$&&C.current&&(U(C.current,A),C.current=null)},[fe,U,e,$,A]),a.useEffect(()=>{if(!e||!$||C.current!==$)return;Ne(A);const V=setInterval(()=>{Ne(A)},3e4);return()=>{clearInterval(V)}},[Ne,e,$,A]),a.useEffect(()=>()=>{B.current?.close(),C.current&&(U(C.current,A),C.current=null)},[U,A]),a.useEffect(()=>{if(!e)return;const V=de=>{de.key==="Escape"&&(de.preventDefault(),Ye())};return document.addEventListener("keydown",V),()=>document.removeEventListener("keydown",V)},[e,Ye]);const _e=a.useCallback((V,de)=>{m(Z=>Z.map(we=>we.id===V?{...we,...de}:we)),T(!0)},[]),Fe=a.useCallback(()=>{m(V=>[...V,F_(V.length+1)]),T(!0)},[]),ae=a.useCallback(V=>{m(de=>de.filter(Z=>Z.id!==V).map(Z=>({...Z,dependsOn:Z.dependsOn.filter(we=>we!==V)}))),T(!0)},[]),be=a.useCallback(V=>de=>{z(V),de.dataTransfer.setData("text/plain",V),de.dataTransfer.effectAllowed="move"},[]),ne=a.useCallback(()=>{z(null),P(null),R(null)},[]),Ie=a.useCallback(V=>de=>{if(de.preventDefault(),V===I)return;const Z=de.currentTarget.getBoundingClientRect(),we=Z.top+Z.height/2,pe=de.clientY<we?"before":"after";P(V),R(pe)},[I]),Pe=a.useCallback(V=>de=>{de.preventDefault();const Z=de.dataTransfer.getData("text/plain");if(!Z||Z===V){z(null),P(null),R(null);return}m(we=>{const pe=we.findIndex(Le=>Le.id===Z),Te=we.findIndex(Le=>Le.id===V);if(pe===-1||Te===-1)return we;const Qe=[...we],[Ee]=Qe.splice(pe,1);let Re=Te;return E==="after"&&pe<Te&&Re--,E==="after"&&Re++,Qe.splice(Re,0,Ee),Qe}),T(!0),z(null),P(null),R(null)},[E]),ce=a.useCallback(V=>{const de=V.currentTarget.getBoundingClientRect(),Z=V.clientX,we=V.clientY;(Z<de.left||Z>de.right||we<de.top||we>de.bottom)&&(P(null),R(null))},[]),le=a.useCallback((V,de)=>{de<0||de>=d.length||(m(Z=>{const we=[...Z],[pe]=we.splice(V,1);return we.splice(de,0,pe),we}),T(!0))},[d.length]),$e=a.useCallback(V=>{G.current[V+1]?.focus()},[]),at=a.useCallback(async()=>{if(!(!$||ee)){N(null),u({type:"creating",sessionId:$});try{const V=await rk($,d,r,o);i(V.tasks),Be(),n()}catch(V){N(je(V)||"Failed to create tasks"),u({type:"editing",sessionId:$})}}},[ee,n,i,r,o,Be,$,d]),tt=a.useCallback(async()=>{if(c.type!=="error")return;const V=c.sessionId;N(null),k(!0),f(""),u({type:"generating",sessionId:V}),Ge(V);try{await sk(V,o,A)}catch(de){let Z=de;if((je(de)||"").includes("not in an error state"))try{const pe=await ti(V);if(!pe)throw new Error("Failed to refresh subtask session.");if(g(la(pe.conversationHistory)),pe.status==="generating"||pe.status==="awaiting_input")f(pe.thinkingOutput??""),u({type:"generating",sessionId:pe.id}),B.current?.isConnected()||Ge(pe.id);else if(pe.status==="complete"){if(!pe.result)throw new Error("Subtask session is complete but has no result.");rl(o);const Te=JSON.parse(pe.result);m(Te),u({type:"editing",sessionId:pe.id}),T(!1)}else pe.status==="error"&&u({type:"error",sessionId:pe.id,errorMessage:pe.error??"Retry failed. Please try again."});y(!1);return}catch(pe){Z=pe}B.current?.close(),B.current=null,u({type:"error",sessionId:V,errorMessage:je(Z)||"Retry failed. Please try again."}),y(!1)}finally{k(!1)}},[Ge,o,A,c]);return e?t.jsx("div",{className:"modal-overlay open",onClick:V=>V.target===V.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(wo,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Subtask Breakdown"})]}),t.jsxs("div",{className:"modal-header-actions",children:[ve&&t.jsx("button",{className:"modal-send-to-background",onClick:Je,title:"Send to background","aria-label":"Send to background",children:t.jsx(mr,{size:16})}),t.jsx("button",{className:"modal-close",onClick:()=>void Ye(),"aria-label":"Close",children:t.jsx(zt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[_&&t.jsx("div",{className:"form-error planning-error",children:_}),b&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Me&&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:M})]})}),c.type==="generating"&&t.jsxs("div",{className:"planning-loading",children:[h.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ms,{entries:h,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsx(rt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:"AI is generating subtasks..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>v(!x),type:"button",children:x?"Hide thinking":"Show thinking"}),x&&p&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:p})})]})]}),c.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[h.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ms,{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 tt(),disabled:S,children:[S?t.jsx(rt,{size:14,className:"spin"}):t.jsx(wn,{size:14}),t.jsx("span",{className:"icon-ml-6",children:S?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:()=>void Ye(),disabled:S,children:"Cancel"})]})]})]})}),(c.type==="editing"||c.type==="creating")&&t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[h.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ms,{entries:h}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(un,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Review your subtasks"}),t.jsx("p",{className:"text-muted",children:"Edit titles, descriptions, sizes, and dependencies before creating all tasks at once."})]}),t.jsxs("div",{className:"planning-summary-form",children:[d.map((V,de)=>{const Z=I===V.id,we=K===V.id,pe=["task-detail-section","subtask-item",Z?"subtask-item-dragging":"",we?"subtask-item-drop-target":"",we&&E==="before"?"subtask-item-drop-before":"",we&&E==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:pe,"data-testid":`subtask-item-${de}`,draggable:c.type!=="creating",onDragStart:be(V.id),onDragEnd:ne,onDragOver:Ie(V.id),onDrop:Pe(V.id),onDragLeave:ce,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(Lc,{size:16}),t.jsx("strong",{children:V.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>le(de,de-1),disabled:c.type==="creating"||de===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(Mi,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>le(de,de+1),disabled:c.type==="creating"||de===d.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(cr,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>ae(V.id),disabled:c.type==="creating",children:[t.jsx(Jt,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:Te=>{G.current[de]=Te},value:V.title,onChange:Te=>_e(V.id,{title:Te.target.value}),onKeyDown:Te=>{Te.key==="Enter"&&(Te.preventDefault(),$e(de))},disabled:c.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:8,value:V.description,onChange:Te=>_e(V.id,{description:Te.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:V.suggestedSize,onChange:Te=>_e(V.id,{suggestedSize:Te.target.value}),disabled:c.type==="creating",children:[t.jsx("option",{value:"S",children:"S"}),t.jsx("option",{value:"M",children:"M"}),t.jsx("option",{value:"L",children:"L"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"planning-deps-list",children:[d.slice(0,de).filter(Te=>Te.id!==V.id).map(Te=>{const Qe=V.dependsOn.includes(Te.id);return t.jsxs("label",{className:`planning-dep-chip ${Qe?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:Qe,onChange:()=>{const Ee=Qe?V.dependsOn.filter(Re=>Re!==Te.id):[...V.dependsOn,Te.id];_e(V.id,{dependsOn:Ee})},disabled:c.type==="creating"}),t.jsx("span",{className:"planning-dep-id",children:Te.id}),t.jsx("span",{className:"planning-dep-title",children:Te.title||"Untitled"})]},Te.id)}),de===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),de>0&&d.slice(0,de).filter(Te=>Te.id!==V.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},V.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:Fe,disabled:c.type==="creating",children:[t.jsx(Xt,{size:16,className:"icon-mr-6"})," Add subtask"]}),Hm(d)&&t.jsx("div",{className:"form-error planning-error",children:"Dependencies contain a cycle. Remove circular references before creating tasks."})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsx("button",{className:"btn",onClick:()=>void Ye(),disabled:c.type==="creating",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:()=>void at(),disabled:c.type==="creating"||ee,children:c.type==="creating"?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]}),j&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(No,{size:16}),t.jsx("span",{children:ze?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),ze&&t.jsx("button",{type:"button",onClick:()=>{J()},disabled:W,className:"btn btn-primary session-lock-take-control",children:W?"Taking control...":"Take Control"})]})})]})]})}):null}const U_=5,B_=1e3,H_=45e3;function Kr(){return{scrollback:null,connected:null,data:[]}}function q_(e,n){const[s,i]=a.useState("disconnected"),r=a.useRef(0),o=a.useRef(e),l=a.useRef(n),c=o.current!==e||l.current!==n;c&&(o.current=e,l.current=n,r.current++);const u=a.useRef(null),d=a.useRef(0),m=a.useRef(null),h=a.useRef(null),g=a.useRef(!1),p=a.useRef(new Set),f=a.useRef(new Set),x=a.useRef(new Set),v=a.useRef(new Set),b=a.useRef(new Set),y=a.useRef(Kr()),S=a.useCallback(P=>{p.current.add(P);const E=y.current;return E.data.length>0&&(E.data.forEach(R=>P(R)),E.data=[]),()=>p.current.delete(P)},[]),k=a.useCallback(P=>(f.current.add(P),()=>f.current.delete(P)),[]),M=a.useCallback(P=>{x.current.add(P);const E=y.current;return E.connected&&(P(E.connected),E.connected=null),()=>x.current.delete(P)},[]),w=a.useCallback(P=>{v.current.add(P);const E=y.current;return E.scrollback&&(P(E.scrollback),E.scrollback=null),()=>v.current.delete(P)},[]),_=a.useCallback(P=>(b.current.add(P),()=>b.current.delete(P)),[]),N=a.useCallback(P=>{const E=u.current;E?.readyState===WebSocket.OPEN&&E.send(JSON.stringify({type:"input",data:P}))},[]),L=a.useCallback((P,E)=>{const R=u.current;R?.readyState===WebSocket.OPEN&&R.send(JSON.stringify({type:"resize",cols:P,rows:E}))},[]),T=a.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.current=null),u.current&&(u.current.onopen=null,u.current.onmessage=null,u.current.onclose=null,u.current.onerror=null,u.current.close(),u.current=null),y.current=Kr()},[]),I=a.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.current=null),u.current&&(g.current=!0,u.current.close(),u.current=null),y.current=Kr()},[]),z=a.useCallback(()=>{if(!e){i("disconnected");return}if(u.current?.readyState===WebSocket.OPEN)return;u.current&&(g.current=!0,u.current.close()),g.current=!1,i("connecting");const P=r.current;let R=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/terminal/ws?sessionId=${encodeURIComponent(e)}`;n&&(R+=`&projectId=${encodeURIComponent(n)}`);const B=new WebSocket(Ks(R));u.current=B,B.onopen=()=>{if(r.current!==P){B.close();return}y.current=Kr(),i("connected"),d.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{r.current===P&&B.readyState===WebSocket.OPEN&&B.send(JSON.stringify({type:"ping"}))},H_)},B.onmessage=G=>{if(r.current===P)try{const X=JSON.parse(G.data),C=y.current;switch(X.type){case"data":X.data&&(p.current.size===0&&C.data.push(X.data),p.current.forEach($=>$(X.data)));break;case"scrollback":X.data&&(C.scrollback=X.data,v.current.forEach($=>$(X.data)));break;case"connected":X.shell&&X.cwd&&(C.connected={shell:X.shell,cwd:X.cwd},x.current.forEach($=>$({shell:X.shell,cwd:X.cwd})));break;case"exit":X.exitCode!==void 0&&f.current.forEach($=>$(X.exitCode));break;case"ping":B.readyState===WebSocket.OPEN&&B.send(JSON.stringify({type:"pong"}));break;case"pong":break}}catch{}},B.onclose=G=>{if(r.current!==P)return;if(u.current=null,h.current&&(clearInterval(h.current),h.current=null),g.current){i("disconnected");return}if(G.code===4e3||G.code===4004){i("disconnected"),G.code===4004&&b.current.forEach($=>$());return}if(d.current++,d.current>U_){i("disconnected");return}const X=B_*Math.pow(2,d.current-1);i("reconnecting");const C=r.current;m.current=setTimeout(()=>{r.current===C&&(g.current||z())},Math.min(X,16e3))},B.onerror=()=>{}},[e,n]),K=a.useCallback(()=>{d.current=0,I(),z()},[I,z]);return a.useEffect(()=>(c&&(T(),d.current=0,i("disconnected")),e?z():i("disconnected"),I),[e,n,c,z,I,T]),{connectionStatus:s,sendInput:N,resize:L,onData:S,onExit:k,onConnect:M,onScrollback:w,reconnect:K,onSessionInvalid:_}}const If="kb-terminal-tabs",V_=15e3,W_=15e3;function qm(){return`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function Vm(e){if(typeof window>"u")return[];try{const n=zn(If,e);if(n)return JSON.parse(n)}catch{}return[]}function zl(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return n.includes("Failed to parse URL")||n.includes("Invalid URL")}function Wm(e,n,s){let i;const r=new Promise((o,l)=>{i=setTimeout(()=>l(new Error(`${s} timed out after ${n}ms`)),n)});return Promise.race([e,r]).finally(()=>clearTimeout(i))}function K_(e){const[n,s]=a.useState(()=>Vm(e)),[i,r]=a.useState(!1),[o,l]=a.useState(!0),[c,u]=a.useState(null),[d,m]=a.useState(0),h=a.useRef(0);a.useEffect(()=>{h.current+=1,s(Vm(e)),r(!1),l(!0),u(null)},[e]),a.useEffect(()=>{try{as(If,JSON.stringify(n),e)}catch{}},[e,n]),a.useEffect(()=>{let M=!1;const w=h.current;return(async()=>{if(!M)try{const N=await Wm(ey(e),V_,"listTerminalSessions");if(M||w!==h.current)return;const L=new Set(N.map(T=>T.id));l(!0),s(T=>{if(M||w!==h.current)return T;const z=T.map(E=>({...E,_verified:L.has(E.sessionId)})).filter(E=>E._verified);if(z.length===0)return[];const K=z.map(({_verified:E,...R})=>R);return K.find(E=>E.isActive)?K:K.map((E,R)=>({...E,isActive:R===0}))}),r(!0)}catch(N){if(M||w!==h.current)return;const L=zl(N);L||console.warn("Failed to validate terminal sessions with server:",N),l(!L),r(!0)}})(),()=>{M=!0}},[e]),a.useEffect(()=>{if(n.length===0&&i&&o){const M=h.current,w=setTimeout(()=>{Wm(Ar(void 0,void 0,void 0,e),W_,"createTerminalSession").then(_=>{if(M!==h.current)return;const N={id:qm(),sessionId:_.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};s(L=>L.length>0?L:[...L.map(I=>({...I,isActive:!1})),N]),u(null)}).catch(_=>{if(M!==h.current)return;zl(_)||console.error(_);const N=_ instanceof Error?_.message:typeof _=="string"?_:"Failed to create terminal session";u(N)})},0);return()=>clearTimeout(w)}},[i,o,n.length,d]);const g=a.useCallback(async()=>{const M=await Ar(void 0,void 0,void 0,e),w={id:qm(),sessionId:M.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};return s(_=>[..._.map(L=>({...L,isActive:!1})),w]),w},[n.length]),p=a.useCallback(async()=>g(),[g]),f=a.useCallback(M=>{s(w=>{const _=w.find(I=>I.id===M);if(!_)return w;Rd(_.sessionId,e).catch(I=>{console.warn(`Failed to kill terminal session ${_.sessionId}:`,I)});const N=w.findIndex(I=>I.id===M),L=_.isActive,T=w.filter(I=>I.id!==M);if(T.length===0)return[];if(L){const I=Math.min(N,T.length-1);return T.map((z,K)=>({...z,isActive:K===I}))}return T})},[]),x=a.useCallback(M=>{s(w=>{let _=!1;const N=w.map(L=>L.id===M?(_=!0,{...L,isActive:!0}):{...L,isActive:!1});return _?N:w})},[]),v=a.useCallback((M,w)=>{s(_=>_.map(N=>N.id===M?{...N,title:w}:N))},[]),b=a.useCallback(async()=>{s(_=>{const N=_.find(L=>L.isActive);return N&&Rd(N.sessionId,e).catch(L=>{console.warn(`Failed to kill old session ${N.sessionId}:`,L)}),_});const M=n.find(_=>_.isActive);if(!M)return;const w=await Ar(void 0,void 0,void 0,e);s(_=>_.map(N=>N.id===M.id?{...N,sessionId:w.sessionId}:N))},[n]),y=a.useCallback(async()=>{const M=n.find(w=>w.isActive);if(M)try{const w=await Ar(void 0,void 0,void 0,e);s(_=>_.map(N=>N.id===M.id?{...N,sessionId:w.sessionId}:N)),u(null)}catch(w){zl(w)||console.error(w);const _=w instanceof Error?w.message:typeof w=="string"?w:"Failed to create terminal session";u(_)}},[n]),S=n.find(M=>M.isActive)??null,k=a.useCallback(()=>{u(null),h.current+=1,m(M=>M+1)},[]);return{tabs:n,activeTab:S,isReady:i,bootstrapError:c,createTab:p,closeTab:f,setActiveTab:x,updateTabTitle:v,restartActiveTab:b,retryBootstrap:k,replaceActiveTabSession:y}}const G_=1e4,J_=[500,1500,3e3],$f="kb-terminal-font-size",Ka=14,Y_=8,Q_=32;function X_(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 Z_(e){return`\x1B${e}`}const eA=[{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 Ga(e){return Math.min(Q_,Math.max(Y_,e))}function tA(){if(typeof window>"u")return Ka;try{const e=window.localStorage.getItem($f);if(!e)return Ka;const n=Number.parseInt(e,10);return Number.isFinite(n)?Ga(n):Ka}catch{return Ka}}function nA(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 sA(e){return new Promise(n=>setTimeout(n,e))}async function iA(e,n=J_){let s;for(let i=0;i<=n.length;i+=1)try{return await e()}catch(r){if(!nA(r))throw r;s===void 0&&(s=r);const o=n[i];if(o===void 0)throw s??r;const l=r instanceof Error?r.message:String(r);console.warn(`[TerminalModal] Dynamic xterm import failed (attempt ${i+1}/${n.length+1}). Retrying in ${o}ms...`,l),await sA(o)}throw s??new Error("Dynamic import failed")}function Km(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}function aA(){if(typeof window>"u"||!window.visualViewport)return 0;const e=window.visualViewport,n=Math.max(0,window.innerHeight-e.offsetTop-e.height);if(n>0)return n;const i=rA()-e.offsetTop-e.height;return i>=30&&i>80?i:0}let Fl=null;function rA(){return Fl===null&&(Fl=window.innerHeight),Fl}function oA({isOpen:e,onClose:n,initialCommand:s,projectId:i}){const[r,o]=a.useState(null),[l,c]=a.useState(null),[u,d]=a.useState(!1),[m,h]=a.useState(null),[g,p]=a.useState(0),[f,x]=a.useState(0),[v,b]=a.useState(null),[y,S]=a.useState(()=>tA()),[k,M]=a.useState(!1),[w,_]=a.useState(null),N=a.useRef(null),L=a.useRef(null),T=a.useRef(!1);Gs(L,e,"fusion:terminal-modal-size");const I=a.useRef(null),z=a.useRef(null),K=a.useRef(!1),P=a.useRef(!1),E=a.useRef(null),R=a.useRef(()=>{}),B=a.useRef(null),G=a.useRef(0),X=a.useRef(y),C=a.useRef(null),$=a.useRef(i);G.current=f,X.current=y;const A=a.useCallback(Z=>{if(Z&&P.current!==Z)return;const we=z.current,pe=I.current,Te=E.current;if(!(!we||!pe)&&!(Z&&P.current!==Z))try{we.fit(),Te&&Te(pe.cols,pe.rows)}catch{}},[]);a.useEffect(()=>{e&&p(Z=>Z+1)},[e]),a.useEffect(()=>{if(!e||!Km())return;const Z=window.visualViewport;if(!Z)return;const we=()=>{const pe=aA();x(pe),b(Z.height),pe>0&&L.current?.scrollIntoView&&L.current.scrollIntoView({block:"end",behavior:"smooth"}),C.current!==null&&(cancelAnimationFrame(C.current),C.current=null);const Te=typeof P.current=="string"?P.current:void 0;C.current=requestAnimationFrame(()=>{C.current=null,A(Te)})};return we(),Z.addEventListener("resize",we),Z.addEventListener("scroll",we),()=>{Z.removeEventListener("resize",we),Z.removeEventListener("scroll",we),C.current!==null&&(cancelAnimationFrame(C.current),C.current=null),x(0),b(null)}},[A,e]),a.useEffect(()=>{if(!e)return;const Z=L.current;if(!Z||typeof ResizeObserver>"u")return;let we=null;const pe=new ResizeObserver(()=>{we!==null&&cancelAnimationFrame(we),we=requestAnimationFrame(()=>{we=null;const Te=typeof P.current=="string"?P.current:void 0;A(Te)})});return pe.observe(Z),()=>{pe.disconnect(),we!==null&&cancelAnimationFrame(we)}},[A,e]);const{tabs:j,activeTab:J,isReady:W,bootstrapError:oe,createTab:he,closeTab:se,setActiveTab:fe,updateTabTitle:U,restartActiveTab:Ne,retryBootstrap:ee,replaceActiveTabSession:ve}=K_(i),{connectionStatus:ue,sendInput:ye,resize:ie,onData:Me,onConnect:ze,onExit:Be,onScrollback:Je,reconnect:Ye,onSessionInvalid:Ge}=q_(J?.sessionId??null,i);E.current=ie,R.current=ye,a.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem($f,String(y))}catch{}},[y]);const it=a.useCallback(()=>{const Z=I.current;if(Z)try{z.current?.fit(),ie(Z.cols,Z.rows)}catch{}},[ie]);a.useEffect(()=>{if(!e||!W)return;const Z=J?.sessionId;if(!Z)return;const we=$.current!==i;if(we&&($.current=i),P.current===Z&&I.current&&!we)return;I.current&&(P.current!==Z||we)&&(I.current.dispose(),I.current=null,z.current=null,P.current=!1,B.current&&(window.removeEventListener("resize",B.current),B.current=null),d(!1),h(null));let pe=!0,Te;return(async()=>{const Ee=iA(()=>Promise.all([sn(()=>import("./vendor-xterm-DzcZoU0P.js").then(Se=>Se.x),__vite__mapDeps([0,1,2])),sn(()=>import("./addon-fit-C7jRorKK.js").then(Se=>Se.a),__vite__mapDeps([3,1])),sn(()=>import("./addon-web-links-CkJwd4cQ.js").then(Se=>Se.a),__vite__mapDeps([4,1]))])),Re=new Promise((Se,mt)=>{Te=setTimeout(()=>{mt(new Error("xterm initialization timed out"))},G_)});let Le,ct;try{const[{Terminal:Se},{FitAddon:mt},{WebLinksAddon:gt}]=await Promise.race([Ee,Re]);if(!pe||!N.current||I.current)return;Le=new Se({cursorBlink:!0,cursorStyle:"block",fontSize:X.current,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',theme:{background:"#1e1e1e",foreground:"#d4d4d4",cursor:"#d4d4d4",selectionBackground:"#264f78",black:"#1e1e1e",red:"#f48771",green:"#4ec9b0",yellow:"#dcdcaa",blue:"#569cd6",magenta:"#c586c0",cyan:"#9cdcfe",white:"#d4d4d4"},allowProposedApi:!0,scrollback:5e3}),ct=new mt,Le.loadAddon(ct);const wt=new gt;if(Le.loadAddon(wt),!Km())try{const{WebglAddon:Ct}=await sn(async()=>{const{WebglAddon:Ft}=await import("./addon-webgl-BjvOw43o.js").then(Ut=>Ut.a);return{WebglAddon:Ft}},__vite__mapDeps([5,1])),Rt=new Ct;Rt.onContextLoss(()=>{Rt.dispose()}),Le.loadAddon(Rt)}catch{}Le.open(N.current),Te&&clearTimeout(Te);const yt=N.current?.querySelector(".xterm-helper-textarea");if(yt&&yt.focus(),N.current)try{N.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}setTimeout(()=>{ct.fit();const Ct=N.current?.querySelector(".xterm-helper-textarea");Ct&&Ct.focus()},50),I.current=Le,z.current=ct,P.current=Z,G.current>0&&(C.current!==null&&(cancelAnimationFrame(C.current),C.current=null),C.current=requestAnimationFrame(()=>{C.current=null,A(Z)})),Le.onData(Ct=>{P.current===Z&&R.current(Ct)});const kt=()=>{if(P.current===Z&&z.current&&I.current)try{z.current.fit();const{cols:Ct,rows:Rt}=I.current;E.current?.(Ct,Rt)}catch{}};window.addEventListener("resize",kt),B.current&&window.removeEventListener("resize",B.current),B.current=kt,d(!0),h(null)}catch(Se){if(Te&&clearTimeout(Te),!pe)return;const mt=Se instanceof Error?Se.message:"xterm initialization failed";h(mt)}})(),()=>{pe=!1,Te&&clearTimeout(Te)}},[A,e,W,J?.sessionId,i]),a.useEffect(()=>{e||(I.current&&(I.current.dispose(),I.current=null),z.current=null,P.current=!1,B.current&&(window.removeEventListener("resize",B.current),B.current=null),d(!1),h(null),K.current=!1,o(null),c(null),M(!1),_(null))},[e]),a.useEffect(()=>{if(!u||!I.current||!J)return;const Z=J.sessionId,we=Re=>{P.current===Z&&I.current?.write(Re)},pe=Me(Re=>{we(Re)}),Te=Je(Re=>{we(Re)}),Qe=ze(Re=>{U(J.id,Re.shell.split("/").pop()||Re.shell)}),Ee=Be(Re=>{P.current===Z&&(c(Re),I.current?.write(`\r
643
+ \x1B[33m[Process exited with code ${Re}]\x1B[0m\r
644
+ `))});return()=>{pe(),Te(),Qe(),Ee()}},[u,J?.sessionId,J?.id,J,ue,Me,Je,ze,Be,U]),a.useEffect(()=>{ue==="connected"&&s&&K.current!==s&&J&&(K.current=s,setTimeout(()=>{ye(s+`
645
+ `)},500))},[ue,s,ye,J,g]),a.useEffect(()=>{if(!u||!I.current)return;I.current.options.fontSize=y,C.current!==null&&(cancelAnimationFrame(C.current),C.current=null);const Z=requestAnimationFrame(()=>{C.current=null,it()});return C.current=Z,()=>{C.current===Z&&(cancelAnimationFrame(Z),C.current=null)}},[y,u,it]),a.useEffect(()=>{if(!e)return;const Z=we=>{if(!(!we.ctrlKey&&!we.metaKey)){if(we.code==="Equal"||we.code==="NumpadAdd"){we.preventDefault(),S(pe=>Ga(pe+1));return}if(we.code==="Minus"||we.code==="NumpadSubtract"){we.preventDefault(),S(pe=>Ga(pe-1));return}if(we.code==="Digit0"||we.code==="Numpad0"){we.preventDefault(),S(Ka);return}}};return window.addEventListener("keydown",Z),()=>window.removeEventListener("keydown",Z)},[e,it]),a.useEffect(()=>{if(!e)return;const Z=we=>{we.key==="Escape"&&n()};return document.addEventListener("keydown",Z),()=>document.removeEventListener("keydown",Z)},[e,n]),a.useEffect(()=>{ue==="connected"&&I.current&&setTimeout(()=>{if(!I.current||!N.current)return;const Z=N.current.querySelector(".xterm-helper-textarea");Z&&Z.focus();try{N.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[ue]);const _e=a.useCallback(()=>{if(!N.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;I.current?.focus();const we=N.current.querySelector(".xterm-helper-textarea");if(!we)return;we.autocapitalize="off",we.autocomplete="off",we.autocorrect="off",we.spellcheck=!1,we.setAttribute("inputmode","text");try{we.focus({preventScroll:!0})}catch{we.focus()}const pe=we.value.length;we.setSelectionRange(pe,pe)},[]);a.useEffect(()=>Ge(()=>{I.current?.clear(),c(null),K.current=!1,I.current&&(I.current.dispose(),I.current=null),z.current=null,P.current=!1,B.current&&(window.removeEventListener("resize",B.current),B.current=null),d(!1),h(null),ve().catch(we=>{console.error("Failed to replace invalid terminal session:",we)})}),[Ge,ve]);const Fe=a.useCallback(Z=>{Z.target===Z.currentTarget&&(T.current=!0)},[]),ae=a.useCallback(Z=>{T.current&&Z.target===Z.currentTarget&&n(),T.current=!1},[n]),be=a.useCallback(()=>{I.current?.clear()},[]),ne=a.useCallback(async()=>{I.current?.clear(),c(null),K.current=!1;try{await Ne()}catch(Z){o(je(Z)||"Failed to restart terminal session")}},[Ne]),Ie=a.useCallback(()=>{I.current&&(I.current.dispose(),I.current=null),z.current=null,P.current=!1,B.current&&(window.removeEventListener("resize",B.current),B.current=null),h(null),d(!1)},[]),Pe=a.useCallback(()=>{window.location.reload()},[]),ce=a.useCallback(()=>{S(Z=>Ga(Z+1))},[]),le=a.useCallback(()=>{S(Z=>Ga(Z-1))},[]),$e=a.useCallback(Z=>{_(we=>we===Z?null:Z)},[]),at=a.useCallback(Z=>{if(w==="ctrl"){ye(X_(Z)),_(null);return}if(w==="alt"){ye(Z_(Z)),_(null);return}ye(Z)},[ye,w]),tt=a.useCallback(Z=>{ye(Z),_(null)},[ye]);if(!e)return null;const V=()=>{switch(ue){case"connected":return t.jsx("span",{className:"terminal-status connected",title:"Connected"});case"connecting":case"reconnecting":return t.jsx("span",{className:"terminal-status connecting",title:"Connecting..."});case"disconnected":return t.jsx("span",{className:"terminal-status disconnected",title:"Disconnected"});default:return null}},de=!W||!J&&!oe;return t.jsx("div",{className:"modal-overlay open",onMouseDown:Fe,onMouseUp:ae,role:"dialog","aria-modal":"true","data-testid":"terminal-modal-overlay",style:f>0?{"--overlay-padding-top":"0px"}:void 0,children:t.jsxs("div",{ref:L,className:"modal terminal-modal","data-testid":"terminal-modal",style:f>0?{"--keyboard-overlap":`${f}px`,"--vv-height":v?`${v}px`:void 0}:void 0,children:[t.jsxs("div",{className:"terminal-header",children:[t.jsxs("div",{className:"terminal-tabs","data-testid":"terminal-tabs",children:[j.map(Z=>t.jsxs("div",{className:`terminal-tab ${Z.isActive?"terminal-tab--active":""}`,onClick:()=>fe(Z.id),title:Z.title,role:"tab","aria-selected":Z.isActive,children:[t.jsx("span",{className:"terminal-tab-label",children:Z.title}),j.length>1&&t.jsx("button",{className:"terminal-tab-close",onClick:we=>{we.stopPropagation(),se(Z.id)},title:"Close tab",children:"×"})]},Z.id)),t.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:he,title:"New terminal",children:"+"})]}),t.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[t.jsx(ei,{size:16}),V()]}),t.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[ue==="disconnected"&&J&&t.jsxs("button",{className:"terminal-reconnect-btn",onClick:Ye,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[t.jsx(wn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),l!==null&&t.jsxs("button",{className:"terminal-restart-btn",onClick:ne,title:"New Session","data-testid":"terminal-restart-btn",children:[t.jsx(wn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:be,"data-testid":"terminal-clear-btn",title:"Clear terminal",children:[t.jsx(Jt,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Clear"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:()=>M(Z=>!Z),"data-testid":"terminal-shortcut-toggle",title:"Shortcuts","aria-pressed":k,children:[t.jsx(Rx,{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(zt,{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:[de&&!oe&&t.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[t.jsx("div",{className:"terminal-spinner"}),t.jsx("span",{children:"Starting terminal..."})]}),oe&&!J&&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: ",oe]}),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(wn,{size:14}),"Retry"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Pe,"data-testid":"terminal-bootstrap-refresh-btn",children:[t.jsx(wn,{size:14}),"Refresh page"]})]})]})}),m&&J&&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:Ie,"data-testid":"terminal-reinit-btn",children:[t.jsx(wn,{size:14}),"Reinitialize"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Pe,"data-testid":"terminal-xterm-refresh-btn",children:[t.jsx(wn,{size:14}),"Refresh page"]})]})]})}),t.jsx("div",{ref:N,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:_e,onTouchStart:_e},J?.sessionId)]}),k&&t.jsxs("div",{className:"terminal-shortcut-panel","data-testid":"terminal-shortcut-panel",children:[t.jsxs("div",{className:"terminal-shortcut-modifier-row",children:[t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${w==="ctrl"?"is-active":""}`,"data-testid":"terminal-modifier-ctrl",onClick:()=>$e("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:()=>$e("alt"),"aria-pressed":w==="alt",children:"Alt"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>tt("\x1B"),children:"ESC"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>tt(" "),children:"Tab"})]}),eA.map(Z=>t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>at(Z.key),title:Z.description,children:Z.label},Z.label))]}),t.jsxs("div",{className:"terminal-status-bar","data-testid":"terminal-status-bar",children:[t.jsxs("span",{className:`terminal-connection-status ${ue}`,children:[ue==="connected"&&"Connected",ue==="connecting"&&"Connecting...",ue==="reconnecting"&&"Reconnecting...",ue==="disconnected"&&"Disconnected"]}),l!==null&&t.jsxs("span",{className:"terminal-exit-code","data-testid":"terminal-exit-code",children:["Exit: ",l]}),t.jsxs("span",{className:"terminal-font-size-controls",children:[t.jsx("button",{type:"button",className:"terminal-font-size-btn",onClick:le,"data-testid":"terminal-font-size-decrease","aria-label":"Decrease terminal font size",children:t.jsx(Yx,{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:ce,"data-testid":"terminal-font-size-increase","aria-label":"Increase terminal font size",children:t.jsx(Xt,{size:14})})]}),t.jsx("span",{className:"terminal-shortcuts",children:"Ctrl++/- zoom • ⌨ Shortcuts panel • Esc close"})]})]})})}const La={name:"",command:""};function Gm(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function lA(e,n=60){return e.length<=n?e:e.slice(0,n-3)+"..."}function cA({isOpen:e,onClose:n,addToast:s,projectId:i,onRunScript:r}){const[o,l]=a.useState({}),[c,u]=a.useState(!0),[d,m]=a.useState(!1),[h,g]=a.useState(null),[p,f]=a.useState(La),[x,v]=a.useState(!1),[b,y]=a.useState(null),[S,k]=a.useState(null),M=fi(n),w=a.useCallback(async()=>{try{u(!0);const R=await ar(i);l(R)}catch(R){s(je(R)||"Failed to load scripts","error")}finally{u(!1)}},[s,i]);a.useEffect(()=>{e&&w()},[e,w]);const _=a.useCallback(()=>{m(!0),g(null),f(La),k(null)},[]),N=a.useCallback((R,B)=>{g(R),m(!1),f({name:R,command:B}),k(null)},[]),L=a.useCallback(()=>{g(null),m(!1),f(La),k(null)},[]),T=a.useCallback(R=>{f(B=>({...B,name:R})),R&&!Gm(R)?k("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):k(null)},[]),I=a.useCallback(async()=>{const R=p.name.trim(),B=p.command.trim();if(!R){s("Script name is required","error");return}if(!Gm(R)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!B){s("Script command is required","error");return}v(!0);try{await ek(R,B,i),s(h?"Script updated":"Script created","success"),g(null),m(!1),f(La),k(null),await w()}catch(G){const X=je(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,i]),z=a.useCallback(async R=>{try{await tk(R,i),s("Script deleted","success"),y(null),h===R&&(g(null),f(La)),await w()}catch(B){s(je(B)||"Failed to delete script","error")}},[h,s,w,i]),K=a.useCallback((R,B)=>{r&&r(R,B)},[r]);if(!e)return null;const P=d||h!==null,E=Object.entries(o).map(([R,B])=>({name:R,command:B}));return t.jsx("div",{className:"modal-overlay open",...M,"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(rt,{size:24,className:"spin",style:{margin:"0 auto 8px",display:"block"}}),"Loading scripts..."]}):P?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:R=>T(R.target.value),placeholder:"e.g., build, test, lint",disabled:x||h!==null,"data-testid":"script-name-input",style:{width:"100%",borderColor:S?"var(--color-error)":void 0}}),S&&t.jsx("div",{style:{fontSize:"12px",color:"var(--color-error)",marginTop:"4px"},"data-testid":"script-name-error",children:S}),t.jsx("div",{style:{fontSize:"11px",color:"var(--text-muted)",marginTop:"4px"},children:"Letters, numbers, hyphens, and underscores only"})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"script-command",style:{display:"block",marginBottom:"4px",fontSize:"13px",fontWeight:500,color:"var(--text)"},children:"Command"}),t.jsx("textarea",{id:"script-command",className:"input",value:p.command,onChange:R=>f(B=>({...B,command:R.target.value})),placeholder:"e.g., npm run build",rows:3,disabled:x,"data-testid":"script-command-input",style:{width:"100%",resize:"vertical",fontFamily:"monospace"}})]}),t.jsxs("div",{className:"scripts-modal-form-actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end"},children:[t.jsx("button",{className:"btn btn-secondary",onClick:L,disabled:x,"data-testid":"script-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:I,disabled:x||!!S,"data-testid":"script-save-btn",children:x?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:14,className:"spin",style:{marginRight:"6px"}}),"Saving..."]}):h?"Update":"Create"})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"scripts-modal-list-header",style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[t.jsx("div",{style:{fontSize:"13px",color:"var(--text-muted)"},children:E.length===0?"No scripts defined":`${E.length} script${E.length===1?"":"s"}`}),t.jsxs("button",{className:"btn btn-primary",onClick:_,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx(Xt,{size:14}),"Add Script"]})]}),E.length===0?t.jsxs("div",{style:{textAlign:"center",padding:"32px",color:"var(--text-muted)",fontSize:"14px",border:"1px dashed var(--border)",borderRadius:"8px"},"data-testid":"empty-state",children:[t.jsx(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:E.map(R=>t.jsx("div",{className:"script-card","data-testid":`script-${R.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:R.name})}),t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:R.command,children:lA(R.command)})]}),t.jsxs("div",{className:"script-card-actions",style:{display:"flex",gap:"4px",marginLeft:"8px",flexShrink:0},children:[t.jsxs("button",{className:"btn btn-secondary",onClick:()=>K(R.name,R.command),title:"Run script","aria-label":`Run ${R.name}`,"data-testid":`run-script-${R.name}`,style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 10px",fontSize:"12px"},children:[t.jsx(fn,{size:12}),"Run"]}),t.jsx("button",{className:"btn-icon",onClick:()=>N(R.name,R.command),title:"Edit","aria-label":`Edit ${R.name}`,"data-testid":`edit-script-${R.name}`,children:t.jsx(Xt,{size:14,style:{transform:"rotate(45deg)"}})}),b===R.name?t.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[t.jsx("button",{className:"btn-icon",onClick:()=>z(R.name),title:"Confirm delete","aria-label":`Confirm delete ${R.name}`,"data-testid":`confirm-delete-script-${R.name}`,style:{color:"var(--color-error)"},children:t.jsx(Jt,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>y(null),title:"Cancel delete","aria-label":"Cancel delete","data-testid":`cancel-delete-script-${R.name}`,children:t.jsx(zt,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>y(R.name),title:"Delete","aria-label":`Delete ${R.name}`,"data-testid":`delete-script-${R.name}`,children:t.jsx(Jt,{size:14})})]})]})},R.name))})]})})]})})}function dA(e,n,s){const[i,r]=a.useState([]),[o,l]=a.useState("."),[c,u]=a.useState(!1),[d,m]=a.useState(null),[h,g]=a.useState(0),p=a.useCallback(()=>{g(x=>x+1)},[]),f=a.useCallback(x=>{l(x),m(null)},[]);return a.useEffect(()=>{l("."),m(null),r([])},[e]),a.useEffect(()=>{if(!n||!e)return;let x=!1;async function v(){u(!0),m(null);try{const b=await by(e,o==="."?void 0:o,s);x||r(b.entries)}catch(b){x||(m(je(b)||"Failed to load files"),r([]))}finally{x||u(!1)}}return v(),()=>{x=!0}},[e,o,n,h,s]),{entries:i,currentPath:o,setPath:f,loading:c,error:d,refresh:p}}function uA(e,n,s,i){const[r,o]=a.useState(""),[l,c]=a.useState(""),[u,d]=a.useState(null),[m,h]=a.useState(!1),[g,p]=a.useState(!1),[f,x]=a.useState(null),v=a.useCallback(S=>{o(S),x(null)},[]);a.useEffect(()=>{if(!e||!n){o(""),c(""),d(null),x(null);return}let S=!1;async function k(){h(!0),x(null);try{const M=await vy(e,n,i);S||(o(M.content),c(M.content),d(M.mtime))}catch(M){S||(x(je(M)||"Failed to load file"),o(""),c(""),d(null))}finally{S||h(!1)}}return k(),()=>{S=!0}},[e,n,s,i]);const b=r!==l,y=a.useCallback(async()=>{if(!(!e||!n||!b)){p(!0),x(null);try{const S=await yy(e,n,r,i);c(r),d(S.mtime)}catch(S){throw x(je(S)||"Failed to save file"),S}finally{p(!1)}}},[e,n,r,b,i]);return{content:r,setContent:v,originalContent:l,loading:m,saving:g,error:f,save:y,hasChanges:b,mtime:u}}const mA=1e4;function hA(e){const s=e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||e||"Project Root"}function pA(e){return{id:e.id,label:e.id,title:e.title,worktree:e.worktree,kind:"task"}}function fA(e){const[n,s]=a.useState("Project Root"),[i,r]=a.useState([]),[o,l]=a.useState(!0),[c,u]=a.useState(null);return a.useEffect(()=>{let d=!1;async function m(){try{const g=await xy(e);if(d)return;s(hA(g.project)),r(g.tasks.map(pA)),u(null)}catch(g){d||u(je(g)||"Failed to load workspaces")}finally{d||l(!1)}}m();const h=window.setInterval(()=>{m()},mA);return()=>{d=!0,window.clearInterval(h)}},[e]),{projectName:n,workspaces:i,loading:o,error:c}}function gA(e){return e===void 0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function xA(e){return e?new Date(e).toLocaleDateString():""}function Jm(e,n){return e==="."?n:`${e}/${n}`}const za={visible:!1,x:0,y:0,entry:null,entryFullPath:""},Ol={type:null,entry:null,entryFullPath:""},bA=200,vA=500,Ym=10;function yA({x:e,y:n,entry:s,onAction:i,onClose:r}){const o=a.useRef(null),[l,c]=a.useState({x:e,y:n});a.useEffect(()=>{const m=o.current;if(!m)return;const h=m.getBoundingClientRect(),g=window.visualViewport,p=g?.width&&g.width>0?g.width:window.innerWidth,f=g?.height&&g.height>0?g.height:window.innerHeight,x=g?.offsetLeft??0,v=g?.offsetTop??0,b=8;let y=e-x,S=n-v;y+h.width>p-b&&(y=p-b-h.width),S+h.height>f-b&&(S=f-b-h.height),y<b&&(y=b),S<b&&(S=b),c({x:y+x,y:S+v})},[e,n]),a.useEffect(()=>{const m=h=>{h.key==="Escape"&&r()};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[r]);const u=s.type==="directory",d=[{id:"copy",label:"Copy",icon:Ai,disabled:!1},{id:"move",label:"Move",icon:Zx,disabled:!1},{id:"rename",label:"Rename",icon:Qn,disabled:!1},...u?[{id:"download-zip",label:"Download as ZIP",icon:vo,disabled:!1}]:[{id:"download",label:"Download",icon:Vg,disabled:!1}],{id:"divider",label:"",icon:Ai,disabled:!0},{id:"delete",label:"Delete",icon:Jt,disabled:!1}];return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsx("div",{ref:o,className:"file-browser-context-menu",role:"menu","aria-label":"File operations",style:{left:l.x,top:l.y},onClick:m=>m.stopPropagation(),children:d.map(m=>m.id==="divider"?t.jsx("div",{className:"file-browser-context-menu__divider",role:"separator"},"divider"):t.jsxs("button",{role:"menuitem",className:`file-browser-context-menu__item ${m.disabled?"file-browser-context-menu__disabled":""} ${m.id==="delete"?"file-browser-context-menu__item--danger":""}`,disabled:m.disabled,onClick:()=>i(m.id),children:[t.jsx(m.icon,{size:14,className:"file-browser-context-menu__item-icon"}),t.jsx("span",{children:m.label})]},m.id))})})}function kA({type:e,entry:n,entryFullPath:s,onConfirm:i,onCancel:r,loading:o,error:l}){const c=a.useRef(null),u=e==="rename"?n.name:"",[d,m]=a.useState(u);a.useEffect(()=>{setTimeout(()=>c.current?.focus(),50)},[]),a.useEffect(()=>{if(e==="rename"&&c.current){const f=n.name.lastIndexOf(".");f>0?c.current.setSelectionRange(0,f):c.current.select()}},[e,n.name]);const h=f=>{f.key==="Enter"&&d.trim()&&i(d.trim()),f.key==="Escape"&&r()};if(e==="delete")return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsxs("div",{className:"file-browser-dialog",onClick:f=>f.stopPropagation(),children:[t.jsxs("div",{className:"file-browser-dialog-title",children:["Delete ",n.type==="directory"?"Folder":"File"]}),t.jsxs("div",{className:"file-browser-dialog-message",children:["Are you sure you want to delete ",t.jsx("strong",{children:n.name}),"?",n.type==="directory"&&" This will delete all contents recursively."]}),l&&t.jsx("div",{className:"file-browser-dialog-error",children:l}),t.jsxs("div",{className:"file-browser-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:r,disabled:o,children:"Cancel"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>i(""),disabled:o,children:o?"Deleting...":"Delete"})]})]})});const p={copy:{title:"Copy",placeholder:"Destination path",confirm:"Copy"},move:{title:"Move",placeholder:"Destination path",confirm:"Move"},rename:{title:"Rename",placeholder:"New name",confirm:"Rename"}}[e];return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsxs("div",{className:"file-browser-dialog",onClick:f=>f.stopPropagation(),children:[t.jsx("div",{className:"file-browser-dialog-title",children:p.title}),t.jsx("div",{className:"file-browser-dialog-info",children:e==="rename"?n.name:s}),t.jsx("input",{ref:c,className:"file-browser-dialog-input",type:"text",value:d,onChange:f=>m(f.target.value),placeholder:p.placeholder,onKeyDown:h,disabled:o}),l&&t.jsx("div",{className:"file-browser-dialog-error",children:l}),t.jsxs("div",{className:"file-browser-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:r,disabled:o,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>i(d.trim()),disabled:o||!d.trim(),children:o?`${p.confirm}ing...`:p.confirm})]})]})})}function jA({entries:e,currentPath:n,onSelectFile:s,onNavigate:i,loading:r,error:o,onRetry:l,workspace:c,onRefresh:u,projectId:d}){const[m,h]=a.useState(za),[g,p]=a.useState(Ol),[f,x]=a.useState(!1),[v,b]=a.useState(null),[y,S]=a.useState(!1),[k,M]=a.useState(null),w=a.useRef(null),_=a.useRef(null),N=a.useRef(null),L=a.useRef(!1),T=a.useCallback(()=>{w.current!==null&&(window.clearTimeout(w.current),w.current=null),_.current!==null&&(window.clearTimeout(_.current),_.current=null)},[]),I=a.useCallback(()=>{T(),N.current=null,S(!1),M(null)},[T]);a.useEffect(()=>()=>{T()},[T]);const z=a.useCallback(($,A,j,J)=>{h({visible:!0,x:$,y:A,entry:j,entryFullPath:J})},[]),K=a.useCallback(($,A,j)=>{if($.touches.length!==1)return;const J=$.touches[0];J&&(I(),N.current={x:J.clientX,y:J.clientY},_.current=window.setTimeout(()=>{S(!0),M(j)},bA),w.current=window.setTimeout(()=>{const W=N.current;W&&(L.current=!0,S(!1),M(null),T(),z(W.x,W.y,A,j))},vA))},[I,T,z]),P=a.useCallback($=>{const A=N.current,j=$.touches[0];!A||!j||(Math.abs(j.clientX-A.x)>Ym||Math.abs(j.clientY-A.y)>Ym)&&I()},[I]),E=a.useCallback(()=>{I()},[I]);a.useEffect(()=>{if(!m.visible)return;const $=document.querySelector(".file-browser-list"),A=()=>{L.current=!1,I(),h(za)};return $?.addEventListener("scroll",A),()=>$?.removeEventListener("scroll",A)},[I,m.visible]),a.useEffect(()=>{if(!m.visible)return;const $=A=>{A.key==="Escape"&&(L.current=!1,h(za))};return document.addEventListener("keydown",$),()=>document.removeEventListener("keydown",$)},[m.visible]);const R=a.useCallback(($,A)=>{$.preventDefault(),$.stopPropagation(),I(),L.current=!1,z($.clientX,$.clientY,A,Jm(n,A.name))},[I,n,z]),B=a.useCallback($=>{if(!m.entry)return;L.current=!1;const A=m.entry,j=m.entryFullPath;if(h(za),$==="download"){if(!c)return;const J=Kh(c,j,d);window.open(Ks(J),"_blank");return}if($==="download-zip"){if(!c)return;const J=Cy(c,j,d);window.open(Ks(J),"_blank");return}p({type:$,entry:A,entryFullPath:j}),b(null)},[m,c,d]),G=a.useCallback(async $=>{if(!(!g.type||!g.entry||!c)){x(!0),b(null);try{switch(g.type){case"copy":await jy(c,g.entryFullPath,$,d);break;case"move":await wy(c,g.entryFullPath,$,d);break;case"rename":await Sy(c,g.entryFullPath,$,d);break;case"delete":await Ny(c,g.entryFullPath,d);break}p(Ol),u?.()}catch(A){b(je(A)||"Operation failed")}finally{x(!1)}}},[g,c,u,d]),X=a.useCallback(()=>{p(Ol),b(null)},[]),C=a.useCallback(($,A)=>{if(L.current){L.current=!1;return}m.visible||($.type==="directory"?i(A):s(A))},[m.visible,i,s]);return r?t.jsxs("div",{className:"file-browser-loading",children:[t.jsx(rt,{className:"spin",size:24}),t.jsx("span",{children:"Loading files..."})]}):o?t.jsxs("div",{className:"file-browser-error",children:[t.jsxs("p",{children:["Error: ",o]}),l&&t.jsx("button",{className:"btn btn-sm",onClick:l,children:"Retry"})]}):t.jsxs("div",{className:"file-browser",children:[t.jsxs("div",{className:"file-browser-header",children:[n!=="."&&t.jsxs("button",{className:"file-browser-up",onClick:()=>{const $=n.split("/").filter(Boolean);$.pop(),i($.length===0?".":$.join("/"))},children:[t.jsx(mn,{size:16,style:{transform:"rotate(-90deg)"}}),"Up one level"]}),t.jsx("span",{className:"file-browser-path",children:n==="."?"Root":n})]}),t.jsx("div",{className:"file-browser-list",children:e.length===0?t.jsx("div",{className:"file-browser-empty",children:"(empty directory)"}):e.map($=>{const A=Jm(n,$.name),j=y&&k===A;return t.jsxs("div",{className:`file-node file-node--${$.type} ${j?"file-node--long-pressing":""}`,onClick:()=>C($,A),onContextMenu:J=>R(J,$),onTouchStart:J=>K(J,$,A),onTouchMove:P,onTouchEnd:E,onTouchCancel:E,children:[t.jsx("div",{className:"file-node-icon",children:$.type==="directory"?t.jsx(Dn,{size:16}):t.jsx(Ih,{size:16})}),t.jsx("div",{className:"file-node-name",children:$.name}),$.type==="file"&&$.size!==void 0&&t.jsx("div",{className:"file-node-size",children:gA($.size)}),$.mtime&&t.jsx("div",{className:"file-node-time",children:xA($.mtime)})]},$.name)})}),m.visible&&m.entry&&t.jsx(yA,{x:m.x,y:m.y,entry:m.entry,onAction:B,onClose:()=>{L.current=!1,h(za)}}),g.type&&g.entry&&t.jsx(kA,{type:g.type,entry:g.entry,entryFullPath:g.entryFullPath,onConfirm:G,onCancel:X,loading:f,error:v})]})}function wA(e){if(!e)return!1;const n=e.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function NA({content:e,onChange:n,readOnly:s,filePath:i}){const[r,o]=a.useState(!1),[l,c]=a.useState(!0),u=wA(i),d=u&&(s?!0:r),m=a.useCallback(()=>{o(!1)},[]),h=a.useCallback(()=>{o(!0)},[]),g=a.useCallback(()=>{c(p=>!p)},[]);return t.jsxs("div",{className:"file-editor-container",children:[u?t.jsxs("div",{className:"file-editor-toolbar",children:[t.jsxs("div",{className:"file-editor-mode-toggle",children:[!s&&t.jsxs("button",{className:`btn btn-sm ${d?"":"btn-primary"}`,onClick:m,disabled:!d,"aria-label":"Edit mode",children:[t.jsx(Ph,{size:14}),"Edit"]}),t.jsxs("button",{className:`btn btn-sm ${d?"btn-primary":""}`,onClick:h,disabled:d,"aria-label":"Preview mode",children:[t.jsx(sa,{size:14}),"Preview"]})]}),!s&&t.jsx("button",{className:`btn btn-sm ${l?"btn-primary":""}`,onClick:g,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(so,{size:14})})]}):!s&&t.jsxs("div",{className:"file-editor-toolbar",children:[t.jsx("div",{className:"file-editor-mode-toggle"}),t.jsx("button",{className:`btn btn-sm ${l?"btn-primary":""}`,onClick:g,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(so,{size:14})})]}),d?t.jsx("div",{className:"file-editor-preview markdown-body",children:t.jsx(si,{remarkPlugins:[ii],children:e})}):t.jsx("textarea",{className:`file-editor-textarea ${l?"file-editor-textarea--wrap":""}`,value:e,onChange:p=>n(p.target.value),readOnly:s,spellCheck:!1,"aria-label":i?`Editor for ${i}`:"File editor"})]})}function SA(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function CA({currentWorkspace:e,projectName:n,workspaces:s,onSelect:i}){const[r,o]=a.useState(!1),l=a.useMemo(()=>e==="project"?n||"Project Root":s.find(u=>u.id===e)?.label??e,[e,n,s]);return t.jsxs("div",{className:"workspace-selector",children:[t.jsxs("button",{type:"button",className:"workspace-selector-trigger",onClick:()=>o(c=>!c),"aria-haspopup":"listbox","aria-expanded":r,children:[e==="project"?t.jsx(jd,{size:14}):t.jsx(sc,{size:14}),t.jsx("span",{className:"workspace-selector-trigger-label",children:l}),t.jsx(qt,{size:14,className:`workspace-selector-trigger-icon${r?" open":""}`})]}),r&&t.jsxs("div",{className:"workspace-selector-menu",role:"listbox","aria-label":"Select workspace",children:[t.jsxs("button",{type:"button",className:`workspace-selector-option${e==="project"?" active":""}`,onClick:()=>{i("project"),o(!1)},children:[t.jsxs("div",{className:"workspace-selector-option-main",children:[t.jsx(jd,{size:14}),t.jsx("span",{children:"Project Root"})]}),t.jsx("span",{className:"workspace-selector-option-meta",children:n})]}),s.length>0&&t.jsxs("div",{className:"workspace-selector-group",children:[t.jsx("div",{className:"workspace-selector-group-label",children:"Task Worktrees"}),s.map(c=>t.jsxs("button",{type:"button",className:`workspace-selector-option${e===c.id?" active":""}`,onClick:()=>{i(c.id),o(!1)},children:[t.jsxs("div",{className:"workspace-selector-option-main",children:[t.jsx(sc,{size:14}),t.jsx("span",{children:c.id})]}),c.title&&t.jsx("span",{className:"workspace-selector-option-meta",title:c.title,children:SA(c.title)})]},c.id))]})]})]})}const EA=768,Df=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),MA=new Set([...Df,".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 Qm(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return MA.has(n)}function _A(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return Df.has(n)}function AA({initialWorkspace:e="project",onClose:n,onWorkspaceChange:s,projectId:i}){const{projectName:r,workspaces:o}=fA(i),l=a.useRef(null);Gs(l,!0,"fusion:files-modal-size");const c=fi(n),[u,d]=a.useState(e),[m,h]=a.useState(null),[g,p]=a.useState(!1),[f,x]=a.useState("list"),{entries:v,currentPath:b,setPath:y,loading:S,error:k,refresh:M}=dA(u,!0,i),{content:w,setContent:_,originalContent:N,loading:L,saving:T,error:I,save:z,hasChanges:K,mtime:P}=uA(u,m,!0,i);a.useEffect(()=>{d(e)},[e]),a.useEffect(()=>{const j=()=>{p(window.innerWidth<=EA)};return j(),window.addEventListener("resize",j),()=>window.removeEventListener("resize",j)},[]),a.useEffect(()=>{m||x("list")},[m]),a.useEffect(()=>{const j=J=>{J.key==="Escape"&&n(),(J.metaKey||J.ctrlKey)&&J.key==="s"&&(J.preventDefault(),K&&!T&&z())};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[n,K,T,z]);const E=a.useCallback(j=>{h(j),g&&x("editor")},[g]),R=a.useCallback(()=>{x("list")},[]),B=a.useCallback(()=>{_(N)},[N,_]),G=a.useCallback(j=>{d(j),h(null),x("list"),s?.(j)},[s]),C=`Files — ${a.useMemo(()=>u==="project"?"Project":o.find(j=>j.id===u)?.id??u,[u,o])}`,$=a.useMemo(()=>!m||!_A(m)?null:Kh(u,m,i),[m,u,i]),A=j=>{const J=new Blob([j]).size;return J<1024?`${J} B`:`${(J/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(Dn,{size:18}),t.jsx("span",{children:C}),m&&t.jsx("span",{className:"file-browser-header-path",children:m})]}),t.jsxs("div",{className:"file-browser-header-actions",children:[t.jsx(CA,{currentWorkspace:u,projectName:r,workspaces:o,onSelect:G}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(zt,{size:20})})]})]}),t.jsxs("div",{className:"file-browser-body",children:[t.jsx("div",{className:`file-browser-sidebar ${g?"mobile":""} ${f==="list"?"active":""}`,children:t.jsx(jA,{entries:v,currentPath:b,onSelectFile:E,onNavigate:y,loading:S,error:k,onRetry:M,workspace:u,onRefresh:M,projectId:i})}),t.jsx("div",{className:`file-browser-content ${g?"mobile":""} ${f==="editor"?"active":""}`,children:m?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"file-browser-toolbar",children:[t.jsxs("div",{className:"file-browser-file-info",children:[g&&f==="editor"&&t.jsxs("button",{className:"file-browser-back-button",onClick:R,"aria-label":"Back to file list",children:[t.jsx(ga,{size:16}),t.jsx("span",{children:"Back"})]}),m,Qm(m)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(dx,{size:12}),"Binary file — read only"]}),P&&t.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date(P).toLocaleString()]}),L&&t.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),t.jsx("div",{className:"file-browser-actions",children:!$&&K&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:B,disabled:T,children:[t.jsx(ub,{size:14}),"Discard"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void z(),disabled:T,children:[t.jsx(Fh,{size:14}),T?"Saving...":"Save"]})]})})]}),I&&!$&&t.jsx("div",{className:"file-browser-error-banner",children:I}),$?t.jsx("div",{className:"file-browser-image-preview",children:t.jsx("img",{src:$,alt:m??"",className:"file-browser-image"})}):t.jsx("div",{className:"file-editor-wrapper",children:t.jsx(NA,{content:w,onChange:_,filePath:m,readOnly:Qm(m)})}),!$&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:A(w)}),K&&t.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):t.jsxs("div",{className:"file-browser-placeholder",children:[t.jsx(Dn,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to edit"})]})})]})]})})}function RA(e={}){const{pollInterval:n=3e4,autoRefresh:s=!0}=e,[i,r]=a.useState({providers:[],loading:!0,error:null,lastUpdated:null}),o=a.useRef(null),l=a.useRef(null),c=a.useCallback(async(d=!1)=>{l.current&&l.current.abort(),l.current=new AbortController,d&&r(m=>({...m,loading:!0,error:null}));try{const{providers:m}=await Iv();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:je(m)||"Failed to fetch usage data"}))}},[]);a.useEffect(()=>{c()},[c]),a.useEffect(()=>{if(s)return o.current=setInterval(()=>{c(!1)},n),()=>{o.current&&(clearInterval(o.current),o.current=null)}},[s,n,c]),a.useEffect(()=>()=>{l.current&&l.current.abort(),o.current&&clearInterval(o.current)},[]);const u=a.useCallback(()=>c(!0),[c]);return{providers:i.providers,loading:i.loading,error:i.error,lastUpdated:i.lastUpdated,refresh:u}}function TA(e){const n=new Date(e),s=new Date,i=n.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit",hour12:!0});if(n.toDateString()===s.toDateString())return i;const o=new Date(s.getFullYear(),s.getMonth(),s.getDate()),l=new Date(n.getFullYear(),n.getMonth(),n.getDate()),c=Math.round((l.getTime()-o.getTime())/(1440*60*1e3));return c>=1&&c<=7?`${n.toLocaleDateString(void 0,{weekday:"short"})} ${i}`:`${n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}, ${i}`}function PA(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}const Lf="kb-usage-hidden-windows";function Xm(e){const n=zn(Lf,e);if(!n)return{};try{const s=JSON.parse(n);return!s||typeof s!="object"?{}:Object.entries(s).reduce((i,[r,o])=>{if(Array.isArray(o)){const l=o.filter(c=>typeof c=="string");l.length>0&&(i[r]=l)}return i},{})}catch{return{}}}function IA(e,n){as(Lf,JSON.stringify(e),n)}function zf(e,n,s){return s[e]?.includes(n)??!1}function $A({window:e,viewMode:n,isHidden:s,onToggleHidden:i}){const r=PA(e.percentUsed),o=n==="remaining",l=Math.round(o?e.percentLeft:e.percentUsed),c=o?`${Math.round(e.percentLeft)}% remaining`:`${Math.round(e.percentUsed)}% used`,u=o?`${Math.round(e.percentUsed)}% used`:`${Math.round(e.percentLeft)}% left`;let d=e.resetText;if(!d&&e.resetAt){const v=new Date(e.resetAt).getTime()-Date.now();if(v>0){const b=Math.floor(v/36e5),y=Math.floor(b/24),S=b%24;y>0&&S>0?d=`resets in ${y}d ${S}h`:y>0?d=`resets in ${y}d`:b>0?d=`resets in ${b}h`:d=`resets in ${Math.floor(v/6e4)}m`}}const m=e.pace,h=m!==void 0;let g=0;h&&(g=o?100-m.percentElapsed:m.percentElapsed);const p=m?.status==="ahead",f=m?.status==="behind",x=m?.status==="on-track";return t.jsxs("div",{className:`usage-window ${s?"usage-window--hidden":""}`,children:[t.jsxs("div",{className:"usage-window-header",children:[t.jsx("span",{className:"usage-window-label",children:e.label}),t.jsxs("div",{className:"usage-window-header-controls",children:[!s&&t.jsx("span",{className:"usage-window-percentage",children:c}),!s&&t.jsx("button",{className:"btn-icon usage-window-hide-btn",onClick:i,"aria-label":`Hide ${e.label}`,"data-testid":"usage-window-hide-btn",children:t.jsx(sa,{size:14})})]})]}),t.jsxs("div",{className:"usage-progress-wrapper",children:[t.jsx("div",{className:"usage-progress-bar",children:t.jsx("div",{className:`usage-progress-fill ${r}`,style:{width:`${l}%`},role:"progressbar","aria-valuenow":l,"aria-valuemin":0,"aria-valuemax":100,"aria-label":`${e.label}: ${c}`})}),h&&t.jsx("div",{className:"usage-pace-marker",style:{left:`${g}%`},"aria-hidden":"true","data-testid":"pace-marker"})]}),t.jsxs("div",{className:"usage-window-footer",children:[t.jsx("span",{className:"usage-window-left",children:u}),t.jsxs("span",{className:"usage-window-reset-group",children:[d&&t.jsx("span",{className:"usage-window-reset",children:d}),e.resetAt&&t.jsx("span",{className:"usage-window-reset-at",children:TA(e.resetAt)})]})]}),h&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[p&&t.jsxs(t.Fragment,{children:[t.jsx(zc,{size:14,className:"pace-icon pace-ahead"}),t.jsx("span",{className:"pace-text pace-ahead",children:m.message})]}),f&&t.jsxs(t.Fragment,{children:[t.jsx(Rb,{size:14,className:"pace-icon pace-behind"}),t.jsx("span",{className:"pace-text pace-behind",children:m.message})]}),x&&t.jsxs(t.Fragment,{children:[t.jsx(un,{size:14,className:"pace-icon pace-ontrack"}),t.jsx("span",{className:"pace-text pace-ontrack",children:m.message})]})]})]})}function DA(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 LA({provider:e,viewMode:n,hiddenWindows:s,onToggleWindow:i,onShowAllHidden:r}){const o=s[e.name]?.length??0,l=()=>{switch(e.status){case"ok":return null;case"error":return t.jsx("span",{className:"usage-status-badge usage-status-badge--error",children:"Error"});case"no-auth":default:return t.jsx("span",{className:"usage-status-badge usage-status-badge--not-configured",children:"Not configured"})}};return t.jsxs("div",{className:"usage-provider","data-provider":e.name,"data-status":e.status,children:[t.jsxs("div",{className:"usage-provider-header",children:[t.jsxs("div",{className:"usage-provider-info",children:[t.jsx(Tn,{provider:DA(e.name),size:"md"}),t.jsx("span",{className:"usage-provider-name",children:e.name}),o>0&&t.jsxs("button",{className:"btn btn-sm usage-show-hidden-btn",onClick:()=>r(e.name),"data-testid":"usage-show-hidden-btn",children:["Show hidden (",o,")"]})]}),t.jsx("div",{className:"usage-provider-actions",children:l()})]}),e.error&&t.jsx("div",{className:"usage-provider-error",children:e.error}),e.plan&&t.jsx("div",{className:"usage-provider-meta",children:t.jsx("span",{className:"usage-provider-plan",children:e.plan})}),e.windows.length>0?t.jsx("div",{className:"usage-provider-windows",children:e.windows.map((c,u)=>{const d=zf(e.name,c.label,s);return t.jsx($A,{window:c,viewMode:n,isHidden:d,onToggleHidden:()=>i(e.name,c.label)},`${e.name}-${c.label}-${u}`)})}):e.status==="ok"?t.jsx("div",{className:"usage-provider-empty",children:"No usage data available"}):null]})}function zA(){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 FA({isOpen:e,onClose:n,projectId:s,anchorRect:i}){const{providers:r,loading:o,error:l,lastUpdated:c,refresh:u}=RA({autoRefresh:e}),[d,m]=a.useState(!1),[h,g]=a.useState(()=>typeof window<"u"?window.innerWidth>=769:!1),[p,f]=a.useState("used"),[x,v]=a.useState(()=>Xm(s)),b=a.useRef(null),y=a.useRef(e),S=a.useRef(!1);a.useEffect(()=>{e||(S.current=!1)},[e]),a.useEffect(()=>{r.length>0&&(S.current=!0)},[r.length]),a.useEffect(()=>{if(typeof window>"u")return;const E=()=>{g(window.innerWidth>=769)};return window.addEventListener("resize",E),()=>window.removeEventListener("resize",E)},[]),a.useEffect(()=>{!y.current&&e&&(!c||Date.now()-c.getTime()>5e3)&&u(),y.current=e},[e,c,u]),a.useEffect(()=>{const E=zn("kb-usage-view-mode",s);if(E==="used"||E==="remaining"){f(E);return}f("used")},[s]);const k=a.useCallback(E=>{f(E),as("kb-usage-view-mode",E,s)},[s]);a.useEffect(()=>{v(Xm(s))},[s]),a.useEffect(()=>{IA(x,s)},[x,s]);const M=a.useCallback((E,R)=>{v(B=>{if(zf(E,R,B)){const G=(B[E]??[]).filter(X=>X!==R);if(G.length===0){const{[E]:X,...C}=B;return C}return{...B,[E]:G}}return{...B,[E]:[...B[E]??[],R]}})},[]),w=a.useCallback(E=>{v(R=>{if(!R[E])return R;const{[E]:B,...G}=R;return G})},[]),_=a.useCallback(async()=>{m(!0),await u(),m(!1)},[u]);a.useEffect(()=>{if(!e)return;const E=R=>{R.key==="Escape"&&n()};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[e,n]);const N=a.useCallback(E=>{E.target===E.currentTarget&&n()},[n]);if(!e)return null;const L=!!(i&&h),z=L?Math.min((i?.bottom??0)+8,window.innerHeight-12):void 0,K=L?Math.max(window.innerWidth-(i?.right??0),0):void 0,P=t.jsxs("div",{className:`usage-modal${L?" usage-modal--popover":" modal"}`,"data-testid":"usage-modal",style:L?{position:"fixed",top:z,right:K}:void 0,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"usage-header",children:[t.jsx(Es,{size:18,className:"usage-header-icon"}),t.jsx("h3",{children:"Usage"})]}),t.jsxs("div",{className:"usage-header-actions",children:[t.jsxs("div",{className:"usage-view-toggle",role:"group","aria-label":"Usage view mode",children:[t.jsx("button",{className:`usage-view-toggle-btn ${p==="used"?"active":""}`,onClick:()=>k("used"),"aria-pressed":p==="used","data-testid":"usage-view-toggle-used",children:"Used"}),t.jsx("button",{className:`usage-view-toggle-btn ${p==="remaining"?"active":""}`,onClick:()=>k("remaining"),"aria-pressed":p==="remaining","data-testid":"usage-view-toggle-remaining",children:"Remaining"})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close usage modal","data-testid":"usage-modal-close",children:t.jsx(zt,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:b,children:(o||!S.current&&!l)&&r.length===0?t.jsx(zA,{}):l&&r.length===0?t.jsxs("div",{className:"usage-error",children:[t.jsx("p",{children:"Failed to load usage data"}),t.jsx("p",{className:"usage-error-message",children:l}),t.jsx("button",{className:"btn btn-sm",onClick:_,children:"Retry"})]}):r.length===0?t.jsxs("div",{className:"usage-empty",children:[t.jsx("p",{children:"No AI providers configured"}),t.jsx("p",{className:"usage-empty-hint",children:"Configure authentication in Settings to see usage data."})]}):t.jsx("div",{className:"usage-providers",children:r.map(E=>t.jsx(LA,{provider:E,viewMode:p,hiddenWindows:x,onToggleWindow:M,onShowAllHidden:w},E.name))})}),t.jsxs("div",{className:"modal-actions usage-actions",children:[t.jsx("div",{className:"modal-actions-left usage-actions-left",children:t.jsx("div",{className:"usage-last-updated",children:c&&t.jsxs("span",{children:["Last updated: ",c.toLocaleTimeString()]})})}),t.jsxs("div",{className:"modal-actions-right usage-actions-right",children:[t.jsxs("button",{className:"btn btn-sm",onClick:_,disabled:o||d,"data-testid":"usage-refresh-btn",children:[t.jsx(wn,{size:14,className:d?"spin":"",style:{marginRight:6}}),"Refresh"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]});return L?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"usage-popover-backdrop",onClick:n,"data-testid":"usage-modal-overlay"}),P]}):t.jsx("div",{className:"modal-overlay open",onClick:N,"data-testid":"usage-modal-overlay",children:P})}function Ff(e){if(e<1e3)return`${e}ms`;const n=Math.floor(e/1e3);if(n<60)return`${n}s`;const s=Math.floor(n/60),i=n%60;if(s<60)return i>0?`${s}m ${i}s`:`${s}m`;const r=Math.floor(s/60),o=s%60;return o>0?`${r}h ${o}m`:`${r}h`}function go(e){const n=Date.now(),s=new Date(e).getTime(),i=n-s;if(i<0){const r=Math.abs(i);return r<6e4?"in a moment":r<36e5?`in ${Math.floor(r/6e4)}m`:r<864e5?`in ${Math.floor(r/36e5)}h`:`in ${Math.floor(r/864e5)}d`}return i<6e4?"just now":i<36e5?`${Math.floor(i/6e4)}m ago`:i<864e5?`${Math.floor(i/36e5)}h ago`:`${Math.floor(i/864e5)}d ago`}const OA={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},Of={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},UA={cron:Ah,webhook:Uh,api:Rh,manual:In},BA={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},HA={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function qA({result:e}){const n=e.completedAt&&e.startedAt?new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime():0;return t.jsxs("span",{className:`schedule-run-badge ${e.success?"success":"failure"}`,children:[e.success?t.jsx(un,{size:12}):t.jsx(ur,{size:12}),t.jsx("span",{children:e.success?"Success":"Failed"}),n>0&&t.jsx("span",{className:"schedule-run-duration",children:Ff(n)})]})}function VA({result:e,index:n}){const[s,i]=a.useState(!1),r=e.completedAt&&e.startedAt?new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime():0;return t.jsxs("div",{className:"schedule-history-item",children:[t.jsxs("button",{className:"schedule-history-header",onClick:()=>i(!s),"aria-expanded":s,"aria-label":`Run #${n+1}: ${e.success?"succeeded":"failed"} ${go(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx(un,{size:12}):t.jsx(ur,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:go(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:Of[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:Ff(r)}),s?t.jsx(ni,{size:12}):t.jsx(qt,{size:12})]}),s&&t.jsxs("div",{className:"schedule-history-detail",children:[e.output&&t.jsx("pre",{className:"schedule-history-output",children:e.output}),e.error&&t.jsx("div",{className:"schedule-history-error",children:e.error})]})]})}function WA({routine:e,onEdit:n,onDelete:s,onRun:i,onToggle:r,running:o,lastRunOutput:l}){const[c,u]=a.useState(!1),{confirm:d}=Is(),m=a.useCallback(async()=>{await d({title:"Delete Routine",message:`Delete routine "${e.name}"? This cannot be undone.`,danger:!0})&&s(e)},[e,s,d]),h=OA[e.trigger.type],g=UA[e.trigger.type],p=e.trigger.type==="cron"?("cronExpression"in e.trigger?e.trigger.cronExpression:void 0)||e.cronExpression||"":e.cronExpression||"";return t.jsxs("div",{className:`routine-card${e.enabled?"":" disabled"}${o?" running":""}`,children:[t.jsxs("div",{className:"routine-card-header",children:[t.jsxs("div",{className:"routine-card-info",children:[t.jsxs("div",{className:"routine-card-name-row",children:[t.jsx("span",{className:"routine-card-name",children:e.name}),t.jsxs("span",{className:"routine-trigger-badge",style:{borderColor:h,color:h},children:[t.jsx(g,{size:10}),Of[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(jo,{size:10}):t.jsx(Dn,{size:10}),e.scope]})]}),e.description&&t.jsx("p",{className:"routine-card-description",children:e.description})]}),t.jsxs("div",{className:"routine-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>i(e),disabled:o,title:o?"Running…":"Run now","aria-label":o?"Running…":`Run ${e.name} now`,children:o?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(fn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>r(e),title:e.enabled?"Disable":"Enable","aria-label":e.enabled?`Disable ${e.name}`:`Enable ${e.name}`,"aria-pressed":e.enabled,children:e.enabled?t.jsx(qs,{size:14}):t.jsx(fn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:"Edit","aria-label":`Edit ${e.name}`,children:t.jsx(Qn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:m,title:"Delete","aria-label":`Delete ${e.name}`,children:t.jsx(Jt,{size:14})})]})]}),t.jsxs("div",{className:"routine-card-meta",children:[e.steps&&e.steps.length>0?t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(Ti,{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(hi,{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:BA[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:HA[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:go(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:go(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(qA,{result:e.lastRunResult}),t.jsxs("div",{className:"routine-meta-item",children:[t.jsx("span",{className:"routine-meta-label",children:"Runs:"}),t.jsx("span",{children:e.runCount})]})]}),l&&t.jsxs("div",{className:`routine-run-output ${l.success?"success":"failure"}`,children:[l.output&&t.jsx("pre",{className:"routine-run-output-text",children:l.output}),l.error&&t.jsx("div",{className:"routine-run-output-error",children:l.error})]}),e.runHistory.length>0&&t.jsxs("div",{className:"routine-card-history",children:[t.jsxs("button",{className:"schedule-history-toggle",onClick:()=>u(f=>!f),"aria-expanded":c,children:[c?t.jsx(ni,{size:12}):t.jsx(qt,{size:12}),t.jsxs("span",{children:["Run History (",e.runHistory.length,")"]})]}),c&&t.jsxs("div",{className:"schedule-history-list",children:[e.runHistory.slice(0,10).map((f,x)=>t.jsx(VA,{result:f,index:x},`${f.startedAt}-${x}`)),e.runHistory.length>10&&t.jsxs("div",{className:"schedule-history-more",children:["…and ",e.runHistory.length-10," more"]})]})]})]})}function KA({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(Lx,{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(Vn,{size:n}),t.jsx("span",{children:"AI Prompt"})]})}function Ul(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function GA(e){return e==="command"?{id:Ul(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:Ul(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:Ul(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function JA({step:e,onSave:n,onCancel:s}){const[i,r]=a.useState(e.name),[o,l]=a.useState(e.type),[c,u]=a.useState(e.command??""),[d,m]=a.useState(e.prompt??""),[h,g]=a.useState(e.modelProvider??""),[p,f]=a.useState(e.modelId??""),[x,v]=a.useState(e.taskTitle??""),[b,y]=a.useState(e.taskDescription??""),[S,k]=a.useState(e.taskColumn??"triage"),[M,w]=a.useState(e.timeoutMs),[_,N]=a.useState(e.continueOnFailure??!1),[L,T]=a.useState({}),[I,z]=a.useState([]),[K,P]=a.useState(!1),[E,R]=a.useState(null);a.useEffect(()=>{let $=!1;return P(!0),R(null),os().then(A=>{$||z(A.models)}).catch(A=>{$||R(A instanceof Error?A.message:"Failed to load models")}).finally(()=>{$||P(!1)}),()=>{$=!0}},[]);const B=a.useCallback(()=>{const $={};return i.trim()||($.name="Step name is required"),o==="command"&&!c.trim()&&($.command="Command is required"),o==="ai-prompt"&&!d.trim()&&($.prompt="Prompt is required"),o==="create-task"&&!b.trim()&&($.taskDescription="Task description is required"),(o==="ai-prompt"||o==="create-task")&&(h||p)&&(!h||!p)&&($.modelProvider="Both model provider and model ID must be set together"),M!==void 0&&M<1e3&&($.timeoutMs="Timeout must be at least 1 second (1000ms)"),T($),Object.keys($).length===0},[i,o,c,d,b,h,p,M]),G=h&&p?`${h}/${p}`:"",X=a.useCallback($=>{if(!$)g(""),f("");else{const A=$.indexOf("/");A!==-1&&(g($.slice(0,A)),f($.slice(A+1)))}},[]),C=a.useCallback(()=>{if(!B())return;const $={...e,name:i.trim(),type:o,command:o==="command"?c.trim():void 0,prompt:o==="ai-prompt"?d.trim():void 0,taskTitle:o==="create-task"&&x.trim()?x.trim():void 0,taskDescription:o==="create-task"&&b.trim()?b.trim():void 0,taskColumn:o==="create-task"?S:void 0,modelProvider:(o==="ai-prompt"||o==="create-task")&&h.trim()?h.trim():void 0,modelId:(o==="ai-prompt"||o==="create-task")&&p.trim()?p.trim():void 0,timeoutMs:M||void 0,continueOnFailure:_};o!=="ai-prompt"&&delete $.prompt,o!=="create-task"&&(delete $.taskTitle,delete $.taskDescription,delete $.taskColumn),n($)},[B,n,e,i,o,c,d,x,b,S,h,p,M,_]);return t.jsxs("div",{className:"step-editor",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-name-${e.id}`,children:"Step Name"}),t.jsx("input",{id:`step-name-${e.id}`,type:"text",placeholder:"e.g. Run tests",value:i,onChange:$=>r($.target.value),"aria-invalid":!!L.name}),L.name&&t.jsx("small",{className:"field-error",children:L.name})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-type-${e.id}`,children:"Step Type"}),t.jsxs("select",{id:`step-type-${e.id}`,value:o,onChange:$=>l($.target.value),children:[t.jsx("option",{value:"command",children:"Command"}),t.jsx("option",{value:"ai-prompt",children:"AI Prompt"}),t.jsx("option",{value:"create-task",children:"Create Task"})]})]}),o==="command"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-command-${e.id}`,children:"Command"}),t.jsx("textarea",{id:`step-command-${e.id}`,placeholder:"e.g. npm test",value:c,onChange:$=>u($.target.value),rows:2,"aria-invalid":!!L.command}),L.command&&t.jsx("small",{className:"field-error",children:L.command})]}),o==="ai-prompt"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-prompt-${e.id}`,children:"Prompt"}),t.jsx("textarea",{id:`step-prompt-${e.id}`,placeholder:"e.g. Summarize the test results and highlight any failures",value:d,onChange:$=>m($.target.value),rows:3,"aria-invalid":!!L.prompt}),L.prompt&&t.jsx("small",{className:"field-error",children:L.prompt})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-model-${e.id}`,children:"Model (optional)"}),t.jsx(Ln,{id:`step-model-${e.id}`,label:"Model",models:I,value:G,onChange:X,placeholder:"Use default",disabled:K}),E&&t.jsx("small",{className:"field-error",children:E}),t.jsx("small",{children:"AI model for this step. Uses default if not selected."})]})]}),o==="create-task"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-title-${e.id}`,children:"Task Title (optional)"}),t.jsx("input",{id:`step-task-title-${e.id}`,type:"text",placeholder:"e.g. Review weekly dependencies",value:x,onChange:$=>v($.target.value)}),t.jsx("small",{children:"Leave blank to auto-summarize from description"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-description-${e.id}`,children:"Task Description *"}),t.jsx("textarea",{id:`step-task-description-${e.id}`,placeholder:"e.g. Check all npm dependencies for security vulnerabilities and update outdated packages",value:b,onChange:$=>y($.target.value),rows:4,"aria-invalid":!!L.taskDescription}),L.taskDescription&&t.jsx("small",{className:"field-error",children:L.taskDescription})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-column-${e.id}`,children:"Target Column"}),t.jsxs("select",{id:`step-task-column-${e.id}`,value:S,onChange:$=>k($.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(Ln,{id:`step-task-model-${e.id}`,label:"Model",models:I,value:G,onChange:X,placeholder:"Use default",disabled:K}),E&&t.jsx("small",{className:"field-error",children:E}),L.modelProvider&&t.jsx("small",{className:"field-error",children:L.modelProvider}),t.jsx("small",{children:"AI model for executing the created task. Uses default if not selected."})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-timeout-${e.id}`,children:"Timeout (ms, optional)"}),t.jsx("input",{id:`step-timeout-${e.id}`,type:"number",min:1e3,step:1e3,placeholder:"Override schedule timeout",value:M??"",onChange:$=>w($.target.value?Number($.target.value):void 0),"aria-invalid":!!L.timeoutMs}),L.timeoutMs&&t.jsx("small",{className:"field-error",children:L.timeoutMs})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:`step-continue-${e.id}`,className:"checkbox-label",children:[t.jsx("input",{id:`step-continue-${e.id}`,type:"checkbox",checked:_,onChange:$=>N($.target.checked)}),"Continue on failure"]}),t.jsx("small",{children:"If checked, the next step will run even if this one fails"})]}),t.jsxs("div",{className:"step-editor-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:C,children:"Save Step"})]})]})}function YA({steps:e,onChange:n,onEditingChange:s}){const[i,r]=a.useState(null);a.useEffect(()=>{s?.(i!==null)},[i,s]);const o=a.useCallback(d=>{const m=GA(d);n([...e,m]),r(m.id)},[e,n]),l=a.useCallback(d=>{n(e.filter(m=>m.id!==d)),i===d&&r(null)},[e,n,i]),c=a.useCallback((d,m)=>{const h=e.findIndex(f=>f.id===d);if(h<0)return;const g=m==="up"?h-1:h+1;if(g<0||g>=e.length)return;const p=[...e];[p[h],p[g]]=[p[g],p[h]],n(p)},[e,n]),u=a.useCallback(d=>{n(e.map(m=>m.id===d.id?d:m)),r(null)},[e,n]);return t.jsxs("div",{className:"steps-editor",children:[t.jsx("div",{className:"steps-editor-header",children:t.jsxs("span",{className:"steps-editor-title",children:["Steps (",e.length,")"]})}),e.length===0&&t.jsx("div",{className:"steps-empty-state",children:t.jsx("p",{children:"No steps added yet. Add a command or AI prompt step to get started."})}),t.jsx("div",{className:"steps-list",children:e.map((d,m)=>t.jsx("div",{className:"step-card",children:i===d.id?t.jsx(JA,{step:d,onSave:u,onCancel:()=>r(null)}):t.jsxs("div",{className:"step-card-row",children:[t.jsx("div",{className:"step-card-drag",children:t.jsx(Lc,{size:14})}),t.jsx("span",{className:"step-card-index",children:m+1}),t.jsx(KA,{type:d.type}),t.jsx("span",{className:"step-card-name",children:d.name}),d.continueOnFailure&&t.jsx("span",{className:"step-card-flag",title:"Continues on failure",children:"⚡"}),t.jsxs("div",{className:"step-card-actions",children:[t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>c(d.id,"up"),disabled:m===0,title:"Move up","aria-label":`Move ${d.name} up`,children:t.jsx(ni,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>c(d.id,"down"),disabled:m===e.length-1,title:"Move down","aria-label":`Move ${d.name} down`,children:t.jsx(qt,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(d.id),title:"Edit","aria-label":`Edit ${d.name}`,children:t.jsx(Qn,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>l(d.id),title:"Delete","aria-label":`Delete ${d.name}`,children:t.jsx(Jt,{size:14})})]})]})},d.id))}),t.jsxs("div",{className:"steps-add-buttons",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("command"),children:[t.jsx(Xt,{size:14}),"Add Command Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ai-prompt"),children:[t.jsx(Xt,{size:14}),"Add AI Prompt Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("create-task"),children:[t.jsx(Xt,{size:14}),"Add Create Task Step"]})]})]})}const Uf={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},QA={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function XA(e){const n=e.trim();for(const[s,i]of Object.entries(Uf))if(i===n)return s;return"custom"}function ZA(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function eR(e,n,s,i,r){switch(e){case"cron":return{type:"cron",cronExpression:n};case"webhook":return{type:"webhook",webhookPath:s||"/trigger/"+Math.random().toString(36).slice(2,10),secret:i||void 0};case"api":return{type:"api",endpoint:r||"/api/routine/"+Math.random().toString(36).slice(2,10)};case"manual":return{type:"manual"}}}function tR(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 nR=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],sR=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function Zm(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function eh({routine:e,onSubmit:n,onCancel:s,scope:i,projectId:r,onScopeChange:o}){const l=!!e,c=e?tR(e):{triggerType:"cron",cronExpression:"0 * * * *",webhookPath:"",webhookSecret:"",endpoint:""},[u,d]=a.useState(e?.name??""),[m,h]=a.useState(e?.description??""),[g,p]=a.useState(c.triggerType),[f,x]=a.useState(c.cronExpression),[v,b]=a.useState(()=>c.triggerType!=="cron"?"custom":XA(c.cronExpression)),[y,S]=a.useState(c.webhookPath),[k,M]=a.useState(c.webhookSecret),[w,_]=a.useState(c.endpoint),[N,L]=a.useState(e?.executionPolicy??"queue"),[T,I]=a.useState(e?.catchUpPolicy??"run_one"),[z,K]=a.useState(e?.enabled??!0),P=e?.steps&&e.steps.length===1&&e.steps[0].type==="ai-prompt"&&!e.command,E=e?.steps&&e.steps.length===1&&e.steps[0].type==="create-task"&&!e.command,[R,B]=a.useState(e?.steps&&e.steps.length>0&&!P&&!E?"advanced":"simple"),[G,X]=a.useState(()=>P?"ai-prompt":E?"create-task":"command"),[C,$]=a.useState(e?.command??""),[A,j]=a.useState(e?.steps??[]),[J,W]=a.useState(!1),[oe,he]=a.useState(e?.timeoutMs??3e5),[se,fe]=a.useState(P?e.steps?.[0]?.prompt??"":""),[U,Ne]=a.useState(E?e.steps?.[0]?.taskTitle??"":""),[ee,ve]=a.useState(E?e.steps?.[0]?.taskDescription??"":""),[ue,ye]=a.useState(E?e.steps?.[0]?.taskColumn??"triage":"triage"),[ie,Me]=a.useState(P||E?e.steps?.[0]?.modelProvider??"":""),[ze,Be]=a.useState(P||E?e.steps?.[0]?.modelId??"":""),[Je,Ye]=a.useState([]),[Ge,it]=a.useState(!1),[_e,Fe]=a.useState(null),[ae,be]=a.useState(i??"global"),[ne,Ie]=a.useState({}),[Pe,ce]=a.useState(!1),le=a.useRef(!0);a.useEffect(()=>()=>{le.current=!1},[]),a.useEffect(()=>{i&&be(i)},[i]),a.useEffect(()=>{let Se=!1;return it(!0),Fe(null),os().then(mt=>{Se||Ye(mt.models)}).catch(mt=>{Se||Fe(mt instanceof Error?mt.message:"Failed to load models")}).finally(()=>{Se||it(!1)}),()=>{Se=!0}},[]);const $e=ie&&ze?`${ie}/${ze}`:"",at=a.useCallback(Se=>{if(!Se){Me(""),Be("");return}const mt=Se.indexOf("/");mt!==-1&&(Me(Se.slice(0,mt)),Be(Se.slice(mt+1)))},[]),tt=a.useCallback(()=>{const Se={};if(u.trim()||(Se.name="Name is required"),ae==="project"&&!r&&(Se.scope="Project-specific entries require an active project."),g==="cron"&&v==="custom"&&(f.trim()?ZA(f)||(Se.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):Se.cronExpression="Cron expression is required"),g==="webhook"&&!y.trim()&&(Se.webhookPath="Webhook path is required"),g==="api"&&!w.trim()&&(Se.endpoint="API endpoint is required"),R==="simple")G==="command"&&!C.trim()&&(Se.command="Command is required"),G==="ai-prompt"&&!se.trim()&&(Se.prompt="Prompt is required"),G==="create-task"&&!ee.trim()&&(Se.taskDescription="Task description is required"),(ie.trim()&&!ze.trim()||!ie.trim()&&ze.trim())&&(Se.model="Both model provider and model ID must be set, or both must be empty");else{A.length===0&&(Se.steps="At least one step is required"),J&&(Se.stepsEditing="Please save or cancel all step edits before saving the routine");const mt=[];A.forEach((gt,wt)=>{gt.name?.trim()||mt.push(`Step ${wt+1}: Name is required`),gt.type==="command"&&!gt.command?.trim()&&mt.push(`Step ${wt+1}: Command is required`),gt.type==="ai-prompt"&&!gt.prompt?.trim()&&mt.push(`Step ${wt+1}: Prompt is required`),gt.type==="create-task"&&!gt.taskDescription?.trim()&&mt.push(`Step ${wt+1}: Task description is required`)}),mt.length>0&&(Se.steps=mt.join("; "))}return oe<1e3&&(Se.timeoutMs="Timeout must be at least 1 second (1000ms)"),Ie(Se),Object.keys(Se).length===0},[u,g,f,v,y,w,ae,r,R,G,C,se,ee,ie,ze,A,J,oe]),V=a.useCallback(async Se=>{if(Se.preventDefault(),!!tt()){ce(!0);try{let mt=e?.scope??ae??(r?"project":"global");mt==="project"&&!r&&(mt="global");const gt=eR(g,f,y,k,w);let wt,yt;R==="simple"?G==="command"?wt=C.trim()||void 0:G==="ai-prompt"?yt=[{id:Zm(),type:"ai-prompt",name:u.trim(),prompt:se.trim(),modelProvider:ie.trim()||void 0,modelId:ze.trim()||void 0}]:yt=[{id:Zm(),type:"create-task",name:u.trim(),taskTitle:U.trim()||void 0,taskDescription:ee.trim(),taskColumn:ue,modelProvider:ie.trim()||void 0,modelId:ze.trim()||void 0}]:yt=A;const kt={name:u.trim(),agentId:e?.agentId??"",description:m.trim()||void 0,trigger:gt,command:wt,steps:yt,timeoutMs:oe,executionPolicy:N,catchUpPolicy:T,enabled:z,scope:mt};await n(kt)}finally{le.current&&ce(!1)}}},[tt,n,u,m,g,f,y,k,w,R,G,C,se,ie,ze,U,ee,ue,A,oe,N,T,z,ae,r,e?.scope,e?.agentId]),de="routine-name-error",Z="routine-cron-error",we="routine-webhook-error",pe="routine-endpoint-error",Te="routine-command-error",Qe="routine-prompt-error",Ee="routine-task-description-error",Re="routine-model-error",Le="routine-timeout-error",ct=a.useCallback(Se=>{b(Se),Se!=="custom"&&x(Uf[Se])},[]);return t.jsxs("form",{className:"routine-form",onSubmit:V,noValidate:!0,children:[t.jsx("h4",{className:"settings-section-heading",children:l?"Edit Routine":"New Routine"}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-name",children:"Name"}),t.jsx("input",{id:"routine-name",type:"text",placeholder:"e.g. Daily standup reminder",value:u,onChange:Se=>d(Se.target.value),"aria-invalid":!!ne.name,"aria-describedby":ne.name?de:void 0}),ne.name&&t.jsx("small",{id:de,className:"field-error",children:ne.name})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-description",children:"Description (optional)"}),t.jsx("textarea",{id:"routine-description",placeholder:"What does this routine do?",value:m,onChange:Se=>h(Se.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${ae==="global"?" active":""}`,onClick:()=>{be("global"),o?.("global")},role:"radio","aria-checked":ae==="global"?"true":"false",disabled:!!e?.scope,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:"Global scope",children:[t.jsx(jo,{size:12}),"Global"]}),t.jsxs("button",{type:"button",className:`routine-scope-btn${ae==="project"?" active":""}`,onClick:()=>{be("project"),o?.("project")},role:"radio","aria-checked":ae==="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(Dn,{size:12}),"Project"]})]}),t.jsx("small",{children:!r&&!e?.scope?"No active project. Routines will be created at global scope.":ae==="project"&&r?"This routine will be scoped to the current project.":"This routine will be created at global scope."}),ne.scope&&t.jsx("small",{className:"field-error",children:ne.scope})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Trigger Type"}),t.jsxs("div",{className:"routine-trigger-type-selector",role:"radiogroup","aria-label":"Trigger type",children:[t.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="cron"?" active":""}`,onClick:()=>p("cron"),role:"radio","aria-checked":g==="cron",children:[t.jsx(Ah,{size:14}),"Cron"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="webhook"?" active":""}`,onClick:()=>p("webhook"),role:"radio","aria-checked":g==="webhook",children:[t.jsx(Uh,{size:14}),"Webhook"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="api"?" active":""}`,onClick:()=>p("api"),role:"radio","aria-checked":g==="api",children:[t.jsx(Rh,{size:14}),"API"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="manual"?" active":""}`,onClick:()=>p("manual"),role:"radio","aria-checked":g==="manual",children:[t.jsx(In,{size:14}),"Manual"]})]})]}),g==="cron"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-frequency",children:"Frequency"}),t.jsx("select",{id:"routine-frequency",value:v,onChange:Se=>ct(Se.target.value),children:Object.entries(QA).map(([Se,mt])=>t.jsx("option",{value:Se,children:mt},Se))}),t.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),t.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:f,onChange:Se=>x(Se.target.value),disabled:v!=="custom","aria-invalid":!!ne.cronExpression,"aria-describedby":ne.cronExpression?Z:void 0}),ne.cronExpression?t.jsx("small",{id:Z,className:"field-error",children:ne.cronExpression}):t.jsx("small",{children:v==="custom"?t.jsxs(t.Fragment,{children:["min hour day month weekday — ",t.jsx("a",{href:"https://crontab.guru",target:"_blank",rel:"noopener noreferrer",children:"crontab.guru"})]}):`Auto-filled from preset: ${f}`})]}),g==="webhook"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-path",children:"Webhook Path"}),t.jsx("input",{id:"routine-webhook-path",type:"text",placeholder:"/trigger/my-routine",value:y,onChange:Se=>S(Se.target.value),"aria-invalid":!!ne.webhookPath,"aria-describedby":ne.webhookPath?we:void 0}),ne.webhookPath?t.jsx("small",{id:we,className:"field-error",children:ne.webhookPath}):t.jsx("small",{children:"URL path for the webhook endpoint"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-secret",children:"Webhook Secret (optional)"}),t.jsx("input",{id:"routine-webhook-secret",type:"password",placeholder:"Optional — leave empty for unauthenticated webhooks",value:k,onChange:Se=>M(Se.target.value)}),t.jsx("small",{children:"HMAC secret for signature verification. Leave empty for unauthenticated webhooks."})]})]}),g==="api"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-endpoint",children:"API Endpoint"}),t.jsx("input",{id:"routine-endpoint",type:"text",placeholder:"/api/routine/my-routine",value:w,onChange:Se=>_(Se.target.value),"aria-invalid":!!ne.endpoint,"aria-describedby":ne.endpoint?pe:void 0}),ne.endpoint?t.jsx("small",{id:pe,className:"field-error",children:ne.endpoint}):t.jsx("small",{children:"API endpoint path that triggers this routine"})]}),g==="manual"&&t.jsx("div",{className:"form-group",children:t.jsx("small",{className:"routine-trigger-info",children:"This routine will be triggered manually via the dashboard or API."})}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Action Mode"}),t.jsxs("div",{className:"schedule-mode-toggle",role:"radiogroup","aria-label":"Action mode",children:[t.jsx("button",{type:"button",className:`schedule-mode-btn${R==="simple"?" active":""}`,onClick:()=>B("simple"),role:"radio","aria-checked":R==="simple",children:"Simple"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${R==="advanced"?" active":""}`,onClick:()=>B("advanced"),role:"radio","aria-checked":R==="advanced",children:"Multi-Step"})]}),t.jsx("small",{children:R==="simple"?"Run one command, prompt, or task creation action":"Run multiple actions sequentially"})]}),R==="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:C,onChange:Se=>$(Se.target.value),"aria-invalid":!!ne.command,"aria-describedby":ne.command?Te:void 0}),ne.command?t.jsx("small",{id:Te,className:"field-error",children:ne.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:se,onChange:Se=>fe(Se.target.value),rows:3,"aria-invalid":!!ne.prompt,"aria-describedby":ne.prompt?Qe:void 0}),ne.prompt?t.jsx("small",{id:Qe,className:"field-error",children:ne.prompt}):t.jsx("small",{children:"AI prompt to execute."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-model",children:"Model (optional)"}),t.jsx(Ln,{id:"routine-model",label:"Model",models:Je,value:$e,onChange:at,placeholder:"Use default",disabled:Ge}),_e&&t.jsx("small",{className:"field-error",children:_e}),ne.model&&t.jsx("small",{id:Re,className:"field-error",children:ne.model})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-title",children:"Task Title (optional)"}),t.jsx("input",{id:"routine-task-title",type:"text",placeholder:"e.g. Review weekly dependencies",value:U,onChange:Se=>Ne(Se.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:Se=>ve(Se.target.value),rows:4,"aria-invalid":!!ne.taskDescription,"aria-describedby":ne.taskDescription?Ee:void 0}),ne.taskDescription?t.jsx("small",{id:Ee,className:"field-error",children:ne.taskDescription}):t.jsx("small",{children:"Describes the task that will be created."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-column",children:"Target Column"}),t.jsxs("select",{id:"routine-task-column",value:ue,onChange:Se=>ye(Se.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(Ln,{id:"routine-task-model",label:"Executor Model",models:Je,value:$e,onChange:at,placeholder:"Use default",disabled:Ge}),_e&&t.jsx("small",{className:"field-error",children:_e}),ne.model&&t.jsx("small",{id:Re,className:"field-error",children:ne.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(YA,{steps:A,onChange:j,onEditingChange:W}),ne.steps&&t.jsx("small",{className:"field-error",children:ne.steps}),ne.stepsEditing&&t.jsx("small",{className:"field-error",children:ne.stepsEditing})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-timeout",children:"Timeout (ms)"}),t.jsx("input",{id:"routine-timeout",type:"number",min:1e3,step:1e3,value:oe,onChange:Se=>he(Number(Se.target.value)),"aria-invalid":!!ne.timeoutMs,"aria-describedby":ne.timeoutMs?Le:void 0}),ne.timeoutMs?t.jsx("small",{id:Le,className:"field-error",children:ne.timeoutMs}):t.jsx("small",{children:"Maximum execution time in milliseconds."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-execution-policy",children:"Execution Policy"}),t.jsx("select",{id:"routine-execution-policy",value:N,onChange:Se=>L(Se.target.value),children:nR.map(Se=>t.jsx("option",{value:Se.value,children:Se.label},Se.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:T,onChange:Se=>I(Se.target.value),children:sR.map(Se=>t.jsx("option",{value:Se.value,children:Se.label},Se.value))}),t.jsx("small",{children:"What to do when a scheduled run is missed"})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:"routine-enabled",className:"checkbox-label",children:[t.jsx("input",{id:"routine-enabled",type:"checkbox",checked:z,onChange:Se=>K(Se.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:Pe,children:"Cancel"}),t.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:Pe,children:Pe?"Saving…":l?"Save Changes":"Create Routine"})]})]})}const iR=3e4;function aR({onClose:e,addToast:n,projectId:s}){const[i,r]=a.useState(()=>s?"project":"global"),[o,l]=a.useState([]),[c,u]=a.useState("list"),[d,m]=a.useState(),[h,g]=a.useState(null),[p,f]=a.useState({}),x=a.useRef(null);Gs(x,!0,"fusion:automation-modal-size");const v=a.useMemo(()=>({scope:i,projectId:i==="project"?s:void 0}),[i,s]),b=a.useCallback(async()=>{try{const P=await qy(v);l(P),f(E=>{const R={...E};for(const B of P){const G=R[B.id];if(!G||!B.lastRunResult)continue;const X=B.lastRunResult;X.success===G.success&&(X.output||"")===G.output&&(X.error||"")===(G.error||"")&&delete R[B.id]}return R})}catch(P){n(je(P)||"Failed to load routines","error")}},[n,v]);a.useEffect(()=>{b()},[b]),a.useEffect(()=>{const P=setInterval(()=>{b()},iR);return()=>clearInterval(P)},[b]),a.useEffect(()=>{const P=E=>{E.key==="Escape"&&(c!=="list"?(u("list"),m(void 0)):e())};return document.addEventListener("keydown",P),()=>document.removeEventListener("keydown",P)},[e,c]);const y=fi(e),S=a.useCallback(async P=>{try{await Vy(P,v),n("Routine created","success"),u("list"),await b()}catch(E){n(je(E)||"Failed to create routine","error")}},[n,b,v]),k=a.useCallback(P=>{m(P),u("edit")},[]),M=a.useCallback(async P=>{if(d)try{await Ld(d.id,P,v),n("Routine updated","success"),u("list"),m(void 0),await b()}catch(E){n(je(E)||"Failed to update routine","error")}},[d,n,b,v]),w=a.useCallback(async P=>{try{await Wy(P.id,v),n(`Deleted "${P.name}"`,"success"),await b()}catch(E){n(je(E)||"Failed to delete routine","error")}},[n,b,v]),_=a.useCallback(async P=>{g(P.id);try{const{result:E}=await Ky(P.id,v);f(R=>({...R,[P.id]:{output:E.output||"",error:E.error,success:E.success}})),E.success?n(`"${P.name}" completed successfully`,"success"):n(`"${P.name}" failed: ${E.error||"Unknown error"}`,"error"),await b()}catch(E){n(je(E)||"Failed to run routine","error")}finally{g(null)}},[n,b,v]),N=a.useCallback(async P=>{try{await Ld(P.id,{enabled:!P.enabled},v),n(`"${P.name}" ${P.enabled?"disabled":"enabled"}`,"success"),await b()}catch(E){n(je(E)||"Failed to toggle routine","error")}},[n,b,v]),L=a.useCallback(()=>{u("list"),m(void 0)},[]);a.useEffect(()=>{c!=="list"&&f({})},[c]);const T=a.useCallback(P=>{r(P),u("list"),m(void 0),f({})},[]),I=()=>c==="create"?t.jsx(eh,{onSubmit:S,onCancel:L,scope:i,projectId:s}):c==="edit"&&d?t.jsx(eh,{routine:d,onSubmit:M,onCancel:L,scope:i,projectId:s}):o.length===0?t.jsxs("div",{className:"routine-empty-state",children:[t.jsx(In,{size:48,strokeWidth:1}),t.jsx("h4",{children:"No automations yet"}),t.jsx("p",{children:"Create an automation with a schedule, webhook, API, or manual trigger."}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>u("create"),children:[t.jsx(Xt,{size:14}),"Create your first automation"]})]}):t.jsx("div",{className:"routine-list",children:o.map(P=>t.jsx(WA,{routine:P,onEdit:k,onDelete:w,onRun:_,onToggle:N,running:h===P.id,lastRunOutput:p[P.id]??null},P.id))}),z=()=>I(),K=c==="list"&&o.length>0;return t.jsx("div",{className:"modal-overlay open",...y,children:t.jsxs("div",{ref:x,className:"modal modal-lg automation-modal",role:"dialog","aria-modal":"true","aria-labelledby":"schedules-modal-title",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(In,{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(zt,{size:20})})]}),t.jsxs("div",{className:"scheduling-toolbar","aria-live":"polite",children:[t.jsxs("div",{className:"scheduling-toolbar-left",role:"group","aria-label":"Scheduling scope",children:[t.jsxs("div",{className:"scheduling-scope-selector",children:[t.jsxs("button",{type:"button",className:`scope-btn${i==="global"?" active":""}`,onClick:()=>T("global"),"aria-pressed":i==="global",title:"Global (user-level) automations",children:[t.jsx(jo,{size:14}),"Global"]}),t.jsxs("button",{type:"button",className:`scope-btn${i==="project"?" active":""}`,onClick:()=>T("project"),"aria-pressed":i==="project",title:"Project-scoped automations",children:[t.jsx(Dn,{size:14}),"Project"]})]}),t.jsxs("span",{className:"scheduling-count",children:[t.jsx(In,{size:14}),o.length," automation",o.length===1?"":"s"]})]}),t.jsx("div",{className:"scheduling-toolbar-right",children:K&&t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>u("create"),"aria-label":"Create new automation",children:[t.jsx(Xt,{size:14}),"New Automation"]})})]}),t.jsx("div",{className:"schedule-modal-content",id:"scheduled-tasks-content",children:z()})]})})}const rR=3e4,Ac=new Map,Bl=new Map;function th(e){return e??"default"}function nh(e){const n=Ac.get(e);return n?Date.now()>=n.expiresAt?(Ac.delete(e),null):n:null}function oR(e,n){const s=e.some(r=>r.id!=="github"&&r.authenticated),i=e.some(r=>r.id==="github"&&r.authenticated)||(n?.authenticated??!1);return{hasAiProvider:s,hasGithub:i}}async function lR(e){const n=Bl.get(e);if(n)return n;const s=ir().then(({providers:i,ghCli:r})=>{const l={...oR(i,r),ghCli:r,expiresAt:Date.now()+rR};return Ac.set(e,l),l}).finally(()=>{Bl.delete(e)});return Bl.set(e,s),s}function Bf(e){const n=th(e),s=nh(n),[i,r]=a.useState(s?.hasAiProvider??!1),[o,l]=a.useState(s?.hasGithub??!1),[,c]=a.useState(s?.ghCli),[u,d]=a.useState(s==null),m=a.useRef(!!s);return a.useEffect(()=>{let h=!1;const g=th(e),p=nh(g);if(p)return r(p.hasAiProvider),l(p.hasGithub),c(p.ghCli),d(!1),m.current=!0,()=>{h=!0};m.current=!1;async function f(){!m.current&&d(!0);try{const v=await lR(g);if(h)return;r(v.hasAiProvider),l(v.hasGithub),c(v.ghCli)}catch{}finally{h||(m.current=!0,d(!1))}}return f(),()=>{h=!0}},[e]),a.useMemo(()=>({hasAiProvider:i,hasGithub:o,loading:u,hasWarnings:!i||!o}),[i,o,u])}function Hf({hasAiProvider:e,hasGithub:n,compact:s=!1,onDismiss:i}){if(e&&n)return null;const r=i?t.jsx("button",{type:"button",className:"setup-warning-banner__dismiss touch-target","aria-label":"Dismiss setup warning",onClick:i,children:t.jsx(zt,{size:16,"aria-hidden":"true"})}):null;if(s)return t.jsxs("div",{className:`setup-warning-banner setup-warning-banner--compact${i?" setup-warning-banner--dismissible":""}`,role:"status","aria-live":"polite",children:[t.jsx("p",{className:"setup-warning-banner__compact-text",children:"⚠ Setup incomplete — AI and/or GitHub features will be limited."}),r]});const o=[];return e||o.push({key:"ai",title:"No AI provider connected",description:"AI agents won't be able to work on tasks until you connect a provider. Set one up in Settings → AI Setup."}),n||o.push({key:"github",title:"GitHub not connected",description:"You won't be able to import issues from GitHub, but you can still create tasks manually."}),t.jsxs("div",{className:`setup-warning-banner${i?" setup-warning-banner--dismissible":""}`,role:"status","aria-live":"polite",children:[r,o.map(l=>t.jsxs("div",{className:"setup-warning-banner__item",children:[t.jsx("strong",{className:"setup-warning-banner__title",children:l.title}),t.jsx("p",{className:"setup-warning-banner__description",children:l.description})]},l.key))]})}function cR({isOpen:e,onClose:n,projectId:s,tasks:i,onCreateTask:r,addToast:o,onPlanningMode:l,onSubtaskBreakdown:c}){const{confirm:u}=Is(),[d,m]=a.useState(""),[h,g]=a.useState([]),[p,f]=a.useState([]),[x,v]=a.useState(!1),[b,y]=a.useState(""),[S,k]=a.useState(""),[M,w]=a.useState(""),[_,N]=a.useState(""),[L,T]=a.useState(""),[I,z]=a.useState("default"),[K,P]=a.useState(!1),[E,R]=a.useState([]),[B,G]=a.useState(!1),[X,C]=a.useState(void 0),[$,A]=a.useState(ps),[j,J]=a.useState(null),[W,oe]=a.useState([]),[he,se]=a.useState(!1),[fe,U]=a.useState(!1),Ne=a.useRef(null),[ee,ve]=a.useState(!1),[ue,ye]=a.useState(""),ie=a.useRef(null),{hasAiProvider:Me,hasGithub:ze,loading:Be}=Bf(s),Je=a.useCallback(le=>{G(!0),R(le)},[]),Ye=a.useCallback(()=>{G(!1)},[]),Ge=a.useCallback(async()=>{if(W.length>0){se(!0);return}U(!0);try{const le=await xa(void 0,s);oe(le),se(!0)}catch(le){const $e=je(le);o($e?`Failed to load agents: ${$e}`:"Failed to load agents","error"),se(!1)}finally{U(!1)}},[W.length,s,o]);a.useEffect(()=>{if(!he)return;const le=$e=>{Ne.current&&!Ne.current.contains($e.target)&&se(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[he]),a.useEffect(()=>{if(!ee)return;const le=$e=>{ie.current&&!ie.current.contains($e.target)&&(ve(!1),ye(""))};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[ee]);const it=i.filter(le=>!h.includes(le.id)).sort((le,$e)=>{const at=$e.createdAt.localeCompare(le.createdAt);if(at!==0)return at;const tt=parseInt(le.id.slice(le.id.lastIndexOf("-")+1),10)||0;return(parseInt($e.id.slice($e.id.lastIndexOf("-")+1),10)||0)-tt}),_e=ue?it.filter(le=>le.id.toLowerCase().includes(ue.toLowerCase())||le.title&&le.title.toLowerCase().includes(ue.toLowerCase())||le.description&&le.description.toLowerCase().includes(ue.toLowerCase())):it,Fe=(le,$e)=>le.length>$e?le.slice(0,$e)+"…":le;a.useEffect(()=>{const le=d.trim()!==""||h.length>0||p.length>0||b!==""||S!==""||M!==""||_!==""||E.length>0||j!==null||X!==void 0||$!==ps;P(le)},[d,h,p,b,S,M,_,E,j,X,$]);const ae=a.useCallback(async()=>{K&&!await u({title:"Discard Changes",message:"You have unsaved changes. Discard them?",danger:!0})||(p.forEach(le=>URL.revokeObjectURL(le.previewUrl)),f([]),m(""),g([]),y(""),k(""),w(""),N(""),T(""),z("default"),R([]),G(!1),J(null),se(!1),C(void 0),A(ps),P(!1),n())},[K,n,p,u]),be=a.useCallback(async()=>{const le=d.trim();if(!(!le||x)){v(!0);try{const $e=b.indexOf("/"),at=S.indexOf("/"),tt=M.indexOf("/"),V=await r({title:void 0,description:le,column:"triage",dependencies:h.length?h:void 0,enabledWorkflowSteps:B?E.length>0?E:[]:void 0,...j?{assignedAgentId:j}:{},modelPresetId:I==="preset"&&L||void 0,modelProvider:b&&$e!==-1?b.slice(0,$e):void 0,modelId:b&&$e!==-1?b.slice($e+1):void 0,validatorModelProvider:S&&at!==-1?S.slice(0,at):void 0,validatorModelId:S&&at!==-1?S.slice(at+1):void 0,planningModelProvider:M&&tt!==-1?M.slice(0,tt):void 0,planningModelId:M&&tt!==-1?M.slice(tt+1):void 0,thinkingLevel:_!==""?_:void 0,reviewLevel:X,priority:$});if(p.length>0){const de=[];for(const Z of p)try{await sr(V.id,Z.file,s)}catch{de.push(Z.file.name)}de.length>0&&o(`Failed to upload: ${de.join(", ")}`,"error")}p.forEach(de=>URL.revokeObjectURL(de.previewUrl)),f([]),m(""),g([]),y(""),k(""),w(""),N(""),T(""),z("default"),R([]),G(!1),J(null),se(!1),C(void 0),A(ps),o(`Created ${V.id}`,"success"),n()}catch($e){o(je($e)||"Failed to create task","error")}finally{v(!1)}}},[d,h,p,b,S,M,_,x,r,o,n,s,I,L,E,B,j,X,$]),ne=a.useCallback(le=>{le.key==="Escape"&&(le.preventDefault(),ae())},[ae]),Pe=(j?W.find(le=>le.id===j):void 0)?.name??j,ce=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:ie,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>ve(le=>!le),disabled:x,"data-testid":"dep-trigger",children:h.length>0?`${h.length} selected`:"Add dependencies"}),ee&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:ue,onChange:le=>ye(le.target.value),onClick:le=>le.stopPropagation()}),_e.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):_e.map(le=>t.jsxs("div",{className:`dep-dropdown-item${h.includes(le.id)?" selected":""}`,onClick:()=>{g(h.includes(le.id)?h.filter($e=>$e!==le.id):[...h,le.id]),ve(!1),ye("")},onMouseDown:$e=>$e.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:le.id}),t.jsx("span",{className:"dep-dropdown-title",children:Fe(le.title||le.description||le.id,30)})]},le.id))]})]}),h.length>0&&t.jsx("div",{className:"selected-deps",children:h.map(le=>t.jsxs("span",{className:"dep-chip",children:[le,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>g(h.filter($e=>$e!==le)),disabled:x,children:"×"})]},le))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Assign Agent"}),t.jsxs("div",{className:"agent-trigger-wrap",ref:Ne,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{he?se(!1):Ge()},disabled:x,"data-testid":"new-task-agent-button",children:[t.jsx(pn,{size:12,style:{verticalAlign:"middle"}}),Pe?` ${Pe}`:" Assign agent"]}),he&&t.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:le=>le.preventDefault(),children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),fe&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!fe&&W.filter(le=>le.state!=="terminated").map(le=>t.jsxs("div",{className:`dep-dropdown-item${j===le.id?" selected":""}`,onMouseDown:$e=>$e.preventDefault(),onClick:()=>{J(le.id===j?null:le.id),se(!1)},"data-testid":`agent-option-${le.id}`,children:[t.jsx(pn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:le.role}),t.jsx("span",{className:"dep-dropdown-title",children:le.name})]},le.id)),!fe&&W.filter(le=>le.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),j&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:le=>le.preventDefault(),onClick:()=>{J(null),se(!1)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return e?t.jsx("div",{className:"modal-overlay open",onClick:ae,onKeyDown:ne,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:le=>le.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:"New Task"}),t.jsx("button",{className:"modal-close",onClick:ae,disabled:x,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!Be&&t.jsx(Hf,{hasAiProvider:Me,hasGithub:ze}),t.jsx(Pf,{mode:"create",description:d,onDescriptionChange:m,dependencies:h,onDependenciesChange:g,executorModel:b,onExecutorModelChange:y,validatorModel:S,onValidatorModelChange:k,presetMode:I,onPresetModeChange:z,selectedPresetId:L,onSelectedPresetIdChange:T,selectedWorkflowSteps:E,onWorkflowStepsChange:Je,onDefaultOnApplied:Ye,pendingImages:p,onImagesChange:f,tasks:i,projectId:s,disabled:x,addToast:o,isActive:e,onPlanningMode:l,onSubtaskBreakdown:c,onClose:ae,planningModel:M,onPlanningModelChange:w,thinkingLevel:_,onThinkingLevelChange:N,reviewLevel:X,onReviewLevelChange:C,priority:$,onPriorityChange:A,renderBelowPrimary:ce,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:ae,disabled:x,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:be,disabled:!d.trim()||x,children:x?"Creating...":"Create Task"})]})]})}):null}function Xs(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 sh(e,n){return!Number.isFinite(e)||!Number.isFinite(n)||n<=0?"—":`${(e/n*100).toFixed(1)}%`}function dR(e,n){if(n<=0)return"normal";const s=e/n;return s>=.85?"critical":s>=.65?"warning":"normal"}function uR(e,n){if(n<=0)return"normal";const s=e/n;return s>=.5?"critical":s>=.25?"warning":"normal"}function mR(e,n){if(n<=0)return"normal";const s=e/n;return s>=.9?"critical":s>=.75?"warning":"normal"}function Hl(e){return e==="critical"?"system-stats-modal__value--critical":e==="warning"?"system-stats-modal__value--warning":""}function hR(e){if(!e)return"Not yet";const n=new Date(e);return Number.isNaN(n.getTime())?"Not yet":n.toLocaleString()}function pR({isOpen:e,onClose:n,projectId:s}){const[i,r]=a.useState(null),[o,l]=a.useState(!1),[c,u]=a.useState(null),[d,m]=a.useState(!0),[h,g]=a.useState(90),[p,f]=a.useState(!1),[x,v]=a.useState(!1),[b,y]=a.useState(null),[S,k]=a.useState(null),[M,w]=a.useState(null),_=a.useCallback(async $=>{l(!0);try{const A=await vk(s);r(A),u(null),w(Date.now()),$?.preserveKillResult||y(null)}catch(A){u(A instanceof Error?A.message:"Failed to load system stats")}finally{l(!1)}},[s]);a.useEffect(()=>{if(!e)return;_();const $=window.setInterval(()=>{_()},5e3);return()=>{window.clearInterval($)}},[e,_]),a.useEffect(()=>{if(!e)return;(async()=>{try{const A=await Di();m(A.vitestAutoKillEnabled??!0),g(A.vitestKillThresholdPct??90),k(null)}catch(A){k(A instanceof Error?A.message:"Failed to load vitest settings")}})()},[e]),a.useEffect(()=>{if(!e)return;const $=A=>{A.key==="Escape"&&n()};return document.addEventListener("keydown",$),()=>document.removeEventListener("keydown",$)},[e,n]);const N=a.useMemo(()=>{if(!i)return[];const $=i.systemStats,A=Hl(dR($.heapUsed,$.heapLimit)),j=Hl(uR($.rss,$.systemTotalMem));return[{label:"RSS",value:Xs($.rss),detail:sh($.rss,$.systemTotalMem),className:j},{label:"Heap Used",value:Xs($.heapUsed),detail:`of ${Xs($.heapTotal)}`,className:A},{label:"Heap Limit",value:Xs($.heapLimit),detail:"V8 limit"},{label:"External",value:Xs($.external)},{label:"Array Buffers",value:Xs($.arrayBuffers)}]},[i]),L=a.useCallback(async $=>{m($);try{await an({vitestAutoKillEnabled:$}),k(null)}catch(A){k(A instanceof Error?A.message:"Failed to save vitest settings")}},[]),T=a.useCallback(async $=>{const A=Math.min(99,Math.max(50,Number.isFinite($)?Math.round($):90));g(A);try{await an({vitestKillThresholdPct:A}),k(null)}catch(j){k(j instanceof Error?j.message:"Failed to save vitest settings")}},[]),I=a.useCallback(async()=>{if(!p){if(!x){v(!0);return}f(!0);try{const $=await yk(s);y($),v(!1),await _({preserveKillResult:!0})}catch($){u($ instanceof Error?$.message:"Failed to kill vitest processes")}finally{f(!1)}}},[x,p,_,s]);if(!e)return null;const z=i?.systemStats,K=o&&!!i,P=M?`Updated ${new Date(M).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`:"Waiting for first update",E=i?.taskStats,R=z?z.systemTotalMem-z.systemFreeMem:0,B=z?Hl(mR(R,z.systemTotalMem)):"",G=i?.vitestProcessCount,X=b?b.killed>0?"system-stats-modal__kill-result system-stats-modal__kill-result--success":"system-stats-modal__kill-result system-stats-modal__kill-result--error":"",C=hR(i?.vitestLastAutoKillAt);return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"system-stats-modal-title",onClick:$=>{$.target===$.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(nr,{}),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:P})]}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>void _(),title:"Refresh","aria-label":"Refresh system stats",children:t.jsx(wn,{size:16,className:K?"system-stats-modal__refresh--spinning":void 0})}),t.jsx("button",{type:"button",className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(zt,{})})]})]}),o&&!i&&t.jsx("div",{className:"system-stats-modal__state",children:"Loading system stats…"}),c&&!i&&t.jsx("div",{className:"system-stats-modal__state system-stats-modal__state--error",role:"alert",children:c}),i&&t.jsxs("div",{className:"system-stats-modal__content",children:[t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Process stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Process"}),t.jsx("dl",{className:"system-stats-modal__grid",children:N.map($=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:$.label}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${$.className}`.trim(),children:$.value}),$.detail?t.jsx("span",{className:"system-stats-modal__detail",children:$.detail}):null]})]},$.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:z?.loadAvg.map($=>$.toFixed(2)).join(" ")??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Cores"}),t.jsx("dd",{children:z?.cpuCount??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Platform"}),t.jsx("dd",{children:z?.platform??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Node"}),t.jsx("dd",{children:z?.nodeVersion??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"PID"}),t.jsx("dd",{children:z?.pid??"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"System memory stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"System"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Memory Used"}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${B}`.trim(),children:z?Xs(R):"—"}),t.jsx("span",{className:"system-stats-modal__detail",children:z?`${sh(R,z.systemTotalMem)} of ${Xs(z.systemTotalMem)}`:""})]})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Memory Free"}),t.jsx("dd",{children:z?Xs(z.systemFreeMem):"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Task stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Tasks"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Total"}),t.jsx("dd",{children:E?.total??0})]}),Object.entries(E?.byColumn??{}).map(([$,A])=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:$}),t.jsx("dd",{children:A})]},$))]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Agent stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Agents"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"idle"}),t.jsx("dd",{children:E?.agents.idle??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"active"}),t.jsx("dd",{children:E?.agents.active??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"running"}),t.jsx("dd",{children:E?.agents.running??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"error"}),t.jsx("dd",{children:E?.agents.error??0})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Vitest controls",children:[t.jsxs("h3",{className:"system-stats-modal__section-title system-stats-modal__section-title--with-icon",children:[t.jsx(bb,{}),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:G??"—"})]})}),t.jsxs("div",{className:"system-stats-modal__vitest-controls",children:[t.jsx("div",{className:"system-stats-modal__kill-row",children:t.jsxs("button",{type:"button",className:"btn btn-danger",onClick:()=>void I(),disabled:p||G===0,children:[t.jsx(jb,{}),t.jsx("span",{children:x?"Confirm Kill?":"Kill Vitest Processes"})]})}),t.jsxs("label",{className:"system-stats-modal__toggle-row",children:[t.jsx("input",{type:"checkbox",checked:d,onChange:$=>{L($.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:$=>{const A=Number.parseInt($.target.value,10);T(Number.isNaN(A)?90:A)}}),t.jsx("input",{id:"vitest-threshold-number",type:"number",className:"input",min:50,max:99,value:h,"aria-label":"Kill threshold (%)",onChange:$=>{const A=Number.parseInt($.target.value,10);T(Number.isNaN(A)?90:A)},onBlur:()=>{T(h)}})]})]}),b&&t.jsxs("p",{className:X,children:["Killed ",b.killed," processes"]}),t.jsxs("p",{className:"system-stats-modal__last-kill",children:["Last auto-kill: ",C]}),S&&t.jsx("p",{className:"system-stats-modal__kill-result system-stats-modal__kill-result--error",children:S})]})]})]}),c&&i&&t.jsxs("div",{className:"system-stats-modal__footer-error",children:["Latest refresh failed: ",c]})]})})}const fR=5e3;function gR(e={}){const{projectId:n,type:s,limit:i=50,autoRefresh:r=!0,useCentralFeed:o=!1}=e,[l,c]=a.useState([]),[u,d]=a.useState(!1),[m,h]=a.useState(null),[g,p]=a.useState(!1),f=a.useRef(null),x=a.useRef(void 0),v=a.useCallback(async()=>{try{d(!0),h(null);let S;o?S=await Vd({limit:i,projectId:n,type:s}):S=(await zd({limit:i,type:s,projectId:n})).map(M=>({...M,projectId:n??"",projectName:""})),c(S),p(S.length===i),S.length>0&&(x.current=S[S.length-1].timestamp)}catch(S){h(S instanceof Error?S.message:"Failed to load activity log")}finally{d(!1)}},[i,n,s,o]),b=a.useCallback(async()=>{if(x.current)try{d(!0);let S;o?S=await Vd({limit:i,projectId:n,type:s,since:x.current}):S=(await zd({limit:i,type:s,since:x.current,projectId:n})).map(M=>({...M,projectId:n??"",projectName:""})),c(k=>[...k,...S]),p(S.length===i),S.length>0&&(x.current=S[S.length-1].timestamp)}catch(S){h(S instanceof Error?S.message:"Failed to load more entries")}finally{d(!1)}},[i,n,s,o]),y=a.useCallback(()=>{c([]),p(!1),x.current=void 0},[]);return a.useEffect(()=>{v()},[v]),a.useEffect(()=>{if(r)return f.current=setInterval(()=>{v()},fR),()=>{f.current&&(clearInterval(f.current),f.current=null)}},[r,v]),{entries:l,loading:u,error:m,refresh:v,clear:y,hasMore:g,loadMore:b}}const ql={"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"},xR={"task:created":t.jsx(Xt,{size:14,className:"activity-icon created"}),"task:moved":t.jsx(dr,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx(wn,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(zt,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx(un,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(ur,{size:14,className:"activity-icon failed"}),"settings:updated":t.jsx(Ja,{size:14,className:"activity-icon settings"})};function bR(e){const n=new Date(e),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),o=Math.floor(i/36e5),l=Math.floor(i/864e5);return r<1?"Just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function vR({isOpen:e,onClose:n,tasks:s,onOpenTaskDetail:i,projectId:r,projects:o=[],onProjectFilterChange:l,currentProject:c}){const[u,d]=a.useState("all"),[m,h]=a.useState(r||"all"),[g,p]=a.useState(!1);a.useEffect(()=>{h(r||"all")},[r]);const f=u==="all"?void 0:u,x=m==="all"?void 0:m,v=!c&&o.length>0,{entries:b,loading:y,error:S,refresh:k,hasMore:M}=gR({projectId:x,type:f,limit:100,autoRefresh:e,useCentralFeed:v}),w=b.map(I=>({id:I.id,timestamp:I.timestamp,type:I.type,taskId:I.taskId,taskTitle:I.taskTitle,details:I.details,metadata:I.metadata,projectId:I.projectId,projectName:I.projectName})),_=async()=>{try{await Gy(),k(),p(!1)}catch{p(!1)}},N=I=>{i&&i(I)},L=I=>{h(I),l?.(I==="all"?void 0:I)};a.useEffect(()=>{if(!e)return;const I=z=>{z.key==="Escape"&&(g?p(!1):n())};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[e,n,g]);const T=u!=="all"||m!=="all";return e?t.jsx("div",{className:"modal-overlay open",onClick:I=>{I.target===I.currentTarget&&n()},role:"dialog","aria-modal":"true","data-testid":"activity-log-modal-overlay",children:t.jsxs("div",{className:"modal modal-lg activity-log-modal","data-testid":"activity-log-modal",children:[t.jsxs("div",{className:"modal-header activity-log-header",children:[t.jsxs("div",{className:"activity-log-title",children:[t.jsx(tr,{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(Dn,{size:14}),t.jsxs("select",{value:m,onChange:I=>L(I.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[t.jsx("option",{value:"all",children:"All Projects"}),o.map(I=>t.jsx("option",{value:I.id,children:I.name},I.id))]})]}),t.jsxs("div",{className:"activity-log-filter",children:[t.jsx(to,{size:14}),t.jsxs("select",{value:u,onChange:I=>d(I.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:"All Events"}),Object.entries(ql).map(([I,z])=>t.jsx("option",{value:I,children:z},I))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>k(),title:"Refresh","data-testid":"activity-refresh",children:y?t.jsx(rt,{size:14,className:"spin"}):t.jsx(wn,{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(Jt,{size:14})})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",title:"Close","data-testid":"activity-close",children:"×"})]}),T&&t.jsxs("div",{className:"activity-log-active-filters",children:[t.jsx("span",{className:"activity-log-filter-label",children:"Active filters:"}),m!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Project: ",o.find(I=>I.id===m)?.name||m]}),u!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",ql[u]]}),t.jsx("button",{className:"activity-log-clear-filters",onClick:()=>{d("all"),h("all"),l?.(void 0)},children:"Clear all"})]}),t.jsxs("div",{className:"activity-log-content","data-testid":"activity-log-content",children:[S&&t.jsxs("div",{className:"activity-log-error","data-testid":"activity-error",children:[t.jsx(Zn,{size:16}),t.jsx("span",{children:S})]}),w.length===0&&!y&&!S&&t.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[t.jsx(tr,{size:48,className:"activity-log-empty-icon"}),t.jsx("p",{children:T?"No activity matches the current filters":"No activity recorded yet"}),T&&t.jsx("button",{className:"btn btn-secondary",onClick:()=>{d("all"),h("all"),l?.(void 0)},children:"Clear Filters"})]}),t.jsx("div",{className:"activity-log-list",children:w.map(I=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:xR[I.type]}),t.jsxs("div",{className:"activity-log-entry-content",children:[t.jsxs("div",{className:"activity-log-entry-header",children:[t.jsx("span",{className:"activity-log-entry-type",children:ql[I.type]}),t.jsx("span",{className:"activity-log-entry-time",children:bR(I.timestamp)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[I.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>N(I.taskId),"data-testid":"activity-task-link",children:I.taskId}),I.taskTitle&&t.jsx("span",{className:"activity-log-task-title",children:I.taskTitle}),t.jsx("span",{className:"activity-log-entry-text",children:I.details})]}),I.metadata&&Object.keys(I.metadata).length>0&&t.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof I.metadata.from=="string"&&typeof I.metadata.to=="string"&&t.jsxs("span",{className:"activity-log-metadata-item",children:[I.metadata.from," → ",I.metadata.to]}),typeof I.metadata.merged=="boolean"&&t.jsx("span",{className:`activity-log-metadata-item ${I.metadata.merged?"success":"error"}`,children:I.metadata.merged?"Merged":"Not merged"})]})]})]},I.id))}),M&&!y&&t.jsx("button",{className:"activity-log-load-more",onClick:k,"data-testid":"activity-load-more",children:"Load More"}),y&&w.length>0&&t.jsx("div",{className:"activity-log-loading",children:t.jsx(rt,{size:20,className:"spin"})})]}),g&&t.jsx("div",{className:"activity-log-confirm-overlay",children:t.jsxs("div",{className:"activity-log-confirm-dialog",children:[t.jsx("h3",{children:"Clear Activity Log?"}),t.jsx("p",{children:"This will permanently delete all activity log entries. This action cannot be undone."}),t.jsxs("div",{className:"activity-log-confirm-actions",children:[t.jsx("button",{className:"activity-log-confirm-cancel",onClick:()=>p(!1),children:"Cancel"}),t.jsx("button",{className:"activity-log-confirm-clear",onClick:_,children:"Clear Log"})]})]})})]})}):null}const Fa=[{id:"status",label:"Status",icon:zh},{id:"changes",label:"Changes",icon:Th},{id:"commits",label:"Commits",icon:er},{id:"branches",label:"Branches",icon:Vs},{id:"worktrees",label:"Worktrees",icon:Nx},{id:"stashes",label:"Stashes",icon:vo},{id:"remotes",label:"Remotes",icon:$h}];function ih({status:e}){switch(e){case"added":case"untracked":return t.jsx(ax,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(Ph,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(nx,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return t.jsx(Ri,{size:14,className:"gm-file-icon gm-file-renamed"});default:return t.jsx(ox,{size:14,className:"gm-file-icon"})}}function ah({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 yR(e){return a.useCallback(async(n,s)=>{try{await navigator.clipboard.writeText(n),e(`Copied ${s||"to clipboard"}`,"success")}catch{e("Failed to copy","error")}},[e])}function ua(e){if(!e)return"—";const n=new Date(e);if(isNaN(n.getTime()))return"—";const i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4);if(r<1)return"just now";if(r<60)return`${r}m ago`;const o=Math.floor(r/60);if(o<24)return`${o}h ago`;const l=Math.floor(o/24);return l<30?`${l}d ago`:n.toLocaleDateString()}function kR({isOpen:e,onClose:n,tasks:s,addToast:i,projectId:r}){const o=Is(),[l,c]=a.useState("status"),[u,d]=a.useState(!1),[m,h]=a.useState(null),g=a.useRef(null);Gs(g,e,"fusion:git-modal-size");const p=fi(n),f=yR(i),[x,v]=a.useState(null),[b,y]=a.useState([]),[S,k]=a.useState(new Set),[M,w]=a.useState(""),[_,N]=a.useState(!1),[L,T]=a.useState(null),[I,z]=a.useState(!1),[K,P]=a.useState(null),[E,R]=a.useState(null),B=a.useRef(0),[G,X]=a.useState([]),[C,$]=a.useState(null),[A,j]=a.useState(null),[J,W]=a.useState(!1),[oe,he]=a.useState(20),[se,fe]=a.useState(""),[U,Ne]=a.useState([]),[ee,ve]=a.useState(""),[ue,ye]=a.useState(""),[ie,Me]=a.useState(""),[ze,Be]=a.useState(null),[Je,Ye]=a.useState([]),[Ge,it]=a.useState(!1),[_e,Fe]=a.useState(null),[ae,be]=a.useState(null),[ne,Ie]=a.useState(!1),[Pe,ce]=a.useState([]),[le,$e]=a.useState([]),[at,tt]=a.useState(""),[V,de]=a.useState(null),[Z,we]=a.useState(null),[pe,Te]=a.useState(null),Qe=a.useCallback(async()=>{if(e){d(!0),h(null);try{switch(l){case"status":{const H=await Rs(r);v(H);break}case"changes":{const[H,ge]=await Promise.all([Rs(r),Vi(r)]);v(H),y(ge),k(new Set),R(null),T(null),P(null);break}case"commits":{const H=await ty(oe,r);X(H);break}case"branches":{const[H,ge]=await Promise.all([Sa(r),Rs(r)]);Ne(H),v(ge);break}case"worktrees":{const H=await ay(r);ce(H);break}case"stashes":{const H=await Rr(r);$e(H);break}case"remotes":{const H=await Rs(r);v(H);break}}}catch(H){h(je(H)||"Failed to fetch git data"),i(je(H)||"Failed to fetch git data","error")}finally{d(!1)}}},[l,e,oe,i,r]);a.useEffect(()=>{e&&Qe()},[Qe,e]),a.useEffect(()=>{if(!e)return;const H=ge=>{if(ge.key==="Escape"){n();return}if((ge.key==="ArrowUp"||ge.key==="ArrowDown")&&ge.altKey){ge.preventDefault();const me=Fa.findIndex(We=>We.id===l);ge.key==="ArrowUp"&&me>0?c(Fa[me-1].id):ge.key==="ArrowDown"&&me<Fa.length-1&&c(Fa[me+1].id)}};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[e,n,l]);const Ee=a.useCallback(async H=>{try{await Pd(H,r),i(`Staged ${H.length} file(s)`,"success");const ge=await Vi(r);y(ge),k(new Set),R(null),T(null),P(null)}catch(ge){i(je(ge)||"Failed to stage files","error")}},[i,r]),Re=a.useCallback(async H=>{try{await fy(H,r),i(`Unstaged ${H.length} file(s)`,"success");const ge=await Vi(r);y(ge),k(new Set),R(null),T(null),P(null)}catch(ge){i(je(ge)||"Failed to unstage files","error")}},[i,r]),Le=a.useCallback(async H=>{if(await o.confirm({title:"Discard Changes",message:`Discard changes to ${H.length} file(s)? This cannot be undone.`,danger:!0}))try{await gy(H,r),i(`Discarded changes to ${H.length} file(s)`,"success");const[me,We]=await Promise.all([Vi(r),Rs(r)]);y(me),v(We),k(new Set),R(null),T(null),P(null)}catch(me){i(je(me)||"Failed to discard changes","error")}},[i,r,confirm]),ct=a.useCallback(async H=>{if(H.preventDefault(),!!M.trim()){N(!0);try{const ge=await Id(M.trim(),r);i(`Committed: ${ge.hash}`,"success"),w("");const[me,We]=await Promise.all([Vi(r),Rs(r)]);y(me),v(We),R(null),T(null),P(null)}catch(ge){i(je(ge)||"Failed to commit","error")}finally{N(!1)}}},[M,i,r]),Se=a.useCallback(async()=>{if(M.trim()){N(!0);try{const H=b.filter(dt=>!dt.staged).map(dt=>dt.file);H.length>0&&await Pd(H,r);const ge=await Id(M.trim(),r);i(`Committed: ${ge.hash}`,"success"),w("");const[me,We]=await Promise.all([Vi(r),Rs(r)]);y(me),v(We),R(null),T(null),P(null)}catch(H){i(je(H)||"Failed to commit","error")}finally{N(!1)}}},[M,b,i,r]),mt=a.useCallback(async(H,ge)=>{R({file:H,staged:ge}),z(!0),P(null);const me=B.current+1;B.current=me;try{const We=await py(H,ge,r);if(B.current!==me)return;T(We)}catch(We){if(B.current!==me)return;const dt=je(We)||"Failed to load file diff";T(null),P(dt),i(dt,"error")}finally{B.current===me&&z(!1)}},[i,r]),gt=a.useCallback(H=>{k(ge=>{const me=new Set(ge);return me.has(H)?me.delete(H):me.add(H),me})},[]),wt=a.useCallback(async H=>{if(C===H){$(null),j(null);return}$(H),W(!0);try{const ge=await ro(H,r);j(ge)}catch(ge){i(je(ge)||"Failed to load diff","error"),j(null)}finally{W(!1)}},[C,i,r]),yt=a.useCallback(()=>{he(H=>Math.min(H+20,100))},[]),kt=a.useMemo(()=>{if(!se.trim())return G;const H=se.toLowerCase();return G.filter(ge=>ge.message.toLowerCase().includes(H)||ge.author.toLowerCase().includes(H)||ge.shortHash.toLowerCase().includes(H))},[G,se]),Ct=a.useCallback(async H=>{if(H.preventDefault(),!!ee.trim()){d(!0);try{await ry(ee.trim(),ue.trim()||void 0,r),i(`Created branch ${ee}`,"success"),ve(""),ye("");const ge=await Sa(r);Ne(ge)}catch(ge){i(je(ge)||"Failed to create branch","error")}finally{d(!1)}}},[ee,ue,i,r]),Rt=a.useCallback(async H=>{d(!0);try{await oy(H,r),i(`Switched to ${H}`,"success");const[ge,me]=await Promise.all([Rs(r),Sa(r)]);v(ge),Ne(me)}catch(ge){i(je(ge)||"Failed to checkout branch","error")}finally{d(!1)}},[i,r]),Ft=a.useCallback(async H=>{if(await o.confirm({title:"Delete Branch",message:`Delete branch "${H}"?`,danger:!0})){d(!0);try{await Td(H,void 0,r),i(`Deleted branch ${H}`,"success");const me=await Sa(r);Ne(me)}catch(me){if(je(me).includes("not fully merged")){if(await o.confirm({title:"Force Delete Branch",message:"Branch has unmerged commits. Force delete?",danger:!0}))try{await Td(H,!0,r),i(`Force deleted branch ${H}`,"success");const dt=await Sa(r);Ne(dt)}catch(dt){i(je(dt)||"Failed to delete branch","error")}}else i(je(me)||"Failed to delete branch","error")}finally{d(!1)}}},[i,r,confirm]),Ut=a.useMemo(()=>{if(!ie.trim())return U;const H=ie.toLowerCase();return U.filter(ge=>ge.name.toLowerCase().includes(H))},[U,ie]),St=a.useCallback(async H=>{if(ze===H){Be(null),Ye([]),Fe(null),be(null);return}Be(H),Ye([]),Fe(null),be(null),it(!0);try{const ge=await iy(H,10,r);Ye(ge)}catch{Ye([])}finally{it(!1)}},[ze,r]),Et=a.useCallback(async H=>{if(_e===H){Fe(null),be(null);return}Fe(H),be(null),Ie(!0);try{const ge=await ro(H,r);be(ge)}catch{be(null)}finally{Ie(!1)}},[_e,r]),It=a.useCallback(()=>{Be(null),Ye([]),Fe(null),be(null)},[]),Mt=a.useCallback(async H=>{H.preventDefault(),de("create");try{await uy(at.trim()||void 0,r),i("Changes stashed","success"),tt("");const ge=await Rr(r);$e(ge)}catch(ge){i(je(ge)||"Failed to stash changes","error")}finally{de(null)}},[at,i,r]),Kt=a.useCallback(async(H,ge=!1)=>{de(`apply-${H}`);try{await my(H,ge,r),i(ge?"Stash popped":"Stash applied","success");const me=await Rr(r);$e(me)}catch(me){i(je(me)||"Failed to apply stash","error")}finally{de(null)}},[i,r]),Ot=a.useCallback(async H=>{if(await o.confirm({title:"Drop Stash",message:`Drop stash@{${H}}? This cannot be undone.`,danger:!0})){de(`drop-${H}`);try{await hy(H,r),i("Stash dropped","success");const me=await Rr(r);$e(me)}catch(me){i(je(me)||"Failed to drop stash","error")}finally{de(null)}}},[i,r,confirm]),xe=a.useCallback(async()=>{we("fetch");try{const H=await ly(void 0,r);Te(H),i(H.message||"Fetch completed",H.fetched?"success":"info");const ge=await Rs(r);v(ge)}catch(H){i(je(H)||"Fetch failed","error")}finally{we(null)}},[i,r]),st=a.useCallback(async()=>{we("pull");try{const H=await cy(r);Te(H),H.conflict?i("Merge conflict detected. Resolve manually.","error"):i(H.message||"Pull completed","success");const ge=await Rs(r);v(ge)}catch(H){i(je(H)||"Pull failed","error")}finally{we(null)}},[i,r]),Ve=a.useCallback(async()=>{we("push");try{const H=await dy(r);Te(H),i(H.message||"Push completed","success");const ge=await Rs(r);v(ge)}catch(H){i(je(H)||"Push failed","error")}finally{we(null)}},[i,r]),Y=a.useMemo(()=>b.filter(H=>H.staged),[b]),F=a.useMemo(()=>b.filter(H=>!H.staged),[b]);return e?t.jsx("div",{className:"modal-overlay open",...p,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal gm-modal",ref:g,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h3",{children:[t.jsx(sc,{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:Qe,disabled:u,title:"Refresh",children:t.jsx(wn,{size:14,className:u?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(zt,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:Fa.map(H=>{const ge=H.icon;return t.jsxs("button",{role:"tab","aria-selected":l===H.id,className:`gm-nav-item${l===H.id?" active":""}`,onClick:()=>c(H.id),children:[t.jsx(ge,{size:16}),t.jsx("span",{className:"gm-nav-label",children:H.label})]},H.id)})}),t.jsxs("div",{className:"gm-content",role:"tabpanel",children:[u&&t.jsxs("div",{className:"gm-loading",children:[t.jsx(rt,{size:24,className:"spin"}),t.jsx("span",{children:"Loading..."})]}),m&&!u&&t.jsxs("div",{className:"gm-error",children:[t.jsx(Zn,{size:18}),t.jsx("span",{children:m}),t.jsx("button",{className:"btn btn-sm",onClick:Qe,children:"Retry"})]}),l==="status"&&!u&&x&&t.jsx(jR,{status:x,copyToClipboard:f}),l==="changes"&&!u&&t.jsx(wR,{status:x,stagedFiles:Y,unstagedFiles:F,selectedFiles:S,toggleFileSelection:gt,onStageFiles:Ee,onUnstageFiles:Re,onDiscardChanges:Le,onSelectDiffFile:mt,selectedDiffTarget:E,changeDiff:L,loadingChangeDiff:I,changeDiffError:K,commitMessage:M,setCommitMessage:w,onCommit:ct,onStageAllAndCommit:Se,committing:_}),l==="commits"&&!u&&t.jsx(NR,{commits:kt,commitSearch:se,setCommitSearch:fe,selectedCommit:C,commitDiff:A,loadingDiff:J,onCommitClick:wt,onLoadMore:yt,canLoadMore:G.length>=oe&&oe<100,copyToClipboard:f}),l==="branches"&&!u&&t.jsx(SR,{branches:Ut,branchSearch:ie,setBranchSearch:Me,newBranchName:ee,setNewBranchName:ve,branchBase:ue,setBranchBase:ye,onCreateBranch:Ct,onCheckoutBranch:Rt,onDeleteBranch:Ft,loading:u,allBranches:U,selectedBranch:ze,branchCommits:Je,loadingBranchCommits:Ge,expandedBranchCommit:_e,branchCommitDiff:ae,loadingBranchCommitDiff:ne,onSelectBranch:St,onBranchCommitClick:Et,onCloseBranchDetails:It}),l==="worktrees"&&!u&&t.jsx(CR,{worktrees:Pe}),l==="stashes"&&!u&&t.jsx(ER,{stashes:le,stashMessage:at,setStashMessage:tt,onCreateStash:Mt,onApplyStash:Kt,onDropStash:Ot,stashLoading:V}),l==="remotes"&&!u&&t.jsx(MR,{status:x,remoteLoading:Z,lastRemoteResult:pe,onFetch:xe,onPull:st,onPush:Ve,addToast:i,projectId:r,copyToClipboard:f})]})]})]})}):null}function jR({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(Vs,{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(Ai,{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(Zn,{size:12}),"Modified"]}):t.jsxs(t.Fragment,{children:[t.jsx(un,{size:12}),"Clean"]})})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Remote Sync"}),t.jsxs("span",{className:"gm-status-value",children:[e.ahead>0&&t.jsxs("span",{className:"gm-ahead",title:`${e.ahead} commit(s) ahead`,children:[t.jsx(Mi,{size:12}),e.ahead]}),e.behind>0&&t.jsxs("span",{className:"gm-behind",title:`${e.behind} commit(s) behind`,children:[t.jsx(cr,{size:12}),e.behind]}),e.ahead===0&&e.behind===0&&t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(un,{size:12}),"Up to date"]})]})]})]})]})}function wR({status:e,stagedFiles:n,unstagedFiles:s,selectedFiles:i,toggleFileSelection:r,onStageFiles:o,onUnstageFiles:l,onDiscardChanges:c,onSelectDiffFile:u,selectedDiffTarget:d,changeDiff:m,loadingChangeDiff:h,changeDiffError:g,commitMessage:p,setCommitMessage:f,onCommit:x,onStageAllAndCommit:v,committing:b}){const y=s.filter(k=>i.has(`unstaged:${k.file}`)),S=n.filter(k=>i.has(`staged:${k.file}`));return t.jsxs("div",{className:"gm-panel","data-testid":"changes-panel",children:[e&&t.jsxs("div",{className:"gm-changes-header",children:[t.jsxs("span",{className:"gm-branch-indicator",children:[t.jsx(Vs,{size:14}),e.branch]}),e.isDirty&&t.jsx("span",{className:"gm-dirty-badge",children:"Modified"})]}),t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Unstaged Changes (",s.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[y.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>o(y.map(k=>k.file)),title:"Stage selected",children:[t.jsx(Xt,{size:12})," Stage (",y.length,")"]}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>c(y.map(k=>k.file)),title:"Discard selected",children:t.jsx(ur,{size:12})})]}),s.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>o(s.map(k=>k.file)),title:"Stage all",children:"Stage All"})]})]}),t.jsx("div",{className:"gm-file-list",children:s.length===0?t.jsx("div",{className:"gm-empty",children:"No unstaged changes"}):s.map(k=>{const M=d?.file===k.file&&d.staged===!1;return t.jsxs("div",{className:`gm-file-item${M?" active":""}`,onClick:()=>u(k.file,!1),role:"button",tabIndex:0,onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),u(k.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:w=>w.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`unstaged:${k.file}`),onChange:()=>r(`unstaged:${k.file}`)})}),t.jsx(ih,{status:k.status}),t.jsx("span",{className:"gm-file-name",title:k.file,children:k.file}),t.jsx(ah,{status:k.status}),t.jsx("button",{className:"gm-icon-btn",onClick:w=>{w.stopPropagation(),o([k.file])},title:"Stage file",children:t.jsx(Xt,{size:12})})]},`unstaged:${k.file}`)})})]}),t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Staged Changes (",n.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[S.length>0&&t.jsxs("button",{className:"btn btn-sm",onClick:()=>l(S.map(k=>k.file)),title:"Unstage selected",children:["Unstage (",S.length,")"]}),n.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(n.map(k=>k.file)),title:"Unstage all",children:"Unstage All"})]})]}),t.jsx("div",{className:"gm-file-list",children:n.length===0?t.jsx("div",{className:"gm-empty",children:"No staged changes"}):n.map(k=>{const M=d?.file===k.file&&d.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${M?" active":""}`,onClick:()=>u(k.file,!0),role:"button",tabIndex:0,onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),u(k.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:w=>w.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`staged:${k.file}`),onChange:()=>r(`staged:${k.file}`)})}),t.jsx(ih,{status:k.status}),t.jsx("span",{className:"gm-file-name",title:k.file,children:k.file}),t.jsx(ah,{status:k.status}),t.jsx("button",{className:"gm-icon-btn",onClick:w=>{w.stopPropagation(),l([k.file])},title:"Unstage file",children:t.jsx(zt,{size:12})})]},`staged:${k.file}`)})})]}),(d||h||m||g)&&t.jsxs("div",{className:"gm-diff-section",children:[d&&t.jsxs("div",{className:"gm-diff-target",children:[t.jsx(Th,{size:14}),t.jsxs("span",{children:[d.staged?"Staged":"Unstaged"," diff: "]}),t.jsx("code",{children:d.file})]}),h&&t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(rt,{size:16,className:"spin"}),"Loading diff..."]}),g&&!h&&t.jsx("div",{className:"gm-diff-error",children:g}),m&&!h&&t.jsxs("div",{className:"gm-diff-viewer",children:[m.stat&&t.jsx("pre",{className:"gm-diff-stat",children:m.stat}),t.jsx("pre",{className:"gm-diff-patch",children:m.patch})]})]}),t.jsxs("form",{className:"gm-commit-form",onSubmit:x,children:[t.jsx("textarea",{className:"gm-commit-input",placeholder:"Commit message...",value:p,onChange:k=>f(k.target.value),rows:3,disabled:b}),t.jsxs("div",{className:"gm-commit-actions",children:[t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:b||!p.trim()||n.length===0,title:n.length===0?"No staged changes to commit":"Commit staged changes",children:[b?t.jsx(rt,{size:14,className:"spin"}):t.jsx(Ei,{size:14}),"Commit"]}),s.length>0&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:v,disabled:b||!p.trim(),title:"Stage all and commit",children:"Stage All & Commit"})]})]})]})}function NR({commits:e,commitSearch:n,setCommitSearch:s,selectedCommit:i,commitDiff:r,loadingDiff:o,onCommitClick:l,onLoadMore:c,canLoadMore:u,copyToClipboard:d}){return t.jsxs("div",{className:"gm-panel","data-testid":"commits-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Commits"}),t.jsxs("div",{className:"gm-search-box",children:[t.jsx(ea,{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:ua(m.date)}),m.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),t.jsx("div",{className:"gm-commit-actions-row",children:t.jsx("button",{className:"gm-icon-btn",onClick:()=>d(m.hash,"commit hash"),title:"Copy full hash",children:t.jsx(Ai,{size:12})})}),i===m.hash&&t.jsx("div",{className:"gm-commit-diff",children:o?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(rt,{size:16,className:"spin"}),"Loading diff..."]}):r?t.jsxs(t.Fragment,{children:[r.stat&&t.jsx("pre",{className:"gm-diff-stat",children:r.stat}),t.jsx("pre",{className:"gm-diff-patch",children:r.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]})]},m.hash))}),u&&t.jsx("button",{className:"gm-load-more",onClick:c,children:"Load more commits"})]})}function SR({branches:e,branchSearch:n,setBranchSearch:s,newBranchName:i,setNewBranchName:r,branchBase:o,setBranchBase:l,onCreateBranch:c,onCheckoutBranch:u,onDeleteBranch:d,loading:m,allBranches:h,selectedBranch:g,branchCommits:p,loadingBranchCommits:f,expandedBranchCommit:x,branchCommitDiff:v,loadingBranchCommitDiff:b,onSelectBranch:y,onBranchCommitClick:S,onCloseBranchDetails:k}){return t.jsxs("div",{className:"gm-panel","data-testid":"branches-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Branches"}),t.jsxs("div",{className:"gm-search-box",children:[t.jsx(ea,{size:14}),t.jsx("input",{type:"text",placeholder:"Filter branches...",value:n,onChange:M=>s(M.target.value)})]})]}),t.jsxs("form",{className:"gm-create-form",onSubmit:c,children:[t.jsx("input",{type:"text",placeholder:"New branch name",value:i,onChange:M=>r(M.target.value),disabled:m}),t.jsxs("select",{value:o,onChange:M=>l(M.target.value),disabled:m,className:"gm-branch-select",children:[t.jsx("option",{value:"",children:"Base: HEAD"}),h.map(M=>t.jsx("option",{value:M.name,children:M.name},M.name))]}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:m||!i.trim(),children:[t.jsx(Xt,{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(M=>t.jsxs("div",{children:[t.jsxs("div",{className:`gm-branch-item${M.isCurrent?" current":""}${g===M.name?" selected":""}`,onClick:()=>y(M.name),children:[t.jsxs("div",{className:"gm-branch-info",children:[t.jsxs("span",{className:"gm-branch-name",children:[M.isCurrent&&t.jsx(Rn,{size:14,className:"gm-current-icon"}),M.name]}),M.remote&&t.jsxs("span",{className:"gm-branch-remote",children:["→ ",M.remote]}),M.lastCommitDate&&t.jsx("span",{className:"gm-branch-date",children:ua(M.lastCommitDate)})]}),t.jsx("div",{className:"gm-branch-actions",children:!M.isCurrent&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:w=>{w.stopPropagation(),u(M.name)},disabled:m,title:"Checkout",children:t.jsx(Vs,{size:14})}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:w=>{w.stopPropagation(),d(M.name)},disabled:m,title:"Delete",children:t.jsx(Jt,{size:14})})]})})]}),g===M.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(er,{size:14}),"Commits on ",M.name]}),t.jsx("button",{className:"gm-icon-btn",onClick:k,title:"Close","data-testid":"close-branch-details",children:t.jsx(zt,{size:14})})]}),f?t.jsxs("div",{className:"gm-branch-details-loading",children:[t.jsx(rt,{size:16,className:"spin"}),"Loading commits..."]}):p.length===0?t.jsx("div",{className:"gm-empty",children:"No commits found"}):t.jsx("div",{className:"gm-branch-commits-list",children:p.map(w=>t.jsxs("div",{className:"gm-branch-commit",children:[t.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>S(w.hash),"data-testid":`branch-commit-${w.shortHash}`,children:[t.jsx("span",{className:"gm-commit-hash",children:w.shortHash}),t.jsx("span",{className:"gm-commit-message",title:w.message,children:w.message}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:w.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:ua(w.date)}),w.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),x===w.hash&&t.jsx("div",{className:"gm-commit-diff",children:b?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(rt,{size:16,className:"spin"}),"Loading diff..."]}):v?t.jsxs(t.Fragment,{children:[v.stat&&t.jsx("pre",{className:"gm-diff-stat",children:v.stat}),t.jsx("pre",{className:"gm-diff-patch",children:v.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},w.hash))})]})]},M.name))})]})}function CR({worktrees:e}){return t.jsxs("div",{className:"gm-panel","data-testid":"worktrees-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Worktrees"}),t.jsxs("div",{className:"gm-worktree-stats",children:[t.jsxs("span",{children:[e.length," total"]}),t.jsx("span",{className:"gm-stat-separator",children:"•"}),t.jsxs("span",{children:[e.filter(n=>n.taskId).length," in use"]})]})]}),t.jsx("div",{className:"gm-worktrees-list",children:e.map(n=>t.jsx("div",{className:`gm-worktree-item${n.isMain?" main":""}`,children:t.jsxs("div",{className:"gm-worktree-info",children:[t.jsxs("div",{className:"gm-worktree-path-row",children:[n.isMain&&t.jsx("span",{className:"gm-badge main",children:"main"}),n.isBare&&t.jsx("span",{className:"gm-badge bare",children:"bare"}),t.jsx("span",{className:"gm-worktree-path",title:n.path,children:n.path.split("/").pop()||n.path})]}),t.jsxs("div",{className:"gm-worktree-detail",children:[n.branch&&t.jsxs("span",{className:"gm-worktree-branch",children:[t.jsx(Vs,{size:12}),n.branch]}),n.taskId&&t.jsx("span",{className:"gm-worktree-task",children:n.taskId})]})]})},n.path))})]})}function ER({stashes:e,stashMessage:n,setStashMessage:s,onCreateStash:i,onApplyStash:r,onDropStash:o,stashLoading:l}){return t.jsxs("div",{className:"gm-panel","data-testid":"stashes-panel",children:[t.jsx("div",{className:"gm-panel-header",children:t.jsx("h4",{children:"Stashes"})}),t.jsxs("form",{className:"gm-create-form",onSubmit:i,children:[t.jsx("input",{type:"text",placeholder:"Stash message (optional)",value:n,onChange:c=>s(c.target.value),disabled:l!==null}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:l!==null,children:[l==="create"?t.jsx(rt,{size:14,className:"spin"}):t.jsx(vo,{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(Vs,{size:12}),c.branch]}),t.jsx("span",{children:ua(c.date)})]})]}),t.jsxs("div",{className:"gm-stash-actions",children:[t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>r(c.index,!1),disabled:l!==null,title:"Apply stash (keep)",children:l===`apply-${c.index}`?t.jsx(rt,{size:14,className:"spin"}):"Apply"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>r(c.index,!0),disabled:l!==null,title:"Pop stash (apply and drop)",children:"Pop"}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>o(c.index),disabled:l!==null,title:"Drop stash",children:l===`drop-${c.index}`?t.jsx(rt,{size:14,className:"spin"}):t.jsx(Jt,{size:14})})]})]},c.index))})]})}function MR({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:i,onPull:r,onPush:o,addToast:l,projectId:c,copyToClipboard:u}){const d=ne=>{try{return new URL(ne).hostname}catch{return ne.replace(/^git@/,"").split(":")[0]||ne}},[m,h]=a.useState([]),[g,p]=a.useState(!1),[f,x]=a.useState(null),[v,b]=a.useState(""),[y,S]=a.useState(""),[k,M]=a.useState(null),[w,_]=a.useState(""),[N,L]=a.useState(""),[T,I]=a.useState(!1),[z,K]=a.useState([]),[P,E]=a.useState(!1),[R,B]=a.useState(null),[G,X]=a.useState([]),[C,$]=a.useState(!1),[A,j]=a.useState(null),J=m.find(ne=>ne.name===R),[W,oe]=a.useState(null),[he,se]=a.useState(null),[fe,U]=a.useState(!1),[Ne,ee]=a.useState(null),[ve,ue]=a.useState(null),[ye,ie]=a.useState(!1);a.useEffect(()=>{Me()},[]),a.useEffect(()=>{e&&e.ahead>0?ze():e&&e.ahead===0&&K([])},[e?.ahead]),a.useEffect(()=>{m.length>0&&!R&&B(m[0].name)},[m]),a.useEffect(()=>{R?Be(R):(X([]),j(null))},[R]),a.useEffect(()=>{R&&!m.find(ne=>ne.name===R)&&B(m.length>0?m[0].name:null)},[m,R]);const Me=async()=>{p(!0);try{const ne=await Wv(c);h(ne)}catch(ne){l(je(ne)||"Failed to load remotes","error")}finally{p(!1)}},ze=async()=>{E(!0);try{const ne=await ny(c);K(ne)}catch{K([])}finally{E(!1)}},Be=async ne=>{$(!0),j(null);try{const Ie=await sy(ne,void 0,10,c);X(Ie)}catch(Ie){j(je(Ie)||"Failed to load remote commits"),X([])}finally{$(!1)}},Je=Is(),Ye=async ne=>{if(ne.preventDefault(),!(!v.trim()||!y.trim())){x("add");try{await Kv(v.trim(),y.trim(),c),l(`Remote '${v}' added successfully`,"success"),b(""),S(""),I(!1),await Me()}catch(Ie){l(je(Ie)||"Failed to add remote","error")}finally{x(null)}}},Ge=async ne=>{if(await Je.confirm({title:"Remove Remote",message:`Are you sure you want to remove remote '${ne}'?`,danger:!0})){x(`remove-${ne}`);try{await Gv(ne,c),l(`Remote '${ne}' removed`,"success"),await Me()}catch(Pe){l(je(Pe)||"Failed to remove remote","error")}finally{x(null)}}},it=async ne=>{if(N.trim()){x(`rename-${ne}`);try{await Jv(ne,N.trim(),c),l(`Remote renamed to '${N.trim()}'`,"success"),M(null),L(""),await Me()}catch(Ie){l(je(Ie)||"Failed to rename remote","error")}finally{x(null)}}},_e=async ne=>{if(w.trim()){x(`url-${ne}`);try{await Yv(ne,w.trim(),c),l("Remote URL updated","success"),M(null),_(""),await Me()}catch(Ie){l(je(Ie)||"Failed to update remote URL","error")}finally{x(null)}}},Fe=a.useCallback(async(ne,Ie)=>{if(Ie==="ahead"){if(W===ne){oe(null),se(null);return}oe(ne),se(null),U(!0);try{const Pe=await ro(ne);se(Pe)}catch{se(null)}finally{U(!1)}}else{if(Ne===ne){ee(null),ue(null);return}ee(ne),ue(null),ie(!0);try{const Pe=await ro(ne);ue(Pe)}catch{ue(null)}finally{ie(!1)}}},[W,Ne]),ae=ne=>{M(`url-${ne.name}`),_(ne.pushUrl||ne.fetchUrl)},be=ne=>{M(`name-${ne.name}`),L(ne.name)};return t.jsx("div",{className:"gm-panel gm-remotes-panel","data-testid":"remotes-panel",children:t.jsxs("div",{className:"gm-remotes-layout",children:[t.jsxs("div",{className:"gm-remote-selector","data-testid":"remote-selector",children:[t.jsxs("div",{className:"gm-remote-selector-header",children:[t.jsx("span",{className:"gm-remote-selector-title",children:"Remotes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>I(!T),disabled:f!==null,title:T?"Cancel":"Add Remote",children:T?t.jsx(zt,{size:14}):t.jsx(Xt,{size:14})})]}),T&&t.jsxs("form",{className:"gm-remote-form",onSubmit:Ye,children:[t.jsx("input",{type:"text",placeholder:"Remote name",value:v,onChange:ne=>b(ne.target.value),disabled:f==="add",className:"gm-input"}),t.jsx("input",{type:"text",placeholder:"Repository URL",value:y,onChange:ne=>S(ne.target.value),disabled:f==="add",className:"gm-input gm-input-url"}),t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:!v.trim()||!y.trim()||f==="add",children:[f==="add"?t.jsx(rt,{size:12,className:"spin"}):t.jsx(Xt,{size:12}),"Add"]})]}),g?t.jsxs("div",{className:"gm-loading",children:[t.jsx(rt,{size:16,className:"spin"}),"Loading..."]}):m.length===0?t.jsx("div",{className:"gm-empty",children:"No remotes"}):m.map(ne=>t.jsxs("div",{className:`gm-remote-selector-item${R===ne.name?" selected":""}`,onClick:()=>B(ne.name),role:"button",tabIndex:0,children:[t.jsxs("div",{className:"gm-remote-selector-info",children:[t.jsxs("span",{className:"gm-remote-selector-name",children:[ne.name,ne.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),t.jsx("span",{className:"gm-remote-selector-host",children:d(ne.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:Ie=>{Ie.stopPropagation(),Ge(ne.name)},disabled:f!==null,title:"Remove remote",children:t.jsx(Jt,{size:14})})]},ne.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[R&&J?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:R}),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(Mi,{size:14}),e.ahead," to push"]}),e.behind>0&&t.jsxs("div",{className:"gm-remote-indicator behind",children:[t.jsx(cr,{size:14}),e.behind," to pull"]})]})]}),t.jsxs("div",{className:"gm-remote-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:i,disabled:n!==null||g,children:[n==="fetch"?t.jsx(rt,{size:14,className:"spin"}):t.jsx(wn,{size:14}),"Fetch"]}),t.jsxs("button",{className:"btn btn-primary",onClick:r,disabled:n!==null||g,children:[n==="pull"?t.jsx(rt,{size:14,className:"spin"}):t.jsx(hs,{size:14}),"Pull"]}),t.jsxs("button",{className:"btn btn-primary",onClick:o,disabled:n!==null||g,children:[n==="push"?t.jsx(rt,{size:14,className:"spin"}):t.jsx(Mi,{size:14}),"Push"]})]})]}),t.jsxs("div",{className:"gm-remote-detail-card","data-testid":"remote-detail-card",children:[t.jsxs("div",{className:"gm-remote-detail-urls",children:[t.jsxs("div",{className:"gm-remote-detail-url-row",children:[t.jsx("span",{className:"gm-url-label",children:"Fetch:"}),k===`url-${R}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:w,onChange:ne=>_(ne.target.value),className:"gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>_e(R),disabled:f===`url-${R}`,children:f===`url-${R}`?t.jsx(rt,{size:12,className:"spin"}):t.jsx(Rn,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{M(null),_("")},title:"Cancel",children:t.jsx(zt,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:J.fetchUrl,children:J.fetchUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>u(J.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:t.jsx(Ai,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>ae(J),disabled:f!==null,title:"Edit remote URL",children:t.jsx(Qn,{size:14})})]})]}),J.pushUrl&&J.pushUrl!==J.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:J.pushUrl,children:J.pushUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>u(J.pushUrl,"push URL"),title:"Copy push URL",children:t.jsx(Ai,{size:14})})]})]}),t.jsx("div",{className:"gm-remote-detail-name-row",children:k===`name-${R}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:N,onChange:ne=>L(ne.target.value),className:"gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>it(R),disabled:f===`rename-${R}`,children:f===`rename-${R}`?t.jsx(rt,{size:12,className:"spin"}):t.jsx(Rn,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{M(null),L("")},title:"Cancel",children:t.jsx(zt,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>be(J),disabled:f!==null,title:"Edit remote name",children:t.jsx(Qn,{size:14})})})]}),e&&e.ahead>0&&t.jsxs("div",{className:"gm-remote-section","data-testid":"commits-to-push",children:[t.jsx("div",{className:"gm-section-subheader",children:t.jsxs("h5",{children:[t.jsx(Mi,{size:14}),"Commits to Push (",e.ahead,")"]})}),P?t.jsxs("div",{className:"gm-loading",children:[t.jsx(rt,{size:14,className:"spin"}),"Loading..."]}):z.length>0?t.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:z.map(ne=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>Fe(ne.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:ne.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:ne.message,children:ne.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:ne.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:ua(ne.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:W===ne.hash?t.jsx(qt,{size:14}):t.jsx(mn,{size:14})})]}),W===ne.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:fe?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(rt,{size:16,className:"spin"}),"Loading diff..."]}):he?t.jsxs(t.Fragment,{children:[ne.message&&t.jsx("div",{className:"gm-commit-message-full",children:ne.message}),he.stat&&t.jsx("pre",{className:"gm-diff-stat",children:he.stat}),t.jsx("pre",{className:"gm-diff-patch",children:he.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},ne.hash))}):t.jsx("div",{className:"gm-empty",children:"No ahead commits found (may need to fetch first)"})]}),t.jsxs("div",{className:"gm-remote-section","data-testid":"remote-commits-section",children:[t.jsx("div",{className:"gm-section-subheader",children:t.jsxs("h5",{children:[t.jsx(zh,{size:14}),"Recent commits on ",R]})}),C?t.jsxs("div",{className:"gm-loading",children:[t.jsx(rt,{size:14,className:"spin"}),"Loading commits..."]}):A?t.jsxs("div",{className:"gm-error",children:[t.jsx(Zn,{size:14}),A]}):G.length===0?t.jsxs("div",{className:"gm-empty",children:["No commits found on ",R,". Try fetching first."]}):t.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:G.map(ne=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>Fe(ne.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:ne.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:ne.message,children:ne.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:ne.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:ua(ne.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:Ne===ne.hash?t.jsx(qt,{size:14}):t.jsx(mn,{size:14})})]}),Ne===ne.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:ye?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(rt,{size:16,className:"spin"}),"Loading diff..."]}):ve?t.jsxs(t.Fragment,{children:[ne.message&&t.jsx("div",{className:"gm-commit-message-full",children:ne.message}),ve.stat&&t.jsx("pre",{className:"gm-diff-stat",children:ve.stat}),t.jsx("pre",{className:"gm-diff-patch",children:ve.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},ne.hash))})]})]}):t.jsx("div",{className:"gm-empty",children:"Select a remote to view details"}),s&&t.jsx("div",{className:"gm-remote-result",children:s.message})]})]})})}const Oa={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function _R(e,n){return e&&n?`${e}/${n}`:""}function AR(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 RR(e){switch(e){case"file-text":return Ri;case"check-circle":return un;case"shield":return yb;case"zap":return In;case"eye":return sa;case"globe":return jo;case"layout-grid":return Pi;default:return un}}function TR(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 PR({isOpen:e,onClose:n,addToast:s,projectId:i}){const[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState(!0),[m,h]=a.useState(!0),[g,p]=a.useState("my-steps"),[f,x]=a.useState(null),[v,b]=a.useState(!1),[y,S]=a.useState(Oa),[k,M]=a.useState(!1),[w,_]=a.useState(!1),[N,L]=a.useState(null),[T,I]=a.useState(null),[z,K]=a.useState({}),[P,E]=a.useState([]),R=a.useRef(null);Gs(R,e,"fusion:workflow-steps-modal-size");const B=a.useCallback(async()=>{try{d(!0);const U=await Mo(i);o(U)}catch(U){s(je(U)||"Failed to load workflow steps","error")}finally{d(!1)}},[s,i]),G=a.useCallback(async()=>{try{const U=await ar(i);K(U||{})}catch{}},[i]),X=a.useCallback(async()=>{try{const U=await os();E(U.models||[])}catch{}},[]),C=a.useCallback(async()=>{try{h(!0);const U=await Xy();c(U.templates)}catch(U){s(je(U)||"Failed to load templates","error")}finally{h(!1)}},[s]);a.useEffect(()=>{e&&(B(),C(),G(),X())},[e,B,C,G,X]);const $=a.useCallback(()=>{b(!0),x(null),S(Oa)},[]),A=a.useCallback(U=>{x(U.id),b(!1),S({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=a.useCallback(()=>{x(null),b(!1),S(Oa)},[]),J=a.useCallback(async()=>{if(!y.name.trim()||!y.description.trim()){s("Name and description are required","error");return}M(!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 Ne={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 Fd(Ne,i),s("Workflow step created","success")}else f&&(await Jy(f,{name:y.name.trim(),description:y.description.trim(),mode:y.mode,phase:y.phase,prompt:y.mode==="prompt"?y.prompt:"",scriptName:y.mode==="script"?y.scriptName.trim():void 0,enabled:y.enabled,defaultOn:y.defaultOn,...U},i),s("Workflow step updated","success"));b(!1),x(null),S(Oa),await B()}catch(U){s(je(U)||"Failed to save workflow step","error")}finally{M(!1)}},[y,v,f,s,B]),W=a.useCallback(async U=>{try{await Yy(U,i),s("Workflow step deleted","success"),L(null),f===U&&(x(null),S(Oa)),await B()}catch(Ne){s(je(Ne)||"Failed to delete workflow step","error")}},[f,s,B]),oe=a.useCallback(async()=>{if(!(!f&&!v)&&y.mode==="prompt"){if(v){if(!y.name.trim()||!y.description.trim()){s("Name and description are required before refining","error");return}M(!0);try{const U=y.modelProvider&&y.modelId?{modelProvider:y.modelProvider,modelId:y.modelId}:{},Ne={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 Fd(Ne,i);b(!1),x(ee.id),_(!0);const ve=await Od(ee.id,i);S(ue=>({...ue,prompt:ve.prompt})),s("Prompt refined with AI","success"),await B()}catch(U){s(je(U)||"Failed to refine prompt","error")}finally{M(!1),_(!1)}return}if(f){_(!0);try{const U=await Od(f,i);S(Ne=>({...Ne,prompt:U.prompt})),s("Prompt refined with AI","success"),await B()}catch(U){s(je(U)||"Failed to refine prompt","error")}finally{_(!1)}}}},[f,v,y,s,B]),he=a.useCallback(async U=>{I(U.id);try{await Zy(U.id,i),s(`Added ${U.name} workflow step`,"success"),await B(),p("my-steps")}catch(Ne){const ee=je(Ne);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{I(null)}},[s,B]);if(!e)return null;const se=v||f!==null,fe=fi(n);return t.jsx("div",{className:"modal-overlay open",...fe,"data-testid":"workflow-step-manager",children:t.jsxs("div",{ref:R,className:"modal workflow-step-manager-modal",role:"dialog","aria-modal":"true","aria-label":"Workflow Steps",children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h2",{children:"Workflow Steps"}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]}),t.jsx("div",{className:"wfm-body",children:u?t.jsx("div",{className:"wfm-loading",children:"Loading..."}):t.jsxs(t.Fragment,{children:[!se&&t.jsxs("div",{className:"wfm-tab-row",children:[t.jsxs("button",{className:`btn ${g==="my-steps"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>p("my-steps"),"data-testid":"tab-my-steps",children:[t.jsx(bg,{size:14}),"My Workflow Steps (",r.length,")"]}),t.jsxs("button",{className:`btn ${g==="templates"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>p("templates"),"data-testid":"tab-templates",children:[t.jsx(Pi,{size:14}),"Templates (",l.length,")"]})]}),g==="my-steps"&&!se&&t.jsxs(t.Fragment,{children:[r.length===0&&t.jsx("div",{className:"wfm-empty","data-testid":"empty-state",children:"No workflow steps defined. Create one to get started, or add one from the Templates tab."}),r.length>0&&t.jsx("div",{className:"wfm-step-list",children:r.map(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:()=>A(U),title:"Edit","aria-label":`Edit ${U.name}`,children:t.jsx(Qn,{size:14})}),N===U.id?t.jsxs("div",{className:"wfm-delete-confirm",children:[t.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>W(U.id),title:"Confirm delete","aria-label":`Confirm delete ${U.name}`,children:t.jsx(Rn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>L(null),title:"Cancel delete","aria-label":"Cancel delete",children:t.jsx(zt,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>L(U.id),title:"Delete","aria-label":`Delete ${U.name}`,children:t.jsx(Jt,{size:14})})]})]})},U.id))})]}),g==="templates"&&!se&&t.jsx(t.Fragment,{children:m?t.jsxs("div",{className:"wfm-loading",children:[t.jsx(rt,{size:24,className:"spin wfm-spinner"}),"Loading templates..."]}):l.length===0?t.jsx("div",{className:"wfm-empty","data-testid":"no-templates-state",children:"No templates available."}):t.jsx("div",{className:"wfm-template-list",children:l.map(U=>{const Ne=RR(U.icon),ee=TR(U.category),ve=T===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(Ne,{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:()=>he(U),disabled:ve,"data-testid":`add-template-${U.id}`,children:ve?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Xt,{size:12}),"Add"]})})]})]})},U.id)})})}),se&&t.jsxs("div",{className:"wfm-form","data-testid":"workflow-step-form",children:[t.jsx("h3",{className:"wfm-form-title",children:v?"New Workflow Step":"Edit Workflow Step"}),t.jsxs("div",{className:"wfm-form-fields",children:[t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Name"}),t.jsx("input",{type:"text",value:y.name,onChange:U=>S(Ne=>({...Ne,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=>S(Ne=>({...Ne,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:()=>S(U=>({...U,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[t.jsx(ui,{size:14}),"AI Prompt"]}),t.jsxs("button",{className:`btn ${y.mode==="script"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>S(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:()=>S(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:()=>S(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:oe,disabled:!y.description.trim()||w,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[w?t.jsx(rt,{size:12,className:"spin"}):t.jsx(Vn,{size:12}),t.jsx("span",{children:"Refine with AI"})]})]}),t.jsx("textarea",{value:y.prompt,onChange:U=>S(Ne=>({...Ne,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:()=>S(U=>({...U,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[t.jsx(zt,{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(Ln,{models:P,value:_R(y.modelProvider,y.modelId),onChange:U=>{const Ne=AR(U);S(ee=>({...ee,modelProvider:Ne.provider,modelId:Ne.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(z).length===0?t.jsx("div",{className:"wfm-no-scripts","data-testid":"no-scripts-message",children:"No scripts configured. Add scripts in Settings → Scripts first."}):t.jsxs("select",{value:y.scriptName,onChange:U=>S(Ne=>({...Ne,scriptName:U.target.value})),"data-testid":"workflow-step-script-select",children:[t.jsx("option",{value:"",children:"Select a script…"}),Object.entries(z).map(([U,Ne])=>t.jsxs("option",{value:U,children:[U," (",Ne,")"]},U))]})]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:y.enabled,onChange:U=>S(Ne=>({...Ne,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=>S(Ne=>({...Ne,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:k,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:J,disabled:k||!y.name.trim()||!y.description.trim()||y.mode==="script"&&!y.scriptName.trim(),"data-testid":"save-workflow-step",children:k?"Saving...":v?"Create":"Save"})]})]})]})]})}),!se&&t.jsx("div",{className:"wfm-footer",children:t.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:$,"data-testid":"add-workflow-step",children:[t.jsx(Xt,{size:14}),"Add Workflow Step"]})})]})})}const IR=36e5,$R=3e5,Vl=[{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 DR(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 LR(e){return typeof e!="number"||!Number.isFinite(e)?IR:Math.max($R,Math.round(e))}function G$(e){if(Vl.some(s=>s.value===e))return[...Vl];const n={value:e,label:`${DR(e)} (custom)`};return[...Vl,n].sort((s,i)=>s.value-i.value)}const zR=4,FR=5*6e4;function OR(e){const n=LR(e?.heartbeatIntervalMs);return Math.max(n*zR,FR)}function UR(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 BR(e){const{state:n,lastHeartbeatAt:s,lastError:i,pauseReason:r,runtimeConfig:o}=e,l=UR(e);if(n==="terminated")return{label:"Terminated",icon:t.jsx(ms,{size:14}),color:"var(--state-error-text)",stateDerived:!0};if(n==="error")return{label:i??"Error",icon:t.jsx(Es,{size:14}),color:"var(--state-error-text)",stateDerived:!i};if(n==="paused")return{label:r?`Paused: ${r}`:"Paused",icon:t.jsx(qs,{size:14}),color:"var(--state-paused-text)",stateDerived:!r};if(n==="running"||l&&n==="active")return{label:"Running",icon:t.jsx(Es,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:t.jsx(pn,{size:14}),color:"var(--text-secondary)",stateDerived:!1};const c=new Date(s).getTime(),u=Date.now()-c,d=OR(o);return u>d?{label:"Unresponsive",icon:t.jsx(Es,{size:14}),color:"var(--state-error-text)",stateDerived:!1}:{label:"Healthy",icon:t.jsx(Cx,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}const Ua=[{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 HR({isOpen:e,onClose:n,addToast:s,projectId:i}){const[r,o]=a.useState([]),[l,c]=a.useState(!1),[u,d]=a.useState(!1),[m,h]=a.useState(""),[g,p]=a.useState("custom"),[f,x]=a.useState("all"),[v,b]=a.useState(()=>{if(typeof window>"u")return"list";const A=zn("fn-agent-view",i);return A==="board"||A==="list"?A:"list"});a.useEffect(()=>{const A=zn("fn-agent-view",i);if(A==="board"||A==="list"){b(A);return}b("list")},[i]),a.useEffect(()=>{as("fn-agent-view",v,i)},[i,v]);const[y,S]=a.useState(null),k=a.useRef(null),[M,w]=a.useState(new Set),[_,N]=a.useState(new Map),{confirm:L}=Is(),T=a.useMemo(()=>_.size===0?r:r.map(A=>{const j=_.get(A.id);return j?{...A,state:j}:A}),[r,_]),I=a.useMemo(()=>f==="all"?T.filter(A=>A.state!=="terminated"):T,[T,f]),z=a.useCallback(async()=>{c(!0);try{const j=await xa(f!=="all"?{state:f}:void 0,i);o(j)}catch(A){s(`Failed to load agents: ${je(A)}`,"error")}finally{c(!1)}},[f,s,i]);a.useEffect(()=>{e&&z()},[e,z]),a.useEffect(()=>{if(!e)return;const A=setInterval(()=>{z()},3e4);return()=>{clearInterval(A)}},[e,z]);const K=async()=>{if(m.trim())try{await lk({name:m.trim(),role:g},i),s(`Agent "${m}" created`,"success"),h(""),d(!1),z()}catch(A){s(`Failed to create agent: ${je(A)}`,"error")}},P=async(A,j)=>{if(!M.has(A)){w(J=>new Set(J).add(A)),N(J=>{const W=new Map(J);return W.set(A,j),W});try{await dk(A,j,i),s(`Agent state updated to ${j}`,"success"),await z(),N(J=>{const W=new Map(J);return W.delete(A),W})}catch(J){N(W=>{const oe=new Map(W);return oe.delete(A),oe}),s(`Failed to update state: ${je(J)}`,"error")}finally{w(J=>{const W=new Set(J);return W.delete(A),W})}}},E=async(A,j)=>{if(await L({title:"Delete Agent",message:`Delete agent "${j}"? This cannot be undone.`,danger:!0}))try{await uk(A,i),s(`Agent "${j}" deleted`,"success"),z()}catch(W){s(`Failed to delete agent: ${je(W)}`,"error")}},R=async(A,j)=>{const J=r.find(W=>W.id===A);if(J){if(J.role===j){S(null);return}try{await ck(A,{role:j},i),s(`Agent role updated to ${Ua.find(W=>W.value===j)?.label??j}`,"success"),S(null),z()}catch(W){s(`Failed to update role: ${je(W)}`,"error")}}},B=(A,j)=>{A.key==="Escape"&&S(null)},G=A=>Ua.find(j=>j.value===A)?.label??A,X=A=>Ua.find(j=>j.value===A)?.icon??"◆",C=A=>BR(A),$=A=>A.color==="var(--state-active-text)"?"active":A.color==="var(--state-paused-text)"?"paused":A.color==="var(--state-error-text)"?"error":"muted";return e?t.jsx("div",{className:"modal-overlay open",onClick:A=>A.target===A.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(pn,{size:20}),"Agents"]}),t.jsxs("div",{className:"modal-actions",children:[t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${v==="board"?" active":""}`,onClick:()=>b("board"),title:"Board view","aria-label":"Board view","aria-pressed":v==="board",children:t.jsx(Pi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${v==="list"?" active":""}`,onClick:()=>b("list"),title:"List view","aria-label":"List view","aria-pressed":v==="list",children:t.jsx(ic,{size:16})})]}),t.jsx("button",{className:"btn-icon",onClick:()=>void z(),title:"Refresh",disabled:l,children:t.jsx(wn,{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(to,{size:14}),t.jsxs("select",{className:"agent-state-filter-select",value:f,onChange:A=>x(A.target.value),"aria-label":"Filter agents by state",children:[t.jsx("option",{value:"all",children:"All States"}),t.jsx("option",{value:"idle",children:"Idle"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"running",children:"Running"}),t.jsx("option",{value:"paused",children:"Paused"}),t.jsx("option",{value:"error",children:"Error"}),t.jsx("option",{value:"terminated",children:"Terminated"})]})]}),t.jsxs("button",{className:"btn btn-task-create btn-sm",onClick:()=>d(!u),children:[t.jsx(Xt,{size:16}),u?"Cancel":"New Agent"]})]}),u&&t.jsxs("div",{className:"agent-create-form",children:[t.jsx("input",{type:"text",placeholder:"Agent name...",value:m,onChange:A=>h(A.target.value),onKeyDown:A=>A.key==="Enter"&&K(),className:"input",autoFocus:!0}),t.jsx("select",{className:"select",value:g,onChange:A=>p(A.target.value),children:Ua.map(A=>t.jsxs("option",{value:A.value,children:[A.icon," ",A.label]},A.value))}),t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:()=>void K(),children:"Create"})]}),t.jsx("div",{className:v==="board"?"agent-board":"agent-list",children:I.length===0?t.jsxs("div",{className:"agent-empty",children:[t.jsx(pn,{size:48,opacity:.3}),t.jsx("p",{children:"No agents found"}),t.jsx("p",{className:"text-secondary",children:"Create an agent to get started"})]}):v==="board"?I.map(A=>{const j=C(A),J=$(j);return t.jsxs("div",{className:"agent-board-card","data-state":A.state,children:[t.jsxs("div",{className:"agent-board-header",children:[t.jsx("span",{className:"agent-board-icon",children:X(A.role)}),t.jsx("span",{className:"agent-board-badge","data-state":A.state,children:A.state}),t.jsx("span",{className:"agent-board-health","data-health":J,title:j.label,children:j.icon})]}),t.jsx("div",{className:"agent-board-name",title:A.name,children:A.name}),t.jsx("div",{className:"agent-board-id",children:A.id}),t.jsxs("div",{className:"agent-board-actions",children:[A.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void P(A.id,"active"),disabled:M.has(A.id),title:"Activate",children:t.jsx(fn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void E(A.id,A.name),title:"Delete",children:t.jsx(Jt,{size:14})})]}),A.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void P(A.id,"paused"),disabled:M.has(A.id),title:"Pause",children:t.jsx(qs,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(A.id,"terminated"),disabled:M.has(A.id),title:"Stop",children:t.jsx(ms,{size:14})})]}),A.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void P(A.id,"active"),disabled:M.has(A.id),title:"Resume",children:t.jsx(fn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(A.id,"terminated"),disabled:M.has(A.id),title:"Stop",children:t.jsx(ms,{size:14})})]}),A.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void P(A.id,"paused"),disabled:M.has(A.id),title:"Pause",children:t.jsx(qs,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(A.id,"terminated"),disabled:M.has(A.id),title:"Stop",children:t.jsx(ms,{size:14})})]}),A.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void P(A.id,"active"),disabled:M.has(A.id),title:"Retry",children:t.jsx(fn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(A.id,"terminated"),disabled:M.has(A.id),title:"Stop",children:t.jsx(ms,{size:14})})]}),A.state==="terminated"&&t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void E(A.id,A.name),title:"Delete",children:t.jsx(Jt,{size:14})})]})]},A.id)}):I.map(A=>{const j=C(A),J=$(j);return t.jsxs("div",{className:"agent-card","data-state":A.state,children:[t.jsxs("div",{className:"agent-card-header",children:[t.jsxs("div",{className:"agent-info",children:[y===A.id?t.jsx("select",{ref:k,className:"select agent-role-select",value:A.role,onChange:W=>void R(A.id,W.target.value),onKeyDown:W=>B(W,A.id),onBlur:()=>S(null),autoFocus:!0,children:Ua.map(W=>t.jsxs("option",{value:W.value,children:[W.icon," ",W.label]},W.value))}):t.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>S(A.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:W=>{(W.key==="Enter"||W.key===" ")&&S(A.id)},children:X(A.role)}),t.jsxs("div",{className:"agent-meta",children:[t.jsx("span",{className:"agent-name",children:A.name}),t.jsx("span",{className:"agent-id text-secondary",children:A.id})]})]}),t.jsxs("div",{className:"agent-badges",children:[t.jsx("span",{className:"badge agent-list-state-badge","data-state":A.state,children:A.state}),t.jsxs("span",{className:"badge agent-list-health-badge","data-health":J,title:j.label,children:[j.icon,!j.stateDerived&&` ${j.label}`]}),t.jsx("span",{className:"badge text-secondary",children:G(A.role)})]})]}),t.jsxs("div",{className:"agent-card-body",children:[A.taskId&&t.jsxs("div",{className:"agent-task",children:[t.jsx("span",{className:"text-secondary",children:"Working on:"}),t.jsx("span",{className:"badge",children:A.taskId})]}),A.lastHeartbeatAt&&t.jsxs("div",{className:"agent-heartbeat",children:[t.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),t.jsx("span",{children:new Date(A.lastHeartbeatAt).toLocaleString()})]})]}),t.jsxs("div",{className:"agent-card-actions",children:[A.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void P(A.id,"active"),disabled:M.has(A.id),title:"Activate",children:[t.jsx(fn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void E(A.id,A.name),title:"Delete",children:[t.jsx(Jt,{size:14})," Delete"]})]}),A.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void P(A.id,"paused"),disabled:M.has(A.id),title:"Pause",children:[t.jsx(qs,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(A.id,"terminated"),disabled:M.has(A.id),title:"Stop",children:[t.jsx(ms,{size:14})," Stop"]})]}),A.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void P(A.id,"active"),disabled:M.has(A.id),title:"Resume",children:[t.jsx(fn,{size:14})," Resume"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(A.id,"terminated"),disabled:M.has(A.id),title:"Stop",children:[t.jsx(ms,{size:14})," Stop"]})]}),A.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void P(A.id,"paused"),disabled:M.has(A.id),title:"Pause",children:[t.jsx(qs,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(A.id,"terminated"),disabled:M.has(A.id),title:"Stop",children:[t.jsx(ms,{size:14})," Stop"]})]}),A.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void P(A.id,"active"),disabled:M.has(A.id),title:"Retry",children:[t.jsx(fn,{size:14})," Retry"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(A.id,"terminated"),disabled:M.has(A.id),title:"Stop",children:[t.jsx(ms,{size:14})," Stop"]})]}),A.state==="terminated"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm btn-task-create",onClick:()=>void P(A.id,"active"),disabled:M.has(A.id),title:"Start",children:[t.jsx(fn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void E(A.id,A.name),title:"Delete",children:[t.jsx(Jt,{size:14})," Delete"]})]})]})]},A.id)})})]})]})}):null}function qR({authenticated:e,onToggled:n,compact:s=!1}){const[i,r]=a.useState(null),[o,l]=a.useState(null),[c,u]=a.useState(null),d=a.useRef(!0);a.useEffect(()=>(d.current=!0,()=>{d.current=!1}),[]);const m=a.useCallback(async()=>{try{const b=await $v();return d.current&&r(b),b}catch(b){return d.current&&u({kind:"error",message:b instanceof Error?b.message:String(b)}),null}},[]);a.useEffect(()=>{m()},[m]);const h=a.useCallback(async()=>{l("testing"),u(null),await m(),d.current&&l(null)},[m]),g=a.useCallback(async b=>{l(b?"enabling":"disabling"),u(null);try{const y=await Dv(b);d.current&&u({kind:y.enabled?"enabled":"disabled",restartRequired:y.restartRequired}),n?.(y.enabled),await m()}catch(y){d.current&&u({kind:"error",message:y instanceof Error?y.message:String(y)})}finally{d.current&&l(null)}},[n,m]),p=i?.binary.available??!1,f=i?.enabled??e,x=t.jsxs("span",{className:"onboarding-provider-card__description",children:["Route AI calls through your locally-installed ",t.jsx("code",{children:"claude"})," CLI. Uses your existing Claude subscription / quota instead of an API key."]}),v=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:12,className:"animate-spin"}),"Testing…"]}):"Test"}),f?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void g(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void g(!0),disabled:o!==null||!p,title:p?void 0:"`claude` binary not detected on PATH — install Claude CLI first.",children:o==="enabling"?"Enabling…":"Enable"})]});return s?t.jsxs("div",{className:`auth-provider-card auth-provider-card--cli${e?" auth-provider-card--authenticated":""}`,"data-testid":"claude-cli-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(Tn,{provider:"claude-cli",size:"sm"}),t.jsx("strong",{children:"Anthropic — via Claude CLI"}),t.jsx(VR,{status:i,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:v})]}),t.jsxs("details",{className:"auth-provider-cli-details",children:[t.jsx("summary",{children:"Details"}),t.jsxs("div",{className:"auth-provider-cli-details-body",children:[x,t.jsx(rh,{status:i,authenticated:e}),c&&t.jsx(oh,{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(Tn,{provider:"claude-cli",size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:"Anthropic — via Claude CLI"}),x,t.jsx(rh,{status:i,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(oh,{action:c})]})}function VR({status:e,authenticated:n}){const s=e?.enabled??n,i=e?.binary.available??!1;return s?t.jsx("span",{className:"auth-status-badge authenticated",children:"✓ Active"}):!i&&e?t.jsx("span",{className:"auth-status-badge not-authenticated",children:"✗ Not installed"}):t.jsx("span",{className:"auth-status-badge not-authenticated",children:"✗ Not connected"})}function rh({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(rt,{size:10,className:"animate-spin"})," Probing local CLI…"]});const{binary:s,enabled:i,extension:r,ready:o}=e;return s.available?i?r&&r.status!=="ok"?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--warning",children:["⚠ Extension load failed: ",r.reason??r.status]}):o||n?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--connected",children:["✓ Connected",s.version?` — ${s.version}`:""]}):t.jsx("small",{className:"settings-muted",children:"Enabled. Validating…"}):t.jsxs("small",{className:"settings-muted",children:[t.jsx("code",{children:"claude"})," ",s.version?`(${s.version})`:""," detected",s.binaryPath?` at ${s.binaryPath}`:"",". Click Enable to route AI calls through it."]}):t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--error",children:["✗ ",s.reason??"`claude` not found on PATH"]})}function oh({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 WR(e){const n="([A-Z0-9]{2,}(?:-[A-Z0-9]{2,})+|[A-Z0-9]{6,9})",s=new RegExp(`\\b(?:device\\s+code|your\\s+code|code)\\s*(?:is|:)?\\s*${n}\\b`,"i"),i=new RegExp(`\\b(?:enter|use)\\s+${n}\\b`,"i"),r=/\b([A-Z0-9]{2,}(?:-[A-Z0-9]{2,})+)\b/,o=e.match(s);if(o?.[1])return o[1];const l=e.match(i);if(l?.[1])return l[1];const c=e.match(r);return c?.[1]?c[1]:null}function Wl({instructions:e,"data-testid":n}){const[s,i]=a.useState(!1),r=WR(e),o=a.useRef(null),l=a.useCallback(()=>{i(!0),setTimeout(()=>i(!1),2e3)},[]),c=a.useCallback(async()=>{const u=r??e;try{await navigator.clipboard.writeText(u),l()}catch{}},[r,e,l]);return a.useEffect(()=>{const u=o.current===null&&r!==null;if(o.current=r,!u)return;(async()=>{try{await navigator.clipboard.writeText(r),l()}catch{}})()},[r,l]),t.jsx("p",{className:"auth-login-instructions","data-testid":n,children:r?t.jsx(t.Fragment,{children:e.split(r).map((u,d,m)=>t.jsxs("span",{children:[u,d<m.length-1&&t.jsxs("span",{className:"device-code-wrapper",children:[t.jsx("code",{className:"device-code",children:r}),t.jsx("button",{className:"device-code-copy-btn",onClick:c,title:s?"Copied!":"Copy code","aria-label":s?"Copied to clipboard":"Copy device code",type:"button",children:s?t.jsx(Rn,{size:12}):t.jsx(Ai,{size:12})})]})]},d))}):e})}const $i="fusion_model_onboarding_state",ma=[],ha=[],xo=!1,bo=!1,pa={},KR=void 0,di=["ai-setup","github","project-setup","first-task"],GR={"ai-setup":"AI Setup",github:"GitHub","project-setup":"Project","first-task":"First Task",complete:"Complete"};function gs(){if(typeof window>"u")return null;try{const e=localStorage.getItem($i);if(!e)return null;const n=JSON.parse(e);return n&&typeof n=="object"&&"currentStep"in n&&typeof n.currentStep=="string"?JR(n):null}catch{return null}}function JR(e){const n=e.postOnboardingDismissedAt??KR;return{...e,completedSteps:e.completedSteps??ma,skippedSteps:e.skippedSteps??ha,dismissed:e.dismissed??xo,completed:e.completed??bo,stepData:e.stepData??pa,...n?{postOnboardingDismissedAt:n}:{}}}function Gr(e,n){if(!(typeof window>"u")){if(!n){const s={currentStep:e,updatedAt:new Date().toISOString(),completedSteps:ma,skippedSteps:ha,dismissed:xo,completed:bo,stepData:pa};try{localStorage.setItem($i,JSON.stringify(s))}catch{}return}try{const s=gs(),i=new Date().toISOString(),r=n.completed??bo;let o=n.dismissed??xo;r&&(o=!1);const l=n.completedSteps??s?.completedSteps??ma,c=n.skippedSteps??s?.skippedSteps??ha,u={...s?.stepData??pa};if(n.stepData)for(const[m,h]of Object.entries(n.stepData))h!==void 0&&(u[m]={...u[m]??{},...h});const d={currentStep:e,updatedAt:i,completedSteps:l,skippedSteps:c,dismissed:o,completed:r,stepData:u};localStorage.setItem($i,JSON.stringify(d))}catch{}}}function YR(e){if(!(typeof window>"u"))try{const n=gs(),s=new Date().toISOString();if(!n){const o={currentStep:e,updatedAt:s,completedSteps:ma,skippedSteps:[e],dismissed:xo,completed:bo,stepData:pa};localStorage.setItem($i,JSON.stringify(o));return}const i=n.skippedSteps.includes(e)?n.skippedSteps:[...n.skippedSteps,e],r={...n,skippedSteps:i,completedSteps:n.completedSteps.filter(o=>o!==e),updatedAt:s};localStorage.setItem($i,JSON.stringify(r))}catch{}}function lh(){if(!(typeof window>"u"))try{const e=gs(),n=new Date().toISOString(),s=e?{...e,completedAt:n,completed:!0,dismissed:!1,updatedAt:n}:{currentStep:"complete",updatedAt:n,completedAt:n,completedSteps:ma,skippedSteps:ha,dismissed:!1,completed:!0,stepData:pa};localStorage.setItem($i,JSON.stringify(s))}catch{}}function fa(){const e=gs();return e?e.completed===!0?!0:typeof e.completedAt=="string"&&e.completedAt.length>0:!1}function QR(){if(!(typeof window>"u"))try{const e=gs(),n=new Date().toISOString(),s=e?{...e,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:ma,skippedSteps:ha,dismissed:!1,completed:!1,stepData:pa,postOnboardingDismissedAt:n};localStorage.setItem($i,JSON.stringify(s))}catch{}}function qf(){const e=gs();return e?typeof e.postOnboardingDismissedAt=="string"&&e.postOnboardingDismissedAt.length>0:!1}function XR(){const e=gs();return!e||fa()?!1:e.currentStep!=="complete"}function ZR(){const e=gs();if(!e||fa()||e.currentStep==="complete")return null;const n=e.currentStep,s=GR[n]??n4(e.currentStep);return{currentStep:e.currentStep,label:s,completedSteps:e.completedSteps}}function e4(){const e=gs();return e?e.skippedSteps:ha}function t4(e){const n=gs();return!n||!n.stepData?null:n.stepData[e]??null}function n4(e){return e.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const Vf="fusion_onboarding_events",ch="fusion_onboarding_session_id",s4=200,i4=50;function Ns(e,n={}){if(!(typeof window>"u"))try{const s=r4(),i=c4(n.step),r={type:e,timestamp:new Date().toISOString(),...i?{step:i}:{},metadata:n,sessionId:a4()},o=l4([...s,r]);o4(o)}catch{}}function a4(){if(typeof window>"u")return"server-session";try{const e=sessionStorage.getItem(ch);if(e)return e;const n=dh();return sessionStorage.setItem(ch,n),n}catch{return dh()}}function dh(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function r4(){try{const e=localStorage.getItem(Vf);if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(d4):[]}catch{return[]}}function o4(e){try{localStorage.setItem(Vf,JSON.stringify(e))}catch{}}function l4(e){const n=[...e];for(;n.length>s4;)n.splice(0,i4);return n}function c4(e){if(e==="ai-setup"||e==="github"||e==="first-task"||e==="complete")return e}function d4(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 u4={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"}}},Wf={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:"..."}},m4={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},uh={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 Rc(e){if(uh[e])return uh[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 Kl=["anthropic","openai","google","gemini","ollama"],h4=["anthropic","claude-cli","openai-codex","gemini","minimax","kimi","zai"],p4={anthropic:"anthropic","claude-cli":"claude-cli","openai-codex":"openai-codex",google:"gemini",gemini:"gemini",minimax:"minimax",kimi:"kimi",moonshot:"kimi","kimi-coding":"kimi",zai:"zai"},f4={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function Tc(e){return p4[e]??e}function mh(e){const n=Tc(e),s=h4.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function hh(e,n){if(e.authenticated!==n.authenticated)return e.authenticated?-1:1;const s=mh(e.id),i=mh(n.id);if(s!==i)return s-i;const r=Tc(e.id),o=Tc(n.id);if(r!==o)return r.localeCompare(o);const l=f4[r];if(l){const u=l.indexOf(e.id),d=l.indexOf(n.id);if(u!==d)return(u===-1?Number.POSITIVE_INFINITY:u)-(d===-1?Number.POSITIVE_INFINITY:d)}const c=e.name.localeCompare(n.name);return c!==0?c:e.id.localeCompare(n.id)}function g4(e,n){const s=n.trim();if(!s)return"API key is required";const i=Wf[e]??m4;return i.pattern.test(s)?null:`${Rc(e)} keys should follow this format: ${i.hint} (e.g. ${i.example})`}const Kf={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"},x4={description:"AI provider — connect to start using AI models",apiKeyInfo:Kf};function Pc(e){return u4[e]??x4}function b4(e){return Pc(e.id).apiKeyInfo??Kf}function Hs({summary:e,children:n,className:s=""}){const[i,r]=a.useState(!1);return t.jsxs("div",{className:`onboarding-disclosure ${s}`,children:[t.jsxs("button",{className:"onboarding-disclosure-trigger",onClick:()=>r(!i),"aria-expanded":i,type:"button",children:[t.jsx(mn,{size:14,className:"onboarding-disclosure-chevron","aria-hidden":"true"}),t.jsx("span",{children:e})]}),i&&t.jsx("div",{className:"onboarding-disclosure-content",children:n})]})}function v4({items:e}){return e.some(s=>s.status!=="connected")?t.jsxs("div",{className:"onboarding-readiness-summary","data-testid":"readiness-summary",role:"status",children:[t.jsx("p",{className:"onboarding-readiness-header",children:"Setup Summary"}),e.map(s=>{const i=s.status==="connected"?"✓":s.status==="missing"?"⚠":"○";return t.jsxs("div",{className:`onboarding-readiness-item onboarding-readiness-item--${s.status}`,"data-status":s.status,children:[t.jsx("span",{className:"onboarding-readiness-icon","aria-hidden":"true",children:i}),t.jsxs("span",{className:"onboarding-readiness-content",children:[t.jsx("span",{className:"onboarding-readiness-label",children:s.label}),s.detail&&t.jsx("span",{className:"onboarding-readiness-detail",children:s.detail})]})]},s.label)})]}):t.jsx("div",{className:"onboarding-readiness-summary","data-testid":"readiness-summary",role:"status",children:t.jsx("p",{className:"onboarding-readiness-all-connected",children:"✓ All integrations connected"})})}function y4({provider:e,apiKeyInfo:n,inputValue:s,isSaving:i,error:r,success:o,isConnected:l,onInputChange:c,onSave:u,onClear:d}){const m=`onboarding-apikey-input-${e.id}`,h=i||!s.trim(),g=Wf[e.id],p=`input onboarding-apikey-input${r?" onboarding-apikey-input--error":""}${o?" onboarding-apikey-input--success":""}`,f=t.jsxs(t.Fragment,{children:[g&&t.jsxs("small",{className:"onboarding-apikey-hint",children:["Format: ",g.hint]}),t.jsx("p",{className:"onboarding-apikey-instructions",children:n.setupInstructions}),n.dashboardUrl&&t.jsx("a",{href:n.dashboardUrl,target:"_blank",rel:"noreferrer",className:"onboarding-apikey-dashboard-link",children:"Get your API key →"}),t.jsx("p",{className:"onboarding-apikey-usage",children:n.usageDescription})]});return l?t.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${e.id}`,children:[t.jsxs("div",{className:"onboarding-apikey-connected-header",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:n.fieldLabel}),t.jsx("span",{className:"auth-status-badge connected",children:"✓ API key saved"})]}),t.jsx("button",{className:"btn btn-sm",onClick:()=>d(e.id),disabled:i,children:i?"Removing…":"Remove Key"}),t.jsx(Hs,{summary:"Advanced setup details",children:f}),r&&t.jsx("small",{className:"field-error",children:r})]}):t.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${e.id}`,children:[t.jsx("label",{htmlFor:m,className:"onboarding-apikey-field-label",children:n.fieldLabel}),t.jsxs("div",{className:"onboarding-apikey-input-row",children:[t.jsx("input",{id:m,type:"password",className:p,placeholder:n.inputPlaceholder??"Enter API key",value:s,onChange:x=>c(e.id,x.target.value),onKeyDown:x=>{x.key==="Enter"&&u(e.id,s)},"data-testid":m}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>u(e.id,s),disabled:h,"data-testid":`onboarding-apikey-save-${e.id}`,children:i?"Saving…":"Save"})]}),r&&t.jsx("small",{className:"field-error",children:r}),o&&!r&&t.jsx("small",{className:"onboarding-apikey-success","data-testid":`onboarding-apikey-success-${e.id}`,children:o}),t.jsx(Hs,{summary:"Advanced setup details",children:f})]})}const k4=150;function j4({onComplete:e,addToast:n,projectId:s,onOpenSetupWizard:i,onOpenNewTask:r,onOpenGitHubImport:o,firstCreatedTask:l,onViewTask:c}){const u=gs(),d=u?.currentStep,m=d==="complete"?"ai-setup":di.includes(d)?d:"ai-setup",h=u?.completedSteps??[],g=u?.skippedSteps??e4(),[p,f]=a.useState(!0),[x,v]=a.useState(m),[b,y]=a.useState(h),[S,k]=a.useState(g),[M,w]=a.useState(!1),[_,N]=a.useState(""),[L,T]=a.useState(!1),[I,z]=a.useState(null),[K,P]=a.useState(null),[E,R]=a.useState([]),[B,G]=a.useState(void 0),[X,C]=a.useState(!0),[$,A]=a.useState(null),[j,J]=a.useState({}),[W,oe]=a.useState([]),[he,se]=a.useState(""),[fe,U]=a.useState(!1),[Ne,ee]=a.useState({}),[ve,ue]=a.useState({}),[ye,ie]=a.useState({}),Me=a.useRef({}),ze=a.useRef(null),Be=a.useRef(null),Je=a.useRef(null),[Ye,Ge]=a.useState({}),[it,_e]=a.useState(()=>gs()?.stepData?.github?.skipped===!0),Fe=a.useRef(0),ae=a.useRef(l),be=a.useRef(!1),ne=u?.currentStep,Ie=!!u&&u.currentStep!=="complete";Gs(Be,p,"fusion:model-onboarding-modal-size"),a.useEffect(()=>{const Q=ze.current;Q&&(Q.scrollTop=0)},[x]);const[Pe,ce]=a.useState(()=>gs()?.stepData?.["ai-setup"]?.skippedProviders??{}),le=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"project-setup",label:"Project"},{key:"first-task",label:"First Task"}],$e=le.findIndex(Q=>Q.key===x),at=x==="complete"?le.length:$e;a.useEffect(()=>{x!=="complete"&&Gr(x,{completedSteps:b,skippedSteps:S})},[x,b,S]),a.useEffect(()=>{be.current||(be.current=!0,Ns("onboarding:wizard-opened",{source:Ie?"resume":"initial",resumedFromStep:ne}))},[Ie,ne]),a.useEffect(()=>{const Q=ae.current!=null,Oe=l!=null;!Q&&Oe&&w(!0),Oe||w(!1),ae.current=l},[l]);const tt=a.useRef(m);a.useEffect(()=>{if(tt.current==="ai-setup"&&x!=="ai-setup"&&!E.some(Oe=>Oe.id!=="github"&&Oe.authenticated)){const Oe={};for(const Xe of E)Xe.id!=="github"&&!Xe.authenticated&&!Pe[Xe.id]&&(Oe[Xe.id]=!0);if(Object.keys(Oe).length>0){const Xe={...Pe,...Oe};ce(Xe),Gr(x,{stepData:{"ai-setup":{skippedProviders:Xe}}})}}tt.current=x},[x,E,Pe]);const V=a.useCallback(async()=>{try{const{providers:Q,ghCli:Oe}=await ir();R(Q),G(Oe),J(Xe=>{const Ze={};for(const[pt,Nt]of Object.entries(Xe)){const At=Q.find(xn=>xn.id===pt);At&&!At.authenticated&&(Ze[pt]=Nt)}return Object.keys(Ze).length===Object.keys(Xe).length?Xe:Ze}),ce(Xe=>{const Ze={...Xe};for(const pt of Q)pt.authenticated&&Ze[pt.id]&&delete Ze[pt.id];return Object.keys(Ze).length===Object.keys(Xe).length?Xe:Ze})}catch{}},[]),de=a.useRef(!1);a.useEffect(()=>{de.current&&V(),de.current=x!=="ai-setup"},[x,V]);const Z=E.find(Q=>Q.id==="github"),we=!!Z,pe=Z?.authenticated??!1,Te=B?.authenticated??!1,Qe=pe||Te,Ee=!pe&&Te,Re=a.useCallback(Q=>{if(Q.authenticated)return"connected";const Oe=Ye?.[Q.id];return Oe==="timeout"||Oe==="failed"?"retry":Pe[Q.id]?"skipped":"not-connected"},[Ye,Pe]);function Le({status:Q}){const Oe={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:Xe,className:Ze}=Oe[Q];return t.jsx("span",{"data-testid":"provider-status-badge",className:Ze,"data-status":Q,children:Xe})}const ct=a.useCallback(()=>{if(Qe)return"connected";const Q=Ye.github;return Q==="pending"?"pending":Q==="failed"||Q==="timeout"?"failed":it?"skipped":"not-connected"},[Qe,Ye,it]);function Se({status:Q}){const Oe={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:Xe,className:Ze}=Oe[Q];return t.jsx("span",{"data-testid":"github-status-badge",className:Ze,"data-status":Q,children:Xe})}const mt=a.useCallback(async()=>{try{const Q=await os();oe(Q.models)}catch{}},[]),gt=a.useCallback(async()=>{try{const Q=await Di();if(Q.defaultProvider&&Q.defaultModelId){const Oe=`${Q.defaultProvider}/${Q.defaultModelId}`;se(Oe)}}catch{}},[]);a.useEffect(()=>{Promise.all([V(),mt(),gt()]).finally(()=>C(!1))},[V,mt,gt]),a.useEffect(()=>{const Q=t4("ai-setup");if(Q?.loginOutcomes){const Oe=Q.loginOutcomes,Xe={};for(const[Ze,pt]of Object.entries(Oe))pt!=="pending"&&(Xe[Ze]=pt);Object.keys(Xe).length>0&&Ge(Xe)}},[]);const wt=a.useCallback((Q,Oe)=>{Gr(x,{completedSteps:b,stepData:{"ai-setup":{loginOutcomes:{[Q]:Oe}}}})},[x,b]);a.useEffect(()=>{const Q=Object.entries(Ye).filter(([Oe,Xe])=>Xe!=="pending");for(const[Oe,Xe]of Q)wt(Oe,Xe)},[Ye,wt]),a.useEffect(()=>()=>{Je.current&&clearInterval(Je.current),Object.values(Me.current).forEach(clearTimeout),Me.current={}},[]);const yt=a.useCallback(Q=>{_e(Q),Gr(x,{completedSteps:b,stepData:{github:{skipped:Q}}})},[x,b]),kt=a.useCallback(Q=>Q==="complete"?-1:di.indexOf(Q),[]),Ct=a.useCallback(()=>{y(Oe=>[...new Set([...Oe,x])]),k(Oe=>Oe.filter(Xe=>Xe!==x)),Ns("onboarding:step-completed",{step:x}),x==="github"&&!pe&&yt(!1);const Q=kt(x);Q>=0&&Q<di.length-1&&v(di[Q+1])},[x,pe,yt,kt]),Rt=a.useCallback(()=>{k(Oe=>[...new Set([...Oe,x])]),YR(x),Ns("onboarding:step-skipped",{step:x}),x==="github"&&!pe&&yt(!0);const Q=kt(x);Q>=0&&Q<di.length-1&&v(di[Q+1])},[x,pe,yt,kt]),Ft=a.useCallback(()=>{const Q=x;y(Xe=>Xe.filter(Ze=>Ze!==Q)),k(Xe=>Xe.filter(Ze=>Ze!==Q)),Q==="github"&&!pe&&yt(!1);const Oe=kt(x);Oe>0&&v(di[Oe-1])},[x,pe,yt,kt]),Ut=a.useCallback(()=>{Rt()},[Rt]),St=a.useCallback(async Q=>{Ge(Oe=>{const Xe=Oe[Q];if(Xe&&Xe!=="pending"){const{[Q]:Ze,...pt}=Oe;return pt}return Oe}),J(Oe=>{if(!(Q in Oe))return Oe;const Xe={...Oe};return delete Xe[Q],Xe}),Ge(Oe=>({...Oe,[Q]:"pending"})),A(Q),Fe.current=0;try{const{url:Oe,instructions:Xe}=await Lv(Q);Xe?.trim()&&J(Ze=>({...Ze,[Q]:Xe})),window.open(Ks(Oe),"_blank"),Je.current=setInterval(async()=>{if(Fe.current++,Fe.current>=k4){Je.current&&(clearInterval(Je.current),Je.current=null),A(null),Ge(Ze=>({...Ze,[Q]:"timeout"})),J(Ze=>{if(!(Q in Ze))return Ze;const pt={...Ze};return delete pt[Q],pt}),n("Login timed out. Please try again.","warning");return}try{const{providers:Ze,ghCli:pt}=await ir();R(Ze),G(pt),Ze.find(At=>At.id===Q)?.authenticated&&(Je.current&&(clearInterval(Je.current),Je.current=null),A(null),Ge(At=>({...At,[Q]:"success"})),J(At=>{if(!(Q in At))return At;const xn={...At};return delete xn[Q],xn}),Q==="github"&&yt(!1),n("Login successful","success"))}catch{}},2e3)}catch(Oe){Oe instanceof Error&&Oe.message.includes("already in progress")||Oe&&typeof Oe=="object"&&"status"in Oe&&Oe.status===409?(n("Login already in progress. Please wait or cancel the current attempt.","warning"),Ge(Ze=>({...Ze,[Q]:"failed"}))):(n(Oe instanceof Error?Oe.message:"Login failed","error"),Ge(Ze=>({...Ze,[Q]:"failed"}))),A(null),J(Ze=>{if(!(Q in Ze))return Ze;const pt={...Ze};return delete pt[Q],pt})}},[n,yt]),Et=a.useCallback(Q=>{Je.current&&(clearInterval(Je.current),Je.current=null),A(null),Fe.current=0,Ge(Oe=>({...Oe,[Q]:"cancelled"})),J(Oe=>{if(!(Q in Oe))return Oe;const Xe={...Oe};return delete Xe[Q],Xe})},[]),It=a.useCallback((Q,Oe)=>{ee(Ze=>({...Ze,[Q]:Oe}));const Xe=Me.current[Q];Xe&&(clearTimeout(Xe),delete Me.current[Q]),ue(Ze=>{if(!Ze[Q])return Ze;const pt={...Ze};return delete pt[Q],pt}),ie(Ze=>{if(!Ze[Q])return Ze;const pt={...Ze};return delete pt[Q],pt})},[]),Mt=a.useCallback(()=>{const Q=ze.current;if(!Q)return;const Oe=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof Q.scrollTo=="function"){Q.scrollTo({top:0,behavior:Oe?"auto":"smooth"});return}}catch{}Q.scrollTop=0},[]),Kt=a.useCallback(async(Q,Oe)=>{const Xe=(Oe??Ne[Q]??"").trim(),Ze=g4(Q,Xe);if(Ze){ue(Nt=>({...Nt,[Q]:Ze}));return}const pt=Me.current[Q];pt&&(clearTimeout(pt),delete Me.current[Q]),A(Q),ue(Nt=>{const At={...Nt};return delete At[Q],At}),ie(Nt=>{if(!Nt[Q])return Nt;const At={...Nt};return delete At[Q],At});try{await Fv(Q,Xe),await V(),Mt(),ee(Nt=>{const At={...Nt};return delete At[Q],At}),ue(Nt=>{if(!Nt[Q])return Nt;const At={...Nt};return delete At[Q],At}),ie(Nt=>({...Nt,[Q]:"✓ Key saved"})),Me.current[Q]=setTimeout(()=>{ie(Nt=>{if(!Nt[Q])return Nt;const At={...Nt};return delete At[Q],At}),delete Me.current[Q]},3e3),n("API key saved","success")}catch(Nt){const At=Nt instanceof TypeError&&Nt.message.includes("Failed to fetch")?"Could not reach the server. Check your connection and try again.":Nt instanceof Error?Nt.message:"Failed to save API key";ue(xn=>({...xn,[Q]:At})),ie(xn=>{if(!xn[Q])return xn;const Qt={...xn};return delete Qt[Q],Qt}),n(At,"error")}finally{A(null)}},[Ne,n,V,Mt]),Ot=a.useCallback(async Q=>{A(Q);try{await Ov(Q),await V(),n("API key removed","success")}catch(Oe){n(Oe instanceof Error?Oe.message:"Failed to clear API key","error")}finally{A(null)}},[n,V]),xe=a.useCallback(async Q=>{A(Q);try{await zv(Q),await V(),n("Logged out","success")}catch(Oe){n(Oe instanceof Error?Oe.message:"Logout failed","error")}finally{A(null)}},[n,V]),st=a.useCallback(Q=>{se(Q)},[]),Ve=a.useCallback(async()=>{try{const Q={modelOnboardingComplete:!0};if(he){const Oe=he.indexOf("/"),Xe=Oe!==-1?he.slice(0,Oe):void 0,Ze=Oe!==-1?he.slice(Oe+1):he,pt=W.find(Nt=>Nt.id===Ze);pt?(Q.defaultProvider=pt.provider,Q.defaultModelId=pt.id):Xe&&Ze&&(Q.defaultProvider=Xe,Q.defaultModelId=Ze)}await an(Q),lh()}catch{}},[he,W,an,lh]),Y=a.useCallback(async()=>{const Q=[...new Set([...b,"first-task"])];U(!0);try{await Ve(),Ns("onboarding:completed",{completedSteps:Q,skippedSteps:S}),y(Q),k(Oe=>Oe.filter(Xe=>Xe!=="first-task")),v("complete")}finally{U(!1)}},[Ve,b,S]),F=a.useCallback(async()=>{if(!s)return;const Q=_.trim();if(!Q){z("Please enter a task description.");return}z(null),T(!0);let Oe=!1;try{const Xe=await qh({description:Q},s);P(Xe),w(!0),Ns("onboarding:first-task-created",{taskId:Xe?.id}),n("Task created","success"),Oe=!0}catch(Xe){const Ze=Xe instanceof Error?Xe.message:"Something went wrong creating your task. Please try again.";z(Ze),n(Ze,"error")}finally{T(!1)}Oe&&Ve()},[s,_,n,Ve]),H=a.useCallback(async()=>{U(!0);try{await Ve()}finally{U(!1)}Ns("onboarding:open-new-task",{}),r?.()},[Ve,r]),ge=a.useCallback(async()=>{if(Qe){U(!0);try{await Ve()}finally{U(!1)}f(!1),e(),Ns("onboarding:open-github-import",{}),o?.()}},[Ve,Qe,e,o]),me=a.useCallback(async()=>{Ns("onboarding:dismissed",{currentStep:x,completedSteps:b,skippedSteps:S}),U(!0);try{await an({modelOnboardingComplete:!0})}catch{}f(!1),e()},[x,b,S,e]),We=a.useCallback(()=>{Ns("onboarding:finished",{}),f(!1),e()},[e]),dt=a.useCallback(()=>{const Q=l??K;Q&&(Ve(),c?.(Q),e())},[l,K,Ve,c,e]),_t=a.useCallback(()=>{Ve(),e()},[Ve,e]);if(!p)return null;const $t=ct(),vn=E.filter(Q=>Q.id!=="github"),kn=[...vn].sort(hh),Yt=kn.some(Q=>!Q.type||Q.type==="oauth"),En=kn.some(Q=>Q.type==="api_key"),on=vn.filter(Q=>Q.authenticated),Mn=on.length>0,Vt=!!s,hn=x==="github"&&!Mn,ke=(()=>{if(!he)return"";const Q=he.indexOf("/"),Oe=Q===-1?void 0:he.slice(0,Q),Xe=Q===-1?he:he.slice(Q+1),Ze=W.find(pt=>pt.id===Xe&&(!Oe||pt.provider===Oe));return Ze?.name?Ze.name:Oe?`${Rc(Oe)} ${Xe}`:he})(),nt=[];if(Vt?nt.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):nt.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),Mn){const Q=Rc(on[0]?.id??"");nt.push({label:"AI Provider",status:"connected",detail:`${Q} connected — AI agents can work on tasks`})}else vn.length>0&&vn.some(Q=>Pe[Q.id])?nt.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):nt.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});Qe?nt.push({label:"GitHub",status:"connected",detail:Ee?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!we||it?nt.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):nt.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),ke&&nt.push({label:"Default Model",status:"connected",detail:ke});const tn=l??K,Pn=tn?.description?.split(`
646
+ `)[0]?.trim()||tn?.title||"",Nn=new Set(Kl),gn=kn.filter(Q=>Nn.has(Q.id)).sort((Q,Oe)=>{const Xe=Kl.indexOf(Q.id),Ze=Kl.indexOf(Oe.id);return Xe!==Ze?Xe-Ze:hh(Q,Oe)}),nn=kn.filter(Q=>Q.authenticated&&!Nn.has(Q.id)),_n=kn.filter(Q=>!Q.authenticated&&!Nn.has(Q.id)),jn=Q=>{if(Q.id==="claude-cli"&&Q.type==="cli")return t.jsx(qR,{authenticated:Q.authenticated,onToggled:()=>{V()}},Q.id);if(Q.type==="api_key"){const Oe=Pc(Q.id),Xe=b4(Q);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${Q.id}`,className:`onboarding-provider-card${Q.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${Q.id}`,"aria-hidden":"true",children:t.jsx(Tn,{provider:Q.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(Lh,{size:14,className:"onboarding-provider-key-icon"}),Q.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:Oe.description}),t.jsx(Le,{status:Re(Q)}),Q.authenticated&&Q.keyHint&&t.jsxs("span",{className:"auth-key-hint",children:["Key: ",Q.keyHint]})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx(y4,{provider:Q,apiKeyInfo:Xe,inputValue:Ne[Q.id]??"",isSaving:$===Q.id,error:ve[Q.id],success:ye[Q.id],isConnected:Q.authenticated,onInputChange:It,onSave:Kt,onClear:Ot})})]},Q.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${Q.id}`,className:`onboarding-provider-card${Q.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${Q.id}`,"aria-hidden":"true",children:t.jsx(Tn,{provider:Q.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:Q.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:Pc(Q.id).description}),t.jsx(Le,{status:Re(Q)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:$===Q.id?t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:Q.authenticated?"Logging out…":"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Et(Q.id),children:"Cancel"})]}):Q.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>xe(Q.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>St(Q.id),children:"Login"})}),$===Q.id&&j[Q.id]&&t.jsx(Wl,{instructions:j[Q.id],"data-testid":`onboarding-login-instructions-${Q.id}`}),Ye[Q.id]==="timeout"&&$!==Q.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),Ye[Q.id]==="failed"&&$!==Q.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},Q.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:Be,children:[t.jsxs("div",{className:"model-onboarding-header",children:[t.jsxs("h2",{id:"onboarding-title",className:"model-onboarding-title",children:[x==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(In,{size:24})," Set Up AI ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(hs,{size:24})," Connect GitHub ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(wd,{size:24})," Set Up Your Project"]}),x==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(wd,{size:24})," Create Your First Task"]}),x==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx(un,{size:24})," All Set!"]})]}),x!=="complete"&&t.jsx("button",{className:"modal-close",onClick:me,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(zt,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:le.map((Q,Oe)=>{const Xe=at>Oe,Ze=b.includes(Q.key)&&Xe,pt=S.includes(Q.key)&&!b.includes(Q.key)&&Xe,Nt=Ze||pt;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[Oe>0&&t.jsx("div",{className:`model-onboarding-step-connector ${Oe<=at?"done":""}`}),Nt?t.jsxs("button",{className:`model-onboarding-step-indicator ${x===Q.key?"active":""} ${Ze?"done":""} ${pt?"skipped":""}`,onClick:()=>v(Q.key),"aria-label":`Go back to ${Q.label}`,title:`Review ${Q.label}`,children:[t.jsx("span",{className:"step-number",children:Ze?t.jsx(un,{size:14}):pt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Oe+1}),t.jsx("span",{className:"step-label",children:Q.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${x===Q.key?"active":""} ${Ze?"done":""} ${pt?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:Ze?t.jsx(un,{size:14}):pt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Oe+1}),t.jsx("span",{className:"step-label",children:Q.label})]})]},Q.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:ze,children:[x==="ai-setup"&&t.jsxs("div",{className:"model-onboarding-ai-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Fusion uses AI models to plan, write, and review code for you. Connect an AI provider below to get started — you can use a hosted service or enter an API key."}),t.jsx("p",{className:"onboarding-helper-text model-onboarding-primary-helper",children:"You only need one provider to get started."}),!X&&E.length>0&&(()=>{const Q=E.filter(Nt=>Nt.id!=="github"&&Nt.authenticated).length,Oe=E.filter(Nt=>Nt.id!=="github").length,Xe=Object.keys(Pe).filter(Nt=>!E.find(At=>At.id===Nt)?.authenticated).length;if(Oe===0)return null;let Ze="onboarding-provider-summary",pt="";return Q>0?(Ze+=" onboarding-provider-summary--connected",pt=`✓ ${Q} of ${Oe} provider${Oe!==1?"s":""} connected`):Xe>0?(Ze+=" onboarding-provider-summary--skipped",pt=`${Xe} provider${Xe!==1?"s":""} skipped`):(Ze+=" onboarding-provider-summary--none",pt="No providers connected yet"),t.jsx("div",{className:Ze,"data-testid":"provider-summary",children:pt})})(),t.jsx(Hs,{summary:"What are AI providers?",children:t.jsx("p",{className:"onboarding-helper-text",children:"AI providers like OpenAI and Anthropic power the AI capabilities in Fusion. Connecting a provider lets Fusion's agents use AI models to help with your tasks."})}),E.length>0&&!E.some(Q=>Q.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(rt,{size:24,className:"animate-spin"}),t.jsx("span",{children:"Loading providers…"})]}):E.length===0?t.jsx("div",{className:"model-onboarding-empty",children:"No AI providers are configured. Please check your Fusion configuration."}):t.jsxs(t.Fragment,{children:[t.jsxs("section",{className:"onboarding-provider-section","data-testid":"onboarding-quick-start-providers",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Quick start providers"}),gn.length>0?t.jsx("div",{className:"model-onboarding-providers",children:gn.map(Q=>jn(Q))}):t.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),nn.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:nn.map(Q=>jn(Q))})]}),t.jsx(Hs,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:t.jsx("div",{"data-testid":"onboarding-advanced-provider-settings",children:_n.length>0?t.jsx("div",{className:"model-onboarding-providers",children:_n.map(Q=>jn(Q))}):t.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."})})}),Yt&&t.jsx(Hs,{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."})}),En&&t.jsx(Hs,{summary:"What is an API key?",children:t.jsx("p",{className:"onboarding-helper-text",children:"An API key is a secret token that authenticates Fusion with the provider. You can find your key in the provider's dashboard under API settings. Keys are stored securely on your machine."})})]}),t.jsxs("div",{className:"onboarding-model-section",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Default Model (Optional)"}),t.jsx("p",{className:"model-onboarding-description",children:"Pick a default model for AI tasks, or leave this blank to choose later. Models vary in speed, capability, and cost."}),t.jsx(Hs,{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."})}),W.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(Ln,{models:W,value:he,onChange:st,placeholder:"Select a default model…",label:"Default model"})}),he&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",W.find(Q=>Q.id===he)?.name??he]})})]})]}),x==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[Qe?t.jsx("p",{className:"model-onboarding-description",children:Ee?"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."}),!Qe&&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(Hs,{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."})}),we?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"onboarding-provider-row",children:[t.jsxs("div",{className:"onboarding-provider-info",children:[t.jsxs("strong",{children:[t.jsx(hs,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(Se,{status:$t})})]}),pe&&($==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>xe("github"),children:"Disconnect"}))]}),($t==="not-connected"||$t==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[$==="github"?t.jsxs("div",{className:"onboarding-github-connect-actions",children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Et("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>St("github"),children:[t.jsx(hs,{size:16}),"Connect"]}),$==="github"&&j.github&&t.jsx(Wl,{instructions:j.github,"data-testid":"onboarding-login-instructions-github"})]}),$t==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:Ee?"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."}),$t==="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:()=>St("github"),children:"Retry"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Ut,children:"Skip for now"})]})]}),$t==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),$t==="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:()=>St("github"),children:"Connect anyway"})})]}),$t==="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(Tn,{provider:"github",size:"lg"})}),Ee?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:Ee?"Continue with gh CLI auth →":"Continue without GitHub →"}),Ee&&($==="github"?t.jsxs("button",{className:"btn btn-sm",disabled:!0,children:[t.jsx(rt,{size:14,className:"onboarding-spinner"}),"Waiting for OAuth login…"]}):t.jsxs("button",{className:"btn btn-sm",onClick:()=>St("github"),children:[t.jsx(Tn,{provider:"github",size:"sm"}),"Connect OAuth (optional)"]}))]}),Ee&&$==="github"&&j.github&&t.jsx(Wl,{instructions:j.github,"data-testid":"onboarding-login-instructions-github"})]})]}),x==="project-setup"&&t.jsxs("div",{className:"model-onboarding-project-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Choose your first project before creating or importing tasks. You can register an existing local directory or clone a GitHub repository URL through the setup wizard."}),Vt?t.jsx("div",{className:"onboarding-project-ready","data-testid":"onboarding-project-ready",role:"status",children:t.jsx("p",{children:"Project selected — task creation and imports are available."})}):t.jsxs("div",{className:"onboarding-project-prerequisite","data-testid":"onboarding-project-prerequisite",children:[t.jsx("p",{className:"onboarding-helper-text",children:"A project is required before first-task actions are available."}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:i,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"}),t.jsx("p",{className:"onboarding-helper-text",children:"In the setup wizard, pick an existing directory or paste a GitHub clone URL."})]}),t.jsx(Hs,{summary:"What does project setup do?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Project setup registers a workspace so Fusion knows where to read files, run commands, and track task changes."})})]}),x==="first-task"&&t.jsxs("div",{className:"model-onboarding-first-task",children:[t.jsx("p",{className:"model-onboarding-description",children:"Create your first task to start the board and launch AI execution."}),M&&tn?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx(un,{size:56,className:"success-icon"}),t.jsx("h3",{className:"onboarding-task-created__title",children:"Your first task is ready!"}),t.jsx("div",{className:"onboarding-task-created__task-id",children:tn.id}),Pn&&t.jsx("p",{className:"onboarding-task-created__description",children:Pn}),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:dt,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:_t,children:"Go to Dashboard"})]})]}):t.jsxs(t.Fragment,{children:[Vt?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"onboarding-first-task-form",children:[t.jsx("label",{className:"onboarding-first-task-form__label",htmlFor:"onboarding-first-task-input",children:"Describe your first task"}),t.jsx("textarea",{id:"onboarding-first-task-input",className:"input onboarding-first-task-form__input","data-testid":"onboarding-first-task-input",value:_,onChange:Q=>{N(Q.target.value),z(null)},placeholder:"Example: Build a login page with email and password",rows:4}),t.jsx("div",{className:"onboarding-first-task-form__actions",children:t.jsx("button",{type:"button",className:"btn btn-primary",onClick:F,disabled:L,"data-testid":"onboarding-first-task-submit",children:L?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),I&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:I}),t.jsx("p",{className:"onboarding-helper-text",children:"Your text has been preserved — fix the issue and try again."})]})]}):t.jsxs("div",{className:"onboarding-project-prerequisite","data-testid":"onboarding-project-prerequisite",children:[t.jsx("p",{className:"onboarding-helper-text",children:"A project must be selected before you can create tasks or import from GitHub."}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:i,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"})]}),t.jsx(v4,{items:nt}),Vt&&t.jsxs(t.Fragment,{children:[t.jsx(Hs,{summary:"What happens when I create a task?",children:t.jsx("p",{className:"onboarding-helper-text",children:"A task describes something you want done. Fusion's AI agents will read your description and work on implementing it. You can track progress on the board and review the results."})}),t.jsxs("div",{className:"onboarding-cta-options",children:[t.jsxs("button",{className:"onboarding-cta-card primary",onClick:H,disabled:fe,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(Xt,{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${Qe?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:ge,disabled:fe||!Qe,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(hs,{size:24})}),t.jsxs("div",{className:"cta-content",children:[t.jsx("strong",{children:"Import from GitHub"}),t.jsx("span",{children:"Turn GitHub issues into tasks you can track here"}),!Qe&&t.jsx("small",{className:"onboarding-cta-note",children:"Requires GitHub connection"})]})]})]}),t.jsxs("p",{className:"onboarding-skip-note",children:["You can create tasks anytime from the board, or use"," ",t.jsx("code",{children:"fn task create"})," in the terminal."]})]})]})]}),x==="complete"&&t.jsxs("div",{className:"model-onboarding-complete",children:[t.jsx(un,{size:48,className:"success-icon"}),t.jsx("p",{children:"Setup complete! Head to the board to create your first task, or explore the dashboard to see what's available."})]})]}),t.jsxs("div",{className:"model-onboarding-footer",children:[x==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:me,disabled:fe,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Rt,children:"Skip setup →"}),t.jsx("button",{className:"btn btn-primary",onClick:Ct,children:"Next →"})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Ft,children:"← Back"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Rt,children:"Skip GitHub →"}),t.jsx("button",{className:"btn btn-primary",onClick:Ct,children:"Next →"})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Ft,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:Ct,disabled:!Vt,children:"Next →"})]}),x==="first-task"&&!M&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Ft,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:Y,disabled:fe,children:fe?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),x==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:We,children:[t.jsx(un,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function Gf({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 w4=a.lazy(()=>sn(()=>import("./SetupWizardModal-oRNpImWR.js"),__vite__mapDeps([6,1,7,8,9,0,2,10])).then(e=>({default:e.SetupWizardModal}))),N4=a.lazy(()=>sn(()=>import("./SettingsModal-GZdRt8fX.js"),__vite__mapDeps([11,1,12,13,14,15,0,2,16])).then(e=>({default:e.SettingsModal})));function S4(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{sn(()=>import("./SettingsModal-GZdRt8fX.js"),__vite__mapDeps([11,1,12,13,14,15,0,2,16]))},{timeout:1500})}function C4({projectId:e,tasks:n,projects:s,currentProject:i,addToast:r,toasts:o,removeToast:l,modalManager:c,projectActions:u,taskHandlers:d,taskOperations:m,deepLink:h,settings:g,onSettingsClose:p,onReopenOnboarding:f}){const[x,v]=a.useState(null),b=p??c.closeSettings,y=a.useCallback(()=>{c.openNewTask()},[c]),S=a.useCallback(()=>{c.openGitHubImport()},[c]),k=a.useCallback(w=>{v(null),c.closeModelOnboarding(),c.openDetailTask(w)},[c]),M=a.useCallback(async w=>{const _=await d.handleModalCreate(w);return c.modelOnboardingOpen&&v(_),_},[d.handleModalCreate,c.modelOnboardingOpen]);return a.useEffect(()=>{!c.modelOnboardingOpen&&x&&v(null)},[c.modelOnboardingOpen,x]),a.useEffect(()=>{S4()},[]),t.jsxs(t.Fragment,{children:[c.detailTask&&t.jsx(wi,{children:t.jsx(N_,{task:c.detailTask,projectId:e,tasks:n,onClose:h.handleDetailClose,onOpenDetail:c.openDetailTask,onMoveTask:m.moveTask,onDeleteTask:m.deleteTask,onMergeTask:m.mergeTask,onRetryTask:m.retryTask,onDuplicateTask:m.duplicateTask,onTaskUpdated:c.updateDetailTask,addToast:r,prAuthAvailable:g.prAuthAvailable,initialTab:c.detailTaskInitialTab})}),c.settingsOpen&&t.jsx(wi,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(N4,{onClose:b,addToast:r,initialSection:c.settingsInitialSection,projectId:e,themeMode:g.themeMode,colorTheme:g.colorTheme,onThemeModeChange:g.setThemeMode,onColorThemeChange:g.setColorTheme,onReopenOnboarding:f})})}),t.jsx(C_,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:d.handleGitHubImport,tasks:n,projectId:e}),t.jsx(wi,{children:t.jsx(A_,{isOpen:c.isPlanningOpen,onClose:c.closePlanning,onTaskCreated:d.handlePlanningTaskCreated,onTasksCreated:d.handlePlanningTasksCreated,tasks:n,initialPlan:c.planningInitialPlan??void 0,projectId:e,resumeSessionId:c.planningResumeSessionId})}),t.jsx(wi,{children:t.jsx(O_,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:d.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx(oA,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx(cA,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx(AA,{initialWorkspace:c.fileBrowserWorkspace,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),t.jsx(FA,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e,anchorRect:c.usageAnchorRect}),t.jsx(pR,{isOpen:c.systemStatsOpen,onClose:c.closeSystemStats,projectId:e}),c.schedulesOpen&&t.jsx(aR,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx(wi,{children:t.jsx(cR,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:M,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan,onSubtaskBreakdown:c.openSubtaskBreakdown})}),t.jsx(vR,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:i,onOpenTaskDetail:w=>{const _=n.find(N=>N.id===w);_&&c.openDetailTask(_)}}),t.jsx(wi,{children:t.jsx(kR,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx(wi,{children:t.jsx(PR,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(HR,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(a.Suspense,{fallback:null,children:t.jsx(w4,{onProjectRegistered:u.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(j4,{onComplete:u.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:u.handleAddProject,onOpenNewTask:y,onOpenGitHubImport:S,firstCreatedTask:x,onViewTask:k}),t.jsx(Gf,{toasts:o,onRemove:l})]})}function E4({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 Ic=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function M4(e,n){if(n==="ready")return"done";const s=Ic.findIndex(r=>r.id===n),i=Ic.findIndex(r=>r.id===e);return i<s?"done":i===s?"active":"pending"}function _4({stage:e}){const[n]=a.useState(()=>Ub());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:Ic.map(s=>{const i=M4(s.id,e);return t.jsxs("li",{className:`dashboard-loader__step dashboard-loader__step--${i}`,"data-testid":`dashboard-loader-step-${s.id}`,children:[t.jsx("span",{className:"dashboard-loader__step-icon","aria-hidden":"true",children:i==="done"?"✓":i==="active"?t.jsx(rt,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:s.label})]},s.id)})})]})})}const A4=5e3;function R4(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function T4(e,n,s){let i=0,r=0,o=0,l=0,c=0;for(const u of e){switch(u.column){case"in-progress":i++,lo(u,n,s)&&o++;break;case"todo":l++;break;case"in-review":c++;break}u.blockedBy&&u.blockedBy.length>0&&r++}return{runningTaskCount:i,blockedTaskCount:r,stuckTaskCount:o,queuedTaskCount:l,inReviewCount:c}}function P4(e,n,s,i){const[r,o]=a.useState({globalPause:!1,enginePaused:!1,maxConcurrent:2}),[l,c]=a.useState(!0),[u,d]=a.useState(null),m=a.useRef(null),h=a.useRef(null),g=a.useCallback(async()=>{h.current&&h.current.abort(),h.current=new AbortController;try{c(!0),d(null);const v=await bk(n);o(v)}catch(v){if(v instanceof Error&&v.name==="AbortError")return;d(v instanceof Error?v.message:"Failed to fetch executor stats")}finally{c(!1)}},[n]);a.useEffect(()=>(g(),()=>{h.current&&h.current.abort()}),[g]),a.useEffect(()=>(m.current&&clearInterval(m.current),m.current=setInterval(()=>{g()},A4),()=>{m.current&&(clearInterval(m.current),m.current=null)}),[g]);const p=T4(e,s,i),f=R4(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:f,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:u,refresh:g}}const I4={planning:Ws,subtask:Ti,mission_interview:rs,milestone_interview:rs,slice_interview:rs},$4={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function D4({sessions:e,generating:n,needsInput:s,onOpenSession:i,onDismissSession:r}){const{confirm:o}=Is(),[l,c]=a.useState(!1),[u,d]=a.useState(new Set),m=a.useRef(null),h=a.useRef(new Map),g=a.useRef(null),{activeTabMap:p}=ba(),f=a.useMemo(()=>Li(),[]);if(a.useEffect(()=>{if(!l)return;const b=y=>{m.current&&!m.current.contains(y.target)&&c(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[l]),a.useEffect(()=>{const b=new Set,y=new Map;for(const S of e){const k=p.get(S.id),M=[S.status,S.updatedAt,k?.tabId??S.lockedByTab??"",k?.stale?"stale":"fresh"].join("|"),w=h.current.get(S.id);w&&w!==M&&b.add(S.id),y.set(S.id,M)}if(h.current=y,b.size!==0)return d(b),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{d(new Set),g.current=null},500),()=>{g.current&&(clearTimeout(g.current),g.current=null)}},[p,e]),e.length===0)return null;const x=e.length,v=s>0;return t.jsxs("div",{ref:m,className:"background-tasks-indicator",children:[t.jsxs("button",{className:`background-tasks-indicator__pill${v?" background-tasks-indicator__pill--attention":""}`,onClick:()=>c(b=>!b),title:`${x} background AI task${x!==1?"s":""}${s>0?` (${s} need${s!==1?"":"s"} input)`:""}`,children:[n>0&&t.jsx(rt,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&t.jsx(ec,{size:12}),t.jsxs("span",{children:["AI ",x]})]}),l&&t.jsxs("div",{className:"background-tasks-indicator__popover",children:[t.jsx("div",{className:"background-tasks-indicator__popover-header",children:"Background Tasks"}),t.jsx("div",{className:"background-tasks-indicator__popover-list",children:e.map(b=>{const y=I4[b.type],S=b.status==="generating",k=b.status==="awaiting_input",M=b.status==="error",w=p.get(b.id),_=w?.tabId??b.lockedByTab??null,N=!!(_&&_!==f&&!w?.stale),L=u.has(b.id);return t.jsxs("div",{className:`background-tasks-indicator__item${L?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:L?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:L?"translateY(-1px)":void 0},onClick:async()=>{N&&!await o({title:"Open Active Session",message:"This session is active in another tab. Open anyway?"})||(i(b),c(!1))},children:[M?t.jsx(Zn,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--color-error)"}}):t.jsx(y,{size:14,className:"background-tasks-indicator__session-icon"}),t.jsxs("div",{className:"background-tasks-indicator__session-content",children:[t.jsx("div",{className:"background-tasks-indicator__session-title",children:b.title}),t.jsxs("div",{className:"background-tasks-indicator__session-meta",children:[M?"Failed":$4[b.type],S&&" — generating...",k&&!N&&" — needs input",k&&N&&" — active in another tab"]})]}),S&&t.jsx(rt,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),k&&!N&&t.jsx(ec,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),k&&N&&t.jsx(No,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),t.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:T=>{T.stopPropagation(),r(b.id)},title:"Dismiss",children:t.jsx(zt,{size:12})})]},b.id)})})]})]})}function L4(e){if(!e)return"no activity";const n=Date.now(),s=new Date(e).getTime(),i=n-s,r=Math.floor(i/1e3),o=Math.floor(r/60),l=Math.floor(o/60),c=Math.floor(l/24);return c>0?`${c}d ago`:l>0?`${l}h ago`:o>0?`${o}m ago`:r>10?`${r}s ago`:"just now"}function z4(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:fn};case"paused":return{label:"Paused",color:"var(--triage)",icon:qs};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:In}}}function F4({tasks:e,projectId:n,taskStuckTimeoutMs:s,backgroundSessions:i,backgroundGenerating:r,backgroundNeedsInput:o,onOpenBackgroundSession:l,onDismissBackgroundSession:c,lastFetchTimeMs:u,currentProjectPath:d,onOpenProjectDirectory:m}){const{stats:h,loading:g,error:p}=P4(e,n,s,u),[f,x]=a.useState(!1),v=a.useMemo(()=>z4(h.executorState),[h.executorState]),b=a.useMemo(()=>L4(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(zc,{size:14}),p]})}):g&&h.runningTaskCount===0?t.jsx("div",{className:"executor-status-bar executor-status-bar--loading",role:"status","aria-label":"Executor status",children:t.jsx("span",{className:"executor-status-bar__loading-text",children:"Loading..."})}):t.jsxs("div",{className:`executor-status-bar ${h.executorState==="running"?"executor-status-bar--running":""}`,role:"status","aria-label":"Executor status",children:[i&&i.length>0&&l&&c&&t.jsxs(t.Fragment,{children:[t.jsx(D4,{sessions:i,generating:r??0,needsInput:o??0,onOpenSession:l,onDismissSession:c}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--queued","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Queued"}),t.jsx("span",{className:"executor-status-bar__count",children:h.queuedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--running ${h.runningTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Running"}),t.jsx("span",{className:"executor-status-bar__count",children:h.runningTaskCount}),t.jsx("span",{className:"executor-status-bar__separator","aria-hidden":"true",children:"/"}),t.jsx("span",{className:"executor-status-bar__max",children:h.maxConcurrent})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),h.stuckTaskCount>0&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--stuck",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--stuck executor-status-bar__indicator--active","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Stuck"}),t.jsx("span",{className:"executor-status-bar__count executor-status-bar__count--error",children:h.stuckTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--blocked ${h.blockedTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Blocked"}),t.jsx("span",{className:`executor-status-bar__count ${h.blockedTaskCount>0?"executor-status-bar__count--warning":""}`,children:h.blockedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--review","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"In Review"}),t.jsx("span",{className:"executor-status-bar__count",children:h.inReviewCount})]}),d&&m&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--project-directory",children:[t.jsx("button",{className:`executor-status-bar__folder-toggle${f?" executor-status-bar__folder-toggle--active":""}`,onClick:()=>x(S=>!S),"aria-label":f?"Hide project directory":"Show project directory","aria-expanded":f,"data-testid":"executor-project-path-toggle",title:f?"Hide project directory":"Show project directory",children:t.jsx(Dn,{size:12,"aria-hidden":"true"})}),f&&t.jsx("button",{className:"executor-status-bar__project-path",onClick:m,title:d,"data-testid":"executor-project-path-link",children:d})]})]}),t.jsx("div",{className:"executor-status-bar__spacer"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--time",children:[t.jsx(hi,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__time",children:b})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx(y,{size:12,style:{color:v.color},"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__state",style:{color:v.color},children:v.label})]})]})}const O4={planning:Ws,subtask:Ti,mission_interview:rs,milestone_interview:rs,slice_interview:rs},U4={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},Ci=new Set;function B4({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:i}){const[r,o]=a.useState(0),l=()=>o(f=>f+1);a.useEffect(()=>{if(Ci.size===0)return;const f=new Map(e.map(v=>[v.id,v]));let x=!1;for(const v of Ci){const b=f.get(v);b&&b.status!=="awaiting_input"&&b.status!=="error"&&(Ci.delete(v),x=!0)}x&&l()},[e]);const c=a.useMemo(()=>e.filter(f=>(f.status==="awaiting_input"||f.status==="error")&&!Ci.has(f.id)),[e,r]);if(c.length===0)return null;const u=c.filter(f=>f.status==="awaiting_input").length,d=c.filter(f=>f.status==="error").length;let m="";u>0&&d>0?m=`${u} AI session${u===1?"":"s"} need${u===1?"s":""} your input, ${d} failed`:u>0?m=`${u} AI session${u===1?"":"s"} need${u===1?"s":""} your input`:d>0&&(m=`${d} AI session${d===1?"":"s"} failed`);const h=f=>{Ci.add(f),l()},g=f=>{Ci.delete(f.id),l(),n(f)},p=()=>{for(const f of c)Ci.add(f.id);l(),i()};return t.jsxs("section",{className:"session-notification-banner",role:"region","aria-live":"polite","aria-label":"AI sessions needing input or failed",children:[t.jsxs("div",{className:"session-notification-banner__header",children:[t.jsxs("div",{className:"session-notification-banner__headline",children:[t.jsx(Zn,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:m})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[t.jsx(zt,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Dismiss all"})]})]}),t.jsx("div",{className:"session-notification-banner__list",children:c.map(f=>{const x=O4[f.type],v=f.status==="error";return t.jsxs("article",{className:`session-notification-banner__item${v?" session-notification-banner__item--error":""}`,"data-session-type":f.type,"data-session-status":f.status,children:[t.jsxs("div",{className:"session-notification-banner__item-main",children:[v?t.jsx(Zn,{size:16,className:"session-notification-banner__type-icon session-notification-banner__type-icon--error","aria-hidden":"true"}):t.jsx(x,{size:16,className:"session-notification-banner__type-icon","aria-hidden":"true"}),t.jsxs("div",{className:"session-notification-banner__text",children:[t.jsx("p",{className:"session-notification-banner__title",title:f.title,children:f.title}),t.jsx("p",{className:"session-notification-banner__meta",children:v?"Failed":U4[f.type]})]})]}),t.jsxs("div",{className:"session-notification-banner__actions",children:[t.jsx("button",{className:"session-notification-banner__resume",onClick:()=>g(f),children:v?"Retry":"Resume"}),t.jsx("button",{className:"session-notification-banner__dismiss",onClick:()=>{h(f.id),s(f.id)},"aria-label":`Dismiss ${f.title}`,children:t.jsx(zt,{size:14,"aria-hidden":"true"})})]})]},f.id)})})]})}function H4({latestVersion:e,currentVersion:n,onDismiss:s}){return t.jsxs("div",{className:"update-available-banner",role:"status","aria-live":"polite",children:[t.jsxs("p",{className:"update-available-banner__text",children:["Update available: v",e," (current: v",n,"). Run ",t.jsx("code",{children:"npm i -g @runfusion/fusion"})," to update. "," ",t.jsx("a",{className:"update-available-banner__link",href:"https://github.com/Runfusion/Fusion/releases",target:"_blank",rel:"noreferrer",children:"Release notes"})]}),t.jsx("button",{type:"button",className:"update-available-banner__dismiss touch-target","aria-label":"Dismiss update notice",onClick:s,children:t.jsx(zt,{size:16,"aria-hidden":"true"})})]})}function q4({onResume:e}){const n=ZR();if(!n)return null;const s=n.completedSteps.length,i=di.length,r=s>0?`${s} of ${i} step${s!==1?"s":""} complete — You're on the `:"You're on the ";return t.jsxs("section",{className:"onboarding-resume-card",role:"region","aria-label":"Resume onboarding",children:[t.jsxs("div",{className:"onboarding-resume-card__main",children:[t.jsx("div",{className:"onboarding-resume-card__icon","aria-hidden":"true",children:t.jsx(Vn,{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:()=>{Ns("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),e()},children:[t.jsx(fn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function V4({onOpenSettings:e,onOpenModelOnboarding:n}){const s=fa(),i=qf(),[r,o]=a.useState(!0),[l,c]=a.useState(!1),[u,d]=a.useState(!1),[m,h]=a.useState({needsAiProvider:!1,needsDefaultModel:!1,needsGitHub:!1});a.useEffect(()=>{if(!s||i){o(!1);return}let b=!1;return(async()=>{try{o(!0),c(!1);const[S,k]=await Promise.all([ir(),Di()]);if(b)return;const M=S.providers??[],w=M.find(I=>I.id==="github"),N=!M.some(I=>I.id!=="github"&&I.authenticated),L=!k.defaultProvider&&!k.defaultModelId,T=w?!w.authenticated:!1;h({needsAiProvider:N,needsDefaultModel:L,needsGitHub:T})}catch{b||c(!0)}finally{b||o(!1)}})(),()=>{b=!0}},[s,i]);const g=a.useCallback(()=>{QR(),d(!0)},[]),p=a.useCallback(()=>{n()},[n]),f=a.useCallback(()=>{e("global-models")},[e]),x=a.useCallback(()=>{e("authentication")},[e]),v=a.useMemo(()=>{const b=[];return m.needsAiProvider&&b.push({id:"ai-provider",title:"Connect AI Provider",description:"Connect an AI provider to enable AI agents for task planning and code generation",actionLabel:"Set Up AI",onAction:p,icon:In}),m.needsDefaultModel&&b.push({id:"default-model",title:"Select Default Model",description:"Choose a default AI model for task execution",actionLabel:"Choose Model",onAction:f,icon:Lh}),m.needsGitHub&&b.push({id:"github",title:"Connect GitHub",description:"Connect GitHub to import issues and track pull requests",actionLabel:"Connect GitHub",onAction:x,icon:hs}),b},[m.needsAiProvider,m.needsDefaultModel,m.needsGitHub,x,f,p]);return!s||i||u||r||l||v.length===0?null:t.jsxs("section",{className:"post-onboarding-recommendations",role:"region","aria-label":"Setup recommendations",children:[t.jsxs("div",{className:"post-onboarding-recommendations__main",children:[t.jsx("div",{className:"post-onboarding-recommendations__icon","aria-hidden":"true",children:t.jsx(Ws,{size:18,"aria-hidden":!0})}),t.jsxs("div",{className:"post-onboarding-recommendations__content",children:[t.jsx("h2",{className:"post-onboarding-recommendations__title",children:"Recommended Next Steps"}),t.jsx("p",{className:"post-onboarding-recommendations__description",children:"Complete these setup items to get the most out of Fusion."}),t.jsx("ul",{className:"post-onboarding-recommendations__list",children:v.map(b=>{const y=b.icon;return t.jsxs("li",{className:"post-onboarding-recommendations__item",children:[t.jsxs("span",{className:"post-onboarding-recommendations__item-icon","aria-hidden":"true",children:[t.jsx(Zn,{size:14,"aria-hidden":!0}),t.jsx(y,{size:14,"aria-hidden":!0})]}),t.jsxs("span",{className:"post-onboarding-recommendations__item-text",children:[t.jsx("strong",{children:b.title}),t.jsx("span",{children:b.description})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-primary",onClick:b.onAction,children:b.actionLabel})]},b.id)})})]})]}),t.jsx("button",{type:"button",className:"post-onboarding-recommendations__dismiss",onClick:g,"aria-label":"Dismiss recommendations",children:t.jsx(zt,{size:16,"aria-hidden":!0})})]})}function W4({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 Gl(e){return e>99?"99+":String(e)}function K4({view:e,onChangeView:n,footerVisible:s,modalOpen:i=!1,onOpenSettings:r,onOpenActivityLog:o,onOpenSystemStats:l,onOpenMailbox:c,mailboxUnreadCount:u=0,onOpenGitManager:d,onOpenWorkflowSteps:m,onOpenSchedules:h,onOpenScripts:g,onToggleTerminal:p,onOpenFiles:f,onOpenGitHubImport:x,onOpenPlanning:v,onResumePlanning:b,activePlanningSessionCount:y=0,onOpenUsage:S,onRunScript:k,projectId:M,onViewAllProjects:w,showSkillsTab:_,experimentalFeatures:N}){const L=br(),[T,I]=a.useState(!1),[z,K]=a.useState(!1),[P,E]=a.useState({}),[R,B]=a.useState(!1),G=a.useMemo(()=>Object.entries(P).sort(([fe],[U])=>fe.localeCompare(U)),[P]);a.useEffect(()=>{if(!z)return;let fe=!1;return B(!0),ar(M).then(U=>{fe||E(U)}).catch(()=>{fe||E({})}).finally(()=>{fe||B(!1)}),()=>{fe=!0}},[z,M]);const X=a.useCallback(()=>I(!1),[]),C=a.useCallback(fe=>{X(),fe?.()},[X]);if(a.useEffect(()=>{if(!T)return;const fe=U=>{U.key==="Escape"&&I(!1)};return document.addEventListener("keydown",fe),()=>document.removeEventListener("keydown",fe)},[T]),L!=="mobile"||i)return null;const $=y>0&&b?b:v,A=!!N?.roadmap,j=!!_,J=!!N?.todoView,W=A&&(!j||e==="roadmaps"),oe=j&&(!A||e!=="roadmaps"),he=j&&!oe,se=e==="documents"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||e==="todos"&&J||e==="roadmaps"&&!W||e==="skills"&&!oe;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(Pi,{}),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(pn,{}),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(rs,{}),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(ui,{}),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(aa,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-nav-tab-badge",children:Gl(u)})]}),oe&&t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="skills"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-skills",role:"tab","aria-selected":e==="skills",onClick:()=>n("skills"),children:[t.jsx(In,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),W&&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(ac,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Roadmaps"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${se?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>I(fe=>!fe),children:[t.jsx(tc,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),T&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mobile-more-sheet-backdrop",onClick:X}),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:()=>C(c),children:[t.jsx(aa,{}),t.jsx("span",{children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:Gl(u)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>C(o),children:[t.jsx(Es,{}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-system-stats",onClick:()=>C(l),children:[t.jsx(nr,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>C(d),children:[t.jsx(Vs,{}),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:()=>C(p),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:()=>K(fe=>!fe),"aria-expanded":z,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(mn,{size:14,className:`mobile-more-chevron${z?" mobile-more-chevron--open":""}`})})]}),z&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:R?t.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[t.jsx(rt,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):G.length>0?t.jsxs(t.Fragment,{children:[G.map(([fe,U])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${fe}`,onClick:()=>{k&&k(fe,U),X(),K(!1)},children:[t.jsx(fn,{size:14}),t.jsx("span",{children:fe})]},fe)),g&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{X(),K(!1),g()},children:[t.jsx(Ts,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):g&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":"mobile-more-scripts-manage",onClick:()=>{X(),K(!1),g()},children:[t.jsx(Ts,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-files",onClick:()=>C(f),children:[t.jsx(Dn,{}),t.jsx("span",{children:"Files"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>C($),children:[t.jsx(Ws,{}),t.jsx("span",{children:"Planning"}),y>0&&t.jsx("span",{className:"mobile-more-item-badge",children:Gl(y)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>C(m),children:[t.jsx(oc,{}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>C(h),children:[t.jsx(hi,{}),t.jsx("span",{children:"Automation"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>C(x),children:[t.jsx(W4,{}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>C(S),children:[t.jsx(Es,{}),t.jsx("span",{children:"Usage"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>C(w),children:[t.jsx(Dh,{}),t.jsx("span",{children:"Projects"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>C(()=>n("documents")),children:[t.jsx(Ri,{}),t.jsx("span",{children:"Documents"})]}),he&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>C(()=>n("skills")),children:[t.jsx(In,{}),t.jsx("span",{children:"Skills"})]}),A&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-roadmaps",onClick:()=>C(()=>n("roadmaps")),children:[t.jsx(ac,{}),t.jsx("span",{children:"Roadmaps"})]}),N?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>C(()=>n("insights")),children:[t.jsx(Vn,{}),t.jsx("span",{children:"Insights"})]}),N?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>C(()=>n("memory")),children:[t.jsx(eo,{}),t.jsx("span",{children:"Memory"})]}),N?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{C(()=>n("dev-server"))},children:[t.jsx(nr,{size:14}),t.jsx("span",{children:"Dev Server"})]}),J&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-todos",onClick:()=>C(()=>n("todos")),children:[t.jsx(Oh,{size:14}),t.jsx("span",{children:"Todos"})]}),t.jsx("div",{className:"mobile-more-separator"}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-settings",onClick:()=>C(r),children:[t.jsx(Ja,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function G4({agents:e,filter:n,highlightedIndex:s,visible:i,onSelect:r,position:o="below"}){const l=a.useMemo(()=>{const c=n.trim().toLowerCase();return c?e.filter(u=>u.name.toLowerCase().includes(c)):e},[e,n]);return i?t.jsx("div",{className:`agent-mention-popup agent-mention-popup--${o}`,"data-testid":"agent-mention-popup",role:"listbox","aria-label":"Agent mention suggestions",children:l.length===0?t.jsx("div",{className:"agent-mention-empty",children:"No agents found"}):l.map((c,u)=>t.jsxs("button",{type:"button",className:`agent-mention-item${u===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${c.id}`,onMouseDown:d=>d.preventDefault(),onClick:()=>r(c),role:"option","aria-selected":u===s,children:[t.jsx(pn,{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 hd="__fn_agent__";function Jf(e,n){const s=typeof e=="string"?e.trim():"",i=typeof n=="string"?n.trim():"";return!s||!i?{}:{modelProvider:s,modelId:i}}function ph(e,n,s){const i=typeof e=="string"?e.trim():"",r=Jf(n,s),o=i||(r.modelProvider&&r.modelId?hd:"");return o?{agentId:o,...r}:null}function Jl(e,n,s){const i=Jf(n,s),r=i.modelProvider??"",o=i.modelId??"";return`${e}::${r}/${o}`}function J4(e){const n=e?.toolCalls;if(!Array.isArray(n))return;const s=n.map(i=>{if(!i||typeof i!="object")return null;const r=i,o=typeof r.toolName=="string"?r.toolName:"";if(!o)return null;const l=r.args;return{toolName:o,...l&&typeof l=="object"?{args:l}:{},isError:!!r.isError,result:r.result,status:"completed"}}).filter(i=>i!==null);return s.length>0?s:void 0}function fh(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:J4(e.metadata),createdAt:e.createdAt}}function Y4(e,n){const[s,i]=a.useState(null),[r,o]=a.useState(!1),[l,c]=a.useState([]),[u,d]=a.useState(!1),[m,h]=a.useState(!1),[g,p]=a.useState(""),[f,x]=a.useState(""),[v,b]=a.useState([]),[y,S]=a.useState(""),k=a.useRef(null),M=a.useRef(!1),w=a.useRef(""),_=a.useRef(""),N=a.useRef(null);a.useEffect(()=>{w.current=y},[y]);const L=a.useCallback(async X=>{const C={agentId:X.agentId};return X.modelProvider&&X.modelId&&(C.modelProvider=X.modelProvider,C.modelId=X.modelId),(await Tj(C,e)).session},[e]),T=a.useCallback(async(X,C,$)=>{const A=ph(X,C,$);if(!A)return;const j=Jl(A.agentId,A.modelProvider,A.modelId);o(!0);try{const{session:J}=await Rj({agentId:A.agentId,modelProvider:A.modelProvider,modelId:A.modelId},e);if(J)i(J),_.current=j;else{const W=await L(A);i(W),_.current=j}}catch(J){console.error("[useQuickChat] Failed to initialize session:",J),n?.("Failed to initialize chat","error")}finally{o(!1)}},[e,n,L]),I=a.useCallback(async()=>{if(s){d(!0);try{const X=await Gd(s.id,{limit:50},e);c(X.messages.map(fh))}catch(X){console.error("[useQuickChat] Failed to load messages:",X)}finally{d(!1)}}},[s,e]);a.useEffect(()=>{s?I():c([])},[s,I]);const z=a.useCallback(async()=>{if(s){d(!0);try{const X=await Gd(s.id,{limit:50},e);c(X.messages.map(fh))}catch(X){console.error("[useQuickChat] Failed to reload messages:",X)}finally{d(!1)}}},[s,e]),K=a.useCallback(async(X,C,$)=>{const A=ph(X,C,$);if(!A)return;const j=Jl(A.agentId,A.modelProvider,A.modelId);if(N.current=A,k.current&&(k.current.close(),k.current=null),p(""),x(""),b([]),h(!1),j===_.current&&s){await z();return}c([]),_.current=j,await T(A.agentId,A.modelProvider,A.modelId)},[T,z,s]),P=a.useCallback(async(X,C)=>{await K(hd,X,C)},[K]),E=a.useCallback(async()=>{const X=N.current;if(!X)return;const C=Jl(X.agentId,X.modelProvider,X.modelId);k.current&&(k.current.close(),k.current=null),p(""),x(""),b([]),h(!1),c([]),o(!0);try{const $=await L(X);i($),_.current=C}catch($){console.error("[useQuickChat] Failed to start a fresh session:",$),n?.("Failed to start a new chat","error")}finally{o(!1)}},[n,L]),R=a.useCallback(()=>{s&&(M.current=!0,k.current?.close(),k.current=null,Pj(s.id,e).catch(()=>{}),h(!1),p(""),x(""),b([]))},[s,e]),B=a.useCallback(()=>{w.current="",S("")},[]),G=a.useCallback(X=>{if(!s||!X.trim())return;if(m){w.current=X,S(X);return}M.current=!1,k.current&&(k.current.close(),k.current=null);const $={id:`temp-${Date.now()}`,sessionId:s.id,role:"user",content:X,createdAt:new Date().toISOString()};c(oe=>[...oe,$]),p(""),x(""),b([]),h(!0);let A="",j="",J=[];const W={onThinking:oe=>{j+=oe,x(j)},onText:oe=>{A+=oe,p(A)},onToolStart:oe=>{J=[...J,{toolName:oe.toolName,args:oe.args,isError:!1,status:"running"}],b(J)},onToolEnd:oe=>{const he=[...J];for(let se=he.length-1;se>=0;se--){const fe=he[se];if(fe?.toolName===oe.toolName&&fe.status==="running"){he[se]={...fe,status:"completed",isError:oe.isError,result:oe.result},J=he,b(he);return}}J=[...he,{toolName:oe.toolName,isError:oe.isError,result:oe.result,status:"completed"}],b(J)},onDone:oe=>{const he={id:oe.messageId||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:A,thinkingOutput:j||void 0,toolCalls:J.length>0?J:void 0,createdAt:new Date().toISOString()};c(fe=>[...fe,he]),p(""),x(""),b([]),h(!1),k.current=null;const se=w.current.trim();se&&(w.current="",S(""),G(se))},onError:oe=>{if(p(""),x(""),b([]),h(!1),k.current=null,console.error("[useQuickChat] Stream error:",oe),n?.("Failed to get response","error"),!M.current){const he=w.current.trim();he&&(w.current="",S(""),G(he))}z()}};k.current=Ij(s.id,X,W,e)},[s,m,e,n,z]);return a.useEffect(()=>()=>{k.current&&(k.current.close(),k.current=null)},[]),a.useMemo(()=>({activeSession:s,sessionsLoading:r,messages:l,messagesLoading:u,isStreaming:m,streamingText:g,streamingThinking:f,streamingToolCalls:v,pendingMessage:y,sendMessage:G,stopStreaming:R,clearPendingMessage:B,switchSession:K,startModelChat:P,startFreshSession:E,loadMessages:I,reloadMessages:z}),[s,r,l,u,m,g,f,v,y,G,R,B,K,P,E,I,z])}function Q4(e,n){const[s,i]=a.useState([]),[r,o]=a.useState(null),[l,c]=a.useState(!1),u=a.useCallback(async g=>{c(!0);try{const p=n?.filterState,f=p&&p!=="all"?{state:p}:void 0,x=n?.showSystemAgents??!1,v=await xa({...f,...g,includeEphemeral:g?.includeEphemeral??x},e),b=Array.from(new Map(v.map(y=>[y.id,y])).values());i(b)}catch(p){console.error("Failed to load agents:",p)}finally{c(!1)}},[e,n?.filterState,n?.showSystemAgents]),d=a.useCallback(async()=>{try{const g=await mk(e);o(g)}catch(g){console.error("Failed to load agent stats:",g)}},[e]);a.useEffect(()=>{u(),d()},[u,d]),a.useEffect(()=>{const g=e?`?projectId=${encodeURIComponent(e)}`:"",p=()=>{u(),d()};return $s(`/api/events${g}`,{events:{"agent:created":p,"agent:updated":p,"agent:deleted":p,"agent:stateChanged":p}})},[e,u,d]);const m=n?.showSystemAgents??!1,h=s.filter(g=>g.state!=="active"&&g.state!=="running"?!1:m||!Kj(g));return{agents:s,activeAgents:h,stats:r,isLoading:l,loadAgents:u,loadStats:d}}function X4({visible:e,position:n,files:s,selectedIndex:i,onSelect:r,loading:o}){return e?t.jsxs("div",{className:"file-mention-popup",style:{top:n.top,left:n.left},"data-testid":"file-mention-popup",onMouseDown:l=>{l.preventDefault()},children:[o&&t.jsx("div",{className:"file-mention-popup-loading","data-testid":"file-mention-loading",children:t.jsx("span",{className:"spinner"})}),!o&&s.length===0&&t.jsx("div",{className:"file-mention-popup-empty","data-testid":"file-mention-empty",children:"No files found"}),!o&&s.length>0&&t.jsx("ul",{className:"file-mention-popup-list",role:"listbox",children:s.map((l,c)=>{const u=l.path.includes("/")?l.path.slice(0,l.path.lastIndexOf("/")+1):"",d=l.name;return t.jsxs("li",{className:`file-mention-popup-item${c===i?" file-mention-popup-item--selected":""}`,onClick:()=>r(l),onMouseEnter:()=>{},role:"option","aria-selected":c===i,"data-testid":`file-mention-item-${c}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(Ih,{size:14})}),t.jsxs("div",{className:"file-mention-popup-info",children:[t.jsx("span",{className:"file-mention-popup-item-name",children:d}),u&&t.jsx("span",{className:"file-mention-popup-item-path",children:u})]})]},l.path)})})]}):null}const Z4=200;function eT(e={}){const{projectId:n,workspace:s="project"}=e,[i,r]=a.useState(!1),[o,l]=a.useState(""),[c,u]=a.useState(-1),[d,m]=a.useState([]),[h,g]=a.useState(!1),[p,f]=a.useState(0),x=a.useRef(null),v=a.useRef(null);a.useEffect(()=>()=>{x.current&&clearTimeout(x.current),v.current?.abort()},[]);const b=a.useCallback((w,_)=>{if(_<0||_>w.length){r(!1);return}const N=L=>/[a-zA-Z0-9/_.-]/.test(L);for(let L=_-1;L>=0;L--){if(w[L]==="#")if(L===0){const T=w.slice(L+1,_);u(L),l(T),f(0),r(!0);return}else{const T=w[L-1];if(/[\s,.;:!?'"()[\]{}]/.test(T)){const I=w.slice(L+1,_);u(L),l(I),f(0),r(!0);return}r(!1);return}if(!N(w[L])){r(!1);return}}r(!1)},[]),y=a.useCallback(()=>{r(!1),l(""),u(-1),m([]),f(0),g(!1)},[]),S=a.useCallback(async w=>{if(!w.trim()){m([]),g(!1);return}v.current?.abort(),v.current=new AbortController;try{g(!0);const _=await ky(w,s,n);m(_.files),f(0)}catch(_){_.name!=="AbortError"&&m([])}finally{g(!1)}},[s,n]);a.useEffect(()=>{if(i)return x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{S(o)},Z4),()=>{x.current&&clearTimeout(x.current)}},[o,i,S]);const k=a.useCallback((w,_)=>{if(!i||c<0)return _;const N=_.slice(0,c),L=_.slice(c+1),T=L.match(/[\s]|$/),I=T?T.index:L.length,z=L.slice(I);return`${N}#${w.path}${z}`},[i,c]),M=a.useCallback((w,_)=>{if(!i||d.length===0)return!1;switch(w.key){case"ArrowDown":return w.preventDefault(),f(N=>Math.min(N+1,d.length-1)),!0;case"ArrowUp":return w.preventDefault(),f(N=>Math.max(N-1,0)),!0;case"Enter":case"Tab":return d[p]?(w.preventDefault(),!0):!1;case"Escape":return w.preventDefault(),y(),!0;default:return!1}},[i,d,p,y]);return{mentionActive:i,files:d,loading:h,mentionQuery:o,selectedIndex:p,setSelectedIndex:f,detectMention:b,selectFile:k,dismissMention:y,handleKeyDown:M}}function tT(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let Yl=null;function nT(){return Yl===null&&(Yl=window.innerHeight),Yl}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 i=nT()-e.offsetTop-e.height;return i>=30&&i>80?i:0}function iT({enabled:e=!0}={}){const[n,s]=a.useState(0),[i,r]=a.useState(null);return a.useEffect(()=>{if(!e||!tT()){s(0),r(null);return}const o=window.visualViewport;if(!o){s(0),r(null);return}const l=()=>{const c=sT();s(c),r(c>0?o.height:null)};return l(),o.addEventListener("resize",l),o.addEventListener("scroll",l),()=>{o.removeEventListener("resize",l),o.removeEventListener("scroll",l),s(0),r(null)}},[e]),{keyboardOverlap:n,viewportHeight:i}}const aT={display:"inline-flex",alignItems:"center",maxWidth:"180px",padding:"var(--space-xs) var(--space-sm)",borderRadius:"var(--radius-pill)",border:"1px solid color-mix(in srgb, var(--todo) 35%, var(--border))",background:"color-mix(in srgb, var(--todo) 14%, transparent)",color:"var(--text)",fontSize:"11px",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},rT={display:"flex",alignItems:"center",gap:"var(--space-sm)",minWidth:0};function oT(e){return`${e.name?.trim()||e.id} (${e.role})`}function lT(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 cT(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 Xr(e,n){return e.length>n?`${e.slice(0,n)}…`:e}function dT(e){if(!e)return null;const n=Object.entries(e);return n.length===0?null:n.map(([s,i])=>{let r="";if(typeof i=="string")r=i;else try{r=JSON.stringify(i)}catch{r=String(i)}return`${s}=${Xr(r,50)}`}).join(", ")}function uT(e){if(e===void 0)return null;if(typeof e=="string")return Xr(e,200);try{return Xr(JSON.stringify(e),200)}catch{return Xr(String(e),200)}}function gh(e,n=!1){return!e||e.length===0?null:t.jsxs("div",{className:`chat-tool-calls${n?" chat-tool-calls--compact":""}`,"data-testid":"chat-tool-calls",children:[t.jsxs("div",{className:"chat-tool-calls-header",children:[t.jsx(zb,{size:12,"aria-hidden":"true"}),t.jsx("span",{children:"Tool calls"})]}),e.map((s,i)=>{const r=s.status==="running",o=s.status==="completed"&&s.isError,l=dT(s.args),c=uT(s.result),u=r?l:c?`result: ${c}`:l?`args: ${l}`:null,d=r?"running":o?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${r?" chat-tool-call--running":""}${o?" chat-tool-call--error":""}`,open:r,children:[t.jsxs("summary",{children:[t.jsx("span",{className:"chat-tool-call-status-dot","aria-hidden":"true"}),t.jsx("span",{className:"chat-tool-call-name",children:s.toolName}),u&&t.jsx("span",{className:"chat-tool-call-preview",title:u,children:u}),t.jsx("span",{className:"chat-tool-call-status-text",children:d})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[l&&t.jsxs("div",{className:"chat-tool-call-row",children:[t.jsx("span",{className:"chat-tool-call-label",children:"args"}),t.jsx("span",{className:"chat-tool-call-value",children:l})]}),c&&t.jsxs("div",{className:`chat-tool-call-row${o?" chat-tool-call-row--error":""}`,children:[t.jsx("span",{className:"chat-tool-call-label",children:"result"}),t.jsx("span",{className:"chat-tool-call-value",children:c})]})]})]},`${s.toolName}-${i}`)})]})}const mT={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 hT(e,n){const s=e.slice(0,n),i=/(^|[\s])@([\w-]*)$/.exec(s);if(!i)return null;const r=i[2]??"",o=s.length-r.length-1;return{filter:r,start:o,end:n}}const Jr={width:320,height:400},Qi={width:280,height:260},$c=768,Xi=8;function pT(e,n){const s=a.useCallback(()=>{if(typeof window>"u")return 0;const x=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return x&&parseFloat(x)||0},[]),i=a.useCallback(()=>typeof window<"u"&&window.innerWidth<=768?{x:4,y:4+s()}:{x:24,y:24+s()},[s]),[r,o]=a.useState(()=>{if(typeof window>"u")return i();const x=`fusion-quick-chat-position-${e||"default"}`;try{const v=localStorage.getItem(x);if(v){const b=JSON.parse(v);if(typeof b.x=="number"&&typeof b.y=="number"&&!isNaN(b.x)&&!isNaN(b.y))return b}}catch{}return i()}),[l,c]=a.useState(!1),u=a.useRef(null),d=n??a.useRef(!1),m=a.useCallback(x=>{if(typeof window>"u")return x;const v=48,b=window.innerWidth<=768?4:8,y=window.innerWidth<=768?44:0,S=window.innerWidth>768?s():0,k=window.innerWidth-v-b,M=window.innerHeight-v-b-y-S;return{x:Math.max(b,Math.min(k,x.x)),y:Math.max(b,Math.min(M,x.y))}},[s]),h=a.useCallback(x=>{if(typeof window>"u")return;const v=`fusion-quick-chat-position-${e||"default"}`;try{localStorage.setItem(v,JSON.stringify(x))}catch{}},[e]),g=a.useCallback(x=>{if(x.button!==0&&x.pointerType==="mouse")return;const b=x.target.closest(".quick-chat-fab");b&&(x.preventDefault(),typeof b.setPointerCapture=="function"&&b.setPointerCapture(x.pointerId),u.current={x:r.x,y:r.y,pointerX:x.clientX,pointerY:x.clientY},d.current=!1,c(!0),document.body.style.userSelect="none")},[r]),p=a.useCallback(x=>{if(!u.current||!l)return;const v=x.clientX-u.current.pointerX,b=x.clientY-u.current.pointerY;if((Math.abs(v)>=5||Math.abs(b)>=5)&&(d.current=!0),d.current){const y=u.current.x-v,S=u.current.y-b,k=m({x:y,y:S});o(k)}},[l,m]),f=a.useCallback(x=>{if(!u.current)return;const v=x.target.closest(".quick-chat-fab");if(v&&typeof v.releasePointerCapture=="function"&&v.releasePointerCapture(x.pointerId),c(!1),document.body.style.userSelect="",!d.current){u.current=null;return}h(r),u.current=null,d.current=!1},[r,h]);return{position:r,isDragging:l,handlePointerDown:g,handlePointerMove:p,handlePointerUp:f}}function fT(e,n,s){const i=`fusion:quick-chat-size-${e||"default"}`,r=a.useCallback(()=>typeof window<"u"&&window.innerWidth>$c,[]),o=a.useCallback((g,p,f)=>{if(typeof window>"u")return g;const x=Math.max(Qi.width,window.innerWidth-p-Xi),v=Math.max(Qi.height,window.innerHeight-f-Xi);return{width:Math.max(Qi.width,Math.min(x,g.width)),height:Math.max(Qi.height,Math.min(v,g.height))}},[]),l=a.useCallback(()=>{if(typeof window>"u"||window.innerWidth<=$c)return Jr;try{const g=localStorage.getItem(i);if(!g)return Jr;const p=JSON.parse(g);return typeof p.width!="number"||typeof p.height!="number"?Jr:{width:p.width,height:p.height}}catch{return Jr}},[i]),[c,u]=a.useState(l),[d,m]=a.useState({right:0,bottom:0});a.useEffect(()=>{if(!r())return;const g={right:n+d.right,bottom:s+d.bottom};u(p=>o(p,g.right,g.bottom))},[o,r,n,s,d]),a.useEffect(()=>{if(r())try{localStorage.setItem(i,JSON.stringify(c))}catch{}},[r,c,i]);const h=a.useCallback(g=>{if(!r())return;const p=g.currentTarget.dataset.resizeDirection;if(!p)return;g.preventDefault(),g.stopPropagation();const f=g.currentTarget;typeof f.setPointerCapture=="function"&&f.setPointerCapture(g.pointerId);const x={pointerX:g.clientX,pointerY:g.clientY,width:c.width,height:c.height,anchorRight:d.right,anchorBottom:d.bottom};document.body.style.userSelect="none";const v=y=>{const S=y.clientX-x.pointerX,k=y.clientY-x.pointerY;let M=x.width,w=x.height,_=x.anchorRight,N=x.anchorBottom;if(p.includes("w")&&(M=x.width-S),p.includes("e")){const P=S;M=x.width+P,_=x.anchorRight-P}if(p.includes("n")&&(w=x.height-k),p.includes("s")){const P=k;w=x.height+P,N=x.anchorBottom-P}const L=n+_,T=s+N,I=o({width:M,height:w},L,T),z=Math.max(Xi-n,Math.min(window.innerWidth-n-Qi.width-Xi,_)),K=Math.max(Xi-s,Math.min(window.innerHeight-s-Qi.height-Xi,N));u(I),m({right:z,bottom:K})},b=y=>{typeof f.releasePointerCapture=="function"&&f.releasePointerCapture(y.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",b);try{localStorage.setItem(i,JSON.stringify({width:c.width,height:c.height}))}catch{}};document.addEventListener("pointermove",v),document.addEventListener("pointerup",b)},[d.bottom,d.right,o,s,n,r,c.height,c.width,i]);return{panelSize:c,anchorOffset:d,handleResizeStart:h}}function gT({projectId:e,addToast:n,showFAB:s=!0,open:i,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:c,onToggleModelFavorite:u}){const{agents:d}=Q4(e),[m,h]=a.useState(!1),g=i!==void 0,p=g?i:m,f=g?me=>{r?.(typeof me=="function"?me(p):me)}:h,{keyboardOverlap:x,viewportHeight:v}=iT({enabled:p}),b=x>0?{"--keyboard-overlap":`${x}px`,...v!==null?{"--vv-height":`${v}px`}:{}}:{},[y,S]=a.useState("agent"),[k,M]=a.useState(""),[w,_]=a.useState([]),[N,L]=a.useState(!1),[T,I]=a.useState(""),[z,K]=a.useState(""),[P,E]=a.useState(""),[R,B]=a.useState(!1),[G,X]=a.useState(0),[C,$]=a.useState(-1),[A,j]=a.useState(()=>new Set),[,J]=a.useState(!1),[W,oe]=a.useState({top:0,left:0}),he=eT({projectId:e}),se=a.useCallback(me=>{if(!me||!he.mentionActive)return;const We=me.getBoundingClientRect();oe({top:We.top-260,left:We.left+8})},[he.mentionActive]),fe=a.useRef(!1),U=a.useRef(!1),Ne=a.useRef(""),ee=a.useRef(0),ve=a.useRef(null),{position:ue,isDragging:ye,handlePointerDown:ie,handlePointerMove:Me,handlePointerUp:ze}=pT(e,fe),Be=ue.y+60,{panelSize:Je,anchorOffset:Ye,handleResizeStart:Ge}=fT(e,ue.x,Be),it=typeof window<"u"&&window.innerWidth>$c,{activeSession:_e,messages:Fe,isStreaming:ae,streamingText:be,streamingThinking:ne,streamingToolCalls:Ie,sessionsLoading:Pe,messagesLoading:ce,sendMessage:le,stopStreaming:$e,pendingMessage:at,clearPendingMessage:tt,switchSession:V,startModelChat:de,startFreshSession:Z}=Y4(e,n),we=a.useRef(null),pe=a.useRef(null),Te=a.useRef(null),Qe=a.useRef(null),Ee=a.useMemo(()=>lT(T),[T]),Re=a.useMemo(()=>w.find(me=>`${me.provider}/${me.id}`===T)??null,[w,T]),Le=a.useMemo(()=>cT(Re,Ee),[Re,Ee]),ct=a.useMemo(()=>y==="model"?Ee?`${hd}::${Ee.modelProvider}/${Ee.modelId}`:"":k?`${k}::`:"",[y,Ee,k]),Se=y==="agent"?!!k:!!Ee;a.useEffect(()=>{if(d.length===0){M(""),S("model");return}d.some(We=>We.id===k)||M(d[0]?.id??"")},[d,k]),a.useEffect(()=>{!p||U.current||(U.current=!0,L(!0),os().then(me=>{const We=me.models??[];if(_(We),d.length===0&&We.length>0&&!T){const dt=We[0];dt&&I(`${dt.provider}/${dt.id}`)}}).catch(me=>{console.error("[QuickChatFAB] Failed to load models:",me),_([])}).finally(()=>{L(!1)}))},[p,d.length,T]),a.useEffect(()=>{if(!p){Ne.current="";return}if(!ct){Ne.current="";return}if(ct!==Ne.current){if(Ne.current=ct,y==="model"&&Ee){de(Ee.modelProvider,Ee.modelId);return}y==="agent"&&k&&V(k)}},[p,y,Ee,k,ct,de,V]),a.useEffect(()=>{p||(B(!1),E(""),$(-1))},[p]);const mt=a.useCallback(me=>{M(me)},[]),gt=a.useCallback(me=>{I(me)},[]),wt=a.useCallback(()=>{!Se||Pe||Z()},[Se,Pe,Z]),yt=a.useMemo(()=>d.find(me=>me.id===k)??null,[d,k]),kt=a.useMemo(()=>{const me=P.trim().toLowerCase();return me?d.filter(We=>We.name.toLowerCase().includes(me)):d},[d,P]),Ct=a.useMemo(()=>{const me=new Map;for(const We of d)me.set(We.name.toLowerCase(),We);return me},[d]);a.useEffect(()=>{X(0)},[P,R]),a.useEffect(()=>()=>{ve.current!==null&&(window.clearTimeout(ve.current),ve.current=null)},[]),a.useEffect(()=>{if(!p)return;const me=dt=>{const _t=dt.target;we.current?.contains(_t)||pe.current?.contains(_t)||_t.closest(".model-combobox-dropdown--portal")||f(!1)},We=dt=>{dt.key==="Escape"&&f(!1)};return document.addEventListener("mousedown",me),document.addEventListener("keydown",We),()=>{document.removeEventListener("mousedown",me),document.removeEventListener("keydown",We)}},[p,f]),a.useEffect(()=>{if(!p)return;const me=Te.current;me&&(me.scrollTop=me.scrollHeight)},[Fe,be,ne,p]);const Rt=a.useMemo(()=>y==="agent"?yt?`Message ${yt.name||yt.id}`:"Select an agent to start chatting":Le?`Message ${Le}`:"Select a model to start chatting",[y,yt,Le]),Ft=!Se||!_e||Pe,Ut=at.length>50?`${at.slice(0,50)}…`:at,St=a.useCallback(()=>{const me=z.trim();!me||Ft||(K(""),B(!1),E(""),$(-1),le(me))},[le,Ft,z]),Et=a.useCallback((me,We)=>{const dt=hT(me,We);if(dt){B(!0),E(dt.filter),$(dt.start);return}B(!1),E(""),$(-1)},[]),It=a.useCallback(me=>{const We=Qe.current;if(!We||C<0)return;const dt=We.selectionStart??ee.current,_t=We.selectionEnd??dt,$t=Math.max(dt,_t),vn=Math.min(C,$t),Yt=`${`@${me.name.replace(/\s+/g,"_")}`} `,En=z.slice(0,vn)+Yt+z.slice($t),on=vn+Yt.length;K(En),B(!1),E(""),X(0),$(-1),window.requestAnimationFrame(()=>{Qe.current&&(Qe.current.focus(),Qe.current.setSelectionRange(on,on))})},[C,z]),Mt=a.useCallback(me=>{const We=me.target.value,dt=me.target.selectionStart??We.length;ee.current=dt,K(We),Et(We,dt),he.detectMention(We,dt),J(he.mentionActive),he.mentionActive&&se(me.target)},[Et,he,se]),Kt=a.useCallback(()=>{ve.current!==null&&window.clearTimeout(ve.current),ve.current=window.setTimeout(()=>{B(!1),E(""),$(-1),J(!1),he.dismissMention(),ve.current=null},120)},[he]),Ot=a.useCallback(()=>{ve.current!==null&&(window.clearTimeout(ve.current),ve.current=null)},[]),xe=a.useCallback(me=>{const We=me.currentTarget,dt=We.selectionStart??We.value.length;ee.current=dt,Et(We.value,dt),he.detectMention(We.value,dt),J(he.mentionActive),he.mentionActive&&se(We)},[Et,he,se]),st=a.useCallback(me=>{me.key!=="Escape"&&xe(me)},[xe]),Ve=a.useCallback(me=>{const We=/@([\w-]+)/g,dt=[];let _t=0,$t=We.exec(me);for(;$t;){const[vn,kn=""]=$t,Yt=$t.index;Yt>_t&&dt.push(me.slice(_t,Yt));const En=kn.replace(/_/g," ").toLowerCase(),on=Ct.get(En);on?dt.push(t.jsxs("span",{className:"chat-mention-chip",children:["@",on.name.replace(/\s+/g,"_")]},`${on.id}-${Yt}`)):dt.push(vn),_t=Yt+vn.length,$t=We.exec(me)}return _t<me.length&&dt.push(me.slice(_t)),dt.length===0?me:dt},[Ct]),Y=a.useCallback(me=>{j(We=>{const dt=new Set(We);return dt.has(me)?dt.delete(me):dt.add(me),dt})},[]),F=a.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(si,{remarkPlugins:[ii],components:mT,children:me})}),[]),H=a.useCallback(me=>{if(ee.current=me.currentTarget.selectionStart??ee.current,he.mentionActive&&he.files.length>0){if(he.handleKeyDown(me,z),me.key==="Enter"||me.key==="Tab"){const We=he.files[he.selectedIndex];if(We){const dt=he.selectFile(We,z);K(dt),he.dismissMention(),J(!1)}}return}if(R&&me.key==="ArrowDown"){me.preventDefault(),kt.length>0&&X(We=>(We+1)%kt.length);return}if(R&&me.key==="ArrowUp"){me.preventDefault(),kt.length>0&&X(We=>We===0?kt.length-1:We-1);return}if(R&&me.key==="Enter"){me.preventDefault();const We=kt[G]??kt[0];We&&It(We);return}if(R&&me.key==="Escape"){me.preventDefault(),me.stopPropagation(),B(!1),E(""),$(-1);return}me.key!=="Enter"||me.shiftKey||(me.preventDefault(),St())},[R,kt,G,It,St,he,z]),ge=a.useCallback(()=>{if(fe.current){fe.current=!1;return}f(me=>!me)},[f]);return t.jsxs(t.Fragment,{children:[s&&t.jsx("button",{ref:pe,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":ye?"true":"false",style:{right:ue.x,bottom:ue.y},onPointerDown:ie,onPointerMove:Me,onPointerUp:ze,onClick:ge,children:t.jsx(ui,{size:24})}),p&&t.jsxs("div",{className:"quick-chat-panel",ref:we,"data-testid":"quick-chat-panel",style:{right:ue.x+Ye.right,bottom:Be+Ye.bottom,...it?{width:Je.width,height:Je.height}:{},...b},children:[it&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"n","data-testid":"quick-chat-resize-n",onPointerDown:Ge,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:Ge,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:Ge,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:Ge,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:Ge,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:Ge,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:Ge,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:Ge,role:"separator","aria-label":"Resize panel from bottom-right corner"})]}),t.jsxs("div",{className:"quick-chat-panel-header",children:[t.jsxs("div",{style:rT,children:[t.jsx("h3",{children:"Quick Chat"}),Le&&t.jsx("span",{style:aT,"data-testid":"quick-chat-model-tag",title:Le,children:Le})]}),t.jsxs("div",{className:"quick-chat-panel-header-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm","data-testid":"quick-chat-new-thread",onClick:wt,disabled:!Se||Pe,children:"New chat"}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":"Close quick chat","data-testid":"quick-chat-close",onClick:()=>f(!1),children:t.jsx(zt,{size:16})})]})]}),d.length>0&&t.jsxs("div",{className:"quick-chat-mode-toggle","data-testid":"quick-chat-mode-toggle",children:[t.jsx("button",{type:"button",className:`quick-chat-mode-btn${y==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-mode-agent",onClick:()=>{S("agent"),I("")},children:"Agent"}),t.jsx("button",{type:"button",className:`quick-chat-mode-btn${y==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-mode-model",onClick:()=>{S("model"),M("")},children:"Model"})]}),y==="agent"&&d.length>0&&t.jsxs("div",{className:"quick-chat-panel-agent-select",children:[t.jsx("label",{htmlFor:"quick-chat-agent-select",className:"visually-hidden",children:"Select agent"}),t.jsx("select",{id:"quick-chat-agent-select",value:k,onChange:me=>mt(me.target.value),"data-testid":"quick-chat-agent-select",children:d.map(me=>t.jsx("option",{value:me.id,children:oT(me)},me.id))})]}),y==="model"&&t.jsxs("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-model-select",children:[t.jsx("label",{htmlFor:"quick-chat-model-override",className:"visually-hidden",children:"Select model override"}),t.jsx(Ln,{id:"quick-chat-model-override",models:w,value:T,onChange:gt,label:"Select model override",placeholder:N?"Loading models…":"Select a model",disabled:N||w.length===0,favoriteProviders:o,favoriteModels:l,onToggleFavorite:c,onToggleModelFavorite:u})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:Te,"data-testid":"quick-chat-messages",children:Pe||ce?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):Fe.length===0&&!be&&!ne&&!ae?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[Fe.map(me=>{const We=me.role==="user",dt=!We&&A.has(me.id);return t.jsxs("div",{className:`quick-chat-panel-message ${We?"quick-chat-panel-message--sent":"quick-chat-panel-message--received"}`,"data-testid":`quick-chat-message-${me.id}`,children:[We?t.jsx("p",{children:Ve(me.content)}):t.jsxs(t.Fragment,{children:[F(me.content,dt),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${dt?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":dt?"Show rendered markdown":"Show plain text",onClick:()=>Y(me.id),children:dt?t.jsx(nc,{size:14}):t.jsx(sa,{size:14})})]}),gh(me.toolCalls,!0)]},me.id)}),ae&&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:[be?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:F(be,A.has("__streaming__"))}),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${A.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":A.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>Y("__streaming__"),children:A.has("__streaming__")?t.jsx(nc,{size:14}):t.jsx(sa,{size:14})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:ne?"Thinking…":"Connecting…"}),gh(Ie,!0),ne&&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:ne})]})]})]})}),t.jsxs("div",{className:"quick-chat-panel-input",children:[t.jsxs("div",{className:"quick-chat-input-wrapper",children:[t.jsx("input",{ref:Qe,type:"text",value:z,onChange:Mt,onKeyDown:H,onKeyUp:st,onClick:xe,onBlur:Kt,onFocus:Ot,placeholder:Rt,disabled:Ft,"data-testid":"quick-chat-input"}),t.jsx(G4,{agents:d,filter:P,highlightedIndex:G,visible:R,onSelect:It,position:"above"}),t.jsx(X4,{visible:he.mentionActive&&!R,position:W,files:he.files,selectedIndex:he.selectedIndex,onSelect:me=>{const We=he.selectFile(me,z);K(We),he.dismissMention(),J(!1),Qe.current?.focus()},loading:he.loading}),at&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${Ut}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:tt,children:"×"})]})]}),ae?t.jsx("button",{type:"button",className:"chat-input-stop",onClick:$e,"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:t.jsx(ms,{size:14})}):t.jsx("button",{type:"button",onClick:()=>void St(),disabled:Ft||z.trim().length===0,"data-testid":"quick-chat-send",children:t.jsx(Ei,{size:16})})]})]})]})}function Ba(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function xh(e){return e.status==="generating"||e.status==="awaiting_input"}function Ha(e){return e==="complete"||e==="error"}function xT(e){const[n,s]=a.useState([]),i=a.useRef(new Map),r=a.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:c,requestSync:u}=ba(),d=a.useCallback(()=>{Uc(e).then(p=>{const f=p.filter(v=>{const b=Ba(v.updatedAt),y=r.current.get(v.id);return y===void 0?!0:b<=y?!1:(r.current.delete(v.id),!0)}),x=new Map;for(const v of f)x.set(v.id,Ba(v.updatedAt));i.current=x,s(f)}).catch(p=>{console.warn("[useBackgroundSessions] Failed to fetch AI sessions:",p)})},[e]);a.useEffect(()=>{u(),d()},[d,u]),a.useEffect(()=>{s(p=>{if(o.size===0)return p;let f=!1;const x=new Map(p.map(v=>[v.id,v]));for(const v of o.values()){if(e&&v.projectId&&v.projectId!==e)continue;const b=v.lastEventTimestamp,y=i.current.get(v.sessionId)??0;if(b<y)continue;const S=r.current.get(v.sessionId);if(S!==void 0&&b<=S)continue;if(S!==void 0&&b>S&&!Ha(v.status)&&r.current.delete(v.sessionId),Ha(v.status)){x.delete(v.sessionId)&&(f=!0),i.current.set(v.sessionId,b);continue}const k=x.get(v.sessionId),M=v.type??k?.type,w=v.title??k?.title;if(!k&&(!M||!w))continue;const _={id:v.sessionId,type:M??"planning",status:v.status,title:w??"AI Session",projectId:v.projectId??k?.projectId??e??null,lockedByTab:v.owningTabId??k?.lockedByTab??null,updatedAt:v.updatedAt??k?.updatedAt??new Date(b).toISOString()},N=x.get(v.sessionId);(!N||N.status!==_.status||N.title!==_.title||N.type!==_.type||N.projectId!==_.projectId||N.lockedByTab!==_.lockedByTab||N.updatedAt!==_.updatedAt)&&(x.set(v.sessionId,_),i.current.set(v.sessionId,b),f=!0)}return f?[...x.values()].sort((v,b)=>Ba(b.updatedAt)-Ba(v.updatedAt)):p})},[e,o]),a.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",f=v=>{try{const b=JSON.parse(v.data),y=Ba(b.updatedAt)||Date.now();s(S=>{const k=i.current.get(b.id)??0;if(y<k)return S;const M=r.current.get(b.id);if(M!==void 0&&y<=M)return S;if(M!==void 0&&y>M&&!Ha(b.status)&&r.current.delete(b.id),i.current.set(b.id,y),Ha(b.status))return S.filter(_=>_.id!==b.id);const w=S.findIndex(_=>_.id===b.id);if(w>=0){const _=[...S];return _[w]=b,_}return xh(b)?[b,...S]:S}),l({sessionId:b.id,status:b.status,needsInput:b.status==="awaiting_input",type:b.type,title:b.title,projectId:b.projectId,owningTabId:b.lockedByTab,updatedAt:b.updatedAt,timestamp:y}),Ha(b.status)&&c({sessionId:b.id,status:b.status,timestamp:y})}catch{}},x=v=>{try{const b=JSON.parse(v.data),y=Date.now();r.current.set(b,y),i.current.set(b,Math.max(i.current.get(b)??0,y)),c({sessionId:b,status:"complete",timestamp:y}),s(S=>S.filter(k=>k.id!==b))}catch{}};return $s(`/api/events${p}`,{events:{"ai_session:updated":f,"ai_session:deleted":x},onReconnect:()=>{d()}})},[c,l,e,d]);const m=a.useCallback(async p=>{const x=n.find(S=>S.id===p)?.type,v=Li();let b=!1;if(x==="planning")try{await Gh(p,e,v)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of planning session ${p} despite lock by another tab`)}else if(x==="subtask")try{await Qh(p,e,v)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of subtask session ${p} despite lock by another tab`)}else if(x==="mission_interview")try{await np(p,e,v)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of mission interview session ${p} despite lock by another tab`)}b&&console.warn(`[useBackgroundSessions] Cancellation failed for session ${p}, attempting delete anyway`);const y=Date.now();r.current.set(p,y),i.current.set(p,Math.max(i.current.get(p)??0,y)),c({sessionId:p,status:"complete",timestamp:y});try{await sp(p)}catch{}s(S=>S.filter(k=>k.id!==p))},[c,e,n]),h=a.useMemo(()=>n.filter(p=>xh(p)),[n]),g=a.useMemo(()=>h.filter(p=>p.type==="planning"),[h]);return{sessions:h,generating:h.filter(p=>p.status==="generating").length,needsInput:h.filter(p=>p.status==="awaiting_input").length,planningSessions:g,dismissSession:m,refresh:d}}function Hn(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 bh(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function bT(e){const n=e?.projectId,s=e?.searchQuery,i=e?.sseEnabled??!0,[r,o]=a.useState([]),[l,c]=a.useState(!1),u=a.useRef(l);u.current=l;const d=a.useRef(r),m=a.useRef(0),h=a.useRef(0),g=a.useRef(s),p=a.useRef(null),f=a.useRef(void 0),x=a.useRef(0),v=a.useRef(n);d.current=r,g.current=s,v.current!==n&&(v.current=n,x.current++);const b=1e3,y=a.useCallback(async E=>{const R=++m.current,B=n,G=E?.searchQueryOverride??s,X=E?.includeArchivedOverride??u.current;try{const C=await cv(void 0,void 0,B,G,X);if(m.current!==R||n!==B)return;o(C.map(Hn)),f.current=Date.now()}catch{if(m.current!==R||n!==B)return;if(E?.clearOnError){o([]);return}o(C=>C)}},[n,s]);p.current=y;const S=a.useCallback(async()=>{u.current||(c(!0),u.current=!0,await p.current({includeArchivedOverride:!0}))},[]);a.useEffect(()=>{if(s===void 0)return;const E=setTimeout(()=>{y({searchQueryOverride:s})},300);return()=>clearTimeout(E)},[s]),a.useEffect(()=>{y({clearOnError:!0});const E=()=>{if(document.visibilityState!=="visible")return;const R=Date.now();R-h.current<b||(h.current=R,y())};return document.addEventListener("visibilitychange",E),()=>{document.removeEventListener("visibilitychange",E)}},[y]),a.useEffect(()=>{if(i===!1)return;const E=x.current,R=n?`?projectId=${encodeURIComponent(n)}`:"",B=()=>x.current!==E;let G=!0;const X=W=>{if(B())return;const oe=Hn(JSON.parse(W.data));if(g.current){p.current({searchQueryOverride:g.current});return}o(he=>he.some(se=>se.id===oe.id)?he:[...he,oe])},C=W=>{if(B())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:oe,to:he}=JSON.parse(W.data),se=Hn(oe);o(fe=>fe.map(U=>U.id===se.id?{...se,column:he}:U)),f.current=Date.now()},$=W=>{if(B())return;if(g.current){p.current({searchQueryOverride:g.current});return}const oe=Hn(JSON.parse(W.data));o(he=>he.map(se=>{if(se.id!==oe.id||bh(oe.updatedAt,se.updatedAt)<0)return se;if(se.column===oe.column)return oe;const U=bh(se.columnMovedAt,oe.columnMovedAt);return se.columnMovedAt&&!oe.columnMovedAt?{...oe,column:se.column,columnMovedAt:se.columnMovedAt}:U>0?{...oe,column:se.column,columnMovedAt:se.columnMovedAt}:oe})),f.current=Date.now()},A=W=>{if(B())return;if(g.current){p.current({searchQueryOverride:g.current});return}const oe=Hn(JSON.parse(W.data));o(he=>he.filter(se=>se.id!==oe.id))},j=W=>{if(B())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:oe}=JSON.parse(W.data),he=Hn(oe);o(se=>se.map(fe=>fe.id===he.id?{...he,column:"done"}:fe))},J=$s(`/api/events${R}`,{events:{"task:created":X,"task:moved":C,"task:updated":$,"task:deleted":A,"task:merged":j},onReconnect:()=>{G&&(B()||p.current())}});return()=>{G=!1,J()}},[n,i]);const k=a.useCallback(async E=>{const R=Hn(await qh(E,n));return o(B=>B.some(G=>G.id===R.id)?B:[...B,R]),R},[n]),M=a.useCallback(async(E,R)=>Hn(await uv(E,R,n)),[n]),w=a.useCallback(async E=>Hn(await Vh(E,n)),[n]),_=a.useCallback(async E=>Hn(await mv(E,n)),[n]),N=a.useCallback(async E=>hv(E,n),[n]),L=a.useCallback(async E=>Hn(await pv(E,n)),[n]),T=a.useCallback(async E=>{const R=Hn(await fv(E,n));return o(B=>B.some(G=>G.id===R.id)?B:[...B,R]),R},[n]),I=a.useCallback(async(E,R)=>{const B=d.current.find(X=>X.id===E),G=B?{...B,...R,updatedAt:new Date().toISOString()}:void 0;G&&o(X=>X.map(C=>C.id===E?G:C));try{const X=Hn(await Zs(E,R,n));return o(C=>C.map($=>$.id===E?X:$)),X}catch(X){throw B&&o(C=>C.map($=>$.id===E?B:$)),X}},[n]),z=a.useCallback(async E=>{const R=Hn(await xv(E,n));return o(B=>B.map(G=>G.id===E?R:G)),R},[n]),K=a.useCallback(async E=>{const R=Hn(await bv(E,n));return o(B=>B.map(G=>G.id===E?R:G)),R},[n]),P=a.useCallback(async()=>{const R=(await vv(n)).map(Hn);return o(B=>B.map(G=>R.find(C=>C.id===G.id)||G)),R},[n]);return{tasks:r,createTask:k,moveTask:M,pauseTask:w,deleteTask:_,mergeTask:N,retryTask:L,duplicateTask:T,updateTask:I,archiveTask:z,unarchiveTask:K,archiveAllDone:P,loadArchivedTasks:S,includeArchived:l,lastFetchTimeMs:f.current}}const vT=5e3,yT=1e3;function kT(){const[e,n]=a.useState([]),[s,i]=a.useState(!0),[r,o]=a.useState(null),l=a.useRef(null),c=a.useRef(0),u=a.useCallback(async()=>{try{o(null);const g=await Bd();n(g)}catch(g){o(g instanceof Error?g.message:"Failed to fetch projects")}},[]);a.useEffect(()=>{let g=!1;async function p(){i(!0);const x=performance.now();try{const v=await Bd(),y=`initial fetchProjectsAcrossNodes took ${Math.round(performance.now()-x)}ms (${v.length} projects)`;console.log(`[useProjects] ${y}`),Ya("[useProjects]",y),g||(n(v),o(null))}catch(v){const y=`initial fetch failed after ${Math.round(performance.now()-x)}ms: ${v instanceof Error?v.message:String(v)}`;console.warn(`[useProjects] ${y}`),Ya("[useProjects]",y),g||o(v instanceof Error?v.message:"Failed to fetch projects")}finally{g||i(!1)}}p();const f=()=>{if(document.visibilityState!=="visible")return;const x=Date.now();x-c.current<yT||(c.current=x,u())};return document.addEventListener("visibilitychange",f),()=>{g=!0,document.removeEventListener("visibilitychange",f)}},[u]),a.useEffect(()=>{if(!s)return l.current=setInterval(()=>{u()},vT),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async g=>{const p=await xk(g);return n(f=>[...f,p]),p},[]),m=a.useCallback(async(g,p)=>{const f=await wk(g,p);return n(x=>x.map(v=>v.id===g?f:v)),f},[]),h=a.useCallback(async g=>{await Zh(g),n(p=>p.filter(f=>f.id!==g))},[]);return{projects:e,loading:s,error:r,refresh:u,register:d,update:m,unregister:h}}const jT=1e4,wT=1e3;function NT(){const[e,n]=a.useState([]),[s,i]=a.useState(!0),[r,o]=a.useState(null),l=a.useRef(null),c=a.useRef(0),u=a.useCallback(async()=>{try{o(null);const p=await Hd();n(p)}catch(p){o(p instanceof Error?p.message:"Failed to fetch nodes")}},[]);a.useEffect(()=>{let p=!1;async function f(){i(!0);try{const v=await Hd();p||(n(v),o(null))}catch(v){p||o(v instanceof Error?v.message:"Failed to fetch nodes")}finally{p||i(!1)}}f();const x=()=>{if(document.visibilityState!=="visible")return;const v=Date.now();v-c.current<wT||(c.current=v,u())};return document.addEventListener("visibilitychange",x),()=>{p=!0,document.removeEventListener("visibilitychange",x)}},[u]),a.useEffect(()=>{if(!s)return l.current=setInterval(()=>{u()},jT),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async p=>{const f=await hk(p);return n(x=>[...x,f]),f},[]),m=a.useCallback(async(p,f)=>{const x=await pk(p,f);return n(v=>v.map(b=>b.id===p?x:b)),x},[]),h=a.useCallback(async p=>{await fk(p),n(f=>f.filter(x=>x.id!==p))},[]),g=a.useCallback(async p=>{const f=await gk(p);n(x=>x.map(v=>v.id===p?{...v,status:f.status,updatedAt:f.checkedAt}:v))},[]);return{nodes:e,loading:s,error:r,refresh:u,register:d,update:m,unregister:h,healthCheck:g}}const ST="kb-dashboard-current-project";function CT(e){return e??"local"}function ET(e,n={}){const{nodeId:s=null}=n,[i,r]=a.useState(null),[o,l]=a.useState(!0),c=a.useRef(!1),u=a.useRef(!1),d=a.useRef(null),m=CT(s);a.useEffect(()=>{let p=!1;async function f(){try{const x=await Di();if(p)return;d.current=x.dashboardCurrentProjectIdByNode??{};const v=d.current[m];if(v){const b=e.find(y=>y.id===v);b&&(r(b),c.current=!0)}if(!v)try{const b=localStorage.getItem(ST);if(b){const y=JSON.parse(b);y?.id&&e.some(k=>k.id===y.id)&&(r(y),c.current=!0,d.current={...d.current,[m]:y.id},await an({dashboardCurrentProjectIdByNode:d.current}).catch(()=>{}))}}catch{}}catch{}finally{p||l(!1)}}return f(),()=>{p=!0}},[m,e]),a.useEffect(()=>{if(!o){if(i){if(!e.some(x=>x.id===i.id)&&e.length>0){const x=e.find(v=>v.status==="active");r(x||e[0]||null);return}const f={...d.current,[m]:i.id};d.current=f,an({dashboardCurrentProjectIdByNode:f}).catch(()=>{})}else if(e.length>0&&!u.current){const p=e.find(f=>f.status==="active");p&&r(p)}}},[i,e,o,m]);const h=a.useCallback(p=>{if(u.current=!1,r(p),p){const f={...d.current,[m]:p.id};d.current=f,an({dashboardCurrentProjectIdByNode:f}).catch(()=>{})}},[m]),g=a.useCallback(()=>{u.current=!0,r(null);const p={...d.current};delete p[m],d.current=p,an({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[m]);return{currentProject:i,setCurrentProject:h,clearCurrentProject:g,loading:o}}const Yf=a.createContext(null);function MT({children:e}){const[n,s]=a.useState([]),i=a.useRef(0),r=a.useRef(new Map),o=a.useCallback(c=>{const u=r.current.get(c);u!==void 0&&(clearTimeout(u),r.current.delete(c)),s(d=>d.filter(m=>m.id!==c))},[]),l=a.useCallback((c,u="info")=>{const d=i.current++;s(h=>[...h,{id:d,message:c,type:u}]);const m=setTimeout(()=>o(d),4e3);r.current.set(d,m)},[o]);return a.useEffect(()=>()=>{r.current.forEach(c=>clearTimeout(c)),r.current.clear()},[]),Zr.createElement(Yf.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function _T(){const e=a.useContext(Yf);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const Qf="kb-dashboard-theme-mode",Xf="kb-dashboard-color-theme",Zf=[...Vj],Dc="theme-data",Ql="theme-data.css";function AT(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.endsWith("/")?e.slice(0,-1)+`/${Ql}`:e.replace(/\/[^/]+$/,`/${Ql}`):`/${Ql}`}const Cs=typeof window<"u",RT=Cs?a.useLayoutEffect:a.useEffect;function eg(e){return e==="dark"||e==="light"||e==="system"}function vh(){if(!Cs)return"dark";try{const e=localStorage.getItem(Qf);if(eg(e))return e}catch{}return"dark"}function yh(){if(!Cs)return"default";try{const e=localStorage.getItem(Xf);if(e&&Zf.includes(e))return e}catch{}return"default"}function kh(e){if(Cs)try{localStorage.setItem(Qf,e)}catch{}}function jh(e){if(Cs)try{localStorage.setItem(Xf,e)}catch{}}function TT(e,n){return e==="system"?n?"dark":"light":e}function PT(e,n,s){if(!Cs)return;const i=TT(e,s);document.documentElement.setAttribute("data-theme",i),document.documentElement.setAttribute("data-color-theme",n)}function wh(){if(!Cs)return;const e=AT(),n=document.getElementById(Dc);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=Dc,document.head.appendChild(s)}function Nh(){if(!Cs)return;const e=document.getElementById(Dc);e&&e.remove()}function IT(){const[e,n]=a.useState(()=>vh()),[s,i]=a.useState(()=>yh()),[r,o]=a.useState(!0),[l,c]=a.useState(()=>Cs?window.matchMedia("(prefers-color-scheme: dark)").matches:!0),u=a.useRef(e),d=a.useRef(s),m=a.useRef(!1),h=a.useRef(!1);a.useEffect(()=>{u.current=e},[e]),a.useEffect(()=>{d.current=s},[s]),a.useEffect(()=>{if(!Cs||!r)return;let f=!1;return Di().then(x=>{f||(eg(x.themeMode)&&!m.current&&(u.current!==x.themeMode&&(u.current=x.themeMode,n(x.themeMode)),vh()!==x.themeMode&&kh(x.themeMode)),x.colorTheme&&Zf.includes(x.colorTheme)&&!h.current&&(d.current!==x.colorTheme&&(d.current=x.colorTheme,i(x.colorTheme)),yh()!==x.colorTheme&&jh(x.colorTheme)))}).catch(x=>{console.warn("[useTheme] Failed to hydrate theme from global settings",x)}).finally(()=>{f||o(!1)}),()=>{f=!0}},[r]),a.useEffect(()=>{if(!Cs)return;const f=window.matchMedia("(prefers-color-scheme: dark)"),x=v=>{c(v.matches)};return f.addEventListener("change",x),()=>f.removeEventListener("change",x)},[]),RT(()=>{PT(e,s,l)},[e,s,l]),a.useEffect(()=>{!Cs||r||(s!=="default"?wh():Nh())},[s,r]);const g=a.useCallback(f=>{m.current=!0,u.current=f,n(f),kh(f),an({themeMode:f}).catch(x=>{console.warn("[useTheme] Failed to persist themeMode to global settings",x)})},[]),p=a.useCallback(f=>{h.current=!0,d.current=f,i(f),jh(f),f!=="default"?wh():Nh(),an({colorTheme:f}).catch(x=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",x)})},[]);return{themeMode:e,colorTheme:s,setThemeMode:g,setColorTheme:p,isSystemDark:l}}function $T(e){const{planningSessions:n}=e,[s,i]=a.useState(!1),[r,o]=a.useState(!1),[l,c]=a.useState(null),[u,d]=a.useState(void 0),[m,h]=a.useState(!1),[g,p]=a.useState(null),[f,x]=a.useState(void 0),[v,b]=a.useState(null),[y,S]=a.useState("definition"),[k,M]=a.useState(!1),[w,_]=a.useState(void 0),[N,L]=a.useState(!1),[T,I]=a.useState(!1),[z,K]=a.useState(!1),[P,E]=a.useState(null),[R,B]=a.useState(!1),[G,X]=a.useState(!1),[C,$]=a.useState(void 0),[A,j]=a.useState(!1),[J,W]=a.useState("project"),[oe,he]=a.useState(!1),[se,fe]=a.useState(!1),[U,Ne]=a.useState(!1),[ee,ve]=a.useState(!1),[ue,ye]=a.useState(!1),[ie,Me]=a.useState(!1),[ze,Be]=a.useState(!1),Je=!!(v||k||s||r||m||G||A||oe||se||U||ue||ee||z||R||N||T||ie||ze),Ye=a.useCallback(()=>i(!0),[]),Ge=a.useCallback(()=>i(!1),[]),it=a.useCallback(()=>o(!0),[]),_e=a.useCallback(H=>{c(H),o(!0)},[]),Fe=a.useCallback(()=>{const H=n[0];H&&(d(H.id),o(!0))},[n]),ae=a.useCallback(H=>{d(H),o(!0)},[]),be=a.useCallback(()=>{o(!1),c(null),d(void 0)},[]),ne=a.useCallback(H=>{p(H),h(!0)},[]),Ie=a.useCallback(H=>{x(H),h(!0)},[]),Pe=a.useCallback(()=>{h(!1),p(null),x(void 0)},[]),ce=a.useCallback((H,ge="definition")=>{b(H),S(ge)},[]),le=a.useCallback(H=>{b(H),S("changes")},[]),$e=a.useCallback(H=>{b(ge=>ge&&{...ge,...H})},[]),at=a.useCallback(()=>{b(null)},[]),tt=a.useCallback(H=>{_(H),M(!0)},[]),V=a.useCallback(()=>{M(!1),_(void 0)},[]),de=a.useCallback(()=>L(!0),[]),Z=a.useCallback(()=>L(!1),[]),we=a.useCallback(()=>I(!0),[]),pe=a.useCallback(()=>I(!1),[]),Te=a.useCallback(H=>{E(H??null),K(!0)},[]),Qe=a.useCallback(()=>{K(!1),E(null)},[]),Ee=a.useCallback(()=>B(!0),[]),Re=a.useCallback(()=>B(!1),[]),Le=a.useCallback(()=>{X(H=>!H)},[]),ct=a.useCallback(()=>{X(!1),$(void 0)},[]),Se=a.useCallback(()=>j(!0),[]),mt=a.useCallback(()=>j(!1),[]),gt=a.useCallback(H=>{W(H)},[]),wt=a.useCallback(()=>he(!0),[]),yt=a.useCallback(()=>he(!1),[]),kt=a.useCallback(()=>fe(!0),[]),Ct=a.useCallback(()=>fe(!1),[]),Rt=a.useCallback(()=>Ne(!0),[]),Ft=a.useCallback(()=>Ne(!1),[]),Ut=a.useCallback(()=>ve(!0),[]),St=a.useCallback(()=>ve(!1),[]),Et=a.useCallback(()=>ye(!0),[]),It=a.useCallback(()=>ye(!1),[]),Mt=a.useCallback(async(H,ge)=>{ye(!1),$(ge),X(!0)},[]),Kt=a.useCallback(()=>Me(!0),[]),Ot=a.useCallback(()=>Me(!1),[]),xe=a.useCallback(()=>Be(!0),[]),st=a.useCallback(()=>Be(!1),[]),Ve=a.useCallback((H,ge)=>{ge(`Created ${H.id} from planning mode`,"success"),o(!1),c(null)},[]),Y=a.useCallback((H,ge)=>{const me=H.map(We=>We.id).join(", ");ge(`Created ${me} from planning mode`,"success"),o(!1),c(null)},[]),F=a.useCallback((H,ge)=>{const me=H.map(We=>We.id).join(", ");ge(`Created ${me} from subtask breakdown`,"success"),h(!1),p(null)},[]);return{newTaskModalOpen:s,isPlanningOpen:r,planningInitialPlan:l,planningResumeSessionId:u,isSubtaskOpen:m,subtaskInitialDescription:g,subtaskResumeSessionId:f,detailTask:v,detailTaskInitialTab:y,settingsOpen:k,settingsInitialSection:w,schedulesOpen:N,githubImportOpen:T,usageOpen:z,usageAnchorRect:P,systemStatsOpen:R,terminalOpen:G,terminalInitialCommand:C,filesOpen:A,fileBrowserWorkspace:J,activityLogOpen:oe,gitManagerOpen:se,workflowStepsOpen:U,agentsOpen:ee,scriptsOpen:ue,setupWizardOpen:ie,modelOnboardingOpen:ze,anyModalOpen:Je,openNewTask:Ye,closeNewTask:Ge,openPlanning:it,openPlanningWithInitialPlan:_e,resumePlanning:Fe,openPlanningWithSession:ae,closePlanning:be,openSubtaskBreakdown:ne,openSubtaskWithSession:Ie,closeSubtask:Pe,openDetailTask:ce,openDetailWithChangesTab:le,updateDetailTask:$e,closeDetailTask:at,openSettings:tt,closeSettings:V,openSchedules:de,closeSchedules:Z,openGitHubImport:we,closeGitHubImport:pe,openUsage:Te,closeUsage:Qe,openSystemStats:Ee,closeSystemStats:Re,toggleTerminal:Le,closeTerminal:ct,openFiles:Se,closeFiles:mt,setFileWorkspace:gt,openActivityLog:wt,closeActivityLog:yt,openGitManager:kt,closeGitManager:Ct,openWorkflowSteps:Rt,closeWorkflowSteps:Ft,openAgents:Ut,closeAgents:St,openScripts:Et,closeScripts:It,runScript:Mt,openSetupWizard:Kt,closeSetupWizard:Ot,openModelOnboarding:xe,closeModelOnboarding:st,onPlanningTaskCreated:Ve,onPlanningTasksCreated:Y,onSubtaskTasksCreated:F}}function DT(e){const[n,s]=a.useState(2),[i,r]=a.useState("."),[o,l]=a.useState(!0),[c,u]=a.useState(!1),[d,m]=a.useState(!1),[h,g]=a.useState(void 0),[p,f]=a.useState(!1),[x,v]=a.useState(!1),[b,y]=a.useState({}),[S,k]=a.useState(!1),[M,w]=a.useState(!1),[_,N]=a.useState(!1),[L,T]=a.useState(!1),[I,z]=a.useState(!1),K=a.useCallback(async()=>{const[G,X]=await Promise.allSettled([jv(e),Eo(e)]);if(G.status==="fulfilled"&&(s(G.value.maxConcurrent),r(G.value.rootDir)),X.status==="fulfilled"){const C=X.value;l(!!C.autoMerge),u(!!C.globalPause),m(!!C.enginePaused),v(!!C.prAuthAvailable),g(C.taskStuckTimeoutMs),f(C.showQuickChatFAB===!0),y(C.experimentalFeatures??{});const $=C.experimentalFeatures??{};k($.insights===!0),w($.roadmap===!0),N($.memoryView===!0),T($.devServerView===!0||$.devServer===!0),z($.todoView===!0)}},[e]);a.useEffect(()=>{K()},[K]);const P=a.useCallback(async()=>{const G=!o;l(G);try{await _r({autoMerge:G},e)}catch{l(!G)}},[o,e]),E=a.useCallback(async()=>{const G=!c;u(G);try{await _r({globalPause:G,globalPauseReason:G?"manual":void 0},e)}catch{u(!G)}},[c,e]),R=a.useCallback(async()=>{const G=!d;m(G);try{await _r({enginePaused:G},e)}catch{m(!G)}},[d,e]),B=a.useCallback(async()=>{const G=!p;f(G);try{await _r({showQuickChatFAB:G},e)}catch{f(!G)}},[p,e]);return{maxConcurrent:n,rootDir:i,autoMerge:o,globalPaused:c,enginePaused:d,taskStuckTimeoutMs:h,showQuickChatFAB:p,prAuthAvailable:x,experimentalFeatures:b,insightsEnabled:S,roadmapEnabled:M,memoryEnabled:_,devServerEnabled:L,todosEnabled:I,toggleAutoMerge:P,toggleGlobalPause:E,toggleEnginePause:R,toggleShowQuickChatFAB:B,refresh:K}}function LT(e){const{projectId:n,projects:s,projectsLoading:i,currentProject:r,setCurrentProject:o,addToast:l,openTaskDetail:c,closeTaskDetail:u}=e,d=a.useRef(!1),m=a.useRef(null);return a.useEffect(()=>{const g=new URLSearchParams(window.location.search),p=g.get("project"),f=g.get("task");if(!f||i)return;if(p){const v=s.find(b=>b.id===p);if(!v){l(`Project '${p}' not found`,"error");return}r?.id!==v.id&&o(v)}if(d.current)return;d.current=!0,ao(f,p??n).then(v=>{c(v),m.current=f}).catch(()=>{l(`Task ${f} not found`,"error")})},[n,s,i,r,o,l,c]),{handleDetailClose:a.useCallback(()=>{if(m.current){const g=new URLSearchParams(window.location.search);g.delete("task");const p=g.toString();window.history.replaceState(null,"",p?`${window.location.pathname}?${p}`:window.location.pathname),m.current=null}u()},[u])}}function zT(){const[e,n]=a.useState([]),[s,i]=a.useState([]),[r,o]=a.useState([]),l=a.useRef(s),c=a.useRef(r);a.useEffect(()=>{os().then(m=>{n(m.models),l.current=m.favoriteProviders,c.current=m.favoriteModels,i(m.favoriteProviders),o(m.favoriteModels)}).catch(()=>{})},[]),a.useEffect(()=>{l.current=s},[s]),a.useEffect(()=>{c.current=r},[r]);const u=a.useCallback(async m=>{const h=l.current,p=h.includes(m)?h.filter(f=>f!==m):[m,...h];l.current=p,i(()=>p);try{await an({favoriteProviders:p,favoriteModels:c.current})}catch(f){throw l.current=h,i(()=>h),f}},[]),d=a.useCallback(async m=>{const h=c.current,p=h.includes(m)?h.filter(f=>f!==m):[m,...h];c.current=p,o(()=>p);try{await an({favoriteProviders:l.current,favoriteModels:p})}catch(f){throw c.current=h,o(()=>h),f}},[]);return{availableModels:e,favoriteProviders:s,favoriteModels:r,toggleFavoriteProvider:u,toggleFavoriteModel:d}}function FT({projectId:e,setupWizardOpen:n,openModelOnboarding:s,openSettings:i}){const r=a.useRef(!1);a.useEffect(()=>{if(n||r.current)return;r.current=!0;let o=!1,l=!1;ir().then(({providers:c})=>{const u=c.some(m=>m.authenticated);if(c.length>0&&!u||c.length>0&&u)return Di().then(m=>{const h=!!(m.defaultProvider&&m.defaultModelId);(m.modelOnboardingComplete===!1||m.modelOnboardingComplete===void 0)&&(!u||!h)&&!fa()?o=!0:!u&&!fa()&&(l=!0)})}).then(()=>{o?(Ns("onboarding:auto-triggered",{trigger:"first-run"}),s()):l&&(Ns("onboarding:auto-triggered",{trigger:"missing-provider"}),i("authentication"))}).catch(()=>{})},[e,n,s,i])}const Sh="kb-update-banner-dismissed";function OT(){const[e,n]=a.useState(!0),[s,i]=a.useState(!1),[r,o]=a.useState(null),[l,c]=a.useState(null),[u,d]=a.useState(!1);a.useEffect(()=>{const h=sessionStorage.getItem(Sh)==="true";d(h);let g=!1;return wv().then(p=>{g||p.disabled||(i(p.updateAvailable===!0),o(typeof p.latestVersion=="string"?p.latestVersion:null),c(typeof p.currentVersion=="string"?p.currentVersion:null))}).catch(()=>{}).finally(()=>{g||n(!1)}),()=>{g=!0}},[]);const m=a.useCallback(()=>{d(!0),sessionStorage.setItem(Sh,"true")},[]);return{updateAvailable:s,latestVersion:r,currentVersion:l,loading:e,dismissed:u,dismiss:m}}const UT=["board","list","agents","missions","chat","documents","roadmaps","skills","mailbox","insights","memory","devserver","dev-server","todos"];function Ch(e){return e!==null&&UT.includes(e)}function BT(e){return e==="devserver"?"dev-server":e}function HT(e){const{projectsLoading:n,projectsError:s,currentProjectLoading:i,currentProject:r,projectsLength:o,setupWizardOpen:l,openSetupWizard:c,themeMode:u,setThemeMode:d}=e,[m,h]=a.useState(()=>{if(typeof window<"u"){const b=window.localStorage.getItem("kb-dashboard-view-mode");if(b==="overview"||b==="project")return b}return"overview"}),[g,p]=a.useState(()=>{const b=zn("kb-dashboard-task-view");return Ch(b)?b:"board"}),f=a.useRef(!1);a.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",m)},[m]),a.useEffect(()=>{const b=zn("kb-dashboard-task-view",r?.id);if(Ch(b)){const y=!f.current&&b==="devserver";p(y?"devserver":BT(b))}else p("board");r?.id&&(f.current=!0)},[r?.id]),a.useEffect(()=>{as("kb-dashboard-task-view",g,r?.id)},[r?.id,g]),a.useEffect(()=>{n||i||r&&m==="overview"&&h("project")},[n,i,r,m]),a.useEffect(()=>{if(n||i||l||s||o>0||r)return;const b=window.setTimeout(()=>{c()},500);return()=>window.clearTimeout(b)},[n,s,o,i,r,l,c]);const x=a.useCallback(b=>{p(b)},[]),v=a.useCallback(()=>{const b=["dark","light","system"],y=b.indexOf(u),S=b[(y+1)%b.length];d(S)},[u,d]);return{viewMode:m,setViewMode:h,taskView:g,setTaskView:p,handleChangeTaskView:x,handleToggleTheme:v}}function qT(e){const{setCurrentProject:n,clearCurrentProject:s,setViewMode:i,currentProject:r,refreshProjects:o,toggleFavoriteProvider:l,toggleFavoriteModel:c,addToast:u,openSettings:d,openSetupWizard:m,closeSetupWizard:h,closeModelOnboarding:g}=e,p=a.useCallback(N=>{n(N),i("project")},[n,i]),f=a.useCallback(()=>{s(),i("overview")},[s,i]),x=a.useCallback(()=>{d()},[d]),v=a.useCallback(()=>{m()},[m]),b=a.useCallback(N=>{h(),n(N),i("project"),u(`Project ${N.name} registered successfully`,"success"),o()},[h,n,i,u,o]),y=a.useCallback(()=>{g()},[g]),S=a.useCallback(async N=>{try{await kk(N.id),u(`Project ${N.name} paused`,"success"),await o()}catch{u(`Failed to pause project ${N.name}`,"error")}},[u,o]),k=a.useCallback(async N=>{try{await jk(N.id),u(`Project ${N.name} resumed`,"success"),await o()}catch{u(`Failed to resume project ${N.name}`,"error")}},[u,o]),M=a.useCallback(async N=>{try{await Zh(N.id),u(`Project ${N.name} removed`,"success"),r?.id===N.id&&(s(),i("overview")),await o()}catch{u(`Failed to remove project ${N.name}`,"error")}},[r,s,i,u,o]),w=a.useCallback(async N=>{try{await l(N)}catch{u("Failed to update favorites","error")}},[l,u]),_=a.useCallback(async N=>{try{await c(N)}catch{u("Failed to update model favorites","error")}},[c,u]);return{handleSelectProject:p,handleViewAllProjects:f,handleOpenSettings:x,handleAddProject:v,handleSetupComplete:b,handleModelOnboardingComplete:y,handlePauseProject:S,handleResumeProject:k,handleRemoveProject:M,handleToggleFavorite:w,handleToggleModelFavorite:_}}function VT(e){const{createTask:n,onPlanningTaskCreated:s,onPlanningTasksCreated:i,onSubtaskTasksCreated:r,addToast:o}=e,l=a.useCallback(async g=>n({...g,column:"triage"}),[n]),c=a.useCallback(async g=>await n({...g,column:"triage"}),[n]),u=a.useCallback(g=>{s(g,o)},[s,o]),d=a.useCallback(g=>{i(g,o)},[i,o]),m=a.useCallback(g=>{r(g,o)},[r,o]),h=a.useCallback(g=>{o(`Imported ${g.id} from GitHub`,"success")},[o]);return{handleBoardQuickCreate:l,handleModalCreate:c,handlePlanningTaskCreated:u,handlePlanningTasksCreated:d,handleSubtaskTasksCreated:m,handleGitHubImport:h}}async function WT(e){return _o("/health",{nodeId:e})}async function KT(e){return _o("/projects",{nodeId:e})}async function GT(e,n,s){const i=new URLSearchParams({projectId:n});return s&&s.trim()&&i.set("q",s.trim()),_o(`/tasks?${i.toString()}`,{nodeId:e})}async function JT(e,n){return _o(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:e})}async function J$(e){return D(`/nodes/${encodeURIComponent(e)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function Y$(e){return D(`/nodes/${encodeURIComponent(e)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function Q$(e){return D(`/nodes/${encodeURIComponent(e)}/settings/sync-status`)}async function X$(e){return D(`/nodes/${encodeURIComponent(e)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}function YT(e,n){const{projectId:s,searchQuery:i}=n??{},[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState(null),[m,h]=a.useState(!1),[g,p]=a.useState(null),f=a.useRef(null),x=a.useCallback(async()=>{if(!e){o([]),c([]),d(null),h(!1),p(null);return}f.current?.abort();const b=new AbortController;f.current=b,h(!0),p(null);try{const y=[WT(e),KT(e)];s&&(y.push(GT(e,s,i)),y.push(JT(e,s)));const S=await Promise.allSettled(y);if(b.signal.aborted)return;const k=S[0],M=S[1];if(k.status==="rejected"){p(`Failed to fetch node health: ${k.reason}`),h(!1);return}if(d(k.value),M.status==="rejected"){p(`Failed to fetch projects: ${M.reason}`),h(!1);return}if(o(M.value),s&&S[2]){const w=S[2];if(w.status==="rejected"){p(`Failed to fetch tasks: ${w.reason}`),h(!1);return}w.status==="fulfilled"&&c(w.value)}h(!1)}catch(y){b.signal.aborted||(p(y instanceof Error?y.message:"Unknown error"),h(!1))}},[e,s,i]);a.useEffect(()=>(x(),()=>{f.current?.abort()}),[x]);const v=a.useCallback(()=>{x()},[x]);return{projects:r,tasks:l,health:u,loading:m,error:g,refresh:v}}function QT(e){const[n,s]=a.useState(!1),[i,r]=a.useState(null);return a.useEffect(()=>{if(!e){s(!1),r(null);return}const o=`/api/proxy/${encodeURIComponent(e)}/events`;return $s(o,{events:{"task:created":l=>{r({type:"task:created",data:l.data})},"task:moved":l=>{r({type:"task:moved",data:l.data})},"task:updated":l=>{r({type:"task:updated",data:l.data})},"task:deleted":l=>{r({type:"task:deleted",data:l.data})},"task:merged":l=>{r({type:"task:merged",data:l.data})}},onOpen:()=>s(!0),onError:()=>s(!1)})},[e]),{isConnected:n,lastEvent:i}}const XT="fusion-dashboard-current-node",tg=a.createContext(null);function ZT({children:e}){const[n,s]=a.useState(null),[i,r]=a.useState(!0),o=a.useRef(!1),l=a.useRef(void 0);a.useEffect(()=>{let m=!1;async function h(){try{const g=await Di();if(m)return;l.current=g.dashboardCurrentNodeId;const p=g.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const f=localStorage.getItem(XT);if(f){const x=JSON.parse(f);x?.id&&x?.type==="remote"&&(l.current=x.id,await an({dashboardCurrentNodeId:x.id}).catch(()=>{}))}}catch{}}catch{}finally{m||r(!1)}}return h(),()=>{m=!0}},[]),a.useEffect(()=>{if(!i)if(n&&n.type==="remote"&&n.id){const m=n.id;l.current!==m&&(l.current=m,an({dashboardCurrentNodeId:m}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,an({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,i]);const c=a.useCallback(m=>{s(m)},[]),u=a.useCallback(()=>{s(null),l.current=void 0,an({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),d={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:u};return t.jsx(tg.Provider,{value:d,children:e})}function eP(){const e=a.useContext(tg);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}function tP({open:e}){const[n,s]=a.useState(""),i=a.useRef(null);a.useEffect(()=>{e&&i.current?.focus()},[e]);const r=a.useCallback(()=>{const l=n.trim();l&&(Xb(l),window.location.reload())},[n]),o=a.useCallback(()=>{Zb(),window.location.reload()},[]);return e?t.jsx("div",{className:"modal-overlay open auth-token-recovery-overlay",role:"presentation",onKeyDownCapture:l=>{l.key==="Escape"&&(l.preventDefault(),l.stopPropagation())},children:t.jsxs("div",{className:"modal modal-md",role:"dialog","aria-modal":"true","aria-labelledby":"auth-token-recovery-title","aria-describedby":"auth-token-recovery-description",children:[t.jsx("div",{className:"modal-header auth-token-recovery-header",children:t.jsx("h3",{id:"auth-token-recovery-title",children:"Authentication token required"})}),t.jsxs("div",{className:"auth-token-recovery-content",children:[t.jsx("p",{id:"auth-token-recovery-description",children:"This dashboard session can't authenticate with the daemon. Set a replacement token or clear the current token and retry."}),t.jsxs("div",{className:"auth-token-recovery-field",children:[t.jsx("label",{htmlFor:"auth-token-recovery-input",children:"Replacement token"}),t.jsx("input",{ref:i,id:"auth-token-recovery-input",className:"input",type:"password",value:n,onChange:l=>s(l.target.value),placeholder:"Paste token",autoComplete:"off",spellCheck:!1})]})]}),t.jsxs("div",{className:"modal-actions auth-token-recovery-actions",children:[t.jsx("button",{type:"button",className:"btn",onClick:o,children:"Clear token and retry"}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:r,disabled:n.trim().length===0,children:"Set token and reload"})]})]})}):null}const nP=a.lazy(()=>sn(()=>import("./AgentsView-BkgNEbNs.js").then(e=>e.A),__vite__mapDeps([17,1,18,8,19])).then(e=>({default:e.AgentsView}))),sP=a.lazy(()=>sn(()=>import("./DocumentsView-DOe0E1WQ.js"),__vite__mapDeps([20,1,0,2,21])).then(e=>({default:e.DocumentsView}))),iP=a.lazy(()=>sn(()=>import("./InsightsView-DWZbS6z-.js"),__vite__mapDeps([22,1,14,0,2,23])).then(e=>({default:e.InsightsView}))),aP=a.lazy(()=>sn(()=>import("./NodesView-DO9jxhM4.js"),__vite__mapDeps([24,1,18,0,2,25])).then(e=>({default:e.NodesView}))),rP=a.lazy(()=>sn(()=>import("./ChatView-LDte0TdV.js"),__vite__mapDeps([26,1,0,2])).then(e=>({default:e.ChatView}))),oP=a.lazy(()=>sn(()=>import("./RoadmapsView-CgAM3YfN.js"),__vite__mapDeps([27,1,0,2,28])).then(e=>({default:e.RoadmapsView}))),lP=a.lazy(()=>sn(()=>import("./SkillsView-BhwtL-0_.js"),__vite__mapDeps([29,1,0,2,30])).then(e=>({default:e.SkillsView}))),cP=a.lazy(()=>sn(()=>import("./MemoryView-BxnlhBoa.js"),__vite__mapDeps([31,1,12,13,0,2,32])).then(e=>({default:e.MemoryView}))),dP=a.lazy(()=>sn(()=>import("./DevServerView-AXznq3jv.js"),__vite__mapDeps([33,1,0,2,34])).then(e=>({default:e.DevServerView}))),uP=a.lazy(()=>sn(()=>import("./TodoView-CmhUBFNV.js"),__vite__mapDeps([35,1,36,0,2,37])).then(e=>({default:e.TodoView})));function mP(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{sn(()=>import("./AgentsView-BkgNEbNs.js").then(n=>n.A),__vite__mapDeps([17,1,18,8,19])),sn(()=>import("./DocumentsView-DOe0E1WQ.js"),__vite__mapDeps([20,1,0,2,21])),sn(()=>import("./InsightsView-DWZbS6z-.js"),__vite__mapDeps([22,1,14,0,2,23])),sn(()=>import("./NodesView-DO9jxhM4.js"),__vite__mapDeps([24,1,18,0,2,25])),sn(()=>import("./ChatView-LDte0TdV.js"),__vite__mapDeps([26,1,0,2])),sn(()=>import("./RoadmapsView-CgAM3YfN.js"),__vite__mapDeps([27,1,0,2,28])),sn(()=>import("./SkillsView-BhwtL-0_.js"),__vite__mapDeps([29,1,0,2,30])),sn(()=>import("./MemoryView-BxnlhBoa.js"),__vite__mapDeps([31,1,12,13,0,2,32])),sn(()=>import("./DevServerView-AXznq3jv.js"),__vite__mapDeps([33,1,0,2,34])),sn(()=>import("./TodoView-CmhUBFNV.js"),__vite__mapDeps([35,1,36,0,2,37]))})}const Xl="kb-setup-warning-dismissed";function hP(){const{toasts:e,addToast:n,removeToast:s}=_T(),i=typeof window<"u"&&!!window.electronAPI;a.useEffect(()=>{mP()},[]);const{projects:r,loading:o,error:l,refresh:c}=kT(),{nodes:u}=NT(),{currentNode:d,currentNodeId:m,isRemote:h,setCurrentNode:g,clearCurrentNode:p}=eP(),{currentProject:f,setCurrentProject:x,clearCurrentProject:v,loading:b}=ET(r,{nodeId:m}),{hasAiProvider:y,hasGithub:S,loading:k,hasWarnings:M}=Bf(f?.id),{updateAvailable:w,latestVersion:_,currentVersion:N,dismissed:L,dismiss:T}=OT();a.useEffect(()=>{if(m&&!d&&u.length>0){const ot=u.find(Ht=>Ht.id===m);if(ot){g(ot);return}}m&&u.length>0&&(u.some(Ht=>Ht.id===m)||p())},[m,d,u,g,p]);const[I,z]=a.useState(""),K=YT(m,{projectId:f?.id,searchQuery:I||void 0});QT(m);const P=h&&K.projects.length>0?K.projects:r,{themeMode:E,colorTheme:R,setThemeMode:B,setColorTheme:G}=IT(),{sessions:X,generating:C,needsInput:$,planningSessions:A,dismissSession:j}=xT(f?.id),J=X.filter(ot=>ot.status==="awaiting_input"||ot.status==="error"),W=$T({projectId:f?.id,planningSessions:A}),{viewMode:oe,setViewMode:he,taskView:se,handleChangeTaskView:fe}=HT({projectsLoading:o,projectsError:l,currentProjectLoading:b,currentProject:f,projectsLength:r.length,setupWizardOpen:W.setupWizardOpen,openSetupWizard:W.openSetupWizard,themeMode:E,setThemeMode:B}),U=a.useCallback(ot=>{ot==="missions"&&(Qe(void 0),Re(void 0),ct(void 0)),fe(ot)},[fe]),Ne=se==="board"||se==="list",{tasks:ee,createTask:ve,moveTask:ue,pauseTask:ye,deleteTask:ie,mergeTask:Me,retryTask:ze,updateTask:Be,duplicateTask:Je,archiveTask:Ye,unarchiveTask:Ge,archiveAllDone:it,loadArchivedTasks:_e,lastFetchTimeMs:Fe}=bT({...f?{projectId:f.id}:{},searchQuery:I||void 0,sseEnabled:Ne}),[ae,be]=a.useState(!1),ne=a.useRef(performance.now()),Ie=a.useRef(!1),Pe=a.useRef(!1),ce=a.useMemo(()=>o?"projects":b?"project":"tasks",[o,b]);a.useEffect(()=>{if(!o&&!Ie.current){Ie.current=!0;const ot=`projects loaded at ${Math.round(performance.now()-ne.current)}ms from mount`;console.log(`[App] ${ot}`),Ya("[App]",ot)}if(!b&&!Pe.current){Pe.current=!0;const ot=`current-project resolved at ${Math.round(performance.now()-ne.current)}ms from mount`;console.log(`[App] ${ot}`),Ya("[App]",ot)}},[o,b]),a.useEffect(()=>{if(ae||o||b)return;const ot=performance.now(),Ht=window.setTimeout(()=>{const en=`dashboard ready at ${Math.round(performance.now()-ne.current)}ms from mount (settle delay=${Math.round(performance.now()-ot)}ms)`;console.log(`[App] ${en}`),Ya("[App]",en),be(!0)},200);return()=>{window.clearTimeout(Ht)}},[ae,o,b]);const $e=br()==="mobile",[at,tt]=a.useState(0),V=a.useCallback(()=>{ip(f?.id).then(ot=>{tt(ot.unreadCount)}).catch(ot=>{console.warn("[App] Failed to fetch mailbox unread count:",ot)})},[f?.id]);a.useEffect(()=>{V();const ot=new URLSearchParams;f?.id&&ot.set("projectId",f.id);const Ht=ot.size>0?`?${ot.toString()}`:"";return $s(`/api/events${Ht}`,{events:{"message:sent":V,"message:received":V,"message:read":V,"message:deleted":V}})},[f?.id,V]);const[de,Z]=a.useState(!1),[we,pe]=a.useState(!1),[Te,Qe]=a.useState(void 0),[Ee,Re]=a.useState(void 0),[Le,ct]=a.useState(void 0),[Se,mt]=a.useState(!1),[gt,wt]=a.useState(!1),[yt,kt]=a.useState(()=>zn(Xl,f?.id)==="true");a.useEffect(()=>{kt(zn(Xl,f?.id)==="true")},[f?.id]),a.useEffect(()=>{const ot=()=>{wt(!0)};return window.addEventListener(dc,ot),()=>{window.removeEventListener(dc,ot)}},[]);const Ct=a.useCallback(()=>{as(Xl,"true",f?.id),kt(!0)},[f?.id]),{maxConcurrent:Rt,autoMerge:Ft,globalPaused:Ut,enginePaused:St,taskStuckTimeoutMs:Et,showQuickChatFAB:It,prAuthAvailable:Mt,experimentalFeatures:Kt,insightsEnabled:Ot,roadmapEnabled:xe,memoryEnabled:st,devServerEnabled:Ve,todosEnabled:Y,toggleAutoMerge:F,toggleGlobalPause:H,toggleEnginePause:ge,refresh:me}=DT(f?.id),We=Kt.skillsView===!0,dt=Kt.nodesView===!0,_t=!0;a.useEffect(()=>{Object.keys(Kt).length!==0&&(se==="insights"&&!Ot&&fe("board"),se==="roadmaps"&&!xe&&fe("board"),se==="memory"&&!st&&fe("board"),(se==="devserver"||se==="dev-server")&&!Ve&&fe("board"),se==="todos"&&!Y&&fe("board"))},[se,Ot,xe,Kt,fe,_t,st,Ve,Y]),a.useEffect(()=>{de&&!dt&&Z(!1)},[de,dt]);const{availableModels:$t,favoriteProviders:vn,favoriteModels:kn,toggleFavoriteProvider:Yt,toggleFavoriteModel:En}=zT();FT({projectId:f?.id,setupWizardOpen:W.setupWizardOpen,openModelOnboarding:W.openModelOnboarding,openSettings:W.openSettings});const{handleSelectProject:on,handleViewAllProjects:Mn,handleOpenSettings:Vt,handleAddProject:hn,handleSetupComplete:ke,handleModelOnboardingComplete:nt,handlePauseProject:tn,handleResumeProject:Pn,handleRemoveProject:Nn,handleToggleFavorite:gn,handleToggleModelFavorite:nn}=qT({setCurrentProject:x,clearCurrentProject:v,setViewMode:he,currentProject:f,refreshProjects:c,toggleFavoriteProvider:Yt,toggleFavoriteModel:En,addToast:n,openSettings:W.openSettings,openSetupWizard:W.openSetupWizard,closeSetupWizard:W.closeSetupWizard,closeModelOnboarding:W.closeModelOnboarding}),{handleDetailClose:_n}=LT({projectId:f?.id,projects:r,projectsLoading:o,currentProject:f,setCurrentProject:x,addToast:n,openTaskDetail:W.openDetailTask,closeTaskDetail:W.closeDetailTask}),{handleBoardQuickCreate:jn,handleModalCreate:Q,handlePlanningTaskCreated:Oe,handlePlanningTasksCreated:Xe,handleSubtaskTasksCreated:Ze,handleGitHubImport:pt}=VT({createTask:ve,onPlanningTaskCreated:W.onPlanningTaskCreated,onPlanningTasksCreated:W.onPlanningTasksCreated,onSubtaskTasksCreated:W.onSubtaskTasksCreated,addToast:n}),Nt=a.useCallback((ot,Ht)=>{if(Ht==="changes"){W.openDetailWithChangesTab(ot);return}W.openDetailTask(ot,Ht)},[W]),At=a.useCallback(()=>{dt&&Z(ot=>!ot)},[dt]),xn=a.useCallback(()=>{W.setFileWorkspace("project"),W.openFiles()},[W]),Qt=a.useCallback(async()=>{pe(!0);try{await c()}finally{pe(!1)}},[c]),bt=a.useCallback(ot=>{Re(ot),Qe(void 0),fe("missions")},[fe]),Kn=a.useCallback(ot=>{ot.type==="planning"?W.openPlanningWithSession(ot.id):ot.type==="subtask"?W.openSubtaskWithSession(ot.id):ot.type==="mission_interview"?(Re(void 0),Qe(ot.id),ct(void 0),fe("missions")):(ot.type==="milestone_interview"||ot.type==="slice_interview")&&(Qe(void 0),Re(void 0),ct(ot.id),fe("missions"))},[fe,W]),re=a.useCallback(()=>{},[]),Ae=a.useCallback(()=>{},[]),lt=!o&&!b&&r.length===0&&!f&&!!l,vt=()=>lt?t.jsx(E4,{errorMessage:l??"Failed to fetch projects",isRetrying:we,onRetry:Qt}):de?t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(Yn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(aP,{addToast:n,onClose:()=>Z(!1)})})})}):oe==="overview"?t.jsx(Yn,{children:t.jsx(xN,{projects:r,loading:o,onSelectProject:on,onAddProject:hn,onPauseProject:tn,onResumeProject:Pn,onRemoveProject:Nn,nodes:u})}):se==="skills"?We?t.jsx(Yn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(lP,{addToast:n,projectId:f?.id,onClose:()=>fe("board")})})}):(fe("board"),null):se==="chat"?t.jsx(Yn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(rP,{addToast:n,projectId:f?.id})})}):se==="mailbox"?t.jsx(Yn,{children:t.jsx(c1,{projectId:f?.id,addToast:n,onUnreadCountChange:tt})}):se==="roadmaps"?t.jsx(Yn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(oP,{addToast:n,projectId:f?.id})})}):se==="missions"?t.jsx(Yn,{children:t.jsx(a1,{isInline:!0,isOpen:!0,onClose:()=>{Re(void 0),Qe(void 0),ct(void 0),fe("board")},addToast:n,projectId:f?.id,onSelectTask:ot=>{const Ht=ee.find(en=>en.id===ot);Ht&&W.openDetailTask(Ht)},availableTasks:ee.map(ot=>({id:ot.id,title:ot.title})),resumeSessionId:Te,targetMissionId:Ee,milestoneSliceResumeSessionId:Le,onMilestoneSliceResumeFetchError:()=>ct(void 0)})}):se==="agents"&&_t?t.jsx(Yn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(nP,{addToast:n,projectId:f?.id})})}):se==="documents"?t.jsx(Yn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(sP,{projectId:f?.id,addToast:n,onOpenDetail:W.openDetailTask})})}):se==="insights"?t.jsx(Yn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(iP,{projectId:f?.id,addToast:n,onClose:()=>fe("board")})})}):se==="memory"?t.jsx(Yn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(cP,{addToast:n,projectId:f?.id})})}):se==="todos"?t.jsx(Yn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(uP,{addToast:n,projectId:f?.id})})}):se==="devserver"||se==="dev-server"?t.jsx(Yn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(dP,{addToast:n,projectId:f?.id})})}):se==="board"?t.jsx(Yn,{children:t.jsx(aN,{tasks:h&&K.tasks.length>0?K.tasks:ee,projectId:f?.id,maxConcurrent:Rt,onMoveTask:ue,onPauseTask:ye,onOpenDetail:W.openDetailTask,addToast:n,onQuickCreate:jn,onNewTask:W.openNewTask,onPlanningMode:W.openPlanningWithInitialPlan,onSubtaskBreakdown:W.openSubtaskBreakdown,autoMerge:Ft,onToggleAutoMerge:F,globalPaused:Ut,onUpdateTask:Be,onArchiveTask:Ye,onUnarchiveTask:Ge,onDeleteTask:ie,onArchiveAllDone:it,onLoadArchivedTasks:_e,searchQuery:I,availableModels:$t,onOpenDetailWithTab:Nt,favoriteProviders:vn,favoriteModels:kn,onToggleFavorite:gn,onToggleModelFavorite:nn,taskStuckTimeoutMs:Et,onOpenMission:bt,lastFetchTimeMs:Fe})}):t.jsx(Yn,{children:t.jsx(oN,{tasks:h&&K.tasks.length>0?K.tasks:ee,projectId:f?.id,onMoveTask:ue,onOpenDetail:W.openDetailTask,addToast:n,globalPaused:Ut,onNewTask:W.openNewTask,onQuickCreate:jn,onPlanningMode:W.openPlanningWithInitialPlan,onSubtaskBreakdown:W.openSubtaskBreakdown,availableModels:$t,favoriteProviders:vn,favoriteModels:kn,onToggleFavorite:gn,onToggleModelFavorite:nn,taskStuckTimeoutMs:Et,searchQuery:I,lastFetchTimeMs:Fe})});if(!ae)return t.jsxs(t.Fragment,{children:[t.jsx(_4,{stage:ce}),t.jsx(Gf,{toasts:e,onRemove:s})]});const xt=!W.modelOnboardingOpen&&XR(),Zt=!W.modelOnboardingOpen&&!xt&&fa()&&!qf();return t.jsxs(t.Fragment,{children:[t.jsx(Oj,{isElectron:i,onOpenSettings:Vt,onOpenGitHubImport:W.openGitHubImport,onOpenPlanning:W.openPlanning,onResumePlanning:W.resumePlanning,activePlanningSessionCount:A.length,onOpenUsage:W.openUsage,onOpenActivityLog:W.openActivityLog,onOpenSystemStats:W.openSystemStats,onOpenMailbox:()=>U("mailbox"),mailboxUnreadCount:at,onOpenSchedules:W.openSchedules,onOpenGitManager:W.openGitManager,onOpenNodes:At,showNodesButton:dt,onOpenWorkflowSteps:W.openWorkflowSteps,onOpenScripts:W.openScripts,onRunScript:W.runScript,onToggleTerminal:W.toggleTerminal,onOpenFiles:W.openFiles,filesOpen:W.filesOpen,globalPaused:Ut,enginePaused:St,onToggleGlobalPause:H,onToggleEnginePause:ge,view:se,onChangeView:oe==="project"&&f?U:void 0,showSkillsTab:We,showAgentsTab:_t,searchQuery:I,onSearchChange:z,projects:P,currentProject:f,onSelectProject:on,onViewAllProjects:Mn,projectId:f?.id,mobileNavEnabled:$e,availableNodes:u,currentNode:d,onSelectNode:ot=>{ot===null?p():g(ot)},isRemote:h,experimentalFeatures:{insights:Ot,roadmap:xe,memoryView:st,devServer:Ve,devServerView:Ve,todoView:Y}}),oe==="project"&&f&&!de&&se!=="missions"&&!W.isPlanningOpen&&t.jsx(B4,{sessions:J,onResumeSession:Kn,onDismissSession:re,onDismissAll:Ae}),oe==="project"&&f&&xt&&t.jsx(q4,{onResume:W.openModelOnboarding}),oe==="project"&&f&&Zt&&t.jsx(V4,{onOpenModelOnboarding:W.openModelOnboarding,onOpenSettings:ot=>W.openSettings(ot)}),oe==="project"&&f&&w&&_&&N&&!L&&t.jsx(H4,{latestVersion:_,currentVersion:N,onDismiss:T}),oe==="project"&&f&&!k&&M&&!yt&&t.jsx(Hf,{hasAiProvider:y,hasGithub:S,onDismiss:Ct}),t.jsx("div",{className:`project-content${oe==="project"&&f?" project-content--with-footer":""}${$e?" project-content--with-mobile-nav":""}`,children:vt()}),oe==="project"&&f&&!de&&t.jsx(F4,{tasks:h&&K.tasks.length>0?K.tasks:ee,projectId:f.id,taskStuckTimeoutMs:Et,backgroundSessions:X,backgroundGenerating:C,backgroundNeedsInput:$,onOpenBackgroundSession:Kn,onDismissBackgroundSession:j,lastFetchTimeMs:Fe,currentProjectPath:f.path,onOpenProjectDirectory:xn}),t.jsx(K4,{view:se,onChangeView:oe==="project"&&f?U:()=>{},footerVisible:oe==="project"&&!!f,modalOpen:W.anyModalOpen,onOpenSettings:Vt,onOpenActivityLog:W.openActivityLog,onOpenSystemStats:W.openSystemStats,onOpenMailbox:()=>U("mailbox"),mailboxUnreadCount:at,onOpenGitManager:W.openGitManager,onOpenWorkflowSteps:W.openWorkflowSteps,onOpenSchedules:W.openSchedules,onOpenScripts:W.openScripts,onToggleTerminal:W.toggleTerminal,onOpenFiles:W.openFiles,onOpenGitHubImport:W.openGitHubImport,onOpenPlanning:W.openPlanning,onResumePlanning:W.resumePlanning,activePlanningSessionCount:A.length,onOpenUsage:()=>W.openUsage(null),onViewAllProjects:Mn,onRunScript:W.runScript,projectId:f?.id,showSkillsTab:We,experimentalFeatures:{insights:Ot,roadmap:xe,memoryView:st,devServer:Ve,devServerView:Ve,todoView:Y}}),oe==="project"&&f&&se!=="chat"&&se!=="mailbox"&&se!=="insights"&&se!=="devserver"&&se!=="dev-server"&&t.jsx(gT,{projectId:f.id,addToast:n,showFAB:It,open:Se,onOpenChange:mt,favoriteProviders:vn,favoriteModels:kn,onToggleFavorite:gn,onToggleModelFavorite:nn}),t.jsx(C4,{projectId:f?.id,tasks:ee,projects:r,currentProject:f,addToast:n,toasts:e,removeToast:s,modalManager:W,projectActions:{handleAddProject:hn,handleSetupComplete:ke,handleModelOnboardingComplete:nt},taskHandlers:{handleModalCreate:Q,handlePlanningTaskCreated:Oe,handlePlanningTasksCreated:Xe,handleSubtaskTasksCreated:Ze,handleGitHubImport:pt},taskOperations:{moveTask:ue,deleteTask:ie,mergeTask:Me,retryTask:ze,duplicateTask:Je},deepLink:{handleDetailClose:_n},settings:{prAuthAvailable:Mt,themeMode:E,colorTheme:R,setThemeMode:B,setColorTheme:G},onSettingsClose:()=>{W.closeSettings(),me()},onReopenOnboarding:()=>{W.closeSettings(),W.openModelOnboarding()}}),t.jsx(tP,{open:gt})]})}function pP(){return t.jsx(MT,{children:t.jsx(ZT,{children:t.jsx(Yj,{children:t.jsx(hP,{})})})})}rv();Vb();sg.createRoot(document.getElementById("root")).render(t.jsx(a.StrictMode,{children:t.jsx(Wb,{children:t.jsx(pP,{})})}));"serviceWorker"in navigator&&navigator.serviceWorker.register("/sw.js").then(e=>{console.log("SW registered:",e.scope)}).catch(e=>{console.log("SW registration failed:",e)});export{sn as $,Es as A,pn as B,un as C,LR as D,G$ as E,Ri as F,jo as G,mn as H,Vl as I,fn as J,Jt as K,rt as L,qs as M,qt as N,BR as O,Tn as P,ck as Q,wn as R,ea as S,zc as T,$R as U,DR as V,dk as W,zt as X,uk as Y,In as Z,CI as _,as as a,e$ as a$,QP as a0,XP as a1,ao as a2,vy as a3,nc as a4,sa as a5,ga as a6,si as a7,ii as a8,ni as a9,rr as aA,Tj as aB,L$ as aC,z$ as aD,Pj as aE,Ij as aF,eT as aG,br as aH,iT as aI,yo as aJ,G4 as aK,X4 as aL,ms as aM,Ei as aN,ui as aO,zb as aP,HI as aQ,VI as aR,qI as aS,WI as aT,KI as aU,GI as aV,JI as aW,YI as aX,QI as aY,XI as aZ,ZI as a_,F$ as aa,B$ as ab,U$ as ac,O$ as ad,H$ as ae,Vn as af,Zn as ag,Rb as ah,Ws as ai,Yg as aj,vo as ak,hi as al,Q$ as am,J$ as an,Y$ as ao,X$ as ap,no as aq,yb as ar,Ja as as,Vg as at,Qn as au,Fh as av,NT as aw,kT as ax,D$ as ay,Gd as az,$I as b,rI as b$,t$ as b0,n$ as b1,i$ as b2,a$ as b3,s$ as b4,Rn as b5,Lc as b6,Ai as b7,I$ as b8,P$ as b9,zy as bA,Fy as bB,Oy as bC,Ly as bD,oI as bE,mr as bF,So as bG,bb as bH,nr as bI,o$ as bJ,l$ as bK,c$ as bL,d$ as bM,u$ as bN,m$ as bO,h$ as bP,r$ as bQ,qh as bR,ra as bS,xk as bT,Xb as bU,Zb as bV,M$ as bW,eI as bX,ZP as bY,_$ as bZ,tI as b_,$$ as ba,TP as bb,RP as bc,AP as bd,PP as be,UP as bf,BP as bg,zP as bh,$P as bi,DP as bj,LP as bk,IP as bl,_P as bm,FP as bn,NA as bo,dI as bp,cI as bq,gI as br,lI as bs,uI as bt,mI as bu,hI as bv,pI as bw,Uy as bx,fI as by,Oc as bz,Ue as c,AI as c$,nI as c0,sI as c1,iI as c2,aI as c3,bg as c4,Gs as c5,dA as c6,HP as c7,UI as c8,xP as c9,jP as cA,wP as cB,NP as cC,SP as cD,CP as cE,EP as cF,MP as cG,Dm as cH,W$ as cI,K$ as cJ,OP as cK,p$ as cL,g$ as cM,v$ as cN,x$ as cO,f$ as cP,b$ as cQ,y$ as cR,Xh as cS,_d as cT,Cx as cU,k$ as cV,MI as cW,wI as cX,SI as cY,NI as cZ,RI as c_,bP as ca,ir as cb,DI as cc,vP as cd,kP as ce,Wv as cf,Lv as cg,Ks as ch,zv as ci,Fv as cj,Ov as ck,WP as cl,LI as cm,zI as cn,FI as co,fi as cp,q$ as cq,V$ as cr,BI as cs,yP as ct,ec as cu,Dn as cv,jA as cw,qR as cx,Wl as cy,Ao as cz,PI as d,Ph as d0,kI as d1,yI as d2,IR as d3,EI as d4,ur as d5,zM as d6,bI as d7,xI as d8,yy as d9,vI as da,jI as db,j$ as dc,w$ as dd,ub as de,rc as df,A$ as dg,C$ as dh,S$ as di,E$ as dj,N$ as dk,OI as dl,KP as dm,qP as dn,VP as dp,JP as dq,YP as dr,GP as ds,II as e,T$ as f,zn as g,os as h,xa as i,R$ as j,Ln as k,lk as l,TI as m,Q4 as n,Is as o,Eo as p,_r as q,je as r,$s as s,Kj as t,an as u,_I as v,ic as w,Vs as x,Xt as y,to as z};