@runfusion/fusion 0.13.0 → 0.14.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 (69) hide show
  1. package/README.md +13 -0
  2. package/dist/bin.js +1250 -522
  3. package/dist/client/assets/AgentDetailView-CBFUveyO.js +18 -0
  4. package/dist/client/assets/{AgentsView-Dvf_xUkx.js → AgentsView-DPezXQ-U.js} +4 -4
  5. package/dist/client/assets/ChatView-5N4-EuhD.js +1 -0
  6. package/dist/client/assets/{DevServerView-C2qTJch7.js → DevServerView-Daft4YFc.js} +1 -1
  7. package/dist/client/assets/{DirectoryPicker-DRfhg9zz.js → DirectoryPicker-rew1y6qO.js} +1 -1
  8. package/dist/client/assets/{DocumentsView-j8ic1xUw.js → DocumentsView-i72qJzwd.js} +1 -1
  9. package/dist/client/assets/{InsightsView-CpAz3o0i.js → InsightsView-BL5eZJ0a.js} +1 -1
  10. package/dist/client/assets/{MemoryView-BcQsi_JK.js → MemoryView-pl8Cdg_p.js} +1 -1
  11. package/dist/client/assets/{NodesView-Bo_Yhr4N.js → NodesView-D6eJ15zc.js} +1 -1
  12. package/dist/client/assets/PiExtensionsManager-ExInwXWP.js +11 -0
  13. package/dist/client/assets/{PluginManager-BQhBHWrB.js → PluginManager-CYhtxHun.js} +1 -1
  14. package/dist/client/assets/{ResearchView-CLyyqAWE.js → ResearchView-B_QPUEjB.js} +1 -1
  15. package/dist/client/assets/{RoadmapsView-tG7IdOoc.js → RoadmapsView-DBNLaEsK.js} +1 -1
  16. package/dist/client/assets/SettingsModal-1ET586M3.js +31 -0
  17. package/dist/client/assets/{SettingsModal-CXUGeZ0_.js → SettingsModal-CL_gWmOj.js} +1 -1
  18. package/dist/client/assets/SettingsModal-D_AFkDJa.css +1 -0
  19. package/dist/client/assets/{SetupWizardModal-BMJL6eNR.js → SetupWizardModal-CLkY9HFL.js} +1 -1
  20. package/dist/client/assets/{SkillMultiselect-ILMft-Kz.js → SkillMultiselect-B0qi32SQ.js} +1 -1
  21. package/dist/client/assets/{SkillsView-x4_YwBz6.js → SkillsView-umVjRq6o.js} +1 -1
  22. package/dist/client/assets/TodoView-CFifSvrD.js +6 -0
  23. package/dist/client/assets/TodoView-SeO9o7km.css +1 -0
  24. package/dist/client/assets/{folder-open-DDdJt8aE.js → folder-open-nYPrL1W3.js} +1 -1
  25. package/dist/client/assets/index-Bc8nfKeH.js +661 -0
  26. package/dist/client/assets/index-C1prPuSl.css +1 -0
  27. package/dist/client/assets/{list-checks-DFxQ9biT.js → list-checks-sK8xJeH_.js} +1 -1
  28. package/dist/client/assets/{star-BKs1bgJN.js → star-BRtXbYkB.js} +1 -1
  29. package/dist/client/assets/{upload-Bb5Pidne.js → upload-BP60eBwN.js} +1 -1
  30. package/dist/client/assets/{users-BImNn91Q.js → users-qSGAX2Pf.js} +1 -1
  31. package/dist/client/index.html +2 -2
  32. package/dist/client/sw.js +6 -0
  33. package/dist/client/version.json +1 -1
  34. package/dist/droid-cli/index.ts +127 -0
  35. package/dist/droid-cli/package.json +37 -0
  36. package/dist/droid-cli/src/__tests__/control-handler.test.ts +164 -0
  37. package/dist/droid-cli/src/__tests__/event-bridge.test.ts +1318 -0
  38. package/dist/droid-cli/src/__tests__/mcp-config.test.ts +310 -0
  39. package/dist/droid-cli/src/__tests__/process-manager.test.ts +818 -0
  40. package/dist/droid-cli/src/__tests__/prompt-builder.test.ts +1206 -0
  41. package/dist/droid-cli/src/__tests__/provider.test.ts +1894 -0
  42. package/dist/droid-cli/src/__tests__/setup-test-isolation.test.ts +32 -0
  43. package/dist/droid-cli/src/__tests__/setup-test-isolation.ts +14 -0
  44. package/dist/droid-cli/src/__tests__/stream-parser.test.ts +188 -0
  45. package/dist/droid-cli/src/__tests__/thinking-config.test.ts +141 -0
  46. package/dist/droid-cli/src/__tests__/tool-mapping.test.ts +253 -0
  47. package/dist/droid-cli/src/control-handler.ts +82 -0
  48. package/dist/droid-cli/src/event-bridge.ts +397 -0
  49. package/dist/droid-cli/src/mcp-config.ts +144 -0
  50. package/dist/droid-cli/src/mcp-schema-server.cjs +49 -0
  51. package/dist/droid-cli/src/process-manager.ts +358 -0
  52. package/dist/droid-cli/src/prompt-builder.ts +629 -0
  53. package/dist/droid-cli/src/provider.ts +447 -0
  54. package/dist/droid-cli/src/stream-parser.ts +37 -0
  55. package/dist/droid-cli/src/thinking-config.ts +83 -0
  56. package/dist/droid-cli/src/tool-mapping.ts +147 -0
  57. package/dist/droid-cli/src/types.ts +87 -0
  58. package/dist/extension.js +473 -119
  59. package/dist/pi-claude-cli/package.json +1 -1
  60. package/package.json +2 -1
  61. package/dist/client/assets/AgentDetailView-B7j297GT.js +0 -18
  62. package/dist/client/assets/ChatView-BgUt38ty.js +0 -1
  63. package/dist/client/assets/PiExtensionsManager-DHt2zFg8.js +0 -11
  64. package/dist/client/assets/SettingsModal-9HS8MnmW.css +0 -1
  65. package/dist/client/assets/SettingsModal-UziTDnLh.js +0 -31
  66. package/dist/client/assets/TodoView-BBYcMbXE.js +0 -6
  67. package/dist/client/assets/TodoView-C1g65hJo.css +0 -1
  68. package/dist/client/assets/index-B15xwijw.css +0 -1
  69. package/dist/client/assets/index-DmSs2FGE.js +0 -661
@@ -0,0 +1,661 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AgentDetailView-CBFUveyO.js","assets/vendor-react-K0fH_qHe.js","assets/star-BRtXbYkB.js","assets/SkillMultiselect-B0qi32SQ.js","assets/SkillMultiselect-DDHJnrkn.css","assets/list-checks-sK8xJeH_.js","assets/vendor-xterm-DzcZoU0P.js","assets/vendor-xterm-LZoznX6r.css","assets/AgentDetailView-B5tq9ius.css","assets/addon-fit-C7jRorKK.js","assets/addon-web-links-CkJwd4cQ.js","assets/addon-webgl-BjvOw43o.js","assets/SetupWizardModal-CLkY9HFL.js","assets/DirectoryPicker-rew1y6qO.js","assets/folder-open-nYPrL1W3.js","assets/DirectoryPicker-DzKVmxOf.css","assets/SetupWizardModal-DRF5fOoR.css","assets/SettingsModal-1ET586M3.js","assets/SettingsModal-CL_gWmOj.js","assets/SettingsModal-DcGFm6NR.css","assets/users-qSGAX2Pf.js","assets/SettingsModal-D_AFkDJa.css","assets/AgentsView-DPezXQ-U.js","assets/upload-BP60eBwN.js","assets/AgentsView-V5GhlBYu.css","assets/DocumentsView-i72qJzwd.js","assets/DocumentsView-BrhyOdeE.css","assets/InsightsView-BL5eZJ0a.js","assets/InsightsView-4KiUKzbz.css","assets/ResearchView-B_QPUEjB.js","assets/ResearchView-BzRdUzNq.css","assets/NodesView-D6eJ15zc.js","assets/NodesView-DCoS6iYh.css","assets/ChatView-5N4-EuhD.js","assets/RoadmapsView-DBNLaEsK.js","assets/RoadmapsView-BOYnyMCh.css","assets/SkillsView-umVjRq6o.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-pl8Cdg_p.js","assets/MemoryView-DiajLXby.css","assets/DevServerView-Daft4YFc.js","assets/DevServerView-DlZpuAnj.css","assets/TodoView-CFifSvrD.js","assets/TodoView-SeO9o7km.css"])))=>i.map(i=>d[i]);
2
+ import{r as a,j as t,R as Ao,a as ma,g as lp,c as Yg}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 cp=(...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 Qg=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 Xg=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=Xg(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 yl={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 Zg=e=>{for(const n in e)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},eb=a.createContext({}),tb=()=>a.useContext(eb),nb=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:f="currentColor",className:p=""}=tb()??{},g=i??h?Number(s??m)*24/Number(n??d):s??m;return a.createElement("svg",{ref:u,...yl,width:n??d??yl.width,height:n??d??yl.height,stroke:e??f,strokeWidth:g,className:cp("lucide",p,r),...!o&&!Zg(c)&&{"aria-hidden":"true"},...c},[...l.map(([b,v])=>a.createElement(b,v)),...Array.isArray(o)?o:[o]])});/**
33
+ * @license lucide-react v1.7.0 - ISC
34
+ *
35
+ * This source code is licensed under the ISC license.
36
+ * See the LICENSE file in the root directory of this source tree.
37
+ */const Ke=(e,n)=>{const s=a.forwardRef(({className:i,...r},o)=>a.createElement(nb,{ref:o,iconNode:n,className:cp(`lucide-${Qg(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 sb=[["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"}]],Ds=Ke("activity",sb);/**
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 ib=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h2",key:"tvwodi"}],["path",{d:"M20 8v11a2 2 0 0 1-2 2h-2",key:"1gkqxj"}],["path",{d:"m9 15 3-3 3 3",key:"1pd0qc"}],["path",{d:"M12 12v9",key:"192myk"}]],ab=Ke("archive-restore",ib);/**
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 rb=[["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"}]],Rr=Ke("archive",rb);/**
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 ob=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],Tr=Ke("arrow-down",ob);/**
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 lb=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],_a=Ke("arrow-left",lb);/**
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 cb=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],Pr=Ke("arrow-right",cb);/**
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 db=[["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"}]],dp=Ke("arrow-up-down",db);/**
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 ub=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Fi=Ke("arrow-up",ub);/**
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 mb=[["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"}]],hb=Ke("book-open",mb);/**
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 pb=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],Sn=Ke("bot",pb);/**
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 fb=[["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"}]],Ec=Ke("box",fb);/**
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 gb=[["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"}]],Ro=Ke("brain",gb);/**
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 bb=[["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"}]],up=Ke("calendar",bb);/**
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 xb=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],vb=Ke("check-check",xb);/**
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 yb=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Vn=Ke("check",yb);/**
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 jb=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Xt=Ke("chevron-down",jb);/**
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 kb=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],Jo=Ke("chevron-left",kb);/**
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 wb=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],xn=Ke("chevron-right",wb);/**
128
+ * @license lucide-react v1.7.0 - ISC
129
+ *
130
+ * This source code is licensed under the ISC license.
131
+ * See the LICENSE file in the root directory of this source tree.
132
+ */const Nb=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],bi=Ke("chevron-up",Nb);/**
133
+ * @license lucide-react v1.7.0 - ISC
134
+ *
135
+ * This source code is licensed under the ISC license.
136
+ * See the LICENSE file in the root directory of this source tree.
137
+ */const Sb=[["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"}]],gs=Ke("circle-alert",Sb);/**
138
+ * @license lucide-react v1.7.0 - ISC
139
+ *
140
+ * This source code is licensed under the ISC license.
141
+ * See the LICENSE file in the root directory of this source tree.
142
+ */const Cb=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],wn=Ke("circle-check-big",Cb);/**
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 Eb=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],Yo=Ke("circle-dot",Eb);/**
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 _b=[["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"}]],_c=Ke("circle-question-mark",_b);/**
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 Mb=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],Ab=Ke("circle-stop",Mb);/**
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 Rb=[["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"}]],Ir=Ke("circle-x",Rb);/**
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 Tb=[["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"}]],Pb=Ke("clipboard-list",Tb);/**
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 Ib=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],Ei=Ke("clock",Ib);/**
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 $b=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],mp=Ke("code",$b);/**
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 Db=[["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"}]],Lb=Ke("columns-3",Db);/**
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 zb=[["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"}]],Ui=Ke("copy",zb);/**
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 Fb=[["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"}]],Ob=Ke("cpu",Fb);/**
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 Ub=[["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"}]],Bb=Ke("download",Ub);/**
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 Hb=[["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"}]],qb=Ke("ellipsis-vertical",Hb);/**
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 Vb=[["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"}]],Mc=Ke("ellipsis",Vb);/**
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 Wb=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],Kb=Ke("external-link",Wb);/**
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 Gb=[["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"}]],md=Ke("eye-off",Gb);/**
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 Jb=[["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"}]],Ma=Ke("eye",Jb);/**
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 Yb=[["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"}]],Hs=Ke("file-code",Yb);/**
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 Qb=[["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"}]],Ac=Ke("file-diff",Qb);/**
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 Xb=[["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"}]],Zb=Ke("file-minus",Xb);/**
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 ex=[["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"}]],hp=Ke("file-pen",ex);/**
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 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"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],nx=Ke("file-plus",tx);/**
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 sx=[["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"}]],ix=Ke("file-question-mark",sx);/**
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 ax=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Bi=Ke("file-text",ax);/**
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 rx=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M11 18h2",key:"12mj7e"}],["path",{d:"M12 12v6",key:"3ahymv"}],["path",{d:"M9 13v-.5a.5.5 0 0 1 .5-.5h5a.5.5 0 0 1 .5.5v.5",key:"qbrxap"}]],ox=Ke("file-type",rx);/**
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 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"}]],pp=Ke("file",lx);/**
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 cx=[["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"}]],Rc=Ke("folder-git-2",cx);/**
273
+ * @license lucide-react v1.7.0 - ISC
274
+ *
275
+ * This source code is licensed under the ISC license.
276
+ * See the LICENSE file in the root directory of this source tree.
277
+ */const dx=[["path",{d:"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"}]],Gd=Ke("folder-root",dx);/**
278
+ * @license lucide-react v1.7.0 - ISC
279
+ *
280
+ * This source code is licensed under the ISC license.
281
+ * See the LICENSE file in the root directory of this source tree.
282
+ */const ux=[["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"}]],Xn=Ke("folder",ux);/**
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 mx=[["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=Ke("funnel",mx);/**
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 hx=[["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"}]],Ws=Ke("git-branch",hx);/**
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 px=[["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"}]],$r=Ke("git-commit-horizontal",px);/**
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 fx=[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M6 21V9a9 9 0 0 0 9 9",key:"7kw0sc"}]],fp=Ke("git-merge",fx);/**
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 gx=[["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"}]],Es=Ke("git-pull-request",gx);/**
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 bx=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],Qo=Ke("globe",bx);/**
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 xx=[["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"}]],gp=Ke("grid-3x3",xx);/**
318
+ * @license lucide-react v1.7.0 - ISC
319
+ *
320
+ * This source code is licensed under the ISC license.
321
+ * See the LICENSE file in the root directory of this source tree.
322
+ */const vx=[["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"}]],hd=Ke("grip-vertical",vx);/**
323
+ * @license lucide-react v1.7.0 - ISC
324
+ *
325
+ * This source code is licensed under the ISC license.
326
+ * See the LICENSE file in the root directory of this source tree.
327
+ */const yx=[["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"}]],jx=Ke("hard-drive",yx);/**
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 kx=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5",key:"mvr1a0"}]],wx=Ke("heart",kx);/**
333
+ * @license lucide-react v1.7.0 - ISC
334
+ *
335
+ * This source code is licensed under the ISC license.
336
+ * See the LICENSE file in the root directory of this source tree.
337
+ */const Nx=[["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"}]],yr=Ke("history",Nx);/**
338
+ * @license lucide-react v1.7.0 - ISC
339
+ *
340
+ * This source code is licensed under the ISC license.
341
+ * See the LICENSE file in the root directory of this source tree.
342
+ */const Sx=[["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"}]],or=Ke("inbox",Sx);/**
343
+ * @license lucide-react v1.7.0 - ISC
344
+ *
345
+ * This source code is licensed under the ISC license.
346
+ * See the LICENSE file in the root directory of this source tree.
347
+ */const Cx=[["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"}]],bp=Ke("key",Cx);/**
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 Ex=[["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"}]],_x=Ke("keyboard",Ex);/**
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 Mx=[["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"}]],Hi=Ke("layers",Mx);/**
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 Ax=[["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"}]],qi=Ke("layout-grid",Ax);/**
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 Rx=[["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"}]],ri=Ke("lightbulb",Rx);/**
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 Tx=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]],ga=Ke("link",Tx);/**
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 Px=[["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"}]],Ix=Ke("list-plus",Px);/**
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 $x=[["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"}]],Xo=Ke("list-tree",$x);/**
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 Dx=[["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"}]],Tc=Ke("list",Dx);/**
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 Lx=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],ot=Ke("loader-circle",Lx);/**
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 zx=[["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"}]],Zo=Ke("lock",zx);/**
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 Fx=[["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"}]],ba=Ke("mail",Fx);/**
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 Ox=[["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"}]],Pc=Ke("map",Ox);/**
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 Ux=[["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"}]],el=Ke("maximize-2",Ux);/**
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 Bx=[["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"}]],Hx=Ke("message-square-plus",Bx);/**
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 qx=[["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"}]],Si=Ke("message-square",qx);/**
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 Vx=[["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"}]],Dr=Ke("minimize-2",Vx);/**
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 Wx=[["path",{d:"M5 12h14",key:"1ays0h"}]],Kx=Ke("minus",Wx);/**
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 Gx=[["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"}]],jr=Ke("monitor",Gx);/**
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 Jx=[["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"}]],Yx=Ke("move",Jx);/**
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 Qx=[["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"}]],Ic=Ke("package",Qx);/**
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 Xx=[["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"}]],xp=Ke("paperclip",Xx);/**
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 Zx=[["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=Ke("pause",Zx);/**
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 ev=[["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"}]],hs=Ke("pencil",ev);/**
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 tv=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],Cn=Ke("play",tv);/**
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 nv=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],rn=Ke("plus",nv);/**
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 sv=[["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"}]],vp=Ke("radio",sv);/**
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 iv=[["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"}]],Ln=Ke("refresh-cw",iv);/**
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 av=[["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"}]],Jd=Ke("rocket",av);/**
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 rv=[["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"}]],ov=Ke("rotate-ccw",rv);/**
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 lv=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]],cv=Ke("rotate-cw",lv);/**
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 dv=[["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"}]],yp=Ke("save",dv);/**
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 uv=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Ni=Ke("search",uv);/**
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 mv=[["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"}]],zi=Ke("send",mv);/**
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 hv=[["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"}]],kr=Ke("server",hv);/**
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 pv=[["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"}]],pr=Ke("settings",pv);/**
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 fv=[["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"}]],gv=Ke("shield-alert",fv);/**
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 bv=[["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"}]],xv=Ke("shield",bv);/**
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 vv=[["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"}]],yv=Ke("skull",vv);/**
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 jv=[["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"}]],cs=Ke("sparkles",jv);/**
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 kv=[["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"}]],jp=Ke("square-check-big",kv);/**
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 wv=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],Cs=Ke("square",wv);/**
553
+ * @license lucide-react v1.7.0 - ISC
554
+ *
555
+ * This source code is licensed under the ISC license.
556
+ * See the LICENSE file in the root directory of this source tree.
557
+ */const Nv=[["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"}]],ws=Ke("target",Nv);/**
558
+ * @license lucide-react v1.7.0 - ISC
559
+ *
560
+ * This source code is licensed under the ISC license.
561
+ * See the LICENSE file in the root directory of this source tree.
562
+ */const Sv=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],gi=Ke("terminal",Sv);/**
563
+ * @license lucide-react v1.7.0 - ISC
564
+ *
565
+ * This source code is licensed under the ISC license.
566
+ * See the LICENSE file in the root directory of this source tree.
567
+ */const Cv=[["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"}]],Po=Ke("text-wrap",Cv);/**
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 Ev=[["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"}]],an=Ke("trash-2",Ev);/**
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 _v=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],Mv=Ke("trending-up",_v);/**
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 Av=[["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"}]],pd=Ke("triangle-alert",Av);/**
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 Rv=[["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"}]],Yd=Ke("unlink",Rv);/**
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 Tv=[["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"}]],sa=Ke("user",Tv);/**
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 Pv=[["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"}]],kp=Ke("webhook",Pv);/**
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 Iv=[["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"}]],$c=Ke("workflow",Iv);/**
603
+ * @license lucide-react v1.7.0 - ISC
604
+ *
605
+ * This source code is licensed under the ISC license.
606
+ * See the LICENSE file in the root directory of this source tree.
607
+ */const $v=[["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"}]],Qd=Ke("wrench",$v);/**
608
+ * @license lucide-react v1.7.0 - ISC
609
+ *
610
+ * This source code is licensed under the ISC license.
611
+ * See the LICENSE file in the root directory of this source tree.
612
+ */const Dv=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Ht=Ke("x",Dv);/**
613
+ * @license lucide-react v1.7.0 - ISC
614
+ *
615
+ * This source code is licensed under the ISC license.
616
+ * See the LICENSE file in the root directory of this source tree.
617
+ */const Lv=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],Qn=Ke("zap",Lv),Dc="fusion:version-reload",Lc="fusion:version-update";function zv(){try{if(sessionStorage.getItem(Lc))return sessionStorage.removeItem(Lc),!0}catch{}return!1}function fd(e){if(sessionStorage.getItem(Dc)){console.warn("[versionCheck] reload already attempted, suppressing",e);return}sessionStorage.setItem(Dc,"1"),console.info("[versionCheck] reloading:",e),window.location.reload()}function Fv(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 Ov(e){return Fv(e)?(fd(`chunk load error: ${e?.message??e}`),!0):!1}async function Uv(){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 jl=!1;async function kl(){if(!(jl||document.visibilityState!=="visible")){jl=!0;try{const e=await Uv();if(e&&e!=="monistpj-af26ccb5"){try{sessionStorage.setItem(Lc,"1")}catch{}fd(`build version changed: monistpj-af26ccb5 -> ${e}`)}}finally{jl=!1}}}function Bv(){window.setTimeout(()=>sessionStorage.removeItem(Dc),5e3),document.addEventListener("visibilitychange",()=>{kl()}),window.addEventListener("focus",()=>{kl()}),window.setTimeout(()=>void kl(),2e3)}class tl 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),!Ov(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(pd,{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 rs({children:e,onError:n}){return t.jsx(tl,{level:"page",onError:n,children:e})}function $i({children:e,onError:n}){return t.jsx(tl,{level:"modal",onError:n,children:e})}function Hv({children:e,onError:n}){return t.jsx(tl,{level:"root",onError:n,children:e})}const qv="modulepreload",Vv=function(e){return"/"+e},Xd={},ln=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=Vv(d),d in Xd)return;Xd[d]=!0;const m=d.endsWith(".css"),h=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${h}`))return;const f=document.createElement("link");if(f.rel=m?"stylesheet":qv,m||(f.as="script"),f.crossOrigin="",f.href=d,u&&f.setAttribute("nonce",u),document.head.appendChild(f),m)return new Promise((p,g)=>{f.addEventListener("load",p),f.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${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)})},gd="fn.authToken",Zd="token",Wv="fn_token";let pa,eu=!1,Io=!1;const zc="fn:auth-token-recovery-required";function Kv(){try{const e=window.localStorage.getItem(gd);return e&&e.length>0?e:void 0}catch{return}}function wp(e){try{window.localStorage.setItem(gd,e)}catch{}}function Gv(){if(!(eu||typeof window>"u")){eu=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(Zd);if(!n)return;wp(n),e.searchParams.delete(Zd);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function xa(){if(pa!==void 0)return pa;const e=Gv();if(e)return pa=e,e;const n=Kv();if(n)return pa=n,n}function Jv(e){pa=e,Io=!1,wp(e)}function Yv(){pa=void 0,Io=!1;try{window.localStorage.removeItem(gd)}catch{}}function tu(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function Qv(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function Xv(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!Qv(e.protocol))return!1;const s=e.hostname===n.hostname,i=e.port===n.port,r=tu(e.protocol)===tu(n.protocol);return s&&i&&r}function Zv(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 oi(e){const n=xa();if(!n||typeof window>"u")return e;const s=Zv(e);return!s||!Xv(s.parsed)?e:(s.parsed.searchParams.set(Wv,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function xi(e){const n=xa();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function ey(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function ty(){typeof window>"u"||Io||(Io=!0,window.dispatchEvent(new CustomEvent(zc)))}async function ny(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();ey(i)&&ty()}catch{}}function sy(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,xa();const e=window.fetch.bind(window);window.fetch=function(s,i){const r=xa(),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=>(ny(u),u))}}class iy extends Error{status;details;constructor(n,s,i){super(n),this.name="ApiRequestError",this.status=s,this.details=i}}function ay(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function ds(e){return`/api${e}`}async function P(e,n={}){const s=ds(e),i=xa(),r=(()=>{if(i){const f=new Headers(n.headers??{});return f.has("Content-Type")||f.set("Content-Type","application/json"),xi(f)}if(!n.headers)return{"Content-Type":"application/json"};const h=new Headers(n.headers);return h.has("Content-Type")||h.set("Content-Type","application/json"),Object.fromEntries(h.entries())})(),o=await fetch(s,{...n,headers:r});if(o.status===204){if(!o.ok)throw new Error(`Request failed for ${s}: ${o.status} ${o.statusText}`);return}const l=o.headers.get("content-type")??"",c=await o.text(),u=l.includes("application/json");if(l.includes("text/html")||ay(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 iy(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return m}function y$(){return P("/health")}function j$(){return P("/updates/check")}function ry(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 P(`/tasks${l}`)}async function wr(e,n){const i=ds(V(`/tasks/${e}`,n));for(let r=1;r<=2;r++){const o=await fetch(i,{headers:xi({"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 Np(e,n){const{title:s,description:i,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:u,modelPresetId:d,modelProvider:m,modelId:h,validatorModelProvider:f,validatorModelId:p,planningModelProvider:g,planningModelId:b,thinkingLevel:v,summarize:x,reviewLevel:y,executionMode:w,priority:E,source:C}=e;return P(V("/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:f,validatorModelId:p,planningModelProvider:g,planningModelId:b,thinkingLevel:v,summarize:x,reviewLevel:y,executionMode:w,priority:E,source:C})})}function ii(e,n,s){return P(V(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function oy(e,n,s,i,r,o,l,c,u){return P(V("/tasks/batch-update-models",u),{method:"POST",body:JSON.stringify({taskIds:e,modelProvider:n,modelId:s,validatorModelProvider:i,validatorModelId:r,planningModelProvider:o,planningModelId:l,nodeId:c})})}function ly(e,n,s){return P(V(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n})})}function cy(e,n,s){const i=new URLSearchParams,r=i.size>0?`?${i.toString()}`:"";return P(V(`/tasks/${e}${r}`,n),{method:"DELETE"})}function dy(e,n){return P(V(`/tasks/${e}/merge`,n),{method:"POST"})}function uy(e,n){return P(V(`/tasks/${e}/retry`,n),{method:"POST"})}function my(e,n){return P(V(`/tasks/${e}/reset`,n),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({confirm:!0})})}function hy(e,n){return P(V(`/tasks/${e}/duplicate`,n),{method:"POST"})}function Sp(e,n){return P(V(`/tasks/${e}/pause`,n),{method:"POST"})}function py(e,n){return P(V(`/tasks/${e}/unpause`,n),{method:"POST"})}function fy(e,n){return P(V(`/tasks/${e}/archive`,n),{method:"POST"})}function gy(e,n){return P(V(`/tasks/${e}/unarchive`,n),{method:"POST"})}function by(e){return P(V("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function xy(e,n){return P(V(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function vy(e,n){return P(V(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function yy(e){return P(V("/config",e))}function nl(e){return P(V("/settings",e))}function Zr(e,n){return P(V("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function jy(e){return P(V("/update-check",e))}function k$(e){return P(V("/remote/settings",e))}function w$(e,n){return P(V("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function N$(e){return P(V("/remote/status",e))}function S$(e){return P(V("/remote/install-cloudflared",e),{method:"POST"})}function C$(e){return P(V("/remote/tunnel/start",e),{method:"POST"})}function E$(e){return P(V("/remote/tunnel/stop",e),{method:"POST"})}function _$(e){return P(V("/remote/tunnel/kill-external",e),{method:"POST"})}function M$(e){return P(V("/remote/token/persistent/regenerate",e),{method:"POST"})}function A$(e,n){return P(V("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function Cp(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 R$(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:i}=e,r=Cp(null,s,i);return P(V(`/remote/url${r}`,n))}function T$(e="text",n={}){const{projectId:s,tokenType:i="persistent",ttlMs:r}=n,o=Cp(e,i,r);return P(V(`/remote/qr${o}`,s))}function P$(e){return P(V("/memory",e))}function I$(e,n){return P(V("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function $$(e){return P(V("/memory/files",e))}function D$(e,n){const s=`path=${encodeURIComponent(e)}`;return P(V(`/memory/file?${s}`,n))}function L$(e,n,s){return P(V("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function z$(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 P(V("/memory/compact",i),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function F$(e){return P(V("/memory/dream",e),{method:"POST"})}function O$(e){return P(V("/memory/insights",e))}function U$(e,n){return P(V("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function B$(e){return P(V("/memory/extract",e),{method:"POST"})}function H$(e){return P(V("/memory/audit",e))}function q$(e){return P(V("/memory/stats",e))}function V$(e){return P(V("/memory/backend",e))}function W$(e){return P(V("/memory/install-qmd",e),{method:"POST"})}function K$(e,n){return P(V("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function Ji(){return P("/settings/global")}function pn(e){return P("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function G$(e){return P(V("/settings/scopes",e))}function J$(e){return P(V("/settings/pi-extensions",e))}function Y$(e,n){return P(V("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function Q$(e,n,s){return P(V("/settings/test-notification",s),{method:"POST",body:JSON.stringify({providerId:e,...n??{}})})}function X$(){return P("/pi-settings")}async function Z$(e){return P("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function eD(e){return P("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function tD(e){return P(V("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function Nr(e,n,s){const i=new FormData;i.append("file",n);const r=await fetch(ds(V(`/tasks/${e}/attachments`,s)),{method:"POST",headers:xi(),body:i}),o=await r.json();if(!r.ok)throw new Error(o.error||"Upload failed");return o}async function ky(e,n,s){return P(V(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function nu(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=V(`/tasks/${e}/logs${r}`,n),l=await fetch(ds(o),{headers:xi()});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 wy(e,n,s,i){return P(V(`/tasks/${e}/comments/${n}`,i),{method:"PATCH",body:JSON.stringify({text:s})})}function Ny(e,n,s){return P(V(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function Sy(e,n){return P(V(`/tasks/${e}/documents`,n))}function Cy(e,n,s){return P(V(`/tasks/${e}/documents/${n}/revisions`,s))}async function nD(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 P(V(r,n))}function sD(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const i=s.toString(),r=`/files/markdown-list${i?`?${i}`:""}`;return P(V(r,e))}function su(e,n,s,i,r){return P(V(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:i?.author,metadata:i?.metadata})})}function Ey(e,n,s){return P(V(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function _y(e,n,s){return P(V(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function My(e,n,s){return P(V(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Ay(e,n){return P(V(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function Ry(e,n,s){return P(V(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function bs(){return P("/models")}function Ty(){return P("/usage")}function Py(){return P("/providers/claude-cli/status")}function Iy(){return P("/system/fn-binary/status")}function $y(){return P("/system/fn-binary/install",{method:"POST"})}function Dy(){return P("/providers/droid-cli/status")}async function iD(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return P(`/providers/hermes/status${n}`)}async function aD(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return(await P(`/providers/hermes/profiles${n}`)).profiles??[]}async function rD(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return P(`/providers/openclaw/status${n}`)}async function oD(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),P(`/providers/paperclip/status?${n.toString()}`)}async function lD(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),(await P(`/providers/paperclip/companies?${n.toString()}`)).companies??[]}async function cD(e){const n=new URLSearchParams({apiUrl:e.apiUrl,companyId:e.companyId});return e.apiKey&&n.set("apiKey",e.apiKey),(await P(`/providers/paperclip/agents?${n.toString()}`)).agents??[]}async function dD(e){return P("/providers/paperclip/cli-mint-key",{method:"POST",body:JSON.stringify(e)})}async function uD(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return P(`/providers/paperclip/cli-status${s?`?${s}`:""}`)}async function mD(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return(await P(`/providers/paperclip/cli-companies${s?`?${s}`:""}`)).companies??[]}async function hD(e){const n=new URLSearchParams({companyId:e.companyId});return e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath),(await P(`/providers/paperclip/cli-agents?${n.toString()}`)).agents??[]}async function pD(e={}){const n=new URLSearchParams;e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return P(`/providers/paperclip/cli-discovery${s?`?${s}`:""}`)}function Ly(e){return P("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function zy(e){return P("/auth/droid-cli",{method:"POST",body:JSON.stringify({enabled:e})})}async function Fy(){const n=(await P("/custom-providers")).map(s=>({id:s.id,name:s.name,baseUrl:s.baseUrl,api:s.apiType==="anthropic-compatible"?"anthropic-messages":"openai-completions",apiKey:s.apiKey,models:(s.models??[]).map(i=>({id:i.id,name:i.name}))}));return Object.assign(n,{providers:n})}function Oy(e){return P("/custom-providers",{method:"POST",body:JSON.stringify(e)})}function fD(e,n){const s=n,i={...typeof s.name=="string"?{name:s.name}:{},...typeof s.baseUrl=="string"?{baseUrl:s.baseUrl}:{},...typeof s.apiKey=="string"?{apiKey:s.apiKey}:{},...Array.isArray(s.models)?{models:s.models.map(r=>({id:r.id,name:r.name??r.id}))}:{},...s.api?{apiType:s.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible"}:{},..."apiType"in n?{apiType:n.apiType}:{}};return P(`/custom-providers/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(i)})}function gD(e){return P(`/custom-providers/${encodeURIComponent(e)}`,{method:"DELETE"})}function Uy(e){const n=e.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible";return Oy({name:e.name?.trim()||e.id,apiType:n,baseUrl:e.baseUrl,apiKey:e.apiKey,models:e.models?.map(s=>({id:s.id,name:s.name??s.id}))})}function Sr(){return P("/auth/status")}function By(e){return P("/auth/login",{method:"POST",body:JSON.stringify({provider:e,origin:window.location.origin})})}function Hy(e){return P("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function qy(e){return P("/auth/cancel",{method:"POST",body:JSON.stringify({provider:e})})}function Vy(e,n){return P("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function Wy(e){return P("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function Ky(e,n,s,i){return P("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:i})})}function Gy(e,n,s,i){return P(V("/github/issues/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function Jy(e,n,s){return P("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function Yy(e,n,s,i){return P(V("/github/pulls/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function Qy(e){return P(V("/git/remotes",e))}function Xy(e){return P(V("/git/remotes/detailed",e))}function Zy(e,n,s){return P(V("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function ej(e,n){return P(V(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function tj(e,n,s){return P(V(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function nj(e,n,s){return P(V(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function sj(e,n,s){return P(V(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function ij(e,n){return P(V(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}async function aj(e,n){return(await P(V("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:e})})).results}function eo(e,n,s,i){return P(V("/terminal/sessions",i),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function iu(e,n){return P(V(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function rj(e){return P(V("/terminal/sessions",e))}function Us(e){return P(V("/git/status",e))}function oj(e,n){const s=e?`?limit=${e}`:"";return P(V(`/git/commits${s}`,n))}function $o(e,n){return P(V(`/git/commits/${e}/diff`,n))}function lj(e){return P(V("/git/commits/ahead",e))}function cj(e,n,s,i){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return P(V(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,i))}function Ba(e){return P(V("/git/branches",e))}function dj(e,n,s){const i=`?limit=${n}`;return P(V(`/git/branches/${encodeURIComponent(e)}/commits${i}`,s))}function uj(e){return P(V("/git/worktrees",e))}function mj(e,n,s){return P(V("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function hj(e,n){return P(V(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function au(e,n,s){const i=n?"?force=true":"";return P(V(`/git/branches/${encodeURIComponent(e)}${i}`,s),{method:"DELETE"})}function pj(e,n){return P(V("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function fj(e){return P(V("/git/pull",e),{method:"POST"})}function gj(e){return P(V("/git/push",e),{method:"POST"})}function to(e){return P(V("/git/stashes",e))}function bj(e,n){return P(V("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function xj(e,n,s){return P(V(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function vj(e,n){return P(V(`/git/stashes/${e}`,n),{method:"DELETE"})}function yj(e,n,s){const i=new URLSearchParams;return i.set("path",e),i.set("staged",String(n)),P(V(`/git/diff/file?${i.toString()}`,s))}function ia(e){return P(V("/git/changes",e))}function ru(e,n){return P(V("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function jj(e,n){return P(V("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function ou(e,n){return P(V("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function kj(e,n){return P(V("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function wj(e){return P(V("/workspaces",e))}function Nj(e,n,s){const i=new URLSearchParams({workspace:e});return n&&i.set("path",n),s&&i.set("projectId",s),P(`/files?${i.toString()}`)}function Sj(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),P(`/files/${encodeURIComponent(n)}?${i.toString()}`)}function Cj(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),P(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function Ej(e,n,s){const i=new URLSearchParams({q:e});return n&&i.set("workspace",n),s&&i.set("projectId",s),P(`/files/search?${i.toString()}`)}function _j(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),P(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function Mj(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),P(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function Aj(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),P(`/files/${encodeURIComponent(n)}/delete?${i.toString()}`,{method:"POST"})}function Rj(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),P(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function Ep(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${i.toString()}`}function Tj(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${i.toString()}`}function Pj(e,n,s){return P(V("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function Ij(e,n,s,i){return P(V("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function $j(e,n,s){return P(V(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Dj(e,n,s){return P(V(`/planning/${encodeURIComponent(e)}/stop`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function _p(e,n,s){return P(V("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function bD(e,n,s,i){return P(V("/agents/onboarding/start-streaming",s),{method:"POST",body:JSON.stringify({intent:e,context:n,planningModelProvider:i?.planningModelProvider,planningModelId:i?.planningModelId})})}function xD(e,n,s){return P(V("/agents/onboarding/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n})})}function vD(e,n){return P(V("/agents/onboarding/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function Lj(e,n,s){return P(V("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function zj(e,n,s){return P(V("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Fj(e,n,s){return P(V("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const Fc=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(Fc))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function Oj(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function Aa(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 g=p.lastEventId;if(!g)return!0;const b=Number.parseInt(g,10);return Number.isFinite(b)?u!==null&&b<=u?!1:(u=b,!0):!0},h=()=>{if(o)return;const p=Oj(e,u),g=new EventSource(oi(p));r=g,g.onopen=()=>{l=0,d=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},g.onmessage=b=>{const v=b;m(v)&&n.onMessage?.(v)};for(const[b,v]of Object.entries(n.events??{}))g.addEventListener(b,x=>{const y=x;m(y)&&v(y)});g.onerror=()=>{if(o||r!==g)return;if(g.readyState===EventSource.CONNECTING){d||(d=!0,s.onConnectionStateChange?.("reconnecting"));return}if(g.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 f={close:()=>{o=!0,c&&(clearTimeout(c),c=null),r?.close(),Fc.delete(f)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return Fc.add(f),f}function lu(e){const n=typeof e.source=="string"&&e.source.trim().length>0?e.source.trim():"root",s=n==="root"?".":n,i=e.name,r=typeof e.packagePath=="string"&&e.packagePath.trim().length>0?e.packagePath.trim():s,o=typeof e.confidence=="number"?e.confidence:1,l=n==="root"?"root":n,c=typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():"project";return{name:e.name,command:e.command,scriptName:i,packagePath:r,confidence:o,cwd:s,source:n,workspaceName:typeof e.packageName=="string"?e.packageName:void 0,label:`${c} · ${i} (${l})`}}function va(e){const n=e.status,s=n==="starting"||n==="running"||n==="failed"||n==="stopped"?n:"stopped",i=typeof e.previewUrl=="string"?e.previewUrl:e.detectedUrl,r=typeof e.manualPreviewUrl=="string"?e.manualPreviewUrl:e.manualUrl;return{id:typeof e.id=="string"?e.id:"",name:typeof e.name=="string"&&e.name.length>0?e.name:"default",status:s,command:typeof e.command=="string"?e.command:"",scriptName:typeof e.scriptId=="string"?e.scriptId:"",cwd:typeof e.cwd=="string"?e.cwd:"",pid:e.pid,startedAt:e.startedAt,previewUrl:i,detectedUrl:typeof e.detectedUrl=="string"?e.detectedUrl:i,detectedPort:e.detectedPort,manualPreviewUrl:r,manualUrl:typeof e.manualUrl=="string"?e.manualUrl:r,logs:Array.isArray(e.logHistory)?e.logHistory:[],exitCode:e.exitCode}}function Uj(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 Bj(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((i,r)=>Uj(i,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function Hj(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 cu(e){return Array.isArray(e)?e.map(lu):(e.candidates??[]).map(lu)}async function qj(e){try{const n=await P(V("/dev-server/candidates",e));return cu(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await P(V("/dev-server/detect",e));return cu(s)}throw n}}function bd(e){return P(V("/dev-server/status",e)).then(va)}async function yD(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 P(V(`/dev-server/logs/history${i}`,n));return Bj(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await bd(n);return Hj(o.logs,e)}throw r}}function Vj(e,n){const s=e.cwd??e.packagePath??".",i=e.scriptName;return P(V("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:i,scriptId:i,cwd:s,packagePath:e.packagePath})}).then(va)}function Wj(e){return P(V("/dev-server/stop",e),{method:"POST"}).then(va)}function Kj(e){return P(V("/dev-server/restart",e),{method:"POST"}).then(va)}async function Gj(e,n){const s=typeof e=="string"?{url:e}:e;try{const i=await P(V("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return va(i)}catch(i){if(i instanceof Error&&/\/dev-server\/preview-url/.test(i.message)){const r=await P(V("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return va(r)}throw i}}function jD(e){return ds(V("/dev-server/logs/stream",e))}async function kD(e){try{return(await P(V("/devserver",e))).sessions??[]}catch{try{const n=await bd(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 wD(e,n){try{return await P(V(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await bd(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 ND(e,n){try{return await P(V(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await Vj({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 SD(e,n){try{return await P(V(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await Wj(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 CD(e,n){try{return await P(V(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await Kj(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 ED(e,n,s){try{const i=await P(V(`/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 Gj({url:n},s);return{url:i.previewUrl??i.manualUrl??null,source:"manual"}}}async function _D(e){try{return(await P(V("/devserver/detect",e))).candidates??[]}catch{try{return(await qj(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function MD(e,n){return ds(V(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function Lr(e,n,s=25e3){const i=setInterval(()=>{Rw(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(i)}}}function Jj(e,n){return ds(V(`/planning/${encodeURIComponent(e)}/stream`,n))}function Yj(e,n){return ds(V(`/agents/onboarding/${encodeURIComponent(e)}/stream`,n))}function AD(e,n,s,i){const r=Yj(e,n),o=Aa(r,{events:{thinking:l=>{try{s.onThinking?.(JSON.parse(l.data))}catch{s.onThinking?.(l.data)}},question:l=>{try{s.onQuestion?.(JSON.parse(l.data))}catch{}},summary:l=>{try{s.onSummary?.(JSON.parse(l.data))}catch{}},error:l=>{try{const c=JSON.parse(l.data);s.onError?.(c.message||c)}catch{s.onError?.(l.data||"Stream error")}},complete:()=>{s.onComplete?.()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:l=>s.onError?.(l)});return{close:o.close,isConnected:o.isConnected}}function Qj(e,n,s,i){const r=Jj(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Aa(r,{onOpen:()=>{c(),o=Lr(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 zr(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 Xj(e){return P(zr("/routines",e))}function Zj(e,n){return P(zr("/routines",n),{method:"POST",body:JSON.stringify(e)})}function du(e,n,s){return P(zr(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function ek(e,n){await P(zr(`/routines/${e}`,n),{method:"DELETE"})}function tk(e,n){return P(zr(`/routines/${e}/trigger`,n),{method:"POST"})}function uu(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 P(`/activity${s}`)}function nk(e){const n=V("/activity",e);return P(n,{method:"DELETE"})}function sl(e){return P(V("/workflow-steps",e))}function mu(e,n){return P(V("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function sk(e,n,s){return P(V(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function ik(e,n){return P(V(`/workflow-steps/${e}`,n),{method:"DELETE"})}function hu(e,n){return P(V(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function ak(e,n){return P(V(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function rk(){return P("/workflow-step-templates")}function ok(e,n){return P(V(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function Cr(e){return P(V("/scripts",e))}function lk(e,n,s){return P(V("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function ck(e,n){return P(V(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function Mp(e,n,s){return(await P(V("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const no={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 Ap(e){if(!(e instanceof Error))return no.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?no.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?no.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:no.NETWORK}function dk(e,n){return P(V("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function uk(e,n,s){return P(V(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function mk(e,n){return ds(V(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function hk(e,n,s,i){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=Aa(mk(e,n),{onOpen:()=>{l(),r=Lr(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 pk(e,n,s,i){return P(V("/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 Rp(e,n,s){return P(V("/subtasks/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function V(e,n){if(!n)return e;const s=e.includes("?")?"&":"?";return`${e}${s}projectId=${encodeURIComponent(n)}`}function fk(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 il(e,n){const{nodeId:s,localNodeId:i,...r}=n??{},o=fk(e,s,i);return P(o,r)}function Ra(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 P(`/agents${i}`)}function Oc(e,n){return P(V(`/agents/${encodeURIComponent(e)}`,n))}function gk(e,n){return P(V("/agents",n),{method:"POST",body:JSON.stringify(e)})}function bk(e,n,s){return P(V(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function RD(e,n){return P(V(`/agents/${encodeURIComponent(e)}/upgrade-heartbeat-procedure`,n),{method:"POST"})}function TD(e,n,s){return P(V(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function PD(e,n,s){return P(V(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function ID(e,n,s){return P(V(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function $D(e,n){return P(V(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function DD(e,n,s){const i=`path=${encodeURIComponent(n)}`;return P(V(`/agents/${encodeURIComponent(e)}/memory/file?${i}`,s))}function LD(e,n,s,i){return P(V(`/agents/${encodeURIComponent(e)}/memory/file`,i),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function xk(e,n,s){return P(V(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function vk(e,n){return P(V(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function zD(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 P(`/agents/${encodeURIComponent(e)}/runs${r}`)}function FD(e,n,s){return P(V(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function OD(e,n,s){return P(V(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function UD(e,n,s){const i=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return P(V(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:i,triggerDetail:r})})}function BD(e,n){return P(V(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function yk(e){return P(V("/agents/stats",e))}function HD(e,n){return P(V(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function qD(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeEphemeral&&s.set("includeEphemeral","true");const i=s.toString();return P(`/agents/org-tree${i?`?${i}`:""}`)}function VD(e,n){return P(V(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function pu(e,n,s){return P(V(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function WD(e,n){return P(V(`/agents/${encodeURIComponent(e)}/tasks`,n))}function KD(){return P("/agents/companies")}function GD(e,n){return P(V("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function JD(e,n){return P(V("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function YD(e,n){return P(V(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function QD(e){return P(V("/backups",e))}function XD(e){return P(V("/backups",e),{method:"POST"})}function ZD(e,n){const s=V("/settings/export",n),i=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return P(i)}function eL(e,n,s){return P(V("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}function fu(){return P("/projects/across-nodes")}function fr(e,n){P("/_perf/dashboard-load",{method:"POST",body:JSON.stringify({source:e,message:n})}).catch(()=>{})}function Do(){return P("/nodes")}function jk(e){return P("/nodes",{method:"POST",body:JSON.stringify(e)})}function kk(e,n){return P(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function wk(e){return P(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Nk(e){const n=await P(`/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 tL(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=xa();l&&o.set("fn_token",l);const c=o.toString(),u=`/browse-directory${c?`?${c}`:""}`;return P(u)}function Sk(e){return P("/projects",{method:"POST",body:JSON.stringify(e)})}function Tp(e){return P(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function gu(e){return P(`/projects/${encodeURIComponent(e)}/health`)}function Ck(e){return P(V("/executor/stats",e))}function Ek(e){return P(V("/system-stats",e))}function _k(e){return P(V("/kill-vitest",e),{method:"POST"})}function bu(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 P(`/activity-feed${s}`)}function Mk(e){return P(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function Ak(e){return P(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function nL(){return P("/global-concurrency")}function sL(e){return P("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function Rk(e,n){return P(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function Pp(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 P(`/tasks/${encodeURIComponent(e)}/diff${r}`)}function Tk(e){return P(V("/missions",e))}function Pk(e,n){return P(V("/missions",n),{method:"POST",body:JSON.stringify(e)})}function Ip(e,n){return P(V(`/missions/${encodeURIComponent(e)}`,n))}function Ik(e,n,s){return P(V(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function $k(e,n){return P(V(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Dk(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 P(V(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function Lk(e){return P(V("/missions/health",e))}function zk(e,n,s){return P(V(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function Fk(e,n,s){return P(V(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Ok(e,n){return P(V(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Uk(e,n,s){return P(V(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function Bk(e,n,s){return P(V(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Hk(e,n){return P(V(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function qk(e,n){return P(V(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function Vk(e,n,s){return P(V(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function Wk(e,n,s){return P(V(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Kk(e,n){return P(V(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Gk(e,n,s){return P(V(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function Jk(e,n){return P(V(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function Yk(e,n,s,i){return P(V(`/missions/features/${encodeURIComponent(e)}/triage`,i),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s})})}function Qk(e,n){return P(V(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST"})}function wl(e,n){return P(V(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function Xk(e,n,s){return P(V(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function Zk(e,n,s){return P(V(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function ew(e,n,s){return P(V(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function tw(e,n,s){return P(V(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function nw(e,n){return P(V(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function Nl(e,n){return P(V(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function xu(e,n){return P(V(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function sw(e,n){return P(V(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function vu(e,n){return P(V(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function iw(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 P(V(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function aw(e,n){return P(V(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function rw(e,n){return P(V(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function ow(e,n){return P(V(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function lw(e,n){return P(V(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function cw(e,n,s){return P(V(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function dw(e,n,s){return P(V("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function uw(e,n,s,i){return P(V("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function mw(e,n,s){return P(V(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function $p(e,n,s){return P(V("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function hw(e,n,s){return P(V("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function pw(e,n,s,i){const r=ds(V(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Aa(r,{onOpen:()=>{c(),o=Lr(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 Fr(e,n,s){return V(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function Or(e,n,s){return V(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function fw(e,n){return P(Fr(e,"/start",n),{method:"POST"})}function gw(e,n,s,i){return P(Fr(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function bw(e,n,s,i){const r=ds(Fr(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Aa(r,{onOpen:()=>{c(),o=Lr(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 xw(e,n,s){return P(Fr(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function vw(e,n){return P(Fr(e,"/skip",n),{method:"POST"})}function yw(e,n){return P(Or(e,"/start",n),{method:"POST"})}function jw(e,n,s,i){return P(Or(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function kw(e,n,s,i){const r=ds(Or(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Aa(r,{onOpen:()=>{c(),o=Lr(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 ww(e,n,s){return P(Or(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function Nw(e,n){return P(Or(e,"/skip",n),{method:"POST"})}async function Sw(e,n){try{return await P(V(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function iL(e){return P(V("/roadmaps",e))}function aL(e,n){return P(V("/roadmaps",n),{method:"POST",body:JSON.stringify(e)})}function rL(e,n){return P(V(`/roadmaps/${encodeURIComponent(e)}`,n))}function oL(e,n,s){return P(V(`/roadmaps/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function lL(e,n){return P(V(`/roadmaps/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function cL(e,n,s){return P(V(`/roadmaps/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function dL(e,n,s){return P(V(`/roadmaps/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function uL(e,n){return P(V(`/roadmaps/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function mL(e,n,s){return P(V(`/roadmaps/milestones/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function hL(e,n,s){return P(V(`/roadmaps/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function pL(e,n){return P(V(`/roadmaps/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function fL(e,n,s){return P(V(`/roadmaps/${encodeURIComponent(e)}/milestones/reorder`,s),{method:"POST",body:JSON.stringify({orderedMilestoneIds:n})})}function gL(e,n,s){return P(V(`/roadmaps/milestones/${encodeURIComponent(e)}/features/reorder`,s),{method:"POST",body:JSON.stringify({orderedFeatureIds:n})})}function bL(e,n,s,i){return P(V(`/roadmaps/features/${encodeURIComponent(e)}/move`,i),{method:"POST",body:JSON.stringify({targetMilestoneId:n,targetIndex:s})})}function xL(e,n){return P(V(`/roadmaps/${encodeURIComponent(e)}/handoff`,n))}function vL(e,n,s,i){return P(V(`/roadmaps/${encodeURIComponent(e)}/suggestions/milestones`,i),{method:"POST",body:JSON.stringify({goalPrompt:n.trim(),...s!==void 0?{count:s}:{}})})}function yL(e,n,s){return P(V(`/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 jL(e){return P(V("/todos",e))}function kL(e,n){const s={title:e};return P(V("/todos",n),{method:"POST",body:JSON.stringify(s)})}function wL(e,n,s){const i={title:n};return P(V(`/todos/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(i)})}function NL(e,n){return P(V(`/todos/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function SL(e,n,s){const i={text:n};return P(V(`/todos/${encodeURIComponent(e)}/items`,s),{method:"POST",body:JSON.stringify(i)})}function CL(e,n,s){const i=n;return P(V(`/todos/items/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(i)})}function EL(e,n){return P(V(`/todos/items/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function _L(e,n,s){return P(V(`/todos/${encodeURIComponent(e)}/items/reorder`,s),{method:"POST",body:JSON.stringify({itemIds:n})})}function ya(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function xd(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeCompleted&&s.set("includeCompleted","1"),n?.includeArchived&&s.set("includeArchived","1");const i=s.toString(),r=await fetch(ds(`/ai-sessions${i?`?${i}`:""}`),{headers:xi()});return r.ok?(await r.json()).sessions??[]:[]}async function Cw(e){return P(`/ai-sessions/${encodeURIComponent(e)}/archive`,{method:"POST"})}async function Ew(e){return P(`/ai-sessions/${encodeURIComponent(e)}/unarchive`,{method:"POST"})}async function ai(e){const n=await fetch(ds(`/ai-sessions/${encodeURIComponent(e)}`),{headers:xi()});return n.ok?n.json():null}async function _w(e,n){const s=await P(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function Mw(e,n){return P(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function Aw(e,n){return P(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function Dp(e){await fetch(ds(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:xi()})}function Rw(e,n){return P(V(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function Tw(e,n){const s=new URLSearchParams;s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),e?.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 P(`/messages/inbox${i}`)}function Pw(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 P(`/messages/outbox${i}`)}function Lp(e){return P(V("/messages/unread-count",e))}function Iw(e,n){return P(V("/messages",n),{method:"POST",body:JSON.stringify(e)})}function $w(e,n){return P(V(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function Dw(e){return P(V("/messages/read-all",e),{method:"POST"})}function Lw(e,n){return P(V(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function zw(e,n,s){const i=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return P(V(i,s))}function Fw(e,n){return P(V(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function ML(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 P(`/agents/${encodeURIComponent(e)}/reflections${r}`)}function AL(e,n){return P(V(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function RL(e,n,s){const i=new URLSearchParams;s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return P(`/agents/${encodeURIComponent(e)}/performance${r}`)}function TL(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 P(`/agents/${encodeURIComponent(e)}/ratings${r}`)}function PL(e,n,s){return P(V(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function IL(e,n){return P(V(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function $L(e,n,s){return P(V(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function DL(e,n){return P(V(`/agents/${encodeURIComponent(e)}/budget`,n))}function LL(e,n){return P(V(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function zL(e){return P(V("/plugins",e))}async function FL(e,n){return P(V("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function OL(e,n){return P(V(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function UL(e,n){return P(V(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function BL(e,n){return P(V(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function HL(e,n){return P(V(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function qL(e,n,s){return P(V(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function VL(e,n){return P(V(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function Ow(e){return P(V("/plugins/ui-slots",e))}async function WL(e){return P(V("/plugins/runtimes",e))}async function KL(e){return(await P(V("/skills/discovered",e))).skills}async function GL(e,n,s){return P(V("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function JL(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 P(V(`/skills/catalog${r}`,s))}async function YL(e,n){return(await P(V(`/skills/${encodeURIComponent(e)}/content`,n))).content}function yu(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const i=s.toString();return P(`/chat/sessions${i?`?${i}`:""}`)}async function Uw(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 P(`/chat/sessions?${o.toString()}`)).sessions[0]??null}}function Bw(e,n){return P(V("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function QL(e,n,s){return P(V(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function XL(e,n){return P(V(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function ju(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 P(V(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function Hw(e,n){return P(V(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function qw(e,n,s,i,r,o){const l=ds(V(`/chat/sessions/${encodeURIComponent(e)}/messages`,r)),c=new AbortController;let u=!1;const d=(m,h)=>{if(!(!m||!h))switch(m){case"thinking":try{s.onThinking?.(JSON.parse(h))}catch{s.onThinking?.(h)}break;case"text":try{s.onText?.(JSON.parse(h))}catch{s.onText?.(h)}break;case"tool_start":try{s.onToolStart?.(JSON.parse(h))}catch{}break;case"tool_end":try{s.onToolEnd?.(JSON.parse(h))}catch{}break;case"done":try{s.onDone?.(JSON.parse(h))}catch{s.onDone?.({messageId:""})}break;case"error":try{const f=JSON.parse(h);s.onError?.(f.message||f)}catch{s.onError?.(h||"Stream error")}break}};return(async()=>{try{const m=Array.isArray(i)&&i.length>0,h=m?(()=>{const w=new FormData;return w.append("content",n),i.forEach(E=>w.append("attachments",E)),w})():JSON.stringify({content:n}),f=await fetch(l,{method:"POST",headers:m?xi():xi({"Content-Type":"application/json"}),body:h,signal:c.signal});if(!f.ok){const w=await f.text();let E=`Request failed: ${f.status}`;try{E=JSON.parse(w).error||E}catch{}s.onError?.(E);return}if(!f.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected");const p=f.body.getReader(),g=new TextDecoder;let b="",v="",x=[];const y=(w,E=!1)=>{b+=w;const C=b.split(`
618
+ `);b=C.pop()||"",E&&b.length>0&&(C.push(b),b="");for(const j of C){const A=j.endsWith("\r")?j.slice(0,-1):j;if(A.startsWith("event:"))v=A.slice(6).trim();else if(A.startsWith("data:")){const S=A.slice(5);x.push(S.startsWith(" ")?S.slice(1):S)}else if(A===""){const S=x.join(`
619
+ `);d(v,S),v="",x=[]}}if(E&&v&&x.length>0){const j=x.join(`
620
+ `);d(v,j),v="",x=[]}};for(;;){const{done:w,value:E}=await p.read();if(w){y(g.decode(),!0);break}y(g.decode(E,{stream:!0}))}}catch(m){if(m instanceof DOMException&&m.name==="AbortError"){u||s.onError?.("Connection aborted");return}if(u)return;s.onError?.(m instanceof Error?m.message:"Connection error")}})(),{close:()=>{u=!0,c.abort()},isConnected:()=>!u}}function ZL(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 P(V(`/insights${i}`,n))}function e3(e,n){return P(V(`/insights/${encodeURIComponent(e)}/dismiss`,n),{method:"POST"})}function t3(e="manual",n,s){return P(V("/insights/run",s),{method:"POST",body:JSON.stringify({trigger:e,inputMetadata:n})})}function n3(e){return P(V("/insights/runs",e))}function s3(e,n){return P(V(`/insights/${encodeURIComponent(e)}/create-task`,n),{method:"POST"})}function i3(e={},n){const s=new URLSearchParams;e.q&&s.set("q",e.q),e.status&&s.set("status",e.status),e.limit!==void 0&&s.set("limit",String(e.limit));const i=s.size>0?`?${s.toString()}`:"";return P(V(`/research/runs${i}`,n))}function a3(e,n){return P(V("/research/runs",n),{method:"POST",body:JSON.stringify(e)})}function r3(e,n){return P(V(`/research/runs/${encodeURIComponent(e)}`,n))}function o3(e,n){return P(V(`/research/runs/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function l3(e,n){return P(V(`/research/runs/${encodeURIComponent(e)}/retry`,n),{method:"POST"})}function c3(e,n,s){return P(V(`/research/runs/${encodeURIComponent(e)}/export?format=${encodeURIComponent(n)}`,s))}function d3(e,n,s){return P(V(`/research/runs/${encodeURIComponent(e)}/create-task`,s),{method:"POST",body:JSON.stringify(n)})}function u3(e,n,s){return P(V(`/research/runs/${encodeURIComponent(e)}/attach-task`,s),{method:"POST",body:JSON.stringify(n)})}function Vw(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 Ww({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}=Vw(e.status),r=e.status==="connecting";return t.jsxs("div",{className:"node-status-indicator node-status-indicator--remote",children:[t.jsx("span",{className:`node-status-indicator__dot ${i}`,children:r&&t.jsx("span",{className:"node-status-indicator__spinner"})}),t.jsx("span",{className:"node-status-indicator__name",children:e.name}),n&&t.jsxs("span",{className:"node-status-indicator__details",children:[e.type," · ",s]})]})}function Kw(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Vi({status:e,showLabel:n=!1,className:s,compact:i=!1}){const r=Kw(e);return t.jsxs("span",{className:`node-health-dot${i?" node-health-dot--compact":""}${s?` ${s}`:""}`,title:r,"aria-label":`Node status: ${r}`,children:[t.jsx("span",{className:`status-dot status-dot--${e}`}),n?t.jsx("span",{className:"node-health-dot__label",children:r}):null]})}const ku=new Map,Gw=6e4;function zp(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 f(){const p=ku.get(m);if(p&&Date.now()<p.expiresAt){if(h||u.current)return;s(p.slots),r(!1);return}!c.current&&r(!0),l(null);try{const b=await Ow(e);if(h||u.current)return;ku.set(m,{slots:b,expiresAt:Date.now()+Gw}),s(b),c.current=!0}catch(b){if(h||u.current)return;l(b instanceof Error?b.message:"Failed to fetch UI slots"),c.current=!0}finally{!h&&!u.current&&r(!1)}}return f(),()=>{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 al({slotId:e,projectId:n}){const{getSlotsForId:s,loading:i,error:r}=zp(n);if(i||r||!e)return null;const o=s(e);return o.length===0?null:t.jsx(tl,{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 Jw(){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 Ta(){const[e,n]=a.useState(Jw);return a.useEffect(()=>{if(typeof window>"u")return;const s=window.matchMedia("(max-width: 768px)"),i=window.matchMedia("(min-width: 769px) and (max-width: 1024px)"),r=()=>{s.matches?n("mobile"):i.matches?n("tablet"):n("desktop")};return s.addEventListener("change",r),i.addEventListener("change",r),()=>{s.removeEventListener("change",r),i.removeEventListener("change",r)}},[]),e}function Pa(e){return e.replace(/\\/g,"/")}function vd(e){return e.replace(/[\\/]+$/g,"")}function yd(e){const n=Pa(vd(e));return n?n.split("/").filter(Boolean):[]}function jd(e){const n=Pa(vd(e));if(!n)return e;const s=n.split("/").filter(Boolean);return s[s.length-1]||n}function Fp(e,n){const s=yd(e);return s.length===0?Pa(e):s.slice(-2).join("/")}function Yw(e){const n=Pa(vd(e)),s=n.lastIndexOf("/");return s<0?"":n.slice(0,s+1)}function Qw(e,n){return!e||e==="."?n:[...yd(e),n].join("/")}function Xw(e){const n=yd(e);return n.length===0?".":(n.pop(),n.length===0?".":n.join("/"))}function m3(e){const n=Pa(e),s=n.match(/^([A-Za-z]:)(?:\/(.*))?$/);if(s){const r=`${s[1]}/`,o=(s[2]??"").split("/").filter(Boolean),l=[{label:s[1],path:r}];for(let c=0;c<o.length;c+=1)l.push({label:o[c],path:`${r}${o.slice(0,c+1).join("/")}`});return l}if(n.startsWith("/")){const r=n.split("/").filter(Boolean),o=[{label:"/",path:"/"}];for(let l=0;l<r.length;l+=1)o.push({label:r[l],path:`/${r.slice(0,l+1).join("/")}`});return o}const i=n.split("/").filter(Boolean);return i.map((r,o)=>({label:r,path:i.slice(0,o+1).join("/")}))}const Op={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function Zw({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(Xt,{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=Op[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:Fp(u.path)})]}),d&&t.jsx(Vn,{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 wu({size:e=16}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:t.jsx("path",{d:"M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.203 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.942.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z"})})}function eN({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:f,showNodesButton:p,onOpenWorkflowSteps:g,onOpenScripts:b,onRunScript:v,onToggleTerminal:x,onOpenFiles:y,filesOpen:w,globalPaused:E,enginePaused:C,onToggleGlobalPause:j,onToggleEnginePause:A,view:S="board",onChangeView:z,showSkillsTab:_,showAgentsTab:R,searchQuery:B="",onSearchChange:K,projects:L=[],currentProject:$,onSelectProject:U,onViewAllProjects:G,projectId:Y,isElectron:ee=!1,mobileNavEnabled:N,availableNodes:I=[],currentNode:T,onSelectNode:k,isRemote:H=!1,experimentalFeatures:J}){const ue=Ta(),fe=ue==="mobile",he=fe||ue==="tablet",O=fe&&N,[ne,Q]=a.useState(!1),[ge,de]=a.useState(!1),[me,ie]=a.useState(!1),[Ee,Ue]=a.useState(!1),[Te,at]=a.useState(!1),[et,Ve]=a.useState(!1),[Xe,De]=a.useState(!1),[Be,oe]=a.useState(!1),[Ne,se]=a.useState(!1),[Me,Le]=a.useState(!1),[pe,Ae]=a.useState(!1),[Je,it]=a.useState({}),[ye,ce]=a.useState(!1),[Re,be]=a.useState(-1),[Pe,Ye]=a.useState(null),[$e,ft]=a.useState({}),[Z,re]=a.useState(!1),je=a.useRef(null),rt=a.useRef(null),te=a.useRef(null),Ze=a.useRef(null),pt=a.useRef(null),gt=a.useRef(null),wt=a.useRef(!1),Et=a.useRef(null),mt=a.useRef(null),Nt=a.useRef(null),Tt=a.useRef(null),qt=a.useRef(null),Pt=a.useRef(null),At=a.useRef(null),Bt=a.useRef(null),Ft=a.useRef(!1),Dt=a.useMemo(()=>I.filter(ke=>ke.type==="remote"),[I]),Mt=Dt.length>0,St=a.useMemo(()=>Object.entries(Je).sort(([ke],[ut])=>ke.localeCompare(ut)),[Je]),Wt=St.length>0,It=St.length+(Wt?1:0),Yt=a.useMemo(()=>Object.entries($e).sort(([ke],[ut])=>ke.localeCompare(ut)),[$e]),Rt=a.useMemo(()=>!!(J?.researchView||J?.todoView||J?.insights||J?.roadmap||_||J?.memoryView||J?.devServerView||!O),[J,_,O]),xe=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}},[]),Fe=a.useCallback(()=>{const ke=At.current;if(!ke)return;const ut=ke.getBoundingClientRect(),Lt=Bt.current,{width:En,height:hn,offsetTop:Rn,offsetLeft:is}=xe(),Dn=16,nn=16,cn=6,Hn=Lt?.offsetWidth||Math.max(ut.width,260),fn=Math.min(Hn,Math.max(En-Dn*2,160)),dn=Lt?.offsetHeight||280,_n=Math.min(dn,Math.max(hn-nn*2,160)),zn=ut.top-Rn,es=ut.bottom-Rn,Fn=ut.right-is,Qt=hn-es,yt=zn,on=Qt<_n&&yt>Qt,M=Math.min(Math.max(Fn-fn,Dn),En-Dn-fn)+is,le=on?Math.max(nn+Rn,zn-_n-cn+Rn):Math.min(es+cn+Rn,hn+Rn-nn-_n);Ye({top:le,left:M,width:fn})},[xe]),ct=a.useCallback((ke,ut)=>{v?.(ke,ut),Ae(!1),be(-1)},[v]),D=a.useCallback(()=>{b?.(),Ae(!1),be(-1)},[b]),F=a.useCallback(ke=>{switch(ke.key){case"ArrowDown":ke.preventDefault(),It>0&&be(ut=>ut<It-1?ut+1:0);break;case"ArrowUp":ke.preventDefault(),It>0&&be(ut=>ut>0?ut-1:It-1);break;case"Enter":if(ke.preventDefault(),Re>=0)if(Re<St.length){const[ut,Lt]=St[Re];ct(ut,Lt)}else Wt&&Re===St.length&&D();break;case"Home":ke.preventDefault(),It>0&&be(0);break;case"End":ke.preventDefault(),It>0&&be(It-1);break}},[D,ct,Re,St,Wt,It]);a.useEffect(()=>{wt.current=Te},[Te]),a.useEffect(()=>{Ft.current=pe},[pe]),a.useEffect(()=>{if(!Te||!he)return;let ke=!1;return re(!0),Cr(Y).then(ut=>{ke||ft(ut)}).catch(()=>{ke||ft({})}).finally(()=>{ke||re(!1)}),()=>{ke=!0}},[Te,he,Y]),a.useEffect(()=>{if(!pe||he)return;let ke=!1;return ce(!0),Cr(Y).then(ut=>{ke||it(ut)}).catch(()=>{ke||it({})}).finally(()=>{ke||ce(!1)}),()=>{ke=!0}},[pe,he,Y]),a.useEffect(()=>{if(!pe)return;const ke=ut=>{Pt.current&&!Pt.current.contains(ut.target)&&Ae(!1)};return document.addEventListener("mousedown",ke),()=>document.removeEventListener("mousedown",ke)},[pe]),a.useEffect(()=>{if(!pe)return;const ke=ut=>{ut.key==="Escape"&&(Ae(!1),At.current?.focus())};return document.addEventListener("keydown",ke),()=>document.removeEventListener("keydown",ke)},[pe]),a.useEffect(()=>{if(pe){be(-1);const ke=window.setTimeout(()=>Bt.current?.focus(),0);return()=>window.clearTimeout(ke)}Ye(null)},[pe]),a.useEffect(()=>{if(!pe)return;const ke=requestAnimationFrame(()=>{Fe()});return()=>cancelAnimationFrame(ke)},[pe,ye,St.length,Wt,Fe]),a.useEffect(()=>{if(!pe)return;const ke=()=>Fe();window.addEventListener("resize",ke),window.addEventListener("scroll",ke,!0);const ut=window.visualViewport;return ut&&(ut.addEventListener("resize",ke),ut.addEventListener("scroll",ke)),()=>{window.removeEventListener("resize",ke),window.removeEventListener("scroll",ke,!0),ut&&(ut.removeEventListener("resize",ke),ut.removeEventListener("scroll",ke))}},[pe,Fe]),a.useEffect(()=>{he&&(Ae(!1),be(-1))},[he]);const ve=ne||B.length>0,ze=(ge||B.length>0)&&!me,Oe=(S==="board"||S==="list")&&!fe&&K&&!me&&B.length===0,Ge=(S==="board"||S==="list")&&!fe&&K;a.useEffect(()=>{B===""&&ie(!1)},[B]),a.useEffect(()=>{if(!Ee)return;const ke=ut=>{rt.current&&!rt.current.contains(ut.target)&&je.current&&!je.current.contains(ut.target)&&Ue(!1)};return document.addEventListener("mousedown",ke),()=>document.removeEventListener("mousedown",ke)},[Ee]),a.useEffect(()=>{if(!Ne)return;const ke=ut=>{Ze.current&&!Ze.current.contains(ut.target)&&te.current&&!te.current.contains(ut.target)&&se(!1)};return document.addEventListener("mousedown",ke),()=>document.removeEventListener("mousedown",ke)},[Ne]),a.useEffect(()=>{if(!et)return;const ke=ut=>{Et.current&&!Et.current.contains(ut.target)&&Ve(!1)};return document.addEventListener("mousedown",ke),()=>document.removeEventListener("mousedown",ke)},[et]),a.useEffect(()=>{const ke=ut=>{if(ut.key==="Escape"){if(oe(!1),se(!1),wt.current){at(!1);return}if(Ft.current){Ae(!1),At.current?.focus();return}Ue(!1),Q(!1),Ve(!1),De(!1)}};return document.addEventListener("keydown",ke),()=>document.removeEventListener("keydown",ke)},[]),a.useEffect(()=>{if(!Xe)return;const ke=ut=>{mt.current&&!mt.current.contains(ut.target)&&De(!1)};return document.addEventListener("mousedown",ke),()=>document.removeEventListener("mousedown",ke)},[Xe]),a.useEffect(()=>{if(!Me)return;const ke=ut=>{qt.current&&!qt.current.contains(ut.target)&&Le(!1)};return document.addEventListener("mousedown",ke),()=>document.removeEventListener("mousedown",ke)},[Me]),a.useEffect(()=>{if(!Me)return;const ke=ut=>{ut.key==="Escape"&&Le(!1)};return document.addEventListener("keydown",ke),()=>document.removeEventListener("keydown",ke)},[Me]),a.useEffect(()=>{if(!Be)return;const ke=ut=>{Nt.current&&!Nt.current.contains(ut.target)&&Tt.current&&!Tt.current.contains(ut.target)&&oe(!1)};return document.addEventListener("mousedown",ke),()=>document.removeEventListener("mousedown",ke)},[Be]);const dt=a.useCallback(()=>{Q(ke=>!ke)},[]),Zt=a.useCallback(()=>{de(!0),ie(!1)},[]),Nn=a.useCallback(()=>{de(!1),ie(!0),K&&K("")},[K]),un=a.useCallback(()=>{Ue(ke=>!ke)},[]),Kt=a.useCallback(ke=>{ke&&ke(),Ue(!1),at(!1)},[]),mn=a.useCallback(()=>{Q(!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"})]}),fe&&L.length>=1&&U&&t.jsxs("div",{className:"mobile-project-switch",ref:mt,children:[t.jsx("button",{className:`mobile-project-switch-trigger${Xe?" mobile-project-switch-trigger--open":""}`,onClick:()=>De(ke=>!ke),title:"Switch project","aria-label":"Switch project","aria-expanded":Xe,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:t.jsx(Xt,{size:14,className:`mobile-project-switch-chevron${Xe?" mobile-project-switch-chevron--open":""}`})}),Xe&&t.jsx("div",{className:"mobile-project-switch-dropdown",role:"listbox","aria-label":"Select project","data-testid":"mobile-project-switch-dropdown",children:L.map(ke=>{const ut=$?.id===ke.id,Lt=Op[ke.status]?.color;return t.jsxs("button",{className:`mobile-project-switch-item${ut?" mobile-project-switch-item--current":""}`,onClick:()=>{U(ke),De(!1)},role:"option","aria-selected":ut,"data-testid":`mobile-project-switch-item-${ke.id}`,children:[t.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:Lt||"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:Fp(ke.path)})]}),ut&&t.jsx(Vn,{size:14,className:"mobile-project-switch-check"})]},ke.id)})})]}),!he&&L.length>=1&&G&&t.jsx(Zw,{projects:L,currentProject:$??null,onViewAll:G,onSelectProject:U}),Mt&&t.jsxs("div",{className:`header-node-selector${fe?" header-node-selector--mobile":""}`,ref:fe?void 0:Et,children:[t.jsx(Ww,{node:T??null,showDetails:!fe}),!fe&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:`btn-icon node-selector-trigger${et?" node-selector-trigger--open":""}`,onClick:()=>Ve(ke=>!ke),title:"Switch node","aria-label":"Switch node","aria-expanded":et,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:t.jsx(xn,{size:12,className:`node-selector-chevron${et?" node-selector-chevron--open":""}`})}),et&&t.jsxs("div",{className:"node-selector-dropdown",role:"listbox","aria-label":"Select node",children:[t.jsxs("button",{className:`node-selector-option${H?"":" node-selector-option--active"}`,onClick:()=>{k?.(null),Ve(!1)},role:"option","aria-selected":!H,"data-testid":"node-option-local",children:[t.jsx(Vi,{status:"online",compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:"Local"})]}),Dt.map(ke=>t.jsxs("button",{className:`node-selector-option${T?.id===ke.id?" node-selector-option--active":""}`,onClick:()=>{k?.(ke),Ve(!1)},role:"option","aria-selected":T?.id===ke.id,"data-testid":`node-option-${ke.id}`,children:[t.jsx(Vi,{status:ke.status,compact:!0}),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:[O&&z&&(S==="board"||S==="list")&&t.jsxs("div",{className:"view-toggle","data-testid":"mobile-view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${S==="board"?" active":""}`,onClick:()=>z("board"),title:"Board view","aria-label":"Board view","aria-pressed":S==="board","data-testid":"mobile-view-toggle-board",children:t.jsx(qi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${S==="list"?" active":""}`,onClick:()=>z("list"),title:"List view","aria-label":"List view","aria-pressed":S==="list","data-testid":"mobile-view-toggle-list",children:t.jsx(Tc,{size:16})})]}),K&&fe&&(O||S==="board"||S==="list")&&!ve&&t.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:dt,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:t.jsx(Ni,{size:16})}),Oe&&t.jsx("button",{className:"btn-icon",onClick:Zt,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:t.jsx(Ni,{size:16})}),fe&&O&&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(Ds,{size:16})}),!O&&z&&t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${S==="board"?" active":""}`,onClick:()=>z("board"),title:"Board view","aria-label":"Board view","aria-pressed":S==="board",children:t.jsx(qi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${S==="list"?" active":""}`,onClick:()=>z("list"),title:"List view","aria-label":"List view","aria-pressed":S==="list",children:t.jsx(Tc,{size:16})}),R&&t.jsx("button",{className:`view-toggle-btn${S==="agents"?" active":""}`,onClick:()=>z("agents"),title:"Agents view","aria-label":"Agents view","aria-pressed":S==="agents",children:t.jsx(Sn,{size:16})}),t.jsx("button",{className:`view-toggle-btn${S==="missions"?" active":""}`,onClick:()=>z("missions"),title:"Missions view","aria-label":"Missions view","aria-pressed":S==="missions",children:t.jsx(ws,{size:16})}),t.jsx("button",{className:`view-toggle-btn${S==="chat"?" active":""}`,onClick:()=>z("chat"),title:"Chat view","aria-label":"Chat view","aria-pressed":S==="chat",children:t.jsx(Si,{size:16})}),t.jsx("button",{className:`view-toggle-btn${S==="documents"?" active":""}`,onClick:()=>z("documents"),title:"Documents view","aria-label":"Documents view","aria-pressed":S==="documents",children:t.jsx(Bi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${S==="mailbox"?" active":""}`,onClick:()=>z("mailbox"),title:"Mailbox view","aria-label":"Mailbox view","aria-pressed":S==="mailbox",children:t.jsx(ba,{size:16})}),Rt&&t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:Tt,className:`view-toggle-btn${["research","skills","roadmaps","insights","memory","dev-server","devserver"].includes(S)||J?.todoView&&S==="todos"?" active":""}`,onClick:()=>oe(ke=>!ke),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":Be,"data-testid":"view-toggle-overflow-trigger",children:t.jsx(Xt,{size:12})}),Be&&t.jsxs("div",{ref:Nt,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[J?.researchView&&t.jsxs("button",{className:`view-toggle-overflow-item${S==="research"?" active":""}`,onClick:()=>{z("research"),oe(!1)},role:"menuitem","data-testid":"view-overflow-research",children:[t.jsx(Ni,{size:14}),t.jsx("span",{children:"Research"})]}),J?.insights&&t.jsxs("button",{className:`view-toggle-overflow-item${S==="insights"?" active":""}`,onClick:()=>{z("insights"),oe(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[t.jsx(cs,{size:14}),t.jsx("span",{children:"Insights"})]}),J?.roadmap&&t.jsxs("button",{className:`view-toggle-overflow-item${S==="roadmaps"?" active":""}`,onClick:()=>{z("roadmaps"),oe(!1)},role:"menuitem","data-testid":"view-overflow-roadmaps",children:[t.jsx(Pc,{size:14}),t.jsx("span",{children:"Roadmaps"})]}),_&&t.jsxs("button",{className:`view-toggle-overflow-item${S==="skills"?" active":""}`,onClick:()=>{z("skills"),oe(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[t.jsx(Qn,{size:14}),t.jsx("span",{children:"Skills"})]}),J?.memoryView&&t.jsxs("button",{className:`view-toggle-overflow-item${S==="memory"?" active":""}`,onClick:()=>{z("memory"),oe(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[t.jsx(Ro,{size:14}),t.jsx("span",{children:"Memory"})]}),J?.devServerView&&t.jsxs("button",{className:`view-toggle-overflow-item${S==="dev-server"||S==="devserver"?" active":""}`,onClick:()=>{z("devserver"),oe(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[t.jsx(jr,{size:14}),t.jsx("span",{children:"Dev Server"}),t.jsx("span",{className:"visually-hidden","data-testid":"view-toggle-dev-server"})]}),J?.todoView&&t.jsxs("button",{className:`view-toggle-overflow-item${S==="todos"?" active":""}`,onClick:()=>{z("todos"),oe(!1)},role:"menuitem","data-testid":"view-overflow-todos",children:[t.jsx(jp,{size:14}),t.jsx("span",{children:"Todos"})]})]})]})]}),!he&&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(Ds,{size:16})}),!he&&c&&t.jsx("button",{className:"btn-icon",onClick:c,title:"System Stats","data-testid":"desktop-header-system-stats-btn",children:t.jsx(jr,{size:16})}),!he&&l&&t.jsx("button",{className:"btn-icon",onClick:l,title:"View Activity Log",children:t.jsx(yr,{size:16})}),!he&&!ee&&t.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:t.jsx(wu,{size:16})}),!he&&t.jsxs("button",{className:`btn-icon${r>0?" btn-icon--has-indicator":""}`,onClick:r>0&&i?i:s,title:r>0?"Resume planning session":"Create a task with AI planning","data-testid":"planning-btn",style:{position:"relative"},children:[t.jsx(ri,{size:16}),r>0&&t.jsx("span",{className:"header-badge header-badge--pulse","data-testid":"planning-badge","aria-label":`${r} active planning session${r!==1?"s":""}`,children:r})]}),!he&&t.jsxs("div",{className:"terminal-split-btn",ref:Pt,children:[t.jsx("button",{className:"btn-icon btn-icon--terminal terminal-split-btn__main",onClick:x,title:"Open Terminal","data-testid":"terminal-toggle-btn",children:t.jsx(gi,{size:16})}),b&&v&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"terminal-split-btn__divider"}),t.jsx("button",{ref:At,className:`btn-icon terminal-split-btn__chevron${pe?" btn-icon--active":""}`,onClick:()=>Ae(ke=>!ke),title:"Scripts","aria-haspopup":"listbox","aria-expanded":pe,"aria-label":"Quick scripts","data-testid":"scripts-btn",children:t.jsx(Xt,{size:12,className:`quick-scripts-dropdown__trigger-chevron${pe?" rotate":""}`})}),pe&&t.jsx("div",{ref:Bt,tabIndex:-1,className:"quick-scripts-dropdown__menu",role:"listbox","aria-label":"Scripts",onKeyDown:F,"data-testid":"quick-scripts-dropdown",style:Pe?{position:"fixed",top:`${Pe.top}px`,left:`${Pe.left}px`,width:`${Pe.width}px`,right:"auto"}:void 0,children:ye?t.jsxs("div",{className:"quick-scripts-dropdown__loading","data-testid":"quick-scripts-loading",children:[t.jsx(ot,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts..."})]}):St.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(gi,{size:16})}),t.jsx("p",{children:"No scripts configured"}),t.jsx("button",{className:"quick-scripts-dropdown__empty-action btn",onClick:D,children:"Add your first script"})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-scripts-dropdown__list",children:St.map(([ke,ut],Lt)=>t.jsxs("button",{className:`quick-scripts-dropdown__item ${Re===Lt?"highlighted":""}`,onClick:()=>ct(ke,ut),role:"option","aria-selected":Re===Lt,"data-testid":`quick-script-item-${ke}`,children:[t.jsx(Cn,{size:14,className:"quick-scripts-dropdown__item-icon"}),t.jsxs("div",{className:"quick-scripts-dropdown__item-info",children:[t.jsx("span",{className:"quick-scripts-dropdown__item-name",children:ke}),t.jsx("span",{className:"quick-scripts-dropdown__item-command",title:ut,children:ut.length>50?`${ut.slice(0,50)}...`:ut})]})]},ke))}),t.jsx("div",{className:"quick-scripts-dropdown__footer",children:t.jsxs("button",{className:`quick-scripts-dropdown__manage ${Wt&&Re===St.length?"highlighted":""}`,onClick:D,"data-testid":"quick-scripts-manage",children:[t.jsx(pr,{size:14}),t.jsx("span",{children:"Manage Scripts..."})]})})]})})]})]}),!he&&y&&t.jsx("button",{className:`btn-icon${w?" btn-icon--active":""}`,onClick:y,title:"Browse files","data-testid":"files-toggle-btn",children:t.jsx(Xn,{size:16})}),!he&&h&&t.jsx("button",{className:"btn-icon",onClick:h,title:"Git Manager","data-testid":"git-manager-btn",children:t.jsx(Ws,{size:16})}),!he&&g&&t.jsx("button",{className:"btn-icon",onClick:g,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:t.jsx($c,{size:16})}),!he&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{ref:te,className:"btn-icon",onClick:()=>se(ke=>!ke),title:"More actions","aria-label":"More actions","aria-expanded":Ne,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:t.jsx(Mc,{size:16})}),Ne&&t.jsxs("div",{ref:Ze,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[f&&p!==!1&&t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{f(),se(!1)},role:"menuitem","data-testid":"desktop-overflow-nodes-btn",children:[t.jsx(kr,{size:14}),t.jsx("span",{children:"Nodes"})]}),t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{Kt(m),se(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[t.jsx(Ei,{size:14}),t.jsx("span",{children:"Automation"})]})]})]}),t.jsxs("div",{className:"engine-control-split-btn",ref:qt,children:[t.jsx("button",{className:`btn-icon engine-control-split-btn__main${E?" btn-icon--stopped":""}`,onClick:j,title:E?"Start AI engine":"Stop AI engine","data-testid":"engine-control-main-btn",children:E?t.jsx(Cn,{size:16}):t.jsx(Cs,{size:16})}),t.jsx("span",{className:"engine-control-split-btn__divider"}),t.jsx("button",{className:`btn-icon engine-control-split-btn__chevron${Me?" btn-icon--active":""}`,onClick:()=>Le(ke=>!ke),title:"Engine options","aria-haspopup":"menu","aria-expanded":Me,"data-testid":"engine-control-chevron-btn",children:t.jsx(Xt,{size:12})}),Me&&t.jsx("div",{className:"engine-control-split-btn__menu",role:"menu",children:t.jsxs("button",{className:`engine-control-split-btn__menu-item${C?" engine-control-split-btn__menu-item--active":""}`,onClick:()=>{A?.(),Le(!1)},role:"menuitem",title:C?"Resume scheduling":"Pause triage",disabled:!!E,"data-testid":"engine-control-pause-triage-btn",children:[C?t.jsx(Cn,{size:14}):t.jsx(qs,{size:14}),t.jsx("span",{children:C?"Resume scheduling":"Pause triage"})]})})]}),!he&&t.jsx("button",{className:"btn-icon",onClick:e,title:"Settings",children:t.jsx(pr,{size:16})}),t.jsx(al,{slotId:"header-action",projectId:Y}),he&&!O&&t.jsx("button",{ref:je,className:"btn-icon compact-overflow-trigger",onClick:un,title:"More header actions","aria-label":"More header actions","aria-expanded":Ee,"aria-haspopup":"menu",children:t.jsx(Mc,{size:16})}),he&&!O&&Ee&&t.jsxs("div",{ref:rt,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[L.length>=1&&G&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Kt(G),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[t.jsx(gp,{size:16}),t.jsx("span",{children:"Projects"})]}),y&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Kt(y),role:"menuitem","data-testid":"overflow-files-btn",children:[t.jsx(Xn,{size:16}),t.jsx("span",{children:"Browse Files"})]}),t.jsxs("button",{className:`mobile-overflow-item${r>0?" mobile-overflow-item--has-indicator":""}`,onClick:()=>Kt(r>0&&i?i:s),role:"menuitem","data-testid":"overflow-planning-btn",children:[t.jsxs("span",{className:"mobile-overflow-icon-wrapper",children:[t.jsx(ri,{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:()=>Kt(h),role:"menuitem","data-testid":"overflow-git-btn",children:[t.jsx(Ws,{size:16}),t.jsx("span",{children:"Git Manager"})]}),f&&p!==!1&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Kt(f),role:"menuitem","data-testid":"overflow-nodes-btn",children:[t.jsx(kr,{size:16}),t.jsx("span",{children:"Nodes"})]}),!ee&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Kt(n),role:"menuitem",children:[t.jsx(wu,{size:16}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("div",{className:"mobile-overflow-group","data-testid":"overflow-terminal-group",children:[t.jsxs("div",{className:"mobile-overflow-split-row",children:[t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-split-primary",onClick:()=>Kt(x),role:"menuitem","data-testid":"overflow-terminal-primary-btn",children:[t.jsx(gi,{size:16}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{className:"mobile-overflow-split-toggle",onClick:()=>at(ke=>!ke),role:"menuitem","aria-expanded":Te,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:t.jsx(xn,{size:14,className:`mobile-overflow-chevron${Te?" mobile-overflow-chevron--open":""}`})})]}),Te&&t.jsx("div",{className:"mobile-overflow-submenu",role:"menu","aria-label":"Scripts submenu",children:Z?t.jsxs("div",{className:"mobile-overflow-submenu-loading","data-testid":"overflow-scripts-loading",children:[t.jsx(ot,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):Yt.length>0?t.jsxs(t.Fragment,{children:[Yt.map(([ke,ut])=>t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{v&&v(ke,ut),Ue(!1),at(!1)},role:"menuitem","data-testid":`overflow-script-item-${ke}`,children:[t.jsx(Cn,{size:14}),t.jsx("span",{children:ke})]},ke)),b&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>Kt(b),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(Hs,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):b&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>Kt(b),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(Hs,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Kt(m),role:"menuitem","data-testid":"overflow-schedules-btn",children:[t.jsx(Ei,{size:16}),t.jsx("span",{children:"Automation"})]}),l&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Kt(l),role:"menuitem","data-testid":"overflow-activity-log-btn",children:[t.jsx(yr,{size:16}),t.jsx("span",{children:"View Activity Log"})]}),u&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Kt(u),role:"menuitem","data-testid":"overflow-mailbox-btn",children:[t.jsx(ba,{size:16}),t.jsxs("span",{children:["Mailbox",d>0?` (${d})`:""]})]}),o&&t.jsxs("button",{className:"mobile-overflow-item",onClick:ke=>Kt(()=>o(ke.currentTarget.getBoundingClientRect())),role:"menuitem","data-testid":"overflow-usage-btn",children:[t.jsx(Ds,{size:16}),t.jsx("span",{children:"View Usage"})]}),g&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Kt(g),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[t.jsx($c,{size:16}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Kt(e),role:"menuitem",children:[t.jsx(pr,{size:16}),t.jsx("span",{children:"Settings"})]})]})]})]}),Ge&&ze&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{className:"header-search",children:[t.jsx(Ni,{size:14,className:"header-search-icon"}),t.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:B,onChange:ke=>K(ke.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:Nn,"aria-label":"Close search",children:t.jsx(Ht,{size:14})})]})}),K&&fe&&ve&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{ref:pt,className:"header-search mobile-search-expanded",children:[t.jsx(Ni,{size:14,className:"header-search-icon"}),t.jsx("input",{ref:gt,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:B,onChange:ke=>K(ke.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:mn,"aria-label":"Close search",children:t.jsx(Ht,{size:14})})]})})]})}const tN={themeMode:"dark",colorTheme:"default",dashboardFontScalePct:100,defaultProvider:void 0,defaultModelId:void 0,fallbackProvider:void 0,fallbackModelId:void 0,defaultThinkingLevel:void 0,ntfyEnabled:!1,ntfyTopic:void 0,ntfyBaseUrl:void 0,ntfyEvents:["in-review","merged","failed","awaiting-approval","awaiting-user-review","planning-awaiting-input","gridlock"],ntfyDashboardHost:void 0,webhookEnabled:!1,webhookUrl:void 0,webhookFormat:"generic",webhookEvents:[],notificationProviders:[],customProviders:[],defaultProjectId:void 0,setupComplete:void 0,favoriteProviders:void 0,favoriteModels:void 0,openrouterModelSync:!0,updateCheckEnabled:!0,updateCheckFrequency:"daily",showGitHubStarButton:!0,modelOnboardingComplete:void 0,useClaudeCli:void 0,useDroidCli:void 0,executionGlobalProvider:void 0,executionGlobalModelId:void 0,planningGlobalProvider:void 0,planningGlobalModelId:void 0,validatorGlobalProvider:void 0,validatorGlobalModelId:void 0,titleSummarizerGlobalProvider:void 0,titleSummarizerGlobalModelId:void 0,daemonToken:void 0,daemonPort:4040,daemonHost:"127.0.0.1",settingsSyncEnabled:!1,settingsSyncAuth:!1,settingsSyncInterval:9e5,settingsSyncConflictResolution:"last-write-wins",dashboardCurrentNodeId:void 0,dashboardCurrentProjectIdByNode:void 0,vitestAutoKillEnabled:!0,vitestKillThresholdPct:90,researchGlobalDefaults:{searchProvider:void 0,synthesisProvider:void 0,synthesisModelId:void 0,enabledSources:{webSearch:!0,pageFetch:!0,github:!1,localDocs:!0,llmSynthesis:!0},maxSourcesPerRun:20,defaultExportFormat:"markdown"},researchGlobalEnabled:!0,researchGlobalMaxConcurrentRuns:3,researchGlobalDefaultTimeout:3e5,researchGlobalMaxSourcesPerRun:20,researchGlobalMaxSynthesisRounds:2,researchWebSearchProvider:"none",researchSearxngUrl:void 0,researchBraveApiKey:void 0,researchGoogleSearchApiKey:void 0,researchGoogleSearchCx:void 0,researchTavilyApiKey:void 0,researchGitHubEnabled:!1,researchLocalDocsEnabled:!0,researchMaxSearchResults:10,researchFetchTimeoutMs:3e4,researchUserAgent:"FusionResearchBot/1.0",remoteAccess:{activeProvider:null,providers:{tailscale:{enabled:!1,hostname:"",targetPort:0,acceptRoutes:!1},cloudflare:{enabled:!1,quickTunnel:!0,tunnelName:"",tunnelToken:null,ingressUrl:""}},tokenStrategy:{persistent:{enabled:!0,token:null},shortLived:{enabled:!1,ttlMs:9e5,maxTtlMs:864e5}},lifecycle:{rememberLastRunning:!1,wasRunningOnShutdown:!1,lastRunningProvider:null}},experimentalFeatures:{}},nN={globalPause:!1,globalPauseReason:void 0,enginePaused:!1,maxConcurrent:2,maxTriageConcurrent:2,globalMaxConcurrent:4,maxWorktrees:4,pollIntervalMs:15e3,heartbeatMultiplier:1,groupOverlappingFiles:!0,overlapIgnorePaths:[],autoMerge:!0,mergeStrategy:"direct",requirePrApproval:!1,pushAfterMerge:!1,pushRemote:"origin",unavailableNodePolicy:"block",defaultNodeId:void 0,worktreeInitCommand:void 0,testCommand:void 0,buildCommand:void 0,recycleWorktrees:!1,worktreeNaming:"random",taskPrefix:"FN",includeTaskIdInCommit:!0,commitAuthorEnabled:!0,commitAuthorName:"Fusion",commitAuthorEmail:"noreply@runfusion.ai",planningProvider:void 0,planningModelId:void 0,planningFallbackProvider:void 0,planningFallbackModelId:void 0,defaultProviderOverride:void 0,defaultModelIdOverride:void 0,executionProvider:void 0,executionModelId:void 0,validatorProvider:void 0,validatorModelId:void 0,validatorFallbackProvider:void 0,validatorFallbackModelId:void 0,modelPresets:[],autoSelectModelPreset:!1,defaultPresetBySize:{},autoResolveConflicts:!0,smartConflictResolution:!0,worktreeRebaseBeforeMerge:!0,worktreeRebaseRemote:"",worktreeRebaseLocalBase:!0,mergeConflictStrategy:"smart-prefer-main",workflowStepTimeoutMs:36e4,strictScopeEnforcement:!1,buildRetryCount:0,verificationFixRetries:3,buildTimeoutMs:3e5,requirePlanApproval:!1,specStalenessEnabled:!1,specStalenessMaxAgeMs:360*60*1e3,taskStuckTimeoutMs:void 0,aiSessionTtlMs:10080*60*1e3,aiSessionCleanupIntervalMs:3600*1e3,autoUnpauseEnabled:!0,autoUnpauseBaseDelayMs:3e5,autoUnpauseMaxDelayMs:36e5,maxStuckKills:6,maxPostReviewFixes:1,maxSpawnedAgentsPerParent:5,maxSpawnedAgentsGlobal:20,maintenanceIntervalMs:9e5,autoArchiveDoneTasksEnabled:!0,autoArchiveDoneAfterMs:2880*60*1e3,archiveAgentLogMode:"compact",autoUpdatePrStatus:!1,githubCommentOnDone:!1,githubCommentTemplate:void 0,autoBackupEnabled:!1,autoBackupSchedule:"0 2 * * *",autoBackupRetention:7,autoBackupDir:".fusion/backups",autoSummarizeTitles:!1,useAiMergeCommitSummary:!0,titleSummarizerProvider:void 0,titleSummarizerModelId:void 0,titleSummarizerFallbackProvider:void 0,titleSummarizerFallbackModelId:void 0,scripts:void 0,setupScript:void 0,insightExtractionEnabled:!1,insightExtractionSchedule:"0 2 * * *",insightExtractionMinIntervalMs:864e5,memoryEnabled:!0,memoryBackendType:"qmd",memoryAutoSummarizeEnabled:!1,memoryAutoSummarizeThresholdChars:5e4,memoryAutoSummarizeSchedule:"0 3 * * *",memoryDreamsEnabled:!1,memoryDreamsSchedule:"0 4 * * *",tokenCap:void 0,runStepsInNewSessions:!1,maxParallelSteps:2,missionStaleThresholdMs:6e5,missionMaxTaskRetries:3,missionHealthCheckIntervalMs:3e5,agentPrompts:void 0,promptOverrides:void 0,reflectionEnabled:!1,reflectionIntervalMs:36e5,reflectionAfterTask:!0,reviewHandoffPolicy:"disabled",showQuickChatFAB:!1,researchSettings:{enabled:!0,searchProvider:void 0,synthesisProvider:void 0,synthesisModelId:void 0,enabledSources:{webSearch:!0,pageFetch:!0,github:!1,localDocs:!0,llmSynthesis:!0},limits:{maxConcurrentRuns:3,maxSourcesPerRun:20,maxDurationMs:3e5,requestTimeoutMs:3e4}},researchEnabled:!0,researchMaxConcurrentRuns:3,researchDefaultTimeout:3e5,researchMaxSourcesPerRun:20,researchMaxSynthesisRounds:2},sN=Object.freeze(Object.keys(tN)),iN=Object.freeze(Object.keys(nN));function h3(e){return sN.includes(e)}function p3(e){return iN.includes(e)}function we(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function aN(e){return!!(e?.provider&&e?.modelId)}function _i(...e){for(const n of e)if(aN(n))return{provider:n.provider,modelId:n.modelId};return{}}function rl(e){return _i({provider:e?.defaultProviderOverride,modelId:e?.defaultModelIdOverride},{provider:e?.defaultProvider,modelId:e?.defaultModelId})}function rN(e){return _i({provider:e?.executionProvider,modelId:e?.executionModelId},{provider:e?.executionGlobalProvider,modelId:e?.executionGlobalModelId},rl(e))}function oN(e){return _i({provider:e?.planningProvider,modelId:e?.planningModelId},{provider:e?.planningGlobalProvider,modelId:e?.planningGlobalModelId},rl(e))}function lN(e){return _i({provider:e?.validatorProvider,modelId:e?.validatorModelId},{provider:e?.validatorGlobalProvider,modelId:e?.validatorGlobalModelId},rl(e))}function f3(e){return _i({provider:e?.titleSummarizerProvider,modelId:e?.titleSummarizerModelId},{provider:e?.titleSummarizerGlobalProvider,modelId:e?.titleSummarizerGlobalModelId},{provider:e?.planningProvider,modelId:e?.planningModelId},rl(e))}function Up(e,n){return _i({provider:e.modelProvider,modelId:e.modelId},rN(n))}function Bp(e,n){return _i({provider:e.validatorModelProvider,modelId:e.validatorModelId},lN(n))}function Hp(e,n){return _i({provider:e.planningModelProvider,modelId:e.planningModelId},oN(n))}const g3=["off","minimal","low","medium","high"],Oi=["triage","todo","in-progress","in-review","done","archived"],kd=["low","normal","high","urgent"],_s="normal",cN=["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"],Bn={triage:"Planning",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},dN={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"},Uc={triage:["todo"],todo:["in-progress","triage"],"in-progress":["in-review","todo","triage","done"],"in-review":["done","in-progress","todo","triage"],done:["todo","triage","archived"],archived:["done"]};function uN(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 mN(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 hN({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 qp=a.createContext(null);function pN({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 Ao.createElement(qp.Provider,{value:u},e,Ao.createElement(hN,{isOpen:c!==null,options:c?.options??null,onConfirm:()=>l(!0),onCancel:()=>l(!1)}))}function Ks(){const e=a.useContext(qp);return e||{confirm:async n=>!1}}function fN(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 Vp({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(Es,{size:12}),t.jsxs("span",{children:["#",e.number]})]}),n&&t.jsxs("span",{className:`card-github-badge ${fN(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,onClick:r,children:[t.jsx(Yo,{size:12}),t.jsxs("span",{children:["#",n.number]})]})]})}function so(e,n){return`${e??"default"}:${n}`}class gN{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=so(this.projectId,o);this.subscriptionsByTask.set(l,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const i=so(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=so(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(oi(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=so(this.projectId,l.taskId),u=this.badgeUpdates.get(c);this.badgeUpdates.set(c,{prInfo:Nu(l,"prInfo")?l.prInfo??null:u?.prInfo,issueInfo:Nu(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 Di=new gN;let bN=0;function Nu(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function Wp(e){const n=a.useRef(null);n.current===null&&(n.current=`badge-hook-${bN++}`);const s=a.useSyncExternalStore(o=>Di.subscribe(o),()=>Di.getSnapshot(),()=>Di.getSnapshot()),i=a.useCallback(o=>{Di.subscribeTask(n.current,o)},[]),r=a.useCallback(o=>{Di.unsubscribeTask(n.current,o)},[]);return a.useEffect(()=>{Di.setProjectId(e??null)},[e]),a.useEffect(()=>()=>{Di.cleanupHook(n.current)},[]),{badgeUpdates:s.badgeUpdates,isConnected:s.isConnected,subscribeToBadge:i,unsubscribeFromBadge:r}}function Lo(e,n,s,i){return e===void 0||!n?s:!i||n>=i?e??void 0:s}function xN({taskId:e,prInfo:n,issueInfo:s,updatedAt:i,isInViewport:r,projectId:o}){const{badgeUpdates:l,subscribeToBadge:c,unsubscribeFromBadge:u}=Wp(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=Lo(m?.prInfo,m?.timestamp,n,n?.lastCheckedAt??i),f=Lo(m?.issueInfo,m?.timestamp,s,s?.lastCheckedAt??i);return!h&&!f?null:t.jsx(Vp,{prInfo:h,issueInfo:f})}const vN=a.memo(xN);vN.displayName="TaskCardBadge";const yN={sm:16,md:20,lg:24};function jN({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 Su({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 Zs({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 kN({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 Cu({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 wN({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 Sl({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 _u({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 Mu({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 Ha({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 Au({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 Cl({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 Ru({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 El({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 NN({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 SN({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 Tu({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 _l({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 CN({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 Pu({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 Ml({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 Iu({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 Al({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 $u({size:e,color:n,label:s="Anthropic — via Claude CLI"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"claude-cli-icon","aria-label":s,children:[t.jsx("g",{transform:"translate(-1 -1.5) scale(0.82)",children:t.jsx("path",{d:"M17.3041 3.541h-3.6718l6.696 16.918H24Zm-10.6082 0L0 20.459h3.7442l1.3693-3.5527h7.0052l1.3693 3.5528h3.7442L10.5363 3.5409Zm-.3712 10.2232 2.2914-5.9456 2.2914 5.9456Z",fill:n})}),t.jsx("rect",{x:"13",y:"13",width:"10",height:"9",rx:"1.5",fill:n}),t.jsx("path",{d:"M15.2 16.2l1.6 1.4-1.6 1.4M18.6 19.6h2.4",stroke:"var(--provider-icon-contrast)",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})]})}function EN({size:e,color:n,label:s="Factory AI — via Droid CLI"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"droid-cli-icon","aria-label":s,children:[t.jsx("rect",{x:"2",y:"3",width:"14",height:"14",rx:"3",fill:n}),t.jsx("path",{d:"M6.5 7.5h2.6a2.9 2.9 0 1 1 0 5.8H6.5zM9 7.5v5.8",stroke:"var(--provider-icon-contrast)",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round"}),t.jsx("rect",{x:"13",y:"13",width:"10",height:"9",rx:"1.5",fill:n}),t.jsx("path",{d:"M15.2 16.2l1.6 1.4-1.6 1.4M18.6 19.6h2.4",stroke:"var(--provider-icon-contrast)",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})]})}const _N={anthropic:{component:jN,color:"var(--provider-anthropic)"},"claude-cli":{component:$u,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"pi-claude-cli":{component:$u,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"droid-cli":{component:EN,color:"var(--provider-openai)",label:"Factory AI — via Droid CLI"},openai:{component:Su,color:"var(--provider-openai)"},"openai-codex":{component:Su,color:"var(--provider-openai)",label:"OpenAI Codex"},google:{component:Zs,color:"var(--provider-gemini)"},gemini:{component:Zs,color:"var(--provider-gemini)"},"google-antigravity":{component:Zs,color:"var(--provider-gemini)",label:"Google Gemini"},antigravity:{component:Zs,color:"var(--provider-gemini)",label:"Google Gemini"},"google-vertex":{component:Zs,color:"var(--provider-gemini)",label:"Google Vertex AI"},vertex:{component:Zs,color:"var(--provider-gemini)",label:"Google Vertex AI"},"google-cloud-code":{component:Zs,color:"var(--provider-gemini)",label:"Google Cloud Code"},"cloud-code":{component:Zs,color:"var(--provider-gemini)",label:"Google Cloud Code"},"google-gemini-cli":{component:Zs,color:"var(--provider-gemini)",label:"Google Gemini CLI"},"google-generative-ai":{component:Zs,color:"var(--provider-gemini)",label:"Google Generative AI"},ollama:{component:kN,color:"var(--text)"},github:{component:Pu,color:"var(--text)"},"github-copilot":{component:Pu,color:"var(--text)",label:"GitHub Copilot"},openrouter:{component:CN,color:"var(--provider-openrouter)"},minimax:{component:Cu,color:"var(--provider-minimax)"},"minimax-cn":{component:Cu,color:"var(--provider-minimax)",label:"MiniMax (CN)"},zai:{component:wN,color:"var(--provider-zai)"},kimi:{component:Sl,color:"var(--provider-kimi)"},moonshot:{component:Sl,color:"var(--provider-kimi)"},"kimi-coding":{component:Sl,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:_u,color:"var(--text)"},grok:{component:_u,color:"var(--text)",label:"xAI"},opencode:{component:Mu,color:"var(--provider-opencode)"},"opencode-go":{component:Mu,color:"var(--provider-opencode)",label:"Opencode (Go)"},qwen:{component:Ha,color:"var(--provider-qwen)"},"qwen-ai":{component:Ha,color:"var(--provider-qwen)",label:"Qwen"},"qwen-coder":{component:Ha,color:"var(--provider-qwen)",label:"Qwen Coder"},alibaba:{component:Ha,color:"var(--provider-qwen)",label:"Qwen"},tongyi:{component:Ha,color:"var(--provider-qwen)",label:"Qwen"},lmstudio:{component:Au,color:"var(--provider-lmstudio)",label:"LM Studio"},"lm-studio":{component:Au,color:"var(--provider-lmstudio)",label:"LM Studio"},huggingface:{component:Cl,color:"var(--provider-huggingface)",label:"Hugging Face"},"hugging-face":{component:Cl,color:"var(--provider-huggingface)",label:"Hugging Face"},hf:{component:Cl,color:"var(--provider-huggingface)",label:"Hugging Face"},mistral:{component:Ru,color:"var(--provider-mistral)",label:"Mistral AI"},"mistral-ai":{component:Ru,color:"var(--provider-mistral)",label:"Mistral AI"},azure:{component:El,color:"var(--provider-azure)"},"azure-openai":{component:El,color:"var(--provider-azure)",label:"Azure OpenAI"},"azure-openai-responses":{component:El,color:"var(--provider-azure)",label:"Azure OpenAI"},fireworks:{component:_l,color:"var(--provider-fireworks)",label:"Fireworks AI"},"fireworks-ai":{component:_l,color:"var(--provider-fireworks)",label:"Fireworks AI"},fireworksai:{component:_l,color:"var(--provider-fireworks)",label:"Fireworks AI"},cerebras:{component:NN,color:"var(--provider-cerebras)"},groq:{component:SN,color:"var(--provider-groq)"},vercel:{component:Tu,color:"var(--provider-vercel)"},"vercel-ai-gateway":{component:Tu,color:"var(--provider-vercel)",label:"Vercel AI Gateway"},hermes:{component:Ml,color:"var(--provider-hermes)",label:"Hermes"},"hermes-agent":{component:Ml,color:"var(--provider-hermes)",label:"Hermes"},hermesagent:{component:Ml,color:"var(--provider-hermes)",label:"Hermes"},openclaw:{component:Iu,color:"var(--provider-openclaw)",label:"OpenClaw"},"open-claw":{component:Iu,color:"var(--provider-openclaw)",label:"OpenClaw"},paperclip:{component:Al,color:"var(--provider-paperclip)",label:"Paperclip"},paperclipai:{component:Al,color:"var(--provider-paperclip)",label:"Paperclip"},"paperclip-ai":{component:Al,color:"var(--provider-paperclip)",label:"Paperclip"}};function An({provider:e,size:n="sm"}){const s=e.toLowerCase(),i=_N[s],r=i?.component,o=i?.color??"var(--text-muted)",l=i?.label,c=yN[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(Ob,{size:c})})}const Ps={data:new Map,pendingPromise:null,lastFetchTime:null},MN=5e3;function Co(e,n){return n?`${n}::${e}`:e}function AN(e,n){const s=Ps.data.get(Co(e,n));if(!(!s||Date.now()-s.timestamp>MN))return s}function RN(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 aj(c,e)}catch(h){d=h instanceof Error?h:new Error(String(h));const f=we(h);if(f?.includes("429")||f?.toLowerCase().includes("rate limit")){const p=Math.min(1e3*Math.pow(2,m),3e4);await new Promise(g=>setTimeout(g,p));continue}break}if(d)throw d;return{}},[e]),o=a.useCallback(async c=>{if(c.length===0)return;const d=Date.now()-5e3;if(c.every(f=>{const p=Ps.data.get(Co(f,e));return p&&p.timestamp>d})&&Ps.lastFetchTime&&Ps.lastFetchTime>d)return;if(i.current&&(clearTimeout(i.current),i.current=null),Ps.pendingPromise){s(!0);try{await Ps.pendingPromise}finally{s(!1)}return}s(!0);const h=r(c);Ps.pendingPromise=h;try{const f=await h,p=Date.now();for(const[g,b]of Object.entries(f))Ps.data.set(Co(g,e),{result:b,timestamp:p});Ps.lastFetchTime=p}catch{}finally{Ps.pendingPromise=null,s(!1)}},[r,e]),l=a.useCallback(c=>Ps.data.get(Co(c,e)),[e]);return{fetchBatch:o,isLoading:n,lastFetchTime:Ps.lastFetchTime,getBatchData:l}}const Bc=new Map,TN=3e4;function Kp(e,n,s,i){return`${e}:${n??""}:${s??""}:${i??""}`}function PN(e,n,s,i){const r=Kp(e,n,s,i),o=Bc.get(r);return o?Date.now()>o.expiresAt?(Bc.delete(r),null):o.stats:null}function IN(e,n,s,i,r){const o=Kp(e,n,s,i);Bc.set(o,{stats:r,expiresAt:Date.now()+TN})}function $N(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,f]=a.useState(!1);return a.useEffect(()=>{if(!o){m(null),f(!1);return}const p=n==="done"&&!!s,g=(n==="in-progress"||n==="in-review")&&!!l;if(!e||!p&&!g){m(null),f(!1);return}const b=g?l:void 0,v=c!==void 0?String(c):void 0;let x=!1;async function y(E=!1){if(!E){const C=PN(e,i,b,v);if(C){x||(m(C),f(!1));return}}f(!0);try{const C=await Pp(e,b,i);x||(m(C.stats),IN(e,i,b,v,C.stats))}catch{x||m(null)}finally{x||f(!1)}}y();let w;return u&&g&&(w=setInterval(()=>{y(!0)},u)),()=>{x=!0,w&&clearInterval(w)}},[e,n,s,i,o,l,c,u]),{stats:d,loading:h}}const DN=new Set(["failed","stuck-killed"]);function zo(e,n,s){if(e.column!=="in-progress"||e.status&&DN.has(e.status)||!n||n<=0)return!1;const i=new Date(e.updatedAt).getTime();return(s??Date.now())-i>n}function LN(e){switch(e){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function zN(e){return e==="done"||e==="skipped"}function FN(e,n,s){const i=s?.get(e)?.trim();if(i)return i;const r=n?.workflowStepName?.trim();return r||e}function Gp(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:FN(u,d,n),status:d?LN(d.status):"pending",source:"workflow",phase:d?.phase??"pre-merge"}}),o=[...s,...r],l=o.length,c=o.filter(u=>zN(u.status)).length;return{total:l,completed:c,items:o}}function ON(e){return(e.action||e.outcome||"").replace(/^\[timing\]\s*/i,"").replace(/^\[[^\]]+\]\s*/i,"").replace(/\s+in\s+\d+(?:\.\d+)?ms\b/i,"").replace(/\s+after\s+\d+(?:\.\d+)?ms\b/i,"").trim()||"Timing event"}function Jp(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??""}
621
+ ${n.outcome??""}`.match(/(\d+(?:\.\d+)?)ms\b/i),r=i?Number(i[1]):void 0;return{timestamp:n.timestamp,durationMs:Number.isFinite(r)?r:void 0,summary:ON(n)}})}function UN(e){if(!e||e.length===0)return null;let n=0,s=0;for(const i of Jp(e))typeof i.durationMs=="number"&&(n+=i.durationMs,s+=1);return s>0?n:null}const Hc=new Map;async function BN(e,n){const s=Hc.get(e);if(s)return s;try{const i=await Ip(e,n);return Hc.set(e,i.title),i.title}catch{return e}}const Du=12;function HN(e){return e.length<=Du?e:e.slice(0,Du-3)+"..."}const qc=new Map;async function qN(e,n){const s=qc.get(e);if(s)return s;try{const i=await Oc(e,n);return qc.set(e,i.name),i.name}catch{return e}}function VN(e){return typeof e=="string"&&kd.includes(e)?e:_s}function WN(e,n){return e.length<=n?e:e.slice(0,n-3)+"..."}const KN=new Set(["triage","todo"]),Lu=new Set(["planning","researching","executing","finalizing","merging"]),zu=new Set(["merging","merging-pr"]),GN={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"},JN=new Set(["in-progress","in-review","done"]),YN=3e4;function Wi(e){if(!e)return null;const n=Date.parse(e);return Number.isFinite(n)?n:null}function QN(e){const n=Wi(e.columnMovedAt??e.updatedAt);if(n==null)return null;const s=Date.now();return n>s?null:n}function Fu(e,n){const s=Wi(e.columnMovedAt??e.updatedAt);return s==null?null:Math.max(0,n-s)}function lr(e,n){const s=Wi(e.executionStartedAt);if(s==null)return null;const i=Wi(e.executionCompletedAt),r=i!=null&&i>=s?i:n;return Math.max(0,r-s)}function XN(e){return e.column==="done"?QN(e):null}function Yp(e,n){const s=Wi(e.updatedAt);return s==null?null:Math.max(0,n-s)}function ZN(e,n){const s=lr(e,n);if(s!=null)return s;const i=Yp(e,n),r=cr(e,n);return r!=null?r+(i??0):i}function e1(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=Wi(o.startedAt);if(l==null)continue;let c;if(o.completedAt){const u=Wi(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 cr(e,n){const s=typeof e.timedExecutionMs=="number"?e.timedExecutionMs:UN(e.log),i=e1(e,n);return s==null&&i==null?null:(s??0)+(i??0)}function Ou(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){if(!Number.isFinite(e)||e<0||e===0)return"";const n=Math.ceil(e/6e4);if(n<59)return`${n}m`;const s=Math.ceil(e/36e5);return s<24?`${s}h`:`${Math.ceil(e/864e5)}d`}function Bu(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 t1(e,n){return e.length!==n.length?!1:e.every((s,i)=>s.name===n[i]?.name&&s.status===n[i]?.status)}function n1(e,n){return e.length!==n.length?!1:e.every((s,i)=>s===n[i])}function s1(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>s===n[i])}function i1(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 a1(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 r1(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 o1(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 l1(e,n){const s=e.task,i=n.task;return e.queued===n.queued&&e.projectId===n.projectId&&e.globalPaused===n.globalPaused&&e.taskStuckTimeoutMs===n.taskStuckTimeoutMs&&e.onOpenDetail===n.onOpenDetail&&e.addToast===n.addToast&&e.onUpdateTask===n.onUpdateTask&&e.onArchiveTask===n.onArchiveTask&&e.onUnarchiveTask===n.onUnarchiveTask&&e.onDeleteTask===n.onDeleteTask&&e.onRetryTask===n.onRetryTask&&e.onOpenDetailWithTab===n.onOpenDetailWithTab&&e.onOpenMission===n.onOpenMission&&e.onMoveTask===n.onMoveTask&&e.workflowStepNameLookup===n.workflowStepNameLookup&&s.id===i.id&&s.title===i.title&&s.description===i.description&&s.column===i.column&&s.columnMovedAt===i.columnMovedAt&&s.timedExecutionMs===i.timedExecutionMs&&s.updatedAt===i.updatedAt&&s.createdAt===i.createdAt&&s.status===i.status&&s.priority===i.priority&&s.executionMode===i.executionMode&&s.paused===i.paused&&s.error===i.error&&s.size===i.size&&s.blockedBy===i.blockedBy&&s.worktree===i.worktree&&s.baseBranch===i.baseBranch&&s.breakIntoSubtasks===i.breakIntoSubtasks&&s.currentStep===i.currentStep&&s.modelProvider===i.modelProvider&&s.modelId===i.modelId&&s.validatorModelProvider===i.validatorModelProvider&&s.validatorModelId===i.validatorModelId&&s.planningModelProvider===i.planningModelProvider&&s.planningModelId===i.planningModelId&&s.reviewLevel===i.reviewLevel&&s.missionId===i.missionId&&s.assignedAgentId===i.assignedAgentId&&s.mergeRetries===i.mergeRetries&&r1(s.attachments,i.attachments)&&o1(s.comments,i.comments)&&n1(s.dependencies,i.dependencies)&&t1(s.steps,i.steps)&&s1(s.enabledWorkflowSteps,i.enabledWorkflowSteps)&&a1(s.workflowStepResults,i.workflowStepResults)&&Bu(s.prInfo,i.prInfo)&&Bu(s.issueInfo,i.issueInfo)}function c1({task:e,projectId:n,queued:s,onOpenDetail:i,addToast:r,globalPaused:o,onUpdateTask:l,onArchiveTask:c,onUnarchiveTask:u,onDeleteTask:d,onRetryTask:m,onOpenDetailWithTab:h,taskStuckTimeoutMs:f,onOpenMission:p,onMoveTask:g,lastFetchTimeMs:b,workflowStepNameLookup:v}){const[x,y]=a.useState(!1),[w,E]=a.useState(!1),[C,j]=a.useState(!1),[A,S]=a.useState(e.description||""),[z,_]=a.useState(!1),[R,B]=a.useState(e.column==="in-progress"||e.column==="triage"&&e.steps.some(D=>D.status==="done"||D.status==="skipped")),[K,L]=a.useState(null),[$,U]=a.useState(null),[G,Y]=a.useState(!1),[ee,N]=a.useState(!1),[I,T]=a.useState(()=>Date.now()),k=a.useRef(null),H=a.useRef(!1),J=a.useRef(null),ue=a.useRef(null),[fe,W]=a.useState(!1),{badgeUpdates:he,subscribeToBadge:O,unsubscribeFromBadge:ne}=Wp(n),{confirm:Q}=Ks(),ge=a.useRef(null),de=a.useRef(!1),me=a.useCallback(D=>D instanceof Element?!!D.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);a.useEffect(()=>{S(e.description||"")},[e.id,e.description]),a.useEffect(()=>{if(!G)return;const D=F=>{ue.current&&!ue.current.contains(F.target)&&Y(!1)};return document.addEventListener("click",D),()=>document.removeEventListener("click",D)},[G]),a.useEffect(()=>{if(!e.missionId){L(null);return}const D=Hc.get(e.missionId);if(D){L(D);return}let F=!1;return BN(e.missionId,n).then(ve=>{F||L(ve)}),()=>{F=!0}},[e.missionId,n]),a.useEffect(()=>{if(!e.assignedAgentId){U(null);return}const D=qc.get(e.assignedAgentId);if(D){U(D);return}U(null);let F=!1;return qN(e.assignedAgentId,n).then(ve=>{F||U(ve)}),()=>{F=!0}},[e.assignedAgentId,n]),a.useEffect(()=>{if(C&&k.current){const D=k.current;D.focus(),D.style.height="auto",D.style.height=D.scrollHeight+"px"}},[C]),a.useEffect(()=>{if(typeof IntersectionObserver>"u"){W(!0);return}const D=J.current;if(!D)return;const F=new IntersectionObserver(([ve])=>{W(ve?.isIntersecting??!0)},{rootMargin:"200px"});return F.observe(D),()=>F.disconnect()},[C,e.id]);const ie=a.useCallback(D=>{D.dataTransfer.setData("text/plain",e.id),D.dataTransfer.effectAllowed="move",y(!0)},[e.id]),Ee=a.useCallback(()=>{y(!1)},[]),Ue=a.useCallback(D=>D.dataTransfer.types.includes("Files"),[]),Te=a.useCallback(D=>{Ue(D)&&(D.preventDefault(),D.stopPropagation(),D.dataTransfer.dropEffect="copy",E(!0))},[Ue]),at=a.useCallback(D=>{Ue(D)&&(D.preventDefault(),D.stopPropagation(),E(!1))},[Ue]),et=a.useCallback(async D=>{if(!Ue(D))return;D.preventDefault(),D.stopPropagation(),E(!1);const F=Array.from(D.dataTransfer.files);for(const ve of F)try{await Nr(e.id,ve,n),r(`Attached ${ve.name} to ${e.id}`,"success")}catch(ze){r(`Failed to attach ${ve.name}: ${we(ze)}`,"error")}},[e.id,Ue,r]),Ve=a.useCallback(()=>{C||i(e)},[e,i,C]),Xe=a.useCallback(D=>{if(H.current){H.current=!1;return}me(D.target)||Ve()},[Ve,me]),De=a.useCallback(D=>{const F=D.touches[0];F&&(ge.current={x:F.clientX,y:F.clientY,time:Date.now()},de.current=!1)},[]),Be=a.useCallback(D=>{if(!ge.current)return;const F=D.touches[0];if(!F)return;const ve=Math.abs(F.clientX-ge.current.x),ze=Math.abs(F.clientY-ge.current.y);(ve>Hu||ze>Hu)&&(de.current=!0)},[]),oe=a.useCallback(D=>{if(me(D.target)||!ge.current)return;const ve=Date.now()-ge.current.time<d1,ze=!de.current;ve&&ze&&(H.current=!0,Ve()),ge.current=null,de.current=!1},[Ve,me]),Ne=a.useCallback(async(D,F)=>{D.stopPropagation();try{const ve=await wr(F,n);i(ve)}catch{r(`Failed to load dependency ${F}`,"error")}},[i,r]),se=e.status==="failed",Me=e.paused===!0,Le=VN(e.priority),pe=Le!==_s,Ae=zo(e,f,b),Je=e.column==="triage"&&e.status==="awaiting-approval",it=e.column==="archived",ye=!o&&!s&&!se&&!Me&&!Ae&&!Je&&(e.column==="in-progress"||Lu.has(e.status)),ce=!s&&!Me&&!C&&!it,Re=KN.has(e.column)&&!ye&&!Me&&!s&&l,be=!!(e.prInfo||e.issueInfo),Pe=!!(e.assignedAgentId&&$===null),Ye=a.useMemo(()=>{const D=[];return e.modelProvider&&D.push(e.modelProvider),e.validatorModelProvider&&!D.includes(e.validatorModelProvider)&&D.push(e.validatorModelProvider),e.planningModelProvider&&!D.includes(e.planningModelProvider)&&D.push(e.planningModelProvider),D},[e.modelProvider,e.validatorModelProvider,e.planningModelProvider]),$e=a.useMemo(()=>Gp(e,v),[e.steps,e.enabledWorkflowSteps,e.workflowStepResults,v]),ft=$e.total>0&&(e.status==="executing"||e.column==="in-progress");a.useEffect(()=>{if(e.column!=="in-progress"&&e.column!=="in-review")return;const D=e.status!=null&&zu.has(e.status);if(e.column==="in-progress"){const ve=lr(e,Date.now()),ze=Fu(e,Date.now()),Oe=cr(e,Date.now());if(ve==null&&ze==null&&Oe==null)return}if(!D&&e.column==="in-review"){const ve=lr(e,Date.now()),ze=cr(e,Date.now());if(ve==null&&ze==null)return}T(Date.now());const F=window.setInterval(()=>{T(Date.now())},YN);return()=>window.clearInterval(F)},[e.column,e.status,e.columnMovedAt,e.updatedAt,e.workflowStepResults,e.timedExecutionMs,e.executionStartedAt,e.executionCompletedAt]);const Z=a.useMemo(()=>{if(!JN.has(e.column))return null;if(e.status!=null&&zu.has(e.status)){const Ge=ZN(e,I);if(Ge!=null){const dt=Uu(Ge);if(dt){const Zt=Yp(e,I),Nn=Zt==null?null:Ou(Zt),un=Nn?`Execution time ${dt}. Merge phase ${Nn}`:`Execution time ${dt}. Merging`;return{label:dt,title:un,ariaLabel:un}}}}if(e.column==="in-progress"){const Ge=lr(e,I)??Fu(e,I)??cr(e,I);if(Ge==null)return null;const dt=Ou(Ge);return dt?{label:dt,title:`In progress ${dt}`,ariaLabel:`In progress ${dt}`}:null}const F=lr(e,I)??cr(e,I);if(F==null)return null;const ve=Uu(F);if(!ve)return null;const ze=XN(e);if(ze==null)return{label:ve,title:`Execution time ${ve}`,ariaLabel:`Execution time ${ve}`};const Oe=new Date(ze).toLocaleString();return{label:ve,title:`Execution time ${ve}. Completed ${Oe}`,ariaLabel:`Execution time ${ve}. Completed ${Oe}`}},[e.column,e.status,e.columnMovedAt,e.timedExecutionMs,e.updatedAt,e.workflowStepResults,e.log,e.executionStartedAt,e.executionCompletedAt,I]);a.useEffect(()=>{if(!be||!fe){ne(e.id);return}return O(e.id),()=>{ne(e.id)}},[be,fe,O,e.id,ne]);const re=he.get(`${n??"default"}:${e.id}`),je=e.column==="in-progress"||e.column==="in-review",rt=a.useMemo(()=>e.steps.map(D=>`${D.name}:${D.status}`).join("|"),[e.steps]),{stats:te}=$N(e.id,e.column,e.mergeDetails?.commitSha,n,{enabled:fe,worktree:e.worktree,stepVersion:je?rt:void 0,pollIntervalMs:je?3e4:void 0}),Ze=a.useMemo(()=>AN(e.id,n),[e.id,n]),pt=a.useMemo(()=>{const D=re?.prInfo,F=re?.timestamp,ve=Ze?.result?.prInfo,ze=Ze?.timestamp?new Date(Ze.timestamp).toISOString():void 0,Oe=e.prInfo,Ge=e.prInfo?.lastCheckedAt??e.updatedAt;let dt=Lo(D,F,Oe,Ge);const Zt=F&&F>=Ge?F:Ge;return ve&&ze&&(!Zt||ze>Zt)&&(dt=ve),dt},[re,Ze,e.prInfo,e.updatedAt]),gt=a.useMemo(()=>{const D=re?.issueInfo,F=re?.timestamp,ve=Ze?.result?.issueInfo,ze=Ze?.timestamp?new Date(Ze.timestamp).toISOString():void 0,Oe=e.issueInfo,Ge=e.issueInfo?.lastCheckedAt??e.updatedAt;let dt=Lo(D,F,Oe,Ge);const Zt=F&&F>=Ge?F:Ge;return ve&&ze&&(!Zt||ze>Zt)&&(dt=ve),dt},[re,Ze,e.issueInfo,e.updatedAt]),wt=a.useCallback(D=>{D?.stopPropagation(),!(!Re||z)&&(j(!0),S(e.description||""))},[Re,z,e.description]),Et=a.useCallback(()=>{j(!1),S(e.description||"")},[e.description]),mt=a.useCallback(()=>A!==(e.description||""),[A,e.description]),Nt=a.useCallback(async()=>{if(!(!l||z)){if(!mt()){Et();return}_(!0);try{await l(e.id,{description:A.trim()||void 0}),r(`Updated ${e.id}`,"success"),j(!1)}catch(D){r(`Failed to update ${e.id}: ${we(D)}`,"error")}finally{_(!1)}}},[l,e.id,A,z,mt,Et,r]),Tt=a.useCallback(D=>{D.key==="Enter"&&!D.shiftKey?(D.preventDefault(),Nt()):D.key==="Escape"&&(D.preventDefault(),Et())},[Nt,Et]),qt=a.useCallback(()=>{setTimeout(()=>{const D=document.activeElement;D===k.current||D?.closest(".card-editing-content")||(mt()?Nt():Et())},0)},[mt,Nt,Et]),Pt=a.useCallback(D=>{Re&&(D.stopPropagation(),wt(D))},[Re,wt]),At=a.useCallback(D=>{D.stopPropagation(),wt(D)},[wt]),Bt=a.useCallback(D=>{S(D.target.value);const F=D.target;F.style.height="auto",F.style.height=F.scrollHeight+"px"},[]),Ft=a.useCallback(D=>{D.stopPropagation(),c&&c(e.id).then(()=>{r(`Archived ${e.id}`,"success")}).catch(F=>{r(`Failed to archive ${e.id}: ${we(F)}`,"error")})},[r,c,e.id]),Dt=a.useCallback(D=>{D.stopPropagation(),u&&u(e.id).then(()=>{r(`Unarchived ${e.id}`,"success")}).catch(F=>{r(`Failed to unarchive ${e.id}: ${we(F)}`,"error")})},[r,u,e.id]),Mt=a.useCallback(async D=>{if(D.stopPropagation(),!(!d||!await Q({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0})))try{await d(e.id),r(`Deleted ${e.id}`,"success")}catch(ve){const ze=i1(ve);if(!ze||ze.dependentIds.length===0){r(`Failed to delete ${e.id}: ${we(ve)}`,"error");return}const Oe=ze.dependentIds.join(", ");if(!await Q({title:"Force Delete Task",message:`${e.id} is a dependency of ${Oe}.
622
+
623
+ 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(dt){r(`Failed to delete ${e.id}: ${we(dt)}`,"error")}}},[r,Q,d,e.id]),St=a.useCallback(D=>{D.stopPropagation(),h?.(e,"changes")},[e,h]),Wt=a.useCallback(D=>{D.stopPropagation(),B(F=>!F)},[]),It=a.useCallback(D=>{D.stopPropagation(),e.missionId&&p&&p(e.missionId)},[e.missionId,p]),Yt=a.useCallback(D=>{D.stopPropagation(),Y(F=>!F)},[]),Rt=a.useCallback((D,F)=>{D.stopPropagation(),Y(!1),g&&g(e.id,F).then(()=>{r(`Moved ${e.id} to ${Bn[F]}`,"success")}).catch(ve=>{r(`Failed to move ${e.id}: ${we(ve)}`,"error")})},[r,g,e.id]),xe=a.useCallback(async D=>{if(D.stopPropagation(),!(!m||ee)){N(!0);try{await m(e.id)}catch(F){r(`Failed to retry ${e.id}: ${we(F)}`,"error")}finally{N(!1)}}},[r,ee,m,e.id]),Fe=`card${x?" dragging":""}${s?" queued":""}${ye?" agent-active":""}${se?" failed":""}${Me?" paused":""}${Ae?" stuck":""}${Je?" awaiting-approval":""}${w?" file-drop-target":""}${C?" card-editing":""}${z?" card-saving":""}`,ct=(()=>{if(e.column==="in-progress"){const D=te?.filesChanged,F=D==null||D===0?e.modifiedFiles?.length:void 0,ve=D!=null&&D>0?D:F;return ve==null||ve===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:St,disabled:!h,children:[t.jsx(Xn,{size:12}),t.jsxs("span",{children:[ve," ",ve===1?"file":"files"," changed"]})]})}if(e.column==="in-review"){const D=te?.filesChanged,F=D==null||D===0?e.modifiedFiles?.length:void 0,ve=D!=null&&D>0?D:F;return ve==null||ve===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:St,disabled:!h,children:[t.jsx(Xn,{size:12}),t.jsxs("span",{children:[ve," ",ve===1?"file":"files"," changed"]})]})}if(e.column==="done"){const D=te?.filesChanged,F=e.mergeDetails?.filesChanged,ve=D??F;if(ve!=null&&ve>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:St,disabled:!h,children:[t.jsx(Xn,{size:12}),t.jsxs("span",{children:[ve," ",ve===1?"file":"files"," changed"]})]});const ze=e.modifiedFiles?.length;if(ze!=null&&ze>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:St,disabled:!h,children:[t.jsx(Xn,{size:12}),t.jsxs("span",{children:[ze," ",ze===1?"file":"files"," changed"]})]})}return null})();return C?t.jsx("div",{ref:J,className:Fe,"data-id":e.id,onDoubleClick:Pt,children:t.jsxs("div",{className:"card-editing-content",children:[t.jsx("textarea",{ref:k,className:"card-edit-desc-textarea",placeholder:"Task description",value:A,onChange:Bt,onKeyDown:Tt,onBlur:qt,disabled:z,rows:4}),z&&t.jsxs("div",{className:"card-edit-loading",children:[t.jsx("span",{className:"card-edit-loading-spinner"}),t.jsx("span",{className:"card-edit-loading-text",children:"Saving..."})]})]})}):t.jsxs("div",{ref:J,className:Fe,"data-id":e.id,draggable:ce,onDragStart:ce?ie:void 0,onDragEnd:ce?Ee:void 0,onDragOver:Te,onDragLeave:at,onDrop:et,onClick:Xe,onTouchStart:De,onTouchMove:Be,onTouchEnd:oe,onDoubleClick:Pt,children:[t.jsxs("div",{className:"card-header",children:[t.jsx("span",{className:"card-id",children:e.id}),Me&&t.jsx("span",{className:"card-status-badge paused",children:"paused"}),!Me&&e.status&&e.status!=="queued"&&t.jsx("span",{className:`card-status-badge card-status-badge--${e.column}${Je?" awaiting-approval":""}${Lu.has(e.status)?" pulsing":""}${se?" failed":""}${Ae?" stuck":""}`,children:Ae?"Stuck":Je?"Awaiting Approval":e.status}),Ae&&(Me||!e.status||e.status==="queued")&&t.jsx("span",{className:"card-status-badge stuck",children:"Stuck"}),be&&t.jsx(Vp,{prInfo:pt,issueInfo:gt}),pe&&t.jsx("span",{className:`card-priority-badge card-priority-badge--${Le}`,children:Le}),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:It,title:`Mission: ${K??e.missionId}`,role:p?"button":void 0,tabIndex:p?0:void 0,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[t.jsx(ws,{size:11}),HN(K??e.missionId)]}),t.jsxs("div",{className:"card-header-actions",children:[Re&&t.jsx("button",{className:"card-edit-btn",onClick:At,title:"Edit task","aria-label":"Edit task",children:t.jsx(hs,{size:12})}),e.column==="triage"&&d&&t.jsx("button",{className:"card-delete-btn",onClick:Mt,title:"Delete task","aria-label":"Delete task",children:t.jsx(an,{size:12})}),e.column==="done"&&c&&t.jsx("button",{className:"card-archive-btn",onClick:Ft,title:"Archive task","aria-label":"Archive task",children:"Archive"}),e.column==="archived"&&u&&t.jsx("button",{className:"card-unarchive-btn",onClick:Dt,title:"Unarchive task","aria-label":"Unarchive task",children:"Unarchive"}),e.column==="in-progress"&&g&&t.jsxs("div",{className:"card-send-back",ref:ue,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:Yt,title:"Send back","aria-label":"Send back","aria-haspopup":"menu","aria-expanded":G,children:["Send back",t.jsx(Xt,{size:10})]}),G&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:Uc["in-progress"].filter(D=>D!=="in-review").map(D=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:F=>Rt(F,D),children:Bn[D]},D))})]}),e.column==="in-review"&&g&&t.jsxs("div",{className:"card-send-back",ref:ue,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:Yt,title:"Move task","aria-label":"Move task","aria-haspopup":"menu","aria-expanded":G,children:["Move",t.jsx(Xt,{size:10})]}),G&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:Uc["in-review"].map(D=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:F=>Rt(F,D),children:D==="done"?"Done (no merge)":Bn[D]},D))})]}),e.size&&t.jsx("span",{className:`card-size-badge size-${e.size.toLowerCase()}`,children:e.size})]})]}),se&&e.error&&t.jsxs("div",{className:"card-error",title:e.error,children:[t.jsx("span",{className:"card-error-icon",children:"⚠"}),t.jsx("span",{className:"card-error-text",children:e.error.length>60?e.error.slice(0,60)+"…":e.error}),m&&t.jsxs("button",{type:"button",className:"btn btn-sm card-error-retry-btn",onClick:xe,disabled:ee,children:[t.jsx(cv,{size:12}),ee?"Retrying…":"Retry"]})]}),t.jsx("div",{className:"card-title",title:e.title||e.description||void 0,children:Vu(e.title,qu)||Vu(e.description,qu)||e.id}),ft&&(()=>{const D=$e.completed/$e.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:`${D}%`,backgroundColor:GN[e.column]}})}),t.jsxs("span",{className:"card-progress-label",children:[$e.completed,"/",$e.total]})]}),t.jsxs("button",{type:"button",className:"card-steps-toggle",onClick:Wt,"aria-expanded":R,"aria-label":R?"Hide steps":"Show steps",children:[t.jsxs("span",{children:[$e.total," step",$e.total===1?"":"s"]}),t.jsx(Xt,{size:14,className:`card-steps-toggle-icon${R?" expanded":""}`})]}),R&&t.jsx("div",{className:"card-steps-list",children:$e.items.map(F=>{const ve=F.source==="workflow"&&F.status==="failed";return t.jsxs("div",{className:"card-step-item",children:[t.jsx("span",{className:`card-step-dot card-step-dot--${F.status}${ve?" card-step-dot--workflow-failed":""}`,"aria-hidden":"true"}),t.jsx("span",{className:`card-step-name${F.status==="done"?" completed":""}`,children:F.name}),F.source==="workflow"&&t.jsx("span",{className:`card-step-workflow-badge card-step-workflow-badge--${F.phase}`,title:"Workflow check",children:"workflow"})]},F.id)})})]})})(),(ct||Z)&&t.jsxs("div",{className:"card-footer-row",children:[ct,Z&&t.jsxs("span",{className:"card-time-indicator",title:Z.title,"aria-label":Z.ariaLabel,children:[t.jsx(Ei,{size:12}),t.jsx("span",{children:Z.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(D=>t.jsxs("span",{className:"card-dep-badge clickable",onClick:F=>void Ne(F,D),title:`Click to view ${D}`,children:[t.jsx(ga,{size:12,style:{verticalAlign:"middle"}})," ",D]},D))}),e.blockedBy&&t.jsxs("span",{className:"card-scope-badge","data-tooltip":`Blocked by ${e.blockedBy} (file overlap)`,children:[t.jsx(Hi,{size:12,style:{verticalAlign:"middle"}})," ",e.blockedBy]}),(s||e.status==="queued")&&e.column!=="in-progress"&&t.jsxs("span",{className:"queued-badge",children:[t.jsx(Ei,{size:12,style:{verticalAlign:"middle"}})," Queued"]})]}),(e.assignedAgentId||Ye.length>0)&&t.jsxs("div",{className:"card-agent-row",children:[Ye.length>0&&t.jsx("span",{className:"card-provider-icons","data-testid":"card-provider-icons",children:Ye.map(D=>t.jsx(An,{provider:D,size:"sm"},D))}),e.assignedAgentId&&t.jsxs("span",{className:`card-agent-badge${Pe?" card-agent-badge--loading":""}`,title:`Assigned to ${$??e.assignedAgentId}`,children:[t.jsx(Sn,{size:11}),t.jsx("span",{className:"card-agent-badge-text",children:WN($??e.assignedAgentId,15)})]})]}),t.jsx(al,{slotId:"task-card-badge",projectId:n})]})}const Hu=10,d1=300,qu=140;function Vu(e,n){return e?e.length>n?e.slice(0,n)+"…":e:""}const Fo=a.memo(c1,l1);Fo.displayName="TaskCard";function u1({label:e,activeTasks:n,queuedTasks:s,projectId:i,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:u,onOpenDetailWithTab:d,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p}){return t.jsxs("div",{className:"worktree-group",children:[t.jsxs("div",{className:"worktree-group-header",children:[t.jsx("span",{className:"worktree-icon",children:e==="Up Next"||e==="Unassigned"?t.jsx(Pb,{size:14}):t.jsx(Ws,{size:14})}),t.jsx("span",{className:"worktree-label",children:e})]}),n.map(g=>t.jsx(Fo,{task:g,projectId:i,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:u,onOpenDetailWithTab:d,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p},g.id)),s.map(g=>t.jsx(Fo,{task:g,projectId:i,queued:!0,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:u,onOpenDetailWithTab:d,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p},g.id))]})}const Qp=a.memo(u1);Qp.displayName="WorktreeGroup";function Wu(e){return e.toLowerCase().replace(/[-_./]/g,"")}function m1(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 h1(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 p1(e,n){const s=Wu(e),i=Wu(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&&m1(s,o)||s.length>=4&&h1(s,o,1))return!0;return!1}function f1(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=>p1(o,r))})}function Zn({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:f="No change"}){const[p,g]=a.useState(!1),[b,v]=a.useState(""),[x,y]=a.useState(0),[w,E]=a.useState(null),[C,j]=a.useState(null),A=a.useRef(null),S=a.useRef(null),z=a.useRef(null),_=a.useRef(null),R=a.useRef(null),B=a.useMemo(()=>f1(e,b),[e,b]),K=a.useMemo(()=>B.reduce((Q,ge)=>((Q[ge.provider]??=[]).push(ge),Q),{}),[B]),L=a.useMemo(()=>{const Q=[];for(const ge of d){const de=ge.indexOf("/");if(de===-1)continue;const me=ge.slice(0,de),ie=ge.slice(de+1),Ee=B.find(Ue=>Ue.provider===me&&Ue.id===ie);Ee&&Q.push({model:Ee,fullId:ge})}return Q},[d,B]),$=a.useMemo(()=>{const Q=Object.entries(K),ge=new Set(c);return Q.sort(([de],[me])=>{const ie=ge.has(de),Ee=ge.has(me);if(ie&&!Ee)return-1;if(!ie&&Ee)return 1;if(ie&&Ee){const Ue=c.indexOf(de),Te=c.indexOf(me);if(Ue!==Te)return Ue-Te}return de.localeCompare(me)})},[K,c]),U=typeof h=="string"&&h.length>0,G=a.useMemo(()=>{if(!n||U&&n===h)return null;const Q=n.indexOf("/");return Q===-1?null:n.slice(0,Q)},[U,h,n]),Y=a.useMemo(()=>{const Q=[];return U&&Q.push({type:"no-change",value:h,label:f}),Q.push({type:"default",value:"",label:"Use default"}),Q},[U,f,h]),ee=a.useMemo(()=>{const Q=[...Y];for(const{model:ge,fullId:de}of L)Q.push({type:"favorite",value:de,label:ge.name,provider:ge.provider});return $.forEach(([ge,de])=>{Q.push({type:"provider",value:`__group_${ge}`,label:ge,provider:ge}),de.forEach(me=>{Q.push({type:"model",value:`${me.provider}/${me.id}`,label:me.name,provider:me.provider})})}),Q},[L,$,Y]),N=a.useMemo(()=>{if(U&&n===h)return f;if(!n)return"Use default";const Q=n.indexOf("/");if(Q===-1)return n;const ge=n.slice(0,Q),de=n.slice(Q+1);return e.find(ie=>ie.provider===ge&&ie.id===de)?.name||n},[U,f,h,n,e]),I=a.useMemo(()=>ee.findIndex(Q=>Q.value===n),[ee,n]),T=a.useCallback(()=>{const Q=window.visualViewport;return Q&&Q.height>0&&Q.width>0?{width:Q.width,height:Q.height,offsetTop:Q.offsetTop,offsetLeft:Q.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),k=a.useCallback(()=>{const{height:Q}=T(),ge=typeof window.matchMedia=="function",de=ge?window.matchMedia("(max-width: 640px)").matches:!1,me=ge?window.matchMedia("(max-width: 768px)").matches:!1;return Q<=0?320:de?Math.min(Q*.6,360):me?Math.min(Q*.7,420):320},[T]),H=a.useCallback(()=>{const Q=S.current;if(!Q)return;const ge=Q.getBoundingClientRect(),{width:de,height:me,offsetTop:ie,offsetLeft:Ee}=T(),Ue=16,Te=16,at=4,et=k(),Ve=ge.bottom-ie,Xe=ge.top-ie,De=ge.left-Ee,Be=me-Ve,oe=Xe,Ne=Math.max(Be-Te-at,160),se=Math.max(oe-Te-at,160),Me=Be<et&&oe>Be,Le=Math.max(Math.min(Me?se:Ne,et),160),pe=Math.min(ge.width,de-Ue*2),Ae=Math.min(Math.max(De,Ue),de-Ue-pe)+Ee,Je=Me?Math.max(Te+ie,Xe-Le-at+ie):Math.min(Ve+at+ie,me+ie-Te-Le);E({top:Je,left:Ae,width:pe,maxHeight:Le})},[T,k]);a.useEffect(()=>{j(document.body)},[]);const J=a.useRef(!1);a.useEffect(()=>{if(!p){J.current=!1;return}if(J.current||ee.length===0)return;const Q=ee.findIndex((ge,de)=>de>=(I>=0?I:0)&&ge.type!=="provider");y(Q>=0?Q:0),J.current=!0},[p,ee,I]),a.useEffect(()=>{p&&J.current&&(y(0),R.current&&(R.current.scrollTop=0))},[b,p]),a.useEffect(()=>{if(!p)return;H();const Q=requestAnimationFrame(()=>_.current?.focus());return()=>cancelAnimationFrame(Q)},[p,H]),a.useEffect(()=>{if(!p)return;const Q=()=>H();window.addEventListener("resize",Q),window.addEventListener("scroll",Q,!0);const ge=window.visualViewport;return ge&&(ge.addEventListener("resize",Q),ge.addEventListener("scroll",Q)),()=>{window.removeEventListener("resize",Q),window.removeEventListener("scroll",Q,!0),ge&&(ge.removeEventListener("resize",Q),ge.removeEventListener("scroll",Q))}},[p,H]),a.useEffect(()=>{if(!p)return;const Q=ge=>{const de=ge.target,me=A.current?.contains(de),ie=z.current?.contains(de);!me&&!ie&&(g(!1),v(""))};return document.addEventListener("mousedown",Q),()=>document.removeEventListener("mousedown",Q)},[p]);const ue=a.useCallback(Q=>{switch(Q.key){case"ArrowDown":if(Q.preventDefault(),!p)g(!0);else{let ge=x;for(let de=1;de<=ee.length;de++){const me=(x+de)%ee.length;if(ee[me]?.type!=="provider"){ge=me;break}}y(ge)}break;case"ArrowUp":if(Q.preventDefault(),p){let ge=x;for(let de=1;de<=ee.length;de++){const me=(x-de+ee.length)%ee.length;if(ee[me]?.type!=="provider"){ge=me;break}}y(ge)}break;case"Enter":if(Q.preventDefault(),p){const ge=ee[x];ge&&ge.type!=="provider"&&ge.type!=="favorite"&&(s(ge.value),g(!1),v(""))}else g(!0);break;case"Escape":Q.preventDefault(),g(!1),v("");break;case"Tab":p&&(g(!1),v(""));break}},[p,x,ee,s]),fe=a.useCallback(Q=>{s(Q),g(!1),v("")},[s]),W=a.useCallback(()=>{v(""),_.current?.focus()},[]),he=a.useCallback(()=>{r||g(Q=>!Q)},[r]);a.useEffect(()=>{if(p&&R.current){const Q=R.current.querySelector(`[data-index="${x}"]`);Q&&typeof Q.scrollIntoView=="function"&&Q.scrollIntoView({block:"nearest"})}},[x,p]);const O=b.length>0,ne=p&&w?t.jsxs("div",{ref:z,className:"model-combobox-dropdown model-combobox-dropdown--portal",role:"listbox","data-testid":"model-combobox-portal",onKeyDown:ue,style:{top:`${w.top}px`,left:`${w.left}px`,width:`${w.width}px`,maxHeight:`${w.maxHeight}px`},children:[t.jsxs("div",{className:"model-combobox-search-wrapper",children:[t.jsx("input",{ref:_,type:"text",className:"model-combobox-search",placeholder:"Filter models…",value:b,onChange:Q=>v(Q.target.value),onClick:Q=>Q.stopPropagation()}),O&&t.jsx("button",{type:"button",className:"model-combobox-clear",onClick:W,"aria-label":"Clear filter",children:"×"})]}),t.jsxs("div",{className:"model-combobox-results-count",children:[B.length," model",B.length!==1?"s":""]}),t.jsxs("div",{ref:R,className:"model-combobox-list",children:[Y.map((Q,ge)=>t.jsx("div",{"data-index":ge,className:`model-combobox-option ${x===ge?"model-combobox-option--highlighted":""} ${n===Q.value?"model-combobox-option--selected":""}`,onClick:()=>fe(Q.value),onMouseEnter:()=>y(ge),role:"option","aria-selected":n===Q.value,children:t.jsx("span",{className:"model-combobox-option-text model-combobox-option-text--default",children:Q.label})},`${Q.type}-${Q.value}`)),L.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"model-combobox-divider"}),L.map(({model:Q,fullId:ge},de)=>{const me=de+Y.length,ie=x===me,Ee=n===ge;return t.jsxs("div",{"data-index":me,className:`model-combobox-option model-combobox-option--favorite ${ie?"model-combobox-option--highlighted":""} ${Ee?"model-combobox-option--selected":""}`,onClick:()=>fe(ge),onMouseEnter:()=>y(me),role:"option","aria-selected":Ee,children:[t.jsxs("span",{className:"model-combobox-option-main",children:[t.jsx("span",{className:"model-combobox-option-icon",children:t.jsx(An,{provider:Q.provider,size:"sm"})}),t.jsx("span",{className:"model-combobox-option-text",children:Q.name})]}),t.jsx("span",{className:"model-combobox-option-id",children:Q.id}),m&&t.jsx("button",{type:"button",className:"model-combobox-option-favorite model-combobox-option-favorite--active",onClick:Ue=>{Ue.stopPropagation(),m(ge)},title:"Remove from favorites","aria-label":`Remove ${Q.name} from favorites`,children:"★"})]},ge)}),t.jsx("div",{className:"model-combobox-divider"})]}),$.map(([Q,ge])=>{const de=ee.findIndex(Ee=>Ee.value===`__group_${Q}`),me=c.includes(Q),ie=ge.filter(Ee=>{const Ue=`${Ee.provider}/${Ee.id}`;return!d.includes(Ue)});return ie.length===0?null:t.jsxs("div",{className:"model-combobox-group",children:[t.jsxs("div",{className:"model-combobox-optgroup","data-index":de,children:[t.jsx(An,{provider:Q,size:"sm"}),t.jsx("span",{className:"model-combobox-optgroup-text",children:Q}),u&&t.jsx("button",{type:"button",className:`model-combobox-optgroup-favorite ${me?"model-combobox-optgroup-favorite--active":""}`,onClick:Ee=>{Ee.stopPropagation(),u(Q)},title:me?"Remove from favorites":"Add to favorites","aria-label":me?`Remove ${Q} from favorites`:`Add ${Q} to favorites`,children:"★"})]}),ie.map(Ee=>{const Ue=`${Ee.provider}/${Ee.id}`,Te=ee.findIndex(Xe=>Xe.value===Ue),at=x===Te,et=n===Ue,Ve=d.includes(Ue);return t.jsxs("div",{"data-index":Te,className:`model-combobox-option ${at?"model-combobox-option--highlighted":""} ${et?"model-combobox-option--selected":""}`,onClick:()=>fe(Ue),onMouseEnter:()=>y(Te),role:"option","aria-selected":et,children:[t.jsx("span",{className:"model-combobox-option-text",children:Ee.name}),t.jsx("span",{className:"model-combobox-option-id",children:Ee.id}),m&&t.jsx("button",{type:"button",className:`model-combobox-option-favorite ${Ve?"model-combobox-option-favorite--active":""}`,onClick:Xe=>{Xe.stopPropagation(),m(Ue)},title:Ve?"Remove from favorites":"Add to favorites","aria-label":Ve?`Remove ${Ee.name} from favorites`:`Add ${Ee.name} to favorites`,children:Ve?"★":"☆"})]},Ue)})]},Q)}),B.length===0&&O&&t.jsxs("div",{className:"model-combobox-no-results",children:["No models match '",b,"'"]})]})]}):null;return t.jsxs(t.Fragment,{children:[t.jsx("div",{ref:A,className:"model-combobox",onKeyDown:ue,children:t.jsxs("button",{ref:S,type:"button",id:o,className:"model-combobox-trigger",onClick:he,disabled:r,"aria-haspopup":"listbox","aria-expanded":p,"aria-label":l,children:[G&&t.jsx("span",{className:"model-combobox-trigger-icon",children:t.jsx(An,{provider:G,size:"sm"})}),t.jsx("span",{className:"model-combobox-trigger-text",children:N||i}),t.jsx("span",{className:"model-combobox-trigger-arrow",children:"▼"})]})}),C&&ne?ma.createPortal(ne,C):null]})}function wd(e,n){return typeof n!="string"||n.length===0?e:`kb:${n}:${e}`}function Wn(e,n){return typeof window>"u"?null:window.localStorage.getItem(wd(e,n))}function fs(e,n,s){typeof window>"u"||window.localStorage.setItem(wd(e,s),n)}function Er(e,n){typeof window>"u"||window.localStorage.removeItem(wd(e,n))}const g1=1e4,b1=1e3;function ol(){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 Do();n(p)}catch(p){o(p instanceof Error?p.message:"Failed to fetch nodes")}},[]);a.useEffect(()=>{let p=!1;async function g(){i(!0);try{const v=await Do();p||(n(v),o(null))}catch(v){p||o(v instanceof Error?v.message:"Failed to fetch nodes")}finally{p||i(!1)}}g();const b=()=>{if(document.visibilityState!=="visible")return;const v=Date.now();v-c.current<b1||(c.current=v,u())};return document.addEventListener("visibilitychange",b),()=>{p=!0,document.removeEventListener("visibilitychange",b)}},[u]),a.useEffect(()=>{if(!s)return l.current=setInterval(()=>{u()},g1),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async p=>{const g=await jk(p);return n(b=>[...b,g]),g},[]),m=a.useCallback(async(p,g)=>{const b=await kk(p,g);return n(v=>v.map(x=>x.id===p?b:x)),b},[]),h=a.useCallback(async p=>{await wk(p),n(g=>g.filter(b=>b.id!==p))},[]),f=a.useCallback(async p=>{const g=await Nk(p);n(b=>b.map(v=>v.id===p?{...v,status:g.status,updatedAt:g.checkedAt}:v))},[]);return{nodes:e,loading:s,error:r,refresh:u,register:d,update:m,unregister:h,healthCheck:f}}const qa="kb-quick-entry-text",x1=["image/png","image/jpeg","image/gif","image/webp"];function v1(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function Rl(e,n){return e&&n?`${e}/${n}`:""}function Tl(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 Xp({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[f,p]=a.useState(()=>typeof window<"u"&&Wn(qa,l)||""),[g,b]=a.useState(!1),[v,x]=a.useState(!1),[y,w]=a.useState(!1),E=a.useRef(null),C=a.useRef(null),j=a.useRef(!1),A=a.useRef(l),[S,z]=a.useState([]),_=a.useRef([]),[R,B]=a.useState([]),[K,L]=a.useState(!1),[$,U]=a.useState(""),[G,Y]=a.useState(null),[ee,N]=a.useState([]),[I,T]=a.useState(void 0),[k,H]=a.useState(!1),[J,ue]=a.useState(!1),[fe,W]=a.useState(!1),[he,O]=a.useState(!1),[ne,Q]=a.useState(null),[ge,de]=a.useState(void 0),[me,ie]=a.useState(void 0),[Ee,Ue]=a.useState(void 0),[Te,at]=a.useState(void 0),[et,Ve]=a.useState(void 0),[Xe,De]=a.useState(void 0),Be=a.useRef(null),oe=a.useRef(null),Ne=a.useRef(null),se=a.useRef(null),Me=a.useRef(null),Le=a.useRef(null),[pe,Ae]=a.useState(null),[Je,it]=a.useState(null),[ye,ce]=a.useState(null),Re=a.useRef(null),be=a.useRef(null),[Pe,Ye]=a.useState(null),[$e]=a.useState(()=>typeof document<"u"?document.body:null),[ft,Z]=a.useState(!1),[re,je]=a.useState(null),[rt,te]=a.useState(i??[]),[Ze,pt]=a.useState([]),[gt,wt]=a.useState([]),[Et,mt]=a.useState(null),[Nt,Tt]=a.useState(void 0),[qt,Pt]=a.useState(!1),[At,Bt]=a.useState(void 0),{nodes:Ft}=ol(),[Dt,Mt]=a.useState(!1),[St,Wt]=a.useState(!1),It=a.useRef(null),Yt=a.useRef(null),[Rt,xe]=a.useState(null),Fe=u??Ze,ct=d??gt,D=!e;a.useEffect(()=>{if(i)te(i),Z(!1),je(null);else{let ae=!1;return Z(!0),je(null),bs().then(_e=>{ae||(te(_e.models),u||pt(_e.favoriteProviders),d||wt(_e.favoriteModels))}).catch(_e=>{ae||je(we(_e)||"Failed to load models")}).finally(()=>{ae||Z(!1)}),nl(l).then(_e=>{ae||mt(_e)}).catch(()=>{}),()=>{ae=!0}}},[i,u,d,l]);const F=Rl(ge,me),ve=Rl(Ee,Te),ze=Rl(et,Xe),Oe=!!(ge&&me),Ge=!!(Ee&&Te),dt=!!(et&&Xe),Zt=Number(Oe)+Number(Ge)+Number(dt),Nn=Nt?Et?.modelPresets?.find(ae=>ae.id===Nt)?.name??"Models":Zt>0?`${Zt} model${Zt===1?"":"s"}`:"Models",un=a.useCallback((ae,_e)=>{if(!ae||!_e)return"Using default";const tt=rt.find(jt=>jt.provider===ae&&jt.id===_e);return tt?`${tt.provider}/${tt.id}`:`${ae}/${_e}`},[rt]);a.useEffect(()=>{p(Wn(qa,l)||"")},[l]),a.useEffect(()=>{typeof window<"u"&&fs(qa,f,l)},[f,l]),a.useEffect(()=>{A.current!==l&&(A.current=l,N([]),T(void 0),Y(null),H(!1),Ae(null))},[l]),a.useEffect(()=>{typeof window<"u"&&localStorage.removeItem("kb-quick-entry-expanded")},[]),a.useEffect(()=>{_.current=S},[S]),a.useEffect(()=>()=>{_.current.forEach(ae=>URL.revokeObjectURL(ae.previewUrl))},[]);const Kt=a.useCallback(()=>{const ae=E.current;if(!ae)return;ae.style.height="auto";const _e=Math.min(ae.scrollHeight,200);ae.style.height=`${_e}px`},[]);a.useEffect(()=>{v&&Kt()},[f,v,Kt]),a.useEffect(()=>{if(!g&&f===""&&E.current){const ae=setTimeout(()=>{E.current?.focus()},0);return()=>clearTimeout(ae)}},[g,f]),a.useEffect(()=>{K||U("")},[K]),a.useEffect(()=>{if(!Dt)return;const ae=_e=>{const tt=_e.target,jt=It.current?.contains(tt),kt=Yt.current?.contains(tt);!jt&&!kt&&Mt(!1)};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[Dt]),a.useEffect(()=>{if(!he)return;const ae=_e=>{const tt=_e.target,jt=Be.current?.contains(tt),kt=oe.current?.contains(tt),gn=tt instanceof Element&&tt.closest?.(".model-combobox-dropdown--portal")!=null;!jt&&!kt&&!gn&&(O(!1),Q(null))};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[he]),a.useEffect(()=>{if(!J)return;const ae=_e=>{const tt=_e.target;Me.current?.contains(tt)||Le.current?.contains(tt)||(ue(!1),it(null))};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[J]),a.useEffect(()=>{if(!k)return;const ae=_e=>{const tt=_e.target;Ne.current?.contains(tt)||se.current?.contains(tt)||(H(!1),Ae(null))};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[k]);const mn=a.useCallback(()=>{S.forEach(ae=>URL.revokeObjectURL(ae.previewUrl)),z([]),C.current&&(C.current.value=""),p(""),B([]),Y(null),H(!1),Ae(null),ue(!1),it(null),de(void 0),ie(void 0),Ue(void 0),at(void 0),Ve(void 0),De(void 0),Tt(void 0),Pt(!1),Bt(void 0),L(!1),O(!1),ce(null),Q(null),Mt(!1),Wt(!1),x(!1),w(!1),j.current=!0,E.current&&(E.current.style.height="auto"),typeof window<"u"&&Er(qa,l)},[S,l]),ke=a.useCallback(ae=>{if(!ae||ae.length===0)return;const _e=[];for(let tt=0;tt<ae.length;tt++){const jt=ae[tt];x1.includes(jt.type)&&_e.push({file:jt,previewUrl:URL.createObjectURL(jt)})}_e.length>0&&z(tt=>[...tt,..._e])},[]),ut=a.useCallback(ae=>{g||ke(ae.clipboardData?.files)},[ke,g]),Lt=a.useCallback(ae=>{z(_e=>{const tt=_e[ae];return tt&&URL.revokeObjectURL(tt.previewUrl),_e.filter((jt,kt)=>kt!==ae)})},[]),En=a.useCallback(async()=>{const ae=f.trim();if(!ae||g||!e)return;const _e=f;b(!0),p("");try{const tt=await e({description:ae,column:"triage",dependencies:R.length?R:void 0,...G?{assignedAgentId:G}:{},modelPresetId:Nt,modelProvider:Oe?ge:void 0,modelId:Oe?me:void 0,validatorModelProvider:Ge?Ee:void 0,validatorModelId:Ge?Te:void 0,planningModelProvider:dt?et:void 0,planningModelId:dt?Xe:void 0,...qt?{executionMode:"fast"}:{},nodeId:At});if(tt&&S.length>0){const jt=[];for(const kt of S)try{await Nr(tt.id,kt.file,l)}catch{jt.push(kt.file.name)}jt.length>0&&n(`Failed to upload: ${jt.join(", ")}`,"error")}mn()}catch(tt){p(_e),n(we(tt)||"Failed to create task","error")}finally{b(!1)}},[f,g,e,R,G,Oe,ge,me,Ge,Ee,Te,dt,et,Xe,S,l,n,mn,qt,At]),hn=a.useCallback(ae=>{if(ae.key==="Enter"){if(ae.shiftKey&&v)return;ae.preventDefault(),En()}else if(ae.key==="Escape"){if(ae.preventDefault(),ne){Q(null);return}if(he){O(!1),ce(null);return}if(K){L(!1);return}if(Dt){Mt(!1);return}if(J){ue(!1),it(null);return}if(k){H(!1),Ae(null);return}f.trim()&&(p(""),E.current&&(E.current.style.height="auto"),typeof window<"u"&&Er(qa,l)),x(!1),w(!1),E.current?.blur()}},[En,f,v,K,k,J,he,ne,Dt,l,w]),Rn=a.useCallback(()=>{j.current&&(j.current=!1)},[]),is=a.useCallback(()=>{c&&x(!0)},[c]),Dn=a.useCallback(ae=>{B(_e=>_e.includes(ae)?_e.filter(tt=>tt!==ae):[..._e,ae])},[]),nn=a.useCallback(()=>{const ae=window.visualViewport;return ae&&ae.width>0&&ae.height>0?{width:ae.width,height:ae.height,offsetTop:ae.offsetTop,offsetLeft:ae.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),cn=a.useCallback(()=>{const ae=Be.current;if(!ae)return;const _e=ae.getBoundingClientRect(),{width:tt,height:jt,offsetTop:kt,offsetLeft:gn}=nn(),sn=16,en=16,nt=4,$t=tt<=768,Tn=Math.min($t?jt*.6:jt*.5,360),qn=Math.max(_e.width*1.35,320),On=$t?Math.min(tt-sn*2,360):qn,Pn=Math.min(On,Math.max(tt-sn*2,240)),Kn=_e.top-kt,xs=_e.bottom-kt,In=_e.left-gn,Gn=jt-xs,vs=Kn,zs=Math.max(Gn-en-nt,160),ys=Math.max(vs-en-nt,160),$n=Gn<Tn&&vs>Gn,Jn=Math.max(Math.min($n?ys:zs,Tn),160),Fs=Math.min(Math.max(In,sn),tt-sn-Pn)+gn,Ri=$n?Math.max(en+kt,Kn-Jn-nt+kt):Math.min(xs+nt+kt,jt+kt-en-Jn);ce({top:Ri,left:Fs,width:Pn,maxHeight:Jn})},[nn]),Hn=a.useCallback(()=>{const ae=It.current?.querySelector(".refine-button");if(!ae)return;const _e=ae.getBoundingClientRect(),{width:tt,height:jt,offsetTop:kt,offsetLeft:gn}=nn(),sn=8,en=12,nt=4,$t=Math.min(200,Math.max(jt-en*2,160)),Tn=Math.min(200,tt-sn*2),qn=_e.top-kt,On=_e.bottom-kt,Pn=_e.left-gn,Kn=jt-On,xs=qn,In=Kn<$t&&xs>Kn,Gn=Math.min(Math.max(Pn,sn),tt-sn-Tn)+gn,vs=In?Math.max(en+kt,qn-$t-nt+kt):Math.min(On+nt+kt,jt+kt-en-$t);xe({top:vs,left:Gn})},[nn]),fn=a.useCallback(()=>{const ae=Re.current;if(!ae)return;const _e=ae.getBoundingClientRect(),{width:tt,height:jt,offsetTop:kt,offsetLeft:gn}=nn(),sn=16,en=16,nt=4,$t=tt<=768,Tn=Math.min($t?jt*.6:jt*.5,320),qn=$t?Math.min(tt-sn*2,360):Math.max(_e.width,280),On=Math.min(qn,Math.max(tt-sn*2,240)),Pn=_e.top-kt,Kn=_e.bottom-kt,xs=_e.left-gn,In=jt-Kn,Gn=Pn,vs=Math.max(In-en-nt,200),zs=Math.max(Gn-en-nt,200),ys=In<Tn&&Gn>In,$n=Math.max(Math.min(ys?zs:vs,Tn),200),Jn=Math.min(Math.max(xs,sn),tt-sn-On)+gn,Fs=ys?Math.max(en+kt,Pn-$n-nt+kt):Math.min(Kn+nt+kt,jt+kt-en-$n);Ye({top:Fs,left:Jn,width:On,maxHeight:$n})},[nn]),dn=a.useCallback(()=>{const ae=Ne.current?.querySelector("button");if(!ae)return;const _e=ae.getBoundingClientRect(),{width:tt,height:jt,offsetTop:kt,offsetLeft:gn}=nn(),sn=16,en=16,nt=4,$t=tt<=768,Tn=Math.min($t?jt*.6:jt*.5,320),qn=$t?Math.min(tt-sn*2,280):Math.max(_e.width,240),On=Math.min(qn,Math.max(tt-sn*2,200)),Pn=_e.top-kt,Kn=_e.bottom-kt,xs=_e.left-gn,In=jt-Kn,Gn=Pn,vs=Math.max(In-en-nt,160),zs=Math.max(Gn-en-nt,160),ys=In<Tn&&Gn>In,$n=Math.max(Math.min(ys?zs:vs,Tn),160),Jn=Math.min(Math.max(xs,sn),tt-sn-On)+gn,Fs=ys?Math.max(en+kt,Pn-$n-nt+kt):Math.min(Kn+nt+kt,jt+kt-en-$n);Ae({top:Fs,left:Jn,width:On,maxHeight:$n})},[nn]),_n=a.useCallback(()=>{const ae=Me.current?.querySelector("button");if(!ae)return;const _e=ae.getBoundingClientRect(),{width:tt,height:jt,offsetTop:kt,offsetLeft:gn}=nn(),sn=16,en=16,nt=4,$t=tt<=768,Tn=Math.min($t?jt*.6:jt*.5,320),qn=$t?Math.min(tt-sn*2,280):Math.max(_e.width,240),On=Math.min(qn,Math.max(tt-sn*2,200)),Pn=_e.top-kt,Kn=_e.bottom-kt,xs=_e.left-gn,In=jt-Kn,Gn=Pn,vs=Math.max(In-en-nt,160),zs=Math.max(Gn-en-nt,160),ys=In<Tn&&Gn>In,$n=Math.max(Math.min(ys?zs:vs,Tn),160),Jn=Math.min(Math.max(xs,sn),tt-sn-On)+gn,Fs=ys?Math.max(en+kt,Pn-$n-nt+kt):Math.min(Kn+nt+kt,jt+kt-en-$n);it({top:Fs,left:Jn,width:On,maxHeight:$n})},[nn]);a.useEffect(()=>{if(!he)return;const ae=()=>cn();window.addEventListener("resize",ae),window.addEventListener("scroll",ae,!0);const _e=window.visualViewport;return _e&&(_e.addEventListener("resize",ae),_e.addEventListener("scroll",ae)),()=>{window.removeEventListener("resize",ae),window.removeEventListener("scroll",ae,!0),_e&&(_e.removeEventListener("resize",ae),_e.removeEventListener("scroll",ae))}},[he,cn]),a.useEffect(()=>{if(!Dt)return;const ae=()=>Hn();window.addEventListener("resize",ae),window.addEventListener("scroll",ae,!0);const _e=window.visualViewport;return _e&&(_e.addEventListener("resize",ae),_e.addEventListener("scroll",ae)),()=>{window.removeEventListener("resize",ae),window.removeEventListener("scroll",ae,!0),_e&&(_e.removeEventListener("resize",ae),_e.removeEventListener("scroll",ae))}},[Dt,Hn]),a.useEffect(()=>{if(!K)return;const ae=()=>fn();window.addEventListener("resize",ae),window.addEventListener("scroll",ae,!0);const _e=window.visualViewport;return _e&&(_e.addEventListener("resize",ae),_e.addEventListener("scroll",ae)),()=>{window.removeEventListener("resize",ae),window.removeEventListener("scroll",ae,!0),_e&&(_e.removeEventListener("resize",ae),_e.removeEventListener("scroll",ae))}},[K,fn]),a.useEffect(()=>{if(!k)return;const ae=()=>dn();window.addEventListener("resize",ae),window.addEventListener("scroll",ae,!0);const _e=window.visualViewport;return _e&&(_e.addEventListener("resize",ae),_e.addEventListener("scroll",ae)),()=>{window.removeEventListener("resize",ae),window.removeEventListener("scroll",ae,!0),_e&&(_e.removeEventListener("resize",ae),_e.removeEventListener("scroll",ae))}},[k,dn]),a.useEffect(()=>{if(!J)return;const ae=()=>_n();window.addEventListener("resize",ae),window.addEventListener("scroll",ae,!0);const _e=window.visualViewport;return _e&&(_e.addEventListener("resize",ae),_e.addEventListener("scroll",ae)),()=>{window.removeEventListener("resize",ae),window.removeEventListener("scroll",ae,!0),_e&&(_e.removeEventListener("resize",ae),_e.removeEventListener("scroll",ae))}},[J,_n]);const zn=a.useCallback(ae=>{const _e=Tl(ae);Ve(_e.provider),De(_e.modelId)},[]),es=a.useCallback(ae=>{const _e=Tl(ae);de(_e.provider),ie(_e.modelId)},[]),Fn=a.useCallback(ae=>{const _e=Tl(ae);Ue(_e.provider),at(_e.modelId)},[]),Qt=a.useCallback(async ae=>{if(m){m(ae);return}const _e=Ze,jt=_e.includes(ae)?_e.filter(kt=>kt!==ae):[ae,..._e];pt(jt);try{await pn({favoriteProviders:jt,favoriteModels:gt})}catch{pt(_e)}},[Ze,gt,m]),yt=a.useCallback(async ae=>{if(h){h(ae);return}const _e=gt,jt=_e.includes(ae)?_e.filter(kt=>kt!==ae):[ae,..._e];wt(jt);try{await pn({favoriteProviders:Ze,favoriteModels:jt})}catch{wt(_e)}},[gt,Ze,h]),on=a.useCallback(()=>{const ae=f.trim();if(!ae){n("Enter a description first","error");return}r?.(ae),mn()},[f,r,n,mn]),M=a.useCallback(()=>{const ae=f.trim();if(!ae){n("Enter a description first","error");return}o?.(ae),mn()},[f,o,n,mn]),le=a.useCallback(()=>{En()},[En]),Se=a.useCallback(async ae=>{const _e=f.trim();if(!(!_e||St)){Mt(!1),Wt(!0);try{const tt=await Mp(_e,ae,l);p(tt),n("Description refined with AI","success"),E.current&&(E.current.style.height="auto",E.current.style.height=`${Math.min(E.current.scrollHeight,200)}px`)}catch(tt){const jt=Ap(tt);n(jt,"error")}finally{Wt(!1)}}},[f,St,n,l]),Qe=(ae,_e)=>ae.length>_e?ae.slice(0,_e)+"…":ae,ht=a.useCallback(async()=>{if(i){te(i),je(null),Z(!1);return}Z(!0),je(null);try{const ae=await bs();te(ae.models),u||pt(ae.favoriteProviders),d||wt(ae.favoriteModels)}catch(ae){je(we(ae)||"Failed to load models")}finally{Z(!1)}},[i,u,d]),bt=a.useCallback(async()=>{if(ee.length>0&&I===l){H(!0),dn();return}W(!0);try{const ae=await Ra(void 0,l);N(ae),T(l),H(!0),dn()}catch(ae){const _e=we(ae);n(_e?`Failed to load agents: ${_e}`:"Failed to load agents","error"),H(!1)}finally{W(!1)}},[ee.length,I,l,n,dn]),yn=(G?ee.find(ae=>ae.id===G):void 0)?.name??G,ts=At?Ft.find(ae=>ae.id===At):void 0,as=y,Js=a.useCallback(()=>{w(ae=>{const _e=!ae;return x(_e),_e})},[]);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:E,className:`quick-entry-input ${v?"quick-entry-input--expanded":""}`,placeholder:g?"Creating...":"Add a task...",value:f,onChange:ae=>p(ae.target.value),onKeyDown:hn,onPaste:ut,onFocus:is,onBlur:Rn,disabled:g||D,"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:Js,"aria-expanded":y,"aria-controls":"quick-entry-controls","data-testid":"quick-entry-toggle",title:y?"Collapse":"Expand",children:y?t.jsx(bi,{size:14}):t.jsx(Xt,{size:14})})]})}),t.jsxs("div",{id:"quick-entry-controls",className:"quick-entry-controls",hidden:!as,"aria-hidden":!as,children:[as&&!g&&t.jsxs("div",{className:"quick-entry-actions","data-testid":"quick-entry-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:on,onMouseDown:ae=>ae.preventDefault(),disabled:!f.trim(),"data-testid":"plan-button",title:"Open planning mode with current description",children:[t.jsx(ri,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Plan"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:M,onMouseDown:ae=>ae.preventDefault(),disabled:!f.trim(),"data-testid":"subtask-button",title:"Break down into AI-generated subtasks",children:[t.jsx(Xo,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Subtask"]}),t.jsxs("div",{className:"refine-trigger-wrap",ref:It,children:[t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${St?"refine-button--loading":""}`,onClick:()=>{Mt(ae=>{const _e=!ae;return _e?Hn():xe(null),_e})},disabled:!f.trim()||St,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(cs,{size:12,style:{verticalAlign:"middle"}}),St?"Refining...":"Refine"]}),Dt&&$e&&Rt&&ma.createPortal(t.jsxs("div",{ref:Yt,className:"refine-menu refine-menu--portal",onMouseDown:ae=>ae.preventDefault(),style:{position:"fixed",top:`${Rt.top}px`,left:`${Rt.left}px`},children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>Se("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:()=>Se("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:()=>Se("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:()=>Se("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)]}),t.jsx("div",{className:"dep-trigger-wrap",children:t.jsxs("button",{ref:Re,type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-deps",onClick:()=>{L(ae=>{const _e=!ae;return _e?(O(!1),ce(null),Q(null),H(!1),Ae(null),ue(!1),it(null),fn()):Ye(null),_e})},children:[t.jsx(ga,{size:12,style:{verticalAlign:"middle"}}),R.length>0?`${R.length} deps`:"Deps"]})}),K&&$e&&Pe&&(()=>{const ae=$.toLowerCase(),_e=(ae?s.filter(tt=>tt.id.toLowerCase().includes(ae)||tt.title&&tt.title.toLowerCase().includes(ae)||tt.description&&tt.description.toLowerCase().includes(ae)):[...s]).sort((tt,jt)=>{const kt=jt.createdAt.localeCompare(tt.createdAt);if(kt!==0)return kt;const gn=parseInt(tt.id.slice(tt.id.lastIndexOf("-")+1),10)||0;return(parseInt(jt.id.slice(jt.id.lastIndexOf("-")+1),10)||0)-gn});return ma.createPortal(t.jsxs("div",{ref:be,className:"dep-dropdown dep-dropdown--portal",onMouseDown:tt=>tt.preventDefault(),style:{position:"fixed",top:`${Pe.top}px`,left:`${Pe.left}px`,width:`${Pe.width}px`,maxHeight:Pe.maxHeight?`${Pe.maxHeight}px`:void 0,overflowY:Pe.maxHeight?"auto":void 0},children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:$,onChange:tt=>U(tt.target.value),onClick:tt=>tt.stopPropagation()}),_e.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No existing tasks"}):_e.map(tt=>t.jsxs("div",{className:`dep-dropdown-item${R.includes(tt.id)?" selected":""}`,onMouseDown:jt=>jt.preventDefault(),onClick:()=>Dn(tt.id),children:[t.jsx("span",{className:"dep-dropdown-id",children:tt.id}),t.jsx("span",{className:"dep-dropdown-title",children:Qe(tt.title||tt.description||tt.id,60)})]},tt.id))]}),$e)})(),t.jsxs("button",{type:"button",className:"btn btn-sm","data-testid":"quick-entry-attach",onClick:()=>C.current?.click(),children:[t.jsx(xp,{size:12,style:{verticalAlign:"middle"}}),S.length>0?`Attach (${S.length})`:"Attach"]}),t.jsxs("button",{ref:Be,type:"button",className:"btn btn-sm","data-testid":"quick-entry-models",onClick:()=>{L(!1),H(!1),Ae(null),ue(!1),it(null),Q(null),O(!0),cn()},children:[t.jsx(Ro,{size:12,style:{verticalAlign:"middle"}}),Nn]}),t.jsx("div",{className:"node-trigger-wrap",ref:Me,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-node-button",onClick:()=>{L(!1),H(!1),Ae(null),O(!1),ce(null),Q(null),ue(ae=>{const _e=!ae;return _e?_n():it(null),_e})},children:[t.jsx(kr,{size:12,style:{verticalAlign:"middle"}}),` ${ts?.name??"Node"}`,ts&&t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(Vi,{status:ts.status,showLabel:!0})})]})}),J&&$e&&Je&&ma.createPortal(t.jsxs("div",{ref:Le,className:"dep-dropdown node-picker-dropdown node-picker-dropdown--portal",onMouseDown:ae=>ae.preventDefault(),style:{position:"fixed",top:`${Je.top}px`,left:`${Je.left}px`,width:`${Je.width}px`,maxHeight:Je.maxHeight?`${Je.maxHeight}px`:void 0,overflowY:Je.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select execution node"}),t.jsx("div",{className:`dep-dropdown-item node-picker-item${At==null?" selected":""}`,onMouseDown:ae=>ae.preventDefault(),onClick:()=>{Bt(void 0),ue(!1),it(null)},children:t.jsx("span",{className:"node-picker-item-name",children:"Project default / local"})}),Ft.map(ae=>t.jsxs("div",{className:`dep-dropdown-item node-picker-item${At===ae.id?" selected":""}`,onMouseDown:_e=>_e.preventDefault(),onClick:()=>{Bt(ae.id),ue(!1),it(null)},children:[t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(Vi,{status:ae.status})}),t.jsx("span",{className:"node-picker-item-name",children:ae.name}),t.jsx("span",{className:"node-picker-item-status",children:v1(ae.status)})]},ae.id))]}),$e),t.jsx("div",{className:"agent-trigger-wrap",ref:Ne,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{k?(H(!1),Ae(null)):(ue(!1),it(null),bt())},"data-testid":"quick-entry-agent-button",children:[t.jsx(Sn,{size:12,style:{verticalAlign:"middle"}}),yn?` ${yn}`:" Agent"]})}),k&&$e&&pe&&ma.createPortal(t.jsxs("div",{ref:se,className:"dep-dropdown agent-picker-dropdown agent-picker-dropdown--portal",onMouseDown:ae=>ae.preventDefault(),style:{position:"fixed",top:`${pe.top}px`,left:`${pe.left}px`,width:`${pe.width}px`,maxHeight:pe.maxHeight?`${pe.maxHeight}px`:void 0,overflowY:pe.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),fe&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!fe&&ee.filter(ae=>ae.state!=="terminated").map(ae=>t.jsxs("div",{className:`dep-dropdown-item${G===ae.id?" selected":""}`,onMouseDown:_e=>_e.preventDefault(),onClick:()=>{Y(ae.id===G?null:ae.id),H(!1),Ae(null)},children:[t.jsx(Sn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:ae.role}),t.jsx("span",{className:"dep-dropdown-title",children:ae.name})]},ae.id)),!fe&&ee.filter(ae=>ae.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),G&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:ae=>ae.preventDefault(),onClick:()=>{Y(null),H(!1),Ae(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]}),$e),t.jsx("button",{type:"button",className:`btn btn-sm ${qt?"btn-primary":""}`,onClick:()=>Pt(ae=>!ae),onMouseDown:ae=>ae.preventDefault(),"aria-pressed":qt,"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:le,onMouseDown:ae=>ae.preventDefault(),disabled:!f.trim()||g,"data-testid":"quick-entry-save",title:"Create task",children:[t.jsx(yp,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Save"]})]}),S.length>0&&t.jsx("div",{className:"inline-create-previews",children:S.map((ae,_e)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:ae.previewUrl,alt:ae.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>Lt(_e),disabled:g,title:"Remove image","data-testid":`quick-entry-preview-remove-${_e}`,children:"×"})]},ae.previewUrl))}),he&&$e&&ye&&ma.createPortal(t.jsx("div",{ref:oe,className:"model-nested-menu model-nested-menu--portal",onMouseDown:ae=>ae.preventDefault(),"data-testid":"model-nested-menu",style:{position:"fixed",top:`${ye.top}px`,left:`${ye.left}px`,width:`${ye.width}px`,maxHeight:ye.maxHeight?`${ye.maxHeight}px`:void 0,overflowY:ye.maxHeight?"auto":void 0},children:ne===null?t.jsxs("div",{className:"model-menu-items",children:[t.jsxs("button",{type:"button",className:`model-menu-item ${dt?"model-menu-item--active":""}`,onClick:()=>Q("plan"),"data-testid":"model-menu-plan",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(ri,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Plan"]}),t.jsx("span",{className:"model-menu-item-value",children:dt?un(et,Xe):"Using default"}),t.jsx(xn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${Oe?"model-menu-item--active":""}`,onClick:()=>Q("executor"),"data-testid":"model-menu-executor",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(cs,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Executor"]}),t.jsx("span",{className:"model-menu-item-value",children:Oe?un(ge,me):"Using default"}),t.jsx(xn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${Ge?"model-menu-item--active":""}`,onClick:()=>Q("validator"),"data-testid":"model-menu-validator",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(Ro,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Reviewer"]}),t.jsx("span",{className:"model-menu-item-value",children:Ge?un(Ee,Te):"Using default"}),t.jsx(xn,{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:()=>Q(null),"data-testid":"model-submenu-back",children:[t.jsx(Xt,{size:12,style:{transform:"rotate(90deg)",marginRight:4}}),"Back"]}),t.jsxs("div",{className:"model-submenu-header",children:[ne==="plan"&&"Plan Model",ne==="executor"&&"Executor Model",ne==="validator"&&"Reviewer Model"]}),t.jsx(Zn,{models:rt,value:ne==="plan"?ze:ne==="executor"?F:ve,onChange:ne==="plan"?zn:ne==="executor"?es:Fn,placeholder:"Using default",disabled:ft,id:`model-${ne}-select`,label:`${ne} model`,favoriteProviders:Fe,onToggleFavorite:Qt,favoriteModels:ct,onToggleModelFavorite:yt}),re&&t.jsxs("div",{className:"model-submenu-error",children:[t.jsx("span",{children:re}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:ht,children:"Retry"})]})]})}),$e)]}),t.jsx("input",{ref:C,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:ae=>{ke(ae.target.files),ae.currentTarget.value=""},"data-testid":"quick-entry-file-input"}),t.jsx("div",{className:"quick-entry-hint",children:"Enter to create · Esc to cancel"})]})}function y1(e){return jd(e)||e}function j1(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 k1(e,n,s){const i=e.filter(g=>g.worktree),r=e.filter(g=>!g.worktree),o=new Map;for(const g of i){const b=g.worktree,v=o.get(b)||[];v.push(g),o.set(b,v)}const l=new Map(n.map(g=>[g.id,g])),u=n.filter(g=>g.column==="todo").filter(g=>!g.paused&&(g.dependencies||[]).every(b=>{const v=l.get(b);return v&&(v.column==="done"||v.column==="in-review"||v.column==="archived")})),m=j1(u).map(g=>l.get(g)).filter(g=>g!==void 0&&u.includes(g)),h=[],f=Array.from(o.keys());for(const g of f)h.push({label:y1(g),activeTasks:o.get(g),queuedTasks:[]});r.length>0&&h.push({label:"Unassigned",activeTasks:r,queuedTasks:[]});const p=m.slice(0,s);return p.length>0&&h.push({label:"Up Next",activeTasks:[],queuedTasks:p}),h}const Ku=100,Pl=50,Gu=25;function w1({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:f,onUpdateTask:p,onRetryTask:g,onArchiveTask:b,onUnarchiveTask:v,onDeleteTask:x,onArchiveAllDone:y,collapsed:w,onToggleCollapse:E,allTasks:C,availableModels:j,onPlanningMode:A,onSubtaskBreakdown:S,onOpenDetailWithTab:z,favoriteProviders:_,favoriteModels:R,onToggleFavorite:B,onToggleModelFavorite:K,isSearchActive:L,taskStuckTimeoutMs:$,onOpenMission:U,lastFetchTimeMs:G,workflowStepNameLookup:Y}){const[ee,N]=a.useState(!1),[I,T]=a.useState(Pl),[k,H]=a.useState(!1),[J,ue]=a.useState(!1),[fe,W]=a.useState(!1),[he,O]=a.useState(!1),ne=a.useRef(null),Q=mN(n.length),{confirm:ge}=Ks();a.useEffect(()=>{if(!k)return;function Ae(it){ne.current?.contains(it.target)||H(!1)}function Je(it){it.key==="Escape"&&H(!1)}return document.addEventListener("mousedown",Ae),document.addEventListener("keydown",Je),()=>{document.removeEventListener("mousedown",Ae),document.removeEventListener("keydown",Je)}},[k]);const de=e==="archived",me=de&&w,ie=!de&&!L&&e!=="in-progress"&&n.length>Ku;a.useEffect(()=>{T(Ae=>e==="in-progress"||de||n.length<=Ku?Pl:Math.min(Math.max(Ae,Pl),n.length))},[e,de,n.length]);const Ee=a.useCallback(Ae=>{de||(Ae.preventDefault(),Ae.dataTransfer.dropEffect="move",N(!0))},[de]),Ue=a.useCallback(Ae=>{Ae.currentTarget.contains(Ae.relatedTarget)||N(!1)},[]),Te=a.useCallback(async Ae=>{Ae.preventDefault(),N(!1);const Je=Ae.dataTransfer.getData("text/plain");if(!Je)return;const it=n.find(ye=>ye.id===Je);if(!(it&&it.column===e))try{await r(Je,e)}catch(ye){c(we(ye),"error")}},[e,r,c,n]),at=a.useMemo(()=>e!=="in-progress"?[]:k1(n,n,i),[e,n,i]),et=a.useMemo(()=>ie?n.slice(0,I):n,[ie,n,I]),Ve=Math.max(0,n.length-et.length),Xe=a.useCallback(()=>{T(Ae=>Math.min(Ae+Gu,n.length))},[n.length]),De=a.useCallback(async()=>{if(H(!1),!(n.length===0||!await ge({title:"Replan All Tasks",message:`Move all ${n.length} todo task${n.length===1?"":"s"} back to planning to be replanned?`}))){ue(!0);try{const Je=await Promise.allSettled(n.map(ce=>r(ce.id,"triage"))),it=Je.filter(ce=>ce.status==="rejected").length,ye=Je.length-it;it===0?c(`Moved ${ye} task${ye===1?"":"s"} to planning for replanning`,"success"):c(`Moved ${ye} of ${Je.length} tasks; ${it} failed`,"error")}finally{ue(!1)}}},[n,r,c,ge]),Be=a.useMemo(()=>n.filter(Ae=>!Ae.paused),[n]),oe=Be.length,Ne=e==="todo"||e==="in-progress"||e==="in-review",se=J||fe||he,Me=a.useCallback(async()=>{if(!(!o||(H(!1),oe===0)||!await ge({title:"Stop All Tasks",message:`Stop all ${oe} ${Bn[e].toLowerCase()} task${oe===1?"":"s"}?`,danger:!0}))){W(!0);try{const Je=await Promise.allSettled(Be.map(ce=>o(ce.id))),it=Je.filter(ce=>ce.status==="rejected").length,ye=Je.length-it;it===0?c(`Stopped ${ye} task${ye===1?"":"s"}`,"success"):c(`Stopped ${ye} of ${Je.length} tasks; ${it} failed`,"error")}finally{W(!1)}}},[o,oe,e,Be,c,ge]),Le=a.useCallback(async()=>{if(H(!1),!(n.length===0||!await ge({title:"Move All to Todo",message:`Move all ${n.length} ${Bn[e].toLowerCase()} task${n.length===1?"":"s"} to Todo?`}))){O(!0);try{const Je=await Promise.allSettled(n.map(ce=>r(ce.id,"todo"))),it=Je.filter(ce=>ce.status==="rejected").length,ye=Je.length-it;it===0?c(`Moved ${ye} task${ye===1?"":"s"} to Todo`,"success"):c(`Moved ${ye} of ${Je.length} tasks to Todo; ${it} failed`,"error")}finally{O(!1)}}},[n,e,r,c,ge]),pe=a.useCallback(async()=>{if(!(!y||n.length===0||!await ge({title:"Archive All Done",message:`Archive all ${n.length} done tasks?`,danger:!0})))try{const Je=await y();c(`Archived ${Je.length} tasks`,"success")}catch(Je){c(we(Je)||"Failed to archive tasks","error")}},[y,n.length,c,ge]);return t.jsxs("div",{className:`column${ee?" drag-over":""}${de?" column-archived":""}${me?" column-collapsed":""}`,"data-column":e,onDragOver:Ee,onDragLeave:Ue,onDrop:Te,children:[t.jsxs("div",{className:"column-header",children:[t.jsx("div",{className:`column-dot dot-${e}`}),t.jsx("h2",{children:Bn[e]}),t.jsx("span",{className:`column-count${Q?" count-flash":""}`,children:n.length}),e==="in-review"&&h&&t.jsxs("label",{className:"auto-merge-toggle",title:m?"Auto-merge enabled":"Auto-merge disabled",children:[t.jsx("input",{type:"checkbox",checked:!!m,onChange:h}),t.jsx("span",{className:"toggle-slider"}),t.jsx("span",{className:"toggle-label",children:"Auto-merge"})]}),d&&t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:d,children:"+ New Task"}),e==="done"&&y&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:pe,disabled:n.length===0,title:"Archive all done tasks","aria-label":"Archive all done tasks",children:t.jsx(Rr,{})}),de&&E&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:E,title:w?"Expand archived tasks":"Collapse archived tasks","aria-label":w?"Expand archived tasks":"Collapse archived tasks",children:w?t.jsx(Xt,{size:16}):t.jsx(bi,{size:16})}),Ne&&t.jsxs("div",{className:"column-menu",ref:ne,children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>H(Ae=>!Ae),"aria-haspopup":"menu","aria-expanded":k,"aria-label":`${Bn[e]} column actions`,title:"Column actions",disabled:se,children:t.jsx(qb,{})}),k&&t.jsxs("div",{className:"column-menu-popover",role:"menu",children:[e==="todo"&&t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void De(),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 Me(),disabled:oe===0||fe||!o,children:["Stop All",t.jsx("span",{className:"column-menu-item-hint",children:n.length===0?"No tasks in this column":oe===0?"All tasks are already paused":`Pause ${oe} active task${oe===1?"":"s"}`})]}),t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Le(),disabled:n.length===0||he,children:["Move All to Todo",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Todo"]})]})]})]})]})]}),!me&&t.jsx("p",{className:"column-desc",children:dN[e]}),!me&&t.jsxs("div",{className:"column-body",children:[e==="triage"&&u&&t.jsx(Xp,{onCreate:u,addToast:c,tasks:C??[],availableModels:j,onPlanningMode:A,onSubtaskBreakdown:S,projectId:s,autoExpand:!1,favoriteProviders:_,favoriteModels:R,onToggleFavorite:B,onToggleModelFavorite:K}),e==="in-progress"?at.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):at.map(Ae=>t.jsx(Qp,{label:Ae.label,activeTasks:Ae.activeTasks,queuedTasks:Ae.queuedTasks,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onOpenDetailWithTab:z,taskStuckTimeoutMs:$,onOpenMission:U,lastFetchTimeMs:G,workflowStepNameLookup:Y},Ae.label)):n.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):t.jsxs(t.Fragment,{children:[et.map(Ae=>t.jsx(Fo,{task:Ae,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onArchiveTask:b,onUnarchiveTask:v,onDeleteTask:x,onOpenDetailWithTab:z,taskStuckTimeoutMs:$,onOpenMission:U,onMoveTask:r,lastFetchTimeMs:G,workflowStepNameLookup:Y},Ae.id)),ie&&Ve>0&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Xe,children:["Load ",Math.min(Gu,Ve)," more (",Ve," remaining)"]})]}),t.jsx(al,{slotId:"board-column-footer",projectId:s})]})]})}const Zp=a.memo(w1);Zp.displayName="Column";function N1(e,n){return[...e].sort((s,i)=>{if(n==="in-review"){const r=s.status==="merging"||s.status==="merging-pr",o=i.status==="merging"||i.status==="merging-pr";if(r!==o)return r?-1:1}return s.columnMovedAt&&i.columnMovedAt?i.columnMovedAt.localeCompare(s.columnMovedAt):s.columnMovedAt&&!i.columnMovedAt?-1:!s.columnMovedAt&&i.columnMovedAt?1:s.createdAt.localeCompare(i.createdAt)})}function S1(e,n){return e.length!==n.length?!1:e.every((s,i)=>s===n[i])}const Ju=new Map;function C1(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 E1({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:f,onRetryTask:p,onArchiveTask:g,onUnarchiveTask:b,onDeleteTask:v,onArchiveAllDone:x,onLoadArchivedTasks:y,searchQuery:w="",availableModels:E,onPlanningMode:C,onSubtaskBreakdown:j,onOpenDetailWithTab:A,favoriteProviders:S,favoriteModels:z,onToggleFavorite:_,onToggleModelFavorite:R,taskStuckTimeoutMs:B,onOpenMission:K,lastFetchTimeMs:L}){const[$,U]=a.useState(!0),G=a.useRef(!1),{fetchBatch:Y}=RN(n),ee=a.useRef(null),[N,I]=a.useState(Ju),T=w.trim()!=="",k=a.useRef({triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]}),H=a.useCallback(()=>{U(fe=>{const W=!fe;return!W&&!G.current&&y&&(G.current=!0,y()),W})},[y]),J=a.useMemo(()=>{const fe=Object.fromEntries(Oi.map(O=>[O,[]]));for(const O of e)fe[O.column].push(O);const W=k.current,he={};for(const O of Oi){const ne=N1(fe[O],O);he[O]=S1(W[O],ne)?W[O]:ne}return k.current=he,he},[e]);a.useEffect(()=>{let fe=!1;return sl(n).then(W=>{if(fe)return;const he=new Map(W.map(O=>[O.id,O.name]));I(O=>C1(O,he)?O:he)}).catch(()=>{fe||I(W=>W.size===0?W:Ju)}),()=>{fe=!0}},[n]);const ue=a.useMemo(()=>e.filter(fe=>fe.prInfo||fe.issueInfo).map(fe=>fe.id),[e]);return a.useEffect(()=>{if(ue.length!==0)return ee.current&&clearTimeout(ee.current),ee.current=setTimeout(()=>{const fe=[];for(let W=0;W<ue.length;W+=50)fe.push(ue.slice(W,W+50));fe.forEach(W=>{Y(W)})},500),()=>{ee.current&&clearTimeout(ee.current)}},[ue,Y]),t.jsx(t.Fragment,{children:t.jsx("main",{className:"board",id:"board",children:Oi.map(fe=>t.jsx(Zp,{column:fe,tasks:J[fe],projectId:n,maxConcurrent:s,onMoveTask:i,onPauseTask:r,onOpenDetail:o,addToast:l,globalPaused:h,onUpdateTask:f,onRetryTask:p,onArchiveTask:g,onUnarchiveTask:b,onDeleteTask:v,allTasks:e,availableModels:E,onOpenDetailWithTab:A,favoriteProviders:S,favoriteModels:z,onToggleFavorite:_,onToggleModelFavorite:R,isSearchActive:T,taskStuckTimeoutMs:B,onOpenMission:K,lastFetchTimeMs:L,workflowStepNameLookup:N,...fe==="triage"?{onQuickCreate:c,onNewTask:u,onPlanningMode:C,onSubtaskBreakdown:j}:{},...fe==="in-review"?{autoMerge:d,onToggleAutoMerge:m}:{},...fe==="done"?{onArchiveAllDone:x}:{},...fe==="archived"?{collapsed:$,onToggleCollapse:H}:{}},fe))})})}const Va={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-secondary)"},Yu=new Set(["planning","researching","executing","finalizing","merging"]),Vc=["id","title","status","column","dependencies","progress"];function _1(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function M1(e){return e==="online"?"●":e==="connecting"?"◐":e==="error"?"✕":"○"}function Qu(e){try{const n=Wn("kb-dashboard-list-columns",e);if(n){const i=JSON.parse(n).filter(r=>Vc.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set(Vc)}function Xu(e){try{const n=Wn("kb-dashboard-hide-done",e);if(n!==null)return n==="true"}catch{}return!1}function Zu(e){try{const n=Wn("kb-dashboard-list-collapsed",e);if(n){const i=JSON.parse(n).filter(r=>Oi.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set}function em(e){try{const n=Wn("kb-dashboard-selected-tasks",e);if(n){const s=JSON.parse(n);return new Set(s)}}catch{}return new Set}function A1(e){return e.status==="executing"||e.column==="in-progress"}function tm(e){const n=Gp(e);return n.total===0||!A1(e)?{label:"-",percent:0,hasProgress:!1}:{label:`${n.completed}/${n.total}`,percent:n.completed/n.total*100,hasProgress:!0}}function R1({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:f,onSubtaskBreakdown:p,onTasksUpdated:g,projectId:b,projectName:v,taskStuckTimeoutMs:x,searchQuery:y="",lastFetchTimeMs:w}){const[E,C]=a.useState("id"),[j,A]=a.useState("desc"),[S,z]=a.useState(null),[_,R]=a.useState(null),[B,K]=a.useState(null),$=Ta()==="mobile",[U,G]=a.useState(()=>Qu(b)),[Y,ee]=a.useState(()=>Xu(b)),[N,I]=a.useState(()=>Zu(b));a.useEffect(()=>{typeof window<"u"&&fs("kb-dashboard-list-columns",JSON.stringify([...U]),b)},[b,U]),a.useEffect(()=>{typeof window<"u"&&fs("kb-dashboard-hide-done",Y.toString(),b)},[Y,b]),a.useEffect(()=>{typeof window<"u"&&fs("kb-dashboard-list-collapsed",JSON.stringify([...N]),b)},[N,b]);const[T,k]=a.useState(!1),H=a.useRef(null),[J,ue]=a.useState(()=>em(b));a.useEffect(()=>{G(Qu(b)),ee(Xu(b)),I(Zu(b)),ue(em(b))},[b]),a.useEffect(()=>{typeof window<"u"&&fs("kb-dashboard-selected-tasks",JSON.stringify([...J]),b)},[b,J]);const fe=a.useCallback(Z=>{ue(re=>{const je=new Set(re);return je.has(Z)?je.delete(Z):je.add(Z),je})},[]),W=a.useCallback(()=>{ue(new Set)},[]),he=a.useCallback(Z=>{G(re=>{const je=new Set(re);return je.has(Z)?je.size>1&&je.delete(Z):je.add(Z),je})},[]);a.useEffect(()=>{if(!T)return;const Z=je=>{H.current&&!H.current.contains(je.target)&&k(!1)},re=je=>{je.key==="Escape"&&k(!1)};return document.addEventListener("mousedown",Z),document.addEventListener("keydown",re),()=>{document.removeEventListener("mousedown",Z),document.removeEventListener("keydown",re)}},[T]);const O={id:"ID",title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},ne=a.useCallback(Z=>{E===Z?A(re=>re==="asc"?"desc":"asc"):(C(Z),A("asc"))},[E]),Q=a.useCallback(Z=>{K(re=>re===Z?null:Z)},[]),ge=a.useCallback(Z=>{I(re=>{const je=new Set(re);return je.has(Z)?je.delete(Z):je.add(Z),je})},[]),de=a.useCallback(()=>{K(null)},[]),me=a.useMemo(()=>{let Z=y?e.filter(te=>te.id.toLowerCase().includes(y.toLowerCase())||te.title&&te.title.toLowerCase().includes(y.toLowerCase())||te.description.toLowerCase().includes(y.toLowerCase())):[...e];Y&&!B&&(Z=Z.filter(te=>te.column!=="done"&&te.column!=="archived"));const je=[...B?Z.filter(te=>te.column===B):Z].sort((te,Ze)=>{let pt=0;switch(E){case"id":pt=te.id.localeCompare(Ze.id);break;case"title":pt=(te.title||te.description).localeCompare(Ze.title||Ze.description);break;case"status":pt=(te.status||"").localeCompare(Ze.status||"");break;case"column":pt=te.column.localeCompare(Ze.column);break}return j==="asc"?pt:-pt}),rt={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};return je.forEach(te=>rt[te.column].push(te)),rt},[e,y,E,j,Y,B]),ie=a.useMemo(()=>Object.values(me).reduce((Z,re)=>Z+re.length,0),[me]),Ee=a.useMemo(()=>e.filter(Z=>Z.column==="done"||Z.column==="archived").length,[e]),Ue=a.useMemo(()=>Y?Ee:0,[Y,Ee]),Te=a.useCallback(()=>{const Z=Object.values(me).flat().filter(re=>re.column!=="archived").map(re=>re.id);ue(re=>{if(Z.every(rt=>re.has(rt))){const rt=new Set(re);return Z.forEach(te=>rt.delete(te)),rt}else return new Set([...re,...Z])})},[me]),at=a.useMemo(()=>{const Z=Object.values(me).flat().filter(re=>re.column!=="archived");return Z.length===0?!1:Z.every(re=>J.has(re.id))},[me,J]),et=a.useMemo(()=>{const Z=Object.values(me).flat().filter(je=>je.column!=="archived");if(Z.length===0)return!1;const re=Z.filter(je=>J.has(je.id)).length;return re>0&&re<Z.length},[me,J]),[Ve,Xe]=a.useState("__no_change__"),[De,Be]=a.useState("__no_change__"),[oe,Ne]=a.useState("__no_change__"),[se,Me]=a.useState([]),[Le,pe]=a.useState(!1),Ae=a.useMemo(()=>oe&&oe!=="__no_change__"?se.find(Z=>Z.id===oe):void 0,[se,oe]),[Je,it]=a.useState(!1);a.useEffect(()=>{if(J.size===0)return;let Z=!1;return(async()=>{pe(!0);try{const je=await Do();Z||Me(je)}catch(je){console.error("Failed to fetch nodes for bulk edit",je),Z||Me([])}finally{Z||pe(!1)}})(),()=>{Z=!0}},[J.size]);const ye=a.useCallback(async()=>{if(J.size===0)return;const Z=Array.from(J).filter(je=>{const rt=e.find(te=>te.id===je);return rt&&rt.column!=="archived"});if(Z.length===0){i("No valid tasks to update (archived tasks cannot be modified)","error");return}const re={taskIds:Z};if(Ve!=="__no_change__")if(Ve==="")re.modelProvider=null,re.modelId=null;else{const je=Ve.indexOf("/");je!==-1&&(re.modelProvider=Ve.slice(0,je),re.modelId=Ve.slice(je+1))}if(De!=="__no_change__")if(De==="")re.validatorModelProvider=null,re.validatorModelId=null;else{const je=De.indexOf("/");je!==-1&&(re.validatorModelProvider=De.slice(0,je),re.validatorModelId=De.slice(je+1))}if(oe!=="__no_change__"&&(oe===""?re.nodeId=null:re.nodeId=oe),Object.keys(re).length===1){i("No changes to apply","info");return}it(!0);try{const je=await oy(re.taskIds,re.modelProvider,re.modelId,re.validatorModelProvider,re.validatorModelId,void 0,void 0,re.nodeId,b);g&&g(je.updated),i(`Updated ${Z.length} task${Z.length===1?"":"s"}`,"success"),W(),Xe("__no_change__"),Be("__no_change__"),Ne("__no_change__")}catch(je){i(we(je)||"Failed to update models","error")}finally{it(!1)}},[J,e,Ve,De,oe,b,i,W,g]),ce=a.useCallback(Z=>{s(Z)},[s]),Re=a.useCallback((Z,re)=>{if(re.paused){Z.preventDefault();return}Z.dataTransfer.setData("text/plain",re.id),Z.dataTransfer.effectAllowed="move",z(re.id)},[]),be=a.useCallback(()=>{z(null),R(null)},[]),Pe=a.useCallback((Z,re)=>{Z.preventDefault(),Z.dataTransfer.dropEffect="move",R(re)},[]),Ye=a.useCallback(()=>{R(null)},[]),$e=a.useCallback(async(Z,re)=>{Z.preventDefault(),R(null);const je=Z.dataTransfer.getData("text/plain");if(je){if(re==="archived"){i("Tasks can only be archived via the archive button","error");return}try{await n(je,re)}catch(rt){i(we(rt),"error")}}},[n,i]),ft=Z=>E!==Z?t.jsx(dp,{size:14,className:"sort-icon"}):j==="asc"?t.jsx(Fi,{size:14,className:"sort-icon active"}):t.jsx(Tr,{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:H,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>k(Z=>!Z),"aria-expanded":T,"aria-haspopup":"menu",children:[t.jsx(Lb,{size:14}),"Columns"]}),T&&t.jsx("div",{className:"list-column-dropdown",role:"menu",children:Vc.map(Z=>{const re=U.has(Z),je=re&&U.size===1;return t.jsxs("label",{className:`list-column-dropdown-item${je?" disabled":""}`,role:"menuitem",title:je?"At least one column must be visible":"",children:[t.jsx("input",{type:"checkbox",checked:re,onChange:()=>he(Z),disabled:je}),t.jsx("span",{children:O[Z]})]},Z)})})]}),t.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>ee(Z=>!Z),"aria-pressed":Y,title:Y?"Show done tasks":"Hide done tasks",children:[Y?t.jsx(Ma,{size:14}):t.jsx(md,{size:14}),Y?"Show Done":"Hide Done"]}),t.jsxs("div",{className:"list-stats",children:[B?`${ie} of ${e.length} tasks in ${Bn[B]}`:`${ie} of ${e.length} tasks`,Ue>0&&!B&&t.jsxs("span",{className:"list-stats-hidden",children:[" (",Ue," hidden)"]}),B&&t.jsx("button",{className:"btn btn-sm",onClick:de,"aria-label":"Clear column filter",style:{marginLeft:"8px"},children:"Clear"})]}),J.size>0&&t.jsxs("div",{className:"list-selection-stats",children:[t.jsxs("span",{className:"selection-count",children:[J.size," selected"]}),t.jsx("button",{className:"btn btn-sm btn-link",onClick:W,children:"Clear"})]}),J.size>0&&c&&c.length>0&&t.jsxs("div",{className:"bulk-edit-toolbar",children:[t.jsx("span",{className:"bulk-edit-label",children:"Bulk Edit Models & Node:"}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx(Zn,{models:c,value:Ve,onChange:Xe,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(Zn,{models:c,value:De,onChange:Be,label:"Reviewer Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:u,onToggleFavorite:m,favoriteModels:d,onToggleModelFavorite:h})}),t.jsxs("div",{className:"bulk-edit-dropdown bulk-edit-node-wrap",children:[t.jsxs("select",{className:"select bulk-node-select",value:oe,onChange:Z=>Ne(Z.target.value),"aria-label":"Node Override",disabled:Le,children:[t.jsx("option",{value:"__no_change__",children:"No change"}),t.jsx("option",{value:"",children:"Use project default"}),se.map(Z=>t.jsx("option",{value:Z.id,children:`${M1(Z.status)} ${Z.name||Z.id} (${_1(Z.status)})`},Z.id))]}),Ae?t.jsx(Vi,{status:Ae.status,showLabel:!0}):null]}),t.jsx("button",{className:"btn btn-primary btn-sm bulk-edit-apply-btn",onClick:ye,disabled:Je||Ve==="__no_change__"&&De==="__no_change__"&&oe==="__no_change__",children:Je?"Applying...":"Apply"})]}),o?t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:o,children:"+ New Task"}):null]}),t.jsx("div",{className:"list-drop-zones",children:Oi.map(Z=>{const re=e.filter(Ze=>Ze.column===Z).length,je=Z==="done"||Z==="archived",rt=Y&&je?0:re,te=Y&&je&&re>0;return t.jsxs("div",{className:`list-drop-zone${_===Z?" drag-over":""}${B===Z?" active":""}`,onClick:()=>Q(Z),onDragOver:Ze=>Pe(Ze,Z),onDragLeave:Ye,onDrop:Ze=>$e(Ze,Z),"data-column":Z,children:[t.jsx("span",{className:"drop-zone-dot",style:{background:Va[Z]}}),t.jsx("span",{className:"drop-zone-label",children:Bn[Z]}),t.jsx("span",{className:"drop-zone-count",children:te?`${rt} of ${re}`:re})]},Z)})}),t.jsxs("div",{className:"list-table-container",children:[t.jsx("div",{className:"list-quick-entry-above-table",children:t.jsx(Xp,{onCreate:l??(async()=>i("Task creation not available","error")),addToast:i,tasks:e,availableModels:c,onPlanningMode:f,onSubtaskBreakdown:p,projectId:b,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"}):$?t.jsx("div",{className:"list-cards",children:Oi.map(Z=>{if(B&&Z!==B||Y&&(Z==="done"||Z==="archived")&&!B)return null;const re=me[Z],je=re.length===0;if(y&&je)return null;const rt=N.has(Z);return t.jsxs(a.Fragment,{children:[t.jsxs("div",{className:`list-card-section-header${rt?" list-section-header--collapsed":""}`,onClick:()=>ge(Z),"aria-expanded":!rt,role:"button",tabIndex:0,onKeyDown:te=>{(te.key==="Enter"||te.key===" ")&&(te.preventDefault(),ge(Z))},children:[t.jsx(xn,{size:14,className:`list-section-chevron${rt?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${Z}`}),t.jsx("span",{className:"list-section-title",children:Bn[Z]}),t.jsx("span",{className:"list-section-count",children:re.length})]}),!rt&&t.jsx(t.Fragment,{children:je?t.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):re.map(te=>{const Ze=te.status==="failed",pt=te.paused===!0,gt=zo(te,x,w),wt=!r&&!Ze&&!pt&&!gt&&(te.column==="in-progress"||Yu.has(te.status)),Et=typeof te.status=="string"&&te.status.trim().length>0,mt=!!(te.dependencies&&te.dependencies.length>0),Nt=tm(te),Tt=Nt.hasProgress,qt=J.size>0;return t.jsxs("div",{className:`list-card${wt?" agent-active":""}${qt?" list-card--selectable":""}`,onClick:()=>ce(te),"data-id":te.id,children:[qt&&t.jsx("label",{className:"list-card-checkbox",onClick:Pt=>Pt.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:J.has(te.id),onChange:Pt=>{Pt.stopPropagation(),fe(te.id)},onClick:Pt=>Pt.stopPropagation(),disabled:te.column==="archived","aria-label":`Select ${te.id}`})}),t.jsxs("div",{className:"list-card-row",children:[t.jsx("span",{className:"list-card-id",children:te.id}),te.executionMode==="fast"&&t.jsx("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",children:"Fast"}),t.jsx("span",{className:"list-card-spacer"}),gt?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):Et?t.jsx("span",{className:`list-status-badge list-status-badge--${te.column}${Ze?" failed":""}${wt?" pulsing":""}`,children:te.status}):null]}),t.jsx("div",{className:"list-card-row",children:t.jsx("div",{className:"list-card-title",children:te.title||te.description})}),(mt||Tt)&&t.jsxs("div",{className:"list-card-row list-card-meta",children:[mt&&t.jsxs("span",{className:"list-dep-badge",title:te.dependencies.join(", "),children:[t.jsx(ga,{size:12})," ",te.dependencies.length]}),Tt&&t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${Nt.percent}%`,backgroundColor:Va[te.column]}})}),t.jsx("span",{className:"list-progress-label",children:Nt.label})]})]})]},te.id)})})]},Z)})}):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:at,ref:Z=>{Z&&(Z.indeterminate=et)},onChange:Te,"aria-label":"Select all visible tasks"})}),U.has("id")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>ne("id"),children:["ID ",ft("id")]}),U.has("title")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>ne("title"),children:["Title ",ft("title")]}),U.has("status")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>ne("status"),children:["Status ",ft("status")]}),U.has("column")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>ne("column"),children:["Column ",ft("column")]}),U.has("dependencies")&&t.jsx("th",{className:"list-header-cell",children:"Dependencies"}),U.has("progress")&&t.jsx("th",{className:"list-header-cell",children:"Progress"})]})}),t.jsx("tbody",{children:Oi.map(Z=>{if(B&&Z!==B||Y&&(Z==="done"||Z==="archived")&&!B)return null;const re=me[Z],je=re.length===0;if(y&&je)return null;const rt=N.has(Z);return t.jsxs(a.Fragment,{children:[t.jsx("tr",{className:`list-section-header${rt?" list-section-header--collapsed":""}`,onClick:()=>ge(Z),"aria-expanded":!rt,children:t.jsxs("th",{colSpan:U.size+1,className:"list-section-cell",children:[t.jsx(xn,{size:14,className:`list-section-chevron${rt?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${Z}`}),t.jsx("span",{className:"list-section-title",children:Bn[Z]}),t.jsx("span",{className:"list-section-count",children:re.length})]})}),!rt&&t.jsx(t.Fragment,{children:je?t.jsx("tr",{className:"list-section-empty",children:t.jsx("td",{colSpan:U.size+1,className:"list-empty-cell",children:"No tasks"})}):re.map(te=>{const Ze=te.status==="failed",pt=te.paused===!0,gt=zo(te,x,w),wt=!r&&!Ze&&!pt&&!gt&&(te.column==="in-progress"||Yu.has(te.status)),Et=S===te.id;return t.jsxs("tr",{className:`list-row${Ze?" failed":""}${pt?" paused":""}${gt?" stuck":""}${wt?" agent-active":""}${Et?" dragging":""}`,onClick:()=>ce(te),draggable:!pt,onDragStart:mt=>Re(mt,te),onDragEnd:be,"data-id":te.id,children:[t.jsx("td",{className:"list-cell list-cell-checkbox",children:t.jsx("input",{type:"checkbox",checked:J.has(te.id),onChange:mt=>{mt.stopPropagation(),fe(te.id)},onClick:mt=>mt.stopPropagation(),disabled:te.column==="archived","aria-label":`Select ${te.id}`})}),U.has("id")&&t.jsx("td",{className:"list-cell list-cell-id",children:te.id}),U.has("title")&&t.jsx("td",{className:"list-cell list-cell-title",children:t.jsxs("div",{className:"list-title-content",children:[te.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:te.title||te.description})]})}),U.has("status")&&t.jsx("td",{className:"list-cell",children:gt?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):te.status?t.jsx("span",{className:`list-status-badge list-status-badge--${te.column}${Ze?" failed":""}${wt?" pulsing":""}`,children:te.status}):t.jsx("span",{className:"list-status-badge",children:"-"})}),U.has("column")&&t.jsx("td",{className:"list-cell",children:t.jsx("span",{className:"list-column-badge",style:{background:`${Va[te.column]}20`,color:Va[te.column]},children:Bn[te.column]})}),U.has("dependencies")&&t.jsx("td",{className:"list-cell list-cell-deps",children:te.dependencies&&te.dependencies.length>0?t.jsxs("span",{className:"list-dep-badge",title:te.dependencies.join(", "),children:[t.jsx(ga,{size:12})," ",te.dependencies.length]}):"-"}),U.has("progress")&&t.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const mt=tm(te);return mt.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:`${mt.percent}%`,backgroundColor:Va[te.column]}})}),t.jsx("span",{className:"list-progress-label",children:mt.label})]}):"-"})()})]},te.id)})})]},Z)})})]})]})]})}const T1={active:{label:"Active",color:"var(--success)",icon:Cn},paused:{label:"Paused",color:"var(--warning)",icon:qs},errored:{label:"Error",color:"var(--color-error)",icon:gs},initializing:{label:"Initializing",color:"var(--info)",icon:ot}};function P1(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 I1(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 $1(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 D1({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=T1[e.status],f=h.icon,p=a.useCallback(()=>{s(e)},[s,e]),g=a.useCallback(E=>{E.stopPropagation(),i(e)},[i,e]),b=a.useCallback(E=>{E.stopPropagation(),r(e)},[r,e]),v=a.useCallback(E=>{if(E.stopPropagation(),!d){m(!0);return}o(e),m(!1)},[d,o,e]),x=e.status==="paused",y=e.status==="errored",w=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:E=>{(E.key==="Enter"||E.key===" ")&&(E.preventDefault(),p())},children:[t.jsxs("div",{className:"project-card-header",children:[t.jsx("div",{className:"project-card-icon",children:t.jsx(Xn,{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:I1(e.path)})]}),t.jsxs("div",{className:"project-card-status-badge",style:{color:h.color,borderColor:h.color},children:[t.jsx(f,{size:12,className:w?"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:P1(e.lastActivityAt||n?.lastActivityAt)})]}),t.jsxs("div",{className:"project-card-actions",children:[x?t.jsxs("button",{className:"project-card-action project-card-action-resume",onClick:b,disabled:u,title:"Resume project","aria-label":"Resume project",children:[t.jsx(Cn,{size:14}),t.jsx("span",{children:"Resume"})]}):t.jsxs("button",{className:"project-card-action project-card-action-pause",onClick:g,disabled:u||w,title:w?"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(Pr,{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(an,{size:14}),t.jsx("span",{children:d?"Confirm":""})]})]})]})]})}const L1=a.memo(D1,$1);function z1(){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(Xn,{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(Ds,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(wn,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(gs,{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 F1=1e4,nm=5;function O1(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 g=0;g<e.length;g+=nm){const b=e.slice(g,g+nm),v=await Promise.allSettled(b.map(async x=>{try{return await gu(x)}catch{return null}}));if(b.forEach((x,y)=>{const w=v[y];p[x]=w.status==="fulfilled"?w.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 f=>{try{const p=await gu(f);s(g=>({...g,[f]:p}))}catch(p){console.error(`Failed to fetch health for project ${f}:`,p)}},[]);return 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()},F1),()=>{c.current&&(clearInterval(c.current),c.current=null)}},[m,e.length]),{healthMap:n,loading:i,error:o,refresh:m,refreshProject:h}}function U1({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),[f,p]=a.useState("activity"),[g,b]=a.useState("desc");a.useEffect(()=>{if(typeof window>"u")return;const K=localStorage.getItem("kb-dashboard-recent-projects");if(K)try{const L=JSON.parse(K);x(L)}catch{}},[]);const[v,x]=a.useState([]),y=a.useMemo(()=>e.map(K=>K.id),[e]),{healthMap:w,loading:E}=O1(y),C=a.useMemo(()=>e.map(K=>({project:K,health:w[K.id]||null})),[e,w]),j=a.useMemo(()=>{let K=[...C];return u!=="all"&&(K=K.filter(({project:L})=>L.status===u)),m!==null&&(K=K.filter(({project:L})=>L.nodeId===m)),K},[C,u,m]),A=a.useMemo(()=>{const K=[...j];return K.sort((L,$)=>{let U=0;switch(f){case"name":U=L.project.name.localeCompare($.project.name);break;case"activity":{const G=L.project.lastActivityAt||L.health?.lastActivityAt||L.project.updatedAt,Y=$.project.lastActivityAt||$.health?.lastActivityAt||$.project.updatedAt;U=new Date(Y).getTime()-new Date(G).getTime();break}case"status":{const G={errored:0,initializing:1,paused:2,active:3};U=G[L.project.status]-G[$.project.status];break}}return g==="asc"?U:-U}),K},[j,f,g]),S=a.useMemo(()=>{const K=e.length,L=e.filter(I=>I.status==="active").length,$=e.filter(I=>I.status==="errored").length,U=new Set;e.forEach(I=>{I.nodeId&&U.add(I.nodeId)});const G=U.size||(K>0?1:0);let Y=0,ee=0,N=0;return Object.values(w).forEach(I=>{I&&(Y+=I.activeTaskCount,ee+=I.totalTasksCompleted,N+=I.inFlightAgentCount)}),{totalProjects:K,activeProjects:L,erroredProjects:$,totalNodes:G,totalActiveTasks:Y,totalCompletedTasks:ee,totalInFlightAgents:N}},[e,w]),z=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]),_=a.useMemo(()=>{const K=new Map;return e.forEach(L=>{const $=L.nodeId,U=K.get($);if(U)U.count++;else{const Y=c.find(ee=>ee.id===$)?.name??L._sourceNodeName??"Local";K.set($,{name:Y,count:1})}}),Array.from(K.entries()).map(([L,{name:$,count:U}])=>({nodeId:L??null,name:$,count:U}))},[e,c]),R=a.useCallback(K=>{const L=[K.id,...v.filter($=>$!==K.id)].slice(0,3);x(L),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify(L)),s(K)},[s,v]);return n||E&&e.length>0&&Object.keys(w).length===0?t.jsx(z1,{}):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(or,{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(rn,{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(qi,{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(Xn,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:S.totalProjects}),t.jsx("span",{className:"project-stat__label",children:"Total"})]})]}),t.jsxs("div",{className:"project-stat project-stat--active",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Ds,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:S.totalActiveTasks}),t.jsx("span",{className:"project-stat__label",children:"Active Tasks"})]})]}),t.jsxs("div",{className:"project-stat project-stat--completed",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(wn,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:S.totalCompletedTasks}),t.jsx("span",{className:"project-stat__label",children:"Completed"})]})]}),S.erroredProjects>0&&t.jsxs("div",{className:"project-stat project-stat--error",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(gs,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:S.erroredProjects}),t.jsx("span",{className:"project-stat__label",children:"Errored"})]})]}),S.totalNodes>1&&t.jsxs("div",{className:"project-stat project-stat--nodes",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(kr,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:S.totalNodes}),t.jsx("span",{className:"project-stat__label",children:"Nodes"})]})]})]}),t.jsxs("button",{className:"btn btn-primary project-overview__add-btn",onClick:i,children:[t.jsx(rn,{size:16}),"Add Project"]})]}),t.jsxs("div",{className:"project-overview__filters",children:[t.jsxs("div",{className:"project-filter-tabs",children:[t.jsxs("button",{className:`project-filter-tab ${u==="all"?"active":""}`,onClick:()=>d("all"),children:["All",t.jsx("span",{className:"project-filter-count",children:z.all})]}),t.jsxs("button",{className:`project-filter-tab ${u==="active"?"active":""}`,onClick:()=>d("active"),children:["Active",t.jsx("span",{className:"project-filter-count",children:z.active})]}),t.jsxs("button",{className:`project-filter-tab ${u==="paused"?"active":""}`,onClick:()=>d("paused"),children:["Paused",t.jsx("span",{className:"project-filter-count",children:z.paused})]}),t.jsxs("button",{className:`project-filter-tab ${u==="errored"?"active":""} ${z.errored>0?"has-errors":""}`,onClick:()=>d("errored"),children:["Errored",t.jsx("span",{className:"project-filter-count",children:z.errored})]})]}),_.length>1&&t.jsxs("div",{className:"project-node-filter",children:[t.jsx(kr,{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"}),_.map(({nodeId:K,name:L,count:$})=>t.jsxs("option",{value:K??"",children:[L," (",$,")"]},K??"local"))]})]}),t.jsxs("div",{className:"project-sort",children:[t.jsx(To,{size:14}),t.jsxs("select",{value:`${f}-${g}`,onChange:K=>{const[L,$]=K.target.value.split("-");p(L),b($)},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(dp,{size:14})]})]}),t.jsx("div",{className:"project-grid",children:A.map(({project:K,health:L})=>{const $=c.find(G=>G.id===K.nodeId),U=$?void 0:K._sourceNodeName;return t.jsx(L1,{project:K,health:L,node:$,nodeNameFallback:U,onSelect:R,onPause:r,onResume:o,onRemove:l},K.id)})}),A.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 B1=45e3,H1=3e3,q1=2e3,V1=1500,sm="fusion:sse-client-id";let aa=null;const Ci=new Map;function im(){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 ef(){if(!(typeof window>"u")){if(aa)return aa;try{const e=window.sessionStorage.getItem(sm);if(e)return aa=e,e;const n=im();return window.sessionStorage.setItem(sm,n),aa=n,n}catch{return aa=im(),aa}}}function tf(e){if(!(typeof window>"u"))try{return{parsed:new URL(e,window.location.origin),preserveRelativePath:e.startsWith("/")}}catch{return}}function nf(e){return e.origin===window.location.origin&&e.pathname==="/api/events"}function W1(e){const n=ef();if(!n)return e;const s=tf(e);return!s||!nf(s.parsed)?e:(s.parsed.searchParams.set("clientId",n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function Nd(e,n){const s=ef();if(!s)return;const i=tf(e);if(!i||!nf(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),oi(`${r.pathname}${r.search}${r.hash}`)}function K1(e){if(typeof window>"u")return;const n=Nd(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 ll(e){e.keepaliveTimer&&(clearInterval(e.keepaliveTimer),e.keepaliveTimer=null)}function am(e){if(typeof window>"u"||typeof window.fetch!="function")return;const n=Nd(e.url,"keepalive");if(!n)return;const s=typeof AbortController<"u"?new AbortController:null,i=s?window.setTimeout(()=>s.abort(),V1):null;window.fetch(n,{method:"POST",cache:"no-store",signal:s?.signal}).catch(()=>{}).finally(()=>{i!==null&&window.clearTimeout(i)})}function G1(e){ll(e),Nd(e.url,"keepalive")&&(am(e),e.keepaliveTimer=window.setInterval(()=>{am(e)},q1))}if(typeof window<"u"){const e=()=>{for(const s of Array.from(Ci.values()))if(!s.closed){if(ll(s),K1(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(Ci.values()))i.subscribers.size!==0&&(i.closed=!1,Sd(i))};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e),window.addEventListener("pageshow",n)}function dr(e){e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),e.heartbeatTimer=setTimeout(()=>{sf(e)},B1)}function sf(e){if(e.heartbeatTimer&&(clearTimeout(e.heartbeatTimer),e.heartbeatTimer=null),e.es&&(e.es.close(),e.es=null),ll(e),e.nativeListeners.clear(),e.closed||e.subscribers.size===0||e.reconnectTimer)return;const n=Ci.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=Ci.get(e.url);s&&s===e&&e.subscribers.size>0&&Sd(e)},H1)}}function Sd(e){if(e.es||e.closed)return;e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=null);const n=new EventSource(oi(W1(e.url)));e.es=n,G1(e),n.addEventListener("open",()=>{dr(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);sf(e)}),n.addEventListener("message",()=>dr(e)),n.addEventListener("heartbeat",()=>dr(e)),af(e),dr(e)}function af(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=>{dr(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 J1(e){e.closed=!0,e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),ll(e),e.reconnectTimer&&clearTimeout(e.reconnectTimer),e.es&&e.es.close(),e.es=null,e.nativeListeners.clear(),Ci.delete(e.url)}function Gs(e,n={}){let s=Ci.get(e);s||(s={url:e,es:null,subscribers:new Set,nativeListeners:new Map,heartbeatTimer:null,keepaliveTimer:null,reconnectTimer:null,hasOpenedOnce:!1,closed:!1},Ci.set(e,s));const i={events:new Map,onOpen:n.onOpen,onReconnect:n.onReconnect,onError:n.onError};if(n.events)for(const[l,c]of Object.entries(n.events)){let u=i.events.get(l);u||(u=new Set,i.events.set(l,u)),u.add(c)}s.subscribers.add(i);const r=!!s.es&&s.hasOpenedOnce;Sd(s),af(s),r&&queueMicrotask(()=>{s.subscribers.has(i)&&i.onOpen?.()});let o=!0;return()=>{if(!o)return;o=!1;const l=Ci.get(e);l&&(l.subscribers.delete(i),l.subscribers.size===0&&J1(l))}}const Cd="kb-planning-last-description",Ed="kb-subtask-last-description",_d="kb-mission-last-goal";function Y1(e,n){fs(Cd,e,n)}function Q1(e){return Wn(Cd,e)||""}function ra(e){Er(Cd,e)}function X1(e,n){fs(Ed,e,n)}function Z1(e){return Wn(Ed,e)||""}function Il(e){Er(Ed,e)}function eS(e,n){fs(_d,e,n)}function tS(e){return Wn(_d,e)||""}function ji(e){Er(_d,e)}function nS(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 sS(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 iS(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 Ls({entries:e,defaultShowThinking:n=!1}){const[s,i]=a.useState({}),r=iS(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?nS(o):void 0,h=o.question&&m!==void 0?sS(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(f=>({...f,[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 rm="fusion-tab-id";function aS(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Yi(){if(typeof window>"u")return"server-tab";const e=window.sessionStorage.getItem(rm);if(e)return e;const n=aS();return window.sessionStorage.setItem(rm,n),n}function cl(e){const n=a.useMemo(()=>Yi(),[]),[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(_w(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=Mw(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=oi(`/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:Gs("/api/events",{events:{"ai_session:updated":m=>{try{const h=JSON.parse(m.data);if(h.id!==e)return;const f=h.lockedByTab??null;o(f),i(!!(f&&f!==n))}catch{}}}}),[e,n]);const u=a.useCallback(async()=>{if(e){c(!0);try{await Promise.resolve(Aw(e,n)),i(!1),o(null)}finally{c(!1)}}},[e,n]);return{isLockedByOther:s,currentHolder:r,takeControl:u,isLoading:l}}const rS="fusion:ai-session-sync",om="fusion:ai-session-sync",oS=3e4,lS=6e4;function ei(){return Date.now()}function cS(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function lm(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 dS{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=cS(),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:ei()})}broadcastUpdate(n){const s=n.timestamp??ei();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??ei();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=ei();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=ei();this.releaseTabOwnership(n,s,i),this.ownedSessions.delete(n),this.publish({type:"tab:inactive",tabId:s,sessionId:n,timestamp:i})}broadcastHeartbeat(n){const s=ei();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(rS),this.channel.onmessage=s=>{const i=lm(s.data);i&&this.handleIncomingMessage(i)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==om||!s.newValue))try{const i=JSON.parse(s.newValue),r=lm(i.message);r&&this.handleIncomingMessage(r)}catch{}};window.addEventListener("storage",n),this.cleanupStorageListener=()=>{window.removeEventListener("storage",n)}}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{const n=ei();this.updateHeartbeat(this.tabId,n),this.publish({type:"tab:heartbeat",tabId:this.tabId,timestamp:n})},oS)}startStaleSweep(){this.staleSweepInterval=setInterval(()=>{this.emit()},1e4)}setupBeforeUnloadCleanup(){const n=()=>{for(const[s,i]of this.ownedSessions.entries()){const r=ei();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(om,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:ei()});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=ei(),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>lS;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 ti=new dS;function Ia(){const e=a.useSyncExternalStore(c=>ti.subscribe(c),()=>ti.getSnapshot(),()=>ti.getSnapshot());a.useEffect(()=>{ti.requestSync()},[]);const n=a.useCallback(c=>{ti.broadcastUpdate(c)},[]),s=a.useCallback(c=>{ti.broadcastCompleted(c)},[]),i=a.useCallback((c,u)=>{ti.broadcastLock(c,u)},[]),r=a.useCallback((c,u)=>{ti.broadcastUnlock(c,u)},[]),o=a.useCallback(c=>{ti.broadcastHeartbeat(c)},[]),l=a.useCallback(()=>{ti.requestSync()},[]);return{tabId:e.tabId,sessions:e.sessions,activeTabMap:e.activeTabMap,broadcastUpdate:n,broadcastCompleted:s,broadcastLock:i,broadcastUnlock:r,broadcastHeartbeat:o,requestSync:l}}function uS(e,n){return e&&n?`${e}/${n}`:""}function mS(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 hS=["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 pS({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),[f,p]=a.useState([]),[g,b]=a.useState([]),[v,x]=a.useState(null),[y,w]=a.useState(!1),E=a.useRef(!1),[C,j]=a.useState(""),[A,S]=a.useState(!0),[z,_]=a.useState(!1),[R,B]=a.useState(!1),[K,L]=a.useState(!1),$=a.useRef(null),U=a.useRef(null),G=a.useRef(null),Y=a.useRef(null),[ee,N]=a.useState(o??null),I=a.useMemo(()=>Yi(),[]),{isLockedByOther:T,takeControl:k,isLoading:H}=cl(e?ee:null),{activeTabMap:J,broadcastUpdate:ue,broadcastCompleted:fe,broadcastLock:W,broadcastUnlock:he,broadcastHeartbeat:O}=Ia(),{confirm:ne}=Ks(),[Q,ge]=a.useState(void 0),[de,me]=a.useState(void 0),[ie,Ee]=a.useState([]),[Ue,Te]=a.useState(!0),[at,et]=a.useState(null),[Ve,Xe]=a.useState([]),[De,Be]=a.useState([]),oe=uS(Q,de);a.useEffect(()=>{(async()=>{try{Te(!0);const re=await bs();Ee(re.models),Xe(re.favoriteProviders),Be(re.favoriteModels)}catch(re){et(we(re)||"Failed to load models")}finally{Te(!1)}})()},[]);const Ne=a.useCallback(Z=>{Xe(re=>{const je=re,te=je.includes(Z)?je.filter(Ze=>Ze!==Z):[Z,...je];return pn({favoriteProviders:te,favoriteModels:De}).catch(()=>{Xe(je)}),te})},[De]),se=a.useCallback(Z=>{Be(re=>{const je=re,te=je.includes(Z)?je.filter(Ze=>Ze!==Z):[Z,...je];return pn({favoriteProviders:Ve,favoriteModels:te}).catch(()=>{Be(je)}),te})},[Ve]),Me=a.useCallback((Z,re)=>{if(!Z||!re)return"Using default";const je=ie.find(rt=>rt.provider===Z&&rt.id===re);return je?`${je.provider}/${je.id}`:`${Z}/${re}`},[ie]),Le=a.useCallback(Z=>{U.current?.close();const re=pw(Z,i,{onThinking:je=>{j(rt=>rt+je),ue({sessionId:Z,status:"generating",needsInput:!1,owningTabId:I,type:"mission_interview",title:l.trim()||void 0,projectId:i??null})},onQuestion:je=>{_(!1),B(!1),ji(i),d({type:"question",sessionId:Z,question:je}),j(""),w(!0),ue({sessionId:Z,status:"awaiting_input",needsInput:!0,owningTabId:I,type:"mission_interview",title:l.trim()||void 0,projectId:i??null})},onSummary:je=>{_(!1),B(!1),ji(i),d({type:"summary",sessionId:Z,summary:je}),x(je),j(""),w(!0),ue({sessionId:Z,status:"complete",needsInput:!1,owningTabId:I,type:"mission_interview",title:l.trim()||void 0,projectId:i??null})},onError:je=>{const rt=je||"Session failed while contacting the AI.";_(!1),B(!1),h(null),d({type:"error",sessionId:Z,errorMessage:rt}),j(""),w(!0),G.current=Z,ue({sessionId:Z,status:"error",needsInput:!1,owningTabId:I,type:"mission_interview",title:l.trim()||void 0,projectId:i??null}),fe({sessionId:Z,status:"error"})},onComplete:()=>{_(!1),B(!1),G.current=null,fe({sessionId:Z,status:"complete"})},onConnectionStateChange:je=>{_(je==="reconnecting")}});U.current=re},[fe,ue,l,i,I]),pe=a.useCallback(async Z=>{const re=Z??l;if(re.trim()){h(null),j(""),p([]),b([]),_(!1),d({type:"loading"});try{const{sessionId:je}=await dw(re.trim(),i,Q&&de?{modelProvider:Q,modelId:de}:void 0);G.current=je,N(je),ji(i),Le(je),p([])}catch(je){_(!1),h(we(je)||"Failed to start interview session"),d({type:"initial"}),G.current=null,N(null)}}},[Le,l,Q,de,i]);a.useEffect(()=>{e&&u.type==="initial"&&$.current?.focus()},[e,u.type]),a.useEffect(()=>{if(e&&r&&!E.current&&u.type==="initial"){c(r);const Z=setTimeout(()=>{E.current=!0,pe(r)},0);return()=>clearTimeout(Z)}else if(e&&!r&&!E.current&&u.type==="initial"){const Z=tS(i);Z&&c(Z)}},[e,r,u.type,pe]),a.useEffect(()=>{e||(E.current=!1,_(!1),B(!1),N(null))},[e]),a.useEffect(()=>{if(!e||!o||u.type!=="initial")return;let Z=!1;return ai(o).then(re=>{if(Z||!re)return;const je=ya(re.conversationHistory);if(b(je),N(re.id),p(je.map(rt=>rt.response).filter(rt=>!!(rt&&typeof rt=="object"&&!Array.isArray(rt)))),re.status==="awaiting_input"&&re.currentQuestion)try{ji(i);const rt=JSON.parse(re.currentQuestion);G.current=re.id,w(!0),d({type:"question",sessionId:re.id,question:rt})}catch{h("Failed to restore session question.")}else if(re.status==="complete"&&re.result)try{ji(i);const rt=JSON.parse(re.result);G.current=re.id,w(!0),x(rt),d({type:"summary",sessionId:re.id,summary:rt})}catch{h("Failed to restore session result.")}else re.status==="generating"?(G.current=re.id,w(!0),re.thinkingOutput&&j(re.thinkingOutput),d({type:"loading"}),Le(re.id)):re.status==="error"&&(G.current=re.id,w(!0),h(null),d({type:"error",sessionId:re.id,errorMessage:re.error??"The session encountered an error."}))}).catch(()=>{Z||h("Failed to resume session.")}),()=>{Z=!0}},[Le,e,o,u.type,i]),a.useEffect(()=>{if(!e){Y.current&&(he(Y.current,I),Y.current=null);return}if(ee&&Y.current!==ee){Y.current&&he(Y.current,I),W(ee,I),Y.current=ee;return}!ee&&Y.current&&(he(Y.current,I),Y.current=null)},[W,he,e,ee,I]),a.useEffect(()=>{if(!e||!ee||Y.current!==ee)return;O(I);const Z=setInterval(()=>{O(I)},3e4);return()=>{clearInterval(Z)}},[O,e,ee,I]),a.useEffect(()=>()=>{U.current?.close(),U.current=null,Y.current&&(he(Y.current,I),Y.current=null)},[he,I]),a.useEffect(()=>{if(!e)return;const Z=re=>{(u.type==="question"||u.type==="summary")&&(re.preventDefault(),re.returnValue=""),U.current?.close()};return window.addEventListener("beforeunload",Z),()=>window.removeEventListener("beforeunload",Z)},[e,u]);const Ae=a.useCallback(()=>{U.current?.close(),U.current=null,n()},[n]),Je=a.useCallback(async()=>{if(l&&eS(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(U.current?.close(),U.current=null,u.type==="question"||u.type==="summary"||u.type==="error")try{await $p(u.sessionId,i,I)}catch{}c(""),d({type:"initial"}),h(null),p([]),b([]),x(null),j(""),_(!1),B(!1),w(!1),L(!1),ge(void 0),me(void 0),G.current=null,N(null),n()}},[l,y,u,n,i,I,ne]);a.useEffect(()=>{if(!e)return;const Z=re=>{re.key==="Escape"&&Je()};return document.addEventListener("keydown",Z),()=>document.removeEventListener("keydown",Z)},[e,Je]);const it=a.useCallback(async Z=>{if(u.type!=="question")return;const{sessionId:re}=u;h(null),p(je=>[...je,Z]),b(je=>[...je,{question:u.question,response:Z}]),d({type:"loading"}),j("");try{Le(re),await uw(re,Z,i,I),w(!0)}catch(je){U.current?.close(),U.current=null,h(we(je)||"Failed to submit response"),d({type:"question",sessionId:re,question:u.question})}},[u,i,I,Le]),ye=a.useCallback(async()=>{if(u.type!=="error")return;const Z=u.sessionId;h(null),B(!0),j(""),d({type:"loading"}),Le(Z);try{G.current=Z,N(Z),await mw(Z,i,I)}catch(re){let je=re;if((we(re)||"").includes("not in an error state"))try{const te=await ai(Z);if(!te)throw new Error("Failed to refresh interview session.");const Ze=ya(te.conversationHistory);if(b(Ze),p(Ze.map(pt=>pt.response).filter(pt=>!!(pt&&typeof pt=="object"&&!Array.isArray(pt)))),G.current=te.id,N(te.id),w(!0),te.status==="generating")j(te.thinkingOutput??""),d({type:"loading"}),U.current?.isConnected()||Le(te.id);else if(te.status==="awaiting_input"){if(!te.currentQuestion)throw new Error("Interview session is awaiting input but has no current question.");ji(i);const pt=JSON.parse(te.currentQuestion);d({type:"question",sessionId:te.id,question:pt}),U.current?.isConnected()||Le(te.id)}else if(te.status==="complete"){if(!te.result)throw new Error("Interview session is complete but has no result.");ji(i);const pt=JSON.parse(te.result);x(pt),d({type:"summary",sessionId:te.id,summary:pt})}else te.status==="error"&&d({type:"error",sessionId:te.id,errorMessage:te.error??"Retry failed. Please try again."});_(!1);return}catch(te){je=te}U.current?.close(),U.current=null,d({type:"error",sessionId:Z,errorMessage:we(je)||"Retry failed. Please try again."}),_(!1)}finally{B(!1)}},[Le,i,I,u]),ce=a.useCallback(async()=>{if(u.type==="summary"){h(null),L(!0);try{const Z=await hw(u.sessionId,v||void 0,i);s(Z),ji(i),U.current?.close(),U.current=null,c(""),d({type:"initial"}),h(null),p([]),b([]),x(null),j(""),_(!1),B(!1),w(!1),L(!1),G.current=null,N(null),n()}catch(Z){h(we(Z)||"Failed to create mission"),L(!1)}}},[u,v,s,n,i]),Re=()=>u.type==="question"?Math.min(f.length+1,6):6,be=u.type==="loading"||u.type==="question"||u.type==="summary"||u.type==="error",Pe=ee?J.get(ee):null,Ye=Pe&&Pe.tabId!==I,$e=!!(Ye&&!Pe.stale),ft=T&&(!Ye||Pe.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Z=>Z.target===Z.currentTarget&&Je(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(ws,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Plan Mission with AI"})]}),t.jsxs("div",{className:"modal-header-actions",children:[be&&t.jsx("button",{className:"modal-send-to-background",onClick:Ae,title:"Send to background","aria-label":"Send to background",children:t.jsx(Dr,{size:16})}),t.jsx("button",{className:"modal-close",onClick:Je,"aria-label":"Close",children:t.jsx(Ht,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[m&&t.jsx("div",{className:"form-error planning-error",children:m}),z&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),$e&&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(cs,{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:$,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:Z=>c(Z.target.value),onKeyDown:Z=>{Z.key==="Enter"&&!Z.shiftKey&&l.trim()&&(Z.preventDefault(),pe())}})]}),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:hS.map((Z,re)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>c(Z),children:Z.length>45?Z.slice(0,45)+"...":Z},re))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"mission-interview-modal-model",className:"form-label",children:["Planning Model",Ue&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(Zn,{id:"mission-interview-modal-model",label:"Planning Model",value:oe,onChange:Z=>{const{provider:re,modelId:je}=mS(Z);ge(re),me(je)},models:ie,disabled:Ue,favoriteProviders:Ve,onToggleFavorite:Ne,favoriteModels:De,onToggleModelFavorite:se}),at&&t.jsxs("div",{className:"form-hint form-hint-error",children:[at," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{Te(!0);const Z=await bs();Ee(Z.models),Xe(Z.favoriteProviders),Be(Z.favoriteModels),et(null)}catch(Z){et(we(Z)||"Failed to load models")}finally{Te(!1)}})()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${Q&&de?"model-badge-custom":"model-badge-default"}`,children:Me(Q,de)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>pe(),disabled:!l.trim(),children:[t.jsx(ws,{size:16,className:"icon-mr-8"}),"Start Interview"]})})]}),u.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(ot,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:C?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>S(!A),type:"button",children:A?"Hide thinking":"Show thinking"}),A&&C&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:C})})]})]}),u.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[g.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ls,{entries:g}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:u.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void ye(),disabled:R,children:[R?t.jsx(ot,{size:14,className:"spin"}):t.jsx(Ln,{size:14}),t.jsx("span",{className:"icon-ml-6",children:R?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Je,disabled:R,children:"Cancel"})]})]})]})}),u.type==="question"&&t.jsx(fS,{question:u.question,progress:Re(),historyEntries:g,onSubmit:it}),u.type==="summary"&&v&&t.jsx(gS,{summary:v,historyEntries:g,onSummaryChange:x,onApprove:ce,onStartOver:()=>{d({type:"initial"}),w(!1),x(null),p([]),b([]),N(null),U.current?.close(),U.current=null},isCreating:K}),T&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Zo,{size:16}),t.jsx("span",{children:ft?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),ft&&t.jsx("button",{type:"button",onClick:()=>{k()},disabled:H,className:"btn btn-primary session-lock-take-control",children:H?"Taking control...":"Take Control"})]})})]})]})}):null}function fS({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(Ls,{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:f=>{const p=f.target.checked?[...h,m.id]:h.filter(g=>g!==m.id);o({[e.id]:p})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!0?"selected":""}`,onClick:()=>o({[e.id]:!0}),children:[t.jsx(wn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(Ht,{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(Pr,{size:16,className:"icon-ml-4"})]})})]})}function gS({summary:e,historyEntries:n,onSummaryChange:s,onApprove:i,onStartOver:r,isCreating:o}){const[l,c]=a.useState(()=>new Set(e.milestones.map((E,C)=>C))),[u,d]=a.useState(()=>{const E=new Set;return e.milestones.forEach((C,j)=>{C.slices.forEach((A,S)=>E.add(`${j}-${S}`))}),E}),m=E=>{c(C=>{const j=new Set(C);return j.has(E)?j.delete(E):j.add(E),j})},h=E=>{d(C=>{const j=new Set(C);return j.has(E)?j.delete(E):j.add(E),j})},f=(E,C)=>{const j=[...e.milestones];j[E]={...j[E],...C},s({...e,milestones:j})},p=(E,C,j)=>{const A=[...e.milestones],S=[...A[E].slices];S[C]={...S[C],...j},A[E]={...A[E],slices:S},s({...e,milestones:A})},g=(E,C,j,A)=>{const S=[...e.milestones],z=[...S[E].slices],_=[...z[C].features];_[j]={..._[j],...A},z[C]={...z[C],features:_},S[E]={...S[E],slices:z},s({...e,milestones:S})},b=E=>{const C=e.milestones.filter((j,A)=>A!==E);s({...e,milestones:C})},v=(E,C)=>{const j=[...e.milestones];j[E]={...j[E],slices:j[E].slices.filter((A,S)=>S!==C)},s({...e,milestones:j})},x=(E,C,j)=>{const A=[...e.milestones],S=[...A[E].slices];S[C]={...S[C],features:S[C].features.filter((z,_)=>_!==j)},A[E]={...A[E],slices:S},s({...e,milestones:A})},y=(E,C)=>{const j=[...e.milestones],A=[...j[E].slices];A[C]={...A[C],features:[...A[C].features,{title:"New feature",description:""}]},j[E]={...j[E],slices:A},s({...e,milestones:j})},w=e.milestones.reduce((E,C)=>E+C.slices.reduce((j,A)=>j+A.features.length,0),0);return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ls,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(wn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Mission Plan Ready"}),t.jsxs("p",{className:"text-muted",children:[e.milestones.length," milestones, ",w," 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:E=>s({...e,missionTitle:E.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:E=>s({...e,missionDescription:E.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Roadmap"}),t.jsx("div",{className:"roadmap-list",children:e.milestones.map((E,C)=>t.jsxs("div",{className:"roadmap-card",children:[t.jsxs("div",{className:"roadmap-card-header",onClick:()=>m(C),children:[l.has(C)?t.jsx(Xt,{size:16,className:"icon-text-secondary"}):t.jsx(xn,{size:16,className:"icon-text-secondary"}),t.jsx(Hi,{size:16,className:"icon-milestone"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-title",value:E.title,onChange:j=>f(C,{title:j.target.value}),onClick:j=>j.stopPropagation()}),e.milestones.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:j=>{j.stopPropagation(),b(C)},title:"Remove milestone",children:t.jsx(an,{size:14,className:"icon-text-secondary"})})]}),l.has(C)&&t.jsxs("div",{className:"roadmap-card-body",children:[t.jsx("textarea",{className:"planning-textarea roadmap-textarea-md",rows:2,placeholder:"Milestone description...",value:E.description||"",onChange:j=>f(C,{description:j.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:E.verification||"",onChange:j=>f(C,{verification:j.target.value})})]}),E.slices.map((j,A)=>{const S=`${C}-${A}`;return t.jsxs("div",{className:"roadmap-slice-card",children:[t.jsxs("div",{className:"roadmap-slice-header",onClick:()=>h(S),children:[u.has(S)?t.jsx(Xt,{size:14,className:"icon-text-secondary"}):t.jsx(xn,{size:14,className:"icon-text-secondary"}),t.jsx(Ic,{size:14,className:"icon-slice"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:j.title,onChange:z=>p(C,A,{title:z.target.value}),onClick:z=>z.stopPropagation()}),E.slices.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:z=>{z.stopPropagation(),v(C,A)},title:"Remove slice",children:t.jsx(an,{size:12,className:"icon-text-secondary"})})]}),u.has(S)&&t.jsxs("div",{className:"roadmap-slice-body",children:[t.jsxs("div",{className:"roadmap-slice-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Slice Verification"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-xs",rows:1,placeholder:"How to confirm this slice is done...",value:j.verification||"",onChange:z=>p(C,A,{verification:z.target.value})})]}),j.features.map((z,_)=>t.jsxs("div",{className:"roadmap-feature-row",children:[t.jsx(Ec,{size:12,className:"icon-feature"}),t.jsxs("div",{className:"roadmap-feature-content",children:[t.jsx("input",{type:"text",className:"form-input roadmap-input-feature",value:z.title,onChange:R=>g(C,A,_,{title:R.target.value})}),z.description&&t.jsx("p",{className:"roadmap-feature-text",children:z.description}),z.acceptanceCriteria&&t.jsxs("p",{className:"roadmap-feature-text--italic",children:["AC: ",z.acceptanceCriteria]})]}),t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:()=>x(C,A,_),title:"Remove feature",children:t.jsx(an,{size:12,className:"icon-text-secondary"})})]},_)),t.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>y(C,A),children:[t.jsx(rn,{size:12}),"Add Feature"]})]})]},A)})]})]},C))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:r,disabled:o,children:[t.jsx(_a,{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(ot,{size:16,className:"spin icon-mr-8"}),"Creating Mission..."]}):t.jsxs(t.Fragment,{children:[t.jsx(wn,{size:16,className:"icon-mr-8"}),"Approve Plan"]})})]})]})}function bS({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,f]=a.useState(null),[p,g]=a.useState([]),[b,v]=a.useState([]),[x,y]=a.useState(null),[w,E]=a.useState(""),[C,j]=a.useState(!0),[A,S]=a.useState(!1),[z,_]=a.useState(!1),R=a.useRef(null),B=a.useRef(null),K=a.useRef(null),L=a.useRef(null),[$,U]=a.useState(null),G=a.useMemo(()=>Yi(),[]);cl(e?$:null);const{activeTabMap:Y,broadcastUpdate:ee,broadcastCompleted:N,broadcastLock:I,broadcastUnlock:T,broadcastHeartbeat:k}=Ia(),H=i==="milestone"?fw:yw,J=i==="milestone"?gw:jw,ue=i==="milestone"?bw:kw,fe=i==="milestone"?xw:ww,W=i==="milestone"?vw:Nw,he=i==="milestone"?"Milestone":"Slice",O=i==="milestone"?"milestone_interview":"slice_interview",ne=a.useCallback(De=>{B.current?.close();const Be=ue(De,c,{onThinking:oe=>{E(Ne=>Ne+oe),ee({sessionId:De,status:"generating",needsInput:!1,owningTabId:G,type:O,title:o,projectId:c??null})},onQuestion:oe=>{S(!1),Q(),m({type:"question",sessionId:De,question:oe}),E(""),ee({sessionId:De,status:"awaiting_input",needsInput:!0,owningTabId:G,type:O,title:o,projectId:c??null})},onSummary:oe=>{S(!1),Q(),m({type:"summary",sessionId:De,summary:oe}),y(oe),E(""),ee({sessionId:De,status:"complete",needsInput:!1,owningTabId:G,type:O,title:o,projectId:c??null})},onError:oe=>{const Ne=oe||"Session failed while contacting the AI.";S(!1),f(null),m({type:"error",sessionId:De,errorMessage:Ne}),E(""),K.current=De,ee({sessionId:De,status:"error",needsInput:!1,owningTabId:G,type:O,title:o,projectId:c??null}),N({sessionId:De,status:"error"})},onComplete:()=>{S(!1),K.current=null,N({sessionId:De,status:"complete"})},onConnectionStateChange:oe=>{S(oe==="reconnecting")}});B.current=Be},[N,ee,ue,O,c,G,o]),Q=()=>{y(null),g([]),v([]),E("")},ge=a.useCallback(async()=>{f(null),Q(),S(!1),m({type:"loading"});try{const{sessionId:De}=await H(r,c);K.current=De,U(De),ne(De)}catch(De){S(!1),f(we(De)||`Failed to start ${he.toLowerCase()} interview`),m({type:"initial"}),K.current=null,U(null)}},[ne,c,H,r,he]),de=a.useCallback(async()=>{f(null),_(!0);try{await W(r,c),s(),m({type:"applied"})}catch(De){f(we(De)||`Failed to skip ${he.toLowerCase()} interview`),_(!1)}},[s,c,W,r,he]);a.useEffect(()=>{e&&d.type==="initial"&&R.current?.focus()},[e,d.type]),a.useEffect(()=>{if(!e||!u||d.type!=="initial")return;let De=!1;return ai(u).then(Be=>{if(De||!Be)return;const oe=ya(Be.conversationHistory);if(v(oe),U(Be.id),g(oe.map(Ne=>Ne.response).filter(Ne=>!!(Ne&&typeof Ne=="object"&&!Array.isArray(Ne)))),Be.status==="awaiting_input"&&Be.currentQuestion)try{const Ne=JSON.parse(Be.currentQuestion);K.current=Be.id,m({type:"question",sessionId:Be.id,question:Ne})}catch{f("Failed to restore session question.")}else if(Be.status==="complete"&&Be.result)try{const Ne=JSON.parse(Be.result);K.current=Be.id,y(Ne),m({type:"summary",sessionId:Be.id,summary:Ne})}catch{f("Failed to restore session result.")}else Be.status==="generating"?(K.current=Be.id,Be.thinkingOutput&&E(Be.thinkingOutput),m({type:"loading"}),ne(Be.id)):Be.status==="error"&&(K.current=Be.id,f(null),m({type:"error",sessionId:Be.id,errorMessage:Be.error??"The session encountered an error."}))}).catch(()=>{De||f("Failed to resume session.")}),()=>{De=!0}},[ne,e,u,d.type]),a.useEffect(()=>{e||(S(!1),U(null))},[e]),a.useEffect(()=>{if(!(!e||!$)){if(L.current!==$){L.current&&T(L.current,G),I($,G),L.current=$;return}!$&&L.current&&(T(L.current,G),L.current=null)}},[I,T,e,$,G]),a.useEffect(()=>{if(!e||!$||L.current!==$)return;k(G);const De=setInterval(()=>{k(G)},3e4);return()=>{clearInterval(De)}},[k,e,$,G]),a.useEffect(()=>()=>{B.current?.close(),B.current=null,L.current&&(T(L.current,G),L.current=null)},[T,G]);const me=a.useCallback(()=>{B.current?.close(),B.current=null,n()},[n]),ie=a.useCallback(async()=>{B.current?.close(),B.current=null,Q(),m({type:"initial"}),f(null),K.current=null,U(null),n()},[n]),Ee=a.useCallback(async De=>{if(d.type!=="question")return;const{sessionId:Be}=d;f(null),g(oe=>[...oe,De]),v(oe=>[...oe,{question:d.question,response:De}]),m({type:"loading"}),E("");try{ne(Be),await J(Be,De,c,G)}catch(oe){B.current?.close(),B.current=null,f(we(oe)||"Failed to submit response"),m({type:"question",sessionId:Be,question:d.question})}},[ne,c,J,G,d]),Ue=a.useCallback(async()=>{if(d.type==="summary"){f(null),_(!0);try{await fe(d.sessionId,x||void 0,c),s(),m({type:"applied"})}catch(De){f(we(De)||"Failed to apply interview results"),_(!1)}}},[fe,x,s,c,d]),Te=()=>d.type==="question"?Math.min(p.length+1,6):6,at=d.type==="loading"||d.type==="question"||d.type==="summary"||d.type==="error",et=$?Y.get($):null,Xe=!!(et&&et.tabId!==G&&!et.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:De=>De.target===De.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(cs,{size:20,className:"icon-triage"}),t.jsxs("h3",{children:["Plan ",he,": ",o]})]}),t.jsxs("div",{className:"modal-header-actions",children:[at&&t.jsx("button",{className:"modal-send-to-background",onClick:me,title:"Send to background","aria-label":"Send to background",children:t.jsx(Dr,{size:16})}),t.jsx("button",{className:"modal-close",onClick:ie,"aria-label":"Close",children:t.jsx(Ht,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[h&&t.jsx("div",{className:"form-error planning-error",children:h}),A&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Xe&&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(cs,{size:32,className:"icon-triage-lg"}),t.jsxs("h4",{children:["Refine ",he," scope with AI"]}),t.jsxs("p",{className:"text-muted",children:["The AI will interview you to refine the ",i,"'s scope, acceptance criteria, and verification methods. Each ",i," can have its own refined plan or inherit context from the mission level."]}),l&&t.jsxs("div",{className:"planning-context-info",children:[t.jsx("span",{className:"planning-context-label",children:"Mission context:"}),t.jsx("span",{className:"planning-context-text",children:l})]})]})}),t.jsxs("div",{className:"planning-view-footer",children:[t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>void ge(),children:[t.jsx(cs,{size:16,className:"icon-mr-8"}),"Start Interview"]}),t.jsxs("button",{className:"btn planning-use-context-btn",onClick:()=>void de(),disabled:z,children:[z?t.jsx(ot,{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(ot,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:w?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>j(!C),type:"button",children:C?"Hide thinking":"Show thinking"}),C&&w&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:w})})]})]}),d.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[b.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ls,{entries:b}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:d.errorMessage}),t.jsx("div",{className:"ai-error-actions",children:t.jsx("button",{className:"btn",onClick:ie,children:"Cancel"})})]})]})}),d.type==="question"&&t.jsx(xS,{question:d.question,progress:Te(),historyEntries:b,onSubmit:Ee}),d.type==="summary"&&x&&t.jsx(vS,{summary:x,historyEntries:b,onSummaryChange:y,onApply:Ue,onCancel:ie,isApplying:z}),d.type==="applied"&&t.jsxs("div",{className:"planning-summary planning-applied",children:[t.jsx("div",{className:"planning-view-scroll",children:t.jsxs("div",{className:"planning-applied-content",children:[t.jsx(wn,{size:48,className:"icon-success"}),t.jsxs("h4",{children:[he," Updated"]}),t.jsxs("p",{className:"text-muted",children:["The ",i,"'s scope and verification have been ",d.type==="applied"?"applied":"updated","."]})]})}),t.jsx("div",{className:"planning-view-footer",children:t.jsx("button",{className:"btn btn-primary",onClick:s,children:"Done"})})]})]})]})}):null}function xS({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(Ls,{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:f=>{const p=f.target.checked?[...h,m.id]:h.filter(g=>g!==m.id);o({[e.id]:p})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!0?"selected":""}`,onClick:()=>o({[e.id]:!0}),children:[t.jsx(wn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(Ht,{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(Pr,{size:16,className:"icon-ml-4"})]})})]})}function vS({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,f)=>{const p={...l,[h]:f};c(p),s(p)};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ls,{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(Xt,{size:16}):t.jsx(xn,{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(ot,{size:16,className:"spin"}):null,"Apply"]}),t.jsx("button",{className:"btn",onClick:r,disabled:o,children:"Cancel"})]})]})}const Wa={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)"}},cm={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)"}},dm={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)"}},io={defined:{bg:"var(--feature-defined-bg)",text:"var(--feature-defined-text)"},triaged:{bg:"var(--feature-triaged-bg)",text:"var(--feature-triaged-text)"},"in-progress":{bg:"var(--feature-in-progress-bg)",text:"var(--feature-in-progress-text)"},done:{bg:"var(--feature-done-bg)",text:"var(--feature-done-text)"}},ao={inactive:{bg:"var(--autopilot-inactive-bg)",text:"var(--autopilot-inactive-text)"},watching:{bg:"var(--autopilot-watching-bg)",text:"var(--autopilot-watching-text)"},activating:{bg:"var(--autopilot-activating-bg)",text:"var(--autopilot-activating-text)"},completing:{bg:"var(--autopilot-completing-bg)",text:"var(--autopilot-completing-text)"}},ro={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)"}},um={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)"}},yS=3;function jS(e){return e==="completed"?"planned":e==="needs_update"?"needs_update":"not_started"}function mm({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 hm(e){return e?e.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const $l={title:"",description:"",status:"planning",autopilotEnabled:!1},Dl={title:"",description:"",status:"planning",dependencies:[]},Ll={title:"",description:"",status:"pending"},zl={title:"",description:"",acceptanceCriteria:"",status:"defined"},kS=3600*1e3;function Oo(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 wS(e){if(!e)return"healthy";const n=typeof e.lastErrorAt=="string"&&Date.now()-new Date(e.lastErrorAt).getTime()<=kS,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 NS(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 SS(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 Fl(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 rf=["feature_triaged","feature_completed"],of=["slice_activated","slice_completed","milestone_completed"],lf=["mission_started","mission_paused","mission_resumed","mission_completed"],cf=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function pm(e,n){switch(n){case"errors":return e==="error"||e==="warning";case"state_changes":return lf.includes(e);case"tasks":return rf.includes(e);case"slices":return of.includes(e);case"autopilot":return cf.includes(e);default:return!0}}function CS(e){return e==="error"||e==="warning"?"mission-event__type--error":lf.includes(e)?"mission-event__type--state":rf.includes(e)?"mission-event__type--task":of.includes(e)?"mission-event__type--slice":cf.includes(e)?"mission-event__type--autopilot":"mission-event__type--default"}function ES(e){return e.replace(/_/g," ")}function _S(e,n){return n?e==="watching"?`Watching since ${Oo(n)}`:`Last activation ${Oo(n)}`:null}function MS({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,[f,p]=a.useState([]),[g,b]=a.useState(null),[v,x]=a.useState(!0),[y,w]=a.useState(!1),[E,C]=a.useState(!1),[j,A]=a.useState(null),[S,z]=a.useState($l),[_,R]=a.useState(!1),[B,K]=a.useState(new Set),[L,$]=a.useState(new Set),[U,G]=a.useState(null),[Y,ee]=a.useState(Dl),[N,I]=a.useState(!1),[T,k]=a.useState(null),[H,J]=a.useState(Ll),[ue,fe]=a.useState(!1),[W,he]=a.useState(null),[O,ne]=a.useState(null),[Q,ge]=a.useState(zl),[de,me]=a.useState(!1),[ie,Ee]=a.useState(null),[Ue,Te]=a.useState(null),[at,et]=a.useState(""),[Ve,Xe]=a.useState(!1),[De,Be]=a.useState([]),[oe,Ne]=a.useState(void 0),se=oe??c,[Me,Le]=a.useState(null),[pe,Ae]=a.useState(null),[Je,it]=a.useState(null);a.useEffect(()=>{h&&se&&Xe(!0)},[h,se]),a.useEffect(()=>{if(!h||se)return;let q=!1;return xd(r).then(Ce=>{if(q)return;const Ie=Ce.filter(xt=>xt.type==="mission_interview"&&(xt.status==="awaiting_input"||xt.status==="error"));Be(Ie)}).catch(Ce=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",Ce)}),()=>{q=!0}},[h,r,se]),a.useEffect(()=>{if(!h||!d)return;let q=!1;return ai(d).then(Ce=>{if(!(q||!Ce))try{const Ie=JSON.parse(Ce.inputPayload||"{}");Ie.targetId&&Ie.targetType&&Le({type:Ie.targetType,id:Ie.targetId,title:Ie.targetTitle||Ce.title,resumeSessionId:d})}catch{Le({type:"milestone",id:"",title:Ce.title,resumeSessionId:d})}}).catch(Ce=>{q||(console.warn("[MissionManager] Failed to fetch session for milestone/slice resume:",Ce),m?.())}),()=>{q=!0}},[h,d,m]);const[ye,ce]=a.useState(null),[Re,be]=a.useState(new Map),[Pe,Ye]=a.useState(null),[$e,ft]=a.useState({title:"",assertion:"",status:"pending"}),[Z,re]=a.useState(!1),[je,rt]=a.useState(null),[te,Ze]=a.useState(new Map),[pt,gt]=a.useState(new Set),[wt,Et]=a.useState(new Set),[mt,Nt]=a.useState(null),[Tt,qt]=a.useState(new Map),[Pt,At]=a.useState(null),[Bt,Ft]=a.useState(null),[Dt,Mt]=a.useState(!0),[St,Wt]=a.useState(new Set),[It,Yt]=a.useState(new Map),[Rt,xe]=a.useState(null),[Fe,ct]=a.useState(new Map),[D,F]=a.useState(null),[ve,ze]=a.useState(new Map),[Oe,Ge]=a.useState(new Map),[dt,Zt]=a.useState("structure"),[Nn,un]=a.useState([]),Kt=a.useRef([]),mn=a.useRef([]),ke=a.useRef(null),ut=a.useRef(null),Lt=a.useRef("structure"),En=a.useRef("all"),[hn,Rn]=a.useState(!1),[is,Dn]=a.useState(0),[nn,cn]=a.useState("all"),[Hn,fn]=a.useState(new Set),dn=a.useRef(null),_n=a.useRef(null);mn.current=f,ke.current=g,ut.current=Pt,Lt.current=dt,En.current=nn;const zn=a.useCallback((q="auto")=>{const Ce=_n.current;if(Ce&&typeof Ce.scrollIntoView=="function"){Ce.scrollIntoView({block:"end",behavior:q});return}const Ie=dn.current;Ie&&(Ie.scrollTop=Ie.scrollHeight)},[]),es=a.useCallback(()=>{const q=dn.current;return q?q.scrollHeight-q.scrollTop-q.clientHeight<=100:!0},[]),Fn=a.useCallback(async q=>{if(q.length===0){Ge(new Map);return}const Ce=await Lk(r);Ge(Ie=>{const xt=new Map(Ie);for(const[bn,_t]of Object.entries(Ce))NS(_t)&&xt.set(bn,_t);return xt})},[r]),Qt=a.useCallback(async()=>{try{x(!0);const q=await Tk(r);p(q),Fn(q)}catch(q){i(we(q)||"Failed to load missions","error")}finally{x(!1)}},[i,r,Fn]),yt=a.useCallback(async q=>{try{w(!0);const Ce=await Ip(q,r);if(b(Ce),Ce.milestones.length>0){const Ie=Ce.milestones[0].id;At(Ie),Mt(!0),K(new Set([Ie])),wl(Ie,r).then(xt=>{be(bn=>{const _t=new Map(bn);return _t.set(Ie,xt),_t})}).catch(()=>{}),Nl(Ie,r).then(xt=>{qt(bn=>{const _t=new Map(bn);return _t.set(Ie,xt),_t})}).catch(()=>{}),Ce.milestones[0].slices.length>0&&$(new Set([Ce.milestones[0].slices[0].id]))}else At(null),Ft(null)}catch(Ce){i(we(Ce)||"Failed to load mission details","error")}finally{w(!1)}},[i,r]);a.useEffect(()=>{if(!h||!Pt){Ft(null);return}let q=!1;return Ft(null),xu(Pt,r).then(Ce=>{if(!q){if(!Fl(Ce)){Ft(null);return}Ft(Ce),qt(Ie=>{const xt=new Map(Ie);return xt.set(Pt,Ce.rollup),xt})}}).catch(()=>{q||Ft(null)}),()=>{q=!0}},[h,Pt,r]),a.useEffect(()=>{Mt(!0)},[Pt]);const on=a.useCallback(q=>{!q||q!==ut.current||xu(q,r).then(Ce=>{ut.current!==q||!Fl(Ce)||(Ft(Ce),qt(Ie=>{const xt=new Map(Ie);return xt.set(q,Ce.rollup),xt}))}).catch(()=>{})},[r]),M=a.useCallback(async(q,Ce)=>{const Ie=Ce?.append??!1,xt=Ie?Kt.current.length:0;Ie||(Rn(!0),fn(new Set));try{const bn=await Dk(q,{limit:50,offset:xt,eventType:void 0},r),_t=bn.events.filter(Gt=>pm(Gt.eventType,nn));un(Gt=>{if(!Ie)return _t;const He=new Set(Gt.map(vt=>vt.id)),qe=[...Gt];for(const vt of _t)He.has(vt.id)||qe.push(vt);return qe}),Dn(bn.total),Ie||requestAnimationFrame(()=>{zn("auto")})}catch(bn){i(we(bn)||"Failed to load mission activity","error")}finally{Ie||Rn(!1)}},[i,nn,r,zn]);a.useEffect(()=>{Kt.current=Nn},[Nn]),a.useEffect(()=>{h&&(Qt(),b(null),At(null),Ft(null),un([]),Dn(0),Zt("structure"),cn("all"),fn(new Set))},[h,Qt]);const le=a.useRef(null);a.useEffect(()=>{h&&u&&le.current!==u&&f.length>0&&(le.current=u,yt(u))},[h,u,f,yt]),a.useEffect(()=>{h||(le.current=null)},[h]),a.useEffect(()=>{!h||!g||dt!=="activity"||M(g.id)},[dt,h,M,g,nn]),a.useEffect(()=>{if(!h||typeof EventSource>"u")return;const q=new URLSearchParams;r&&q.set("projectId",r);const Ce=`/api/events${q.size>0?`?${q.toString()}`:""}`,Ie=()=>{Fn(mn.current)},xt=ss=>{Ie();const Mn=ss;if(Mn.data)try{const Vt=JSON.parse(Mn.data);Vt?.id&&p(Ii=>Ii.map(Ts=>Ts.id===Vt.id?{...Ts,...Vt}:Ts))}catch{}ke.current&&yt(ke.current.id)},bn=ss=>{Ie(),ke.current&&yt(ke.current.id)},_t=()=>{Ie(),ke.current&&yt(ke.current.id)},Gt=ss=>{Ie(),ke.current&&yt(ke.current.id)},He=ss=>{const Mn=ss;if(Mn.data)try{const Vt=JSON.parse(Mn.data);Vt&&Vt.featureId&&(Qs(Vt.featureId),mi(Vt.featureId),Vt.milestoneId&&on(Vt.milestoneId))}catch{}},qe=ss=>{const Mn=ss;if(Mn.data)try{const Vt=JSON.parse(Mn.data);Vt&&Vt.featureId&&(Qs(Vt.featureId),mi(Vt.featureId),Vt.milestoneId&&on(Vt.milestoneId),ke.current&&yt(ke.current.id))}catch{}},vt=ss=>{const Mn=ss;if(Mn.data)try{const Vt=JSON.parse(Mn.data);Vt&&Vt.milestoneId&&(Jn(Vt.milestoneId),on(Vt.milestoneId))}catch{}},jn=ss=>{const Mn=ss;if(Mn.data)try{const Vt=JSON.parse(Mn.data);Vt&&Vt.milestoneId&&($n(Vt.milestoneId),Jn(Vt.milestoneId),on(Vt.milestoneId))}catch{}};return Gs(Ce,{events:{"mission:updated":xt,"slice:updated":bn,"feature:updated":_t,"milestone:updated":Gt,"mission:event":ss=>{Ie();const Mn=ke.current;if(!Mn||Lt.current!=="activity")return;const Vt=es(),Ii=ss;if(Ii.data)try{const Ts=JSON.parse(Ii.data);if(!SS(Ts)||Ts.missionId!==Mn.id||!pm(Ts.eventType,En.current))return;un(pi=>{const xl=pi.filter(vl=>vl.id!==Ts.id);return[Ts,...xl].slice(0,100)}),Dn(pi=>pi+1),Vt&&requestAnimationFrame(()=>{const pi=dn.current;pi&&(pi.scrollTop=0)})}catch{}},"validator-run:started":He,"validator-run:completed":qe,"milestone:validation:updated":vt,"assertion:created":jn,"assertion:updated":jn,"assertion:deleted":jn,"assertion:linked":jn,"assertion:unlinked":jn,"fix-feature:created":ss=>{const Mn=ss;if(Mn.data)try{const Vt=JSON.parse(Mn.data);if(Vt&&Vt.sourceFeatureId){Qs(Vt.sourceFeatureId);const Ii=Vt?.feature?.sliceId,Ts=ke.current;if(Ii&&Ts){const pi=Ts.milestones.find(xl=>xl.slices.some(vl=>vl.id===Ii));pi&&on(pi.id)}ke.current&&yt(ke.current.id)}}catch{}}}})},[h,es,yt,Fn,r,on]);const Se=a.useCallback(()=>{C(!0),A(null),z($l)},[]),Qe=a.useCallback(q=>{A(q.id),C(!1),z({title:q.title,description:q.description||"",status:q.status,autopilotEnabled:q.autopilotEnabled??!1})},[]),ht=a.useCallback(()=>{A(null),C(!1),z($l)},[]),bt=a.useCallback(async()=>{if(!S.title.trim()){i("Mission title is required","error");return}try{if(R(!0),E)await Pk({title:S.title.trim(),description:S.description.trim()||void 0,autopilotEnabled:S.autopilotEnabled},r),i("Mission created","success");else if(j){const q={title:S.title.trim(),description:S.description.trim()||void 0,status:S.status,autopilotEnabled:S.autopilotEnabled};S.autopilotEnabled&&(q.autoAdvance=!0),await Ik(j,q,r),i("Mission updated","success"),g?.id===j&&await yt(j)}await Qt(),ht()}catch(q){i(we(q)||"Failed to save mission","error")}finally{R(!1)}},[S,E,j,i,Qt,yt,g,ht,r]),zt=a.useCallback(async q=>{try{await $k(q,r),i("Mission deleted","success"),g?.id===q&&b(null),await Qt(),ce(null)}catch(Ce){i(we(Ce)||"Failed to delete mission","error")}},[i,Qt,g,r]),yn=a.useCallback(()=>{I(!0),G(null),ee(Dl)},[]),ts=a.useCallback(q=>{G(q.id),I(!1),ee({title:q.title,description:q.description||"",status:q.status,dependencies:q.dependencies})},[]),as=a.useCallback(()=>{G(null),I(!1),ee(Dl)},[]),Js=a.useCallback(async()=>{if(!Y.title.trim()){i("Milestone title is required","error");return}try{R(!0),N&&g?(await zk(g.id,{title:Y.title.trim(),description:Y.description.trim()||void 0,dependencies:Y.dependencies},r),i("Milestone created","success")):U&&(await Fk(U,{title:Y.title.trim(),description:Y.description.trim()||void 0,status:Y.status,dependencies:Y.dependencies},r),i("Milestone updated","success")),await yt(g.id),as()}catch(q){i(we(q)||"Failed to save milestone","error")}finally{R(!1)}},[Y,N,U,g,i,yt,as,S.title,r]),ae=a.useCallback(async q=>{try{await Ok(q,r),i("Milestone deleted","success"),await yt(g.id),ce(null)}catch(Ce){i(we(Ce)||"Failed to delete milestone","error")}},[i,yt,g,r]),_e=a.useCallback(q=>{At(q),Mt(!0),K(Ce=>{const Ie=new Set(Ce);return!Ie.has(q)?(Ie.add(q),wl(q,r).then(bn=>{be(_t=>{const Gt=new Map(_t);return Gt.set(q,bn),Gt})}).catch(()=>{}),Nl(q,r).then(bn=>{qt(_t=>{const Gt=new Map(_t);return Gt.set(q,bn),Gt})}).catch(()=>{})):Ie.delete(q),Ie})},[r]),tt=a.useCallback(q=>{he(q),fe(!0),k(null),J(Ll)},[]),jt=a.useCallback(q=>{k(q.id),fe(!1),J({title:q.title,description:q.description||"",status:q.status})},[]),kt=a.useCallback(()=>{k(null),fe(!1),he(null),J(Ll)},[]),gn=a.useCallback(async()=>{if(!H.title.trim()){i("Slice title is required","error");return}try{R(!0),ue&&W?(await Uk(W,{title:H.title.trim(),description:H.description.trim()||void 0},r),i("Slice created","success")):T&&(await Bk(T,{title:H.title.trim(),description:H.description.trim()||void 0,status:H.status},r),i("Slice updated","success")),await yt(g.id),kt()}catch(q){i(we(q)||"Failed to save slice","error")}finally{R(!1)}},[H,ue,T,W,g,i,yt,kt,r]),sn=a.useCallback(async q=>{try{await Hk(q,r),i("Slice deleted","success"),await yt(g.id),ce(null)}catch(Ce){i(we(Ce)||"Failed to delete slice","error")}},[i,yt,g,r]),en=a.useCallback(async q=>{try{await qk(q,r),i("Slice activated","success"),await yt(g.id)}catch(Ce){i(we(Ce)||"Failed to activate slice","error")}},[i,yt,g,r]),nt=a.useCallback(q=>{$(Ce=>{const Ie=new Set(Ce);return Ie.has(q)?Ie.delete(q):Ie.add(q),Ie})},[]),$t=a.useCallback(q=>{Ee(q),me(!0),ne(null),ge(zl)},[]),Tn=a.useCallback(q=>{ne(q.id),me(!1),ge({title:q.title,description:q.description||"",acceptanceCriteria:q.acceptanceCriteria||"",status:q.status})},[]),qn=a.useCallback(()=>{ne(null),me(!1),Ee(null),ge(zl)},[]),On=a.useCallback(async()=>{if(!Q.title.trim()){i("Feature title is required","error");return}try{R(!0),de&&ie?(await Vk(ie,{title:Q.title.trim(),description:Q.description.trim()||void 0,acceptanceCriteria:Q.acceptanceCriteria.trim()||void 0},r),i("Feature created","success")):O&&(await Wk(O,{title:Q.title.trim(),description:Q.description.trim()||void 0,acceptanceCriteria:Q.acceptanceCriteria.trim()||void 0,status:Q.status},r),i("Feature updated","success")),await yt(g.id),qn()}catch(q){i(we(q)||"Failed to save feature","error")}finally{R(!1)}},[Q,de,O,ie,g,i,yt,qn,r]),Pn=a.useCallback(async q=>{try{await Kk(q,r),i("Feature deleted","success"),await yt(g.id),ce(null)}catch(Ce){i(we(Ce)||"Failed to delete feature","error")}},[i,yt,g,r]),Kn=a.useCallback(async()=>{if(!Ue||!at.trim()){i("Task ID is required","error");return}try{await Gk(Ue,at.trim(),r),i("Feature linked to task","success"),await yt(g.id),Te(null),et("")}catch(q){i(we(q)||"Failed to link feature to task","error")}},[Ue,at,i,yt,g,r]),xs=a.useCallback(async q=>{try{await Jk(q,r),i("Feature unlinked from task","success"),await yt(g.id)}catch(Ce){i(we(Ce)||"Failed to unlink feature","error")}},[i,yt,g,r]),In=a.useCallback(async q=>{try{R(!0),await Yk(q,void 0,void 0,r),i("Feature triaged — task created","success"),await yt(g.id)}catch(Ce){i(we(Ce)||"Failed to triage feature","error")}finally{R(!1)}},[i,yt,g,r]),Gn=a.useCallback(async q=>{it(q);try{const Ce=await Sw(q,r);Ae({featureId:q,enrichedDescription:Ce.description})}catch{await In(q)}finally{it(null)}},[In,r]),vs=a.useCallback(async()=>{pe&&(Ae(null),await In(pe.featureId))},[In,pe]),zs=a.useCallback(()=>{Ae(null)},[]),ys=a.useCallback(async q=>{try{R(!0);const Ce=await Qk(q,r);i(`Triaged ${Ce.count} feature${Ce.count!==1?"s":""}`,"success"),await yt(g.id)}catch(Ce){i(we(Ce)||"Failed to triage slice features","error")}finally{R(!1)}},[i,yt,g,r]),$n=a.useCallback(async q=>{try{const Ce=await wl(q,r);be(Ie=>{const xt=new Map(Ie);return xt.set(q,Ce),xt})}catch{}},[r]),Jn=a.useCallback(async q=>{try{const Ce=await Nl(q,r);qt(Ie=>{const xt=new Map(Ie);return xt.set(q,Ce),xt})}catch{}},[r]),Fs=a.useCallback(async q=>{if(!$e.title.trim()||!$e.assertion.trim()){i("Title and assertion text are required","error");return}try{R(!0),await Xk(q,{title:$e.title.trim(),assertion:$e.assertion.trim(),status:$e.status},r),i("Assertion created","success"),await $n(q),await Jn(q),re(!1),ft({title:"",assertion:"",status:"pending"})}catch(Ce){i(we(Ce)||"Failed to create assertion","error")}finally{R(!1)}},[$e,i,$n,Jn,r]),Ri=a.useCallback(q=>{Ye(q.id),ft({title:q.title,assertion:q.assertion,status:q.status})},[]),Ti=a.useCallback(()=>{Ye(null),re(!1),ft({title:"",assertion:"",status:"pending"})},[]),qr=a.useCallback(async(q,Ce)=>{if(!$e.title.trim()||!$e.assertion.trim()){i("Title and assertion text are required","error");return}try{R(!0),await Zk(q,{title:$e.title.trim(),assertion:$e.assertion.trim(),status:$e.status},r),i("Assertion updated","success"),await $n(Ce),await Jn(Ce),Ti()}catch(Ie){i(we(Ie)||"Failed to update assertion","error")}finally{R(!1)}},[$e,i,$n,Jn,Ti,r]),Ys=a.useCallback(async q=>{try{const Ce=await nw(q,r);Ze(Ie=>{const xt=new Map(Ie);return xt.set(q,Ce),xt})}catch{}},[r]),yi=a.useCallback(async q=>{const Ce=je!==q;rt(Ie=>Ie===q?null:q),Ce&&await Ys(q)},[je,Ys]),Xi=a.useCallback(q=>{rt(q),Ys(q),requestAnimationFrame(()=>{const Ce=document.querySelector(`[data-mission-assertion-id="${q}"]`);Ce instanceof HTMLElement&&typeof Ce.scrollIntoView=="function"&&Ce.scrollIntoView({behavior:"smooth",block:"center"})})},[Ys]),fl=a.useCallback(async(q,Ce)=>{try{gt(Ie=>new Set(Ie).add(Ce)),await ew(q,Ce,r),i("Feature linked to assertion","success"),await Ys(Ce),Nt(null)}catch(Ie){i(we(Ie)||"Failed to link feature","error")}finally{gt(Ie=>{const xt=new Set(Ie);return xt.delete(Ce),xt})}},[i,Ys,r]),gl=a.useCallback(async(q,Ce)=>{const Ie=`${q}-${Ce}`;try{Et(xt=>new Set(xt).add(Ie)),await tw(q,Ce,r),i("Feature unlinked from assertion","success"),await Ys(Ce)}catch(xt){i(we(xt)||"Failed to unlink feature","error")}finally{Et(xt=>{const bn=new Set(xt);return bn.delete(Ie),bn})}},[i,Ys,r]),Vr=a.useCallback(async q=>{try{Wt(Ie=>new Set(Ie).add(q)),await sw(q,r),i("Validation triggered","success");const Ce=await vu(q,r);Yt(Ie=>{const xt=new Map(Ie);return xt.set(q,Ce),xt})}catch(Ce){i(we(Ce)||"Failed to trigger validation","error")}finally{Wt(Ce=>{const Ie=new Set(Ce);return Ie.delete(q),Ie})}},[i,r]),Qs=a.useCallback(async q=>{try{const Ce=await vu(q,r);Yt(Ie=>{const xt=new Map(Ie);return xt.set(q,Ce),xt})}catch{}},[r]),mi=a.useCallback(async q=>{try{const Ce=await iw(q,{limit:10},r);ct(Ie=>{const xt=new Map(Ie);return xt.set(q,Ce),xt})}catch{}},[r]),Zi=a.useCallback(q=>{const Ce=ke.current;if(Ce){for(const Ie of Ce.milestones)for(const xt of Ie.slices)if(xt.features.find(_t=>_t.id===q)){K(_t=>{const Gt=new Set(_t);return Gt.add(Ie.id),Gt}),$(_t=>{const Gt=new Set(_t);return Gt.add(xt.id),Gt}),xe(q),At(Ie.id),Qs(q),mi(q),requestAnimationFrame(()=>{const _t=document.querySelector(`[data-mission-feature-id="${q}"]`);_t instanceof HTMLElement&&typeof _t.scrollIntoView=="function"&&_t.scrollIntoView({behavior:"smooth",block:"center"})});return}}},[Qs,mi]),Wr=a.useCallback(async q=>{try{const Ce=await aw(q,r);ze(Ie=>{const xt=new Map(Ie);return xt.set(q,Ce),xt})}catch{}},[r]),Kr=a.useCallback(async q=>{Rt===q?xe(null):(xe(q),await Qs(q),await mi(q))},[Rt,Qs,mi]),ns=a.useCallback(async q=>{D===q?F(null):(F(q),await Wr(q))},[D,Wr]),ea=a.useCallback(async q=>{try{await rw(q,r),i("Mission resumed","success"),await yt(q),Qt()}catch(Ce){i(we(Ce)||"Failed to resume mission","error")}},[i,yt,Qt,r]),ms=a.useCallback(async q=>{try{const Ie=(await ow(q,r)).pausedTaskIds?.length??0;i(`Mission stopped (${Ie} task${Ie!==1?"s":""} paused)`,"success"),await yt(q),Qt()}catch(Ce){i(we(Ce)||"Failed to stop mission","error")}},[i,yt,Qt,r]),La=a.useCallback(async q=>{try{await lw(q,r),i("Mission started — first slice activated","success"),await yt(q),Qt()}catch(Ce){i(we(Ce)||"Failed to start mission","error")}},[i,yt,Qt,r]),Gr=a.useCallback(async(q,Ce)=>{try{await cw(q,{enabled:Ce},r),i(Ce?"Autopilot enabled":"Autopilot disabled","success"),await yt(q),Qt()}catch(Ie){i(we(Ie)||"Failed to update autopilot","error")}},[i,yt,Qt,r]),za=a.useCallback(q=>{Zt("structure"),At(null),Ft(null),un([]),Dn(0),cn("all"),fn(new Set),yt(q.id)},[yt]),ta=a.useCallback(()=>{b(null),At(null),Ft(null),Zt("structure"),un([]),Dn(0),cn("all"),fn(new Set),Qt()},[Qt]),Fa=Nn.length<is,hi=g?.autopilotState??"inactive",X=hi==="watching"||hi==="activating",We=_S(hi,g?.lastAutopilotActivityAt),lt=a.useMemo(()=>!Bt||!Pt||!Fl(Bt)?null:Bt.rollup.milestoneId===Pt?Bt:null,[Pt,Bt]),Ot=a.useMemo(()=>{const q=new Map;for(const Ce of lt?.validationTelemetry.validationRounds??[]){const Ie=q.get(Ce.featureId);(!Ie||Ce.startedAt>Ie.startedAt)&&q.set(Ce.featureId,Ce)}return q},[lt]),Xs=a.useCallback(()=>{!g||hn||!Fa||M(g.id,{append:!0})},[hn,Fa,M,g]),Os=a.useCallback(q=>{fn(Ce=>{const Ie=new Set(Ce);return Ie.has(q)?Ie.delete(q):Ie.add(q),Ie})},[]),Oa=a.useCallback(q=>{q.key==="Enter"&&!q.shiftKey&&(q.preventDefault(),bt())},[bt]),Ua=a.useCallback(q=>{q.key==="Enter"&&!q.shiftKey&&(q.preventDefault(),Js())},[Js]),Jr=a.useCallback(q=>{q.key==="Enter"&&!q.shiftKey&&(q.preventDefault(),gn())},[gn]),Yr=a.useCallback(q=>{q.key==="Enter"&&!q.shiftKey&&(q.preventDefault(),On())},[On]),bl=a.useRef(null);if(a.useEffect(()=>{if(!h)return;const q=Ce=>{Ce.key==="Escape"&&s()};return document.addEventListener("keydown",q),()=>document.removeEventListener("keydown",q)},[h,s]),!h)return null;const Qr=t.jsxs("div",{ref:bl,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:[g?t.jsx("button",{className:"mission-manager__back-btn",onClick:ta,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:t.jsx(Jo,{size:18})}):null,t.jsx(ws,{size:18,className:"mission-manager__header-icon"}),t.jsx("h2",{className:"mission-manager__title",children:g?g.title:"Missions"})]}),!n&&t.jsx("button",{className:"modal-close",onClick:s,title:"Close","aria-label":"Close Mission Manager","data-testid":"mission-close-btn",children:t.jsx(Ht,{size:18})})]}),t.jsx("div",{className:"mission-manager__body",children:v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(ot,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(ot,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):g?t.jsxs("div",{className:"mission-detail",children:[t.jsxs("div",{className:"mission-detail__header",children:[t.jsxs("div",{className:"mission-detail__title-row",children:[t.jsxs("div",{className:"mission-detail__title-text",children:[X&&t.jsx("span",{className:"mission-detail__autopilot-dot",title:"Autopilot watching"}),t.jsx("h3",{className:"mission-detail__title",children:g.title})]}),t.jsx("span",{className:"mission-status-badge",style:{backgroundColor:(Wa[g.status]||Wa.planning).bg,color:(Wa[g.status]||Wa.planning).text},children:g.status})]}),g.description&&t.jsx("p",{className:"mission-detail__description",children:g.description}),t.jsx("div",{className:"mission-detail__meta",children:t.jsxs("span",{className:"mission-detail__meta-info",children:[g.milestones.length," milestones"]})}),t.jsxs("div",{className:"mission-detail__autopilot",children:[t.jsxs("div",{className:"mission-detail__autopilot-toggle",children:[t.jsxs("label",{className:"mission-toggle","data-testid":"mission-autopilot-toggle",children:[t.jsx("input",{type:"checkbox",checked:g.autopilotEnabled??!1,onChange:q=>Gr(g.id,q.target.checked),"aria-label":"Autopilot"}),t.jsx("span",{className:"mission-toggle__track","aria-hidden":"true",children:t.jsx("span",{className:"mission-toggle__thumb"})}),t.jsxs("span",{className:"mission-toggle__label",children:[t.jsx(Qn,{size:14,className:"mission-detail__autopilot-icon"}),"Autopilot"]})]}),t.jsxs("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(ao[hi]||ao.inactive).bg,color:(ao[hi]||ao.inactive).text},"data-testid":"autopilot-state-badge",children:[X&&t.jsx("span",{className:"mission-detail__autopilot-pulse"}),hi]})]}),We&&t.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:We})]}),t.jsxs("div",{className:"mission-detail__actions",children:[g.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ms(g.id),title:"Stop mission","aria-label":"Stop mission",children:t.jsx(Cs,{size:14})}),g.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>ea(g.id),title:"Resume mission","aria-label":"Resume mission",children:t.jsx(Cn,{size:14})}),g.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>La(g.id),title:"Start mission","aria-label":"Start mission",children:t.jsx(Cn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Qe(g),title:"Edit mission","aria-label":"Edit mission",children:t.jsx(hs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ce({type:"mission",id:g.id}),title:"Delete mission","aria-label":"Delete mission",children:t.jsx(an,{size:14})})]})]}),j===g.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:S.title,onChange:q=>z({...S,title:q.target.value}),onKeyDown:Oa,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:S.description,onChange:q=>z({...S,description:q.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:S.status,onChange:q=>z({...S,status:q.target.value}),children:[t.jsx("option",{value:"planning",children:"Planning"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"blocked",children:"Blocked"}),t.jsx("option",{value:"complete",children:"Complete"}),t.jsx("option",{value:"archived",children:"Archived"})]}),t.jsxs("label",{className:"mission-checkbox",children:[t.jsx("input",{type:"checkbox",checked:S.autopilotEnabled,onChange:q=>z({...S,autopilotEnabled:q.target.checked})}),t.jsx(Qn,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:bt,disabled:_,children:[_?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Vn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ht,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-detail__tabs",role:"tablist","aria-label":"Mission detail tabs",children:[t.jsx("button",{className:`mission-btn ${dt==="structure"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Zt("structure"),role:"tab","aria-selected":dt==="structure","data-testid":"mission-tab-structure",children:"Structure"}),t.jsxs("button",{className:`mission-btn ${dt==="activity"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Zt("activity"),role:"tab","aria-selected":dt==="activity","data-testid":"mission-tab-activity",children:["Activity (",is,")"]})]}),dt==="structure"?t.jsxs("div",{className:"mission-detail__milestones",children:[g.milestones.map(q=>{const Ce=lt?.rollup.milestoneId===q.id?lt:null,Ie=Ce?.rollup??Tt.get(q.id),xt=Ce?.validationTelemetry.validationRounds??[],bn=Ce?.fixFeatures??[],_t=um[Ie?.state??"not_started"]??um.not_started,Gt=Ie&&(Ie.state==="blocked"||Ie.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:()=>_e(q.id),children:[t.jsx("button",{className:"mission-milestone__expand",children:B.has(q.id)?t.jsx(Xt,{size:16}):t.jsx(xn,{size:16})}),t.jsx(Hi,{size:16,className:"mission-milestone__icon"}),t.jsx("span",{className:"mission-milestone__title",children:q.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:cm[q.status].bg,color:cm[q.status].text},children:q.status}),t.jsxs("span",{className:"mission-milestone__count",children:[q.slices.length," slices"]}),t.jsx(mm,{state:jS(q.interviewState)}),Ie&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:_t.bg,color:_t.text},title:"Validation state",children:hm(Ie.state)}),Ie.totalAssertions>0&&t.jsx("div",{className:"mission-milestone__coverage-bar",title:`${Ie.passedAssertions??0} of ${Ie.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-milestone__coverage-bar-fill",style:{width:`${(Ie.passedAssertions??0)/Ie.totalAssertions*100}%`,backgroundColor:(Ie.passedAssertions??0)===Ie.totalAssertions?"var(--color-success)":"var(--color-warning)"}})})]}),q.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Le({type:"milestone",id:q.id,title:q.title}),title:"Plan milestone","aria-label":"Plan milestone",children:t.jsx(Bi,{size:14})}),t.jsxs("div",{className:"mission-milestone__actions",onClick:He=>He.stopPropagation(),children:[t.jsx("button",{className:"mission-icon-btn",onClick:()=>tt(q.id),title:"Add slice",children:t.jsx(rn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>ts(q),title:"Edit milestone",children:t.jsx(hs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ce({type:"milestone",id:q.id}),title:"Delete milestone",children:t.jsx(an,{size:14})})]})]}),B.has(q.id)&&t.jsxs("div",{className:"mission-milestone__body",children:[(N||U===q.id)&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:Y.title,onChange:He=>ee({...Y,title:He.target.value}),onKeyDown:Ua,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:Y.description,onChange:He=>ee({...Y,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:Js,disabled:_,children:[_?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Vn,{size:14}),U?"Update":"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:as,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]}),xt.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:()=>Mt(He=>!He),title:Dt?"Hide validation rounds":"Show validation rounds",children:[Dt?t.jsx(Xt,{size:12}):t.jsx(xn,{size:12}),"Validation rounds (",xt.length,")"]}),Dt&&t.jsx("div",{className:"mission-validation-rounds__list",children:xt.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:()=>Xi(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:()=>Zi(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))})]}),bn.length>0&&t.jsxs("div",{className:"mission-fix-features",children:[t.jsx("div",{className:"mission-fix-features__title",children:"Generated Fix Features"}),t.jsx("div",{className:"mission-fix-features__list",children:bn.map(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:()=>Zi(He.id),title:`Jump to feature ${He.id}`,children:He.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:io[He.status].bg,color:io[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:()=>Zi(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:()=>Xi(qe),title:`Jump to assertion ${qe}`,children:qe},`${He.id}-${qe}`))})]})]},He.id))})]})]}),t.jsxs("div",{className:"mission-slices",children:[q.slices.map(He=>t.jsxs("div",{className:"mission-slice",children:[t.jsxs("div",{className:"mission-slice__header",onClick:()=>nt(He.id),children:[t.jsx("button",{className:"mission-slice__expand",children:L.has(He.id)?t.jsx(Xt,{size:16}):t.jsx(xn,{size:16})}),t.jsx(Ic,{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:dm[He.status].bg,color:dm[He.status].text},children:He.status}),t.jsxs("span",{className:"mission-slice__count",children:[He.features?.length||0," features"]}),t.jsx(mm,{state:He.planState??"not_started"}),He.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Le({type:"slice",id:He.id,title:He.title}),title:"Plan slice","aria-label":"Plan slice",children:t.jsx(Bi,{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:()=>en(He.id),title:"Activate slice",children:t.jsx(Cn,{size:14})}),He.status==="active"&&He.features?.some(qe=>qe.status==="defined")&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>ys(He.id),title:"Triage all features",disabled:_,children:_?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Qn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>$t(He.id),title:"Add feature",children:t.jsx(rn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>jt(He),title:"Edit slice",children:t.jsx(hs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ce({type:"slice",id:He.id}),title:"Delete slice",children:t.jsx(an,{size:14})})]})]}),L.has(He.id)&&t.jsxs("div",{className:"mission-slice__body",children:[ue&&W===q.id&&!T&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:H.title,onChange:qe=>J({...H,title:qe.target.value}),onKeyDown:Jr,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:H.description,onChange:qe=>J({...H,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:gn,disabled:_,children:[_?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Vn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:kt,children:"Cancel"})]})]}),T===He.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:H.title,onChange:qe=>J({...H,title:qe.target.value}),onKeyDown:Jr,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:H.description,onChange:qe=>J({...H,description:qe.target.value}),rows:2}),t.jsxs("select",{value:H.status,onChange:qe=>J({...H,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:gn,disabled:_,children:[_?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Vn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:kt,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:()=>Kr(qe.id),title:Rt===qe.id?"Collapse details":"Expand to show run history",children:Rt===qe.id?t.jsx(Xt,{size:14}):t.jsx(xn,{size:14})}),t.jsx(Ec,{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:io[qe.status].bg,color:io[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:()=>Zi(qe.generatedFromFeatureId),title:`Generated from feature: ${qe.generatedFromFeatureId}`,children:"🔗 Fix"}),(qe.loopState==="validating"||qe.loopState==="needs_fix")&&(()=>{const vt=It.get(qe.id),jn=Ot.get(qe.id),Rs=vt?.implementationAttemptCount??jn?.implementationAttempt??qe.implementationAttemptCount??0,Pi=vt?.retryBudgetRemaining??Math.max(0,yS-Rs);return t.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",Rs," · ",Pi," ",Pi===1?"retry":"retries"," left"]})})(),qe.loopState==="implementing"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>Vr(qe.id),title:"Validate feature",disabled:St.has(qe.id),children:St.has(qe.id)?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(cs,{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:()=>Gn(qe.id),title:"Triage — create task",disabled:_||Je===qe.id,children:Je===qe.id?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Qn,{size:14})}),qe.taskId?t.jsx("button",{className:"mission-icon-btn",onClick:()=>xs(qe.id),title:"Unlink task",children:t.jsx(Yd,{size:14})}):qe.status!=="defined"?t.jsx("button",{className:"mission-icon-btn",onClick:()=>Te(qe.id),title:"Link to task",children:t.jsx(ga,{size:14})}):null,t.jsx("button",{className:"mission-icon-btn",onClick:()=>Tn(qe),title:"Edit feature",children:t.jsx(hs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ce({type:"feature",id:qe.id}),title:"Delete feature",children:t.jsx(an,{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]}),pe?.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:pe.enrichedDescription}),t.jsxs("div",{className:"mission-triage-preview__actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:vs,disabled:_,children:[_?t.jsx(ot,{size:14,className:"spinner"}):null,"Create Task"]}),t.jsx("button",{className:"btn",onClick:zs,disabled:_,children:"Cancel"})]})]}),O===qe.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:Q.title,onChange:vt=>ge({...Q,title:vt.target.value}),onKeyDown:Yr,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:Q.description,onChange:vt=>ge({...Q,description:vt.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:Q.acceptanceCriteria,onChange:vt=>ge({...Q,acceptanceCriteria:vt.target.value}),rows:2}),t.jsxs("select",{value:Q.status,onChange:vt=>ge({...Q,status:vt.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:On,disabled:_,children:[_?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Vn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:qn,children:"Cancel"})]})]}),Rt===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"})}),(Fe.get(qe.id)??[]).map(vt=>t.jsxs("div",{className:"mission-run",children:[t.jsxs("div",{className:"mission-run__header",onClick:()=>ns(vt.id),children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-run__status mission-run__status--${vt.status}`,title:vt.status,children:vt.status}),t.jsx("span",{className:"mission-run__time",children:new Date(vt.startedAt).toLocaleString()}),vt.completedAt&&t.jsxs("span",{className:"mission-run__duration",children:[Math.round((new Date(vt.completedAt).getTime()-new Date(vt.startedAt).getTime())/1e3),"s"]}),vt.triggerType&&t.jsx("span",{className:"mission-run__trigger",children:vt.triggerType}),t.jsx("button",{className:"mission-icon-btn",title:D===vt.id?"Hide details":"Show details",children:D===vt.id?t.jsx(Xt,{size:12}):t.jsx(xn,{size:12})})]}),D===vt.id&&ve.get(vt.id)&&t.jsxs("div",{className:"mission-run__details",children:[vt.summary&&t.jsx("p",{className:"mission-run__summary",children:vt.summary}),vt.blockedReason&&t.jsxs("p",{className:"mission-run__blocked-reason",children:[t.jsx("strong",{children:"Blocked:"})," ",vt.blockedReason]}),ve.get(vt.id)?.failures&&ve.get(vt.id).failures.length>0&&t.jsxs("div",{className:"mission-run__failures",children:[t.jsx("span",{className:"mission-run__failures-title",children:"Failed Assertions:"}),ve.get(vt.id).failures.map(jn=>t.jsxs("div",{className:"mission-run__failure",children:[t.jsx("span",{className:"mission-run__failure-message",children:jn.message}),jn.expected&&t.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",jn.expected]}),jn.actual&&t.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",jn.actual]})]},jn.id))]}),(!ve.get(vt.id)?.failures||ve.get(vt.id).failures.length===0)&&t.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},vt.id)),(!Fe.get(qe.id)||Fe.get(qe.id).length===0)&&t.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},qe.id)),de&&ie===He.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:Q.title,onChange:qe=>ge({...Q,title:qe.target.value}),onKeyDown:Yr,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:Q.description,onChange:qe=>ge({...Q,description:qe.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:Q.acceptanceCriteria,onChange:qe=>ge({...Q,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:On,disabled:_,children:[_?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Vn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:qn,children:"Cancel"})]})]}),!de&&(!He.features||He.features.length===0)&&t.jsxs("div",{className:"mission-manager__empty mission-features__empty",children:[t.jsx(Ec,{size:16}),t.jsx("span",{children:"No fix features generated."})]})]})]})]},He.id)),q.slices.length===0&&!ue&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Ic,{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"}),Ie&&t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:_t.bg,color:_t.text},children:hm(Ie.state)}),Ie&&Ie.totalAssertions>0&&t.jsx("div",{className:"mission-assertions__coverage-bar",title:`${Ie.passedAssertions??0} of ${Ie.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-assertions__coverage-bar-fill",style:{width:`${(Ie.passedAssertions??0)/Ie.totalAssertions*100}%`,backgroundColor:(Ie.passedAssertions??0)===Ie.totalAssertions?"var(--color-success)":"var(--color-warning)"}})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>{re(!0),Ye(null),ft({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:t.jsx(rn,{size:14})})]}),Z&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:$e.title,onChange:He=>ft({...$e,title:He.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:$e.assertion,onChange:He=>ft({...$e,assertion:He.target.value}),rows:2}),t.jsxs("select",{value:$e.status,onChange:He=>ft({...$e,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:()=>Fs(q.id),disabled:_,children:[_?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Vn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Ti,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-assertions__list",children:[(Array.isArray(Re.get(q.id))?Re.get(q.id):[]).map(He=>t.jsxs("div",{className:"mission-assertion","data-mission-assertion-id":He.id,children:[t.jsx("div",{className:"mission-assertion__header",children:Pe===He.id?t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:$e.title,onChange:qe=>ft({...$e,title:qe.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text",value:$e.assertion,onChange:qe=>ft({...$e,assertion:qe.target.value}),rows:2}),t.jsxs("select",{value:$e.status,onChange:qe=>ft({...$e,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:()=>qr(He.id,q.id),disabled:_,children:[_?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Vn,{size:14}),"Save"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Ti,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(ro[He.status]??ro.pending).bg,color:(ro[He.status]??ro.pending).text},children:He.status}),t.jsx("span",{className:"mission-assertion__title",children:He.title}),(()=>{const vt=te.get(He.id)?.length??0;return vt>0?t.jsxs("span",{className:"mission-assertion__linked-count",title:`${vt} linked feature${vt!==1?"s":""}`,children:["(",vt," linked)"]}):null})(),t.jsx("button",{className:"mission-icon-btn",onClick:()=>yi(He.id),title:"Toggle details",children:je===He.id?t.jsx(Xt,{size:14}):t.jsx(xn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ri(He),title:"Edit assertion",children:t.jsx(hs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ce({type:"assertion",id:He.id}),title:"Delete assertion",children:t.jsx(an,{size:14})})]})}),je===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()=>{je!==He.id&&await yi(He.id),Nt(mt===He.id?null:He.id)},title:"Link a feature",children:[t.jsx(ga,{size:12}),"Link Feature"]})]}),mt===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((te.get(He.id)??[]).map(jn=>jn.id)),vt=[];return g?.milestones.forEach(jn=>jn.slices.forEach(Rs=>vt.push(...Rs.features.filter(Pi=>!qe.has(Pi.id))))),vt.length===0?t.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):vt.map(jn=>t.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>fl(jn.id,He.id),disabled:pt.has(He.id),children:[t.jsx("span",{className:"mission-assertion__feature-picker-title",children:jn.title}),pt.has(He.id)&&t.jsx(ot,{size:12,className:"spinner"})]},jn.id))})()})}),(()=>{const qe=te.get(He.id)??[];return qe.length===0?t.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):qe.map(vt=>{const jn=`${vt.id}-${He.id}`,Rs=wt.has(jn);return t.jsxs("div",{className:"mission-assertion__linked-feature",children:[t.jsx("span",{className:"mission-assertion__linked-feature-title",children:vt.title}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>gl(vt.id,He.id),disabled:Rs,title:"Unlink feature",children:Rs?t.jsx(ot,{size:12,className:"spinner"}):t.jsx(Yd,{size:12})})]},vt.id)})})()]})]})]},He.id)),(!Re.get(q.id)||Re.get(q.id)?.length===0)&&!Z&&t.jsx("div",{className:"mission-manager__empty mission-assertions__empty",children:t.jsx("span",{children:"No assertions defined. Add one to define completion criteria."})})]})]})]})]})]},q.id)}),g&&!N&&U===null&&t.jsxs("button",{className:"mission-add-btn",onClick:yn,children:[t.jsx(rn,{size:16}),"Add Milestone"]}),N&&U===null&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:Y.title,onChange:q=>ee({...Y,title:q.target.value}),onKeyDown:Ua,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:Y.description,onChange:q=>ee({...Y,description:q.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Js,disabled:_,children:[_?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Vn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:as,children:"Cancel"})]})]}),g.milestones.length===0&&!N&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Hi,{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:nn,onChange:q=>cn(q.target.value),"data-testid":"mission-activity-filter",children:[t.jsx("option",{value:"all",children:"All events"}),t.jsx("option",{value:"errors",children:"Errors & warnings"}),t.jsx("option",{value:"state_changes",children:"State changes"}),t.jsx("option",{value:"tasks",children:"Task events"}),t.jsx("option",{value:"slices",children:"Slice & milestone events"}),t.jsx("option",{value:"autopilot",children:"Autopilot events"})]})]}),t.jsxs("span",{className:"mission-detail__activity-count",children:[Nn.length," of ",is]})]}),!hn&&Fa&&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:Xs,"data-testid":"mission-activity-load-more",children:"Load more"})}),hn?t.jsxs("div",{className:"mission-manager__loading mission-detail__activity-loading",children:[t.jsx(ot,{size:18,className:"spinner"}),t.jsx("span",{children:"Loading mission activity..."})]}):Nn.length===0?t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Ds,{size:18}),t.jsx("span",{children:"No events yet."})]}):t.jsxs("div",{ref:dn,className:"mission-events","data-testid":"mission-activity-events",children:[Nn.map(q=>{const Ce=!!(q.metadata&&Object.keys(q.metadata).length>0),Ie=Hn.has(q.id);return t.jsxs("div",{className:"mission-event",children:[t.jsxs("div",{className:"mission-event__header",children:[t.jsx("span",{className:`mission-event__type ${CS(q.eventType)}`,children:ES(q.eventType)}),t.jsx("span",{className:"mission-event__time",children:Oo(q.timestamp)})]}),t.jsx("p",{className:"mission-event__description",children:q.description}),t.jsx("span",{className:"mission-event__timestamp",children:new Date(q.timestamp).toLocaleString()}),Ce&&t.jsxs("div",{className:"mission-event__metadata",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>Os(q.id),"data-testid":`mission-event-metadata-${q.id}`,children:[Ie?"Hide":"Show"," metadata"]}),Ie&&t.jsx("pre",{className:"mission-event__metadata-content",children:JSON.stringify(q.metadata,null,2)})]})]},q.id)}),t.jsx("div",{ref:_n})]})]})]}):t.jsxs("div",{className:"mission-list",children:[E&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:S.title,onChange:q=>z({...S,title:q.target.value}),onKeyDown:Oa,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:S.description,onChange:q=>z({...S,description:q.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:bt,disabled:_,children:[_?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Vn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ht,children:"Cancel"})]})]}),f.map(q=>{const Ce=q,Ie=g,xt=Ie&&Ie.id===Ce.id,bn=Wa[Ce.status]||{bg:"",text:""},_t=Ce.summary,Gt=Oe.get(Ce.id),He=wS(Gt),qe=!!(_t&&(_t.totalMilestones>0||_t.totalFeatures>0)),vt=Gt?.totalTasks??0,jn=Gt?.tasksCompleted??0,Rs=Gt?.tasksFailed??0,Pi=Gt?.estimatedCompletionPercent??_t?.progressPercent??0,ss=qe||vt>0||Rs>0||!!Gt?.lastActivityAt,Mn=Ce.status==="active"&&(Gt?.currentMilestoneId||Gt?.currentSliceId)?"Current milestone/slice in progress":null;return t.jsxs("div",{className:`mission-list__item ${xt?"mission-list__item--selected":""}`,onClick:()=>za(q),children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(ws,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{className:"mission-list__item-title",children:Ce.title}),q.autopilotEnabled&&t.jsx("span",{title:"Autopilot enabled",children:t.jsx(Qn,{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:bn.bg,color:bn.text},children:Ce.status})]}),Ce.description&&t.jsx("p",{className:"mission-list__item-description",children:Ce.description}),Mn&&t.jsxs("p",{className:"mission-list__item-active-slice",children:["Active: ",Mn]}),ss&&t.jsxs("div",{className:"mission-list__item-summary",children:[qe&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"mission-list__item-stat",children:[_t.completedMilestones,"/",_t.totalMilestones," milestones"]}),t.jsxs("span",{className:"mission-list__item-stat",children:[_t.completedFeatures,"/",_t.totalFeatures," features"]})]}),t.jsxs("span",{className:"mission-list__item-stat","data-testid":`mission-task-stats-${Ce.id}`,children:[jn,"/",vt," tasks"]}),Rs>0&&t.jsxs("button",{className:"mission-list__item-failed",onClick:Vt=>{Vt.stopPropagation(),za(q)},"data-testid":`mission-failed-${Ce.id}`,title:"View mission failures",children:[Rs," failed"]}),t.jsxs("span",{className:"mission-relative-time","data-testid":`mission-last-activity-${Ce.id}`,children:["Activity ",Oo(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:`${Pi}%`}})})]})]}),t.jsxs("div",{className:"mission-list__item-actions",onClick:Vt=>Vt.stopPropagation(),children:[Ce.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ms(Ce.id),title:"Stop mission",children:t.jsx(Cs,{size:14})}),Ce.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>ea(Ce.id),title:"Resume mission",children:t.jsx(Cn,{size:14})}),Ce.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>La(Ce.id),title:"Start mission",children:t.jsx(Cn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Qe(q),title:"Edit mission",children:t.jsx(hs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ce({type:"mission",id:Ce.id}),title:"Delete mission",children:t.jsx(an,{size:14})})]})]},Ce.id)}),j&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:S.title,onChange:q=>z({...S,title:q.target.value}),onKeyDown:Oa,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:S.description,onChange:q=>z({...S,description:q.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:S.status,onChange:q=>z({...S,status:q.target.value}),children:[t.jsx("option",{value:"planning",children:"Planning"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"blocked",children:"Blocked"}),t.jsx("option",{value:"complete",children:"Complete"}),t.jsx("option",{value:"archived",children:"Archived"})]}),t.jsxs("label",{className:"mission-checkbox",children:[t.jsx("input",{type:"checkbox",checked:S.autopilotEnabled,onChange:q=>z({...S,autopilotEnabled:q.target.checked})}),t.jsx(Qn,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:bt,disabled:_,children:[_?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Vn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ht,children:"Cancel"})]})]}),f.length===0&&!E&&t.jsxs("div",{className:"mission-manager__empty mission-manager__empty--large",children:[t.jsx(ws,{size:32}),t.jsx("span",{children:"No missions yet. Create one to start planning."})]}),!E&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[De.length>0&&t.jsxs("div",{className:"mission-resume-prompt",children:[t.jsx(gs,{size:16}),t.jsx("span",{children:De.length===1?`Resume "${De[0].title}"?`:`${De.length} interview sessions pending`}),t.jsx("div",{style:{display:"flex",gap:"4px",marginLeft:"auto"},children:De.map(q=>t.jsxs("button",{className:"mission-add-btn",onClick:()=>{Ne(q.id),Xe(!0),Be([])},children:[q.status==="error"?t.jsx(Ln,{size:14}):t.jsx(cs,{size:14}),q.status==="error"?"Retry":"Resume"]},q.id))})]}),t.jsxs("div",{style:{display:"flex",gap:"8px"},children:[t.jsxs("button",{className:"mission-add-btn",onClick:()=>Xe(!0),children:[t.jsx(cs,{size:16}),"Plan with AI"]}),t.jsxs("button",{className:"mission-add-btn",onClick:Se,children:[t.jsx(rn,{size:16}),"New Mission"]})]})]})]})}),ye&&t.jsx("div",{className:"mission-confirm-panel mission-confirm-panel--danger",children:t.jsxs("div",{className:"mission-confirm-panel__content",children:[t.jsxs("p",{children:["Delete this ",ye.type,"? This cannot be undone."]}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--danger",onClick:async()=>{ye.type==="mission"?await zt(ye.id):ye.type==="milestone"?await ae(ye.id):ye.type==="slice"?await sn(ye.id):ye.type==="feature"&&await Pn(ye.id)},children:"Delete"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>ce(null),children:"Cancel"})]})]})}),Ue&&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:at,onChange:q=>et(q.target.value),autoFocus:!0}),l.length>0&&t.jsxs("div",{className:"mission-task-suggestions",children:[t.jsx("small",{children:"Or select:"}),t.jsx("div",{className:"mission-task-suggestions__list",children:l.slice(0,5).map(q=>t.jsxs("button",{className:"mission-task-suggestions__item",onClick:()=>et(q.id),children:[q.id,": ",q.title||"Untitled"]},q.id))})]}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--primary",onClick:Kn,children:"Link"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>{Te(null),et("")},children:"Cancel"})]})]})})]}),Xr=t.jsx(pS,{isOpen:Ve,onClose:()=>Xe(!1),onMissionCreated:()=>{Qt(),i("Mission created from AI interview","success")},projectId:r,resumeSessionId:se}),na=Me?t.jsx(bS,{isOpen:!0,onClose:()=>Le(null),onApplied:()=>{Le(null),g&&yt(g.id)},targetType:Me.type,targetId:Me.id,targetTitle:Me.title,missionContext:g?.title,projectId:r,resumeSessionId:Me.resumeSessionId}):null;return n?t.jsxs(t.Fragment,{children:[Qr,Xr,na]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mission-manager-overlay open",onClick:q=>q.target===q.currentTarget&&s(),"data-testid":"mission-manager-overlay",role:"dialog","aria-modal":"true",children:Qr}),Xr,na]})}const oo=2e3;function fm({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"),[f,p]=a.useState(""),[g,b]=a.useState(!1),[v,x]=a.useState(null),y=u.trim()!==""&&f.trim().length>0&&f.length<=oo,w=a.useCallback(async()=>{if(!(!y||g)){b(!0),x(null);try{const C=m==="agent"?"user-to-agent":"system";await Iw({toId:u.trim(),toType:m,content:f.trim(),type:C,...n?{metadata:{replyTo:{messageId:n.messageId}}}:{}},i),r()}catch(C){const j=we(C)||"Failed to send message";x(j),l?.(j,"error")}finally{b(!1)}}},[y,g,u,m,f,n,i,r,l]),E=a.useCallback(C=>{d(C),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(Ht,{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:C=>E(C.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(C=>t.jsx("option",{value:C.id,children:C.name||C.id},C.id))]})]}),e&&t.jsxs("div",{className:"message-composer-field",children:[t.jsx("span",{className:"message-composer-label",children:"To:"}),t.jsxs("span",{className:"message-composer-recipient-fixed",children:[t.jsx(Sn,{size:14}),e.id]})]}),n&&t.jsxs("div",{className:"message-composer-field","data-testid":"message-composer-reply-context",children:[t.jsx("span",{className:"message-composer-label",children:"Replying to:"}),t.jsx("span",{className:"message-composer-recipient-fixed",children:n.preview?.trim()?n.preview:`Message ${n.messageId}`})]}),t.jsxs("div",{className:"message-composer-field message-composer-field--content",children:[t.jsx("label",{className:"message-composer-label",htmlFor:"message-content",children:"Message:"}),t.jsx("textarea",{id:"message-content",className:"message-composer-textarea",placeholder:"Type your message…",value:f,onChange:C=>p(C.target.value),maxLength:oo,rows:4,"data-testid":"message-composer-content"}),t.jsx("div",{className:"message-composer-charcount","data-testid":"message-composer-charcount",children:t.jsxs("span",{className:f.length>oo?"over-limit":"",children:[f.length,"/",oo]})})]}),v&&t.jsxs("div",{className:"message-composer-error","data-testid":"message-composer-error",children:[t.jsx(gs,{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:w,disabled:!y||g,"data-testid":"message-composer-send",children:g?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:14,className:"spin"}),t.jsx("span",{children:"Sending…"})]}):t.jsxs(t.Fragment,{children:[t.jsx(zi,{size:14}),t.jsx("span",{children:"Send"})]})})]})]})}function oa(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 AS(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 RS(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 gm(e,n=80){return e.length<=n?e:`${e.slice(0,n)}…`}function TS(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 PS({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,f]=a.useState(!1),[p,g]=a.useState(null),[b,v]=a.useState([]),[x,y]=a.useState(!1),[w,E]=a.useState(null),[C,j]=a.useState(null),[A,S]=a.useState(null),[z,_]=a.useState("inbox"),[R,B]=a.useState(null),[K,L]=a.useState([]),$=a.useMemo(()=>new Map(K.map(ie=>[ie.id,ie.name??""])),[K]),U=a.useCallback((ie,Ee)=>AS(ie,Ee,$),[$]),Y=Ta()==="mobile",ee=!Y,N=a.useCallback(async()=>{f(!0);try{const ie=await Tw({limit:50},e);l(ie),m(ie.unreadCount),s?.(ie.unreadCount)}catch{}finally{f(!1)}},[e,s]),I=a.useCallback(async()=>{f(!0);try{const ie=await Pw({limit:50},e);u(ie)}catch{}finally{f(!1)}},[e]),T=a.useCallback(async ie=>{f(!0);try{const Ee=await Fw(ie,e);B(Ee)}catch{}finally{f(!1)}},[e]),k=a.useCallback(async()=>{try{const ie=await Ra(void 0,e);L(ie)}catch{}},[e]),H=a.useCallback(async()=>{try{const ie=await Lp(e);m(ie.unreadCount),s?.(ie.unreadCount)}catch{}},[e,s]);a.useEffect(()=>{i==="inbox"?N():i==="outbox"?I():i==="agents"&&k()},[i,N,I,k]),a.useEffect(()=>{A&&T(A)},[A,T]),a.useEffect(()=>{H()},[H]),a.useEffect(()=>{k()},[k]),a.useEffect(()=>{if(typeof EventSource>"u")return;const ie=e?`?projectId=${encodeURIComponent(e)}`:"",Ee=()=>{H(),i==="inbox"?N():i==="outbox"&&I(),A&&T(A)};return Gs(`/api/events${ie}`,{events:{"message:sent":Ee,"message:received":Ee,"message:read":Ee,"message:deleted":Ee}})},[e,i,A,H,N,I,T]);const J=a.useCallback(async ie=>{if(g(ie),!ie.read)try{const Ee=await $w(ie.id,e);Ee&&l(Te=>Te&&{...Te,messages:Te.messages.map(at=>at.id===Ee.id?Ee:at),unreadCount:Math.max(0,Te.unreadCount-1)});const Ue=Math.max(0,d-1);m(Ue),s?.(Ue)}catch{}try{const Ee=await zw(ie.fromId,ie.fromType,e);v(Ee)}catch{v([ie])}},[e,d,s]),ue=a.useCallback(()=>{g(null),v([])},[]),fe=a.useCallback(async()=>{try{const ie=await Dw(e);m(0),s?.(0),l(Ee=>Ee&&{...Ee,messages:Ee.messages.map(Ue=>({...Ue,read:!0})),unreadCount:0}),n?.(`Marked ${ie.markedAsRead} messages as read`,"success")}catch{n?.("Failed to mark messages as read","error")}},[e,n,s]),W=a.useCallback(async ie=>{try{await Lw(ie,e),g(null),v([]),i==="inbox"?N():i==="outbox"?I():A&&T(A),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[e,i,A,N,I,T,n]),he=a.useCallback(ie=>{E({id:ie.fromId,type:ie.fromType}),j({messageId:ie.id,preview:gm(ie.content,120)}),y(!0)},[]),O=a.useCallback(()=>{y(!1),E(null),j(null),n?.("Message sent","success"),i==="outbox"?I():i==="agents"&&A&&T(A),H()},[i,I,A,T,n,H]),ne=a.useCallback(()=>{E(i==="agents"&&A?{id:A,type:"agent"}:null),j(null),y(!0)},[i,A]),Q=a.useCallback(()=>{y(!1),E(null),j(null)},[]),ge=()=>!p||x?null:t.jsxs("div",{className:"mailbox-message-detail","data-testid":"mailbox-message-detail",children:[t.jsxs("div",{className:"mailbox-message-detail-header",children:[Y&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:ue,"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:RS(p.type)}),t.jsx("span",{className:"mailbox-message-time",children:oa(p.createdAt)})]}),t.jsxs("div",{className:"mailbox-message-detail-actions",children:[p.fromType==="agent"&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>he(p),"data-testid":"mailbox-reply",children:[t.jsx(Si,{size:14}),t.jsx("span",{children:"Reply"})]}),t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>W(p.id),"data-testid":"mailbox-delete",children:[t.jsx(an,{size:14}),t.jsx("span",{children:"Delete"})]})]})]}),t.jsxs("div",{className:"mailbox-message-participants",children:[t.jsxs("div",{className:"mailbox-participant",children:[t.jsx("span",{className:"mailbox-participant-label",children:"From:"}),t.jsxs("span",{className:"mailbox-participant-value",children:[p.fromType==="agent"?t.jsx(Sn,{size:14}):t.jsx(sa,{size:14}),U(p.fromId,p.fromType)]})]}),t.jsxs("div",{className:"mailbox-participant",children:[t.jsx("span",{className:"mailbox-participant-label",children:"To:"}),t.jsxs("span",{className:"mailbox-participant-value",children:[p.toType==="agent"?t.jsx(Sn,{size:14}):t.jsx(sa,{size:14}),U(p.toId,p.toType)]})]})]}),b.length>1&&t.jsxs("div",{className:"mailbox-conversation","data-testid":"mailbox-conversation",children:[t.jsx("div",{className:"mailbox-conversation-label",children:"Conversation"}),b.map(ie=>{const Ee=ie.metadata?.replyTo?.messageId,Ue=Ee?b.find(Te=>Te.id===Ee):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:U(ie.fromId,ie.fromType)}),t.jsx("span",{className:"mailbox-message-time",children:oa(ie.createdAt)})]}),Ee&&t.jsxs("div",{className:"mailbox-reply-context","data-testid":`mailbox-reply-context-${ie.id}`,children:["↪ Replying to ",Ue?gm(Ue.content,60):`message ${Ee}`]}),t.jsx("div",{className:"mailbox-conversation-msg-body",children:ie.content})]},ie.id)})]}),b.length<=1&&t.jsxs(t.Fragment,{children:[p.metadata?.replyTo?.messageId&&t.jsxs("div",{className:"mailbox-reply-context","data-testid":"mailbox-selected-reply-context",children:["↪ Replying to message ",p.metadata.replyTo.messageId]}),t.jsx("div",{className:"mailbox-message-body","data-testid":"mailbox-message-body",children:p.content})]})]}),de=()=>t.jsxs(t.Fragment,{children:[i==="inbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[h&&!o&&t.jsx(Ol,{}),o&&o.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-inbox-empty",children:[t.jsx(or,{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:TS(o.messages).map(ie=>t.jsxs("div",{className:`mailbox-conversation-group ${ie.unreadCount>0?"unread":""}`,onClick:()=>J(ie.latestMessage),"data-testid":`mailbox-conversation-${ie.key}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ie.fromType==="agent"?t.jsx(Sn,{size:16}):t.jsx(sa,{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:U(ie.fromId,ie.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:oa(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(Ol,{}),c&&c.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-outbox-empty",children:[t.jsx(zi,{size:32}),t.jsx("p",{children:"No sent messages"})]}),c?.messages.map(ie=>t.jsxs("div",{className:"mailbox-item",onClick:()=>J(ie),"data-testid":`mailbox-item-${ie.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ie.toType==="agent"?t.jsx(Sn,{size:16}):t.jsx(sa,{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: ",U(ie.toId,ie.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:oa(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(Sn,{size:32}),t.jsx("p",{children:"No agents found"})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"mailbox-agents-header",children:[t.jsx("div",{className:"mailbox-agents-dropdown",children:t.jsxs("select",{className:"message-composer-select mailbox-agent-select",value:A??"",onChange:ie=>{S(ie.target.value||null),_("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(Si,{size:14}),t.jsx("span",{children:"Compose"})]})]}),A&&t.jsxs("div",{className:"mailbox-agent-subtabs","data-testid":"mailbox-agent-subtabs",children:[t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${z==="inbox"?"active":""}`,onClick:()=>_("inbox"),"data-testid":"mailbox-agent-subtab-inbox",children:[t.jsx(or,{size:12}),t.jsx("span",{children:"Inbox"}),R&&R.unreadCount>0&&t.jsx("span",{className:"mailbox-tab-badge",children:R.unreadCount})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${z==="outbox"?"active":""}`,onClick:()=>_("outbox"),"data-testid":"mailbox-agent-subtab-outbox",children:[t.jsx(zi,{size:12}),t.jsx("span",{children:"Outbox"})]})]}),t.jsxs("div",{className:"mailbox-agents-content",children:[!A&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Sn,{size:32}),t.jsx("p",{children:"Select an agent to view their mailbox"})]}),A&&h&&!R&&t.jsx(Ol,{}),A&&R&&z==="inbox"&&R.inbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(or,{size:32}),t.jsx("p",{children:"No received messages for this agent"})]}),A&&R&&z==="outbox"&&R.outbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(zi,{size:32}),t.jsx("p",{children:"No sent messages for this agent"})]}),A&&R&&z==="inbox"&&R.inbox.map(ie=>t.jsxs("div",{className:`mailbox-item ${ie.read?"":"unread"}`,onClick:()=>J(ie),"data-testid":`mailbox-item-${ie.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ie.fromType==="agent"?t.jsx(Sn,{size:16}):t.jsx(sa,{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:U(ie.fromId,ie.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:oa(ie.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ie.content.slice(0,80),ie.content.length>80?"…":""]})]})]},ie.id)),A&&R&&z==="outbox"&&R.outbox.map(ie=>t.jsxs("div",{className:"mailbox-item",onClick:()=>J(ie),"data-testid":`mailbox-item-${ie.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ie.toType==="agent"?t.jsx(Sn,{size:16}):t.jsx(sa,{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: ",U(ie.toId,ie.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:oa(ie.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ie.content.slice(0,80),ie.content.length>80?"…":""]})]})]},ie.id))]})]})})]}),me=()=>x?t.jsx(fm,{recipient:w,replyContext:C,agents:K,projectId:e,onSend:O,onCancel:Q,addToast:n}):p?ge():t.jsxs("div",{className:"mailbox-split-empty","data-testid":"mailbox-split-empty",children:[t.jsx(ba,{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(ba,{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(Si,{size:14}),t.jsx("span",{children:"Compose"})]}),i==="inbox"&&d>0&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:fe,title:"Mark all as read","data-testid":"mailbox-mark-all-read",children:[t.jsx(vb,{size:14}),t.jsx("span",{children:"Mark all read"})]}),t.jsx("button",{className:"btn-icon",onClick:()=>{i==="inbox"?N():i==="outbox"?I():A&&T(A)},disabled:h,title:"Refresh","data-testid":"mailbox-refresh",children:h?t.jsx(ot,{size:14,className:"spin"}):t.jsx(Ln,{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"),g(null)},"data-testid":"mailbox-tab-inbox",children:[t.jsx(or,{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"),g(null)},"data-testid":"mailbox-tab-outbox",children:[t.jsx(zi,{size:14}),t.jsx("span",{children:"Outbox"})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="agents"?"active":""}`,onClick:()=>{r("agents"),g(null)},"data-testid":"mailbox-tab-agents",children:[t.jsx(Sn,{size:14}),t.jsx("span",{children:"Agents"})]})]}),t.jsx("div",{className:"mailbox-content","data-testid":"mailbox-content",children:ee?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:de()}),t.jsx("div",{className:"mailbox-split-detail-pane","data-testid":"mailbox-split-detail-pane",children:me()})]}):t.jsxs(t.Fragment,{children:[ge(),x&&t.jsx(fm,{recipient:w,replyContext:C,agents:K,projectId:e,onSend:O,onCancel:Q,addToast:n}),!p&&!x&&de()]})})]})}function Ol(){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 di(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 Mi(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 IS(e,n){const s={};return(e[e.length-1]===""?[...e,""]:e).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const $S=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,DS=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,LS={};function bm(e,n){return(LS.jsx?DS:$S).test(e)}const zS=/[ \t\n\f\r]/g;function FS(e){return typeof e=="object"?e.type==="text"?xm(e.value):!1:xm(e)}function xm(e){return e.replace(zS,"")===""}class Ur{constructor(n,s,i){this.normal=s,this.property=n,i&&(this.space=i)}}Ur.prototype.normal={};Ur.prototype.property={};Ur.prototype.space=void 0;function df(e,n){const s={},i={};for(const r of e)Object.assign(s,r.property),Object.assign(i,r.normal);return new Ur(s,i,n)}function Wc(e){return e.toLowerCase()}class Ns{constructor(n,s){this.attribute=s,this.property=n}}Ns.prototype.attribute="";Ns.prototype.booleanish=!1;Ns.prototype.boolean=!1;Ns.prototype.commaOrSpaceSeparated=!1;Ns.prototype.commaSeparated=!1;Ns.prototype.defined=!1;Ns.prototype.mustUseProperty=!1;Ns.prototype.number=!1;Ns.prototype.overloadedBoolean=!1;Ns.prototype.property="";Ns.prototype.spaceSeparated=!1;Ns.prototype.space=void 0;let OS=0;const Ut=Qi(),Un=Qi(),Kc=Qi(),st=Qi(),kn=Qi(),fa=Qi(),Ss=Qi();function Qi(){return 2**++OS}const Gc=Object.freeze(Object.defineProperty({__proto__:null,boolean:Ut,booleanish:Un,commaOrSpaceSeparated:Ss,commaSeparated:fa,number:st,overloadedBoolean:Kc,spaceSeparated:kn},Symbol.toStringTag,{value:"Module"})),Ul=Object.keys(Gc);class Md extends Ns{constructor(n,s,i,r){let o=-1;if(super(n,s),vm(this,"space",r),typeof i=="number")for(;++o<Ul.length;){const l=Ul[o];vm(this,Ul[o],(i&Gc[l])===Gc[l])}}}Md.prototype.defined=!0;function vm(e,n,s){s&&(e[n]=s)}function $a(e){const n={},s={};for(const[i,r]of Object.entries(e.properties)){const o=new Md(i,e.transform(e.attributes||{},i),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(i)&&(o.mustUseProperty=!0),n[i]=o,s[Wc(i)]=i,s[Wc(o.attribute)]=i}return new Ur(n,s,e.space)}const uf=$a({properties:{ariaActiveDescendant:null,ariaAtomic:Un,ariaAutoComplete:null,ariaBusy:Un,ariaChecked:Un,ariaColCount:st,ariaColIndex:st,ariaColSpan:st,ariaControls:kn,ariaCurrent:null,ariaDescribedBy:kn,ariaDetails:null,ariaDisabled:Un,ariaDropEffect:kn,ariaErrorMessage:null,ariaExpanded:Un,ariaFlowTo:kn,ariaGrabbed:Un,ariaHasPopup:null,ariaHidden:Un,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:kn,ariaLevel:st,ariaLive:null,ariaModal:Un,ariaMultiLine:Un,ariaMultiSelectable:Un,ariaOrientation:null,ariaOwns:kn,ariaPlaceholder:null,ariaPosInSet:st,ariaPressed:Un,ariaReadOnly:Un,ariaRelevant:null,ariaRequired:Un,ariaRoleDescription:kn,ariaRowCount:st,ariaRowIndex:st,ariaRowSpan:st,ariaSelected:Un,ariaSetSize:st,ariaSort:null,ariaValueMax:st,ariaValueMin:st,ariaValueNow:st,ariaValueText:null,role:null},transform(e,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function mf(e,n){return n in e?e[n]:n}function hf(e,n){return mf(e,n.toLowerCase())}const US=$a({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:fa,acceptCharset:kn,accessKey:kn,action:null,allow:null,allowFullScreen:Ut,allowPaymentRequest:Ut,allowUserMedia:Ut,alt:null,as:null,async:Ut,autoCapitalize:null,autoComplete:kn,autoFocus:Ut,autoPlay:Ut,blocking:kn,capture:null,charSet:null,checked:Ut,cite:null,className:kn,cols:st,colSpan:null,content:null,contentEditable:Un,controls:Ut,controlsList:kn,coords:st|fa,crossOrigin:null,data:null,dateTime:null,decoding:null,default:Ut,defer:Ut,dir:null,dirName:null,disabled:Ut,download:Kc,draggable:Un,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:Ut,formTarget:null,headers:kn,height:st,hidden:Kc,high:st,href:null,hrefLang:null,htmlFor:kn,httpEquiv:kn,id:null,imageSizes:null,imageSrcSet:null,inert:Ut,inputMode:null,integrity:null,is:null,isMap:Ut,itemId:null,itemProp:kn,itemRef:kn,itemScope:Ut,itemType:kn,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:Ut,low:st,manifest:null,max:null,maxLength:st,media:null,method:null,min:null,minLength:st,multiple:Ut,muted:Ut,name:null,nonce:null,noModule:Ut,noValidate:Ut,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:Ut,optimum:st,pattern:null,ping:kn,placeholder:null,playsInline:Ut,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:Ut,referrerPolicy:null,rel:kn,required:Ut,reversed:Ut,rows:st,rowSpan:st,sandbox:kn,scope:null,scoped:Ut,seamless:Ut,selected:Ut,shadowRootClonable:Ut,shadowRootDelegatesFocus:Ut,shadowRootMode:null,shape:null,size:st,sizes:null,slot:null,span:st,spellCheck:Un,src:null,srcDoc:null,srcLang:null,srcSet:null,start:st,step:null,style:null,tabIndex:st,target:null,title:null,translate:null,type:null,typeMustMatch:Ut,useMap:null,value:Un,width:st,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:kn,axis:null,background:null,bgColor:null,border:st,borderColor:null,bottomMargin:st,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:Ut,declare:Ut,event:null,face:null,frame:null,frameBorder:null,hSpace:st,leftMargin:st,link:null,longDesc:null,lowSrc:null,marginHeight:st,marginWidth:st,noResize:Ut,noHref:Ut,noShade:Ut,noWrap:Ut,object:null,profile:null,prompt:null,rev:null,rightMargin:st,rules:null,scheme:null,scrolling:Un,standby:null,summary:null,text:null,topMargin:st,valueType:null,version:null,vAlign:null,vLink:null,vSpace:st,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:Ut,disableRemotePlayback:Ut,prefix:null,property:null,results:st,security:null,unselectable:null},space:"html",transform:hf}),BS=$a({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:Ss,accentHeight:st,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:st,amplitude:st,arabicForm:null,ascent:st,attributeName:null,attributeType:null,azimuth:st,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:st,by:null,calcMode:null,capHeight:st,className:kn,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:st,diffuseConstant:st,direction:null,display:null,dur:null,divisor:st,dominantBaseline:null,download:Ut,dx:null,dy:null,edgeMode:null,editable:null,elevation:st,enableBackground:null,end:null,event:null,exponent:st,externalResourcesRequired:null,fill:null,fillOpacity:st,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:fa,g2:fa,glyphName:fa,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:st,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:st,horizOriginX:st,horizOriginY:st,id:null,ideographic:st,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:st,k:st,k1:st,k2:st,k3:st,k4:st,kernelMatrix:Ss,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:st,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:st,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:st,overlineThickness:st,paintOrder:null,panose1:null,path:null,pathLength:st,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:kn,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:st,pointsAtY:st,pointsAtZ:st,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Ss,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Ss,rev:Ss,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Ss,requiredFeatures:Ss,requiredFonts:Ss,requiredFormats:Ss,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:st,specularExponent:st,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:st,strikethroughThickness:st,string:null,stroke:null,strokeDashArray:Ss,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:st,strokeOpacity:st,strokeWidth:null,style:null,surfaceScale:st,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Ss,tabIndex:st,tableValues:null,target:null,targetX:st,targetY:st,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Ss,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:st,underlineThickness:st,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:st,values:null,vAlphabetic:st,vMathematical:st,vectorEffect:null,vHanging:st,vIdeographic:st,version:null,vertAdvY:st,vertOriginX:st,vertOriginY:st,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:st,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:mf}),pf=$a({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()}}),ff=$a({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:hf}),gf=$a({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,n){return"xml:"+n.slice(3).toLowerCase()}}),HS={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"},qS=/[A-Z]/g,ym=/-[a-z]/g,VS=/^data[-\w.:]+$/i;function WS(e,n){const s=Wc(n);let i=n,r=Ns;if(s in e.normal)return e.property[e.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&VS.test(n)){if(n.charAt(4)==="-"){const o=n.slice(5).replace(ym,GS);i="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=n.slice(4);if(!ym.test(o)){let l=o.replace(qS,KS);l.charAt(0)!=="-"&&(l="-"+l),n="data"+l}}r=Md}return new r(i,n)}function KS(e){return"-"+e.toLowerCase()}function GS(e){return e.charAt(1).toUpperCase()}const JS=df([uf,US,pf,ff,gf],"html"),Ad=df([uf,BS,pf,ff,gf],"svg");function YS(e){return e.join(" ").trim()}var la={},Bl,jm;function QS(){if(jm)return Bl;jm=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=`
624
+ `,d="/",m="*",h="",f="comment",p="declaration";function g(v,x){if(typeof v!="string")throw new TypeError("First argument must be a string");if(!v)return[];x=x||{};var y=1,w=1;function E(L){var $=L.match(n);$&&(y+=$.length);var U=L.lastIndexOf(u);w=~U?L.length-U:w+L.length}function C(){var L={line:y,column:w};return function($){return $.position=new j(L),z(),$}}function j(L){this.start=L,this.end={line:y,column:w},this.source=x.source}j.prototype.content=v;function A(L){var $=new Error(x.source+":"+y+":"+w+": "+L);if($.reason=L,$.filename=x.source,$.line=y,$.column=w,$.source=v,!x.silent)throw $}function S(L){var $=L.exec(v);if($){var U=$[0];return E(U),v=v.slice(U.length),$}}function z(){S(s)}function _(L){var $;for(L=L||[];$=R();)$!==!1&&L.push($);return L}function R(){var L=C();if(!(d!=v.charAt(0)||m!=v.charAt(1))){for(var $=2;h!=v.charAt($)&&(m!=v.charAt($)||d!=v.charAt($+1));)++$;if($+=2,h===v.charAt($-1))return A("End of comment missing");var U=v.slice(2,$-2);return w+=2,E(U),v=v.slice($),w+=2,L({type:f,comment:U})}}function B(){var L=C(),$=S(i);if($){if(R(),!S(r))return A("property missing ':'");var U=S(o),G=L({type:p,property:b($[0].replace(e,h)),value:U?b(U[0].replace(e,h)):h});return S(l),G}}function K(){var L=[];_(L);for(var $;$=B();)$!==!1&&(L.push($),_(L));return L}return z(),K()}function b(v){return v?v.replace(c,h):h}return Bl=g,Bl}var km;function XS(){if(km)return la;km=1;var e=la&&la.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(la,"__esModule",{value:!0}),la.default=s;const n=e(QS());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 la}var Ka={},wm;function ZS(){if(wm)return Ka;wm=1,Object.defineProperty(Ka,"__esModule",{value:!0}),Ka.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 Ka.camelCase=u,Ka}var Ga,Nm;function e0(){if(Nm)return Ga;Nm=1;var e=Ga&&Ga.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},n=e(XS()),s=ZS();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,Ga=i,Ga}var t0=e0();const n0=lp(t0),bf=xf("end"),Rd=xf("start");function xf(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 s0(e){const n=Rd(e),s=bf(e);if(n&&s)return{start:n,end:s}}function gr(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Sm(e.position):"start"in e||"end"in e?Sm(e):"line"in e||"column"in e?Jc(e):""}function Jc(e){return Cm(e&&e.line)+":"+Cm(e&&e.column)}function Sm(e){return Jc(e&&e.start)+"-"+Jc(e&&e.end)}function Cm(e){return e&&typeof e=="number"?e:1}class us 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=gr(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}}us.prototype.file="";us.prototype.name="";us.prototype.reason="";us.prototype.message="";us.prototype.stack="";us.prototype.column=void 0;us.prototype.line=void 0;us.prototype.ancestors=void 0;us.prototype.cause=void 0;us.prototype.fatal=void 0;us.prototype.place=void 0;us.prototype.ruleId=void 0;us.prototype.source=void 0;const Td={}.hasOwnProperty,i0=new Map,a0=/[A-Z]/g,r0=new Set(["table","tbody","thead","tfoot","tr"]),o0=new Set(["td","th"]),vf="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function l0(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=g0(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=f0(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"?Ad:JS,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},o=yf(r,e,void 0);return o&&typeof o!="string"?o:r.create(e,r.Fragment,{children:o||void 0},void 0)}function yf(e,n,s){if(n.type==="element")return c0(e,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return d0(e,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return m0(e,n,s);if(n.type==="mdxjsEsm")return u0(e,n);if(n.type==="root")return h0(e,n,s);if(n.type==="text")return p0(e,n)}function c0(e,n,s){const i=e.schema;let r=i;n.tagName.toLowerCase()==="svg"&&i.space==="html"&&(r=Ad,e.schema=r),e.ancestors.push(n);const o=kf(e,n.tagName,!1),l=b0(e,n);let c=Id(e,n);return r0.has(n.tagName)&&(c=c.filter(function(u){return typeof u=="string"?!FS(u):!0})),jf(e,l,o,n),Pd(l,c),e.ancestors.pop(),e.schema=i,e.create(n,o,l,s)}function d0(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)}_r(e,n.position)}function u0(e,n){if(n.data&&n.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(n.data.estree);_r(e,n.position)}function m0(e,n,s){const i=e.schema;let r=i;n.name==="svg"&&i.space==="html"&&(r=Ad,e.schema=r),e.ancestors.push(n);const o=n.name===null?e.Fragment:kf(e,n.name,!0),l=x0(e,n),c=Id(e,n);return jf(e,l,o,n),Pd(l,c),e.ancestors.pop(),e.schema=i,e.create(n,o,l,s)}function h0(e,n,s){const i={};return Pd(i,Id(e,n)),e.create(n,e.Fragment,i,s)}function p0(e,n){return n.value}function jf(e,n,s,i){typeof s!="string"&&s!==e.Fragment&&e.passNode&&(n.node=i)}function Pd(e,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(e.children=s)}}function f0(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 g0(e,n){return s;function s(i,r,o,l){const c=Array.isArray(o.children),u=Rd(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 b0(e,n){const s={};let i,r;for(r in n.properties)if(r!=="children"&&Td.call(n.properties,r)){const o=v0(e,r,n.properties[r]);if(o){const[l,c]=o;e.tableCellAlignToStyle&&l==="align"&&typeof c=="string"&&o0.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 x0(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 _r(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 _r(e,n.position);else o=i.value===null?!0:i.value;s[r]=o}return s}function Id(e,n){const s=[];let i=-1;const r=e.passKeys?new Map:i0;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=yf(e,o,l);c!==void 0&&s.push(c)}return s}function v0(e,n,s){const i=WS(e.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=i.commaSeparated?IS(s):YS(s)),i.property==="style"){let r=typeof s=="object"?s:y0(e,String(s));return e.stylePropertyNameCase==="css"&&(r=j0(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&i.space?HS[i.property]||i.property:i.attribute,s]}}function y0(e,n){try{return n0(n,{reactCompat:!0})}catch(s){if(e.ignoreInvalidStyle)return{};const i=s,r=new us("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=vf+"#cannot-parse-style-attribute",r}}function kf(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=bm(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=bm(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(i.type==="Literal"){const r=i.value;return Td.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(i);_r(e)}function _r(e,n){const s=new us("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=vf+"#cannot-handle-mdx-estrees-without-createevaluater",s}function j0(e){const n={};let s;for(s in e)Td.call(e,s)&&(n[k0(s)]=e[s]);return n}function k0(e){let n=e.replace(a0,w0);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function w0(e){return"-"+e.toLowerCase()}const Hl={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"]},N0={};function $d(e,n){const s=N0,i=typeof s.includeImageAlt=="boolean"?s.includeImageAlt:!0,r=typeof s.includeHtml=="boolean"?s.includeHtml:!0;return wf(e,i,r)}function wf(e,n,s){if(S0(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 Em(e.children,n,s)}return Array.isArray(e)?Em(e,n,s):""}function Em(e,n,s){const i=[];let r=-1;for(;++r<e.length;)i[r]=wf(e[r],n,s);return i.join("")}function S0(e){return!!(e&&typeof e=="object")}const _m=document.createElement("i");function Dd(e){const n="&"+e+";";_m.innerHTML=n;const s=_m.textContent;return s.charCodeAt(s.length-1)===59&&e!=="semi"||s===n?!1:s}function Ms(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 $s(e,n){return e.length>0?(Ms(e,e.length,0,n),e):n}const Mm={}.hasOwnProperty;function Nf(e){const n={};let s=-1;for(;++s<e.length;)C0(n,e[s]);return n}function C0(e,n){let s;for(s in n){const r=(Mm.call(e,s)?e[s]:void 0)||(e[s]={}),o=n[s];let l;if(o)for(l in o){Mm.call(r,l)||(r[l]=[]);const c=o[l];E0(r[l],Array.isArray(c)?c:c?[c]:[])}}}function E0(e,n){let s=-1;const i=[];for(;++s<n.length;)(n[s].add==="after"?e:i).push(n[s]);Ms(e,0,0,i)}function Sf(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 Vs(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const ps=Ai(/[A-Za-z]/),ls=Ai(/[\dA-Za-z]/),_0=Ai(/[#-'*+\--9=?A-Z^-~]/);function Uo(e){return e!==null&&(e<32||e===127)}const Yc=Ai(/\d/),M0=Ai(/[\dA-Fa-f]/),A0=Ai(/[!-/:-@[-`{-~]/);function Ct(e){return e!==null&&e<-2}function vn(e){return e!==null&&(e<0||e===32)}function Jt(e){return e===-2||e===-1||e===32}const dl=Ai(/\p{P}|\p{S}/u),Ki=Ai(/\s/);function Ai(e){return n;function n(s){return s!==null&&s>-1&&e.test(String.fromCharCode(s))}}function Da(e){const n=[];let s=-1,i=0,r=0;for(;++s<e.length;){const o=e.charCodeAt(s);let l="";if(o===37&&ls(e.charCodeAt(s+1))&&ls(e.charCodeAt(s+2)))r=2;else if(o<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(o))||(l=String.fromCharCode(o));else if(o>55295&&o<57344){const c=e.charCodeAt(s+1);o<56320&&c>56319&&c<57344?(l=String.fromCharCode(o,c),r=1):l="�"}else l=String.fromCharCode(o);l&&(n.push(e.slice(i,s),encodeURIComponent(l)),i=s+r+1,l=""),r&&(s+=r,r=0)}return n.join("")+e.slice(i)}function tn(e,n,s,i){const r=i?i-1:Number.POSITIVE_INFINITY;let o=0;return l;function l(u){return Jt(u)?(e.enter(s),c(u)):n(u)}function c(u){return Jt(u)&&o++<r?(e.consume(u),c):(e.exit(s),n(u))}}const R0={tokenize:T0};function T0(e){const n=e.attempt(this.parser.constructs.contentInitial,i,r);let s;return n;function i(c){if(c===null){e.consume(c);return}return e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),tn(e,n,"linePrefix")}function r(c){return e.enter("paragraph"),o(c)}function o(c){const u=e.enter("chunkText",{contentType:"text",previous:s});return s&&(s.next=u),s=u,l(c)}function l(c){if(c===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(c);return}return Ct(c)?(e.consume(c),e.exit("chunkText"),o):(e.consume(c),l)}}const P0={tokenize:I0},Am={tokenize:$0};function I0(e){const n=this,s=[];let i=0,r,o,l;return c;function c(w){if(i<s.length){const E=s[i];return n.containerState=E[1],e.attempt(E[0].continuation,u,d)(w)}return d(w)}function u(w){if(i++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,r&&y();const E=n.events.length;let C=E,j;for(;C--;)if(n.events[C][0]==="exit"&&n.events[C][1].type==="chunkFlow"){j=n.events[C][1].end;break}x(i);let A=E;for(;A<n.events.length;)n.events[A][1].end={...j},A++;return Ms(n.events,C+1,0,n.events.slice(E)),n.events.length=A,d(w)}return c(w)}function d(w){if(i===s.length){if(!r)return f(w);if(r.currentConstruct&&r.currentConstruct.concrete)return g(w);n.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return n.containerState={},e.check(Am,m,h)(w)}function m(w){return r&&y(),x(i),f(w)}function h(w){return n.parser.lazy[n.now().line]=i!==s.length,l=n.now().offset,g(w)}function f(w){return n.containerState={},e.attempt(Am,p,g)(w)}function p(w){return i++,s.push([n.currentConstruct,n.containerState]),f(w)}function g(w){if(w===null){r&&y(),x(0),e.consume(w);return}return r=r||n.parser.flow(n.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:o}),b(w)}function b(w){if(w===null){v(e.exit("chunkFlow"),!0),x(0),e.consume(w);return}return Ct(w)?(e.consume(w),v(e.exit("chunkFlow")),i=0,n.interrupt=void 0,c):(e.consume(w),b)}function v(w,E){const C=n.sliceStream(w);if(E&&C.push(null),w.previous=o,o&&(o.next=w),o=w,r.defineSkip(w.start),r.write(C),n.parser.lazy[w.start.line]){let j=r.events.length;for(;j--;)if(r.events[j][1].start.offset<l&&(!r.events[j][1].end||r.events[j][1].end.offset>l))return;const A=n.events.length;let S=A,z,_;for(;S--;)if(n.events[S][0]==="exit"&&n.events[S][1].type==="chunkFlow"){if(z){_=n.events[S][1].end;break}z=!0}for(x(i),j=A;j<n.events.length;)n.events[j][1].end={..._},j++;Ms(n.events,S+1,0,n.events.slice(A)),n.events.length=j}}function x(w){let E=s.length;for(;E-- >w;){const C=s[E];n.containerState=C[1],C[0].exit.call(n,e)}s.length=w}function y(){r.write([null]),o=void 0,r=void 0,n.containerState._closeFlow=void 0}}function $0(e,n,s){return tn(e,e.attempt(this.parser.constructs.document,n,s),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function ja(e){if(e===null||vn(e)||Ki(e))return 1;if(dl(e))return 2}function ul(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 Qc={name:"attention",resolveAll:D0,tokenize:L0};function D0(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},f={...e[s][1].start};Rm(h,-u),Rm(f,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:f},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=$s(d,[["enter",e[i][1],n],["exit",e[i][1],n]])),d=$s(d,[["enter",r,n],["enter",l,n],["exit",l,n],["enter",o,n]]),d=$s(d,ul(n.parser.constructs.insideSpan.null,e.slice(i+1,s),n)),d=$s(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=$s(d,[["enter",e[s][1],n],["exit",e[s][1],n]])):m=0,Ms(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 L0(e,n){const s=this.parser.constructs.attentionMarkers.null,i=this.previous,r=ja(i);let o;return l;function l(u){return o=u,e.enter("attentionSequence"),c(u)}function c(u){if(u===o)return e.consume(u),c;const d=e.exit("attentionSequence"),m=ja(u),h=!m||m===2&&r||s.includes(u),f=!r||r===2&&m||s.includes(i);return d._open=!!(o===42?h:h&&(r||!f)),d._close=!!(o===42?f:f&&(m||!h)),n(u)}}function Rm(e,n){e.column+=n,e.offset+=n,e._bufferIndex+=n}const z0={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 ps(p)?(e.consume(p),l):p===64?s(p):d(p)}function l(p){return p===43||p===45||p===46||ls(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||ls(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||Uo(p)?s(p):(e.consume(p),u)}function d(p){return p===64?(e.consume(p),m):_0(p)?(e.consume(p),d):s(p)}function m(p){return ls(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):f(p)}function f(p){if((p===45||ls(p))&&i++<63){const g=p===45?f:h;return e.consume(p),g}return s(p)}}const Br={partial:!0,tokenize:O0};function O0(e,n,s){return i;function i(o){return Jt(o)?tn(e,r,"linePrefix")(o):r(o)}function r(o){return o===null||Ct(o)?n(o):s(o)}}const Cf={continuation:{tokenize:B0},exit:H0,name:"blockQuote",tokenize:U0};function U0(e,n,s){const i=this;return r;function r(l){if(l===62){const c=i.containerState;return c.open||(e.enter("blockQuote",{_container:!0}),c.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(l),e.exit("blockQuoteMarker"),o}return s(l)}function o(l){return Jt(l)?(e.enter("blockQuotePrefixWhitespace"),e.consume(l),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),n):(e.exit("blockQuotePrefix"),n(l))}}function B0(e,n,s){const i=this;return r;function r(l){return Jt(l)?tn(e,o,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l):o(l)}function o(l){return e.attempt(Cf,n,s)(l)}}function H0(e){e.exit("blockQuote")}const Ef={name:"characterEscape",tokenize:q0};function q0(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 A0(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),n):s(o)}}const _f={name:"characterReference",tokenize:V0};function V0(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=ls,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=M0,m):(e.enter("characterReferenceValue"),o=7,l=Yc,m(h))}function m(h){if(h===59&&r){const f=e.exit("characterReferenceValue");return l===ls&&!Dd(i.sliceSerialize(f))?s(h):(e.enter("characterReferenceMarker"),e.consume(h),e.exit("characterReferenceMarker"),e.exit("characterReference"),n)}return l(h)&&r++<o?(e.consume(h),m):s(h)}}const Tm={partial:!0,tokenize:K0},Pm={concrete:!0,name:"codeFenced",tokenize:W0};function W0(e,n,s){const i=this,r={partial:!0,tokenize:C};let o=0,l=0,c;return u;function u(j){return d(j)}function d(j){const A=i.events[i.events.length-1];return o=A&&A[1].type==="linePrefix"?A[2].sliceSerialize(A[1],!0).length:0,c=j,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),m(j)}function m(j){return j===c?(l++,e.consume(j),m):l<3?s(j):(e.exit("codeFencedFenceSequence"),Jt(j)?tn(e,h,"whitespace")(j):h(j))}function h(j){return j===null||Ct(j)?(e.exit("codeFencedFence"),i.interrupt?n(j):e.check(Tm,b,E)(j)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),f(j))}function f(j){return j===null||Ct(j)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),h(j)):Jt(j)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),tn(e,p,"whitespace")(j)):j===96&&j===c?s(j):(e.consume(j),f)}function p(j){return j===null||Ct(j)?h(j):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(j))}function g(j){return j===null||Ct(j)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),h(j)):j===96&&j===c?s(j):(e.consume(j),g)}function b(j){return e.attempt(r,E,v)(j)}function v(j){return e.enter("lineEnding"),e.consume(j),e.exit("lineEnding"),x}function x(j){return o>0&&Jt(j)?tn(e,y,"linePrefix",o+1)(j):y(j)}function y(j){return j===null||Ct(j)?e.check(Tm,b,E)(j):(e.enter("codeFlowValue"),w(j))}function w(j){return j===null||Ct(j)?(e.exit("codeFlowValue"),y(j)):(e.consume(j),w)}function E(j){return e.exit("codeFenced"),n(j)}function C(j,A,S){let z=0;return _;function _($){return j.enter("lineEnding"),j.consume($),j.exit("lineEnding"),R}function R($){return j.enter("codeFencedFence"),Jt($)?tn(j,B,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)($):B($)}function B($){return $===c?(j.enter("codeFencedFenceSequence"),K($)):S($)}function K($){return $===c?(z++,j.consume($),K):z>=l?(j.exit("codeFencedFenceSequence"),Jt($)?tn(j,L,"whitespace")($):L($)):S($)}function L($){return $===null||Ct($)?(j.exit("codeFencedFence"),A($)):S($)}}}function K0(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 ql={name:"codeIndented",tokenize:J0},G0={partial:!0,tokenize:Y0};function J0(e,n,s){const i=this;return r;function r(d){return e.enter("codeIndented"),tn(e,o,"linePrefix",5)(d)}function o(d){const m=i.events[i.events.length-1];return m&&m[1].type==="linePrefix"&&m[2].sliceSerialize(m[1],!0).length>=4?l(d):s(d)}function l(d){return d===null?u(d):Ct(d)?e.attempt(G0,l,u)(d):(e.enter("codeFlowValue"),c(d))}function c(d){return d===null||Ct(d)?(e.exit("codeFlowValue"),l(d)):(e.consume(d),c)}function u(d){return e.exit("codeIndented"),n(d)}}function Y0(e,n,s){const i=this;return r;function r(l){return i.parser.lazy[i.now().line]?s(l):Ct(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),r):tn(e,o,"linePrefix",5)(l)}function o(l){const c=i.events[i.events.length-1];return c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?n(l):Ct(l)?r(l):s(l)}}const Q0={name:"codeText",previous:Z0,resolve:X0,tokenize:eC};function X0(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 Z0(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function eC(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)):Ct(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||Ct(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 tC{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&&Ja(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),Ja(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),Ja(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);Ja(this.right,s.reverse())}else{const s=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);Ja(this.left,s.reverse())}}}function Ja(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 Mf(e){const n={};let s=-1,i,r,o,l,c,u,d;const m=new tC(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,nC(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 Ms(e,0,Number.POSITIVE_INFINITY,m.slice(0)),!d}function nC(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,f=-1,p=s,g=0,b=0;const v=[b];for(;p;){for(;e.get(++r)[1]!==p;);o.push(r),p._tokenizer||(m=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;++f<c.length;)c[f][0]==="exit"&&c[f-1][0]==="enter"&&c[f][1].type===c[f-1][1].type&&c[f][1].start.line!==c[f][1].end.line&&(b=f+1,v.push(b),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(l.events=[],p?(p._tokenizer=void 0,p.previous=void 0):v.pop(),f=v.length;f--;){const x=c.slice(v[f],v[f+1]),y=o.pop();u.push([y,y+x.length-1]),e.splice(y,2,x)}for(u.reverse(),f=-1;++f<u.length;)d[g+u[f][0]]=g+u[f][1],g+=u[f][1]-u[f][0]-1;return d}const sC={resolve:aC,tokenize:rC},iC={partial:!0,tokenize:oC};function aC(e){return Mf(e),e}function rC(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):Ct(c)?e.check(iC,l,o)(c):(e.consume(c),r)}function o(c){return e.exit("chunkContent"),e.exit("content"),n(c)}function l(c){return e.consume(c),e.exit("chunkContent"),s.next=e.enter("chunkContent",{contentType:"content",previous:s}),s=s.next,r}}function oC(e,n,s){const i=this;return r;function r(l){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),tn(e,o,"linePrefix")}function o(l){if(l===null||Ct(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 Af(e,n,s,i,r,o,l,c,u){const d=u||Number.POSITIVE_INFINITY;let m=0;return h;function h(x){return x===60?(e.enter(i),e.enter(r),e.enter(o),e.consume(x),e.exit(o),f):x===null||x===32||x===41||Uo(x)?s(x):(e.enter(i),e.enter(l),e.enter(c),e.enter("chunkString",{contentType:"string"}),b(x))}function f(x){return x===62?(e.enter(o),e.consume(x),e.exit(o),e.exit(r),e.exit(i),n):(e.enter(c),e.enter("chunkString",{contentType:"string"}),p(x))}function p(x){return x===62?(e.exit("chunkString"),e.exit(c),f(x)):x===null||x===60||Ct(x)?s(x):(e.consume(x),x===92?g:p)}function g(x){return x===60||x===62||x===92?(e.consume(x),p):p(x)}function b(x){return!m&&(x===null||x===41||vn(x))?(e.exit("chunkString"),e.exit(c),e.exit(l),e.exit(i),n(x)):m<d&&x===40?(e.consume(x),m++,b):x===41?(e.consume(x),m--,b):x===null||x===32||x===40||Uo(x)?s(x):(e.consume(x),x===92?v:b)}function v(x){return x===40||x===41||x===92?(e.consume(x),b):b(x)}}function Rf(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):Ct(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||Ct(p)||c++>999?(e.exit("chunkString"),m(p)):(e.consume(p),u||(u=!Jt(p)),p===92?f:h)}function f(p){return p===91||p===92||p===93?(e.consume(p),c++,h):h(p)}}function Tf(e,n,s,i,r,o){let l;return c;function c(f){return f===34||f===39||f===40?(e.enter(i),e.enter(r),e.consume(f),e.exit(r),l=f===40?41:f,u):s(f)}function u(f){return f===l?(e.enter(r),e.consume(f),e.exit(r),e.exit(i),n):(e.enter(o),d(f))}function d(f){return f===l?(e.exit(o),u(l)):f===null?s(f):Ct(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),tn(e,d,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),m(f))}function m(f){return f===l||f===null||Ct(f)?(e.exit("chunkString"),d(f)):(e.consume(f),f===92?h:m)}function h(f){return f===l||f===92?(e.consume(f),m):m(f)}}function br(e,n){let s;return i;function i(r){return Ct(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),s=!0,i):Jt(r)?tn(e,i,s?"linePrefix":"lineSuffix")(r):n(r)}}const lC={name:"definition",tokenize:dC},cC={partial:!0,tokenize:uC};function dC(e,n,s){const i=this;let r;return o;function o(p){return e.enter("definition"),l(p)}function l(p){return Rf.call(i,e,c,s,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function c(p){return r=Vs(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 vn(p)?br(e,d)(p):d(p)}function d(p){return Af(e,m,s,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function m(p){return e.attempt(cC,h,h)(p)}function h(p){return Jt(p)?tn(e,f,"whitespace")(p):f(p)}function f(p){return p===null||Ct(p)?(e.exit("definition"),i.parser.defined.push(r),n(p)):s(p)}}function uC(e,n,s){return i;function i(c){return vn(c)?br(e,r)(c):s(c)}function r(c){return Tf(e,o,s,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function o(c){return Jt(c)?tn(e,l,"whitespace")(c):l(c)}function l(c){return c===null||Ct(c)?n(c):s(c)}}const mC={name:"hardBreakEscape",tokenize:hC};function hC(e,n,s){return i;function i(o){return e.enter("hardBreakEscape"),e.consume(o),r}function r(o){return Ct(o)?(e.exit("hardBreakEscape"),n(o)):s(o)}}const pC={name:"headingAtx",resolve:fC,tokenize:gC};function fC(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"},Ms(e,i,s-i+1,[["enter",r,n],["enter",o,n],["exit",o,n],["exit",r,n]])),e}function gC(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||vn(m)?(e.exit("atxHeadingSequence"),c(m)):s(m)}function c(m){return m===35?(e.enter("atxHeadingSequence"),u(m)):m===null||Ct(m)?(e.exit("atxHeading"),n(m)):Jt(m)?tn(e,c,"whitespace")(m):(e.enter("atxHeadingText"),d(m))}function u(m){return m===35?(e.consume(m),u):(e.exit("atxHeadingSequence"),c(m))}function d(m){return m===null||m===35||vn(m)?(e.exit("atxHeadingText"),c(m)):(e.consume(m),d)}}const bC=["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"],Im=["pre","script","style","textarea"],xC={concrete:!0,name:"htmlFlow",resolveTo:jC,tokenize:kC},vC={partial:!0,tokenize:NC},yC={partial:!0,tokenize:wC};function jC(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 kC(e,n,s){const i=this;let r,o,l,c,u;return d;function d(k){return m(k)}function m(k){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(k),h}function h(k){return k===33?(e.consume(k),f):k===47?(e.consume(k),o=!0,b):k===63?(e.consume(k),r=3,i.interrupt?n:N):ps(k)?(e.consume(k),l=String.fromCharCode(k),v):s(k)}function f(k){return k===45?(e.consume(k),r=2,p):k===91?(e.consume(k),r=5,c=0,g):ps(k)?(e.consume(k),r=4,i.interrupt?n:N):s(k)}function p(k){return k===45?(e.consume(k),i.interrupt?n:N):s(k)}function g(k){const H="CDATA[";return k===H.charCodeAt(c++)?(e.consume(k),c===H.length?i.interrupt?n:B:g):s(k)}function b(k){return ps(k)?(e.consume(k),l=String.fromCharCode(k),v):s(k)}function v(k){if(k===null||k===47||k===62||vn(k)){const H=k===47,J=l.toLowerCase();return!H&&!o&&Im.includes(J)?(r=1,i.interrupt?n(k):B(k)):bC.includes(l.toLowerCase())?(r=6,H?(e.consume(k),x):i.interrupt?n(k):B(k)):(r=7,i.interrupt&&!i.parser.lazy[i.now().line]?s(k):o?y(k):w(k))}return k===45||ls(k)?(e.consume(k),l+=String.fromCharCode(k),v):s(k)}function x(k){return k===62?(e.consume(k),i.interrupt?n:B):s(k)}function y(k){return Jt(k)?(e.consume(k),y):_(k)}function w(k){return k===47?(e.consume(k),_):k===58||k===95||ps(k)?(e.consume(k),E):Jt(k)?(e.consume(k),w):_(k)}function E(k){return k===45||k===46||k===58||k===95||ls(k)?(e.consume(k),E):C(k)}function C(k){return k===61?(e.consume(k),j):Jt(k)?(e.consume(k),C):w(k)}function j(k){return k===null||k===60||k===61||k===62||k===96?s(k):k===34||k===39?(e.consume(k),u=k,A):Jt(k)?(e.consume(k),j):S(k)}function A(k){return k===u?(e.consume(k),u=null,z):k===null||Ct(k)?s(k):(e.consume(k),A)}function S(k){return k===null||k===34||k===39||k===47||k===60||k===61||k===62||k===96||vn(k)?C(k):(e.consume(k),S)}function z(k){return k===47||k===62||Jt(k)?w(k):s(k)}function _(k){return k===62?(e.consume(k),R):s(k)}function R(k){return k===null||Ct(k)?B(k):Jt(k)?(e.consume(k),R):s(k)}function B(k){return k===45&&r===2?(e.consume(k),U):k===60&&r===1?(e.consume(k),G):k===62&&r===4?(e.consume(k),I):k===63&&r===3?(e.consume(k),N):k===93&&r===5?(e.consume(k),ee):Ct(k)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(vC,T,K)(k)):k===null||Ct(k)?(e.exit("htmlFlowData"),K(k)):(e.consume(k),B)}function K(k){return e.check(yC,L,T)(k)}function L(k){return e.enter("lineEnding"),e.consume(k),e.exit("lineEnding"),$}function $(k){return k===null||Ct(k)?K(k):(e.enter("htmlFlowData"),B(k))}function U(k){return k===45?(e.consume(k),N):B(k)}function G(k){return k===47?(e.consume(k),l="",Y):B(k)}function Y(k){if(k===62){const H=l.toLowerCase();return Im.includes(H)?(e.consume(k),I):B(k)}return ps(k)&&l.length<8?(e.consume(k),l+=String.fromCharCode(k),Y):B(k)}function ee(k){return k===93?(e.consume(k),N):B(k)}function N(k){return k===62?(e.consume(k),I):k===45&&r===2?(e.consume(k),N):B(k)}function I(k){return k===null||Ct(k)?(e.exit("htmlFlowData"),T(k)):(e.consume(k),I)}function T(k){return e.exit("htmlFlow"),n(k)}}function wC(e,n,s){const i=this;return r;function r(l){return Ct(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 NC(e,n,s){return i;function i(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(Br,n,s)}}const SC={name:"htmlText",tokenize:CC};function CC(e,n,s){const i=this;let r,o,l;return c;function c(N){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(N),u}function u(N){return N===33?(e.consume(N),d):N===47?(e.consume(N),C):N===63?(e.consume(N),w):ps(N)?(e.consume(N),S):s(N)}function d(N){return N===45?(e.consume(N),m):N===91?(e.consume(N),o=0,g):ps(N)?(e.consume(N),y):s(N)}function m(N){return N===45?(e.consume(N),p):s(N)}function h(N){return N===null?s(N):N===45?(e.consume(N),f):Ct(N)?(l=h,G(N)):(e.consume(N),h)}function f(N){return N===45?(e.consume(N),p):h(N)}function p(N){return N===62?U(N):N===45?f(N):h(N)}function g(N){const I="CDATA[";return N===I.charCodeAt(o++)?(e.consume(N),o===I.length?b:g):s(N)}function b(N){return N===null?s(N):N===93?(e.consume(N),v):Ct(N)?(l=b,G(N)):(e.consume(N),b)}function v(N){return N===93?(e.consume(N),x):b(N)}function x(N){return N===62?U(N):N===93?(e.consume(N),x):b(N)}function y(N){return N===null||N===62?U(N):Ct(N)?(l=y,G(N)):(e.consume(N),y)}function w(N){return N===null?s(N):N===63?(e.consume(N),E):Ct(N)?(l=w,G(N)):(e.consume(N),w)}function E(N){return N===62?U(N):w(N)}function C(N){return ps(N)?(e.consume(N),j):s(N)}function j(N){return N===45||ls(N)?(e.consume(N),j):A(N)}function A(N){return Ct(N)?(l=A,G(N)):Jt(N)?(e.consume(N),A):U(N)}function S(N){return N===45||ls(N)?(e.consume(N),S):N===47||N===62||vn(N)?z(N):s(N)}function z(N){return N===47?(e.consume(N),U):N===58||N===95||ps(N)?(e.consume(N),_):Ct(N)?(l=z,G(N)):Jt(N)?(e.consume(N),z):U(N)}function _(N){return N===45||N===46||N===58||N===95||ls(N)?(e.consume(N),_):R(N)}function R(N){return N===61?(e.consume(N),B):Ct(N)?(l=R,G(N)):Jt(N)?(e.consume(N),R):z(N)}function B(N){return N===null||N===60||N===61||N===62||N===96?s(N):N===34||N===39?(e.consume(N),r=N,K):Ct(N)?(l=B,G(N)):Jt(N)?(e.consume(N),B):(e.consume(N),L)}function K(N){return N===r?(e.consume(N),r=void 0,$):N===null?s(N):Ct(N)?(l=K,G(N)):(e.consume(N),K)}function L(N){return N===null||N===34||N===39||N===60||N===61||N===96?s(N):N===47||N===62||vn(N)?z(N):(e.consume(N),L)}function $(N){return N===47||N===62||vn(N)?z(N):s(N)}function U(N){return N===62?(e.consume(N),e.exit("htmlTextData"),e.exit("htmlText"),n):s(N)}function G(N){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(N),e.exit("lineEnding"),Y}function Y(N){return Jt(N)?tn(e,ee,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(N):ee(N)}function ee(N){return e.enter("htmlTextData"),l(N)}}const Ld={name:"labelEnd",resolveAll:AC,resolveTo:RC,tokenize:TC},EC={tokenize:PC},_C={tokenize:IC},MC={tokenize:$C};function AC(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&&Ms(e,0,e.length,s),e}function RC(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=$s(c,e.slice(o+1,o+i+3)),c=$s(c,[["enter",m,n]]),c=$s(c,ul(n.parser.constructs.insideSpan.null,e.slice(o+i+4,l-3),n)),c=$s(c,[["exit",m,n],e[l-2],e[l-1],["exit",d,n]]),c=$s(c,e.slice(l+1)),c=$s(c,[["exit",u,n]]),Ms(e,o,e.length,c),e}function TC(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(f){return o?o._inactive?h(f):(l=i.parser.defined.includes(Vs(i.sliceSerialize({start:o.end,end:i.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(f),e.exit("labelMarker"),e.exit("labelEnd"),u):s(f)}function u(f){return f===40?e.attempt(EC,m,l?m:h)(f):f===91?e.attempt(_C,m,l?d:h)(f):l?m(f):h(f)}function d(f){return e.attempt(MC,m,h)(f)}function m(f){return n(f)}function h(f){return o._balanced=!0,s(f)}}function PC(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 vn(h)?br(e,o)(h):o(h)}function o(h){return h===41?m(h):Af(e,l,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function l(h){return vn(h)?br(e,u)(h):m(h)}function c(h){return s(h)}function u(h){return h===34||h===39||h===40?Tf(e,d,s,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):m(h)}function d(h){return vn(h)?br(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 IC(e,n,s){const i=this;return r;function r(c){return Rf.call(i,e,o,l,"reference","referenceMarker","referenceString")(c)}function o(c){return i.parser.defined.includes(Vs(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)))?n(c):s(c)}function l(c){return s(c)}}function $C(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 DC={name:"labelStartImage",resolveAll:Ld.resolveAll,tokenize:LC};function LC(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 zC={name:"labelStartLink",resolveAll:Ld.resolveAll,tokenize:FC};function FC(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 Vl={name:"lineEnding",tokenize:OC};function OC(e,n){return s;function s(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),tn(e,n,"linePrefix")}}const Eo={name:"thematicBreak",tokenize:UC};function UC(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||Ct(d))?(e.exit("thematicBreak"),n(d)):s(d)}function u(d){return d===r?(e.consume(d),i++,u):(e.exit("thematicBreakSequence"),Jt(d)?tn(e,c,"whitespace")(d):c(d))}}const js={continuation:{tokenize:VC},exit:KC,name:"list",tokenize:qC},BC={partial:!0,tokenize:GC},HC={partial:!0,tokenize:WC};function qC(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 g=i.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(g==="listUnordered"?!i.containerState.marker||p===i.containerState.marker:Yc(p)){if(i.containerState.type||(i.containerState.type=g,e.enter(g,{_container:!0})),g==="listUnordered")return e.enter("listItemPrefix"),p===42||p===45?e.check(Eo,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 Yc(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(Br,i.interrupt?s:m,e.attempt(BC,f,h))}function m(p){return i.containerState.initialBlankLine=!0,o++,f(p)}function h(p){return Jt(p)?(e.enter("listItemPrefixWhitespace"),e.consume(p),e.exit("listItemPrefixWhitespace"),f):s(p)}function f(p){return i.containerState.size=o+i.sliceSerialize(e.exit("listItemPrefix"),!0).length,n(p)}}function VC(e,n,s){const i=this;return i.containerState._closeFlow=void 0,e.check(Br,r,o);function r(c){return i.containerState.furtherBlankLines=i.containerState.furtherBlankLines||i.containerState.initialBlankLine,tn(e,n,"listItemIndent",i.containerState.size+1)(c)}function o(c){return i.containerState.furtherBlankLines||!Jt(c)?(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,l(c)):(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,e.attempt(HC,n,l)(c))}function l(c){return i.containerState._closeFlow=!0,i.interrupt=void 0,tn(e,e.attempt(js,n,s),"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function WC(e,n,s){const i=this;return tn(e,r,"listItemIndent",i.containerState.size+1);function r(o){const l=i.events[i.events.length-1];return l&&l[1].type==="listItemIndent"&&l[2].sliceSerialize(l[1],!0).length===i.containerState.size?n(o):s(o)}}function KC(e){e.exit(this.containerState.type)}function GC(e,n,s){const i=this;return tn(e,r,"listItemPrefixWhitespace",i.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function r(o){const l=i.events[i.events.length-1];return!Jt(o)&&l&&l[1].type==="listItemPrefixWhitespace"?n(o):s(o)}}const $m={name:"setextUnderline",resolveTo:JC,tokenize:YC};function JC(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 YC(e,n,s){const i=this;let r;return o;function o(d){let m=i.events.length,h;for(;m--;)if(i.events[m][1].type!=="lineEnding"&&i.events[m][1].type!=="linePrefix"&&i.events[m][1].type!=="content"){h=i.events[m][1].type==="paragraph";break}return!i.parser.lazy[i.now().line]&&(i.interrupt||h)?(e.enter("setextHeadingLine"),r=d,l(d)):s(d)}function l(d){return e.enter("setextHeadingLineSequence"),c(d)}function c(d){return d===r?(e.consume(d),c):(e.exit("setextHeadingLineSequence"),Jt(d)?tn(e,u,"lineSuffix")(d):u(d))}function u(d){return d===null||Ct(d)?(e.exit("setextHeadingLine"),n(d)):s(d)}}const QC={tokenize:XC};function XC(e){const n=this,s=e.attempt(Br,i,e.attempt(this.parser.constructs.flowInitial,r,tn(e,e.attempt(this.parser.constructs.flow,r,e.attempt(sC,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 ZC={resolveAll:If()},e2=Pf("string"),t2=Pf("text");function Pf(e){return{resolveAll:If(e==="text"?n2: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 f=-1;if(h)for(;++f<h.length;){const p=h[f];if(!p.previous||p.previous.call(i,i.previous))return!0}return!1}}}function If(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 n2(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 s2={42:js,43:js,45:js,48:js,49:js,50:js,51:js,52:js,53:js,54:js,55:js,56:js,57:js,62:Cf},i2={91:lC},a2={[-2]:ql,[-1]:ql,32:ql},r2={35:pC,42:Eo,45:[$m,Eo],60:xC,61:$m,95:Eo,96:Pm,126:Pm},o2={38:_f,92:Ef},l2={[-5]:Vl,[-4]:Vl,[-3]:Vl,33:DC,38:_f,42:Qc,60:[z0,SC],91:zC,92:[mC,Ef],93:Ld,95:Qc,96:Q0},c2={null:[Qc,ZC]},d2={null:[42,95]},u2={null:[]},m2=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:d2,contentInitial:i2,disable:u2,document:s2,flow:r2,flowInitial:a2,insideSpan:c2,string:o2,text:l2},Symbol.toStringTag,{value:"Module"}));function h2(e,n,s){let i={_bufferIndex:-1,_index:0,line:s&&s.line||1,column:s&&s.column||1,offset:s&&s.offset||0};const r={},o=[];let l=[],c=[];const u={attempt:A(C),check:A(j),consume:y,enter:w,exit:E,interrupt:A(j,{interrupt:!0})},d={code:null,containerState:{},defineSkip:b,events:[],now:g,parser:e,previous:null,sliceSerialize:f,sliceStream:p,write:h};let m=n.tokenize.call(d,u);return n.resolveAll&&o.push(n),d;function h(R){return l=$s(l,R),v(),l[l.length-1]!==null?[]:(S(n,0),d.events=ul(o,d.events,d),d.events)}function f(R,B){return f2(p(R),B)}function p(R){return p2(l,R)}function g(){const{_bufferIndex:R,_index:B,line:K,column:L,offset:$}=i;return{_bufferIndex:R,_index:B,line:K,column:L,offset:$}}function b(R){r[R.line]=R.column,_()}function v(){let R;for(;i._index<l.length;){const B=l[i._index];if(typeof B=="string")for(R=i._index,i._bufferIndex<0&&(i._bufferIndex=0);i._index===R&&i._bufferIndex<B.length;)x(B.charCodeAt(i._bufferIndex));else x(B)}}function x(R){m=m(R)}function y(R){Ct(R)?(i.line++,i.column=1,i.offset+=R===-3?2:1,_()):R!==-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=R}function w(R,B){const K=B||{};return K.type=R,K.start=g(),d.events.push(["enter",K,d]),c.push(K),K}function E(R){const B=c.pop();return B.end=g(),d.events.push(["exit",B,d]),B}function C(R,B){S(R,B.from)}function j(R,B){B.restore()}function A(R,B){return K;function K(L,$,U){let G,Y,ee,N;return Array.isArray(L)?T(L):"tokenize"in L?T([L]):I(L);function I(ue){return fe;function fe(W){const he=W!==null&&ue[W],O=W!==null&&ue.null,ne=[...Array.isArray(he)?he:he?[he]:[],...Array.isArray(O)?O:O?[O]:[]];return T(ne)(W)}}function T(ue){return G=ue,Y=0,ue.length===0?U:k(ue[Y])}function k(ue){return fe;function fe(W){return N=z(),ee=ue,ue.partial||(d.currentConstruct=ue),ue.name&&d.parser.constructs.disable.null.includes(ue.name)?J():ue.tokenize.call(B?Object.assign(Object.create(d),B):d,u,H,J)(W)}}function H(ue){return R(ee,N),$}function J(ue){return N.restore(),++Y<G.length?k(G[Y]):U}}}function S(R,B){R.resolveAll&&!o.includes(R)&&o.push(R),R.resolve&&Ms(d.events,B,d.events.length-B,R.resolve(d.events.slice(B),d)),R.resolveTo&&(d.events=R.resolveTo(d.events,d))}function z(){const R=g(),B=d.previous,K=d.currentConstruct,L=d.events.length,$=Array.from(c);return{from:L,restore:U};function U(){i=R,d.previous=B,d.currentConstruct=K,d.events.length=L,c=$,_()}}function _(){i.line in r&&i.column<2&&(i.column=r[i.line],i.offset+=r[i.line]-1)}}function p2(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 f2(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=`
625
+ `;break}case-3:{l=`\r
626
+ `;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 g2(e){const i={constructs:Nf([m2,...(e||{}).extensions||[]]),content:r(R0),defined:[],document:r(P0),flow:r(QC),lazy:{},string:r(e2),text:r(t2)};return i;function r(o){return l;function l(c){return h2(i,o,c)}}}function b2(e){for(;!Mf(e););return e}const Dm=/[\0\t\n\r]/g;function x2(){let e=1,n="",s=!0,i;return r;function r(o,l,c){const u=[];let d,m,h,f,p;for(o=n+(typeof o=="string"?o.toString():new TextDecoder(l||void 0).decode(o)),h=0,n="",s&&(o.charCodeAt(0)===65279&&h++,s=void 0);h<o.length;){if(Dm.lastIndex=h,d=Dm.exec(o),f=d&&d.index!==void 0?d.index:o.length,p=o.charCodeAt(f),!d){n=o.slice(h);break}if(p===10&&h===f&&i)u.push(-3),i=void 0;else switch(i&&(u.push(-5),i=void 0),h<f&&(u.push(o.slice(h,f)),e+=f-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=f+1}return c&&(i&&u.push(-5),n&&u.push(n),u.push(null)),u}}const v2=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function y2(e){return e.replace(v2,j2)}function j2(e,n,s){if(n)return n;if(s.charCodeAt(0)===35){const r=s.charCodeAt(1),o=r===120||r===88;return Sf(s.slice(o?2:1),o?16:10)}return Dd(s)||e}const $f={}.hasOwnProperty;function k2(e,n,s){return n&&typeof n=="object"&&(s=n,n=void 0),w2(s)(b2(g2(s).document().write(x2()(e,n,!0))))}function w2(e){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(Te),autolinkProtocol:z,autolinkEmail:z,atxHeading:o(me),blockQuote:o(O),characterEscape:z,characterReference:z,codeFenced:o(ne),codeFencedFenceInfo:l,codeFencedFenceMeta:l,codeIndented:o(ne,l),codeText:o(Q,l),codeTextData:z,data:z,codeFlowValue:z,definition:o(ge),definitionDestinationString:l,definitionLabelString:l,definitionTitleString:l,emphasis:o(de),hardBreakEscape:o(ie),hardBreakTrailing:o(ie),htmlFlow:o(Ee,l),htmlFlowData:z,htmlText:o(Ee,l),htmlTextData:z,image:o(Ue),label:l,link:o(Te),listItem:o(et),listItemValue:f,listOrdered:o(at,h),listUnordered:o(at),paragraph:o(Ve),reference:k,referenceString:l,resourceDestinationString:l,resourceTitleString:l,setextHeading:o(me),strong:o(Xe),thematicBreak:o(Be)},exit:{atxHeading:u(),atxHeadingSequence:C,autolink:u(),autolinkEmail:he,autolinkProtocol:W,blockQuote:u(),characterEscapeValue:_,characterReferenceMarkerHexadecimal:J,characterReferenceMarkerNumeric:J,characterReferenceValue:ue,characterReference:fe,codeFenced:u(v),codeFencedFence:b,codeFencedFenceInfo:p,codeFencedFenceMeta:g,codeFlowValue:_,codeIndented:u(x),codeText:u($),codeTextData:_,data:_,definition:u(),definitionDestinationString:E,definitionLabelString:y,definitionTitleString:w,emphasis:u(),hardBreakEscape:u(B),hardBreakTrailing:u(B),htmlFlow:u(K),htmlFlowData:_,htmlText:u(L),htmlTextData:_,image:u(G),label:ee,labelText:Y,lineEnding:R,link:u(U),listItem:u(),listOrdered:u(),listUnordered:u(),paragraph:u(),referenceString:H,resourceDestinationString:N,resourceTitleString:I,resource:T,setextHeading:u(S),setextHeadingLineSequence:A,setextHeadingText:j,strong:u(),thematicBreak:u()}};Df(n,(e||{}).mdastExtensions||[]);const s={};return i;function i(oe){let Ne={type:"root",children:[]};const se={stack:[Ne],tokenStack:[],config:n,enter:c,exit:d,buffer:l,resume:m,data:s},Me=[];let Le=-1;for(;++Le<oe.length;)if(oe[Le][1].type==="listOrdered"||oe[Le][1].type==="listUnordered")if(oe[Le][0]==="enter")Me.push(Le);else{const pe=Me.pop();Le=r(oe,pe,Le)}for(Le=-1;++Le<oe.length;){const pe=n[oe[Le][0]];$f.call(pe,oe[Le][1].type)&&pe[oe[Le][1].type].call(Object.assign({sliceSerialize:oe[Le][2].sliceSerialize},se),oe[Le][1])}if(se.tokenStack.length>0){const pe=se.tokenStack[se.tokenStack.length-1];(pe[1]||Lm).call(se,void 0,pe[0])}for(Ne.position={start:ki(oe.length>0?oe[0][1].start:{line:1,column:1,offset:0}),end:ki(oe.length>0?oe[oe.length-2][1].end:{line:1,column:1,offset:0})},Le=-1;++Le<n.transforms.length;)Ne=n.transforms[Le](Ne)||Ne;return Ne}function r(oe,Ne,se){let Me=Ne-1,Le=-1,pe=!1,Ae,Je,it,ye;for(;++Me<=se;){const ce=oe[Me];switch(ce[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{ce[0]==="enter"?Le++:Le--,ye=void 0;break}case"lineEndingBlank":{ce[0]==="enter"&&(Ae&&!ye&&!Le&&!it&&(it=Me),ye=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:ye=void 0}if(!Le&&ce[0]==="enter"&&ce[1].type==="listItemPrefix"||Le===-1&&ce[0]==="exit"&&(ce[1].type==="listUnordered"||ce[1].type==="listOrdered")){if(Ae){let Re=Me;for(Je=void 0;Re--;){const be=oe[Re];if(be[1].type==="lineEnding"||be[1].type==="lineEndingBlank"){if(be[0]==="exit")continue;Je&&(oe[Je][1].type="lineEndingBlank",pe=!0),be[1].type="lineEnding",Je=Re}else if(!(be[1].type==="linePrefix"||be[1].type==="blockQuotePrefix"||be[1].type==="blockQuotePrefixWhitespace"||be[1].type==="blockQuoteMarker"||be[1].type==="listItemIndent"))break}it&&(!Je||it<Je)&&(Ae._spread=!0),Ae.end=Object.assign({},Je?oe[Je][1].start:ce[1].end),oe.splice(Je||Me,0,["exit",Ae,ce[2]]),Me++,se++}if(ce[1].type==="listItemPrefix"){const Re={type:"listItem",_spread:!1,start:Object.assign({},ce[1].start),end:void 0};Ae=Re,oe.splice(Me,0,["enter",Re,ce[2]]),Me++,se++,it=void 0,ye=!0}}}return oe[Ne][1]._spread=pe,se}function o(oe,Ne){return se;function se(Me){c.call(this,oe(Me),Me),Ne&&Ne.call(this,Me)}}function l(){this.stack.push({type:"fragment",children:[]})}function c(oe,Ne,se){this.stack[this.stack.length-1].children.push(oe),this.stack.push(oe),this.tokenStack.push([Ne,se||void 0]),oe.position={start:ki(Ne.start),end:void 0}}function u(oe){return Ne;function Ne(se){oe&&oe.call(this,se),d.call(this,se)}}function d(oe,Ne){const se=this.stack.pop(),Me=this.tokenStack.pop();if(Me)Me[0].type!==oe.type&&(Ne?Ne.call(this,oe,Me[0]):(Me[1]||Lm).call(this,oe,Me[0]));else throw new Error("Cannot close `"+oe.type+"` ("+gr({start:oe.start,end:oe.end})+"): it’s not open");se.position.end=ki(oe.end)}function m(){return $d(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function f(oe){if(this.data.expectingFirstListItemValue){const Ne=this.stack[this.stack.length-2];Ne.start=Number.parseInt(this.sliceSerialize(oe),10),this.data.expectingFirstListItemValue=void 0}}function p(){const oe=this.resume(),Ne=this.stack[this.stack.length-1];Ne.lang=oe}function g(){const oe=this.resume(),Ne=this.stack[this.stack.length-1];Ne.meta=oe}function b(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function v(){const oe=this.resume(),Ne=this.stack[this.stack.length-1];Ne.value=oe.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function x(){const oe=this.resume(),Ne=this.stack[this.stack.length-1];Ne.value=oe.replace(/(\r?\n|\r)$/g,"")}function y(oe){const Ne=this.resume(),se=this.stack[this.stack.length-1];se.label=Ne,se.identifier=Vs(this.sliceSerialize(oe)).toLowerCase()}function w(){const oe=this.resume(),Ne=this.stack[this.stack.length-1];Ne.title=oe}function E(){const oe=this.resume(),Ne=this.stack[this.stack.length-1];Ne.url=oe}function C(oe){const Ne=this.stack[this.stack.length-1];if(!Ne.depth){const se=this.sliceSerialize(oe).length;Ne.depth=se}}function j(){this.data.setextHeadingSlurpLineEnding=!0}function A(oe){const Ne=this.stack[this.stack.length-1];Ne.depth=this.sliceSerialize(oe).codePointAt(0)===61?1:2}function S(){this.data.setextHeadingSlurpLineEnding=void 0}function z(oe){const se=this.stack[this.stack.length-1].children;let Me=se[se.length-1];(!Me||Me.type!=="text")&&(Me=De(),Me.position={start:ki(oe.start),end:void 0},se.push(Me)),this.stack.push(Me)}function _(oe){const Ne=this.stack.pop();Ne.value+=this.sliceSerialize(oe),Ne.position.end=ki(oe.end)}function R(oe){const Ne=this.stack[this.stack.length-1];if(this.data.atHardBreak){const se=Ne.children[Ne.children.length-1];se.position.end=ki(oe.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(Ne.type)&&(z.call(this,oe),_.call(this,oe))}function B(){this.data.atHardBreak=!0}function K(){const oe=this.resume(),Ne=this.stack[this.stack.length-1];Ne.value=oe}function L(){const oe=this.resume(),Ne=this.stack[this.stack.length-1];Ne.value=oe}function $(){const oe=this.resume(),Ne=this.stack[this.stack.length-1];Ne.value=oe}function U(){const oe=this.stack[this.stack.length-1];if(this.data.inReference){const Ne=this.data.referenceType||"shortcut";oe.type+="Reference",oe.referenceType=Ne,delete oe.url,delete oe.title}else delete oe.identifier,delete oe.label;this.data.referenceType=void 0}function G(){const oe=this.stack[this.stack.length-1];if(this.data.inReference){const Ne=this.data.referenceType||"shortcut";oe.type+="Reference",oe.referenceType=Ne,delete oe.url,delete oe.title}else delete oe.identifier,delete oe.label;this.data.referenceType=void 0}function Y(oe){const Ne=this.sliceSerialize(oe),se=this.stack[this.stack.length-2];se.label=y2(Ne),se.identifier=Vs(Ne).toLowerCase()}function ee(){const oe=this.stack[this.stack.length-1],Ne=this.resume(),se=this.stack[this.stack.length-1];if(this.data.inReference=!0,se.type==="link"){const Me=oe.children;se.children=Me}else se.alt=Ne}function N(){const oe=this.resume(),Ne=this.stack[this.stack.length-1];Ne.url=oe}function I(){const oe=this.resume(),Ne=this.stack[this.stack.length-1];Ne.title=oe}function T(){this.data.inReference=void 0}function k(){this.data.referenceType="collapsed"}function H(oe){const Ne=this.resume(),se=this.stack[this.stack.length-1];se.label=Ne,se.identifier=Vs(this.sliceSerialize(oe)).toLowerCase(),this.data.referenceType="full"}function J(oe){this.data.characterReferenceType=oe.type}function ue(oe){const Ne=this.sliceSerialize(oe),se=this.data.characterReferenceType;let Me;se?(Me=Sf(Ne,se==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Me=Dd(Ne);const Le=this.stack[this.stack.length-1];Le.value+=Me}function fe(oe){const Ne=this.stack.pop();Ne.position.end=ki(oe.end)}function W(oe){_.call(this,oe);const Ne=this.stack[this.stack.length-1];Ne.url=this.sliceSerialize(oe)}function he(oe){_.call(this,oe);const Ne=this.stack[this.stack.length-1];Ne.url="mailto:"+this.sliceSerialize(oe)}function O(){return{type:"blockquote",children:[]}}function ne(){return{type:"code",lang:null,meta:null,value:""}}function Q(){return{type:"inlineCode",value:""}}function ge(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function de(){return{type:"emphasis",children:[]}}function me(){return{type:"heading",depth:0,children:[]}}function ie(){return{type:"break"}}function Ee(){return{type:"html",value:""}}function Ue(){return{type:"image",title:null,url:"",alt:null}}function Te(){return{type:"link",title:null,url:"",children:[]}}function at(oe){return{type:"list",ordered:oe.type==="listOrdered",start:null,spread:oe._spread,children:[]}}function et(oe){return{type:"listItem",spread:oe._spread,checked:null,children:[]}}function Ve(){return{type:"paragraph",children:[]}}function Xe(){return{type:"strong",children:[]}}function De(){return{type:"text",value:""}}function Be(){return{type:"thematicBreak"}}}function ki(e){return{line:e.line,column:e.column,offset:e.offset}}function Df(e,n){let s=-1;for(;++s<n.length;){const i=n[s];Array.isArray(i)?Df(e,i):N2(e,i)}}function N2(e,n){let s;for(s in n)if($f.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 Lm(e,n){throw e?new Error("Cannot close `"+e.type+"` ("+gr({start:e.start,end:e.end})+"): a different token (`"+n.type+"`, "+gr({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+gr({start:n.start,end:n.end})+") is still open")}function S2(e){const n=this;n.parser=s;function s(i){return k2(i,{...n.data("settings"),...e,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function C2(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 E2(e,n){const s={type:"element",tagName:"br",properties:{},children:[]};return e.patch(n,s),[e.applyData(n,s),{type:"text",value:`
627
+ `}]}function _2(e,n){const s=n.value?n.value+`
628
+ `:"",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 M2(e,n){const s={type:"element",tagName:"del",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function A2(e,n){const s={type:"element",tagName:"em",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function R2(e,n){const s=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=String(n.identifier).toUpperCase(),r=Da(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 T2(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 P2(e,n){if(e.options.allowDangerousHtml){const s={type:"raw",value:n.value};return e.patch(n,s),e.applyData(n,s)}}function Lf(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 I2(e,n){const s=String(n.identifier).toUpperCase(),i=e.definitionById.get(s);if(!i)return Lf(e,n);const r={src:Da(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 $2(e,n){const s={src:Da(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 D2(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 L2(e,n){const s=String(n.identifier).toUpperCase(),i=e.definitionById.get(s);if(!i)return Lf(e,n);const r={href:Da(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 z2(e,n){const s={href:Da(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 F2(e,n,s){const i=e.all(n),r=s?O2(s):zf(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:`
629
+ `}),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:`
630
+ `});const d={type:"element",tagName:"li",properties:o,children:l};return e.patch(n,d),e.applyData(n,d)}function O2(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=zf(s[i])}return n}function zf(e){const n=e.spread;return n??e.children.length>1}function U2(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 B2(e,n){const s={type:"element",tagName:"p",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function H2(e,n){const s={type:"root",children:e.wrap(e.all(n))};return e.patch(n,s),e.applyData(n,s)}function q2(e,n){const s={type:"element",tagName:"strong",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function V2(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=Rd(n.children[1]),u=bf(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 W2(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],f={},p=l?l[u]:void 0;p&&(f.align=p);let g={type:"element",tagName:o,properties:f,children:[]};h&&(g.children=e.all(h),e.patch(h,g),g=e.applyData(h,g)),d.push(g)}const m={type:"element",tagName:"tr",properties:{},children:e.wrap(d,!0)};return e.patch(n,m),e.applyData(n,m)}function K2(e,n){const s={type:"element",tagName:"td",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}const zm=9,Fm=32;function G2(e){const n=String(e),s=/\r?\n|\r/g;let i=s.exec(n),r=0;const o=[];for(;i;)o.push(Om(n.slice(r,i.index),r>0,!0),i[0]),r=i.index+i[0].length,i=s.exec(n);return o.push(Om(n.slice(r),r>0,!1)),o.join("")}function Om(e,n,s){let i=0,r=e.length;if(n){let o=e.codePointAt(i);for(;o===zm||o===Fm;)i++,o=e.codePointAt(i)}if(s){let o=e.codePointAt(r-1);for(;o===zm||o===Fm;)r--,o=e.codePointAt(r-1)}return r>i?e.slice(i,r):""}function J2(e,n){const s={type:"text",value:G2(String(n.value))};return e.patch(n,s),e.applyData(n,s)}function Y2(e,n){const s={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(n,s),e.applyData(n,s)}const Q2={blockquote:C2,break:E2,code:_2,delete:M2,emphasis:A2,footnoteReference:R2,heading:T2,html:P2,imageReference:I2,image:$2,inlineCode:D2,linkReference:L2,link:z2,listItem:F2,list:U2,paragraph:B2,root:H2,strong:q2,table:V2,tableCell:K2,tableRow:W2,text:J2,thematicBreak:Y2,toml:lo,yaml:lo,definition:lo,footnoteDefinition:lo};function lo(){}const Ff=-1,ml=0,xr=1,Bo=2,zd=3,Fd=4,Od=5,Ud=6,Of=7,Uf=8,Um=typeof self=="object"?self:globalThis,X2=(e,n)=>{const s=(r,o)=>(e.set(o,r),r),i=r=>{if(e.has(r))return e.get(r);const[o,l]=n[r];switch(o){case ml:case Ff:return s(l,r);case xr:{const c=s([],r);for(const u of l)c.push(i(u));return c}case Bo:{const c=s({},r);for(const[u,d]of l)c[i(u)]=i(d);return c}case zd:return s(new Date(l),r);case Fd:{const{source:c,flags:u}=l;return s(new RegExp(c,u),r)}case Od:{const c=s(new Map,r);for(const[u,d]of l)c.set(i(u),i(d));return c}case Ud:{const c=s(new Set,r);for(const u of l)c.add(i(u));return c}case Of:{const{name:c,message:u}=l;return s(new Um[c](u),r)}case Uf: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 Um[o](l),r)};return i},Bm=e=>X2(new Map,e)(0),ca="",{toString:Z2}={},{keys:eE}=Object,Ya=e=>{const n=typeof e;if(n!=="object"||!e)return[ml,n];const s=Z2.call(e).slice(8,-1);switch(s){case"Array":return[xr,ca];case"Object":return[Bo,ca];case"Date":return[zd,ca];case"RegExp":return[Fd,ca];case"Map":return[Od,ca];case"Set":return[Ud,ca];case"DataView":return[xr,s]}return s.includes("Array")?[xr,s]:s.includes("Error")?[Of,s]:[Bo,s]},co=([e,n])=>e===ml&&(n==="function"||n==="symbol"),tE=(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]=Ya(l);switch(c){case ml:{let m=l;switch(u){case"bigint":c=Uf,m=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+u);m=null;break;case"undefined":return r([Ff],l)}return r([c,m],l)}case xr:{if(u){let f=l;return u==="DataView"?f=new Uint8Array(l.buffer):u==="ArrayBuffer"&&(f=new Uint8Array(l)),r([u,[...f]],l)}const m=[],h=r([c,m],l);for(const f of l)m.push(o(f));return h}case Bo:{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 f of eE(l))(e||!co(Ya(l[f])))&&m.push([o(f),o(l[f])]);return h}case zd:return r([c,l.toISOString()],l);case Fd:{const{source:m,flags:h}=l;return r([c,{source:m,flags:h}],l)}case Od:{const m=[],h=r([c,m],l);for(const[f,p]of l)(e||!(co(Ya(f))||co(Ya(p))))&&m.push([o(f),o(p)]);return h}case Ud:{const m=[],h=r([c,m],l);for(const f of l)(e||!co(Ya(f)))&&m.push(o(f));return h}}const{message:d}=l;return r([c,{name:u,message:d}],l)};return o},Hm=(e,{json:n,lossy:s}={})=>{const i=[];return tE(!(n||s),!!n,new Map,i)(e),i},Ho=typeof structuredClone=="function"?(e,n)=>n&&("json"in n||"lossy"in n)?Bm(Hm(e,n)):structuredClone(e):(e,n)=>Bm(Hm(e,n));function nE(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 sE(e,n){return"Back to reference "+(e+1)+(n>1?"-"+n:"")}function iE(e){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=e.options.footnoteBackContent||nE,i=e.options.footnoteBackLabel||sE,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(),f=Da(h.toLowerCase());let p=0;const g=[],b=e.footnoteCounts.get(h);for(;b!==void 0&&++p<=b;){g.length>0&&g.push({type:"text",value:" "});let y=typeof s=="string"?s:s(u,p);typeof y=="string"&&(y={type:"text",value:y}),g.push({type:"element",tagName:"a",properties:{href:"#"+n+"fnref-"+f+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof 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(...g)}else m.push(...g);const x={type:"element",tagName:"li",properties:{id:n+"fn-"+f},children:e.wrap(m,!0)};e.patch(d,x),c.push(x)}if(c.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...Ho(l),id:"footnote-label"},children:[{type:"text",value:r}]},{type:"text",value:`
631
+ `},{type:"element",tagName:"ol",properties:{},children:e.wrap(c,!0)},{type:"text",value:`
632
+ `}]}}const hl=(function(e){if(e==null)return lE;if(typeof e=="function")return pl(e);if(typeof e=="object")return Array.isArray(e)?aE(e):rE(e);if(typeof e=="string")return oE(e);throw new Error("Expected function, string, or object as test")});function aE(e){const n=[];let s=-1;for(;++s<e.length;)n[s]=hl(e[s]);return pl(i);function i(...r){let o=-1;for(;++o<n.length;)if(n[o].apply(this,r))return!0;return!1}}function rE(e){const n=e;return pl(s);function s(i){const r=i;let o;for(o in e)if(r[o]!==n[o])return!1;return!0}}function oE(e){return pl(n);function n(s){return s&&s.type===e}}function pl(e){return n;function n(s,i,r){return!!(cE(s)&&e.call(this,s,typeof i=="number"?i:void 0,r||void 0))}}function lE(){return!0}function cE(e){return e!==null&&typeof e=="object"&&"type"in e}const Bf=[],dE=!0,Xc=!1,uE="skip";function Hf(e,n,s,i){let r;typeof n=="function"&&typeof s!="function"?(i=s,s=n):r=n;const o=hl(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(f,"name",{value:"node ("+(u.type+(p?"<"+p+">":""))+")"})}return f;function f(){let p=Bf,g,b,v;if((!n||o(u,d,m[m.length-1]||void 0))&&(p=mE(s(u,m)),p[0]===Xc))return p;if("children"in u&&u.children){const x=u;if(x.children&&p[0]!==uE)for(b=(i?x.children.length:-1)+l,v=m.concat(x);b>-1&&b<x.children.length;){const y=x.children[b];if(g=c(y,b,v)(),g[0]===Xc)return g;b=typeof g[1]=="number"?g[1]:b+l}}return p}}}function mE(e){return Array.isArray(e)?e:typeof e=="number"?[dE,e]:e==null?Bf:[e]}function Bd(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),Hf(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 Zc={}.hasOwnProperty,hE={};function pE(e,n){const s=n||hE,i=new Map,r=new Map,o=new Map,l={...Q2,...s.handlers},c={all:d,applyData:gE,definitionById:i,footnoteById:r,footnoteCounts:o,footnoteOrder:[],handlers:l,one:u,options:s,patch:fE,wrap:xE};return Bd(e,function(m){if(m.type==="definition"||m.type==="footnoteDefinition"){const h=m.type==="definition"?i:r,f=String(m.identifier).toUpperCase();h.has(f)||h.set(f,m)}}),c;function u(m,h){const f=m.type,p=c.handlers[f];if(Zc.call(c.handlers,f)&&p)return p(c,m,h);if(c.options.passThrough&&c.options.passThrough.includes(f)){if("children"in m){const{children:b,...v}=m,x=Ho(v);return x.children=c.all(m),x}return Ho(m)}return(c.options.unknownHandler||bE)(c,m,h)}function d(m){const h=[];if("children"in m){const f=m.children;let p=-1;for(;++p<f.length;){const g=c.one(f[p],m);if(g){if(p&&f[p-1].type==="break"&&(!Array.isArray(g)&&g.type==="text"&&(g.value=qm(g.value)),!Array.isArray(g)&&g.type==="element")){const b=g.children[0];b&&b.type==="text"&&(b.value=qm(b.value))}Array.isArray(g)?h.push(...g):h.push(g)}}}return h}}function fE(e,n){e.position&&(n.position=s0(e))}function gE(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,Ho(o)),"children"in s&&s.children&&r!==null&&r!==void 0&&(s.children=r)}return s}function bE(e,n){const s=n.data||{},i="value"in n&&!(Zc.call(s,"hProperties")||Zc.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 xE(e,n){const s=[];let i=-1;for(n&&s.push({type:"text",value:`
633
+ `});++i<e.length;)i&&s.push({type:"text",value:`
634
+ `}),s.push(e[i]);return n&&e.length>0&&s.push({type:"text",value:`
635
+ `}),s}function qm(e){let n=0,s=e.charCodeAt(n);for(;s===9||s===32;)n++,s=e.charCodeAt(n);return e.slice(n)}function Vm(e,n){const s=pE(e,n),i=s.one(e,void 0),r=iE(s),o=Array.isArray(i)?{type:"root",children:i}:i||{type:"root",children:[]};return r&&o.children.push({type:"text",value:`
636
+ `},r),o}function vE(e,n){return e&&"run"in e?async function(s,i){const r=Vm(s,{file:i,...n});await e.run(r,i)}:function(s,i){return Vm(s,{file:i,...e||n})}}function Wm(e){if(e)throw e}var Wl,Km;function yE(){if(Km)return Wl;Km=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 f;for(f in d);return typeof f>"u"||e.call(d,f)},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 Wl=function u(){var d,m,h,f,p,g,b=arguments[0],v=1,x=arguments.length,y=!1;for(typeof b=="boolean"&&(y=b,b=arguments[1]||{},v=2),(b==null||typeof b!="object"&&typeof b!="function")&&(b={});v<x;++v)if(d=arguments[v],d!=null)for(m in d)h=c(b,m),f=c(d,m),b!==f&&(y&&f&&(o(f)||(p=r(f)))?(p?(p=!1,g=h&&r(h)?h:[]):g=h&&o(h)?h:{},l(b,{name:m,newValue:u(y,g,f)})):typeof f<"u"&&l(b,{name:m,newValue:f}));return b},Wl}var jE=yE();const Kl=lp(jE);function ed(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 kE(){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?wE(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 wE(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 ni={basename:NE,dirname:SE,extname:CE,join:EE,sep:"/"};function NE(e,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');Hr(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 SE(e){if(Hr(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 CE(e){Hr(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 EE(...e){let n=-1,s;for(;++n<e.length;)Hr(e[n]),e[n]&&(s=s===void 0?e[n]:s+"/"+e[n]);return s===void 0?".":_E(s)}function _E(e){Hr(e);const n=e.codePointAt(0)===47;let s=ME(e,!n);return s.length===0&&!n&&(s="."),s.length>0&&e.codePointAt(e.length-1)===47&&(s+="/"),n?"/"+s:s}function ME(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 Hr(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const AE={cwd:RE};function RE(){return"/"}function td(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function TE(e){if(typeof e=="string")e=new URL(e);else if(!td(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 PE(e)}function PE(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 Gl=["history","path","basename","stem","extname","dirname"];class qf{constructor(n){let s;n?td(n)?s={path:n}:typeof n=="string"||IE(n)?s={value:n}:s=n:s={},this.cwd="cwd"in s?"":AE.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let i=-1;for(;++i<Gl.length;){const o=Gl[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)Gl.includes(r)||(this[r]=s[r])}get basename(){return typeof this.path=="string"?ni.basename(this.path):void 0}set basename(n){Yl(n,"basename"),Jl(n,"basename"),this.path=ni.join(this.dirname||"",n)}get dirname(){return typeof this.path=="string"?ni.dirname(this.path):void 0}set dirname(n){Gm(this.basename,"dirname"),this.path=ni.join(n||"",this.basename)}get extname(){return typeof this.path=="string"?ni.extname(this.path):void 0}set extname(n){if(Jl(n,"extname"),Gm(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=ni.join(this.dirname,this.stem+(n||""))}get path(){return this.history[this.history.length-1]}set path(n){td(n)&&(n=TE(n)),Yl(n,"path"),this.path!==n&&this.history.push(n)}get stem(){return typeof this.path=="string"?ni.basename(this.path,this.extname):void 0}set stem(n){Yl(n,"stem"),Jl(n,"stem"),this.path=ni.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 us(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 Jl(e,n){if(e&&e.includes(ni.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+ni.sep+"`")}function Yl(e,n){if(!e)throw new Error("`"+n+"` cannot be empty")}function Gm(e,n){if(!e)throw new Error("Setting `"+n+"` requires `path` to be set too")}function IE(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const $E=(function(e){const i=this.constructor.prototype,r=i[e],o=function(){return r.apply(o,arguments)};return Object.setPrototypeOf(o,i),o}),DE={}.hasOwnProperty;class Hd extends $E{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=kE()}copy(){const n=new Hd;let s=-1;for(;++s<this.attachers.length;){const i=this.attachers[s];n.use(...i)}return n.data(Kl(!0,{},this.namespace)),n}data(n,s){return typeof n=="string"?arguments.length===2?(Zl("data",this.frozen),this.namespace[n]=s,this):DE.call(this.namespace,n)&&this.namespace[n]||void 0:n?(Zl("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=uo(n),i=this.parser||this.Parser;return Ql("parse",i),i(String(s),s)}process(n,s){const i=this;return this.freeze(),Ql("process",this.parser||this.Parser),Xl("process",this.compiler||this.Compiler),s?r(void 0,s):new Promise(r);function r(o,l){const c=uo(n),u=i.parse(c);i.run(u,c,function(m,h,f){if(m||!h||!f)return d(m);const p=h,g=i.stringify(p,f);FE(g)?f.value=g:f.result=g,d(m,f)});function d(m,h){m||!h?l(m):o?o(h):s(void 0,h)}}}processSync(n){let s=!1,i;return this.freeze(),Ql("processSync",this.parser||this.Parser),Xl("processSync",this.compiler||this.Compiler),this.process(n,r),Ym("processSync","process",s),i;function r(o,l){s=!0,Wm(o),i=l}}run(n,s,i){Jm(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=uo(s);r.run(n,u,d);function d(m,h,f){const p=h||n;m?c(m):l?l(p):i(void 0,p,f)}}}runSync(n,s){let i=!1,r;return this.run(n,s,o),Ym("runSync","run",i),r;function o(l,c){Wm(l),r=c,i=!0}}stringify(n,s){this.freeze();const i=uo(s),r=this.compiler||this.Compiler;return Xl("stringify",r),Jm(n),r(n,i)}use(n,...s){const i=this.attachers,r=this.namespace;if(Zl("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=Kl(!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,f=-1;for(;++h<i.length;)if(i[h][0]===d){f=h;break}if(f===-1)i.push([d,...m]);else if(m.length>0){let[p,...g]=m;const b=i[f][1];ed(b)&&ed(p)&&(p=Kl(!0,b,p)),i[f]=[d,p,...g]}}}}const LE=new Hd().freeze();function Ql(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Xl(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Zl(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 Jm(e){if(!ed(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Ym(e,n,s){if(!s)throw new Error("`"+e+"` finished async. Use `"+n+"` instead")}function uo(e){return zE(e)?e:new qf(e)}function zE(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function FE(e){return typeof e=="string"||OE(e)}function OE(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const UE="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Qm=[],Xm={allowDangerousHtml:!0},BE=/^(https?|ircs?|mailto|xmpp)$/i,HE=[{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 li(e){const n=qE(e),s=VE(e);return WE(n.runSync(n.parse(s),s),e)}function qE(e){const n=e.rehypePlugins||Qm,s=e.remarkPlugins||Qm,i=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Xm}:Xm;return LE().use(S2).use(s).use(vE,i).use(n)}function VE(e){const n=e.children||"",s=new qf;return typeof n=="string"&&(s.value=n),s}function WE(e,n){const s=n.allowedElements,i=n.allowElement,r=n.components,o=n.disallowedElements,l=n.skipHtml,c=n.unwrapDisallowed,u=n.urlTransform||KE;for(const m of HE)Object.hasOwn(n,m.from)&&(""+m.from+(m.to?"use `"+m.to+"` instead":"remove it")+UE+m.id,void 0);return Bd(e,d),l0(e,{Fragment:t.Fragment,components:r,ignoreInvalidStyle:!0,jsx:t.jsx,jsxs:t.jsxs,passKeys:!0,passNode:!0});function d(m,h,f){if(m.type==="raw"&&f&&typeof h=="number")return l?f.children.splice(h,1):f.children[h]={type:"text",value:m.value},h;if(m.type==="element"){let p;for(p in Hl)if(Object.hasOwn(Hl,p)&&Object.hasOwn(m.properties,p)){const g=m.properties[p],b=Hl[p];(b===null||b.includes(m.tagName))&&(m.properties[p]=u(String(g||""),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,f)),p&&f&&typeof h=="number")return c&&m.children?f.children.splice(h,1,...m.children):f.children.splice(h,1),h}}}function KE(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||BE.test(e.slice(0,n))?e:""}function Zm(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 GE(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function JE(e,n,s){const r=hl((s||{}).ignore||[]),o=YE(n);let l=-1;for(;++l<o.length;)Hf(e,"text",c);function c(d,m){let h=-1,f;for(;++h<m.length;){const p=m[h],g=f?f.children:void 0;if(r(p,g?g.indexOf(p):void 0,f))return;f=p}if(f)return u(d,m)}function u(d,m){const h=m[m.length-1],f=o[l][0],p=o[l][1];let g=0;const v=h.children.indexOf(d);let x=!1,y=[];f.lastIndex=0;let w=f.exec(d.value);for(;w;){const E=w.index,C={index:w.index,input:w.input,stack:[...m,d]};let j=p(...w,C);if(typeof j=="string"&&(j=j.length>0?{type:"text",value:j}:void 0),j===!1?f.lastIndex=E+1:(g!==E&&y.push({type:"text",value:d.value.slice(g,E)}),Array.isArray(j)?y.push(...j):j&&y.push(j),g=E+w[0].length,x=!0),!f.global)break;w=f.exec(d.value)}return x?(g<d.value.length&&y.push({type:"text",value:d.value.slice(g)}),h.children.splice(v,1,...y)):y=[d],v+y.length}}function YE(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([QE(r[0]),XE(r[1])])}return n}function QE(e){return typeof e=="string"?new RegExp(GE(e),"g"):e}function XE(e){return typeof e=="function"?e:function(){return e}}const ec="phrasing",tc=["autolink","link","image","label"];function ZE(){return{transforms:[r_],enter:{literalAutolink:t_,literalAutolinkEmail:nc,literalAutolinkHttp:nc,literalAutolinkWww:nc},exit:{literalAutolink:a_,literalAutolinkEmail:i_,literalAutolinkHttp:n_,literalAutolinkWww:s_}}}function e_(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:ec,notInConstruct:tc},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:ec,notInConstruct:tc},{character:":",before:"[ps]",after:"\\/",inConstruct:ec,notInConstruct:tc}]}}function t_(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function nc(e){this.config.enter.autolinkProtocol.call(this,e)}function n_(e){this.config.exit.autolinkProtocol.call(this,e)}function s_(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 i_(e){this.config.exit.autolinkEmail.call(this,e)}function a_(e){this.exit(e)}function r_(e){JE(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,o_],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,l_]],{ignore:["link","linkReference"]})}function o_(e,n,s,i,r){let o="";if(!Vf(r)||(/^w/i.test(n)&&(s=n+s,n="",o="http://"),!c_(s)))return!1;const l=d_(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 l_(e,n,s,i){return!Vf(i,!0)||/[-\d_]$/.test(s)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+s,children:[{type:"text",value:n+"@"+s}]}}function c_(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 d_(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=Zm(e,"(");let o=Zm(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 Vf(e,n){const s=e.input.charCodeAt(e.index-1);return(e.index===0||Ki(s)||dl(s))&&(!n||s!==47)}Wf.peek=v_;function u_(){this.buffer()}function m_(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function h_(){this.buffer()}function p_(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function f_(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=Vs(this.sliceSerialize(e)).toLowerCase(),s.label=n}function g_(e){this.exit(e)}function b_(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=Vs(this.sliceSerialize(e)).toLowerCase(),s.label=n}function x_(e){this.exit(e)}function v_(){return"["}function Wf(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 y_(){return{enter:{gfmFootnoteCallString:u_,gfmFootnoteCall:m_,gfmFootnoteDefinitionLabelString:h_,gfmFootnoteDefinition:p_},exit:{gfmFootnoteCallString:f_,gfmFootnoteCall:g_,gfmFootnoteDefinitionLabelString:b_,gfmFootnoteDefinition:x_}}}function j_(e){let n=!1;return e&&e.firstLineBlank&&(n=!0),{handlers:{footnoteDefinition:s,footnoteReference:Wf},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?`
637
+ `:" ")+o.indentLines(o.containerFlow(i,c.current()),n?Kf:k_))),d(),u}}function k_(e,n,s){return n===0?e:Kf(e,n,s)}function Kf(e,n,s){return(s?"":" ")+e}const w_=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Gf.peek=__;function N_(){return{canContainEols:["delete"],enter:{strikethrough:C_},exit:{strikethrough:E_}}}function S_(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:w_}],handlers:{delete:Gf}}}function C_(e){this.enter({type:"delete",children:[]},e)}function E_(e){this.exit(e)}function Gf(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 __(){return"~"}function M_(e){return e.length}function A_(e,n){const s=n||{},i=(s.align||[]).concat(),r=s.stringLength||M_,o=[],l=[],c=[],u=[];let d=0,m=-1;for(;++m<e.length;){const b=[],v=[];let x=-1;for(e[m].length>d&&(d=e[m].length);++x<e[m].length;){const y=R_(e[m][x]);if(s.alignDelimiters!==!1){const w=r(y);v[x]=w,(u[x]===void 0||w>u[x])&&(u[x]=w)}b.push(y)}l[m]=b,c[m]=v}let h=-1;if(typeof i=="object"&&"length"in i)for(;++h<d;)o[h]=eh(i[h]);else{const b=eh(i);for(;++h<d;)o[h]=b}h=-1;const f=[],p=[];for(;++h<d;){const b=o[h];let v="",x="";b===99?(v=":",x=":"):b===108?v=":":b===114&&(x=":");let y=s.alignDelimiters===!1?1:Math.max(1,u[h]-v.length-x.length);const w=v+"-".repeat(y)+x;s.alignDelimiters!==!1&&(y=v.length+y+x.length,y>u[h]&&(u[h]=y),p[h]=y),f[h]=w}l.splice(1,0,f),c.splice(1,0,p),m=-1;const g=[];for(;++m<l.length;){const b=l[m],v=c[m];h=-1;const x=[];for(;++h<d;){const y=b[h]||"";let w="",E="";if(s.alignDelimiters!==!1){const C=u[h]-(v[h]||0),j=o[h];j===114?w=" ".repeat(C):j===99?C%2?(w=" ".repeat(C/2+.5),E=" ".repeat(C/2-.5)):(w=" ".repeat(C/2),E=w):E=" ".repeat(C)}s.delimiterStart!==!1&&!h&&x.push("|"),s.padding!==!1&&!(s.alignDelimiters===!1&&y==="")&&(s.delimiterStart!==!1||h)&&x.push(" "),s.alignDelimiters!==!1&&x.push(w),x.push(y),s.alignDelimiters!==!1&&x.push(E),s.padding!==!1&&x.push(" "),(s.delimiterEnd!==!1||h!==d-1)&&x.push("|")}g.push(s.delimiterEnd===!1?x.join("").replace(/ +$/,""):x.join(""))}return g.join(`
638
+ `)}function R_(e){return e==null?"":String(e)}function eh(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 T_(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()),P_);return r(),l}function P_(e,n,s){return">"+(s?"":" ")+e}function I_(e,n){return th(e,n.inConstruct,!0)&&!th(e,n.notInConstruct,!1)}function th(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 nh(e,n,s,i){let r=-1;for(;++r<s.unsafe.length;)if(s.unsafe[r].character===`
639
+ `&&I_(s.stack,s.unsafe[r]))return/[ \t]/.test(i.before)?"":" ";return`\\
640
+ `}function $_(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 D_(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 L_(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 z_(e,n,s,i){const r=L_(s),o=e.value||"",l=r==="`"?"GraveAccent":"Tilde";if(D_(e,s)){const h=s.enter("codeIndented"),f=s.indentLines(o,F_);return h(),f}const c=s.createTracker(i),u=r.repeat(Math.max($_(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:`
641
+ `,encode:["`"],...c.current()})),h()}return m+=c.move(`
642
+ `),o&&(m+=c.move(o+`
643
+ `)),m+=c.move(u),d(),m}function F_(e,n,s){return(s?"":" ")+e}function qd(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 O_(e,n,s,i){const r=qd(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?" ":`
644
+ `,...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 U_(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 Mr(e){return"&#x"+e.toString(16).toUpperCase()+";"}function qo(e,n,s){const i=ja(e),r=ja(n);return i===void 0?r===void 0?s==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:r===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:i===1?r===void 0?{inside:!1,outside:!1}:r===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:r===void 0?{inside:!1,outside:!1}:r===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}Jf.peek=B_;function Jf(e,n,s,i){const r=U_(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=qo(i.before.charCodeAt(i.before.length-1),d,r);m.inside&&(u=Mr(d)+u.slice(1));const h=u.charCodeAt(u.length-1),f=qo(i.after.charCodeAt(0),h,r);f.inside&&(u=u.slice(0,-1)+Mr(h));const p=l.move(r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+u+p}function B_(e,n,s){return s.options.emphasis||"*"}function H_(e,n){let s=!1;return Bd(e,function(i){if("value"in i&&/\r?\n|\r/.test(i.value)||i.type==="break")return s=!0,Xc}),!!((!e.depth||e.depth<3)&&$d(e)&&(n.options.setext||s))}function q_(e,n,s,i){const r=Math.max(Math.min(6,e.depth||1),1),o=s.createTracker(i);if(H_(e,s)){const m=s.enter("headingSetext"),h=s.enter("phrasing"),f=s.containerPhrasing(e,{...o.current(),before:`
645
+ `,after:`
646
+ `});return h(),m(),f+`
647
+ `+(r===1?"=":"-").repeat(f.length-(Math.max(f.lastIndexOf("\r"),f.lastIndexOf(`
648
+ `))+1))}const l="#".repeat(r),c=s.enter("headingAtx"),u=s.enter("phrasing");o.move(l+" ");let d=s.containerPhrasing(e,{before:"# ",after:`
649
+ `,...o.current()});return/^[\t ]/.test(d)&&(d=Mr(d.charCodeAt(0))+d.slice(1)),d=d?l+" "+d:l,s.options.closeAtx&&(d+=" "+l),u(),c(),d}Yf.peek=V_;function Yf(e){return e.value||""}function V_(){return"<"}Qf.peek=W_;function Qf(e,n,s,i){const r=qd(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 W_(){return"!"}Xf.peek=K_;function Xf(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 K_(){return"!"}Zf.peek=G_;function Zf(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 G_(){return"`"}function eg(e,n){const s=$d(e);return!!(!n.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type==="text"&&(s===e.url||"mailto:"+s===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}tg.peek=J_;function tg(e,n,s,i){const r=qd(s),o=r==='"'?"Quote":"Apostrophe",l=s.createTracker(i);let c,u;if(eg(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 J_(e,n,s){return eg(e,s)?"<":"["}ng.peek=Y_;function ng(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 Y_(){return"["}function Vd(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 Q_(e){const n=Vd(e),s=e.options.bulletOther;if(!s)return n==="*"?"-":"*";if(s!=="*"&&s!=="+"&&s!=="-")throw new Error("Cannot serialize items with `"+s+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(s===n)throw new Error("Expected `bullet` (`"+n+"`) and `bulletOther` (`"+s+"`) to be different");return s}function X_(e){const n=e.options.bulletOrdered||".";if(n!=="."&&n!==")")throw new Error("Cannot serialize items with `"+n+"` for `options.bulletOrdered`, expected `.` or `)`");return n}function sg(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 Z_(e,n,s,i){const r=s.enter("list"),o=s.bulletCurrent;let l=e.ordered?X_(s):Vd(s);const c=e.ordered?l==="."?")":".":Q_(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),sg(s)===l&&m){let h=-1;for(;++h<e.children.length;){const f=e.children[h];if(f&&f.type==="listItem"&&f.children&&f.children[0]&&f.children[0].type==="thematicBreak"){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 eM(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 tM(e,n,s,i){const r=eM(s);let o=s.bulletCurrent||Vd(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,f,p){return f?(p?"":" ".repeat(l))+h:(p?o:o+" ".repeat(l-o.length))+h}}function nM(e,n,s,i){const r=s.enter("paragraph"),o=s.enter("phrasing"),l=s.containerPhrasing(e,i);return o(),r(),l}const sM=hl(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function iM(e,n,s,i){return(e.children.some(function(l){return sM(l)})?s.containerPhrasing:s.containerFlow).call(s,e,i)}function aM(e){const n=e.options.strong||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize strong with `"+n+"` for `options.strong`, expected `*`, or `_`");return n}ig.peek=rM;function ig(e,n,s,i){const r=aM(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=qo(i.before.charCodeAt(i.before.length-1),d,r);m.inside&&(u=Mr(d)+u.slice(1));const h=u.charCodeAt(u.length-1),f=qo(i.after.charCodeAt(0),h,r);f.inside&&(u=u.slice(0,-1)+Mr(h));const p=l.move(r+r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+u+p}function rM(e,n,s){return s.options.strong||"*"}function oM(e,n,s,i){return s.safe(e.value,i)}function lM(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 cM(e,n,s){const i=(sg(s)+(s.options.ruleSpaces?" ":"")).repeat(lM(s));return s.options.ruleSpaces?i.slice(0,-1):i}const ag={blockquote:T_,break:nh,code:z_,definition:O_,emphasis:Jf,hardBreak:nh,heading:q_,html:Yf,image:Qf,imageReference:Xf,inlineCode:Zf,link:tg,linkReference:ng,list:Z_,listItem:tM,paragraph:nM,root:iM,strong:ig,text:oM,thematicBreak:cM};function dM(){return{enter:{table:uM,tableData:sh,tableHeader:sh,tableRow:hM},exit:{codeText:pM,table:mM,tableData:sc,tableHeader:sc,tableRow:sc}}}function uM(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 mM(e){this.exit(e),this.data.inTable=void 0}function hM(e){this.enter({type:"tableRow",children:[]},e)}function sc(e){this.exit(e)}function sh(e){this.enter({type:"tableCell",children:[]},e)}function pM(e){let n=this.resume();this.data.inTable&&(n=n.replace(/\\([\\|])/g,fM));const s=this.stack[this.stack.length-1];s.type,s.value=n,this.exit(e)}function fM(e,n){return n==="|"?n:e}function gM(e){const n=e||{},s=n.tableCellPadding,i=n.tablePipeAlign,r=n.stringLength,o=s?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
650
+ `,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:f,table:l,tableCell:u,tableRow:c}};function l(p,g,b,v){return d(m(p,b,v),p.align)}function c(p,g,b,v){const x=h(p,b,v),y=d([x]);return y.slice(0,y.indexOf(`
651
+ `))}function u(p,g,b,v){const x=b.enter("tableCell"),y=b.enter("phrasing"),w=b.containerPhrasing(p,{...v,before:o,after:o});return y(),x(),w}function d(p,g){return A_(p,{align:g,alignDelimiters:i,padding:s,stringLength:r})}function m(p,g,b){const v=p.children;let x=-1;const y=[],w=g.enter("table");for(;++x<v.length;)y[x]=h(v[x],g,b);return w(),y}function h(p,g,b){const v=p.children;let x=-1;const y=[],w=g.enter("tableRow");for(;++x<v.length;)y[x]=u(v[x],p,g,b);return w(),y}function f(p,g,b){let v=ag.inlineCode(p,g,b);return b.stack.includes("tableCell")&&(v=v.replace(/\|/g,"\\$&")),v}}function bM(){return{exit:{taskListCheckValueChecked:ih,taskListCheckValueUnchecked:ih,paragraph:vM}}}function xM(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:yM}}}function ih(e){const n=this.stack[this.stack.length-2];n.type,n.checked=e.type==="taskListCheckValueChecked"}function vM(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 yM(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=ag.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 jM(){return[ZE(),y_(),N_(),dM(),bM()]}function kM(e){return{extensions:[e_(),j_(e),S_(),gM(e),xM()]}}const wM={tokenize:MM,partial:!0},rg={tokenize:AM,partial:!0},og={tokenize:RM,partial:!0},lg={tokenize:TM,partial:!0},NM={tokenize:PM,partial:!0},cg={name:"wwwAutolink",tokenize:EM,previous:ug},dg={name:"protocolAutolink",tokenize:_M,previous:mg},vi={name:"emailAutolink",tokenize:CM,previous:hg},ui={};function SM(){return{text:ui}}let Li=48;for(;Li<123;)ui[Li]=vi,Li++,Li===58?Li=65:Li===91&&(Li=97);ui[43]=vi;ui[45]=vi;ui[46]=vi;ui[95]=vi;ui[72]=[vi,dg];ui[104]=[vi,dg];ui[87]=[vi,cg];ui[119]=[vi,cg];function CM(e,n,s){const i=this;let r,o;return l;function l(h){return!nd(h)||!hg.call(i,i.previous)||Wd(i.events)?s(h):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(h))}function c(h){return nd(h)?(e.consume(h),c):h===64?(e.consume(h),u):s(h)}function u(h){return h===46?e.check(NM,m,d)(h):h===45||h===95||ls(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&&ps(i.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),n(h)):s(h)}}function EM(e,n,s){const i=this;return r;function r(l){return l!==87&&l!==119||!ug.call(i,i.previous)||Wd(i.events)?s(l):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(wM,e.attempt(rg,e.attempt(og,o),s),s)(l))}function o(l){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),n(l)}}function _M(e,n,s){const i=this;let r="",o=!1;return l;function l(h){return(h===72||h===104)&&mg.call(i,i.previous)&&!Wd(i.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),r+=String.fromCodePoint(h),e.consume(h),c):s(h)}function c(h){if(ps(h)&&r.length<5)return r+=String.fromCodePoint(h),e.consume(h),c;if(h===58){const f=r.toLowerCase();if(f==="http"||f==="https")return e.consume(h),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||Uo(h)||vn(h)||Ki(h)||dl(h)?s(h):e.attempt(rg,e.attempt(og,m),s)(h)}function m(h){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),n(h)}}function MM(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 AM(e,n,s){let i,r,o;return l;function l(d){return d===46||d===95?e.check(lg,u,c)(d):d===null||vn(d)||Ki(d)||d!==45&&dl(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 RM(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(lg,n,o)(l):l===null||vn(l)||Ki(l)?n(l):(e.consume(l),r)}function o(l){return l===41&&i++,e.consume(l),r}}function TM(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||vn(c)||Ki(c)?n(c):s(c)}function r(c){return c===null||c===40||c===91||vn(c)||Ki(c)?n(c):i(c)}function o(c){return ps(c)?l(c):s(c)}function l(c){return c===59?(e.consume(c),i):ps(c)?(e.consume(c),l):s(c)}}function PM(e,n,s){return i;function i(o){return e.consume(o),r}function r(o){return ls(o)?s(o):n(o)}}function ug(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||vn(e)}function mg(e){return!ps(e)}function hg(e){return!(e===47||nd(e))}function nd(e){return e===43||e===45||e===46||e===95||ls(e)}function Wd(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 IM={tokenize:BM,partial:!0};function $M(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:FM,continuation:{tokenize:OM},exit:UM}},text:{91:{name:"gfmFootnoteCall",tokenize:zM},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:DM,resolveTo:LM}}}}function DM(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=Vs(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 LM(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 zM(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||vn(h))return s(h);if(h===93){e.exit("chunkString");const f=e.exit("gfmFootnoteCallString");return r.includes(Vs(i.sliceSerialize(f)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),n):s(h)}return vn(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(g){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),d}function d(g){return g===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",m):s(g)}function m(g){if(l>999||g===93&&!c||g===null||g===91||vn(g))return s(g);if(g===93){e.exit("chunkString");const b=e.exit("gfmFootnoteDefinitionLabelString");return o=Vs(i.sliceSerialize(b)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),f}return vn(g)||(c=!0),l++,e.consume(g),g===92?h:m}function h(g){return g===91||g===92||g===93?(e.consume(g),l++,m):m(g)}function f(g){return g===58?(e.enter("definitionMarker"),e.consume(g),e.exit("definitionMarker"),r.includes(o)||r.push(o),tn(e,p,"gfmFootnoteDefinitionWhitespace")):s(g)}function p(g){return n(g)}}function OM(e,n,s){return e.check(Br,n,e.attempt(IM,n,s))}function UM(e){e.exit("gfmFootnoteDefinition")}function BM(e,n,s){const i=this;return tn(e,r,"gfmFootnoteDefinitionIndent",5);function r(o){const l=i.events[i.events.length-1];return l&&l[1].type==="gfmFootnoteDefinitionIndent"&&l[2].sliceSerialize(l[1],!0).length===4?n(o):s(o)}}function HM(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)},f=[["enter",m,c],["enter",l[d][1],c],["exit",l[d][1],c],["enter",h,c]],p=c.parser.constructs.insideSpan.null;p&&Ms(f,f.length,0,ul(p,l.slice(d+1,u),c)),Ms(f,f.length,0,[["exit",h,c],["enter",l[u][1],c],["exit",l[u][1],c],["exit",m,c]]),Ms(l,d-1,u-d+3,f),u=d+f.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 f;function f(g){return d===126&&m[m.length-1][1].type!=="characterEscape"?u(g):(l.enter("strikethroughSequenceTemporary"),p(g))}function p(g){const b=ja(d);if(g===126)return h>1?u(g):(l.consume(g),h++,p);if(h<2&&!s)return u(g);const v=l.exit("strikethroughSequenceTemporary"),x=ja(g);return v._open=!x||x===2&&!!b,v._close=!b||b===2&&!!x,c(g)}}}class qM{constructor(){this.map=[]}add(n,s,i){VM(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 VM(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 WM(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 KM(){return{flow:{null:{name:"table",tokenize:GM,resolveAll:JM}}}}function GM(e,n,s){const i=this;let r=0,o=0,l;return c;function c(_){let R=i.events.length-1;for(;R>-1;){const L=i.events[R][1].type;if(L==="lineEnding"||L==="linePrefix")R--;else break}const B=R>-1?i.events[R][1].type:null,K=B==="tableHead"||B==="tableRow"?j:u;return K===j&&i.parser.lazy[i.now().line]?s(_):K(_)}function u(_){return e.enter("tableHead"),e.enter("tableRow"),d(_)}function d(_){return _===124||(l=!0,o+=1),m(_)}function m(_){return _===null?s(_):Ct(_)?o>1?(o=0,i.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(_),e.exit("lineEnding"),p):s(_):Jt(_)?tn(e,m,"whitespace")(_):(o+=1,l&&(l=!1,r+=1),_===124?(e.enter("tableCellDivider"),e.consume(_),e.exit("tableCellDivider"),l=!0,m):(e.enter("data"),h(_)))}function h(_){return _===null||_===124||vn(_)?(e.exit("data"),m(_)):(e.consume(_),_===92?f:h)}function f(_){return _===92||_===124?(e.consume(_),h):h(_)}function p(_){return i.interrupt=!1,i.parser.lazy[i.now().line]?s(_):(e.enter("tableDelimiterRow"),l=!1,Jt(_)?tn(e,g,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(_):g(_))}function g(_){return _===45||_===58?v(_):_===124?(l=!0,e.enter("tableCellDivider"),e.consume(_),e.exit("tableCellDivider"),b):C(_)}function b(_){return Jt(_)?tn(e,v,"whitespace")(_):v(_)}function v(_){return _===58?(o+=1,l=!0,e.enter("tableDelimiterMarker"),e.consume(_),e.exit("tableDelimiterMarker"),x):_===45?(o+=1,x(_)):_===null||Ct(_)?E(_):C(_)}function x(_){return _===45?(e.enter("tableDelimiterFiller"),y(_)):C(_)}function y(_){return _===45?(e.consume(_),y):_===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(_),e.exit("tableDelimiterMarker"),w):(e.exit("tableDelimiterFiller"),w(_))}function w(_){return Jt(_)?tn(e,E,"whitespace")(_):E(_)}function E(_){return _===124?g(_):_===null||Ct(_)?!l||r!==o?C(_):(e.exit("tableDelimiterRow"),e.exit("tableHead"),n(_)):C(_)}function C(_){return s(_)}function j(_){return e.enter("tableRow"),A(_)}function A(_){return _===124?(e.enter("tableCellDivider"),e.consume(_),e.exit("tableCellDivider"),A):_===null||Ct(_)?(e.exit("tableRow"),n(_)):Jt(_)?tn(e,A,"whitespace")(_):(e.enter("data"),S(_))}function S(_){return _===null||_===124||vn(_)?(e.exit("data"),A(_)):(e.consume(_),_===92?z:S)}function z(_){return _===92||_===124?(e.consume(_),S):S(_)}}function JM(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 f=new qM;for(;++s<e.length;){const p=e[s],g=p[1];p[0]==="enter"?g.type==="tableHead"?(c=!1,u!==0&&(ah(f,n,u,d,m),m=void 0,u=0),d={type:"table",start:Object.assign({},g.start),end:Object.assign({},g.end)},f.add(s,0,[["enter",d,n]])):g.type==="tableRow"||g.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({},g.start),end:Object.assign({},g.end)},f.add(s,0,[["enter",m,n]])),r=g.type==="tableDelimiterRow"?2:m?3:1):r&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")?(i=!1,l[2]===0&&(o[1]!==0&&(l[0]=l[1],h=mo(f,n,o,r,void 0,h),o=[0,0,0,0]),l[2]=s)):g.type==="tableCellDivider"&&(i?i=!1:(o[1]!==0&&(l[0]=l[1],h=mo(f,n,o,r,void 0,h)),o=l,l=[o[1],s,0,0])):g.type==="tableHead"?(c=!0,u=s):g.type==="tableRow"||g.type==="tableDelimiterRow"?(u=s,o[1]!==0?(l[0]=l[1],h=mo(f,n,o,r,s,h)):l[1]!==0&&(h=mo(f,n,l,r,s,h)),r=0):r&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")&&(l[3]=s)}for(u!==0&&ah(f,n,u,d,m),f.consume(n.events),s=-1;++s<n.events.length;){const p=n.events[s];p[0]==="enter"&&p[1].type==="table"&&(p[1]._align=WM(n.events,s))}return e}function mo(e,n,s,i,r,o){const l=i===1?"tableHeader":i===2?"tableDelimiter":"tableData",c="tableContent";s[0]!==0&&(o.end=Object.assign({},ha(n.events,s[0])),e.add(s[0],0,[["exit",o,n]]));const u=ha(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=ha(n.events,s[2]),m=ha(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 f=n.events[s[2]],p=n.events[s[3]];if(f[1].end=Object.assign({},p[1].end),f[1].type="chunkText",f[1].contentType="text",s[3]>s[2]+1){const g=s[2]+1,b=s[3]-s[2]-1;e.add(g,b,[])}}e.add(s[3]+1,0,[["exit",h,n]])}return r!==void 0&&(o.end=Object.assign({},ha(n.events,r)),e.add(r,0,[["exit",o,n]]),o=void 0),o}function ah(e,n,s,i,r){const o=[],l=ha(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 ha(e,n){const s=e[n],i=s[0]==="enter"?"start":"end";return s[1][i]}const YM={name:"tasklistCheck",tokenize:XM};function QM(){return{text:{91:YM}}}function XM(e,n,s){const i=this;return r;function r(u){return i.previous!==null||!i._gfmTasklistFirstContentOfListItem?s(u):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(u),e.exit("taskListCheckMarker"),o)}function o(u){return vn(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 Ct(u)?n(u):Jt(u)?e.check({tokenize:ZM},n,s)(u):s(u)}}function ZM(e,n,s){return tn(e,i,"whitespace");function i(r){return r===null?s(r):n(r)}}function eA(e){return Nf([SM(),$M(),HM(e),KM(),QM()])}const tA={};function ci(e){const n=this,s=e||tA,i=n.data(),r=i.micromarkExtensions||(i.micromarkExtensions=[]),o=i.fromMarkdownExtensions||(i.fromMarkdownExtensions=[]),l=i.toMarkdownExtensions||(i.toMarkdownExtensions=[]);r.push(eA(s)),o.push(jM()),l.push(kM(s))}const rh=100;function pg(e,n,s){const[i,r]=a.useState([]),[o,l]=a.useState(!1),[c,u]=a.useState(!1),[d,m]=a.useState(null),[h,f]=a.useState(!1),p=a.useRef(null),g=a.useRef(!1),b=a.useRef(0),v=a.useRef(e),x=a.useRef(s),y=a.useRef(n),w=a.useRef(0);(v.current!==e||x.current!==s||y.current!==n)&&(v.current=e,x.current=s,y.current=n,b.current++,g.current=!0,r([]),l(!1),u(!1),m(null),f(!1),p.current&&(p.current(),p.current=null)),a.useEffect(()=>{if(!e||!n){p.current&&(p.current(),p.current=null);return}const A=b.current,S=++w.current;g.current=!1;const z=e,_=s;async function R(){if(!z)return;l(!0),f(!1);try{const K=await nu(z,_,{limit:rh});if(g.current||b.current!==A||w.current!==S)return;r(K.entries),u(K.hasMore),m(K.total)}catch{if(g.current||b.current!==A||w.current!==S)return;r([]),u(!1),m(null)}finally{!g.current&&b.current===A&&w.current===S&&l(!1)}const B=_?`?projectId=${encodeURIComponent(_)}`:"";p.current=Gs(`/api/tasks/${z}/logs/stream${B}`,{events:{"agent:log":K=>{if(!(g.current||b.current!==A))try{const L=JSON.parse(K.data);r($=>[...$,L]),m($=>$!==null?$+1:null)}catch{}}}})}return R(),()=>{g.current=!0,p.current&&(p.current(),p.current=null)}},[e,n,s]);const C=a.useCallback(async()=>{if(!e||h)return;const A=b.current,S=i.length,z=e;f(!0);try{const _=await nu(z,s,{limit:rh,offset:S});if(g.current||b.current!==A)return;r(R=>[..._.entries,...R]),u(_.hasMore),m(_.total)}catch{}finally{f(!1)}},[e,s,i.length,h]),j=a.useCallback(()=>r([]),[]);return{entries:i,loading:o,clear:j,loadMore:C,hasMore:c,total:d,loadingMore:h}}function nA(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 oh={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})},fg=50,sA={triage:"Plan"};function lh(e){return e.scrollHeight-(e.scrollTop+e.clientHeight)<=fg}function sd(e){return[e.taskId,e.timestamp,e.agent??"",e.type,e.text,e.detail??""].join("|")}function iA(e){const n=new Map;return e.map(s=>{const i=sd(s),r=n.get(i)??0;return n.set(i,r+1),`${i}|${r}`})}function aA(e){return e==="tool"||e==="tool_result"||e==="tool_error"}function ic(e){return e?t.jsx("pre",{className:"agent-log-tool-detail",children:e}):null}function rA(e,n){return e.agent?aA(e.type)?!0:!n||n.agent!==e.agent||n.type!==e.type:!1}function oA(e,n){const s=[];for(let i=0;i<e.length;i+=1){const r=e[i],o=n[i]??`${sd(r)}|fallback`,l=i>0?e[i-1]:void 0,c=rA(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]??`${sd(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 lA({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),f=a.useRef(null),p=a.useRef(null),[g,b]=a.useState(!0),[v,x]=a.useState(!1),[y,w]=a.useState(!1),[E,C]=a.useState(!0),j=a.useMemo(()=>iA(e),[e]),A=a.useMemo(()=>oA(e,j),[e,j]);a.useLayoutEffect(()=>{const $=d.current;if(!$)return;const U=e.length,G=m.current,Y=h.current||$.scrollHeight,ee=j[0]??null,N=j[j.length-1]??null,I=f.current!==ee,T=p.current!==N;if(U>G)if(G===0)$.scrollTop=$.scrollHeight;else{const k=Y-($.scrollTop+$.clientHeight)<=fg,H=T&&!I,J=I&&!T;if(H&&k&&($.scrollTop=$.scrollHeight),J){const ue=$.scrollHeight-Y;ue>0&&($.scrollTop+=ue)}}m.current=U,h.current=$.scrollHeight,f.current=ee,p.current=N,C(lh($))},[e,j]);const S=a.useCallback(()=>{const $=d.current;$&&C(lh($))},[]),z=a.useCallback(()=>{const $=d.current;$&&($.scrollTop=$.scrollHeight,C(!0))},[]),_=a.useCallback($=>{$.key==="Escape"&&v&&x(!1)},[v]);a.useEffect(()=>{if(v)return document.addEventListener("keydown",_),()=>{document.removeEventListener("keydown",_)}},[v,_]);const R=s?.provider&&s?.modelId,B=i?.provider&&i?.modelId,K=r?.provider&&r?.modelId,L=a.useMemo(()=>{const $=[];return R&&$.push({role:"Executor",provider:s.provider,modelId:s.modelId}),B&&$.push({role:"Reviewer",provider:i.provider,modelId:i.modelId}),K&&$.push({role:"Planning",provider:r.provider,modelId:r.modelId}),$},[R,s,B,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:[L.map($=>t.jsx(An,{provider:$.provider,size:"sm"},`${$.role}-${$.provider}-${$.modelId??"default"}`)),t.jsx("button",{className:"agent-log-model-expand-btn",onClick:()=>w($=>!$),"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(Xt,{size:14}):t.jsx(xn,{size:14})})]}),t.jsxs("div",{className:"agent-log-model-header-toggle",children:[t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>b($=>!$),"aria-label":g?"Switch to plain text mode":"Switch to markdown mode","aria-pressed":g,"data-testid":"agent-log-mode-toggle",title:g?"Show raw text":"Show formatted markdown",children:g?"Markdown":"Plain"}),t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>x($=>!$),"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(Dr,{size:14}):t.jsx(el,{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:"}),R?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(An,{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:"}),B?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(An,{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(An,{provider:r.provider,size:"sm"}),t.jsxs("span",{children:[r.provider,"/",r.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]})]})]}),t.jsxs("div",{ref:d,className:"agent-log-viewer-scroll",onScroll:S,children:[u!==null&&t.jsxs("div",{className:"agent-log-summary","data-testid":"agent-log-summary",children:["Showing ",e.length," of ",u," entries"]}),o&&l&&t.jsx("div",{className:"agent-log-load-more","data-testid":"agent-log-load-more",children:t.jsx("button",{className:"agent-log-mode-toggle",onClick:l,disabled:c,"data-testid":"agent-log-load-more-button",children:c?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:14,className:"animate-spin"}),"Loading…"]}):"Load More"})}),A.map($=>{const U=$.kind==="single"?$.entry:$.entries[0],G=$.showBadge?t.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:nA(U.timestamp)}):null,Y=$.showBadge?t.jsxs("span",{className:"agent-log-badge-row",children:[t.jsxs("span",{className:"agent-log-agent-badge",children:["[",sA[U.agent]??U.agent,"]"]}),G]}):null;if($.kind==="single"){const{entry:N}=$;if(N.type==="tool")return t.jsxs("div",{className:"agent-log-tool",children:[Y,t.jsxs("div",{className:"agent-log-tool-title",children:["⚡ ",N.text]}),ic(N.detail)]},$.key);if(N.type==="tool_result")return t.jsxs("div",{className:"agent-log-tool-result",children:[Y,t.jsxs("div",{className:"agent-log-tool-title",children:["✓ ",N.text]}),ic(N.detail)]},$.key);if(N.type==="tool_error")return t.jsxs("div",{className:"agent-log-tool-error",children:[Y,t.jsxs("div",{className:"agent-log-tool-title",children:["✗ ",N.text]}),ic(N.detail)]},$.key)}const ee=$.kind==="single"?U.text:$.entries.map(N=>N.text).join("");return $.kind==="thinking"?t.jsxs("div",{className:"agent-log-thinking",children:[Y,g?t.jsx("div",{className:"markdown-body",children:t.jsx(li,{remarkPlugins:[ci],components:oh,children:ee})}):t.jsx("pre",{className:"agent-log-plain-block",children:ee})]},$.key):t.jsxs("div",{className:"agent-log-text",children:[Y,g?t.jsx("div",{className:"markdown-body",children:t.jsx(li,{remarkPlugins:[ci],components:oh,children:ee})}):t.jsx("pre",{className:"agent-log-plain-block",children:ee})]},$.key)}),!E&&t.jsxs("button",{type:"button",className:"agent-log-return-to-live",onClick:z,"data-testid":"agent-log-return-to-live",children:[t.jsx(Xt,{size:12}),t.jsx("span",{children:"Live"})]})]})]})}function ka(e){return e??void 0}function ho(e){return{provider:ka(e.modelProvider),modelId:ka(e.modelId)}}function po(e){return{provider:ka(e.validatorModelProvider),modelId:ka(e.validatorModelId)}}function fo(e){return{provider:ka(e.planningModelProvider),modelId:ka(e.planningModelId)}}function cA(e,n){return Up(e,n)}function dA(e,n){return Bp(e,n)}function uA(e,n){return Hp(e,n)}function ac(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 rc(e){return e.provider&&e.modelId?`${e.provider}/${e.modelId}`:""}function oc(e,n){return e.provider===n.provider&&e.modelId===n.modelId}function mA(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 hA({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),[f,p]=a.useState(null),[g,b]=a.useState(()=>ho(e)),[v,x]=a.useState(()=>ho(e)),[y,w]=a.useState(()=>po(e)),[E,C]=a.useState(()=>po(e)),[j,A]=a.useState(()=>fo(e)),[S,z]=a.useState(()=>fo(e)),[_,R]=a.useState(()=>e.thinkingLevel??null),[B,K]=a.useState(()=>e.thinkingLevel??null),[L,$]=a.useState(null),U=a.useRef(e.id);a.useEffect(()=>{h(!0),p(null),bs().then(de=>{o(de.models),c(de.favoriteProviders),d(de.favoriteModels)}).catch(de=>{p(de.message||"Failed to load models")}).finally(()=>{h(!1)})},[]);const G=a.useCallback(async de=>{const me=l,Ee=me.includes(de)?me.filter(Ue=>Ue!==de):[de,...me];c(Ee);try{await pn({favoriteProviders:Ee,favoriteModels:u})}catch{c(me),n("Failed to update favorites","error")}},[l,u,n]),Y=a.useCallback(async de=>{const me=u,Ee=me.includes(de)?me.filter(Ue=>Ue!==de):[de,...me];d(Ee);try{await pn({favoriteProviders:l,favoriteModels:Ee})}catch{d(me),n("Failed to update model favorites","error")}},[u,l,n]);a.useEffect(()=>{U.current=e.id;const de=ho(e),me=po(e),ie=fo(e);b(de),x(de),w(me),C(me),A(ie),z(ie);const Ee=e.thinkingLevel??null;R(Ee),K(Ee),$(null)},[e.id,e.modelProvider,e.modelId,e.validatorModelProvider,e.validatorModelId,e.planningModelProvider,e.planningModelId,e.thinkingLevel]);const ee=a.useMemo(()=>rc(g),[g]),N=a.useMemo(()=>rc(y),[y]),I=a.useMemo(()=>rc(j),[j]),T=a.useMemo(()=>cA(e,i),[e,i]),k=a.useMemo(()=>dA(e,i),[e,i]),H=a.useMemo(()=>uA(e,i),[e,i]),J=L!==null,ue=a.useCallback(async(de,me)=>{const ie=e.id,Ee=v,Ue=E,Te=S;$(de);try{const at=s?de==="executor"?{modelProvider:me.provider??null,modelId:me.modelId??null}:de==="validator"?{validatorModelProvider:me.provider??null,validatorModelId:me.modelId??null}:{planningModelProvider:me.provider??null,planningModelId:me.modelId??null}:{modelProvider:(de==="executor"?me:v).provider??null,modelId:(de==="executor"?me:v).modelId??null,validatorModelProvider:(de==="validator"?me:E).provider??null,validatorModelId:(de==="validator"?me:E).modelId??null,planningModelProvider:(de==="planning"?me:S).provider??null,planningModelId:(de==="planning"?me:S).modelId??null},et=await ii(ie,at);if(U.current!==ie)return;const Ve=ho(et),Xe=po(et),De=fo(et);x(Ve),b(Ve),C(Xe),w(Xe),z(De),A(De),s?.(et),n(mA(de,{executor:Ve,validator:Xe,planning:De}[de]),"success")}catch(at){if(U.current!==ie)return;de==="executor"?b(Ee):de==="validator"?w(Ue):A(Te),n(we(at)||"Failed to save model settings","error")}finally{U.current===ie&&$(null)}},[e.id,v,E,S,n,s]),fe=a.useCallback(de=>{const me=ac(de);b(me),!oc(me,v)&&ue("executor",me)},[v,ue]),W=a.useCallback(de=>{const me=ac(de);w(me),!oc(me,E)&&ue("validator",me)},[E,ue]),he=a.useCallback(de=>{const me=ac(de);A(me),!oc(me,S)&&ue("planning",me)},[S,ue]),O=a.useCallback(async de=>{const me=e.id,ie=B,Ee=de===""?null:de;R(Ee),$("thinking");try{const Ue=await ii(me,{thinkingLevel:Ee});if(U.current!==me)return;const Te=Ue.thinkingLevel??null;K(Te),R(Te),s?.(Ue);const at=i?.defaultThinkingLevel??"off";n(Te===null?`Thinking level set to default (${at})`:`Thinking level set to ${Te}`,"success")}catch(Ue){if(U.current!==me)return;R(ie),n(we(Ue)||"Failed to save thinking level","error")}finally{U.current===me&&$(null)}},[e.id,B,i,n,s]),ne=!v.provider&&!v.modelId,Q=!E.provider&&!E.modelId,ge=!S.provider&&!S.modelId;return t.jsxs("div",{className:"model-selector-tab",children:[t.jsx("h4",{children:"Model Configuration"}),t.jsx("p",{className:"model-selector-intro",children:"Override the AI models used for this task. When not specified, project or global defaults are used."}),m?t.jsx("div",{className:"model-selector-loading",children:"Loading available models…"}):f?t.jsxs("div",{className:"model-selector-error",children:["Error loading models: ",f,t.jsx("button",{className:"btn btn-sm",onClick:()=>{h(!0),p(null),bs().then(de=>{o(de.models),c(de.favoriteProviders),d(de.favoriteModels)}).catch(de=>p(de.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",T.provider&&T.modelId?` (${T.provider}/${T.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[v.provider&&t.jsx(An,{provider:v.provider,size:"sm"}),v.provider,"/",v.modelId]})}),t.jsx(Zn,{id:"executorModel",label:"Executor Model",value:ee,onChange:fe,models:r,disabled:J,placeholder:"Select executor model…",favoriteProviders:l,onToggleFavorite:G,favoriteModels:u,onToggleModelFavorite:Y}),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:Q?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",k.provider&&k.modelId?` (${k.provider}/${k.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[E.provider&&t.jsx(An,{provider:E.provider,size:"sm"}),E.provider,"/",E.modelId]})}),t.jsx(Zn,{id:"validatorModel",label:"Reviewer Model",value:N,onChange:W,models:r,disabled:J,placeholder:"Select reviewer model…",favoriteProviders:l,onToggleFavorite:G,favoriteModels:u,onToggleModelFavorite:Y}),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:ge?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",H.provider&&H.modelId?` (${H.provider}/${H.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[S.provider&&t.jsx(An,{provider:S.provider,size:"sm"}),S.provider,"/",S.modelId]})}),t.jsx(Zn,{id:"planningModel",label:"Planning Model",value:I,onChange:he,models:r,disabled:J,placeholder:"Select planning model…",favoriteProviders:l,onToggleFavorite:G,favoriteModels:u,onToggleModelFavorite:Y}),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:B===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:B})}),t.jsxs("select",{id:"thinkingLevel",value:_??"",onChange:de=>O(de.target.value),disabled:J,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&&Q&&ge&&B===null?"Using project or global default models.":"Model settings are up to date."})]})]})}const pA={open:t.jsx(Yo,{size:16}),closed:t.jsx(Ir,{size:16}),merged:t.jsx(fp,{size:16})};function fA({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,f]=a.useState(""),[p,g]=a.useState(""),[b,v]=a.useState(!1),[x,y]=a.useState(!1),[w,E]=a.useState(null),C=a.useCallback(async()=>{if(h.trim()){v(!0);try{const z=await sj(e,{title:h.trim(),body:p.trim()||void 0},n);l(z),m(!1),f(""),g(""),u(`Created PR #${z.number}`,"success")}catch(z){u(we(z)||"Failed to create PR","error")}finally{v(!1)}}},[e,h,p,n,l,u]),j=a.useCallback(async()=>{if(s){y(!0);try{const z=await ij(e,n);E(z),c(z.prInfo),u("PR status refreshed","success")}catch(z){u(we(z)||"Failed to refresh PR","error")}finally{y(!1)}}},[e,s,n,c,u]);if(!s)return i==="creating-pr"?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Es,{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(Es,{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(Es,{size:16,className:"pr-section-icon"}),"Create Pull Request"]}),t.jsxs("div",{className:"pr-form",children:[t.jsx("input",{type:"text",placeholder:"PR title",value:h,onChange:z=>f(z.target.value),disabled:b,className:"pr-input"}),t.jsx("textarea",{placeholder:"PR description (optional)",value:p,onChange:z=>g(z.target.value),disabled:b,className:"pr-textarea",rows:3}),t.jsxs("div",{className:"pr-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>m(!1),disabled:b,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:C,disabled:!h.trim()||b,children:b?"Creating…":"Create PR"})]})]})]}):t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Es,{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(rn,{size:14,className:"pr-section-icon--sm"}),"Create PR"]}),!o&&t.jsxs("div",{className:"pr-hint pr-hint--subtle",children:["Run ",t.jsx("code",{children:"gh auth login"})," to enable PR creation."]})]});const A=pA[s.status]??t.jsx(Yo,{size:16}),S=w?.blockingReasons??[];return t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Es,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsxs("div",{className:`pr-card pr-card--status-${s.status}`,children:[t.jsxs("div",{className:"pr-header",children:[t.jsx("span",{className:"pr-status-icon",children:A}),t.jsx("span",{className:`pr-status-badge pr-status-badge--${s.status}`,children:s.status}),t.jsxs("span",{className:"pr-number",children:["#",s.number]}),t.jsx("div",{className:"pr-spacer"}),t.jsx("button",{className:"btn btn-sm pr-refresh-btn",onClick:j,disabled:x,title:"Refresh PR status",children:t.jsx(Ln,{size:14,style:{verticalAlign:"middle",opacity:x?.5:1}})})]}),t.jsx("div",{className:"pr-title",children:s.title}),t.jsxs("div",{className:"pr-meta",children:[t.jsx("span",{children:s.headBranch}),t.jsx("span",{className:"pr-meta-arrow",children:"→"}),t.jsx("span",{children:s.baseBranch})]}),i==="merging-pr"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:"fn is merging this pull request automatically."}),i==="awaiting-pr-checks"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:S.length>0?`Waiting for: ${S.join("; ")}`:"Waiting for required checks or review feedback before auto-merge."}),s.status==="merged"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:"This PR is merged. fn will finish local cleanup and move the task to Done."}),t.jsxs("div",{className:"pr-footer",children:[s.commentCount>0&&t.jsxs("span",{className:"pr-comments",children:[t.jsx(Si,{size:14}),s.commentCount]}),t.jsxs("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"pr-link",children:[t.jsx(Kb,{size:14}),"View on GitHub"]})]})]})]})}const ch=2e3;function gA(e){const n=e.updatedAt||e.createdAt,s=new Date(n).toLocaleString();return e.updatedAt?`${s} (edited)`:s}function bA(e){return e==="agent"||e==="system"}function xA({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,f]=a.useState(!1),[p,g]=a.useState(null),b=a.useMemo(()=>[...e.comments||[]].sort((A,S)=>new Date(S.createdAt).getTime()-new Date(A.createdAt).getTime()),[e.comments]),v=o.length>ch;async function x(){const A=o.trim();if(A){f(!0);try{const S=await _y(e.id,A,r);l(""),n?.(S),s("Comment added","success")}catch(S){s(we(S)||"Failed to add comment","error")}finally{f(!1)}}}async function y(A){const S=d.trim();if(S){f(!0);try{const z=await wy(e.id,A,S,r);u(null),m(""),n?.(z),s("Comment updated","success")}catch(z){s(we(z)||"Failed to update comment","error")}finally{f(!1)}}}async function w(A){g(A);try{const S=await Ny(e.id,A,r);n?.(S),s("Comment deleted","success")}catch(S){s(we(S)||"Failed to delete comment","error")}finally{g(null)}}function E(A){A.key==="Enter"&&(A.ctrlKey||A.metaKey)&&(A.preventDefault(),x())}return t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Comments"}),b.length===0?t.jsx("div",{className:"detail-log-empty",children:"No comments yet."}):t.jsx("div",{className:"detail-activity-list",children:b.map(A=>{const S=A.author===i,z=c===A.id,_=bA(A.author);return t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header comments-header-row",children:[t.jsxs("div",{className:"comments-author-row",children:[_?t.jsx("span",{className:"ai-guidance-badge","data-testid":"ai-guidance-badge",children:"AI Guidance"}):t.jsx("strong",{children:A.author}),t.jsx("span",{className:"detail-log-timestamp",children:gA(A)})]}),S&&!z?t.jsxs("div",{className:"comments-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{u(A.id),m(A.text)},children:"Edit"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void w(A.id),disabled:p===A.id,children:p===A.id?"Deleting…":"Delete"})]}):null]}),z?t.jsxs("div",{className:"comments-edit-form",children:[t.jsx("textarea",{value:d,onChange:R=>m(R.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(A.id),disabled:h||!d.trim(),children:"Save"})]})]}):t.jsx("div",{className:"detail-log-outcome comments-outcome-text",children:A.text})]},A.id)})}),t.jsxs("div",{className:"comments-compose-form",children:[t.jsx("textarea",{value:o,onChange:A=>l(A.target.value),onKeyDown:E,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," / ",ch]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void x(),disabled:h||!o.trim()||v,children:h?"Posting…":"Add Comment"})]})]})]})}function vA(e){return e?e.slice(0,7):"Unknown"}function yA({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:vA(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 gg(e){return e.split(`
652
+ `).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}
653
+ `},i):t.jsx(Ao.Fragment,{children:`${s}
654
+ `},i)})}function jA(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function kA({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),f=a.useRef(null);di(f,e,"fusion:changes-diff-modal-size");const p=Mi(l);a.useEffect(()=>{s.length>0&&u===null&&d(0)},[s,u]);const g=a.useCallback(()=>{d(y=>y!==null&&y>0?y-1:y)},[]),b=a.useCallback(()=>{d(y=>y!==null&&y<s.length-1?y+1:y)},[]);if(a.useEffect(()=>{if(!e)return;const y=w=>{if(w.key==="Escape"){l();return}w.key==="ArrowUp"&&(w.metaKey||w.ctrlKey)&&(w.preventDefault(),g()),w.key==="ArrowDown"&&(w.metaKey||w.ctrlKey)&&(w.preventDefault(),b())};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[e,l,g,b]),!e)return null;const v=u!==null?s[u]:null,x=o==="done";return t.jsx("div",{className:"modal-overlay open",...p,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal changes-diff-modal",ref:f,children:[t.jsxs("div",{className:"modal-header changes-diff-modal-header",children:[t.jsxs("div",{className:"changes-diff-header-title",children:[t.jsx(Hs,{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:g,disabled:u===null||u<=0,title:"Previous file (Ctrl+↑)","aria-label":"Previous file",children:t.jsx(Jo,{})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:u!==null?`${u+1}/${s.length}`:`—/${s.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:b,disabled:u===null||u>=s.length-1,title:"Next file (Ctrl+↓)","aria-label":"Next file",children:t.jsx(xn,{})})]}),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(Po,{size:14})}),c&&t.jsxs("button",{className:"btn btn-sm",onClick:c,children:[t.jsx(Ln,{size:14}),"Refresh"]}),t.jsx("button",{className:"modal-close",onClick:l,"aria-label":"Close",children:t.jsx(Ht,{size:20})})]})]}),t.jsxs("div",{className:"changes-diff-body",children:[t.jsxs("div",{className:"changes-diff-sidebar",children:[x&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx($r,{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,w)=>t.jsxs("button",{className:`changes-diff-file-item ${u===w?"selected":""}`,onClick:()=>d(w),title:y.path,children:[t.jsx("span",{className:`changes-file-status changes-file-status--${y.status}`,children:jA(y.status)}),t.jsx("span",{className:"changes-diff-file-path",title:y.path,children:t.jsx("bdo",{dir:"ltr",children:y.path})}),t.jsxs("span",{className:"changes-diff-file-stat",children:["+",y.additions," -",y.deletions]})]},y.path))})]}),t.jsx("div",{className:"changes-diff-content",children:v?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"changes-diff-file-header-bar",children:[t.jsx("span",{className:"changes-diff-file-header-name",children:v.path}),t.jsxs("span",{className:"changes-diff-file-header-stats",children:["+",v.additions," -",v.deletions]})]}),v.patch?t.jsx("div",{className:"changes-diff-viewer",children:t.jsx("pre",{className:`changes-diff-patch ${m?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:t.jsx("code",{children:gg(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(Hs,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to view its diff"})]})})]})]})})}function bg(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function lc(e,n,s){return t.jsxs("div",{className:"detail-section task-changes-tab",children:[n&&s&&t.jsxs("div",{className:"commit-diff-meta",children:[s.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx($r,{size:14}),t.jsx("code",{children:s.commitSha.slice(0,7)})]}),s.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(s.mergedAt).toLocaleString()]})]}),t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Hs,{size:24}),t.jsxs("p",{children:[e.length," file",e.length===1?"":"s"," modified during execution."]}),t.jsx("span",{className:"task-changes-state-hint",children:n?"The recorded merge commit has no diff (likely collapsed into a squash on main). Showing file paths only — patches unavailable.":"The live worktree diff is empty. Showing the last file paths captured during execution — patches unavailable."})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:e.map(i=>t.jsx("div",{className:"changes-file-item",children:t.jsxs("div",{className:"changes-file-header changes-file-header--static",children:[t.jsx("span",{className:"changes-file-status changes-file-status--unknown",title:"status unknown",children:bg("unknown")}),t.jsx("span",{className:"changes-file-path",title:i,children:t.jsx("bdo",{dir:"ltr",children:i})})]})},i))})]})}function wA({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),[f,p]=a.useState(null),[g,b]=a.useState(new Set),[v,x]=a.useState(null),[y,w]=a.useState(!0),[E,C]=a.useState(!1),j=i==="done",A=j&&!!r?.commitSha,S=i==="in-progress"||i==="in-review"||A,z=a.useCallback(async()=>{if(!S){h(!1);return}try{h(!0),p(null);const L=await Pp(e,void 0,s),$=L.files.map(U=>({path:U.path,status:U.status,additions:U.additions,deletions:U.deletions,patch:U.patch}));c($),d(L.stats),$.length>0&&(b(new Set([$[0].path])),x(0))}catch(L){p(we(L)||"Failed to load diff")}finally{h(!1)}},[e,s,S]);a.useEffect(()=>{z()},[z]);const _=L=>{b($=>{const U=new Set($);if(U.has(L))U.delete(L);else{U.add(L);const G=l.findIndex(Y=>Y.path===L);G!==-1&&x(G)}return U})},R=L=>{if(L<0||L>=l.length)return;const $=l[L].path;b(new Set([$])),x(L)},B=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(f)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--error",children:[t.jsx(gs,{size:16}),t.jsxs("span",{children:["Error loading changes: ",f]})]})});if(!j&&!n)return o&&o.length>0?lc(o,!1):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Hs,{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(j&&!A){if(o&&o.length>0)return lc(o,!0,r);const L=r?.filesChanged,$=r?.insertions,U=r?.deletions,G=L!=null||$!=null||U!=null;return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Hs,{size:24}),t.jsx("p",{children:"Detailed file changes unavailable."}),t.jsx("span",{className:"task-changes-state-hint",children:G?`Merge summary: ${L??0} file${(L??0)===1?"":"s"} changed, +${$??0} additions, -${U??0} deletions.`:"No merge commit was recorded for this task."})]})})}return l.length===0?o&&o.length>0?lc(o,j,r):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Hs,{size:24}),t.jsx("p",{children:"No files modified."}),t.jsx("span",{className:"task-changes-state-hint",children:j?"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:[j&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx($r,{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(Hs,{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:()=>B&&R(v-1),disabled:!B,title:"Previous file","aria-label":"Previous file",children:t.jsx(Jo,{})}),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&&R(v+1),disabled:!K,title:"Next file","aria-label":"Next file",children:t.jsx(xn,{})})]}),t.jsx("button",{className:`btn btn-sm ${y?"btn-primary":""}`,onClick:()=>w(L=>!L),title:y?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(Po,{size:14})})]}),t.jsxs("div",{className:"changes-header-actions-secondary",children:[t.jsx("button",{className:"btn btn-sm",onClick:z,disabled:m,children:"Refresh"}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>C(!0),title:"Expand to full-screen diff view","aria-label":"Expand diff view",children:t.jsx(el,{})})]})]})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:l.map(L=>{const $=g.has(L.path);return t.jsxs("div",{className:`changes-file-item ${$?"expanded":""}`,children:[t.jsxs("button",{className:"changes-file-header",onClick:()=>_(L.path),children:[t.jsx("span",{className:"changes-file-toggle",children:$?t.jsx(Xt,{size:14}):t.jsx(xn,{size:14})}),t.jsx("span",{className:`changes-file-status changes-file-status--${L.status}`,title:L.status,children:bg(L.status)}),t.jsx("span",{className:"changes-file-path",title:L.path,children:t.jsx("bdo",{dir:"ltr",children:L.path})}),t.jsxs("span",{className:"changes-file-stat",title:`+${L.additions} -${L.deletions}`,children:["+",L.additions," -",L.deletions]})]}),$&&L.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:gg(L.patch)})})})]},L.path)})}),t.jsx(kA,{isOpen:E,taskId:e,files:l,stats:u,mergeDetails:r,column:i,onClose:()=>C(!1),onRefresh:z})]})}function dh(e){return{executorValue:e?.executorProvider&&e?.executorModelId?`${e.executorProvider}/${e.executorModelId}`:"",validatorValue:e?.validatorProvider&&e?.validatorModelId?`${e.validatorProvider}/${e.validatorModelId}`:""}}function NA(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function b3(e,n){const s=NA(e),i=new Set(n.map(c=>c.id));if(!i.has(s))return s;const r=30;let o=s,l=1;for(;i.has(o)&&l<100;){const c=`-${l}`;o=`${s.slice(0,r-c.length)}${c}`,l++}return o}function SA(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}const uh=["image/png","image/jpeg","image/gif","image/webp"];function CA(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 xg({mode:e,description:n,onDescriptionChange:s,title:i,onTitleChange:r,dependencies:o,onDependenciesChange:l,nodeId:c,onNodeIdChange:u,nodeOptions:d,nodeOverrideDisabled:m=!1,nodeOverrideDisabledReason:h,priority:f,onPriorityChange:p,executorModel:g,onExecutorModelChange:b,validatorModel:v,onValidatorModelChange:x,planningModel:y,onPlanningModelChange:w,thinkingLevel:E,onThinkingLevelChange:C,presetMode:j,onPresetModeChange:A,selectedPresetId:S,onSelectedPresetIdChange:z,selectedWorkflowSteps:_,onWorkflowStepsChange:R,onDefaultOnApplied:B,pendingImages:K,onImagesChange:L,tasks:$,projectId:U,disabled:G=!1,addToast:Y,isActive:ee=!0,onAutoSaveDescription:N,onPlanningMode:I,onSubtaskBreakdown:T,onClose:k,renderBelowPrimary:H,renderBelowModelConfiguration:J,hideDependencies:ue,autoExpandMoreOptionsOnSelection:fe=!0,reviewLevel:W,onReviewLevelChange:he,executionMode:O,onExecutionModeChange:ne}){const Q=(ue?!1:o.length>0)||K.length>0||_.length>0||j!=="default"||(f??_s)!==_s||g!==""||v!==""||(y||"")!==""||(E||"")!==""||W!==void 0||O==="fast"||(c||"")!=="",[ge,de]=a.useState(!1),[me,ie]=a.useState(fe?Q:!1),[Ee,Ue]=a.useState(""),[Te,at]=a.useState([]),[et,Ve]=a.useState([]),[Xe,De]=a.useState([]),[Be,oe]=a.useState(!1),[Ne,se]=a.useState(null),[Me,Le]=a.useState([]),[pe,Ae]=a.useState("idle"),[Je,it]=a.useState(!1),[ye,ce]=a.useState(!1),[Re,be]=a.useState(!1),Pe=a.useRef(null),Ye=a.useRef(null),$e=a.useRef(null),ft=a.useRef(null),Z=a.useRef(null),re=a.useRef(null),je=a.useRef(null),rt=a.useRef(!1),te=a.useRef(Q),Ze=a.useRef(n.trim()),pt=a.useRef(n.trim());a.useEffect(()=>{ee&&(oe(!0),bs().then(D=>{at(D.models),Ve(D.favoriteProviders),De(D.favoriteModels)}).catch(()=>{}).finally(()=>oe(!1)),nl(U).then(D=>se(D)).catch(()=>se(null)),sl(U).then(D=>Le(D.filter(F=>F.enabled))).catch(()=>Le([])))},[ee,U]);const gt=Ne?.modelPresets||[],wt=gt.find(D=>D.id===S),Et=(ue?!1:o.length>0)||K.length>0||_.length>0||j!=="default"||(f??_s)!==_s||g!==""||v!==""||(y||"")!==""||(E||"")!==""||W!==void 0||O==="fast"||(c||"")!=="";a.useEffect(()=>{if(e!=="create"||!ee||!Ne?.autoSelectModelPreset)return;const D=(Ne.defaultPresetBySize,void 0);if(D){const F=dh(D);z(D.id),A("preset"),b(F.executorValue),x(F.validatorValue)}},[ee,Ne,gt,e]);const mt=a.useRef(!1);a.useEffect(()=>{if(e!=="create"||!ee||mt.current||Me.length===0)return;const D=Me.filter(ve=>ve.defaultOn);if(D.length===0)return;mt.current=!0;const F=D.map(ve=>ve.id);R(F),B?.(F)},[e,ee,Me]),a.useEffect(()=>{ee||(mt.current=!1)},[ee]),a.useEffect(()=>{if(!fe){te.current=Et;return}Et&&!te.current&&ie(!0),te.current=Et},[Et,fe]),a.useEffect(()=>{me||(de(!1),Ue(""))},[me]),a.useEffect(()=>{e!=="edit"||!ee||ft.current&&(ft.current.focus(),ft.current.select())},[e,ee]),a.useEffect(()=>{if(!ge)return;const D=F=>{Ye.current&&!Ye.current.contains(F.target)&&de(!1)};return document.addEventListener("mousedown",D),()=>document.removeEventListener("mousedown",D)},[ge]),a.useEffect(()=>{(e!=="edit"||G)&&be(!1)},[e,G]),a.useEffect(()=>{if(e!=="edit"){Ae("idle");return}const D=n.trim();Ze.current=D,pt.current=D,Ae("idle")},[e]),a.useEffect(()=>{if(e!=="edit"||!N||!ee)return;const D=n.trim(),F=Ze.current;if(D===F||D===pt.current){re.current&&(clearTimeout(re.current),re.current=null),rt.current||Ae("idle");return}return re.current&&clearTimeout(re.current),re.current=setTimeout(async()=>{if(!rt.current){rt.current=!0,Ae("saving");try{await N(D),pt.current=D,Ae("saved"),je.current&&clearTimeout(je.current),je.current=setTimeout(()=>{Ae("idle"),je.current=null},2e3)}catch{Ae("idle")}finally{rt.current=!1,re.current=null}}},1500),()=>{re.current&&(clearTimeout(re.current),re.current=null)}},[e,n,N,ee]),a.useEffect(()=>()=>{re.current&&clearTimeout(re.current),je.current&&clearTimeout(je.current)},[]),a.useEffect(()=>{if(!Je)return;const D=F=>{Pe.current&&!Pe.current.contains(F.target)&&it(!1)};return document.addEventListener("mousedown",D),()=>document.removeEventListener("mousedown",D)},[Je]);const Nt=a.useCallback(D=>{const F=D.clipboardData?.items;if(F)for(let ve=0;ve<F.length;ve++){const ze=F[ve];if(ze.type.startsWith("image/")){const Oe=ze.getAsFile();if(Oe&&uh.includes(Oe.type)){D.preventDefault(),L([...K,{file:Oe,previewUrl:URL.createObjectURL(Oe)}]);return}}}},[K,L]),Tt=a.useCallback(D=>{D.preventDefault();const F=D.dataTransfer.files;for(let ve=0;ve<F.length;ve++){const ze=F[ve];if(uh.includes(ze.type)){L([...K,{file:ze,previewUrl:URL.createObjectURL(ze)}]);return}}},[K,L]),qt=a.useCallback(D=>{const F=K[D];F&&URL.revokeObjectURL(F.previewUrl),L(K.filter((ve,ze)=>ze!==D))},[K,L]),Pt=a.useCallback(D=>{l(o.includes(D)?o.filter(F=>F!==D):[...o,D])},[o,l]),At=(D,F)=>D.length>F?D.slice(0,F)+"…":D,Bt=a.useCallback(D=>{s(D.target.value);const F=D.target;F.style.height="auto",F.style.height=F.scrollHeight+"px"},[s]),Ft=a.useCallback(()=>{be(D=>!D)},[]),Dt=a.useCallback(D=>{!Re||D.key!=="Escape"||(D.preventDefault(),D.stopPropagation(),be(!1))},[Re]),Mt=a.useCallback(async D=>{const F=n.trim();if(!(!F||ye)){ce(!0);try{const ve=await Mp(F,D,U);s(ve),it(!1),Y("Description refined with AI","success"),$e.current&&($e.current.style.height="auto",$e.current.style.height=$e.current.scrollHeight+"px")}catch(ve){const ze=Ap(ve);Y(ze,"error")}finally{ce(!1)}}},[n,ye,Y,s,U]),St=a.useCallback(async D=>{const F=et,ze=F.includes(D)?F.filter(Oe=>Oe!==D):[D,...F];Ve(ze);try{await pn({favoriteProviders:ze,favoriteModels:Xe})}catch{Ve(F)}},[et,Xe]),Wt=a.useCallback(async D=>{const F=Xe,ze=F.includes(D)?F.filter(Oe=>Oe!==D):[D,...F];De(ze);try{await pn({favoriteProviders:et,favoriteModels:ze})}catch{De(F)}},[Xe,et]),It=a.useCallback(D=>{if(D<=0)return;const F=[..._];[F[D-1],F[D]]=[F[D],F[D-1]],R(F)},[_,R]),Yt=a.useCallback(D=>{if(D>=_.length-1)return;const F=[..._];[F[D],F[D+1]]=[F[D+1],F[D]],R(F)},[_,R]),Rt=a.useCallback(D=>{R(_.filter(F=>F!==D))},[_,R]),xe=new Map;for(const D of Me)xe.set(D.id,{name:D.name,description:D.description});const Fe=$.filter(D=>!o.includes(D.id)).sort((D,F)=>{const ve=F.createdAt.localeCompare(D.createdAt);if(ve!==0)return ve;const ze=parseInt(D.id.slice(D.id.lastIndexOf("-")+1),10)||0;return(parseInt(F.id.slice(F.id.lastIndexOf("-")+1),10)||0)-ze}),ct=Ee?Fe.filter(D=>D.id.toLowerCase().includes(Ee.toLowerCase())||D.title&&D.title.toLowerCase().includes(Ee.toLowerCase())||D.description&&D.description.toLowerCase().includes(Ee.toLowerCase())):Fe;return t.jsxs("div",{className:"task-form",onDrop:Tt,onDragOver:D=>D.preventDefault(),onPaste:Nt,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:ft,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:"Task title",value:i||"",onChange:D=>r(D.target.value),disabled:G})]}),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${pe==="idle"?"":" is-visible"}`,"aria-live":"polite",children:pe==="saving"?"Saving...":pe==="saved"?"Saved":""})]}),t.jsxs("div",{className:`description-with-refine${Re?" description--fullscreen":""}`,ref:Pe,onKeyDown:Dt,children:[Re&&t.jsxs("div",{className:"description-fullscreen-header",children:[t.jsx("span",{children:"Editing Description"}),t.jsx("button",{type:"button",className:"btn btn-sm description-expand-btn",onClick:Ft,"aria-label":"Collapse description",title:"Collapse description",children:t.jsx(Dr,{size:14})})]}),t.jsx("textarea",{ref:$e,autoFocus:e==="create",id:"task-form-description",value:n,onChange:Bt,placeholder:"What needs to be done?",rows:e==="edit"?8:5,disabled:G||ye}),(()=>{const D=!!n.trim()&&!G;return t.jsxs(t.Fragment,{children:[!Re&&t.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${D?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:Ft,"aria-label":"Expand description",title:"Expand description",children:t.jsx(el,{size:14})}),D&&t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${ye?"refine-button--loading":""}`,onClick:()=>it(F=>!F),disabled:ye,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(cs,{size:12,style:{verticalAlign:"middle"}}),ye?"Refining...":"Refine"]})]})})(),Je&&t.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:D=>D.preventDefault(),children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>Mt("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:()=>Mt("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:()=>Mt("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:()=>Mt("simplify"),"data-testid":"refine-simplify",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Simplify"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Simplify and make more concise"})]})]})]})]}),e==="create"&&(I||T)&&t.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[I&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const D=n.trim();if(!D){Y("Enter a description first","error");return}k?.(),I(D)},disabled:G||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),T&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const D=n.trim();if(!D){Y("Enter a description first","error");return}k?.(),T(D)},disabled:G||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),H,t.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>ie(D=>!D),"aria-expanded":me,"aria-controls":"task-form-more-options",disabled:G,"data-testid":"task-form-more-options-toggle",children:[t.jsx("span",{children:"More options"}),me?t.jsx(bi,{size:14}):t.jsx(Xt,{size:14})]}),t.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${me?"":" collapsed"}`,"aria-hidden":!me,hidden:!me,"data-testid":"task-form-more-options",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Attachments"}),K.length>0&&t.jsx("div",{className:"inline-create-previews",children:K.map((D,F)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:D.previewUrl,alt:D.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>qt(F),disabled:G,title:"Remove image",children:"×"})]},D.previewUrl))}),t.jsx("input",{ref:Z,type:"file",accept:"image/*",onChange:D=>{const F=D.target.files?.[0];F&&(L([...K,{file:F,previewUrl:URL.createObjectURL(F)}]),D.target.value="")},style:{display:"none"}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>Z.current?.click(),disabled:G,children:"Attach Screenshot"}),t.jsx("small",{children:"You can also paste images or drag & drop"})]}),u&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"task-node-select",children:"Execution Node Override"}),t.jsxs("select",{id:"task-node-select",className:"select",value:c??"",onChange:D=>u(D.target.value||void 0),disabled:G||m,children:[t.jsx("option",{value:"",children:"Use project default / local"}),(d??[]).map(D=>t.jsxs("option",{value:D.id,children:[D.name," (",SA(D.status),")"]},D.id))]}),(()=>{const D=(d??[]).find(F=>F.id===c);return D?t.jsx("div",{className:"task-form-node-status",children:t.jsx(Vi,{status:D.status,showLabel:!0})}):null})(),t.jsx("small",{children:h??"Task override takes priority over project default node routing."})]}),!ue&&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:Ye,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>de(D=>!D),disabled:G,children:o.length>0?`${o.length} selected`:"Add dependencies"}),ge&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Ee,onChange:D=>Ue(D.target.value),onClick:D=>D.stopPropagation()}),ct.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):ct.map(D=>t.jsxs("div",{className:`dep-dropdown-item${o.includes(D.id)?" selected":""}`,onClick:()=>Pt(D.id),onMouseDown:F=>F.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:D.id}),t.jsx("span",{className:"dep-dropdown-title",children:At(D.title||D.description||D.id,30)})]},D.id))]})]}),o.length>0&&t.jsx("div",{className:"selected-deps",children:o.map(D=>t.jsxs("span",{className:"dep-chip",children:[D,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>Pt(D),disabled:G,children:"×"})]},D))})]})}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Model Configuration"}),p&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"task-priority",className:"model-select-label",children:"Priority"}),t.jsx("select",{id:"task-priority","data-testid":"task-priority-select",value:f??_s,onChange:D=>p(D.target.value),disabled:G,children:kd.map(D=>t.jsx("option",{value:D,children:D[0].toUpperCase()+D.slice(1)},D))})]}),ne&&O!==void 0&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"task-execution-mode",className:"model-select-label",children:"Execution mode"}),t.jsxs("select",{id:"task-execution-mode","data-testid":"task-form-execution-mode-select",value:O,onChange:D=>ne(D.target.value),disabled:G,children:[t.jsx("option",{value:"standard",children:"Standard"}),t.jsx("option",{value:"fast",children:"Fast"})]})]}),Be?t.jsx("div",{className:"model-selector-loading",children:"Loading models…"}):Te.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:j==="preset"?S:j,onChange:D=>{const F=D.target.value;if(F==="default"){A("default"),z(""),b(""),x("");return}if(F==="custom"){A("custom"),z("");return}const ve=gt.find(Oe=>Oe.id===F),ze=dh(ve);A("preset"),z(F),b(ze.executorValue),x(ze.validatorValue)},disabled:G,children:[t.jsx("option",{value:"default",children:"Use default"}),gt.length>0?t.jsx("option",{disabled:!0,children:"──────────"}):null,gt.map(D=>t.jsx("option",{value:D.id,children:D.name},D.id)),t.jsx("option",{value:"custom",children:"Custom"})]})]}),j==="preset"&&wt?t.jsxs("small",{children:["Using preset: ",wt.name]}):null,j==="preset"?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>A("custom"),disabled:G,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(Zn,{id:"executor-model",label:"Executor Model",value:g,onChange:D=>{A("custom"),z(""),b(D)},models:Te,disabled:G||j==="preset",favoriteProviders:et,onToggleFavorite:St,favoriteModels:Xe,onToggleModelFavorite:Wt})]}),t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"validator-model",className:"model-select-label",children:"Reviewer"}),t.jsx(Zn,{id:"validator-model",label:"Reviewer Model",value:v,onChange:D=>{A("custom"),z(""),x(D)},models:Te,disabled:G||j==="preset",favoriteProviders:et,onToggleFavorite:St,favoriteModels:Xe,onToggleModelFavorite:Wt})]}),w&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"planning-model",className:"model-select-label",children:"Planning"}),t.jsx(Zn,{id:"planning-model",label:"Planning Model",value:y||"",onChange:D=>{A("custom"),z(""),w(D)},models:Te,disabled:G||j==="preset",favoriteProviders:et,onToggleFavorite:St,favoriteModels:Xe,onToggleModelFavorite:Wt})]}),C&&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:E||"",onChange:D=>C(D.target.value),disabled:G||j==="preset",children:[t.jsxs("option",{value:"",children:["Default (",Ne?.defaultThinkingLevel??"off",")"]}),t.jsx("option",{value:"off",children:"Off"}),t.jsx("option",{value:"minimal",children:"Minimal"}),t.jsx("option",{value:"low",children:"Low"}),t.jsx("option",{value:"medium",children:"Medium"}),t.jsx("option",{value:"high",children:"High"})]})]}),he&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"review-level",className:"model-select-label",children:"Review"}),t.jsxs("select",{id:"review-level",value:W??"",onChange:D=>he(D.target.value===""?void 0:parseInt(D.target.value,10)),disabled:G,children:[t.jsx("option",{value:"",children:"Default (Auto — triage decides)"}),t.jsx("option",{value:"0",children:"0 — None"}),t.jsx("option",{value:"1",children:"1 — Plan Only"}),t.jsx("option",{value:"2",children:"2 — Plan and Code"}),t.jsx("option",{value:"3",children:"3 — Full"})]})]})]})]}),J,t.jsxs("div",{className:"form-group","data-testid":"workflow-steps-section",children:[t.jsx("label",{children:"Workflow Steps"}),t.jsxs("div",{className:"workflow-steps-section",children:[t.jsx("small",{className:"workflow-steps-description",children:"Select steps to run after task implementation completes"}),t.jsx("div",{className:"workflow-steps-list",children:Me.length>0&&Me.map(D=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${D.id}`,children:[t.jsx("input",{type:"checkbox",checked:_.includes(D.id),onChange:F=>{R(F.target.checked?[..._,D.id]:_.filter(ve=>ve!==D.id))},disabled:G}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[D.name,CA(D.phase||"pre-merge",D.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:D.description})]})]},D.id))})]}),_.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),_.map((D,F)=>{const ve=xe.get(D);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${D}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:F+1}),t.jsx("span",{className:"workflow-step-order-name",children:ve?.name||D}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>It(F),disabled:G||F===0,"data-testid":`workflow-step-move-up-${D}`,title:"Move up",children:t.jsx(bi,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Yt(F),disabled:G||F===_.length-1,"data-testid":`workflow-step-move-down-${D}`,title:"Move down",children:t.jsx(Xt,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Rt(D),disabled:G,"data-testid":`workflow-step-remove-${D}`,title:"Remove",children:t.jsx(Ht,{})})]})]},D)})]})]})]})]})}const mh={pre:({children:e,className:n,...s})=>t.jsx("pre",{...s,className:["workflow-markdown-pre",n].filter(Boolean).join(" "),children:e}),table:({children:e,className:n,...s})=>t.jsx("table",{...s,className:["workflow-markdown-table",n].filter(Boolean).join(" "),children:e})};function EA(e){switch(e){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return e}}function _A(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 MA(e){return e?new Date(e).toLocaleString():null}function AA(e){const n=e.split(`
655
+ `);return n.length<=1?e:`${n.length} lines`}function go(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 RA({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 TA({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({}),[f,p]=a.useState(null),[g,b]=a.useState([]),[v,x]=a.useState(!1),y=n.some(k=>k.status==="pending"),{entries:w}=pg(e,!!l&&y,o);a.useEffect(()=>{let k=!1;return sl(o).then(H=>{k||b(H.filter(J=>J.enabled))}).catch(()=>{k||b([])}),()=>{k=!0}},[o]);const E=i??[],C=a.useMemo(()=>g.map(k=>({id:k.id,name:k.name,description:k.description,phase:k.phase||"pre-merge"})),[g]),j=a.useMemo(()=>new Map(C.map(k=>[k.id,k])),[C]),A=k=>{d(H=>({...H,[k]:!H[k]}))},S=k=>{h(H=>{const J=H[k]??"markdown";return{...H,[k]:J==="markdown"?"plain":"markdown"}})},z=k=>{p(k)},_=()=>{p(null)};a.useEffect(()=>{if(!f)return;const k=H=>{H.key==="Escape"&&_()};return document.addEventListener("keydown",k),()=>{document.removeEventListener("keydown",k)}},[f]);const R=a.useCallback((k,H)=>{if(c){if(H){if(E.includes(k)){c(E);return}c([...E,k]);return}c(E.filter(J=>J!==k))}},[c,E]),B=a.useCallback(k=>{if(!c||k<=0)return;const H=[...E];[H[k-1],H[k]]=[H[k],H[k-1]],c(H)},[c,E]),K=a.useCallback(k=>{if(!c||k>=E.length-1)return;const H=[...E];[H[k],H[k+1]]=[H[k+1],H[k]],c(H)},[c,E]),L=a.useCallback(k=>{c&&c(E.filter(H=>H!==k))},[c,E]),$=n.length>0,U=E.length>0;a.useEffect(()=>{r||x(!1)},[r]);const G=a.useMemo(()=>E.map(k=>{const H=j.get(k);return{id:k,name:H?.name||k,description:H?.description||"Step definition not found.",phase:H?.phase||"pre-merge"}}),[E,j]),Y=()=>!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:C.map(k=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${k.id}`,children:[t.jsx("input",{type:"checkbox",checked:E.includes(k.id),onChange:H=>R(k.id,H.target.checked)}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[k.name,go(k.phase,k.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:k.description})]})]},k.id))})]}),E.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),E.map((k,H)=>{const J=j.get(k);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${k}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:H+1}),t.jsx("span",{className:"workflow-step-order-name",children:J?.name||k}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>B(H),disabled:H===0,"data-testid":`workflow-step-move-up-${k}`,title:"Move up",children:t.jsx(bi,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>K(H),disabled:H===E.length-1,"data-testid":`workflow-step-move-down-${k}`,title:"Move down",children:t.jsx(Xt,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>L(k),"data-testid":`workflow-step-remove-${k}`,title:"Remove",children:t.jsx(Ht,{})})]})]},k)})]})]}),ee=()=>{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(!$)return t.jsxs("div",{className:"workflow-results-empty","data-testid":"workflow-results-empty",children:[t.jsx("p",{children:"No workflow steps configured for this task."}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."})]});const k=n.filter(W=>W.status==="passed").length,H=n.filter(W=>W.status==="failed").length,J=n.filter(W=>W.status==="skipped").length,ue=n.filter(W=>W.status==="pending").length,fe=[`${n.length} step${n.length!==1?"s":""}`];return k>0&&fe.push(`${k} passed`),H>0&&fe.push(`${H} failed`),J>0&&fe.push(`${J} skipped`),ue>0&&fe.push(`${ue} 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:fe.join(" · ")}),n.map((W,he)=>{const O=W.phase||"pre-merge",ne=u[W.workflowStepId]??!1;return t.jsxs("div",{className:`workflow-result-item workflow-result-item--${W.status}`,"data-testid":`workflow-result-item-${W.workflowStepId}`,children:[t.jsxs("div",{className:"workflow-result-header",children:[t.jsxs("div",{className:"workflow-result-name",children:[W.workflowStepName,go(O,W.workflowStepId,"workflow-result-phase")]}),t.jsx("span",{className:`workflow-result-badge workflow-result-badge--${W.status}`,"data-testid":`workflow-result-badge-${W.workflowStepId}`,children:EA(W.status)})]}),t.jsxs("div",{className:"workflow-result-meta",children:[W.startedAt&&t.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",MA(W.startedAt)]}),W.completedAt&&t.jsx("span",{className:"workflow-result-duration",children:_A(W.startedAt,W.completedAt)})]}),W.status==="pending"&&W.startedAt?t.jsx(RA,{entries:w,startedAt:W.startedAt,stepId:W.workflowStepId}):W.output?t.jsxs("div",{className:"workflow-result-output-section",children:[t.jsxs("div",{className:"workflow-result-output-header",children:[t.jsx("span",{className:"workflow-result-output-label",children:"Output:"}),t.jsx("button",{className:"workflow-result-toggle",onClick:()=>A(W.workflowStepId),"data-testid":`workflow-result-toggle-${W.workflowStepId}`,children:ne?"Hide output":"Show output"}),!ne&&t.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${W.workflowStepId}`,children:AA(W.output)}),ne&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>S(W.workflowStepId),"data-testid":`workflow-result-mode-toggle-${W.workflowStepId}`,title:(m[W.workflowStepId]??"markdown")==="markdown"?"Switch to plain text":"Switch to markdown",children:(m[W.workflowStepId]??"markdown")==="markdown"?"Markdown":"Plain"}),t.jsx("button",{className:"workflow-result-expand-toggle",onClick:()=>z(W.workflowStepId),"data-testid":`workflow-result-expand-${W.workflowStepId}`,title:"Expand output",children:t.jsx(el,{size:12})})]})]}),ne&&t.jsx("div",{className:`workflow-result-output${(m[W.workflowStepId]??"markdown")==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":`workflow-result-output-${W.workflowStepId}`,children:(m[W.workflowStepId]??"markdown")==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(li,{remarkPlugins:[ci],components:mh,children:W.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:W.output})})]}):null]},`${W.workflowStepId}-${he}`)})]})},N=r?t.jsx("button",{type:"button",className:"modal-edit-btn workflow-results-edit-toggle",onClick:()=>x(k=>!k),"data-testid":"workflow-steps-edit-toggle","aria-label":v?"Done editing workflow steps":"Edit workflow steps",title:v?"Done":"Edit",children:v?t.jsxs(t.Fragment,{children:[t.jsx(Vn,{size:14}),"Done"]}):t.jsxs(t.Fragment,{children:[t.jsx(hs,{size:14}),"Edit"]})}):null,I=!s&&!$&&U,T=r&&$;return t.jsxs("div",{className:"workflow-results-tab","data-task-id":e,children:[I?t.jsxs("div",{className:"workflow-configured-steps","data-testid":"workflow-configured-steps",children:[t.jsxs("div",{className:"workflow-configured-header","data-testid":"workflow-configured-header",children:[t.jsxs("div",{className:"workflow-configured-title-row",children:[t.jsx("h4",{children:"Configured Workflow Steps"}),t.jsxs("span",{className:"workflow-configured-count","data-testid":"workflow-configured-count",children:[G.length," step",G.length===1?"":"s"]})]}),N]}),t.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:G.map(k=>t.jsxs("div",{className:"workflow-configured-item","data-testid":`workflow-configured-step-${k.id}`,children:[t.jsxs("div",{className:"workflow-configured-name",children:[k.name,go(k.phase,k.id,"workflow-configured-phase")]}),t.jsx("p",{className:"workflow-configured-description",children:k.description})]},k.id))}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."}),Y()]}):t.jsxs(t.Fragment,{children:[T&&t.jsxs("div",{className:"workflow-results-edit-header","data-testid":"workflow-results-edit-header",children:[t.jsx("h4",{children:"Workflow Steps"}),N]}),ee(),Y()]}),f&&(()=>{const k=n.find(ue=>ue.workflowStepId===f);if(!k)return null;const H=m[k.workflowStepId]??"markdown",J=k.phase||"pre-merge";return t.jsx("div",{className:"workflow-output-modal-overlay",onClick:ue=>{ue.target===ue.currentTarget&&_()},"data-testid":"workflow-output-modal",children:t.jsxs("div",{className:"workflow-output-modal",role:"dialog","aria-modal":"true",children:[t.jsxs("div",{className:"workflow-output-modal-header",children:[t.jsxs("div",{className:"workflow-output-modal-title",children:[t.jsx("span",{className:"workflow-output-modal-name",children:k.workflowStepName}),go(J,k.workflowStepId,"workflow-output-modal-phase")]}),t.jsxs("div",{className:"workflow-output-modal-controls",children:[t.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>S(k.workflowStepId),"data-testid":"workflow-output-modal-mode-toggle",title:H==="markdown"?"Switch to plain text":"Switch to markdown",children:H==="markdown"?"Markdown":"Plain"}),t.jsx("button",{className:"workflow-output-modal-close",onClick:_,"data-testid":"workflow-output-modal-close","aria-label":"Close",children:t.jsx(Ht,{size:16})})]})]}),t.jsx("div",{className:"workflow-output-modal-body",children:t.jsx("div",{className:`workflow-result-output workflow-result-output--expanded${H==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":"workflow-output-modal-content",children:H==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(li,{remarkPlugins:[ci],components:mh,children:k.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:k.output})})})]})})})()]})}function PA(e){return e==="block"?"Block execution":e==="fallback-local"?"Fall back to local":"Not configured"}const IA=new Set(["planning","researching","executing","finalizing","merging"]);function $A(e){return e!==void 0&&e!=="online"}function DA({task:e,settings:n,addToast:s,onTaskUpdated:i}){const[r,o]=a.useState([]),[l,c]=a.useState(!1),[u,d]=a.useState(null),[m,h]=a.useState(e.nodeId??""),[f,p]=a.useState(!1),g=a.useRef(e.id);a.useEffect(()=>{g.current=e.id,h(e.nodeId??""),p(!1)},[e.id,e.nodeId]),a.useEffect(()=>{c(!0),d(null),Do().then(_=>{o(_)}).catch(_=>{d(we(_)||"Failed to load nodes")}).finally(()=>{c(!1)})},[]);const b=a.useMemo(()=>new Map(r.map(_=>[_.id,_])),[r]),v=a.useMemo(()=>[...r].sort((_,R)=>_.name.localeCompare(R.name)),[r]),x=n,y=e.nodeId??x?.defaultNodeId??null,w=e.nodeId?"Per-task override":x?.defaultNodeId?"Project default":"No routing",E=y?b.get(y):void 0,C=E?`${E.name} (${E.type})`:y?`${y} (node unavailable or unknown)`:"Local (no routing configured)",j=e.column==="in-progress"||IA.has(e.status),A=j||f||l,S=a.useCallback(async _=>{if(_===m)return;const R=e.id,B=m;h(_),p(!0);try{const K=await ii(R,{nodeId:_||null});if(g.current!==R)return;h(K.nodeId??""),i?.(K),s(_?"Node override updated":"Node override cleared","success")}catch(K){if(g.current!==R)return;h(B),s(we(K)||"Failed to update node override","error")}finally{g.current===R&&p(!1)}},[s,i,m,e.id]),z=a.useCallback(()=>{S("")},[S]);return t.jsxs("div",{className:"routing-tab",children:[t.jsx("h4",{children:"Task Routing"}),t.jsx("p",{className:"routing-tab__intro",children:"View the effective execution node and control per-task node override."}),t.jsxs("section",{className:"routing-tab__section",children:[t.jsx("h5",{children:"Routing Summary"}),t.jsxs("div",{className:"routing-summary-grid",role:"list",children:[t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Effective node"}),t.jsxs("span",{className:"routing-summary-value",children:[E?t.jsx(Vi,{status:E.status,compact:!0}):null,C,$A(E?.status)?t.jsx("span",{className:"routing-summary-warning",children:"Unhealthy"}):null]})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Routing source"}),t.jsx("span",{className:"routing-summary-value",children:w})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Unavailable-node policy"}),t.jsx("span",{className:"routing-summary-value",children:PA(x?.unavailableNodePolicy)})]})]}),j&&y?t.jsx("div",{className:"routing-tab__info-banner",children:"Routing is locked while this task is active. Node override cannot be changed until the task is no longer active."}):null]}),t.jsxs("section",{className:"routing-tab__section",children:[t.jsx("h5",{children:"Node Override"}),j?t.jsx("div",{className:"routing-tab__warning-banner",children:"Node override cannot be changed while the task is active."}):null,t.jsx("label",{className:"routing-tab__selector-label",htmlFor:`routing-node-${e.id}`,children:"Select execution node"}),t.jsxs("select",{id:`routing-node-${e.id}`,className:"select routing-tab__selector",value:m,disabled:A,onChange:_=>{S(_.target.value)},children:[t.jsx("option",{value:"",children:"Use project default"}),v.map(_=>t.jsxs("option",{value:_.id,title:`Status: ${_.status}`,children:[_.name," (",_.type,") — ",_.status]},_.id))]}),u?t.jsx("div",{className:"routing-tab__error",children:u}):null,e.nodeId?t.jsxs("div",{className:"routing-tab__override-row",children:[t.jsxs("span",{className:"routing-tab__override-text",children:["Override set to: ",b.get(e.nodeId)?.name??e.nodeId]}),t.jsx("button",{type:"button",className:"btn btn-sm",disabled:j||f,onClick:z,children:"Clear override"})]}):null]})]})}const LA=/^[a-zA-Z0-9_-]{1,64}$/,zA=200;function hh(e){return e?new Date(e).toLocaleString():""}function FA(e,n=zA){return e.length<=n?e:e.substring(0,n)+"…"}function OA({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,f]=a.useState(""),[p,g]=a.useState(null),[b,v]=a.useState(""),[x,y]=a.useState(null),[w,E]=a.useState([]),[C,j]=a.useState(!1),[A,S]=a.useState(!1),[z,_]=a.useState(""),[R,B]=a.useState(""),[K,L]=a.useState(!1),[$,U]=a.useState(null),[G,Y]=a.useState(null),[ee,N]=a.useState(!1),I=a.useCallback(async()=>{try{const O=await Sy(e,i);l(O)}catch(O){n(we(O)||"Failed to load documents","error")}finally{u(!1)}},[e,i,n]);a.useEffect(()=>{I()},[I]);async function T(O){d===O.key?(m(null),f(""),g(null),v(""),y(null),E([]),N(!1)):(m(O.key),f(O.content),g(null),v(""),y(null),E([]),N(!1))}async function k(O){if(x===O)y(null),E([]);else{y(O),j(!0);try{const ne=await Cy(e,O,i);E(ne)}catch(ne){n(we(ne)||"Failed to load revisions","error")}finally{j(!1)}}}function H(){d&&(g(d),v(h))}function J(){g(null),v("")}async function ue(){if(!(!p||!b.trim())){L(!0);try{await su(e,p,b,{},i),g(null),v(""),await I();const O=o.find(ne=>ne.key===p);O&&f(O.content),n("Document saved","success")}catch(O){n(we(O)||"Failed to save document","error")}finally{L(!1)}}}async function fe(){const O=z.trim(),ne=R.trim();if(!O){n("Document key is required","error");return}if(!LA.test(O)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!ne){n("Content is required","error");return}L(!0);try{await su(e,O,ne,{},i),S(!1),_(""),B(""),await I(),n("Document created","success")}catch(Q){n(we(Q)||"Failed to create document","error")}finally{L(!1)}}async function W(O){U(O);try{await Ey(e,O,i),Y(null),U(null),d===O&&(m(null),f("")),x===O&&(y(null),E([])),await I(),n("Document deleted","success")}catch(ne){n(we(ne)||"Failed to delete document","error")}finally{U(null)}}function he(O){f(O.content),g(null),v("")}return c?t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),t.jsx("div",{className:"detail-log-empty",children:"Loading documents…"})]}):t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),A&&t.jsxs("div",{className:"task-document-create-form",children:[t.jsx("h5",{children:"New Document"}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-key",children:"Key"}),t.jsx("input",{id:"doc-key",type:"text",className:"task-document-key-input",value:z,onChange:O=>_(O.target.value),placeholder:"e.g., plan, notes, research",disabled:K}),t.jsx("span",{className:"form-hint",children:"Alphanumeric, hyphens, underscores (1-64 chars)"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-content",children:"Content"}),t.jsx("textarea",{id:"doc-content",value:R,onChange:O=>B(O.target.value),rows:6,placeholder:"Enter document content…",disabled:K})]}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{S(!1),_(""),B("")},disabled:K,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void fe(),disabled:K||!z.trim()||!R.trim(),children:K?"Creating…":"Create"})]})]}),o.length===0&&!A?t.jsx("div",{className:"detail-log-empty",children:"No documents yet."}):t.jsx("div",{className:"task-documents-list",children:o.map(O=>t.jsxs("div",{className:"task-document-card",children:[t.jsxs("div",{className:"task-document-card-header",children:[t.jsxs("div",{className:"task-document-card-title",children:[t.jsx(Bi,{size:14}),t.jsx("span",{className:"task-document-key",children:O.key}),t.jsxs("span",{className:"task-document-revision-badge",children:["v",O.revision]})]}),t.jsxs("div",{className:"task-document-meta",children:[t.jsx("span",{className:"task-document-author",children:O.author}),t.jsx("span",{className:"task-document-timestamp",children:hh(O.updatedAt||O.createdAt)})]})]}),d===O.key&&p!==O.key&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"task-document-content-header",children:t.jsx("button",{className:"btn btn-sm document-mode-toggle",onClick:()=>N(ne=>!ne),"aria-label":ee?"Switch to plain text":"Switch to markdown","aria-pressed":ee,title:ee?"Switch to plain text":"Switch to markdown",children:ee?"Markdown":"Plain"})}),t.jsx("div",{className:"task-document-content",children:ee?t.jsx("div",{className:"task-document-content-markdown",children:t.jsx("div",{className:"markdown-body",children:t.jsx(li,{remarkPlugins:[ci],children:h})})}):t.jsx("pre",{className:"task-document-content-text",children:h})}),x===O.key&&t.jsxs("div",{className:"task-document-revisions",children:[t.jsx("h5",{children:"Revision History"}),C?t.jsx("div",{className:"detail-log-empty",children:"Loading…"}):w.length<=1?t.jsx("div",{className:"detail-log-empty",children:"No previous revisions."}):t.jsx("div",{className:"task-document-revision-list",children:w.filter(ne=>ne.revision<O.revision).sort((ne,Q)=>Q.revision-ne.revision).map(ne=>t.jsxs("div",{className:"task-document-revision-item",onClick:()=>he(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:hh(ne.createdAt)})]}),t.jsx("div",{className:"revision-preview",children:FA(ne.content,100)})]},ne.id))})]})]}),p===O.key&&t.jsxs("div",{className:"task-document-edit-form",children:[t.jsx("textarea",{value:b,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:J,disabled:K,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void ue(),disabled:K||!b.trim(),children:K?"Saving…":"Save"})]})]}),t.jsxs("div",{className:"task-document-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>void T(O),children:d===O.key?t.jsxs(t.Fragment,{children:[t.jsx(bi,{size:14})," Collapse"]}):t.jsxs(t.Fragment,{children:[t.jsx(Xt,{size:14})," Expand"]})}),d===O.key&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>void k(O.key),children:[t.jsx(yr,{size:14})," History"]}),r&&p!==O.key&&t.jsx("button",{className:"btn btn-sm",onClick:H,children:"Edit"}),r&&(G===O.key?t.jsxs("div",{className:"confirm-delete-actions",children:[t.jsx("span",{children:"Delete?"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void W(O.key),disabled:$===O.key,children:$===O.key?"…":"Yes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Y(null),disabled:$===O.key,children:"No"})]}):t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>Y(O.key),children:t.jsx(an,{size:14})}))]})]})]},O.key))}),r&&!A&&t.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>S(!0),children:[t.jsx(rn,{size:14})," New Document"]})]})}function bo(e){return e.toLocaleString()}function cc(e){const n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString()}function Qa(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 UA(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 BA({tokenUsage:e,loading:n,task:s}){const i=Jp(s?.log??[]),r=i.filter(m=>typeof m.durationMs=="number"),o=r.reduce((m,h)=>m+(h.durationMs??0),0),l=Math.max(o,s?.timedExecutionMs??0),c=r.reduce((m,h)=>!m||(h.durationMs??0)>(m.durationMs??0)?h:m,void 0),u=UA(s?.workflowStepResults??[]),d=s?.steps?.length??0;return t.jsxs("section",{className:"task-token-stats-panel","aria-label":"Task execution statistics",children:[t.jsx("h4",{children:"Execution & Token Stats"}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Execution Timing"}),t.jsxs("div",{className:"task-token-stats-panel__grid",role:"list","aria-label":"Execution timing metrics",children:[t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Timing events"}),t.jsx("span",{className:"task-token-stats-panel__value",children:i.length.toLocaleString()})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Timed duration"}),t.jsx("span",{className:"task-token-stats-panel__value",children:Qa(l)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Workflow timed steps"}),t.jsx("span",{className:"task-token-stats-panel__value",children:u.timedStepCount.toLocaleString()})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Workflow runtime"}),t.jsx("span",{className:"task-token-stats-panel__value",children:Qa(u.totalDurationMs)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Total execution time"}),t.jsx("span",{className:"task-token-stats-panel__value",children:Qa(l+u.totalDurationMs)})]})]}),t.jsxs("dl",{className:"task-token-stats-panel__timestamps",children:[t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Longest timing event"}),t.jsx("dd",{children:c?.durationMs?`${c.summary} (${Qa(c.durationMs)})`:"No timed events recorded yet."})]}),t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Longest workflow step"}),t.jsx("dd",{children:u.longestStep?`${u.longestStep.name} (${Qa(u.longestStep.durationMs)})`:"No completed workflow step timings yet."})]})]})]}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Execution Details"}),t.jsxs("dl",{className:"task-token-stats-panel__details",children:[t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Execution mode"}),t.jsx("dd",{children:s?.executionMode==="fast"?"Fast":"Standard"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Runtime status"}),t.jsx("dd",{children:s?.status??"Not set"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Paused"}),t.jsx("dd",{children:s?.paused?"Yes":"No"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Step progress"}),t.jsx("dd",{children:d>0?`${Math.min((s?.currentStep??0)+1,d)} / ${d}`:"No steps"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Retries (recovery / workflow / merge / task_done)"}),t.jsx("dd",{children:`${s?.recoveryRetryCount??0} / ${s?.workflowStepRetries??0} / ${s?.mergeRetries??0} / ${s?.taskDoneRetryCount??0}`})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Recovery state"}),t.jsx("dd",{children:s?.nextRecoveryAt?`Next recovery at ${cc(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:bo(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:bo(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:bo(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:bo(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:cc(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:cc(e.lastUsedAt)})})]})]})]}):t.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:"No token usage recorded for this task yet."})]})]})}const HA=new Set(["planning","researching","executing","finalizing","merging"]);function qA(e,n){return Up(e,n)}function VA(e,n){return Bp(e,n)}function WA(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 KA(e,n,s){if(e.planningModelProvider&&e.planningModelId)return{provider:e.planningModelProvider,modelId:e.planningModelId};const i=WA(n);return i||Hp(e,s)}function GA(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 JA(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 YA(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function QA(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 ph(e,n){return e.length>n?e.slice(0,n)+"…":e}function fh(e=[],n=[]){return e.length===n.length&&e.every((s,i)=>s===n[i])}function dc(e){const n=e.indexOf("/");return!e||n===-1?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function uc(e){return e.trim()}function XA(e){const n=e.trim();return n.length>0?n:void 0}function Xa(e){return typeof e=="string"&&kd.includes(e)?e:_s}function Za(e){return e==="fast"?"fast":"standard"}function ZA(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}const eR=a.lazy(()=>ln(()=>import("./AgentDetailView-CBFUveyO.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8])).then(e=>({default:e.AgentDetailView})));function tR(e,n={}){switch(e.sourceType){case"dashboard_ui":return{label:"Dashboard"};case"quick_chat":return{label:"Quick Chat"};case"chat_session":return{label:"Chat Session"};case"agent_heartbeat":return{label:n.sourceAgentName??e.sourceAgentId??"agent",sourceAgentId:e.sourceAgentId};case"automation":return{label:"Automation"};case"cron":return{label:"Scheduled Task"};case"workflow_step":return{label:"Workflow Step"};case"github_import":return{label:"GitHub Import",contextInfo:ZA(e.sourceMetadata)};case"task_refine":return{label:"Refinement",parentTaskId:e.sourceParentTaskId};case"task_duplicate":return{label:"Duplicate",parentTaskId:e.sourceParentTaskId};case"cli":return{label:"CLI"};case"api":return{label:"API"};case"recovery":return{label:"Recovery"};case"unknown":default:return null}}const mc=200,nR=new Set(["triage","todo"]);function sR({task:e,projectId:n,tasks:s=[],onClose:i,onOpenDetail:r,onMoveTask:o,onDeleteTask:l,onMergeTask:c,onRetryTask:u,onResetTask:d,onDuplicateTask:m,onTaskUpdated:h,addToast:f,prAuthAvailable:p,initialTab:g="definition"}){const[b,v]=a.useState(g),[x,y]=a.useState(()=>"prompt"in e?e:null),[w,E]=a.useState(()=>!("prompt"in e));a.useEffect(()=>{if("prompt"in e){y(e),E(!1);return}let X=!1;return E(!0),y(null),wr(e.id,n).then(We=>{X||(y(We),E(!1))}).catch(()=>{X||E(!1)}),()=>{X=!0}},[e.id,n]);const C=x?{...x,...e,prompt:x.prompt,log:x.log}:{...e,prompt:""},j=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,S]=a.useState(null),[z,_]=a.useState(null),R=tR(C,{sourceAgentName:A?.name});a.useEffect(()=>{v(g)},[g]),a.useEffect(()=>{$(!1)},[e.id]);const[B,K]=a.useState("activity"),[L,$]=a.useState(!1),[U,G]=a.useState(e.attachments||[]),[Y,ee]=a.useState(!1),[N,I]=a.useState(e.dependencies||[]),[T,k]=a.useState(!1),[H,J]=a.useState(""),[ue,fe]=a.useState(null),[W,he]=a.useState([]),[O,ne]=a.useState(!1),[Q,ge]=a.useState(!1),[de,me]=a.useState(!1),[ie,Ee]=a.useState(!1),[Ue,Te]=a.useState(!1),[at,et]=a.useState(C.prompt||""),[Ve,Xe]=a.useState(""),[De,Be]=a.useState(!1),[oe,Ne]=a.useState(""),[se,Me]=a.useState(!1),[Le,pe]=a.useState(!1),[Ae,Je]=a.useState(e.title||""),[it,ye]=a.useState(e.description||""),[ce,Re]=a.useState(e.dependencies||[]),[be,Pe]=a.useState(""),[Ye,$e]=a.useState(""),[ft,Z]=a.useState(""),[re,je]=a.useState(""),[rt,te]=a.useState("default"),[Ze,pt]=a.useState(void 0),[gt,wt]=a.useState(_s),[Et,mt]=a.useState(e.nodeId),[Nt,Tt]=a.useState(Za(e.executionMode)),[qt,Pt]=a.useState(""),[At,Bt]=a.useState(e.enabledWorkflowSteps||[]),[Ft,Dt]=a.useState(e.sourceIssue?.provider??""),[Mt,St]=a.useState(e.sourceIssue?.repository??""),[Wt,It]=a.useState(e.sourceIssue?.externalIssueId??""),[Yt,Rt]=a.useState(e.sourceIssue?.url??""),[xe,Fe]=a.useState([]),[ct,D]=a.useState(!1),F=a.useRef(!1),[ve,ze]=a.useState(!1),[Oe,Ge]=a.useState(!1),[dt,Zt]=a.useState(!1),Nn=a.useRef(null),un=a.useRef(null),Kt=a.useRef(null),mn=a.useRef(null);di(mn,!0,"fusion:task-detail-modal-size");const{getSlotsForId:ke}=zp(n),ut=ke("task-detail-tab");a.useEffect(()=>(F.current=!0,()=>{F.current=!1}),[]);const[Lt,En]=a.useState(void 0),[hn,Rn]=a.useState([]),[is,Dn]=a.useState(!1),[nn,cn]=a.useState(e.enabledWorkflowSteps||[]),Hn=e.column==="in-progress"||HA.has(e.status);a.useEffect(()=>{Je(e.title||""),ye(e.description||""),Dt(e.sourceIssue?.provider??""),St(e.sourceIssue?.repository??""),It(e.sourceIssue?.externalIssueId??""),Rt(e.sourceIssue?.url??""),Tt(Za(e.executionMode)),Zt(!1),pe(!1)},[e.id,e.title,e.description,e.sourceIssue,e.executionMode]),a.useEffect(()=>{cn(e.enabledWorkflowSteps||[])},[e.id,e.enabledWorkflowSteps]),a.useEffect(()=>{let X=!1;return nl(n).then(We=>{X||En(We)}).catch(()=>{}),()=>{X=!0}},[n]),a.useEffect(()=>{if(b!=="workflow")return;let X=!1;return Dn(!0),ak(e.id,n).then(We=>{X||Rn(We)}).catch(We=>{X||f(`Failed to load workflow results: ${we(We)}`,"error")}).finally(()=>{X||Dn(!1)}),()=>{X=!0}},[b,e.id,n,f]),a.useEffect(()=>{if(b!=="workflow")return;const X=n?`?projectId=${encodeURIComponent(n)}`:"",We=lt=>{try{const Ot=JSON.parse(lt.data);Ot.id===e.id&&Array.isArray(Ot.workflowStepResults)&&Rn(Ot.workflowStepResults)}catch{}};return Gs(`/api/events${X}`,{events:{"task:updated":We}})},[b,e.id,n]),a.useEffect(()=>{T||J("")},[T]),a.useEffect(()=>{if(!e.assignedAgentId){fe(null);return}const X=W.find(lt=>lt.id===e.assignedAgentId);if(X){fe(X);return}let We=!1;return Oc(e.assignedAgentId,n).then(lt=>{We||fe(lt)}).catch(()=>{We||fe(null)}),()=>{We=!0}},[e.assignedAgentId,n,W]),a.useEffect(()=>{if(!e.sourceAgentId){S(null);return}const X=W.find(lt=>lt.id===e.sourceAgentId);if(X){S(X);return}let We=!1;return Promise.resolve(Oc(e.sourceAgentId,n)).then(lt=>{We||S(lt??null)}).catch(()=>{We||S(null)}),()=>{We=!0}},[e.sourceAgentId,n,W]),a.useEffect(()=>{ne(!1)},[e.id]),a.useEffect(()=>{if(!(ve||Oe))return;const We=lt=>{const Ot=lt.target,Xs=Nn.current?.contains(Ot),Os=Kt.current?.contains(Ot);!Xs&&ve&&ze(!1),!Os&&Oe&&Ge(!1)};return document.addEventListener("mousedown",We),()=>document.removeEventListener("mousedown",We)},[ve,Oe]),a.useEffect(()=>{if(!(ve||Oe))return;const We=lt=>{lt.key==="Escape"&&(lt.stopPropagation(),ve&&ze(!1),Oe&&Ge(!1))};return document.addEventListener("keydown",We),()=>document.removeEventListener("keydown",We)},[ve,Oe]),a.useEffect(()=>{Te(!1),et(C.prompt||""),Xe("")},[e.id,C.prompt]);const fn=nR.has(e.column)&&!ct,dn=a.useCallback(()=>{if(!fn)return;pe(!0),Je(e.title||""),ye(e.description||""),Re(e.dependencies||[]);const X=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"",We=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"",lt=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";Pe(X),$e(We),Z(lt),je(e.thinkingLevel??""),mt(e.nodeId),te(X||We||lt?"custom":"default"),Pt(""),Bt(e.enabledWorkflowSteps||[]),Tt(Za(e.executionMode)),Dt(e.sourceIssue?.provider??""),St(e.sourceIssue?.repository??""),It(e.sourceIssue?.externalIssueId??""),Rt(e.sourceIssue?.url??""),Fe([]),pt(e.reviewLevel),wt(Xa(e.priority))},[fn,e]),_n=a.useCallback(()=>{pe(!1),Je(e.title||""),ye(e.description||""),Re(e.dependencies||[]),mt(e.nodeId),Dt(e.sourceIssue?.provider??""),St(e.sourceIssue?.repository??""),It(e.sourceIssue?.externalIssueId??""),Rt(e.sourceIssue?.url??""),wt(Xa(e.priority)),Tt(Za(e.executionMode)),xe.forEach(X=>URL.revokeObjectURL(X.previewUrl)),Fe([])},[e.title,e.description,e.dependencies,e.nodeId,e.priority,e.executionMode,xe]),zn=a.useCallback(async()=>{D(!0);try{const X={},We=Ae.trim(),lt=it.trim();We&&We!==(e.title??"")&&(X.title=We),lt&&lt!==(e.description??"")&&(X.description=lt),fh(ce,e.dependencies??[])||(X.dependencies=ce),fh(At,e.enabledWorkflowSteps??[])||(X.enabledWorkflowSteps=At);const Ot=dc(be),Xs=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"";be!==Xs&&(X.modelProvider=Ot?.provider??null,X.modelId=Ot?.modelId??null);const Os=dc(Ye),Oa=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"";Ye!==Oa&&(X.validatorModelProvider=Os?.provider??null,X.validatorModelId=Os?.modelId??null);const Ua=dc(ft),Jr=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";ft!==Jr&&(X.planningModelProvider=Ua?.provider??null,X.planningModelId=Ua?.modelId??null);const Yr=e.thinkingLevel??"";re!==Yr&&(X.thinkingLevel=re!==""?re:null),(e.nodeId??void 0)!==Et&&(X.nodeId=Et??null);const bl=e.reviewLevel;Ze!==bl&&(X.reviewLevel=Ze);const Qr=Xa(e.priority);gt!==Qr&&(X.priority=gt);const Xr=Za(e.executionMode);Nt!==Xr&&(X.executionMode=Nt==="fast"?"fast":null);const na=uc(Ft),q=uc(Mt),Ce=uc(Wt),Ie=XA(Yt);if(na.length===0&&q.length===0&&Ce.length===0&&!Ie)e.sourceIssue&&(X.sourceIssue=null);else{if(!na||!q||!Ce){f("Source issue provider, repository, and issue identifier are required","error"),D(!1);return}const _t=Number.parseInt(Ce,10),Gt=e.sourceIssue?.issueNumber??_t;if(!Number.isFinite(Gt)||Gt<=0){f("Source issue identifier must be numeric for new metadata","error"),D(!1);return}const He={provider:na,repository:q,externalIssueId:Ce,issueNumber:Gt,...Ie?{url:Ie}:{}},qe=e.sourceIssue;(!qe||qe.provider!==He.provider||qe.repository!==He.repository||qe.externalIssueId!==He.externalIssueId||qe.issueNumber!==He.issueNumber||(qe.url??void 0)!==He.url)&&(X.sourceIssue=He)}if(Object.keys(X).length>0){const _t=await ii(e.id,X,n);h?.(_t)}if(xe.length>0){const _t=[];for(const Gt of xe)try{const He=await Nr(e.id,Gt.file,n);G(qe=>[...qe,He])}catch{_t.push(Gt.file.name)}_t.length>0&&f(`Failed to upload: ${_t.join(", ")}`,"error")}xe.forEach(_t=>URL.revokeObjectURL(_t.previewUrl)),Fe([]),f(`Updated ${e.id}`,"success"),pe(!1)}catch(X){f(`Failed to update ${e.id}: ${we(X)}`,"error")}finally{F.current&&D(!1)}},[e,Ae,it,ce,be,Ye,ft,re,Et,Ze,gt,Nt,At,Ft,Mt,Wt,Yt,xe,f,n,h]),es=a.useCallback(async X=>{try{await ii(e.id,{description:X},n),f("Description saved","success")}catch(We){f(`Failed to save: ${we(We)}`,"error")}},[e.id,f,n]),Fn=a.useCallback(X=>{Le&&(X.key==="Escape"?(X.preventDefault(),_n()):X.key==="Enter"&&(X.ctrlKey||X.metaKey)&&(X.preventDefault(),zn()))},[Le,_n,zn]);a.useEffect(()=>{if(Le)return document.addEventListener("keydown",Fn),()=>document.removeEventListener("keydown",Fn)},[Le,Fn]);const Qt=a.useRef(null),{nodes:yt}=ol(),{confirm:on}=Ks(),{entries:M,loading:le,loadMore:Se,hasMore:Qe,total:ht,loadingMore:bt}=pg(e.id,b==="logs"&&B==="agent-log",n);a.useEffect(()=>{const X=We=>{We.key==="Escape"&&!Le&&i()};return document.addEventListener("keydown",X),()=>document.removeEventListener("keydown",X)},[i,Le]);const zt=Mi(i),yn=a.useCallback(async X=>{try{await o(e.id,X),i(),f(`Moved to ${Bn[X]}`,"success")}catch(We){f(we(We),"error")}},[e.id,o,i,f]),ts=a.useCallback(async()=>{if(await on({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0}))try{await l(e.id),i(),f(`Deleted ${e.id}`,"info")}catch(We){const lt=QA(We);if(!lt||lt.dependentIds.length===0){f(we(We),"error");return}const Ot=lt.dependentIds.join(", ");if(!await on({title:"Force Delete Task",message:`${e.id} is a dependency of ${Ot}.
656
+
657
+ Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await l(e.id,{removeDependencyReferences:!0}),i(),f(`Deleted ${e.id} after removing dependency references`,"info")}catch(Os){f(we(Os),"error")}}},[e.id,l,i,f,on]),as=a.useCallback(async()=>{await on({title:"Merge Task",message:`Merge ${e.id} into the current branch?`})&&(i(),f(`Merging ${e.id}...`,"info"),c(e.id).then(We=>{const lt=We.merged?`Merged ${e.id} (branch: ${We.branch})`:`Closed ${e.id} (${We.error||"no branch to merge"})`;f(lt,"success")}).catch(We=>{f(we(We),"error")}))},[e.id,c,i,f,on]),Js=a.useCallback(()=>{u&&(i(),u(e.id).then(()=>{f(`Retried ${e.id}`,"success")}).catch(X=>{f(we(X),"error")}))},[e.id,u,i,f]),ae=a.useCallback(()=>{d&&window.confirm(`This will erase all progress for ${e.id} and start the task from scratch. Continue?`)&&(i(),d(e.id).then(()=>{f(`Reset ${e.id} — fresh run will be allocated`,"success")}).catch(X=>{f(we(X),"error")}))},[e.id,d,i,f]),_e=a.useCallback(async()=>{if(!(!m||!await on({title:"Duplicate Task",message:`Duplicate ${e.id}? This will create a new task in Triage with the same description and prompt.`})))try{const We=await m(e.id);i(),f(`Duplicated ${e.id} → ${We.id}`,"success")}catch(We){f(we(We),"error")}},[e.id,m,i,f,on]),tt=a.useCallback(async()=>{try{e.paused?(await py(e.id,n),f(`Unpaused ${e.id}`,"success")):(await Sp(e.id,n),f(`Paused ${e.id}`,"success")),i()}catch(X){f(we(X),"error")}},[e.id,e.paused,i,f]),jt=a.useCallback(async()=>{try{await xy(e.id,n),f(`Plan approved — ${e.id} moved to Todo`,"success"),i()}catch(X){f(we(X),"error")}},[e.id,i,f]),kt=a.useCallback(async()=>{if(await on({title:"Reject Plan",message:"Reject this plan? The specification will be discarded and regenerated.",danger:!0}))try{await vy(e.id,n),f(`Plan rejected — ${e.id} returned to Planning for replanning`,"info"),i()}catch(We){f(we(We),"error")}},[e.id,i,f,on]),gn=a.useCallback(async()=>{if(await on({title:"Rebuild Plan",message:"Rebuild the plan for this task? The task will move to planning for replanning."}))try{await Ay(e.id,n),i(),f(`Replanning ${e.id}...`,"info")}catch(We){f(we(We),"error")}},[e.id,n,i,f,on]),sn=a.useCallback(()=>{Be(!0),Ne("")},[]),en=a.useCallback(()=>{ze(!1),Ge(!1)},[]),nt=a.useCallback(X=>{en(),yn(X)},[en]),$t=a.useCallback(X=>{en(),X()},[en]),Tn=a.useCallback(()=>{en(),as()},[en,as]),qn=a.useCallback(()=>{Be(!1),Ne(""),Me(!1)},[]),On=a.useCallback(async()=>{if(!oe.trim()){f("Please enter feedback describing what needs refinement","error");return}if(oe.length>2e3){f("Feedback must be 2000 characters or less","error");return}Me(!0);try{const X=await Ry(e.id,oe.trim(),n);f(`Refinement task created: ${X.id}`,"success"),i()}catch(X){f(we(X),"error")}finally{Me(!1)}},[e.id,oe,f,i]),Pn=a.useCallback(async X=>{ee(!0);try{const We=await Nr(e.id,X,n);G(lt=>[...lt,We]),f("Screenshot attached","success")}catch(We){f(we(We),"error")}finally{ee(!1)}},[e.id,f]),Kn=a.useCallback(async X=>{const We=X.target.files?.[0];We&&(await Pn(We),Qt.current&&(Qt.current.value=""))},[Pn]);a.useEffect(()=>{const X=We=>{const lt=We.clipboardData?.items;if(lt)for(let Ot=0;Ot<lt.length;Ot++){const Xs=lt[Ot];if(Xs.type.startsWith("image/")){const Os=Xs.getAsFile();if(Os){We.preventDefault(),Pn(Os);return}}}};return document.addEventListener("paste",X),()=>document.removeEventListener("paste",X)},[Pn]);const xs=a.useCallback(X=>{X.preventDefault()},[]),In=a.useCallback(X=>{X.preventDefault();const We=X.dataTransfer.files;for(let lt=0;lt<We.length;lt++){const Ot=We[lt];if(Ot.type.startsWith("image/")){Pn(Ot);return}}},[Pn]),Gn=a.useCallback(async X=>{try{await ky(e.id,X,n),G(We=>We.filter(lt=>lt.filename!==X)),f("Attachment deleted","info")}catch(We){f(we(We),"error")}},[e.id,f]),vs=a.useCallback(async X=>{const We=nn;cn(X);try{const lt=await ii(e.id,{enabledWorkflowSteps:X},n);f("Workflow steps updated","success"),h?.(lt)}catch(lt){cn(We),f(`Failed to update workflow steps: ${we(lt)}`,"error")}},[e.id,n,nn,h,f]),zs=a.useCallback(async()=>{ge(!0);try{const X=await Ra(void 0,n);he(X),ne(!0)}catch(X){f(`Failed to load agents: ${we(X)}`,"error"),ne(!1)}finally{ge(!1)}},[n,f]),ys=a.useCallback(async X=>{try{const We=await pu(e.id,X,n),lt=W.find(Ot=>Ot.id===X)??null;fe(lt||(Ot=>Ot?.id===X?Ot:null)),ne(!1),h?.(We),f("Assigned agent updated","success")}catch(We){f(`Failed to assign agent: ${we(We)}`,"error")}},[e.id,n,W,h,f]),$n=a.useCallback(async()=>{try{const X=await pu(e.id,null,n);fe(null),ne(!1),h?.(X),f("Agent unassigned","success")}catch(X){f(`Failed to unassign agent: ${we(X)}`,"error")}},[e.id,n,h,f]),Jn=a.useCallback(async X=>{const We=[...N,X];I(We);try{await ii(e.id,{dependencies:We},n)}catch(lt){I(N),f(we(lt),"error")}},[e.id,N,f]),Fs=a.useCallback(async(X,We)=>{X.stopPropagation();const lt=N.filter(Ot=>Ot!==We);I(lt);try{await ii(e.id,{dependencies:lt},n)}catch(Ot){I(N),f(we(Ot),"error")}},[e.id,N,f]),Ri=a.useCallback(async X=>{try{const We=await wr(X,n);r(We)}catch{f(`Failed to load dependency ${X}`,"error")}},[r,f]),Ti=a.useCallback(async X=>{me(!0);try{await ii(C.id,{prompt:X},n),f("Spec updated","success"),x&&(x.prompt=X)}catch(We){throw f(we(We),"error"),We}finally{me(!1)}},[C,x,f]),qr=a.useCallback(async X=>{Ee(!0);try{await My(e.id,X,n),f("AI revision requested. Task moved to planning.","success"),i()}catch(We){const lt=we(We);lt.includes("done")||lt.includes("archived")?f("Cannot request revision: Task must be in 'triage', 'todo', 'in-progress', or 'in-review' column.","error"):f(lt,"error")}finally{Ee(!1)}},[e.id,f,i]),Ys=a.useCallback(()=>{Te(!0),et(C.prompt||""),Xe("")},[C.prompt]),yi=a.useCallback(()=>{Te(!1),et(C.prompt||""),Xe("")},[C.prompt]),Xi=a.useCallback(async()=>{if(at===(C.prompt||"")){yi();return}Te(!1);try{await Ti(at)}catch(X){throw Te(!0),X}},[at,C.prompt,Ti,yi]),fl=a.useCallback(async()=>{Ve.trim()&&await qr(Ve.trim())},[Ve,qr]),gl=a.useCallback(X=>{X.key==="Escape"?(X.preventDefault(),yi()):X.key==="Enter"&&(X.ctrlKey||X.metaKey)&&(X.preventDefault(),Xi())},[yi,Xi]),Vr=s.filter(X=>X.id!==e.id&&!N.includes(X.id)).sort((X,We)=>{const lt=We.createdAt.localeCompare(X.createdAt);if(lt!==0)return lt;const Ot=parseInt(X.id.slice(X.id.lastIndexOf("-")+1),10)||0;return(parseInt(We.id.slice(We.id.lastIndexOf("-")+1),10)||0)-Ot}),Qs=ue?.name??e.assignedAgentId??null,mi=a.useMemo(()=>{const X=[];return C.modelProvider&&X.push(C.modelProvider),C.validatorModelProvider&&!X.includes(C.validatorModelProvider)&&X.push(C.validatorModelProvider),C.planningModelProvider&&!X.includes(C.planningModelProvider)&&X.push(C.planningModelProvider),X},[C.modelProvider,C.validatorModelProvider,C.planningModelProvider]),Zi=Uc[e.column]||[],Wr=["todo","in-progress"],Kr=e.column==="in-review"?Wr:Zi,ns=Kr[0],ea=Kr.slice(1),ms=ea.length>0,La=a.useCallback(()=>{ze(!1),un.current?.focus()},[]),Gr=a.useCallback(X=>{if(!ms){ns&&nt(ns);return}const We=X.currentTarget.querySelector(".detail-move-btn__arrow");if(!!(X.target instanceof Element&&X.target.closest(".detail-move-btn__arrow")||We&&X.clientX>0&&X.clientX>=We.getBoundingClientRect().left)){ze(Ot=>!Ot),Ge(!1);return}ns&&nt(ns)},[ms,ns,nt]),za=a.useCallback(X=>{!ms||!(X.key==="ArrowDown"||X.altKey&&X.key==="ArrowDown")||(X.preventDefault(),ze(!0),Ge(!1))},[ms]),ta=a.useCallback(X=>{X.key==="Escape"&&(X.preventDefault(),X.stopPropagation(),La())},[La]);a.useEffect(()=>{if(!ve)return;Nn.current?.querySelector(".detail-move-menu-item")?.focus()},[ve]);const Fa={"creating-pr":"Creating PR…","awaiting-pr-checks":"Awaiting PR checks","merging-pr":"Merging PR…"},hi=e.status?Fa[e.status]:void 0;return t.jsx("div",{className:"modal-overlay open",...zt,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg task-detail-modal",ref:mn,onDragOver:xs,onDrop:In,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:Bn[e.column]})]}),t.jsxs("div",{className:"modal-header-actions",children:[!Le&&fn&&t.jsx("button",{className:"modal-edit-btn",onClick:dn,title:"Edit task","aria-label":"Edit task",children:t.jsx(hs,{size:14})}),t.jsx("button",{className:"modal-close",onClick:i,"aria-label":"Close",children:"×"})]})]}),t.jsxs("div",{className:`detail-body${b==="logs"&&B==="agent-log"&&!Le?" detail-body--agent-log":""}`,children:[Le?t.jsx("div",{className:"modal-edit-form",children:t.jsx(xg,{mode:"edit",title:Ae,onTitleChange:Je,description:it,onDescriptionChange:ye,dependencies:ce,onDependenciesChange:Re,executorModel:be,onExecutorModelChange:Pe,validatorModel:Ye,onValidatorModelChange:$e,planningModel:ft,onPlanningModelChange:Z,thinkingLevel:re,onThinkingLevelChange:je,presetMode:rt,onPresetModeChange:te,selectedPresetId:qt,onSelectedPresetIdChange:Pt,selectedWorkflowSteps:At,onWorkflowStepsChange:Bt,pendingImages:xe,onImagesChange:Fe,tasks:s.filter(X=>X.id!==e.id),projectId:n,disabled:ct,addToast:f,isActive:Le,onAutoSaveDescription:es,reviewLevel:Ze,onReviewLevelChange:pt,priority:gt,onPriorityChange:wt,nodeId:Et,onNodeIdChange:mt,nodeOptions:yt,nodeOverrideDisabled:Hn,nodeOverrideDisabledReason:Hn?"Execution node override is locked while a task is active/in progress.":void 0,executionMode:Nt,onExecutionModeChange:Tt,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:Ft,onChange:X=>Dt(X.target.value),disabled:ct,"data-testid":"task-source-provider-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Repository (e.g. owner/repo)",value:Mt,onChange:X=>St(X.target.value),disabled:ct,"data-testid":"task-source-repository-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Issue identifier",value:Wt,onChange:X=>It(X.target.value),disabled:ct,"data-testid":"task-source-external-id-input"}),t.jsx("input",{type:"url",className:"modal-edit-input",placeholder:"Issue URL",value:Yt,onChange:X=>Rt(X.target.value),disabled:ct,"data-testid":"task-source-url-input"})]}),t.jsx("small",{children:"Leave all fields empty to clear source issue metadata."})]})})}):t.jsxs(t.Fragment,{children:[(()=>{const X=e.title||e.description||e.id,We=!L&&X.length>mc;return t.jsxs(t.Fragment,{children:[t.jsx("h2",{className:"detail-title",children:We?X.slice(0,mc)+"…":X}),X.length>mc&&t.jsx("button",{className:"detail-description-toggle",onClick:()=>$(!L),children:L?"Show less":"Show more"})]})})(),t.jsxs("div",{className:"detail-meta",children:["Created ",new Date(e.createdAt).toLocaleDateString()," · Updated"," ",new Date(e.updatedAt).toLocaleDateString()," ·",t.jsxs("span",{className:`detail-priority-chip detail-priority-chip--${Xa(e.priority)}`,children:["Priority: ",Xa(e.priority)]}),R&&t.jsxs("div",{className:"detail-provenance",children:[t.jsx(Ws,{"aria-hidden":"true"}),t.jsxs("span",{children:[C.sourceType==="agent_heartbeat"?t.jsxs(t.Fragment,{children:["Created by"," ",R.sourceAgentId?t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>_(R.sourceAgentId),children:R.label}):R.label]}):t.jsxs(t.Fragment,{children:["Created via ",R.label]}),R.parentTaskId&&t.jsxs(t.Fragment,{children:[" ","of"," ",t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>Ri(R.parentTaskId),children:R.parentTaskId})]}),R.contextInfo?` (${R.contextInfo})`:""]})]})]})]}),e.status==="failed"&&e.error&&t.jsxs("div",{className:"detail-error-alert",children:[t.jsx("span",{className:"detail-error-icon",children:"⚠"}),t.jsxs("div",{className:"detail-error-content",children:[t.jsx("div",{className:"detail-error-title",children:"Task Failed"}),t.jsx("div",{className:"detail-error-message",children:e.error})]})]}),!Le&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"detail-tabs",children:[t.jsx("button",{className:`detail-tab${b==="definition"?" detail-tab-active":""}`,onClick:()=>v("definition"),children:"Definition"}),t.jsx("button",{className:`detail-tab${b==="logs"?" detail-tab-active":""}`,onClick:()=>v("logs"),children:"Logs"}),(e.column==="in-progress"||e.column==="in-review"||e.column==="done")&&t.jsx("button",{className:`detail-tab${b==="changes"?" detail-tab-active":""}`,onClick:()=>v("changes"),children:"Changes"}),t.jsx("button",{className:`detail-tab${b==="comments"?" detail-tab-active":""}`,onClick:()=>v("comments"),children:"Comments"}),t.jsx("button",{className:`detail-tab${b==="documents"?" detail-tab-active":""}`,onClick:()=>v("documents"),children:"Documents"}),t.jsx("button",{className:`detail-tab${b==="model"?" detail-tab-active":""}`,onClick:()=>v("model"),children:"Model"}),t.jsx("button",{className:`detail-tab${b==="workflow"?" detail-tab-active":""}`,onClick:()=>v("workflow"),children:"Workflow"}),t.jsx("button",{className:`detail-tab${b==="stats"?" detail-tab-active":""}`,onClick:()=>v("stats"),children:"Stats"}),t.jsx("button",{className:`detail-tab${b==="routing"?" detail-tab-active":""}`,onClick:()=>v("routing"),children:"Routing"}),ut.map((X,We)=>{const lt=`plugin-${We}`;return t.jsx("button",{className:`detail-tab${b===lt?" detail-tab-active":""}`,onClick:()=>v(lt),children:X.slot.label},`plugin-tab-${X.pluginId}`)})]}),b==="workflow"?t.jsx("div",{className:"detail-section",children:t.jsx(TA,{taskId:e.id,results:hn,loading:is,enabledWorkflowSteps:nn,canEdit:fn,projectId:n,isTaskInProgress:e.column==="in-progress"&&e.status!=="paused",onWorkflowStepsChange:vs})}):b==="model"?t.jsx("div",{className:"detail-section",children:t.jsx(hA,{task:e,addToast:f,onTaskUpdated:h,settings:Lt})}):b==="logs"?t.jsxs("div",{className:`detail-section${B==="agent-log"?" detail-section--agent-log":""}`,children:[t.jsxs("div",{className:"log-subview-toggle",children:[t.jsx("button",{className:`log-subview-btn${B==="activity"?" log-subview-btn-active":""}`,onClick:()=>K("activity"),children:"Activity"}),t.jsx("button",{className:`log-subview-btn${B==="agent-log"?" log-subview-btn-active":""}`,onClick:()=>K("agent-log"),children:"Agent Log"})]}),B==="agent-log"?t.jsx(lA,{entries:M,loading:le,executorModel:qA(e,Lt),validatorModel:VA(e,Lt),planningModel:KA(e,M,Lt),hasMore:Qe,onLoadMore:Se,loadingMore:bt,totalCount:ht}):t.jsxs("div",{className:"detail-activity",children:[t.jsx("h4",{children:"Activity"}),C.activityLogTruncatedCount?t.jsxs("div",{className:"detail-log-truncated",children:["Showing the most recent ",C.log.length," activity entries."]}):null,C.log&&C.log.length>0?t.jsx("div",{className:"detail-activity-list",children:[...C.log].reverse().map((X,We)=>t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-timestamp",children:JA(X.timestamp)}),t.jsx("span",{className:"detail-log-action",children:X.action})]}),X.outcome&&t.jsx("div",{className:"detail-log-outcome",children:X.outcome})]},We))}):t.jsx("div",{className:"detail-log-empty",children:"(no activity)"})]})]}):b==="changes"?t.jsx(wA,{taskId:e.id,worktree:e.worktree,projectId:n,column:e.column,mergeDetails:e.mergeDetails,modifiedFiles:e.modifiedFiles}):b==="comments"?t.jsx(xA,{task:e,addToast:f,projectId:n,onTaskUpdated:h}):b==="documents"?t.jsx(OA,{taskId:e.id,addToast:f,projectId:n,onTaskUpdated:h,canEdit:fn}):typeof b=="string"&&b.startsWith("plugin-")?t.jsx("div",{className:"detail-section",children:t.jsx(al,{slotId:"task-detail-tab",projectId:n})}):b==="stats"?t.jsx("div",{className:"detail-section",children:t.jsx(BA,{tokenUsage:C.tokenUsage,loading:w,task:C})}):b==="routing"?t.jsx("div",{className:"detail-section",children:t.jsx(DA,{task:e,settings:Lt,addToast:f,onTaskUpdated:h})}):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(li,{remarkPlugins:[ci],children:e.summary})})]}),t.jsx(yA,{task:e}),e.sourceIssue&&t.jsxs("div",{className:"detail-section detail-source-section",children:[t.jsxs("div",{className:"detail-source-header",children:[t.jsxs("div",{className:"detail-source-summary",children:[t.jsx("span",{className:"detail-source-label",children:"Source issue"}),e.sourceIssue.url?t.jsx("a",{className:"detail-source-link detail-source-number",href:e.sourceIssue.url,target:"_blank",rel:"noopener noreferrer",children:`(#${e.sourceIssue.issueNumber})`}):t.jsx("span",{className:"detail-source-number",children:`(#${e.sourceIssue.issueNumber})`})]}),t.jsx("button",{type:"button",className:"detail-source-toggle","aria-expanded":dt,"aria-label":dt?"Collapse source issue details":"Expand source issue details",onClick:()=>Zt(X=>!X),children:t.jsx(xn,{size:16,className:dt?"detail-source-chevron--expanded":void 0})})]}),dt&&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:[mi.length>0&&t.jsx("span",{className:"detail-provider-icons","data-testid":"detail-provider-icons",children:mi.map(X=>t.jsx(An,{provider:X,size:"sm"},X))}),t.jsxs("span",{className:"detail-meta-label",children:[t.jsx(Sn,{size:14,style:{verticalAlign:"middle",marginRight:6}}),"Agent"]})]}),t.jsxs("div",{className:"detail-agent-actions",children:[Qs?t.jsxs("span",{className:"detail-agent-chip",children:[t.jsx(Sn,{size:14}),Qs,t.jsx("button",{className:"detail-agent-clear",onClick:()=>void $n(),title:"Unassign agent",children:t.jsx(Ht,{size:12})})]}):t.jsx("button",{className:"btn btn-sm",onClick:()=>{O?ne(!1):zs()},children:"Assign Agent"}),O&&t.jsxs("div",{className:"agent-picker-dropdown",children:[Q&&t.jsx("div",{className:"agent-picker-loading",children:"Loading agents..."}),!Q&&W.filter(X=>X.state!=="terminated").map(X=>t.jsxs("button",{className:`agent-picker-item${e.assignedAgentId===X.id?" selected":""}`,onClick:()=>void ys(X.id),children:[t.jsx(Sn,{size:14}),t.jsx("span",{className:"agent-picker-name",children:X.name}),t.jsx("span",{className:"agent-picker-role",children:X.role})]},X.id)),!Q&&W.filter(X=>X.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"}),C.steps&&C.steps.length>0?t.jsxs("div",{className:"step-progress-wrapper",children:[t.jsx("div",{className:"step-progress-bar",children:C.steps.map((X,We)=>t.jsx("div",{className:`step-progress-segment step-progress-segment--${X.status}`,"data-tooltip":`${X.name} (${X.status})`,style:{backgroundColor:GA(X.status)}},We))}),t.jsxs("span",{className:"step-progress-label",children:[C.steps.filter(X=>X.status==="done").length,"/",C.steps.length," step",C.steps.length===1?"":"s"]})]}):t.jsx("div",{className:"step-progress-empty",children:"(no steps defined)"})]}),t.jsxs("div",{className:"detail-section",children:[!Ue&&t.jsx("div",{className:"detail-spec-edit-trigger",children:t.jsx("button",{className:"btn btn-sm",onClick:Ys,children:"Edit"})}),Ue?t.jsxs("div",{className:"spec-editor-edit-mode",children:[t.jsx("textarea",{className:"spec-editor-textarea",value:at,onChange:X=>et(X.target.value),onKeyDown:gl,disabled:de,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:yi,disabled:de,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Xi(),disabled:at===(C.prompt||"")||de,children:de?"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:Ve,onChange:X=>Xe(X.target.value),placeholder:"e.g., 'Add more details about error handling', 'Split this into smaller steps', 'Include tests for the API endpoints'...",disabled:ie,rows:4,maxLength:2e3}),t.jsxs("div",{className:"spec-editor-revision-actions",children:[t.jsxs("span",{className:"spec-editor-char-count",children:[Ve.length,"/2000"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void fl(),disabled:!Ve.trim()||ie,children:ie?"Requesting…":"Request AI Revision"})]})]})]}):w?t.jsx("div",{className:"spec-loading",children:"Loading specification…"}):C.prompt?t.jsx("div",{className:"markdown-body",children:t.jsx(li,{remarkPlugins:[ci],children:C.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"}),U.length>0?t.jsx("div",{className:"detail-attachments-grid",children:U.map(X=>{const We=oi(`/api/tasks/${e.id}/attachments/${X.filename}`);return t.jsxs("div",{className:"detail-attachment-card",children:[t.jsx("a",{className:"detail-attachment-link",href:We,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{src:We,alt:X.originalName,className:"detail-attachment-image"})}),t.jsxs("div",{className:"detail-attachment-meta",children:[X.originalName," (",YA(X.size),")"]}),t.jsx("button",{className:"detail-attachment-delete",onClick:()=>Gn(X.filename),title:"Delete attachment",children:"×"})]},X.filename)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no attachments)"}),t.jsx("input",{className:"detail-hidden-file-input",ref:Qt,type:"file",accept:"image/*",onChange:Kn}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Qt.current?.click(),disabled:Y,children:Y?"Uploading…":"Attach Screenshot"})]}),t.jsxs("div",{className:"detail-deps",children:[t.jsx("h4",{children:"Dependencies"}),N.length>0?t.jsx("ul",{className:"detail-dep-list",children:N.map(X=>{const We=s.find(Ot=>Ot.id===X),lt=We?.title||We?.description||X;return t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>Ri(X),onKeyDown:Ot=>{(Ot.key==="Enter"||Ot.key===" ")&&(Ot.preventDefault(),Ri(X))},role:"link",tabIndex:0,title:`Click to view ${X}`,children:[t.jsx("span",{className:"detail-dep-id",children:X}),t.jsx("span",{className:"detail-dep-label",children:ph(lt,40)})]}),t.jsx("button",{className:"dep-remove-btn",onClick:Ot=>Fs(Ot,X),title:`Remove dependency ${X}`,children:"×"})]},X)})}):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:()=>{T&&J(""),k(X=>!X)},children:"Add Dependency"}),T&&(()=>{const X=H.toLowerCase(),We=X?Vr.filter(lt=>lt.id.toLowerCase().includes(X)||lt.title&&lt.title.toLowerCase().includes(X)||lt.description&&lt.description.toLowerCase().includes(X)):Vr;return t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:H,onChange:lt=>J(lt.target.value),onClick:lt=>lt.stopPropagation()}),We.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):We.map(lt=>t.jsxs("div",{className:"dep-dropdown-item",onClick:()=>{Jn(lt.id),k(!1)},children:[t.jsx("span",{className:"dep-dropdown-id",children:lt.id}),t.jsx("span",{className:"dep-dropdown-title",children:ph(lt.title||lt.description||lt.id,30)})]},lt.id))]})})()]})]}),e.column==="in-review"&&t.jsx(fA,{taskId:e.id,projectId:n,prInfo:e.prInfo,automationStatus:e.status??null,autoMerge:Lt?.autoMerge??!1,prAuthAvailable:p??!1,onPrCreated:X=>{e.prInfo=X,f(`PR #${X.number} created`,"success")},onPrUpdated:X=>{e.prInfo=X},addToast:f})]})]})]}),t.jsx("div",{className:"modal-actions",children:Le?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:_n,disabled:ct,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:zn,disabled:ct,children:ct?"Saving…":"Save"})]}):t.jsxs(t.Fragment,{children:[e.column==="triage"&&e.status==="awaiting-approval"&&C.prompt&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:jt,children:"Approve Plan"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:kt,children:"Reject Plan"})]}),e.column==="triage"&&e.status!=="awaiting-approval"&&!j&&t.jsx("button",{className:"btn btn-sm btn-danger",onClick:ts,"aria-label":"Delete task",title:"Delete task",children:"Delete"}),(e.column!=="triage"||e.status==="awaiting-approval"||j||e.paused)&&t.jsxs("div",{className:"detail-actions-dropdown",ref:Kt,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>{Ge(X=>!X),ze(!1)},"aria-haspopup":"menu","aria-expanded":Oe,children:["Actions",t.jsx(Xt,{size:12})]}),Oe&&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:()=>$t(ts),children:"Delete"}),m&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>$t(_e),children:"Duplicate"}),(e.column==="done"||e.column==="in-review")&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>$t(sn),children:"Refine"}),t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>$t(gn),children:"Respecify"}),j&&u&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>$t(Js),children:"Retry"}),d&&e.column!=="done"&&e.column!=="archived"&&t.jsx("button",{className:"detail-actions-menu-item detail-actions-menu-item-danger",role:"menuitem",onClick:()=>$t(ae),children:"Reset"}),e.column!=="done"&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>$t(tt),children:e.paused?"Unpause":"Pause"})]})]}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("div",{className:"detail-move-dropdown",ref:Nn,children:e.column==="in-review"?t.jsxs("div",{className:"detail-move-actions-in-review",children:[t.jsxs("div",{children:[t.jsxs("button",{ref:un,className:"btn btn-primary btn-sm detail-move-btn",onClick:Gr,onKeyDown:za,disabled:!ns,"aria-label":ns?`Move to ${Bn[ns]}`:void 0,"aria-haspopup":ms?"menu":void 0,"aria-expanded":ms?ve:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",ns?Bn[ns]:""]}),ms&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(Xt,{size:12})})]}),ve&&ms&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:ta,children:ea.map(X=>t.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>nt(X),onKeyDown:ta,children:X==="in-progress"?"Back to In Progress":`Move to ${Bn[X]}`},X))})]}),hi?t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!0,children:hi}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Tn,children:"Merge & Close"})]}):t.jsxs("div",{children:[t.jsxs("button",{ref:un,className:"btn btn-primary btn-sm detail-move-btn",onClick:Gr,onKeyDown:za,disabled:!ns,"aria-label":ns?`Move to ${Bn[ns]}`:void 0,"aria-haspopup":ms?"menu":void 0,"aria-expanded":ms?ve:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",ns?Bn[ns]:""]}),ms&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(Xt,{size:12})})]}),ve&&ms&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:ta,children:ea.map(X=>t.jsxs("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>nt(X),onKeyDown:ta,children:["Move to ",Bn[X]]},X))})]})})]})}),De&&t.jsx("div",{className:"modal-overlay open detail-refine-overlay",onClick:qn,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal detail-refine-modal",onClick:X=>X.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{className:"detail-refine-title",children:"Refine"}),t.jsx("button",{className:"modal-close",onClick:qn,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"detail-body",children:[t.jsx("p",{className:"detail-refine-help",children:"Describe what needs to be refined or improved..."}),t.jsx("textarea",{className:"detail-refine-textarea",value:oe,onChange:X=>Ne(X.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:[oe.length,"/2000 characters"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:On,disabled:!oe.trim()||se,children:se?"Creating...":"Create Refinement Task"})]})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:qn,disabled:se,children:"Cancel"})})]})}),z&&t.jsx(a.Suspense,{fallback:null,children:t.jsx(eR,{agentId:z,projectId:n,onClose:()=>_(null),addToast:f})})]})})}const iR=640;function aR({isOpen:e,onClose:n,onImport:s,tasks:i,projectId:r}){const[o,l]=a.useState(""),[c,u]=a.useState(""),[d,m]=a.useState(""),[h,f]=a.useState(!1),[p,g]=a.useState("issues"),[b,v]=a.useState([]),[x,y]=a.useState(null),[w,E]=a.useState([]),[C,j]=a.useState(null),[A,S]=a.useState(null),[z,_]=a.useState(!1),[R,B]=a.useState([]),[K,L]=a.useState(!1),[$,U]=a.useState(""),G=a.useRef(!1),Y=a.useRef(null);di(Y,e,"fusion:github-modal-size");const ee=Mi(n),[N,I]=a.useState(!1),[T,k]=a.useState("list"),H=a.useRef(null),J=new Set;for(const pe of i){const Ae=pe.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);Ae&&J.add(Ae[1]);const Je=pe.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);Je&&J.add(Je[1])}a.useEffect(()=>{if(e)return l(""),u(""),m(""),v([]),y(null),E([]),j(null),g("issues"),S(null),_(!1),B([]),L(!0),U(""),H.current=null,G.current=!0,Qy().then(pe=>{if(G.current)if(B(pe),L(!1),pe.length===1){const Ae=pe[0];l(Ae.owner),u(Ae.repo),U(Ae.name)}else pe.length>1&&(l(""),u(""),U(""))}).catch(()=>{G.current&&L(!1)}),()=>{G.current=!1}},[e]);const ue=a.useCallback(pe=>{if(U(pe),pe==="")l(""),u("");else{const Ae=R.find(Je=>Je.name===pe);Ae&&(l(Ae.owner),u(Ae.repo))}},[R]),fe=a.useCallback(async()=>{if(!o.trim()||!c.trim()){S("Repository must be selected");return}f(!0),S(null),v([]),y(null);try{const pe=d.split(",").map(Je=>Je.trim()).filter(Boolean),Ae=await Ky(o.trim(),c.trim(),30,pe.length>0?pe:void 0);v(Ae),Ae.length===0&&S("No open issues found")}catch(pe){S(we(pe)||"Failed to fetch issues")}finally{f(!1)}},[o,c,d]),W=a.useCallback(async()=>{if(!o.trim()||!c.trim()){S("Repository must be selected");return}f(!0),S(null),E([]),j(null);try{const pe=await Jy(o.trim(),c.trim(),30);E(pe),pe.length===0&&S("No open pull requests found")}catch(pe){S(we(pe)||"Failed to fetch pull requests")}finally{f(!1)}},[o,c]);a.useEffect(()=>{if(!e||!o.trim()||!c.trim()||h||z)return;const pe={owner:o.trim(),repo:c.trim(),labels:d.trim(),tab:p};H.current?.owner===pe.owner&&H.current?.repo===pe.repo&&H.current?.labels===pe.labels&&H.current?.tab===pe.tab||(H.current=pe,p==="issues"?fe():W())},[o,c,d,p,e,h,z,fe,W]),a.useEffect(()=>{if(!e)return;const pe=Ae=>{Ae.key==="Escape"&&n()};return document.addEventListener("keydown",pe),()=>document.removeEventListener("keydown",pe)},[e,n]),a.useEffect(()=>{if(!e)return;const pe=()=>{I(window.innerWidth<=iR)};return pe(),window.addEventListener("resize",pe),()=>window.removeEventListener("resize",pe)},[e]);const he=a.useCallback(pe=>{y(pe),N&&k("preview")},[N]),O=a.useCallback(pe=>{j(pe),N&&k("preview")},[N]),ne=a.useCallback(()=>{k("list")},[]),Q=a.useCallback(async()=>{if(p==="issues"){if(x===null)return;_(!0),S(null);try{const pe=await Gy(o.trim(),c.trim(),x,r);s(pe),y(null),N&&T==="preview"&&k("list")}catch(pe){const Ae=we(pe);Ae?.includes("already imported")?S(Ae):S(Ae||"Failed to import issue")}finally{_(!1)}}else{if(C===null)return;_(!0),S(null);try{const pe=await Yy(o.trim(),c.trim(),C,r);s(pe),j(null),N&&T==="preview"&&k("list")}catch(pe){const Ae=we(pe);Ae?.includes("already imported")?S(Ae):S(Ae||"Failed to import pull request")}finally{_(!1)}}},[p,x,C,o,c,s,N,T]),ge=b.find(pe=>pe.number===x),de=w.find(pe=>pe.number===C);if(!e)return null;const me=R.length>0,ie=R.length===1,Ee=b.filter(pe=>J.has(pe.html_url)).length,Ue=w.filter(pe=>J.has(pe.html_url)).length,Te=A==="No open issues found",at=A==="No open pull requests found",et=p==="issues"?Te:at,Ve=!!A&&!Te&&b.length===0&&!h,Xe=!!A&&!at&&w.length===0&&!h,De=p==="issues"?Ve:Xe,Be=h||b.length>0||Te||Ve,oe=h||w.length>0||at||Xe,Ne=p==="issues"?Be:oe,se=!!A&&b.length>0&&!Te,Me=!!A&&w.length>0&&!at,Le=p==="issues"?se:Me;return t.jsx("div",{className:"modal-overlay open",...ee,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg github-import-modal",ref:Y,children:[t.jsxs("div",{className:"modal-header github-import-modal__header",children:[t.jsxs("div",{children:[t.jsx("h3",{children:"Import from GitHub"}),t.jsx("p",{className:"github-import-modal__subtitle",children:"Choose a detected remote, load open issues or pull requests, and import one into the board."})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close import modal",children:"×"})]}),t.jsxs("div",{className:"modal-body github-import-modal__body",children:[t.jsxs("div",{className:"github-import-tabs",role:"tablist","aria-label":"Import type",children:[t.jsxs("button",{role:"tab","aria-selected":p==="issues","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="issues"?"active":""}`,onClick:()=>{g("issues"),j(null)},disabled:h||z,children:[t.jsx(Yo,{size:16}),t.jsx("span",{children:"Issues"})]}),t.jsxs("button",{role:"tab","aria-selected":p==="pulls","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="pulls"?"active":""}`,onClick:()=>{g("pulls"),y(null)},disabled:h||z,children:[t.jsx(Es,{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(ot,{size:16,className:"spin"}),t.jsx("span",{children:"Detecting…"})]}):me?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:R[0].name}),t.jsxs("span",{className:"github-import-remote-pill__repo",children:[R[0].owner,"/",R[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:$,onChange:pe=>ue(pe.target.value),disabled:h||z,"aria-label":"Select Git remote",children:[t.jsx("option",{value:"",children:"Select remote…"}),R.map(pe=>t.jsxs("option",{value:pe.name,children:[pe.name," (",pe.owner,"/",pe.repo,")"]},pe.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:pe=>m(pe.target.value),onKeyDown:pe=>pe.key==="Enter"&&fe(),disabled:h||z||!me,"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"?fe:W,disabled:h||z||!o.trim()||!c.trim(),"aria-label":h?`Loading ${p}`:`Load ${p} from repository`,title:h?"Loading…":`Load ${p}`,children:[h?t.jsx(ot,{size:14,className:"spin"}):t.jsx(Ln,{size:14}),t.jsx("span",{children:h?"Loading…":"Load"})]})})]}),!K&&!me&&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"})]}),Le&&t.jsx("div",{className:"form-error github-import-banner",role:"alert",children:A}),t.jsxs("div",{className:"github-import-workspace",children:[t.jsxs("section",{className:`github-import-list-pane ${N?"mobile":""} ${T==="list"?"active":""}`,"data-testid":"github-import-list-pane","aria-labelledby":"github-import-results-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[t.jsx("h4",{id:"github-import-results-heading",children:p==="issues"?"Issues":"Pull Requests"}),p==="issues"&&b.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[b.length," issue",b.length===1?"":"s"]}),t.jsxs("span",{children:[Ee," imported"]})]}),p==="pulls"&&w.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[w.length," pull request",w.length===1?"":"s"]}),t.jsxs("span",{children:[Ue," imported"]})]})]}),t.jsxs("div",{className:"github-import-pane-content",children:[!Ne&&t.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-results-idle",children:t.jsxs("div",{children:[t.jsx("strong",{children:"Nothing loaded yet"}),t.jsx("span",{children:"Select a repository and click Load to start reviewing import candidates."})]})}),h&&t.jsxs("div",{className:"github-import-state github-import-state--loading",role:"status","aria-live":"polite",children:[t.jsx(ot,{size:16,className:"spin"}),t.jsxs("div",{children:[t.jsxs("strong",{children:["Loading open ",p==="issues"?"issues":"pull requests","…"]}),t.jsx("span",{children:"Fetching the latest list from GitHub."})]})]}),De&&t.jsx("div",{className:"github-import-state github-import-state--error",role:"alert",children:t.jsxs("div",{children:[t.jsxs("strong",{children:["Could not load ",p==="issues"?"issues":"pull requests"]}),t.jsx("span",{children:A})]})}),et&&t.jsx("div",{className:"github-import-state github-import-state--empty",role:"status",children:t.jsxs("div",{children:[t.jsxs("strong",{children:["No open ",p==="issues"?"issues":"pull requests"," found"]}),t.jsx("span",{children:p==="issues"?"Try a different label filter or choose another repository.":"Choose another repository."})]})}),p==="issues"&&b.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:b.map(pe=>{const Ae=J.has(pe.html_url);return t.jsxs("div",{className:`issue-item ${x===pe.number?"selected":""} ${Ae?"imported":""}`,onClick:()=>!Ae&&he(pe.number),children:[t.jsx("input",{type:"radio",name:"issue",checked:x===pe.number,onChange:()=>he(pe.number),disabled:Ae,"aria-label":`Select issue #${pe.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",pe.number]}),t.jsx("span",{className:"issue-title",children:pe.title})]}),pe.labels.length>0&&t.jsx("span",{className:"issue-labels",children:pe.labels.map(Je=>t.jsx("span",{className:"label-chip",children:Je.name},Je.name))})]}),Ae&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},pe.number)})}),p==="pulls"&&w.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:w.map(pe=>{const Ae=J.has(pe.html_url);return t.jsxs("div",{className:`issue-item ${C===pe.number?"selected":""} ${Ae?"imported":""}`,onClick:()=>!Ae&&O(pe.number),children:[t.jsx("input",{type:"radio",name:"pull",checked:C===pe.number,onChange:()=>O(pe.number),disabled:Ae,"aria-label":`Select pull request #${pe.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",pe.number]}),t.jsx("span",{className:"issue-title",children:pe.title})]}),t.jsxs("span",{className:"pull-branch-info",children:[pe.headBranch," → ",pe.baseBranch]})]}),Ae&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},pe.number)})})]})]}),t.jsxs("section",{className:`github-import-preview-pane ${N?"mobile":""} ${T==="preview"?"active":""}`,"data-testid":"github-import-preview-pane","aria-labelledby":"github-import-preview-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[N&&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(_a,{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"&&ge?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Issue #",ge.number]}),t.jsx("div",{className:"preview-title",children:ge.title}),t.jsx("div",{className:"preview-body",children:ge.body?ge.body.slice(0,200)+(ge.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"&&de?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Pull Request #",de.number]}),t.jsx("div",{className:"preview-title",children:de.title}),t.jsxs("div",{className:"preview-branch",children:[t.jsx("strong",{children:"Branch:"})," ",de.headBranch," → ",de.baseBranch]}),t.jsx("div",{className:"preview-body",children:de.body?de.body.slice(0,200)+(de.body.length>200?"…":""):"(no description)"})]}):p==="pulls"?t.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-preview-empty",children:t.jsxs("div",{children:[t.jsx("strong",{children:"No pull request selected"}),t.jsx("span",{children:"Choose a pull request from the list to inspect its details."})]})}):null]})]})]})]}),t.jsxs("div",{className:"modal-actions github-import-modal__actions",children:[t.jsx("button",{className:"btn",onClick:n,disabled:z,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:Q,disabled:(p==="issues"?x===null:C===null)||z,children:z?t.jsx(ot,{size:14,className:"spin"}):"Import"})]})]})})}function rR({summary:e,children:n,className:s="",onToggle:i}){const[r,o]=a.useState(!1);return t.jsxs("div",{className:`onboarding-disclosure ${s}`.trim(),children:[t.jsxs("button",{className:"onboarding-disclosure-trigger",onClick:()=>{const l=!r;o(l),i?.(l)},"aria-expanded":r,type:"button",children:[t.jsx(xn,{size:14,className:"onboarding-disclosure-chevron","aria-hidden":"true"}),t.jsx("span",{children:e})]}),r?t.jsx("div",{className:"onboarding-disclosure-content",children:n}):null]})}const oR=["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 lR(e,n){return e&&n?`${e}/${n}`:""}function cR(e){if(!e)return{provider:void 0,modelId:void 0};const n=e.indexOf("/");return n===-1?{provider:void 0,modelId:void 0}:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function dR({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"}),[f,p]=a.useState(null),[g,b]=a.useState([]),[v,x]=a.useState([]),[y,w]=a.useState(null),E=a.useRef(!1),C=a.useRef(!1),[j,A]=a.useState(""),[S,z]=a.useState(!0),[_,R]=a.useState(!1),[B,K]=a.useState(!1),[L,$]=a.useState(null),[U,G]=a.useState(0),Y=a.useRef(null),ee=a.useRef(null),N=a.useRef(null),I=a.useRef(null),T=a.useRef(null),[k,H]=a.useState(c??null),J=a.useMemo(()=>Yi(),[]),{isLockedByOther:ue,takeControl:fe,isLoading:W}=cl(e?k:null),{activeTabMap:he,broadcastUpdate:O,broadcastCompleted:ne,broadcastLock:Q,broadcastUnlock:ge,broadcastHeartbeat:de}=Ia(),[me,ie]=a.useState(void 0),[Ee,Ue]=a.useState(void 0),[Te,at]=a.useState([]),[et,Ve]=a.useState(!1),[Xe,De]=a.useState(null),[Be,oe]=a.useState([]),[Ne,se]=a.useState([]),Me=a.useRef(null),[Le,pe]=a.useState([]),[Ae,Je]=a.useState(!1),[it,ye]=a.useState(c??null),[ce,Re]=a.useState(!!c),[be,Pe]=a.useState(null),[Ye,$e]=a.useState(!1),ft=a.useRef(!1),Z=a.useRef(null);di(ee,e,"fusion:planning-modal-size"),a.useEffect(()=>{const F=Z.current;if(!F)return;F.scrollHeight-F.scrollTop-F.clientHeight<32&&(F.scrollTop=F.scrollHeight)},[j]),a.useEffect(()=>{if(m.type!=="loading"){$(null),G(0);return}const F=Date.now();$(F),G(0);const ve=setInterval(()=>{G(Math.max(0,Math.floor((Date.now()-F)/1e3)))},1e3);return()=>clearInterval(ve)},[m.type]),a.useEffect(()=>{if(m.type!=="loading")return;const F=I.current;if(!F)return;let ve=!1;const Oe=setInterval(async()=>{try{const Ge=await ai(F);if(ve||!Ge||I.current!==F)return;if(Ge.status==="awaiting_input"&&Ge.currentQuestion){const dt=JSON.parse(Ge.currentQuestion);h({type:"question",session:{sessionId:F,currentQuestion:dt,summary:null}}),A("")}else if(Ge.status==="complete"&&Ge.result){const dt=JSON.parse(Ge.result);h({type:"summary",session:{sessionId:F,currentQuestion:null,summary:dt},summary:dt}),w(dt),A("")}}catch{}},8e3);return()=>{ve=!0,clearInterval(Oe)}},[m.type]);const re=a.useCallback(()=>{d(""),h({type:"initial"}),p(null),b([]),x([]),w(null),A(""),R(!1),K(!1),ie(void 0),Ue(void 0),I.current=null,H(null)},[]),je=lR(me,Ee),rt=a.useCallback((F,ve)=>{if(!F||!ve)return"Using default";const ze=Te.find(Oe=>Oe.provider===F&&Oe.id===ve);return ze?`${ze.provider}/${ze.id}`:`${F}/${ve}`},[Te]),te=a.useCallback(async()=>{Ve(!0),De(null);try{const F=await bs();at(F.models),oe(F.favoriteProviders),se(F.favoriteModels)}catch(F){De(we(F)||"Failed to load models")}finally{Ve(!1)}},[]),Ze=a.useCallback(F=>{oe(ve=>{const ze=ve,Ge=ze.includes(F)?ze.filter(dt=>dt!==F):[F,...ze];return pn({favoriteProviders:Ge,favoriteModels:Ne}).catch(()=>{oe(ze)}),Ge})},[Ne]),pt=a.useCallback(F=>{se(ve=>{const ze=ve,Ge=ze.includes(F)?ze.filter(dt=>dt!==F):[F,...ze];return pn({favoriteProviders:Be,favoriteModels:Ge}).catch(()=>{se(ze)}),Ge})},[Be]),gt=a.useCallback(F=>{N.current?.close();const ve=()=>I.current!==F,ze=Qj(F,l,{onThinking:Oe=>{ve()||(A(Ge=>Ge+Oe),O({sessionId:F,status:"generating",needsInput:!1,owningTabId:J,type:"planning",title:u.trim()||void 0,projectId:l??null}))},onQuestion:Oe=>{ve()||(R(!1),K(!1),ra(l),h({type:"question",session:{sessionId:F,currentQuestion:Oe,summary:null}}),A(""),O({sessionId:F,status:"awaiting_input",needsInput:!0,owningTabId:J,type:"planning",title:u.trim()||void 0,projectId:l??null}))},onSummary:Oe=>{ve()||(R(!1),K(!1),ra(l),h({type:"summary",session:{sessionId:F,currentQuestion:null,summary:Oe},summary:Oe}),w(Oe),A(""),O({sessionId:F,status:"complete",needsInput:!1,owningTabId:J,type:"planning",title:u.trim()||void 0,projectId:l??null}))},onError:Oe=>{const Ge=Oe||"Session failed while contacting the AI.";R(!0),(async()=>{try{const dt=await ai(F);if(dt&&(dt.status==="generating"||dt.status==="awaiting_input")){gt(F);return}}catch{}R(!1),K(!1),p(null),h(dt=>dt.type==="question"||dt.type==="summary"||dt.type==="error"?{type:"error",session:dt.session,errorMessage:Ge}:{type:"error",session:{sessionId:F,currentQuestion:null,summary:null},errorMessage:Ge}),A(""),I.current=F,O({sessionId:F,status:"error",needsInput:!1,owningTabId:J,type:"planning",title:u.trim()||void 0,projectId:l??null}),ne({sessionId:F,status:"error"})})()},onComplete:()=>{R(!1),K(!1),I.current=null,ne({sessionId:F,status:"complete"})},onConnectionStateChange:Oe=>{R(Oe==="reconnecting")}});N.current=ze},[ne,O,u,l,J]),wt=a.useCallback(async F=>{const ve=F??u;if(ve.trim()){p(null),A(""),x([]),b([]),R(!1),h({type:"loading"});try{const ze=me&&Ee?{planningModelProvider:me,planningModelId:Ee}:void 0,{sessionId:Oe}=await Pj(ve.trim(),l,ze);I.current=Oe,H(Oe),ye(Oe),gt(Oe),b([])}catch(ze){R(!1),p(we(ze)||"Failed to start planning session"),h({type:"initial"}),I.current=null,H(null)}}},[gt,u,Ee,me,l]);a.useEffect(()=>{e&&m.type==="initial"&&Y.current?.focus()},[e,m.type]),a.useEffect(()=>{e&&te()},[e,te]),a.useEffect(()=>{if(e&&o&&!E.current&&m.type==="initial"){d(o);const F=setTimeout(()=>{E.current=!0,wt(o)},0);return()=>clearTimeout(F)}else if(e&&!o&&!E.current&&!C.current&&m.type==="initial"){C.current=!0;const F=Q1(l);F&&d(F)}},[e,o,m.type,wt,l]);const Et=a.useCallback(async F=>{N.current?.close(),N.current=null,p(null),A(""),b([]),x([]),w(null),K(!1),h({type:"loading"});try{const ve=await ai(F);if(!ve){ye(null),Re(!1),h({type:"initial"});return}I.current=F,H(F);const ze=ya(ve.conversationHistory);if(x(ze),b(ze.map(Oe=>Oe.response).filter(Oe=>!!(Oe&&typeof Oe=="object"&&!Array.isArray(Oe)))),ve.status==="awaiting_input"&&ve.currentQuestion){ra(l);const Oe=JSON.parse(ve.currentQuestion);h({type:"question",session:{sessionId:F,currentQuestion:Oe,summary:null}}),ve.thinkingOutput&&A(ve.thinkingOutput),gt(F)}else if(ve.status==="complete"&&ve.result){ra(l);const Oe=JSON.parse(ve.result);h({type:"summary",session:{sessionId:F,currentQuestion:null,summary:Oe},summary:Oe}),w(Oe)}else ve.status==="generating"?(h({type:"loading"}),ve.thinkingOutput&&A(ve.thinkingOutput),gt(F)):ve.status==="error"&&h({type:"error",session:{sessionId:F,currentQuestion:null,summary:null},errorMessage:ve.error||"Session failed"})}catch{p("Failed to load session"),h({type:"initial"})}},[gt,l]);a.useEffect(()=>{!e||!c||I.current!==c&&T.current!==c&&(ye(c),Re(!0),Et(c))},[e,c]),a.useEffect(()=>{e&&it&&(c&&c===it||Et(it))},[e]);const mt=a.useCallback(async()=>{Je(!0);try{const ve=(await xd(l,{includeCompleted:!0,includeArchived:Ye})).filter(ze=>ze.type==="planning").sort((ze,Oe)=>Date.parse(Oe.updatedAt)-Date.parse(ze.updatedAt));pe(ve)}catch{}finally{Je(!1)}},[l,Ye]);a.useEffect(()=>{e&&mt()},[e,mt]),a.useEffect(()=>{if(!e)return;const F=l?`?projectId=${encodeURIComponent(l)}`:"",ve=Oe=>{try{const Ge=JSON.parse(Oe.data);if(Ge.type!=="planning")return;pe(dt=>{const Zt=dt.findIndex(un=>un.id===Ge.id);return(Zt>=0?[...dt.slice(0,Zt),Ge,...dt.slice(Zt+1)]:[Ge,...dt]).sort((un,Kt)=>Date.parse(Kt.updatedAt)-Date.parse(un.updatedAt))})}catch{}},ze=Oe=>{try{const Ge=JSON.parse(Oe.data);pe(dt=>dt.filter(Zt=>Zt.id!==Ge))}catch{}};return Gs(`/api/events${F}`,{events:{"ai_session:updated":ve,"ai_session:deleted":ze},onReconnect:()=>{mt()}})},[e,l,mt]);const Nt=a.useCallback(F=>{if(it===F){Re(!0);return}ye(F),Re(!0),Et(F)},[Et,it]),Tt=a.useCallback(()=>{N.current?.close(),N.current=null,c&&(T.current=c),re(),ye(null),Re(!0)},[re,c]),qt=a.useCallback(()=>{Re(!1)},[]),Pt=a.useCallback(async F=>{const ve=Oe=>Oe==="generating"||Oe==="awaiting_input",ze=Le.find(Oe=>Oe.id===F);if(ze&&ve(ze.status))try{await _p(F,l,J)}catch{}try{await Dp(F)}catch{}ne({sessionId:F,status:"complete",timestamp:Date.now()}),pe(Oe=>Oe.filter(Ge=>Ge.id!==F)),it===F&&(N.current?.close(),N.current=null,re(),ye(null),Re(!1)),Pe(null)},[ne,Le,l,re,it,J]),At=a.useCallback(async F=>{const ze=Le.find(Oe=>Oe.id===F)?.archived===!0;try{ze?await Ew(F):await Cw(F)}catch{return}pe(Oe=>!ze&&!Ye?Oe.filter(Ge=>Ge.id!==F):Oe.map(Ge=>Ge.id===F?{...Ge,archived:!ze}:Ge)),!ze&&it===F&&!Ye&&(N.current?.close(),N.current=null,re(),ye(null),Re(!1))},[Le,re,it,Re,Ye]);a.useEffect(()=>{e||(E.current=!1,C.current=!1,R(!1),K(!1),H(null))},[e]),a.useEffect(()=>{if(!e){Me.current&&(ge(Me.current,J),Me.current=null);return}if(k&&Me.current!==k){Me.current&&ge(Me.current,J),Q(k,J),Me.current=k;return}!k&&Me.current&&(ge(Me.current,J),Me.current=null)},[Q,ge,e,k,J]),a.useEffect(()=>{if(!e||!k||Me.current!==k)return;de(J);const F=setInterval(()=>{de(J)},3e4);return()=>{clearInterval(F)}},[de,e,k,J]),a.useEffect(()=>()=>{N.current?.close(),N.current=null,Me.current&&(ge(Me.current,J),Me.current=null)},[ge,J]),a.useEffect(()=>{if(!e)return;const F=()=>{N.current?.close(),N.current=null};return window.addEventListener("beforeunload",F),()=>window.removeEventListener("beforeunload",F)},[e]);const Bt=a.useCallback(()=>{u&&m.type==="initial"&&Y1(u,l),N.current?.close(),N.current=null,R(!1),K(!1),n()},[u,n,l,m.type]);a.useEffect(()=>{if(!e)return;const F=ve=>{ve.key==="Escape"&&Bt()};return document.addEventListener("keydown",F),()=>document.removeEventListener("keydown",F)},[e,Bt]);const Ft=a.useCallback(async F=>{if(m.type!=="question")return;const{session:ve}=m,ze=ve.sessionId,Oe=ve.currentQuestion;if(!Oe){p("No active question in session");return}p(null),b(Ge=>[...Ge,F]),x(Ge=>[...Ge,{question:Oe,response:F}]),h({type:"loading"}),A("");try{await Ij(ze,F,l,J)}catch(Ge){p(we(Ge)||"Failed to submit response"),h({type:"question",session:ve})}},[l,J,m]),Dt=a.useCallback(async()=>{const F=I.current;if(F){try{await Dj(F,l,J)}catch{}N.current?.close(),N.current=null,R(!1),K(!1),h({type:"error",session:{sessionId:F,currentQuestion:null,summary:null},errorMessage:"Generation stopped by user. You can retry or start a new session."}),A("")}},[l,J]),Mt=a.useCallback(async()=>{if(m.type!=="error")return;const F=m.session;p(null),K(!0),A(""),h({type:"loading"}),gt(F.sessionId);try{I.current=F.sessionId,H(F.sessionId),await $j(F.sessionId,l,J)}catch(ve){let ze=ve;if((we(ve)||"").includes("not in an error state"))try{const Ge=await ai(F.sessionId);if(!Ge)throw new Error("Failed to refresh planning session.");if(I.current=Ge.id,H(Ge.id),Ge.status==="generating")A(Ge.thinkingOutput??""),h({type:"loading"});else if(Ge.status==="awaiting_input"){if(!Ge.currentQuestion)throw new Error("Planning session is awaiting input but has no current question.");const dt=JSON.parse(Ge.currentQuestion);ra(l),h({type:"question",session:{sessionId:Ge.id,currentQuestion:dt,summary:null}}),N.current?.isConnected()||gt(Ge.id)}else if(Ge.status==="complete"){if(!Ge.result)throw new Error("Planning session is complete but has no result.");const dt=JSON.parse(Ge.result);ra(l),h({type:"summary",session:{sessionId:Ge.id,currentQuestion:null,summary:dt},summary:dt}),w(dt)}else Ge.status==="error"&&h({type:"error",session:{sessionId:Ge.id,currentQuestion:null,summary:null},errorMessage:Ge.error||"Retry failed. Please try again."});R(!1);return}catch(Ge){ze=Ge}N.current?.close(),N.current=null,h({type:"error",session:F,errorMessage:we(ze)||"Retry failed. Please try again."}),R(!1)}finally{K(!1)}},[gt,l,J,m]),St=a.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const F=m.session.sessionId,ve=await Lj(F,y??void 0,l);s(ve),ye(null),pe(ze=>ze.filter(Oe=>Oe.id!==F)),ne({sessionId:F,status:"complete",timestamp:Date.now()}),Bt()}catch(F){p(we(F)||"Failed to create task"),h({type:"summary",session:m.session,summary:m.summary})}}},[ne,y,m,l,s,Bt]),Wt=a.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const F=await zj(m.session.sessionId,y??void 0,l);H(F.sessionId),h({type:"breakdown",sessionId:F.sessionId,subtasks:F.subtasks,dirty:!1})}catch(F){p(we(F)||"Failed to start breakdown"),h({type:"summary",session:m.session,summary:m.summary})}}},[y,m,l]),It=a.useCallback(async()=>{if(m.type==="breakdown"){p(null),h({type:"creating"});try{const F=m.sessionId,ve=await Fj(F,m.subtasks,l);i(ve.tasks),pe(ze=>ze.filter(Oe=>Oe.id!==F)),ne({sessionId:F,status:"complete",timestamp:Date.now()}),d(""),h({type:"initial"}),p(null),b([]),x([]),w(null),A(""),ie(void 0),Ue(void 0),I.current=null,H(null),ye(null),n()}catch(F){p(we(F)||"Failed to create tasks"),h({type:"breakdown",sessionId:m.sessionId,subtasks:m.subtasks,dirty:m.dirty})}}},[ne,m,i,n,l]),Yt=a.useCallback(()=>{if(m.type==="question"&&g.length>0){const F=g.slice(0,-1);b(F),h({type:"question",session:m.session})}},[m,g]),Rt=()=>m.type==="question"?Math.min(g.length+1,3):3,xe=k?he.get(k):null,Fe=xe&&xe.tabId!==J,ct=!!(Fe&&!xe.stale),D=ue&&(!Fe||xe.stale);return e?t.jsx("div",{className:"modal-overlay open",onMouseDown:F=>{ft.current=F.target===F.currentTarget},onClick:F=>{F.target===F.currentTarget&&ft.current&&Bt(),ft.current=!1},role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",ref:ee,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:qt,"aria-label":"Back to sessions",title:"Back to sessions",children:t.jsx(Jo,{size:18})}),t.jsx(ri,{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:Bt,"aria-label":"Close",children:t.jsx(Ht,{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(fR,{sessions:Le,loading:Ae,selectedSessionId:it,pendingDeleteId:be,showArchived:Ye,onToggleShowArchived:()=>$e(F=>!F),onArchive:F=>void At(F),onSelectSession:Nt,onNewSession:Tt,onRequestDelete:Pe,onConfirmDelete:F=>void Pt(F),onCancelDelete:()=>Pe(null)}),t.jsxs("div",{className:"planning-detail",children:[f&&t.jsx("div",{className:"form-error planning-error",children:f}),_&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),ct&&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(cs,{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:Y,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:F=>d(F.target.value),onKeyDown:F=>{F.key==="Enter"&&!F.shiftKey&&u.trim()&&(F.preventDefault(),wt())}})]}),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:oR.map((F,ve)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>d(F),children:F.length>40?F.slice(0,40)+"...":F},ve))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"planning-modal-model",className:"form-label",children:["Planning Model",et&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(Zn,{id:"planning-modal-model",label:"Planning Model",value:je,onChange:F=>{const{provider:ve,modelId:ze}=cR(F);ie(ve),Ue(ze)},models:Te,disabled:et,favoriteProviders:Be,onToggleFavorite:Ze,favoriteModels:Ne,onToggleModelFavorite:pt}),Xe&&t.jsxs("div",{className:"form-hint form-hint-error",children:[Xe," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{te()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${me&&Ee?"model-badge-custom":"model-badge-default"}`,children:rt(me,Ee)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>wt(),disabled:!u.trim(),children:[t.jsx(ri,{size:16,className:"icon-mr-8"}),"Start Planning"]})})]}),m.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(ot,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:j?"AI is thinking...":"Generating next question..."}),L&&t.jsxs("div",{className:"planning-elapsed",children:["Thinking… (",U,"s)"]}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>z(!S),type:"button",children:S?"Hide thinking":"Show thinking"}),t.jsx("div",{className:"planning-loading-actions",children:t.jsxs("button",{className:"btn planning-stop-btn",type:"button",onClick:()=>void Dt(),children:[t.jsx(Ab,{size:14}),t.jsx("span",{className:"icon-ml-6",children:"Stop"})]})}),S&&j&&t.jsx("div",{className:"planning-thinking-output",ref:Z,children:t.jsx("pre",{children:j})})]})]}),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(Ls,{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 Mt(),disabled:B,children:[B?t.jsx(ot,{size:14,className:"spin"}):t.jsx(Ln,{size:14}),t.jsx("span",{className:"icon-ml-6",children:B?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Bt,disabled:B,children:"Dismiss"})]})]})]})}),m.type==="creating"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(ot,{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(uR,{question:m.session.currentQuestion,progress:Rt(),historyEntries:v,onSubmit:Ft,onBack:g.length>0?Yt:void 0})}),m.type==="summary"&&y&&t.jsx(mR,{summary:y,historyEntries:v,onSummaryChange:w,tasks:r,onCreateTask:St,onBreakIntoTasks:Wt,onRefine:()=>{h({type:"question",session:m.session})},isLoading:!1}),m.type==="breakdown"&&t.jsx(pR,{subtasks:m.subtasks,dirty:m.dirty,isLoading:!1,onUpdateSubtasks:F=>h({...m,subtasks:F,dirty:!0}),onCreateTasks:It,onBack:()=>{const ve={sessionId:m.sessionId,currentQuestion:null,summary:y??null};y&&h({type:"summary",session:ve,summary:y})}})]}),ue&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Zo,{size:16}),t.jsx("span",{children:D?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),D&&t.jsx("button",{type:"button",onClick:()=>{fe()},disabled:W,className:"btn btn-primary session-lock-take-control",children:W?"Taking control...":"Take Control"})]})})]})]})}):null}function uR({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(Ls,{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 f=o[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:h.id,checked:f.includes(h.id),onChange:p=>{const g=p.target.checked?[...f,h.id]:f.filter(b=>b!==h.id);l({[e.id]:g})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:h.label}),h.description&&t.jsx("span",{className:"planning-option-desc",children:h.description})]})]},h.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!0?"selected":""}`,onClick:()=>l({[e.id]:!0}),children:[t.jsx(wn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!1?"selected":""}`,onClick:()=>l({[e.id]:!1}),children:[t.jsx(Ht,{size:18}),"No"]})]})]})]})]})]}),t.jsxs("div",{className:"planning-actions",children:[r&&t.jsxs("button",{className:"btn",onClick:r,children:[t.jsx(_a,{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(Pr,{size:16,className:"icon-ml-4"})]})]})]})}function mR({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),f=p=>{const g=m.includes(p)?m.filter(b=>b!==p):[...m,p];h(g),s({...e,suggestedDependencies:g})};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(rR,{summary:"Show user Q&A",className:"planning-summary-qa-disclosure",children:[t.jsx(Ls,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(wn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Planning Complete!"}),t.jsx("p",{className:"text-muted",children:"Review and refine your task before creating it."})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{children:["Description",t.jsx("button",{type:"button",className:"planning-expand-btn",onClick:()=>d(!u),children:u?"Collapse":"Expand"})]}),t.jsx("textarea",{className:`planning-textarea ${u?"expanded":""}`,rows:u?10:4,value:e.description,onChange:p=>s({...e,description:p.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Suggested Size"}),t.jsxs("select",{className:"planning-size-select",value:e.suggestedSize,onChange:p=>s({...e,suggestedSize:p.target.value}),disabled:c,children:[t.jsx("option",{value:"S",children:"S (Small)"}),t.jsx("option",{value:"M",children:"M (Medium)"}),t.jsx("option",{value:"L",children:"L (Large)"})]})]}),i.length>0&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Suggested Dependencies"}),t.jsx("div",{className:"planning-deps-list",children:i.map(p=>t.jsxs("label",{className:`planning-dep-chip ${m.includes(p.id)?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:m.includes(p.id),onChange:()=>f(p.id)}),t.jsx("span",{className:"planning-dep-id",children:p.id}),t.jsx("span",{className:"planning-dep-title",children:p.title||p.description.slice(0,30)})]},p.id))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Key Deliverables"}),t.jsx("ul",{className:"planning-deliverables",children:e.keyDeliverables.map((p,g)=>t.jsx("li",{children:p},g))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:l,disabled:c,children:[t.jsx(_a,{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(ot,{size:16,className:"spin icon-mr-8"}),"Breaking down..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Xo,{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(ot,{size:16,className:"spin icon-mr-8"}),"Creating..."]}):t.jsxs(t.Fragment,{children:[t.jsx(wn,{size:16,className:"icon-mr-8"}),"Create Task"]})})]})]})]})}function gh(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 hR(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function pR({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),f=a.useRef([]),p=a.useMemo(()=>e.length===0||e.some(A=>!A.title.trim())?!0:gh(e),[e]),g=a.useCallback((A,S)=>{i(e.map(z=>z.id===A?{...z,...S}:z))},[e,i]),b=a.useCallback(()=>{i([...e,hR(e.length+1)])},[e,i]),v=a.useCallback(A=>{i(e.filter(S=>S.id!==A).map(S=>({...S,dependsOn:S.dependsOn.filter(z=>z!==A)})))},[e,i]),x=a.useCallback((A,S)=>{if(S<0||S>=e.length)return;const z=[...e],[_]=z.splice(A,1);z.splice(S,0,_),i(z)},[e,i]),y=a.useCallback(A=>S=>{c(A),S.dataTransfer.setData("text/plain",A),S.dataTransfer.effectAllowed="move"},[]),w=a.useCallback(()=>{c(null),d(null),h(null)},[]),E=a.useCallback(A=>S=>{if(S.preventDefault(),A===l)return;const z=S.currentTarget.getBoundingClientRect(),_=z.top+z.height/2,R=S.clientY<_?"before":"after";d(A),h(R)},[l]),C=a.useCallback(A=>S=>{S.preventDefault();const z=S.dataTransfer.getData("text/plain");if(!z||z===A){w();return}const _=e.findIndex($=>$.id===z),R=e.findIndex($=>$.id===A);if(_===-1||R===-1){w();return}const B=[...e],[K]=B.splice(_,1);let L=R;m==="after"&&_<R&&L--,m==="after"&&L++,B.splice(L,0,K),i(B),w()},[e,m,i,w]),j=a.useCallback(A=>{const S=A.currentTarget.getBoundingClientRect(),z=A.clientX,_=A.clientY;(z<S.left||z>S.right||_<S.top||_>S.bottom)&&(d(null),h(null))},[]);return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Xo,{size:24,className:"icon-triage"}),t.jsx("h4",{children:"Break into Tasks"}),t.jsx("p",{className:"text-muted",children:"Review and edit the subtasks generated from your plan. Adjust titles, descriptions, sizes, and dependencies before creating."})]}),t.jsxs("div",{className:"planning-summary-form",children:[e.map((A,S)=>{const z=l===A.id,_=u===A.id,R=["task-detail-section","subtask-item",z?"subtask-item-dragging":"",_?"subtask-item-drop-target":"",_&&m==="before"?"subtask-item-drop-before":"",_&&m==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:R,"data-testid":`subtask-item-${S}`,draggable:!s,onDragStart:y(A.id),onDragEnd:w,onDragOver:E(A.id),onDrop:C(A.id),onDragLeave:j,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(hd,{size:16}),t.jsx("strong",{children:A.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>x(S,S-1),disabled:s||S===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(Fi,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>x(S,S+1),disabled:s||S===e.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(Tr,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>v(A.id),disabled:s,children:[t.jsx(an,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:B=>{f.current[S]=B},value:A.title,onChange:B=>g(A.id,{title:B.target.value}),onKeyDown:B=>{B.key==="Enter"&&(B.preventDefault(),S<e.length-1&&f.current[S+1]?.focus())},disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:A.description,onChange:B=>g(A.id,{description:B.target.value}),disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Size"}),t.jsxs("select",{className:"planning-size-select",value:A.suggestedSize,onChange:B=>g(A.id,{suggestedSize:B.target.value}),disabled:s,children:[t.jsx("option",{value:"S",children:"S"}),t.jsx("option",{value:"M",children:"M"}),t.jsx("option",{value:"L",children:"L"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"planning-deps-list",children:[e.slice(0,S).filter(B=>B.id!==A.id).map(B=>{const K=A.dependsOn.includes(B.id);return t.jsxs("label",{className:`planning-dep-chip ${K?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:K,onChange:()=>{const L=K?A.dependsOn.filter($=>$!==B.id):[...A.dependsOn,B.id];g(A.id,{dependsOn:L})},disabled:s}),t.jsx("span",{className:"planning-dep-id",children:B.id}),t.jsx("span",{className:"planning-dep-title",children:B.title||"Untitled"})]},B.id)}),S===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),S>0&&e.slice(0,S).filter(B=>B.id!==A.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},A.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:b,disabled:s,children:[t.jsx(rn,{size:16,className:"icon-mr-6"})," Add subtask"]}),gh(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(_a,{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(ot,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]})}function fR({sessions:e,loading:n,selectedSessionId:s,pendingDeleteId:i,showArchived:r,onToggleShowArchived:o,onArchive:l,onSelectSession:c,onNewSession:u,onRequestDelete:d,onConfirmDelete:m,onCancelDelete:h}){return t.jsxs("aside",{className:"planning-sidebar","aria-label":"Planning sessions",children:[t.jsx("div",{className:"planning-sidebar-header",children:t.jsxs("button",{className:`planning-sidebar-new ${s===null?"active":""}`,onClick:u,type:"button",children:[t.jsx(Hx,{size:16}),t.jsx("span",{children:"New session"})]})}),t.jsxs("div",{className:"planning-sidebar-list",children:[e.length===0&&!n&&t.jsx("div",{className:"planning-sidebar-empty text-muted",children:"No saved sessions yet. Start one on the right to see it here."}),e.map(f=>{const p=f.id===s,g=i===f.id,b=f.archived===!0,v=f.status==="complete"||f.status==="error";return t.jsxs("div",{className:`planning-sidebar-item ${p?"selected":""} ${g?"pending-delete":""} ${b?"archived":""}`,children:[t.jsxs("button",{type:"button",className:"planning-sidebar-item-button",onClick:()=>c(f.id),children:[t.jsx(gR,{status:f.status}),t.jsxs("span",{className:"planning-sidebar-item-body",children:[t.jsx("span",{className:"planning-sidebar-item-title",children:f.title||"Untitled session"}),t.jsxs("span",{className:"planning-sidebar-item-meta",children:[t.jsx(bR,{status:f.status}),t.jsx("span",{"aria-hidden":!0,children:" · "}),t.jsx("span",{children:xR(f.updatedAt)})]})]})]}),g?t.jsxs("div",{className:"planning-sidebar-confirm",children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-danger",onClick:()=>m(f.id),children:"Delete"}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,children:"Cancel"})]}):t.jsxs("div",{className:"planning-sidebar-item-actions",children:[v&&t.jsx("button",{type:"button",className:"planning-sidebar-item-archive",onClick:x=>{x.stopPropagation(),l(f.id)},"aria-label":b?"Unarchive session":"Archive session",title:b?"Unarchive session":"Archive session",children:b?t.jsx(ab,{size:14}):t.jsx(Rr,{size:14})}),t.jsx("button",{type:"button",className:"planning-sidebar-item-delete",onClick:x=>{x.stopPropagation(),d(f.id)},"aria-label":"Delete session",title:"Delete session",children:t.jsx(an,{size:14})})]})]},f.id)})]}),t.jsx("div",{className:"planning-sidebar-footer",children:t.jsx("a",{href:"#",className:"planning-sidebar-toggle-archived-link",onClick:f=>{f.preventDefault(),o()},"aria-pressed":r,children:r?"Hide archived":"Show archived"})})]})}function gR({status:e}){switch(e){case"generating":return t.jsx(ot,{size:14,className:"spin planning-sidebar-status-icon planning-sidebar-status-generating"});case"awaiting_input":return t.jsx(_c,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-awaiting"});case"complete":return t.jsx(wn,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-complete"});case"error":return t.jsx(gs,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-error"});default:return t.jsx(Ei,{size:14,className:"planning-sidebar-status-icon"})}}function bR({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 xR(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 vR(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function bh(e){const n=new Map(e.map(o=>[o.id,o.dependsOn])),s=new Set,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 yR({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,f]=a.useState([]),[p,g]=a.useState(""),[b,v]=a.useState(!0),[x,y]=a.useState(!1),[w,E]=a.useState(!1),[C,j]=a.useState(s),[A,S]=a.useState(null),[z,_]=a.useState(!1),[R,B]=a.useState(null),[K,L]=a.useState(null),[$,U]=a.useState(null),G=a.useRef(null),Y=a.useRef([]),ee=a.useRef(!1),N=a.useRef(null),I=c.type==="generating"||c.type==="editing"||c.type==="creating"||c.type==="error"?c.sessionId:null,T=a.useMemo(()=>Yi(),[]),{isLockedByOther:k,takeControl:H,isLoading:J}=cl(e?I:null),{activeTabMap:ue,broadcastUpdate:fe,broadcastCompleted:W,broadcastLock:he,broadcastUnlock:O,broadcastHeartbeat:ne}=Ia(),Q=a.useMemo(()=>d.length===0||d.some(ce=>!ce.title.trim())?!0:bh(d),[d]),ge=c.type==="generating"||c.type==="editing"||c.type==="error",de=I?ue.get(I):null,{confirm:me}=Ks(),ie=de&&de.tabId!==T,Ee=!!(ie&&!de.stale),Ue=k&&(!ie||de.stale),Te=a.useCallback(()=>{C&&X1(C,o),G.current?.close(),G.current=null,u({type:"initial"}),m([]),f([]),g(""),v(!0),y(!1),E(!1),S(null),_(!1),ee.current=!1},[C,o]),at=a.useCallback(()=>{G.current?.close(),G.current=null,n()},[n]),et=a.useCallback(async()=>{if(!((z||c.type==="editing"||c.type==="creating")&&!await me({title:"Discard Changes",message:"Close subtask breakdown? Unsaved changes will be lost.",danger:!0}))){if(I)try{await Rp(I,o,T)}catch{}Te(),n()}},[z,n,Te,I,T,c.type,o,me]),Ve=a.useCallback(ce=>{G.current?.close(),G.current=hk(ce,o,{onThinking:Re=>{g(be=>be+Re),fe({sessionId:ce,status:"generating",needsInput:!1,owningTabId:T,type:"subtask",title:C.trim()||void 0,projectId:o??null})},onSubtasks:Re=>{y(!1),E(!1),Il(o),m(Re),u({type:"editing",sessionId:ce}),_(!1),fe({sessionId:ce,status:"awaiting_input",needsInput:!0,owningTabId:T,type:"subtask",title:C.trim()||void 0,projectId:o??null})},onError:Re=>{const be=Re||"Session failed while contacting the AI.";y(!1),E(!1),S(null),u({type:"error",sessionId:ce,errorMessage:be}),fe({sessionId:ce,status:"error",needsInput:!1,owningTabId:T,type:"subtask",title:C.trim()||void 0,projectId:o??null}),W({sessionId:ce,status:"error"})},onComplete:()=>{W({sessionId:ce,status:"complete"})},onConnectionStateChange:Re=>{y(Re==="reconnecting")}})},[W,fe,C,o,T]),Xe=a.useCallback(async()=>{if(C.trim()){S(null),f([]),g(""),y(!1);try{const{sessionId:ce}=await dk(C.trim(),o);u({type:"generating",sessionId:ce}),Ve(ce)}catch(ce){S(we(ce)||"Failed to start subtask breakdown"),u({type:"initial"})}}},[Ve,C,o]);a.useEffect(()=>{if(!e){Te();return}if(e&&s&&!ee.current)j(s),ee.current=!0,Xe();else if(e&&!s&&!ee.current){const ce=Z1(o);ce&&j(ce)}},[e,s,Xe,Te]),a.useEffect(()=>{!e||!l||c.type!=="initial"||(async()=>{try{const ce=await ai(l);if(!ce)return;const Re=ya(ce.conversationHistory);if(f(Re),ce.status==="generating"||ce.status==="awaiting_input")g(ce.thinkingOutput??""),u({type:"generating",sessionId:l}),Ve(l);else if(ce.status==="complete"&&ce.result){Il(o);const be=JSON.parse(ce.result);m(be),u({type:"editing",sessionId:l})}else ce.status==="error"&&(S(null),u({type:"error",sessionId:l,errorMessage:ce.error??"Session encountered an error"}))}catch(ce){S(we(ce)||"Failed to resume session")}})()},[Ve,e,l,c.type,o]),a.useEffect(()=>{if(!e){N.current&&(O(N.current,T),N.current=null);return}if(I&&N.current!==I){N.current&&O(N.current,T),he(I,T),N.current=I;return}!I&&N.current&&(O(N.current,T),N.current=null)},[he,O,e,I,T]),a.useEffect(()=>{if(!e||!I||N.current!==I)return;ne(T);const ce=setInterval(()=>{ne(T)},3e4);return()=>{clearInterval(ce)}},[ne,e,I,T]),a.useEffect(()=>()=>{G.current?.close(),N.current&&(O(N.current,T),N.current=null)},[O,T]),a.useEffect(()=>{if(!e)return;const ce=Re=>{Re.key==="Escape"&&(Re.preventDefault(),et())};return document.addEventListener("keydown",ce),()=>document.removeEventListener("keydown",ce)},[e,et]);const De=a.useCallback((ce,Re)=>{m(be=>be.map(Pe=>Pe.id===ce?{...Pe,...Re}:Pe)),_(!0)},[]),Be=a.useCallback(()=>{m(ce=>[...ce,vR(ce.length+1)]),_(!0)},[]),oe=a.useCallback(ce=>{m(Re=>Re.filter(be=>be.id!==ce).map(be=>({...be,dependsOn:be.dependsOn.filter(Pe=>Pe!==ce)}))),_(!0)},[]),Ne=a.useCallback(ce=>Re=>{B(ce),Re.dataTransfer.setData("text/plain",ce),Re.dataTransfer.effectAllowed="move"},[]),se=a.useCallback(()=>{B(null),L(null),U(null)},[]),Me=a.useCallback(ce=>Re=>{if(Re.preventDefault(),ce===R)return;const be=Re.currentTarget.getBoundingClientRect(),Pe=be.top+be.height/2,Ye=Re.clientY<Pe?"before":"after";L(ce),U(Ye)},[R]),Le=a.useCallback(ce=>Re=>{Re.preventDefault();const be=Re.dataTransfer.getData("text/plain");if(!be||be===ce){B(null),L(null),U(null);return}m(Pe=>{const Ye=Pe.findIndex(je=>je.id===be),$e=Pe.findIndex(je=>je.id===ce);if(Ye===-1||$e===-1)return Pe;const ft=[...Pe],[Z]=ft.splice(Ye,1);let re=$e;return $==="after"&&Ye<$e&&re--,$==="after"&&re++,ft.splice(re,0,Z),ft}),_(!0),B(null),L(null),U(null)},[$]),pe=a.useCallback(ce=>{const Re=ce.currentTarget.getBoundingClientRect(),be=ce.clientX,Pe=ce.clientY;(be<Re.left||be>Re.right||Pe<Re.top||Pe>Re.bottom)&&(L(null),U(null))},[]),Ae=a.useCallback((ce,Re)=>{Re<0||Re>=d.length||(m(be=>{const Pe=[...be],[Ye]=Pe.splice(ce,1);return Pe.splice(Re,0,Ye),Pe}),_(!0))},[d.length]),Je=a.useCallback(ce=>{Y.current[ce+1]?.focus()},[]),it=a.useCallback(async()=>{if(!(!I||Q)){S(null),u({type:"creating",sessionId:I});try{const ce=await pk(I,d,r,o);i(ce.tasks),Te(),n()}catch(ce){S(we(ce)||"Failed to create tasks"),u({type:"editing",sessionId:I})}}},[Q,n,i,r,o,Te,I,d]),ye=a.useCallback(async()=>{if(c.type!=="error")return;const ce=c.sessionId;S(null),E(!0),g(""),u({type:"generating",sessionId:ce}),Ve(ce);try{await uk(ce,o,T)}catch(Re){let be=Re;if((we(Re)||"").includes("not in an error state"))try{const Ye=await ai(ce);if(!Ye)throw new Error("Failed to refresh subtask session.");if(f(ya(Ye.conversationHistory)),Ye.status==="generating"||Ye.status==="awaiting_input")g(Ye.thinkingOutput??""),u({type:"generating",sessionId:Ye.id}),G.current?.isConnected()||Ve(Ye.id);else if(Ye.status==="complete"){if(!Ye.result)throw new Error("Subtask session is complete but has no result.");Il(o);const $e=JSON.parse(Ye.result);m($e),u({type:"editing",sessionId:Ye.id}),_(!1)}else Ye.status==="error"&&u({type:"error",sessionId:Ye.id,errorMessage:Ye.error??"Retry failed. Please try again."});y(!1);return}catch(Ye){be=Ye}G.current?.close(),G.current=null,u({type:"error",sessionId:ce,errorMessage:we(be)||"Retry failed. Please try again."}),y(!1)}finally{E(!1)}},[Ve,o,T,c]);return e?t.jsx("div",{className:"modal-overlay open",onClick:ce=>ce.target===ce.currentTarget&&void et(),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(Xo,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Subtask Breakdown"})]}),t.jsxs("div",{className:"modal-header-actions",children:[ge&&t.jsx("button",{className:"modal-send-to-background",onClick:at,title:"Send to background","aria-label":"Send to background",children:t.jsx(Dr,{size:16})}),t.jsx("button",{className:"modal-close",onClick:()=>void et(),"aria-label":"Close",children:t.jsx(Ht,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[A&&t.jsx("div",{className:"form-error planning-error",children:A}),x&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Ee&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),c.type==="initial"&&t.jsx("div",{className:"planning-initial",children:t.jsxs("div",{className:"planning-view-scroll",children:[t.jsx("p",{className:"text-muted",children:"Preparing to break this task into subtasks."}),t.jsx("pre",{className:"planning-thinking-output",children:C})]})}),c.type==="generating"&&t.jsxs("div",{className:"planning-loading",children:[h.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ls,{entries:h,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsx(ot,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:"AI is generating subtasks..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>v(!b),type:"button",children:b?"Hide thinking":"Show thinking"}),b&&p&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:p})})]})]}),c.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[h.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ls,{entries:h,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:c.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void ye(),disabled:w,children:[w?t.jsx(ot,{size:14,className:"spin"}):t.jsx(Ln,{size:14}),t.jsx("span",{className:"icon-ml-6",children:w?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:()=>void et(),disabled:w,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(Ls,{entries:h}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(wn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Review your subtasks"}),t.jsx("p",{className:"text-muted",children:"Edit titles, descriptions, sizes, and dependencies before creating all tasks at once."})]}),t.jsxs("div",{className:"planning-summary-form",children:[d.map((ce,Re)=>{const be=R===ce.id,Pe=K===ce.id,Ye=["task-detail-section","subtask-item",be?"subtask-item-dragging":"",Pe?"subtask-item-drop-target":"",Pe&&$==="before"?"subtask-item-drop-before":"",Pe&&$==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:Ye,"data-testid":`subtask-item-${Re}`,draggable:c.type!=="creating",onDragStart:Ne(ce.id),onDragEnd:se,onDragOver:Me(ce.id),onDrop:Le(ce.id),onDragLeave:pe,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(hd,{size:16}),t.jsx("strong",{children:ce.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Ae(Re,Re-1),disabled:c.type==="creating"||Re===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(Fi,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Ae(Re,Re+1),disabled:c.type==="creating"||Re===d.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(Tr,{})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>oe(ce.id),disabled:c.type==="creating",children:[t.jsx(an,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:$e=>{Y.current[Re]=$e},value:ce.title,onChange:$e=>De(ce.id,{title:$e.target.value}),onKeyDown:$e=>{$e.key==="Enter"&&($e.preventDefault(),Je(Re))},disabled:c.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:8,value:ce.description,onChange:$e=>De(ce.id,{description:$e.target.value}),disabled:c.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Size"}),t.jsxs("select",{className:"planning-size-select",value:ce.suggestedSize,onChange:$e=>De(ce.id,{suggestedSize:$e.target.value}),disabled:c.type==="creating",children:[t.jsx("option",{value:"S",children:"S"}),t.jsx("option",{value:"M",children:"M"}),t.jsx("option",{value:"L",children:"L"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"planning-deps-list",children:[d.slice(0,Re).filter($e=>$e.id!==ce.id).map($e=>{const ft=ce.dependsOn.includes($e.id);return t.jsxs("label",{className:`planning-dep-chip ${ft?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:ft,onChange:()=>{const Z=ft?ce.dependsOn.filter(re=>re!==$e.id):[...ce.dependsOn,$e.id];De(ce.id,{dependsOn:Z})},disabled:c.type==="creating"}),t.jsx("span",{className:"planning-dep-id",children:$e.id}),t.jsx("span",{className:"planning-dep-title",children:$e.title||"Untitled"})]},$e.id)}),Re===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),Re>0&&d.slice(0,Re).filter($e=>$e.id!==ce.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},ce.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:Be,disabled:c.type==="creating",children:[t.jsx(rn,{size:16,className:"icon-mr-6"})," Add subtask"]}),bh(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 et(),disabled:c.type==="creating",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:()=>void it(),disabled:c.type==="creating"||Q,children:c.type==="creating"?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]}),k&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Zo,{size:16}),t.jsx("span",{children:Ue?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),Ue&&t.jsx("button",{type:"button",onClick:()=>{H()},disabled:J,className:"btn btn-primary session-lock-take-control",children:J?"Taking control...":"Take Control"})]})})]})]})}):null}const jR=5,kR=1e3,wR=45e3;function xo(){return{scrollback:null,connected:null,data:[]}}function NR(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),f=a.useRef(!1),p=a.useRef(new Set),g=a.useRef(new Set),b=a.useRef(new Set),v=a.useRef(new Set),x=a.useRef(new Set),y=a.useRef(xo()),w=a.useCallback(L=>{p.current.add(L);const $=y.current;return $.data.length>0&&($.data.forEach(U=>L(U)),$.data=[]),()=>p.current.delete(L)},[]),E=a.useCallback(L=>(g.current.add(L),()=>g.current.delete(L)),[]),C=a.useCallback(L=>{b.current.add(L);const $=y.current;return $.connected&&(L($.connected),$.connected=null),()=>b.current.delete(L)},[]),j=a.useCallback(L=>{v.current.add(L);const $=y.current;return $.scrollback&&(L($.scrollback),$.scrollback=null),()=>v.current.delete(L)},[]),A=a.useCallback(L=>(x.current.add(L),()=>x.current.delete(L)),[]),S=a.useCallback(L=>{const $=u.current;$?.readyState===WebSocket.OPEN&&$.send(JSON.stringify({type:"input",data:L}))},[]),z=a.useCallback((L,$)=>{const U=u.current;U?.readyState===WebSocket.OPEN&&U.send(JSON.stringify({type:"resize",cols:L,rows:$}))},[]),_=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=xo()},[]),R=a.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.current=null),u.current&&(f.current=!0,u.current.close(),u.current=null),y.current=xo()},[]),B=a.useCallback(()=>{if(!e){i("disconnected");return}if(u.current?.readyState===WebSocket.OPEN)return;u.current&&(f.current=!0,u.current.close()),f.current=!1,i("connecting");const L=r.current;let U=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/terminal/ws?sessionId=${encodeURIComponent(e)}`;n&&(U+=`&projectId=${encodeURIComponent(n)}`);const G=new WebSocket(oi(U));u.current=G,G.onopen=()=>{if(r.current!==L){G.close();return}y.current=xo(),i("connected"),d.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{r.current===L&&G.readyState===WebSocket.OPEN&&G.send(JSON.stringify({type:"ping"}))},wR)},G.onmessage=Y=>{if(r.current===L)try{const ee=JSON.parse(Y.data),N=y.current;switch(ee.type){case"data":ee.data&&(p.current.size===0&&N.data.push(ee.data),p.current.forEach(I=>I(ee.data)));break;case"scrollback":ee.data&&(N.scrollback=ee.data,v.current.forEach(I=>I(ee.data)));break;case"connected":ee.shell&&ee.cwd&&(N.connected={shell:ee.shell,cwd:ee.cwd},b.current.forEach(I=>I({shell:ee.shell,cwd:ee.cwd})));break;case"exit":ee.exitCode!==void 0&&g.current.forEach(I=>I(ee.exitCode));break;case"ping":G.readyState===WebSocket.OPEN&&G.send(JSON.stringify({type:"pong"}));break;case"pong":break}}catch{}},G.onclose=Y=>{if(r.current!==L)return;if(u.current=null,h.current&&(clearInterval(h.current),h.current=null),f.current){i("disconnected");return}if(Y.code===4e3||Y.code===4004){i("disconnected"),Y.code===4004&&x.current.forEach(I=>I());return}if(d.current++,d.current>jR){i("disconnected");return}const ee=kR*Math.pow(2,d.current-1);i("reconnecting");const N=r.current;m.current=setTimeout(()=>{r.current===N&&(f.current||B())},Math.min(ee,16e3))},G.onerror=()=>{}},[e,n]),K=a.useCallback(()=>{d.current=0,R(),B()},[R,B]);return a.useEffect(()=>(c&&(_(),d.current=0,i("disconnected")),e?B():i("disconnected"),R),[e,n,c,B,R,_]),{connectionStatus:s,sendInput:S,resize:z,onData:w,onExit:E,onConnect:C,onScrollback:j,reconnect:K,onSessionInvalid:A}}const vg="kb-terminal-tabs",SR=15e3,CR=15e3;function xh(){return`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function vh(e){if(typeof window>"u")return[];try{const n=Wn(vg,e);if(n)return JSON.parse(n)}catch{}return[]}function hc(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return n.includes("Failed to parse URL")||n.includes("Invalid URL")}function yh(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 ER(e){const[n,s]=a.useState(()=>vh(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(vh(e)),r(!1),l(!0),u(null)},[e]),a.useEffect(()=>{try{fs(vg,JSON.stringify(n),e)}catch{}},[e,n]),a.useEffect(()=>{let C=!1;const j=h.current;return(async()=>{if(!C)try{const S=await yh(rj(e),SR,"listTerminalSessions");if(C||j!==h.current)return;const z=new Set(S.map(_=>_.id));l(!0),s(_=>{if(C||j!==h.current)return _;const B=_.map($=>({...$,_verified:z.has($.sessionId)})).filter($=>$._verified);if(B.length===0)return[];const K=B.map(({_verified:$,...U})=>U);return K.find($=>$.isActive)?K:K.map(($,U)=>({...$,isActive:U===0}))}),r(!0)}catch(S){if(C||j!==h.current)return;const z=hc(S);z||console.warn("Failed to validate terminal sessions with server:",S),l(!z),r(!0)}})(),()=>{C=!0}},[e]),a.useEffect(()=>{if(n.length===0&&i&&o){const C=h.current,j=setTimeout(()=>{yh(eo(void 0,void 0,void 0,e),CR,"createTerminalSession").then(A=>{if(C!==h.current)return;const S={id:xh(),sessionId:A.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};s(z=>z.length>0?z:[...z.map(R=>({...R,isActive:!1})),S]),u(null)}).catch(A=>{if(C!==h.current)return;hc(A)||console.error(A);const S=A instanceof Error?A.message:typeof A=="string"?A:"Failed to create terminal session";u(S)})},0);return()=>clearTimeout(j)}},[i,o,n.length,d]);const f=a.useCallback(async()=>{const C=await eo(void 0,void 0,void 0,e),j={id:xh(),sessionId:C.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};return s(A=>[...A.map(z=>({...z,isActive:!1})),j]),j},[n.length]),p=a.useCallback(async()=>f(),[f]),g=a.useCallback(C=>{s(j=>{const A=j.find(R=>R.id===C);if(!A)return j;iu(A.sessionId,e).catch(R=>{console.warn(`Failed to kill terminal session ${A.sessionId}:`,R)});const S=j.findIndex(R=>R.id===C),z=A.isActive,_=j.filter(R=>R.id!==C);if(_.length===0)return[];if(z){const R=Math.min(S,_.length-1);return _.map((B,K)=>({...B,isActive:K===R}))}return _})},[]),b=a.useCallback(C=>{s(j=>{let A=!1;const S=j.map(z=>z.id===C?(A=!0,{...z,isActive:!0}):{...z,isActive:!1});return A?S:j})},[]),v=a.useCallback((C,j)=>{s(A=>A.map(S=>S.id===C?{...S,title:j}:S))},[]),x=a.useCallback(async()=>{s(A=>{const S=A.find(z=>z.isActive);return S&&iu(S.sessionId,e).catch(z=>{console.warn(`Failed to kill old session ${S.sessionId}:`,z)}),A});const C=n.find(A=>A.isActive);if(!C)return;const j=await eo(void 0,void 0,void 0,e);s(A=>A.map(S=>S.id===C.id?{...S,sessionId:j.sessionId}:S))},[n]),y=a.useCallback(async()=>{const C=n.find(j=>j.isActive);if(C)try{const j=await eo(void 0,void 0,void 0,e);s(A=>A.map(S=>S.id===C.id?{...S,sessionId:j.sessionId}:S)),u(null)}catch(j){hc(j)||console.error(j);const A=j instanceof Error?j.message:typeof j=="string"?j:"Failed to create terminal session";u(A)}},[n]),w=n.find(C=>C.isActive)??null,E=a.useCallback(()=>{u(null),h.current+=1,m(C=>C+1)},[]);return{tabs:n,activeTab:w,isReady:i,bootstrapError:c,createTab:p,closeTab:g,setActiveTab:b,updateTabTitle:v,restartActiveTab:x,retryBootstrap:E,replaceActiveTabSession:y}}const _R=1e4,MR=[500,1500,3e3],yg="kb-terminal-font-size",ur=14,AR=8,RR=32,TR='"Fusion Terminal Nerd Font Symbols", "MesloLGS NF", "MesloLGM Nerd Font", "JetBrainsMono Nerd Font", "FiraCode Nerd Font", "Hack Nerd Font", ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace';function PR(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 IR(e){return`\x1B${e}`}const $R=[{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 mr(e){return Math.min(RR,Math.max(AR,e))}function DR(){if(typeof window>"u")return ur;try{const e=window.localStorage.getItem(yg);if(!e)return ur;const n=Number.parseInt(e,10);return Number.isFinite(n)?mr(n):ur}catch{return ur}}function LR(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 zR(e){return new Promise(n=>setTimeout(n,e))}async function FR(e,n=MR){let s;for(let i=0;i<=n.length;i+=1)try{return await e()}catch(r){if(!LR(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 zR(o)}throw s??new Error("Dynamic import failed")}function jh(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}function OR(){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=UR()-e.offsetTop-e.height;return i>=30&&i>80?i:0}let pc=null;function UR(){return pc===null&&(pc=window.innerHeight),pc}function BR({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),[f,p]=a.useState(0),[g,b]=a.useState(0),[v,x]=a.useState(null),[y,w]=a.useState(()=>DR()),[E,C]=a.useState(!1),[j,A]=a.useState(null),S=a.useRef(null),z=a.useRef(null),_=a.useRef(!1);di(z,e,"fusion:terminal-modal-size");const R=a.useRef(null),B=a.useRef(null),K=a.useRef(!1),L=a.useRef(!1),$=a.useRef(null),U=a.useRef(()=>{}),G=a.useRef(null),Y=a.useRef(0),ee=a.useRef(y),N=a.useRef(null),I=a.useRef(i);Y.current=g,ee.current=y;const T=a.useCallback(be=>{if(be&&L.current!==be)return;const Pe=B.current,Ye=R.current,$e=$.current;if(!(!Pe||!Ye)&&!(be&&L.current!==be))try{Pe.fit(),$e&&$e(Ye.cols,Ye.rows)}catch{}},[]);a.useEffect(()=>{e&&p(be=>be+1)},[e]),a.useEffect(()=>{if(!e||!jh())return;const be=window.visualViewport;if(!be)return;const Pe=()=>{const Ye=OR();b(Ye),x(be.height),Ye>0&&z.current?.scrollIntoView&&z.current.scrollIntoView({block:"end",behavior:"smooth"}),N.current!==null&&(cancelAnimationFrame(N.current),N.current=null);const $e=typeof L.current=="string"?L.current:void 0;N.current=requestAnimationFrame(()=>{N.current=null,T($e)})};return Pe(),be.addEventListener("resize",Pe),be.addEventListener("scroll",Pe),()=>{be.removeEventListener("resize",Pe),be.removeEventListener("scroll",Pe),N.current!==null&&(cancelAnimationFrame(N.current),N.current=null),b(0),x(null)}},[T,e]),a.useEffect(()=>{if(!e)return;const be=z.current;if(!be||typeof ResizeObserver>"u")return;let Pe=null;const Ye=new ResizeObserver(()=>{Pe!==null&&cancelAnimationFrame(Pe),Pe=requestAnimationFrame(()=>{Pe=null;const $e=typeof L.current=="string"?L.current:void 0;T($e)})});return Ye.observe(be),()=>{Ye.disconnect(),Pe!==null&&cancelAnimationFrame(Pe)}},[T,e]);const{tabs:k,activeTab:H,isReady:J,bootstrapError:ue,createTab:fe,closeTab:W,setActiveTab:he,updateTabTitle:O,restartActiveTab:ne,retryBootstrap:Q,replaceActiveTabSession:ge}=ER(i),{connectionStatus:de,sendInput:me,resize:ie,onData:Ee,onConnect:Ue,onExit:Te,onScrollback:at,reconnect:et,onSessionInvalid:Ve}=NR(H?.sessionId??null,i);$.current=ie,U.current=me,a.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(yg,String(y))}catch{}},[y]);const Xe=a.useCallback(()=>{const be=R.current;if(be)try{B.current?.fit(),ie(be.cols,be.rows)}catch{}},[ie]);a.useEffect(()=>{if(!e||!J)return;const be=H?.sessionId;if(!be)return;const Pe=I.current!==i;if(Pe&&(I.current=i),L.current===be&&R.current&&!Pe)return;R.current&&(L.current!==be||Pe)&&(R.current.dispose(),R.current=null,B.current=null,L.current=!1,G.current&&(window.removeEventListener("resize",G.current),G.current=null),d(!1),h(null));let Ye=!0,$e;return(async()=>{const Z=FR(()=>Promise.all([ln(()=>import("./vendor-xterm-DzcZoU0P.js").then(te=>te.x),__vite__mapDeps([6,1,7])),ln(()=>import("./addon-fit-C7jRorKK.js").then(te=>te.a),__vite__mapDeps([9,1])),ln(()=>import("./addon-web-links-CkJwd4cQ.js").then(te=>te.a),__vite__mapDeps([10,1]))])),re=new Promise((te,Ze)=>{$e=setTimeout(()=>{Ze(new Error("xterm initialization timed out"))},_R)});let je,rt;try{const[{Terminal:te},{FitAddon:Ze},{WebLinksAddon:pt}]=await Promise.race([Z,re]);if(!Ye||!S.current||R.current)return;je=new te({cursorBlink:!0,cursorStyle:"block",fontSize:ee.current,fontFamily:TR,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}),rt=new Ze,je.loadAddon(rt);const gt=new pt;if(je.loadAddon(gt),!jh())try{const{WebglAddon:mt}=await ln(async()=>{const{WebglAddon:Tt}=await import("./addon-webgl-BjvOw43o.js").then(qt=>qt.a);return{WebglAddon:Tt}},__vite__mapDeps([11,1])),Nt=new mt;Nt.onContextLoss(()=>{Nt.dispose()}),je.loadAddon(Nt)}catch{}je.open(S.current),$e&&clearTimeout($e);const wt=S.current?.querySelector(".xterm-helper-textarea");if(wt&&wt.focus(),S.current)try{S.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}setTimeout(()=>{rt.fit();const mt=S.current?.querySelector(".xterm-helper-textarea");mt&&mt.focus()},50),R.current=je,B.current=rt,L.current=be,Y.current>0&&(N.current!==null&&(cancelAnimationFrame(N.current),N.current=null),N.current=requestAnimationFrame(()=>{N.current=null,T(be)})),je.onData(mt=>{L.current===be&&U.current(mt)});const Et=()=>{if(L.current===be&&B.current&&R.current)try{B.current.fit();const{cols:mt,rows:Nt}=R.current;$.current?.(mt,Nt)}catch{}};window.addEventListener("resize",Et),G.current&&window.removeEventListener("resize",G.current),G.current=Et,d(!0),h(null)}catch(te){if($e&&clearTimeout($e),!Ye)return;const Ze=te instanceof Error?te.message:"xterm initialization failed";h(Ze)}})(),()=>{Ye=!1,$e&&clearTimeout($e)}},[T,e,J,H?.sessionId,i]),a.useEffect(()=>{e||(R.current&&(R.current.dispose(),R.current=null),B.current=null,L.current=!1,G.current&&(window.removeEventListener("resize",G.current),G.current=null),d(!1),h(null),K.current=!1,o(null),c(null),C(!1),A(null))},[e]),a.useEffect(()=>{if(!u||!R.current||!H)return;const be=H.sessionId,Pe=re=>{L.current===be&&R.current?.write(re)},Ye=Ee(re=>{Pe(re)}),$e=at(re=>{Pe(re)}),ft=Ue(re=>{O(H.id,jd(re.shell)||re.shell)}),Z=Te(re=>{L.current===be&&(c(re),R.current?.write(`\r
658
+ \x1B[33m[Process exited with code ${re}]\x1B[0m\r
659
+ `))});return()=>{Ye(),$e(),ft(),Z()}},[u,H?.sessionId,H?.id,H,de,Ee,at,Ue,Te,O]),a.useEffect(()=>{de==="connected"&&s&&K.current!==s&&H&&(K.current=s,setTimeout(()=>{me(s+`
660
+ `)},500))},[de,s,me,H,f]),a.useEffect(()=>{if(!u||!R.current)return;R.current.options.fontSize=y,N.current!==null&&(cancelAnimationFrame(N.current),N.current=null);const be=requestAnimationFrame(()=>{N.current=null,Xe()});return N.current=be,()=>{N.current===be&&(cancelAnimationFrame(be),N.current=null)}},[y,u,Xe]),a.useEffect(()=>{if(!e)return;const be=Pe=>{if(!(!Pe.ctrlKey&&!Pe.metaKey)){if(Pe.code==="Equal"||Pe.code==="NumpadAdd"){Pe.preventDefault(),w(Ye=>mr(Ye+1));return}if(Pe.code==="Minus"||Pe.code==="NumpadSubtract"){Pe.preventDefault(),w(Ye=>mr(Ye-1));return}if(Pe.code==="Digit0"||Pe.code==="Numpad0"){Pe.preventDefault(),w(ur);return}}};return window.addEventListener("keydown",be),()=>window.removeEventListener("keydown",be)},[e,Xe]),a.useEffect(()=>{if(!e)return;const be=Pe=>{Pe.key==="Escape"&&n()};return document.addEventListener("keydown",be),()=>document.removeEventListener("keydown",be)},[e,n]),a.useEffect(()=>{de==="connected"&&R.current&&setTimeout(()=>{if(!R.current||!S.current)return;const be=S.current.querySelector(".xterm-helper-textarea");be&&be.focus();try{S.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[de]);const De=a.useCallback(()=>{if(!S.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;R.current?.focus();const Pe=S.current.querySelector(".xterm-helper-textarea");if(!Pe)return;Pe.autocapitalize="off",Pe.autocomplete="off",Pe.autocorrect="off",Pe.spellcheck=!1,Pe.setAttribute("inputmode","text");try{Pe.focus({preventScroll:!0})}catch{Pe.focus()}const Ye=Pe.value.length;Pe.setSelectionRange(Ye,Ye)},[]);a.useEffect(()=>Ve(()=>{R.current?.clear(),c(null),K.current=!1,R.current&&(R.current.dispose(),R.current=null),B.current=null,L.current=!1,G.current&&(window.removeEventListener("resize",G.current),G.current=null),d(!1),h(null),ge().catch(Pe=>{console.error("Failed to replace invalid terminal session:",Pe)})}),[Ve,ge]);const Be=a.useCallback(be=>{be.target===be.currentTarget&&(_.current=!0)},[]),oe=a.useCallback(be=>{_.current&&be.target===be.currentTarget&&n(),_.current=!1},[n]),Ne=a.useCallback(()=>{R.current?.clear()},[]),se=a.useCallback(async()=>{R.current?.clear(),c(null),K.current=!1;try{await ne()}catch(be){o(we(be)||"Failed to restart terminal session")}},[ne]),Me=a.useCallback(()=>{R.current&&(R.current.dispose(),R.current=null),B.current=null,L.current=!1,G.current&&(window.removeEventListener("resize",G.current),G.current=null),h(null),d(!1)},[]),Le=a.useCallback(()=>{window.location.reload()},[]),pe=a.useCallback(()=>{w(be=>mr(be+1))},[]),Ae=a.useCallback(()=>{w(be=>mr(be-1))},[]),Je=a.useCallback(be=>{A(Pe=>Pe===be?null:be)},[]),it=a.useCallback(be=>{if(j==="ctrl"){me(PR(be)),A(null);return}if(j==="alt"){me(IR(be)),A(null);return}me(be)},[me,j]),ye=a.useCallback(be=>{me(be),A(null)},[me]);if(!e)return null;const ce=()=>{switch(de){case"connected":return t.jsx("span",{className:"terminal-status connected",title:"Connected"});case"connecting":case"reconnecting":return t.jsx("span",{className:"terminal-status connecting",title:"Connecting..."});case"disconnected":return t.jsx("span",{className:"terminal-status disconnected",title:"Disconnected"});default:return null}},Re=!J||!H&&!ue;return t.jsx("div",{className:"modal-overlay open",onMouseDown:Be,onMouseUp:oe,role:"dialog","aria-modal":"true","data-testid":"terminal-modal-overlay",style:g>0?{"--overlay-padding-top":"0px"}:void 0,children:t.jsxs("div",{ref:z,className:"modal terminal-modal","data-testid":"terminal-modal",style:g>0?{"--keyboard-overlap":`${g}px`,"--vv-height":v?`${v}px`:void 0}:void 0,children:[t.jsxs("div",{className:"terminal-header",children:[t.jsxs("div",{className:"terminal-tabs","data-testid":"terminal-tabs",children:[k.map(be=>t.jsxs("div",{className:`terminal-tab ${be.isActive?"terminal-tab--active":""}`,onClick:()=>he(be.id),title:be.title,role:"tab","aria-selected":be.isActive,children:[t.jsx("span",{className:"terminal-tab-label",children:be.title}),k.length>1&&t.jsx("button",{className:"terminal-tab-close",onClick:Pe=>{Pe.stopPropagation(),W(be.id)},title:"Close tab",children:"×"})]},be.id)),t.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:fe,title:"New terminal",children:"+"})]}),t.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[t.jsx(gi,{size:16}),ce()]}),t.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[de==="disconnected"&&H&&t.jsxs("button",{className:"terminal-reconnect-btn",onClick:et,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[t.jsx(Ln,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),l!==null&&t.jsxs("button",{className:"terminal-restart-btn",onClick:se,title:"New Session","data-testid":"terminal-restart-btn",children:[t.jsx(Ln,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:Ne,"data-testid":"terminal-clear-btn",title:"Clear terminal",children:[t.jsx(an,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Clear"})]}),t.jsxs("button",{className:"terminal-clear-btn terminal-clear-btn--shortcut",onClick:()=>C(be=>!be),"data-testid":"terminal-shortcut-toggle",title:"Shortcuts","aria-pressed":E,children:[t.jsx(_x,{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(Ht,{size:20})})]})]}),r&&t.jsx("div",{className:"terminal-error","data-testid":"terminal-error",children:r}),t.jsxs("div",{className:"terminal-container","data-testid":"terminal-container",children:[Re&&!ue&&t.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[t.jsx("div",{className:"terminal-spinner"}),t.jsx("span",{children:"Starting terminal..."})]}),ue&&!H&&t.jsx("div",{className:"terminal-loading","data-testid":"terminal-bootstrap-error",children:t.jsxs("div",{className:"terminal-error-content",children:[t.jsxs("span",{children:["Failed to start terminal: ",ue]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:Q,"data-testid":"terminal-retry-btn",children:[t.jsx(Ln,{size:14}),"Retry"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Le,"data-testid":"terminal-bootstrap-refresh-btn",children:[t.jsx(Ln,{size:14}),"Refresh page"]})]})]})}),m&&H&&t.jsx("div",{className:"terminal-loading","data-testid":"terminal-xterm-init-error",children:t.jsxs("div",{className:"terminal-error-content",children:[t.jsxs("span",{children:["Terminal UI failed to initialize: ",m]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:Me,"data-testid":"terminal-reinit-btn",children:[t.jsx(Ln,{size:14}),"Reinitialize"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Le,"data-testid":"terminal-xterm-refresh-btn",children:[t.jsx(Ln,{size:14}),"Refresh page"]})]})]})}),t.jsx("div",{ref:S,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:De,onTouchStart:De},H?.sessionId)]}),E&&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 ${j==="ctrl"?"is-active":""}`,"data-testid":"terminal-modifier-ctrl",onClick:()=>Je("ctrl"),"aria-pressed":j==="ctrl",children:"Ctrl"}),t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${j==="alt"?"is-active":""}`,"data-testid":"terminal-modifier-alt",onClick:()=>Je("alt"),"aria-pressed":j==="alt",children:"Alt"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>ye("\x1B"),children:"ESC"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>ye(" "),children:"Tab"})]}),$R.map(be=>t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>it(be.key),title:be.description,children:be.label},be.label))]}),t.jsxs("div",{className:"terminal-status-bar","data-testid":"terminal-status-bar",children:[t.jsxs("span",{className:`terminal-connection-status ${de}`,children:[de==="connected"&&"Connected",de==="connecting"&&"Connecting...",de==="reconnecting"&&"Reconnecting...",de==="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:Ae,"data-testid":"terminal-font-size-decrease","aria-label":"Decrease terminal font size",children:t.jsx(Kx,{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:pe,"data-testid":"terminal-font-size-increase","aria-label":"Increase terminal font size",children:t.jsx(rn,{size:14})})]}),t.jsx("span",{className:"terminal-shortcuts",children:"Ctrl++/- zoom • ⌨ Shortcuts panel • Esc close"})]})]})})}const er={name:"",command:""};function kh(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function HR(e,n=60){return e.length<=n?e:e.slice(0,n-3)+"..."}function qR({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,f]=a.useState(null),[p,g]=a.useState(er),[b,v]=a.useState(!1),[x,y]=a.useState(null),[w,E]=a.useState(null),C=Mi(n),j=a.useCallback(async()=>{try{u(!0);const U=await Cr(i);l(U)}catch(U){s(we(U)||"Failed to load scripts","error")}finally{u(!1)}},[s,i]);a.useEffect(()=>{e&&j()},[e,j]);const A=a.useCallback(()=>{m(!0),f(null),g(er),E(null)},[]),S=a.useCallback((U,G)=>{f(U),m(!1),g({name:U,command:G}),E(null)},[]),z=a.useCallback(()=>{f(null),m(!1),g(er),E(null)},[]),_=a.useCallback(U=>{g(G=>({...G,name:U})),U&&!kh(U)?E("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):E(null)},[]),R=a.useCallback(async()=>{const U=p.name.trim(),G=p.command.trim();if(!U){s("Script name is required","error");return}if(!kh(U)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!G){s("Script command is required","error");return}v(!0);try{await lk(U,G,i),s(h?"Script updated":"Script created","success"),f(null),m(!1),g(er),E(null),await j()}catch(Y){const ee=we(Y);ee?.includes("already exists")?s("A script with this name already exists","error"):s(ee||"Failed to save script","error")}finally{v(!1)}},[p,h,s,j,i]),B=a.useCallback(async U=>{try{await ck(U,i),s("Script deleted","success"),y(null),h===U&&(f(null),g(er)),await j()}catch(G){s(we(G)||"Failed to delete script","error")}},[h,s,j,i]),K=a.useCallback((U,G)=>{r&&r(U,G)},[r]);if(!e)return null;const L=d||h!==null,$=Object.entries(o).map(([U,G])=>({name:U,command:G}));return t.jsx("div",{className:"modal-overlay open",...C,"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(gi,{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(ot,{size:24,className:"spin",style:{margin:"0 auto 8px",display:"block"}}),"Loading scripts..."]}):L?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:U=>_(U.target.value),placeholder:"e.g., build, test, lint",disabled:b||h!==null,"data-testid":"script-name-input",style:{width:"100%",borderColor:w?"var(--color-error)":void 0}}),w&&t.jsx("div",{style:{fontSize:"12px",color:"var(--color-error)",marginTop:"4px"},"data-testid":"script-name-error",children:w}),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:U=>g(G=>({...G,command:U.target.value})),placeholder:"e.g., npm run build",rows:3,disabled:b,"data-testid":"script-command-input",style:{width:"100%",resize:"vertical",fontFamily:"monospace"}})]}),t.jsxs("div",{className:"scripts-modal-form-actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end"},children:[t.jsx("button",{className:"btn btn-secondary",onClick:z,disabled:b,"data-testid":"script-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:R,disabled:b||!!w,"data-testid":"script-save-btn",children:b?t.jsxs(t.Fragment,{children:[t.jsx(ot,{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:$.length===0?"No scripts defined":`${$.length} script${$.length===1?"":"s"}`}),t.jsxs("button",{className:"btn btn-primary",onClick:A,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx(rn,{size:14}),"Add Script"]})]}),$.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(gi,{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:$.map(U=>t.jsx("div",{className:"script-card","data-testid":`script-${U.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:U.name})}),t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:U.command,children:HR(U.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(U.name,U.command),title:"Run script","aria-label":`Run ${U.name}`,"data-testid":`run-script-${U.name}`,style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 10px",fontSize:"12px"},children:[t.jsx(Cn,{size:12}),"Run"]}),t.jsx("button",{className:"btn-icon",onClick:()=>S(U.name,U.command),title:"Edit","aria-label":`Edit ${U.name}`,"data-testid":`edit-script-${U.name}`,children:t.jsx(rn,{size:14,style:{transform:"rotate(45deg)"}})}),x===U.name?t.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[t.jsx("button",{className:"btn-icon",onClick:()=>B(U.name),title:"Confirm delete","aria-label":`Confirm delete ${U.name}`,"data-testid":`confirm-delete-script-${U.name}`,style:{color:"var(--color-error)"},children:t.jsx(an,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>y(null),title:"Cancel delete","aria-label":"Cancel delete","data-testid":`cancel-delete-script-${U.name}`,children:t.jsx(Ht,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>y(U.name),title:"Delete","aria-label":`Delete ${U.name}`,"data-testid":`delete-script-${U.name}`,children:t.jsx(an,{size:14})})]})]})},U.name))})]})})]})})}function VR(e,n,s){const[i,r]=a.useState([]),[o,l]=a.useState("."),[c,u]=a.useState(!1),[d,m]=a.useState(null),[h,f]=a.useState(0),p=a.useCallback(()=>{f(b=>b+1)},[]),g=a.useCallback(b=>{l(b),m(null)},[]);return a.useEffect(()=>{l("."),m(null),r([])},[e]),a.useEffect(()=>{if(!n||!e)return;let b=!1;async function v(){u(!0),m(null);try{const x=await Nj(e,o==="."?void 0:o,s);b||r(x.entries)}catch(x){b||(m(we(x)||"Failed to load files"),r([]))}finally{b||u(!1)}}return v(),()=>{b=!0}},[e,o,n,h,s]),{entries:i,currentPath:o,setPath:g,loading:c,error:d,refresh:p}}function WR(e,n,s,i){const[r,o]=a.useState(""),[l,c]=a.useState(""),[u,d]=a.useState(null),[m,h]=a.useState(!1),[f,p]=a.useState(!1),[g,b]=a.useState(null),v=a.useCallback(w=>{o(w),b(null)},[]);a.useEffect(()=>{if(!e||!n){o(""),c(""),d(null),b(null);return}let w=!1;async function E(){h(!0),b(null);try{const C=await Sj(e,n,i);w||(o(C.content),c(C.content),d(C.mtime))}catch(C){w||(b(we(C)||"Failed to load file"),o(""),c(""),d(null))}finally{w||h(!1)}}return E(),()=>{w=!0}},[e,n,s,i]);const x=r!==l,y=a.useCallback(async()=>{if(!(!e||!n||!x)){p(!0),b(null);try{const w=await Cj(e,n,r,i);c(r),d(w.mtime)}catch(w){throw b(we(w)||"Failed to save file"),w}finally{p(!1)}}},[e,n,r,x,i]);return{content:r,setContent:v,originalContent:l,loading:m,saving:f,error:g,save:y,hasChanges:x,mtime:u}}const KR=1e4;function GR(e){const s=e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||e||"Project Root"}function JR(e){return{id:e.id,label:e.id,title:e.title,worktree:e.worktree,kind:"task"}}function YR(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 f=await wj(e);if(d)return;s(GR(f.project)),r(f.tasks.map(JR)),u(null)}catch(f){d||u(we(f)||"Failed to load workspaces")}finally{d||l(!1)}}m();const h=window.setInterval(()=>{m()},KR);return()=>{d=!0,window.clearInterval(h)}},[e]),{projectName:n,workspaces:i,loading:o,error:c}}function QR(e){return e===void 0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function XR(e){return e?new Date(e).toLocaleDateString():""}function wh(e,n){return Qw(e,n)}const tr={visible:!1,x:0,y:0,entry:null,entryFullPath:""},fc={type:null,entry:null,entryFullPath:""},ZR=200,eT=500,Nh=10;function tT({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(),f=window.visualViewport,p=f?.width&&f.width>0?f.width:window.innerWidth,g=f?.height&&f.height>0?f.height:window.innerHeight,b=f?.offsetLeft??0,v=f?.offsetTop??0,x=8;let y=e-b,w=n-v;y+h.width>p-x&&(y=p-x-h.width),w+h.height>g-x&&(w=g-x-h.height),y<x&&(y=x),w<x&&(w=x),c({x:y+b,y:w+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:Ui,disabled:!1},{id:"move",label:"Move",icon:Yx,disabled:!1},{id:"rename",label:"Rename",icon:hs,disabled:!1},...u?[{id:"download-zip",label:"Download as ZIP",icon:Rr,disabled:!1}]:[{id:"download",label:"Download",icon:Bb,disabled:!1}],{id:"divider",label:"",icon:Ui,disabled:!0},{id:"delete",label:"Delete",icon:an,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 nT({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 g=n.name.lastIndexOf(".");g>0?c.current.setSelectionRange(0,g):c.current.select()}},[e,n.name]);const h=g=>{g.key==="Enter"&&d.trim()&&i(d.trim()),g.key==="Escape"&&r()};if(e==="delete")return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsxs("div",{className:"file-browser-dialog",onClick:g=>g.stopPropagation(),children:[t.jsxs("div",{className:"file-browser-dialog-title",children:["Delete ",n.type==="directory"?"Folder":"File"]}),t.jsxs("div",{className:"file-browser-dialog-message",children:["Are you sure you want to delete ",t.jsx("strong",{children:n.name}),"?",n.type==="directory"&&" This will delete all contents recursively."]}),l&&t.jsx("div",{className:"file-browser-dialog-error",children:l}),t.jsxs("div",{className:"file-browser-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:r,disabled:o,children:"Cancel"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>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:g=>g.stopPropagation(),children:[t.jsx("div",{className:"file-browser-dialog-title",children:p.title}),t.jsx("div",{className:"file-browser-dialog-info",children:e==="rename"?n.name:s}),t.jsx("input",{ref:c,className:"file-browser-dialog-input",type:"text",value:d,onChange:g=>m(g.target.value),placeholder:p.placeholder,onKeyDown:h,disabled:o}),l&&t.jsx("div",{className:"file-browser-dialog-error",children:l}),t.jsxs("div",{className:"file-browser-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:r,disabled:o,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>i(d.trim()),disabled:o||!d.trim(),children:o?`${p.confirm}ing...`:p.confirm})]})]})})}function sT({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(tr),[f,p]=a.useState(fc),[g,b]=a.useState(!1),[v,x]=a.useState(null),[y,w]=a.useState(!1),[E,C]=a.useState(null),j=a.useRef(null),A=a.useRef(null),S=a.useRef(null),z=a.useRef(!1),_=a.useCallback(()=>{j.current!==null&&(window.clearTimeout(j.current),j.current=null),A.current!==null&&(window.clearTimeout(A.current),A.current=null)},[]),R=a.useCallback(()=>{_(),S.current=null,w(!1),C(null)},[_]);a.useEffect(()=>()=>{_()},[_]);const B=a.useCallback((I,T,k,H)=>{h({visible:!0,x:I,y:T,entry:k,entryFullPath:H})},[]),K=a.useCallback((I,T,k)=>{if(I.touches.length!==1)return;const H=I.touches[0];H&&(R(),S.current={x:H.clientX,y:H.clientY},A.current=window.setTimeout(()=>{w(!0),C(k)},ZR),j.current=window.setTimeout(()=>{const J=S.current;J&&(z.current=!0,w(!1),C(null),_(),B(J.x,J.y,T,k))},eT))},[R,_,B]),L=a.useCallback(I=>{const T=S.current,k=I.touches[0];!T||!k||(Math.abs(k.clientX-T.x)>Nh||Math.abs(k.clientY-T.y)>Nh)&&R()},[R]),$=a.useCallback(()=>{R()},[R]);a.useEffect(()=>{if(!m.visible)return;const I=document.querySelector(".file-browser-list"),T=()=>{z.current=!1,R(),h(tr)};return I?.addEventListener("scroll",T),()=>I?.removeEventListener("scroll",T)},[R,m.visible]),a.useEffect(()=>{if(!m.visible)return;const I=T=>{T.key==="Escape"&&(z.current=!1,h(tr))};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[m.visible]);const U=a.useCallback((I,T)=>{I.preventDefault(),I.stopPropagation(),R(),z.current=!1,B(I.clientX,I.clientY,T,wh(n,T.name))},[R,n,B]),G=a.useCallback(I=>{if(!m.entry)return;z.current=!1;const T=m.entry,k=m.entryFullPath;if(h(tr),I==="download"){if(!c)return;const H=Ep(c,k,d);window.open(oi(H),"_blank");return}if(I==="download-zip"){if(!c)return;const H=Tj(c,k,d);window.open(oi(H),"_blank");return}p({type:I,entry:T,entryFullPath:k}),x(null)},[m,c,d]),Y=a.useCallback(async I=>{if(!(!f.type||!f.entry||!c)){b(!0),x(null);try{switch(f.type){case"copy":await _j(c,f.entryFullPath,I,d);break;case"move":await Mj(c,f.entryFullPath,I,d);break;case"rename":await Rj(c,f.entryFullPath,I,d);break;case"delete":await Aj(c,f.entryFullPath,d);break}p(fc),u?.()}catch(T){x(we(T)||"Operation failed")}finally{b(!1)}}},[f,c,u,d]),ee=a.useCallback(()=>{p(fc),x(null)},[]),N=a.useCallback((I,T)=>{if(z.current){z.current=!1;return}m.visible||(I.type==="directory"?i(T):s(T))},[m.visible,i,s]);return r?t.jsxs("div",{className:"file-browser-loading",children:[t.jsx(ot,{className:"spin",size:24}),t.jsx("span",{children:"Loading files..."})]}):o?t.jsxs("div",{className:"file-browser-error",children:[t.jsxs("p",{children:["Error: ",o]}),l&&t.jsx("button",{className:"btn btn-sm",onClick:l,children:"Retry"})]}):t.jsxs("div",{className:"file-browser",children:[t.jsxs("div",{className:"file-browser-header",children:[n!=="."&&t.jsxs("button",{className:"file-browser-up",onClick:()=>{i(Xw(n))},children:[t.jsx(xn,{size:16,style:{transform:"rotate(-90deg)"}}),"Up one level"]}),t.jsx("span",{className:"file-browser-path",children:n==="."?"Root":Pa(n)})]}),t.jsx("div",{className:"file-browser-list",children:e.length===0?t.jsx("div",{className:"file-browser-empty",children:"(empty directory)"}):e.map(I=>{const T=wh(n,I.name),k=y&&E===T;return t.jsxs("div",{className:`file-node file-node--${I.type} ${k?"file-node--long-pressing":""}`,onClick:()=>N(I,T),onContextMenu:H=>U(H,I),onTouchStart:H=>K(H,I,T),onTouchMove:L,onTouchEnd:$,onTouchCancel:$,children:[t.jsx("div",{className:"file-node-icon",children:I.type==="directory"?t.jsx(Xn,{size:16}):t.jsx(pp,{size:16})}),t.jsx("div",{className:"file-node-name",children:I.name}),I.type==="file"&&I.size!==void 0&&t.jsx("div",{className:"file-node-size",children:QR(I.size)}),I.mtime&&t.jsx("div",{className:"file-node-time",children:XR(I.mtime)})]},I.name)})}),m.visible&&m.entry&&t.jsx(tT,{x:m.x,y:m.y,entry:m.entry,onAction:G,onClose:()=>{z.current=!1,h(tr)}}),f.type&&f.entry&&t.jsx(nT,{type:f.type,entry:f.entry,entryFullPath:f.entryFullPath,onConfirm:Y,onCancel:ee,loading:g,error:v})]})}function iT(e){if(!e)return!1;const n=e.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function aT({content:e,onChange:n,readOnly:s,filePath:i}){const[r,o]=a.useState(!1),[l,c]=a.useState(!0),u=iT(i),d=u&&(s?!0:r),m=a.useCallback(()=>{o(!1)},[]),h=a.useCallback(()=>{o(!0)},[]),f=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(hp,{size:14}),"Edit"]}),t.jsxs("button",{className:`btn btn-sm ${d?"btn-primary":""}`,onClick:h,disabled:d,"aria-label":"Preview mode",children:[t.jsx(Ma,{size:14}),"Preview"]})]}),!s&&t.jsx("button",{className:`btn btn-sm ${l?"btn-primary":""}`,onClick:f,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(Po,{size:14})})]}):!s&&t.jsxs("div",{className:"file-editor-toolbar",children:[t.jsx("div",{className:"file-editor-mode-toggle"}),t.jsx("button",{className:`btn btn-sm ${l?"btn-primary":""}`,onClick:f,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(Po,{size:14})})]}),d?t.jsx("div",{className:"file-editor-preview markdown-body",children:t.jsx(li,{remarkPlugins:[ci],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 rT(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function oT({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(Gd,{size:14}):t.jsx(Rc,{size:14}),t.jsx("span",{className:"workspace-selector-trigger-label",children:l}),t.jsx(Xt,{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(Gd,{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(Rc,{size:14}),t.jsx("span",{children:c.id})]}),c.title&&t.jsx("span",{className:"workspace-selector-option-meta",title:c.title,children:rT(c.title)})]},c.id))]})]})]})}const lT=768,cT=280,vo=180,yo=500,Sh="fusion:file-browser-sidebar-width",jg=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),dT=new Set([...jg,".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 Ch(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return dT.has(n)}function uT(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return jg.has(n)}function mT({initialWorkspace:e="project",onClose:n,onWorkspaceChange:s,projectId:i}){const{projectName:r,workspaces:o}=YR(i),l=a.useRef(null);di(l,!0,"fusion:files-modal-size");const c=Mi(n),[u,d]=a.useState(e),[m,h]=a.useState(null),[f,p]=a.useState(!1),[g,b]=a.useState("list"),[v,x]=a.useState(cT),{entries:y,currentPath:w,setPath:E,loading:C,error:j,refresh:A}=VR(u,!0,i),{content:S,setContent:z,originalContent:_,loading:R,saving:B,error:K,save:L,hasChanges:$,mtime:U}=WR(u,m,!0,i);a.useEffect(()=>{d(e)},[e]),a.useEffect(()=>{const W=()=>{p(window.innerWidth<=lT)};return W(),window.addEventListener("resize",W),()=>window.removeEventListener("resize",W)},[]),a.useEffect(()=>{m||b("list")},[m]),a.useEffect(()=>{try{const W=localStorage.getItem(Sh);if(!W)return;const he=Number.parseInt(W,10);if(!Number.isNaN(he)){const O=Math.max(vo,Math.min(yo,he));x(O)}}catch{}},[]),a.useEffect(()=>{const W=he=>{he.key==="Escape"&&n(),(he.metaKey||he.ctrlKey)&&he.key==="s"&&(he.preventDefault(),$&&!B&&L())};return document.addEventListener("keydown",W),()=>document.removeEventListener("keydown",W)},[n,$,B,L]);const G=a.useCallback(W=>{h(W),f&&b("editor")},[f]),Y=a.useCallback(()=>{b("list")},[]),ee=a.useCallback(()=>{z(_)},[_,z]),N=a.useCallback(W=>{d(W),h(null),b("list"),s?.(W)},[s]),I=a.useCallback(W=>{try{localStorage.setItem(Sh,String(W))}catch{}},[]),T=a.useCallback(W=>{if(f)return;W.preventDefault(),W.stopPropagation();const he=W.currentTarget;typeof he.setPointerCapture=="function"&&he.setPointerCapture(W.pointerId);const O=W.clientX,ne=v;let Q=ne;document.body.style.userSelect="none";const ge=me=>{const ie=me.clientX-O,Ee=Math.max(vo,Math.min(yo,ne+ie));Q=Ee,x(Ee)},de=me=>{typeof he.releasePointerCapture=="function"&&he.releasePointerCapture(me.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",ge),document.removeEventListener("pointerup",de),I(Q)};document.addEventListener("pointermove",ge),document.addEventListener("pointerup",de)},[f,I,v]),k=a.useCallback(W=>{if(f)return;const he=20;if(W.key!=="ArrowLeft"&&W.key!=="ArrowRight")return;W.preventDefault();const O=W.key==="ArrowLeft"?-he:he,ne=Math.max(vo,Math.min(yo,v+O));x(ne),I(ne)},[f,I,v]),J=`Files — ${a.useMemo(()=>u==="project"?"Project":o.find(W=>W.id===u)?.id??u,[u,o])}`,ue=a.useMemo(()=>!m||!uT(m)?null:Ep(u,m,i),[m,u,i]),fe=W=>{const he=new Blob([W]).size;return he<1024?`${he} B`:`${(he/1024).toFixed(1)} KB`};return t.jsx("div",{className:"modal-overlay open",...c,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal file-browser-modal",ref:l,children:[t.jsxs("div",{className:"modal-header file-browser-modal-header",children:[t.jsxs("div",{className:"file-browser-header-title",children:[t.jsx(Xn,{size:18}),t.jsx("span",{children:J}),m&&t.jsx("span",{className:"file-browser-header-path",children:m})]}),t.jsxs("div",{className:"file-browser-header-actions",children:[t.jsx(oT,{currentWorkspace:u,projectName:r,workspaces:o,onSelect:N}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Ht,{size:20})})]})]}),t.jsxs("div",{className:"file-browser-body",children:[t.jsx("div",{className:`file-browser-sidebar ${f?"mobile":""} ${g==="list"?"active":""}`,style:f?void 0:{width:`${v}px`},children:t.jsx(sT,{entries:y,currentPath:w,onSelectFile:G,onNavigate:E,loading:C,error:j,onRetry:A,workspace:u,onRefresh:A,projectId:i})}),!f&&t.jsx("div",{className:"file-browser-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":vo,"aria-valuemax":yo,"aria-valuenow":v,"aria-label":"Resize sidebar",tabIndex:0,onPointerDown:T,onKeyDown:k}),t.jsx("div",{className:`file-browser-content ${f?"mobile":""} ${g==="editor"?"active":""}`,children:m?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"file-browser-toolbar",children:[t.jsxs("div",{className:"file-browser-file-info",children:[f&&g==="editor"&&t.jsxs("button",{className:"file-browser-back-button",onClick:Y,"aria-label":"Back to file list",children:[t.jsx(_a,{size:16}),t.jsx("span",{children:"Back"})]}),m,Ch(m)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(ox,{size:12}),"Binary file — read only"]}),U&&t.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date(U).toLocaleString()]}),R&&t.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),t.jsx("div",{className:"file-browser-actions",children:!ue&&$&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:ee,disabled:B,children:[t.jsx(ov,{size:14}),"Discard"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void L(),disabled:B,children:[t.jsx(yp,{size:14}),B?"Saving...":"Save"]})]})})]}),K&&!ue&&t.jsx("div",{className:"file-browser-error-banner",children:K}),ue?t.jsx("div",{className:"file-browser-image-preview",children:t.jsx("img",{src:ue,alt:m??"",className:"file-browser-image"})}):t.jsx("div",{className:"file-editor-wrapper",children:t.jsx(aT,{content:S,onChange:z,filePath:m,readOnly:Ch(m)})}),!ue&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:fe(S)}),$&&t.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):t.jsxs("div",{className:"file-browser-placeholder",children:[t.jsx(Xn,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to edit"})]})})]})]})})}function hT(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 Ty();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:we(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 pT(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 fT(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}const kg="kb-usage-hidden-windows",wg="kb-usage-modal-size";function Eh(e){const n=Wn(wg,e);if(!n)return null;try{const s=JSON.parse(n);if(s&&typeof s.width=="number"&&typeof s.height=="number"&&s.width>0&&s.height>0)return{width:s.width,height:s.height}}catch{}return null}function _h(e){const n=Wn(kg,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 gT(e,n){fs(kg,JSON.stringify(e),n)}function Ng(e,n,s){return s[e]?.includes(n)??!1}function bT({window:e,viewMode:n,isHidden:s,onToggleHidden:i}){const r=fT(e.percentUsed),o=n==="remaining",l=Math.round(o?e.percentLeft:e.percentUsed),c=o?`${Math.round(e.percentLeft)}% remaining`:`${Math.round(e.percentUsed)}% used`,u=o?`${Math.round(e.percentUsed)}% used`:`${Math.round(e.percentLeft)}% left`;let d=e.resetText;if(!d&&e.resetAt){const v=new Date(e.resetAt).getTime()-Date.now();if(v>0){const x=Math.floor(v/36e5),y=Math.floor(x/24),w=x%24;y>0&&w>0?d=`resets in ${y}d ${w}h`:y>0?d=`resets in ${y}d`:x>0?d=`resets in ${x}h`:d=`resets in ${Math.floor(v/6e4)}m`}}const m=e.pace,h=m!==void 0;let f=0;h&&(f=o?100-m.percentElapsed:m.percentElapsed);const p=m?.status==="ahead",g=m?.status==="behind",b=m?.status==="on-track";return t.jsxs("div",{className:`usage-window ${s?"usage-window--hidden":""}`,children:[t.jsxs("div",{className:"usage-window-header",children:[t.jsx("span",{className:"usage-window-label",children:e.label}),t.jsxs("div",{className:"usage-window-header-controls",children:[!s&&t.jsx("span",{className:"usage-window-percentage",children:c}),!s&&t.jsx("button",{className:"btn-icon usage-window-hide-btn",onClick:i,"aria-label":`Hide ${e.label}`,"data-testid":"usage-window-hide-btn",children:t.jsx(Ma,{size:14})})]})]}),t.jsxs("div",{className:"usage-progress-wrapper",children:[t.jsx("div",{className:"usage-progress-bar",children:t.jsx("div",{className:`usage-progress-fill ${r}`,style:{width:`${l}%`},role:"progressbar","aria-valuenow":l,"aria-valuemin":0,"aria-valuemax":100,"aria-label":`${e.label}: ${c}`})}),h&&t.jsx("div",{className:"usage-pace-marker",style:{left:`${f}%`},"aria-hidden":"true","data-testid":"pace-marker"})]}),t.jsxs("div",{className:"usage-window-footer",children:[t.jsx("span",{className:"usage-window-left",children: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:pT(e.resetAt)})]})]}),h&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[p&&t.jsxs(t.Fragment,{children:[t.jsx(pd,{size:14,className:"pace-icon pace-ahead"}),t.jsx("span",{className:"pace-text pace-ahead",children:m.message})]}),g&&t.jsxs(t.Fragment,{children:[t.jsx(Mv,{size:14,className:"pace-icon pace-behind"}),t.jsx("span",{className:"pace-text pace-behind",children:m.message})]}),b&&t.jsxs(t.Fragment,{children:[t.jsx(wn,{size:14,className:"pace-icon pace-ontrack"}),t.jsx("span",{className:"pace-text pace-ontrack",children:m.message})]})]})]})}function xT(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 vT({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(An,{provider:xT(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=Ng(e.name,c.label,s);return t.jsx(bT,{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 yT(){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 jT({isOpen:e,onClose:n,projectId:s,anchorRect:i}){const{providers:r,loading:o,error:l,lastUpdated:c,refresh:u}=hT({autoRefresh:e}),[d,m]=a.useState(!1),[h,f]=a.useState(()=>typeof window<"u"?window.innerWidth>=769:!1),[p,g]=a.useState("used"),[b,v]=a.useState(()=>_h(s)),x=a.useRef(null),y=a.useRef(null),w=a.useRef(e),E=a.useRef(!1),[C,j]=a.useState(()=>Eh(s));a.useEffect(()=>{j(Eh(s))},[s]),a.useEffect(()=>{if(!e||!h)return;const I=y.current;if(!I||typeof ResizeObserver>"u")return;let T=null;const k=new ResizeObserver(H=>{const J=H[0];if(!J)return;const{width:ue,height:fe}=J.contentRect;ue<=0||fe<=0||(T&&clearTimeout(T),T=setTimeout(()=>{fs(wg,JSON.stringify({width:Math.round(ue),height:Math.round(fe)}),s)},250))});return k.observe(I),()=>{T&&clearTimeout(T),k.disconnect()}},[e,h,s]),a.useEffect(()=>{e||(E.current=!1)},[e]),a.useEffect(()=>{r.length>0&&(E.current=!0)},[r.length]),a.useEffect(()=>{if(typeof window>"u")return;const I=()=>{f(window.innerWidth>=769)};return window.addEventListener("resize",I),()=>window.removeEventListener("resize",I)},[]),a.useEffect(()=>{!w.current&&e&&(!c||Date.now()-c.getTime()>5e3)&&u(),w.current=e},[e,c,u]),a.useEffect(()=>{const I=Wn("kb-usage-view-mode",s);if(I==="used"||I==="remaining"){g(I);return}g("used")},[s]);const A=a.useCallback(I=>{g(I),fs("kb-usage-view-mode",I,s)},[s]);a.useEffect(()=>{v(_h(s))},[s]),a.useEffect(()=>{gT(b,s)},[b,s]);const S=a.useCallback((I,T)=>{v(k=>{if(Ng(I,T,k)){const H=(k[I]??[]).filter(J=>J!==T);if(H.length===0){const{[I]:J,...ue}=k;return ue}return{...k,[I]:H}}return{...k,[I]:[...k[I]??[],T]}})},[]),z=a.useCallback(I=>{v(T=>{if(!T[I])return T;const{[I]:k,...H}=T;return H})},[]),_=a.useCallback(async()=>{m(!0),await u(),m(!1)},[u]);a.useEffect(()=>{if(!e)return;const I=T=>{T.key==="Escape"&&n()};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[e,n]);const R=a.useCallback(I=>{I.target===I.currentTarget&&n()},[n]);if(!e)return null;const B=!!(i&&h),K=8,L=12,U=C?.width??420,G=B?Math.min((i?.bottom??0)+K,window.innerHeight-L):void 0,Y=B?Math.max(8,(i?.right??0)-U):void 0,ee=h&&C?{width:C.width,height:C.height}:{},N=t.jsxs("div",{ref:y,className:`usage-modal${B?" usage-modal--popover":" modal"}`,"data-testid":"usage-modal",style:B?{position:"fixed",top:G,left:Y,...ee}:ee,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"usage-header",children:[t.jsx(Ds,{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:()=>A("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:()=>A("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(Ht,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:x,children:(o||!E.current&&!l)&&r.length===0?t.jsx(yT,{}):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(I=>t.jsx(vT,{provider:I,viewMode:p,hiddenWindows:b,onToggleWindow:S,onShowAllHidden:z},I.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(Ln,{size:14,className:d?"spin":"",style:{marginRight:6}}),"Refresh"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]});return B?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"usage-popover-backdrop",onClick:n,"data-testid":"usage-modal-overlay"}),N]}):t.jsx("div",{className:"modal-overlay open",onClick:R,"data-testid":"usage-modal-overlay",children:N})}function Sg(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 Vo(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 kT={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},Cg={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},wT={cron:up,webhook:kp,api:mp,manual:Qn},NT={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},ST={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function CT({result:e}){const n=e.completedAt&&e.startedAt?new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime():0;return t.jsxs("span",{className:`schedule-run-badge ${e.success?"success":"failure"}`,children:[e.success?t.jsx(wn,{size:12}):t.jsx(Ir,{size:12}),t.jsx("span",{children:e.success?"Success":"Failed"}),n>0&&t.jsx("span",{className:"schedule-run-duration",children:Sg(n)})]})}function ET({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"} ${Vo(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx(wn,{size:12}):t.jsx(Ir,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:Vo(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:Cg[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:Sg(r)}),s?t.jsx(bi,{size:12}):t.jsx(Xt,{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 _T({routine:e,onEdit:n,onDelete:s,onRun:i,onToggle:r,running:o,lastRunOutput:l}){const[c,u]=a.useState(!1),{confirm:d}=Ks(),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=kT[e.trigger.type],f=wT[e.trigger.type],p=e.trigger.type==="cron"?("cronExpression"in e.trigger?e.trigger.cronExpression:void 0)||e.cronExpression||"":e.cronExpression||"";return t.jsxs("div",{className:`routine-card${e.enabled?"":" disabled"}${o?" running":""}`,children:[t.jsxs("div",{className:"routine-card-header",children:[t.jsxs("div",{className:"routine-card-info",children:[t.jsxs("div",{className:"routine-card-name-row",children:[t.jsx("span",{className:"routine-card-name",children:e.name}),t.jsxs("span",{className:"routine-trigger-badge",style:{borderColor:h,color:h},children:[t.jsx(f,{size:10}),Cg[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(Qo,{size:10}):t.jsx(Xn,{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(ot,{className:"spinner"}):t.jsx(Cn,{})}),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,{}):t.jsx(Cn,{})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:"Edit","aria-label":`Edit ${e.name}`,children:t.jsx(hs,{})}),t.jsx("button",{className:"btn-icon",onClick:m,title:"Delete","aria-label":`Delete ${e.name}`,children:t.jsx(an,{})})]})]}),t.jsxs("div",{className:"routine-card-meta",children:[e.steps&&e.steps.length>0?t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(Hi,{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(Ei,{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:NT[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:ST[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:Vo(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:Vo(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(CT,{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(g=>!g),"aria-expanded":c,children:[c?t.jsx(bi,{size:12}):t.jsx(Xt,{size:12}),t.jsxs("span",{children:["Run History (",e.runHistory.length,")"]})]}),c&&t.jsxs("div",{className:"schedule-history-list",children:[e.runHistory.slice(0,10).map((g,b)=>t.jsx(ET,{result:g,index:b},`${g.startedAt}-${b}`)),e.runHistory.length>10&&t.jsxs("div",{className:"schedule-history-more",children:["…and ",e.runHistory.length-10," more"]})]})]})]})}function MT({type:e,size:n=12}){return e==="command"?t.jsxs("span",{className:"step-type-badge step-type-command",title:"Command step",children:[t.jsx(gi,{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(Ix,{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(cs,{size:n}),t.jsx("span",{children:"AI Prompt"})]})}function gc(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function AT(e){return e==="command"?{id:gc(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:gc(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:gc(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function RT({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,f]=a.useState(e.modelProvider??""),[p,g]=a.useState(e.modelId??""),[b,v]=a.useState(e.taskTitle??""),[x,y]=a.useState(e.taskDescription??""),[w,E]=a.useState(e.taskColumn??"triage"),[C,j]=a.useState(e.timeoutMs),[A,S]=a.useState(e.continueOnFailure??!1),[z,_]=a.useState({}),[R,B]=a.useState([]),[K,L]=a.useState(!1),[$,U]=a.useState(null);a.useEffect(()=>{let I=!1;return L(!0),U(null),bs().then(T=>{I||B(T.models)}).catch(T=>{I||U(T instanceof Error?T.message:"Failed to load models")}).finally(()=>{I||L(!1)}),()=>{I=!0}},[]);const G=a.useCallback(()=>{const I={};return i.trim()||(I.name="Step name is required"),o==="command"&&!c.trim()&&(I.command="Command is required"),o==="ai-prompt"&&!d.trim()&&(I.prompt="Prompt is required"),o==="create-task"&&!x.trim()&&(I.taskDescription="Task description is required"),(o==="ai-prompt"||o==="create-task")&&(h||p)&&(!h||!p)&&(I.modelProvider="Both model provider and model ID must be set together"),C!==void 0&&C<1e3&&(I.timeoutMs="Timeout must be at least 1 second (1000ms)"),_(I),Object.keys(I).length===0},[i,o,c,d,x,h,p,C]),Y=h&&p?`${h}/${p}`:"",ee=a.useCallback(I=>{if(!I)f(""),g("");else{const T=I.indexOf("/");T!==-1&&(f(I.slice(0,T)),g(I.slice(T+1)))}},[]),N=a.useCallback(()=>{if(!G())return;const I={...e,name:i.trim(),type:o,command:o==="command"?c.trim():void 0,prompt:o==="ai-prompt"?d.trim():void 0,taskTitle:o==="create-task"&&b.trim()?b.trim():void 0,taskDescription:o==="create-task"&&x.trim()?x.trim():void 0,taskColumn:o==="create-task"?w: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:C||void 0,continueOnFailure:A};o!=="ai-prompt"&&delete I.prompt,o!=="create-task"&&(delete I.taskTitle,delete I.taskDescription,delete I.taskColumn),n(I)},[G,n,e,i,o,c,d,b,x,w,h,p,C,A]);return t.jsxs("div",{className:"step-editor",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-name-${e.id}`,children:"Step Name"}),t.jsx("input",{id:`step-name-${e.id}`,type:"text",placeholder:"e.g. Run tests",value:i,onChange:I=>r(I.target.value),"aria-invalid":!!z.name}),z.name&&t.jsx("small",{className:"field-error",children:z.name})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-type-${e.id}`,children:"Step Type"}),t.jsxs("select",{id:`step-type-${e.id}`,value:o,onChange:I=>l(I.target.value),children:[t.jsx("option",{value:"command",children:"Command"}),t.jsx("option",{value:"ai-prompt",children:"AI Prompt"}),t.jsx("option",{value:"create-task",children:"Create Task"})]})]}),o==="command"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-command-${e.id}`,children:"Command"}),t.jsx("textarea",{id:`step-command-${e.id}`,placeholder:"e.g. npm test",value:c,onChange:I=>u(I.target.value),rows:2,"aria-invalid":!!z.command}),z.command&&t.jsx("small",{className:"field-error",children:z.command})]}),o==="ai-prompt"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-prompt-${e.id}`,children:"Prompt"}),t.jsx("textarea",{id:`step-prompt-${e.id}`,placeholder:"e.g. Summarize the test results and highlight any failures",value:d,onChange:I=>m(I.target.value),rows:3,"aria-invalid":!!z.prompt}),z.prompt&&t.jsx("small",{className:"field-error",children:z.prompt})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-model-${e.id}`,children:"Model (optional)"}),t.jsx(Zn,{id:`step-model-${e.id}`,label:"Model",models:R,value:Y,onChange:ee,placeholder:"Use default",disabled:K}),$&&t.jsx("small",{className:"field-error",children:$}),t.jsx("small",{children:"AI model for this step. Uses default if not selected."})]})]}),o==="create-task"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-title-${e.id}`,children:"Task Title (optional)"}),t.jsx("input",{id:`step-task-title-${e.id}`,type:"text",placeholder:"e.g. Review weekly dependencies",value:b,onChange:I=>v(I.target.value)}),t.jsx("small",{children:"Leave blank to auto-summarize from description"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-description-${e.id}`,children:"Task Description *"}),t.jsx("textarea",{id:`step-task-description-${e.id}`,placeholder:"e.g. Check all npm dependencies for security vulnerabilities and update outdated packages",value:x,onChange:I=>y(I.target.value),rows:4,"aria-invalid":!!z.taskDescription}),z.taskDescription&&t.jsx("small",{className:"field-error",children:z.taskDescription})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-column-${e.id}`,children:"Target Column"}),t.jsxs("select",{id:`step-task-column-${e.id}`,value:w,onChange:I=>E(I.target.value),children:[t.jsx("option",{value:"triage",children:"Triage"}),t.jsx("option",{value:"todo",children:"To Do"})]}),t.jsx("small",{children:"Column where the new task will be created"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-model-${e.id}`,children:"Executor Model (optional)"}),t.jsx(Zn,{id:`step-task-model-${e.id}`,label:"Model",models:R,value:Y,onChange:ee,placeholder:"Use default",disabled:K}),$&&t.jsx("small",{className:"field-error",children:$}),z.modelProvider&&t.jsx("small",{className:"field-error",children:z.modelProvider}),t.jsx("small",{children:"AI model for executing the created task. Uses default if not selected."})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-timeout-${e.id}`,children:"Timeout (ms, optional)"}),t.jsx("input",{id:`step-timeout-${e.id}`,type:"number",min:1e3,step:1e3,placeholder:"Override schedule timeout",value:C??"",onChange:I=>j(I.target.value?Number(I.target.value):void 0),"aria-invalid":!!z.timeoutMs}),z.timeoutMs&&t.jsx("small",{className:"field-error",children:z.timeoutMs})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:`step-continue-${e.id}`,className:"checkbox-label",children:[t.jsx("input",{id:`step-continue-${e.id}`,type:"checkbox",checked:A,onChange:I=>S(I.target.checked)}),"Continue on failure"]}),t.jsx("small",{children:"If checked, the next step will run even if this one fails"})]}),t.jsxs("div",{className:"step-editor-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:N,children:"Save Step"})]})]})}function TT({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=AT(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(g=>g.id===d);if(h<0)return;const f=m==="up"?h-1:h+1;if(f<0||f>=e.length)return;const p=[...e];[p[h],p[f]]=[p[f],p[h]],n(p)},[e,n]),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(RT,{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(hd,{size:14})}),t.jsx("span",{className:"step-card-index",children:m+1}),t.jsx(MT,{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(bi,{})}),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(Xt,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(d.id),title:"Edit","aria-label":`Edit ${d.name}`,children:t.jsx(hs,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>l(d.id),title:"Delete","aria-label":`Delete ${d.name}`,children:t.jsx(an,{})})]})]})},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(rn,{size:14}),"Add Command Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ai-prompt"),children:[t.jsx(rn,{size:14}),"Add AI Prompt Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("create-task"),children:[t.jsx(rn,{size:14}),"Add Create Task Step"]})]})]})}const Eg={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},PT={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function IT(e){const n=e.trim();for(const[s,i]of Object.entries(Eg))if(i===n)return s;return"custom"}function $T(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function DT(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 LT(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 zT=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],FT=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function Mh(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function Ah({routine:e,onSubmit:n,onCancel:s,scope:i,projectId:r,onScopeChange:o}){const l=!!e,c=e?LT(e):{triggerType:"cron",cronExpression:"0 * * * *",webhookPath:"",webhookSecret:"",endpoint:""},[u,d]=a.useState(e?.name??""),[m,h]=a.useState(e?.description??""),[f,p]=a.useState(c.triggerType),[g,b]=a.useState(c.cronExpression),[v,x]=a.useState(()=>c.triggerType!=="cron"?"custom":IT(c.cronExpression)),[y,w]=a.useState(c.webhookPath),[E,C]=a.useState(c.webhookSecret),[j,A]=a.useState(c.endpoint),[S,z]=a.useState(e?.executionPolicy??"queue"),[_,R]=a.useState(e?.catchUpPolicy??"run_one"),[B,K]=a.useState(e?.enabled??!0),L=e?.steps&&e.steps.length===1&&e.steps[0].type==="ai-prompt"&&!e.command,$=e?.steps&&e.steps.length===1&&e.steps[0].type==="create-task"&&!e.command,[U,G]=a.useState(e?.steps&&e.steps.length>0&&!L&&!$?"advanced":"simple"),[Y,ee]=a.useState(()=>L?"ai-prompt":$?"create-task":"command"),[N,I]=a.useState(e?.command??""),[T,k]=a.useState(e?.steps??[]),[H,J]=a.useState(!1),[ue,fe]=a.useState(e?.timeoutMs??3e5),[W,he]=a.useState(L?e.steps?.[0]?.prompt??"":""),[O,ne]=a.useState($?e.steps?.[0]?.taskTitle??"":""),[Q,ge]=a.useState($?e.steps?.[0]?.taskDescription??"":""),[de,me]=a.useState($?e.steps?.[0]?.taskColumn??"triage":"triage"),[ie,Ee]=a.useState(L||$?e.steps?.[0]?.modelProvider??"":""),[Ue,Te]=a.useState(L||$?e.steps?.[0]?.modelId??"":""),[at,et]=a.useState([]),[Ve,Xe]=a.useState(!1),[De,Be]=a.useState(null),[oe,Ne]=a.useState(i??"global"),[se,Me]=a.useState({}),[Le,pe]=a.useState(!1),Ae=a.useRef(!0);a.useEffect(()=>()=>{Ae.current=!1},[]),a.useEffect(()=>{i&&Ne(i)},[i]),a.useEffect(()=>{let te=!1;return Xe(!0),Be(null),bs().then(Ze=>{te||et(Ze.models)}).catch(Ze=>{te||Be(Ze instanceof Error?Ze.message:"Failed to load models")}).finally(()=>{te||Xe(!1)}),()=>{te=!0}},[]);const Je=ie&&Ue?`${ie}/${Ue}`:"",it=a.useCallback(te=>{if(!te){Ee(""),Te("");return}const Ze=te.indexOf("/");Ze!==-1&&(Ee(te.slice(0,Ze)),Te(te.slice(Ze+1)))},[]),ye=a.useCallback(()=>{const te={};if(u.trim()||(te.name="Name is required"),oe==="project"&&!r&&(te.scope="Project-specific entries require an active project."),f==="cron"&&v==="custom"&&(g.trim()?$T(g)||(te.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):te.cronExpression="Cron expression is required"),f==="webhook"&&!y.trim()&&(te.webhookPath="Webhook path is required"),f==="api"&&!j.trim()&&(te.endpoint="API endpoint is required"),U==="simple")Y==="command"&&!N.trim()&&(te.command="Command is required"),Y==="ai-prompt"&&!W.trim()&&(te.prompt="Prompt is required"),Y==="create-task"&&!Q.trim()&&(te.taskDescription="Task description is required"),(ie.trim()&&!Ue.trim()||!ie.trim()&&Ue.trim())&&(te.model="Both model provider and model ID must be set, or both must be empty");else{T.length===0&&(te.steps="At least one step is required"),H&&(te.stepsEditing="Please save or cancel all step edits before saving the routine");const Ze=[];T.forEach((pt,gt)=>{pt.name?.trim()||Ze.push(`Step ${gt+1}: Name is required`),pt.type==="command"&&!pt.command?.trim()&&Ze.push(`Step ${gt+1}: Command is required`),pt.type==="ai-prompt"&&!pt.prompt?.trim()&&Ze.push(`Step ${gt+1}: Prompt is required`),pt.type==="create-task"&&!pt.taskDescription?.trim()&&Ze.push(`Step ${gt+1}: Task description is required`)}),Ze.length>0&&(te.steps=Ze.join("; "))}return ue<1e3&&(te.timeoutMs="Timeout must be at least 1 second (1000ms)"),Me(te),Object.keys(te).length===0},[u,f,g,v,y,j,oe,r,U,Y,N,W,Q,ie,Ue,T,H,ue]),ce=a.useCallback(async te=>{if(te.preventDefault(),!!ye()){pe(!0);try{let Ze=e?.scope??oe??(r?"project":"global");Ze==="project"&&!r&&(Ze="global");const pt=DT(f,g,y,E,j);let gt,wt;U==="simple"?Y==="command"?gt=N.trim()||void 0:Y==="ai-prompt"?wt=[{id:Mh(),type:"ai-prompt",name:u.trim(),prompt:W.trim(),modelProvider:ie.trim()||void 0,modelId:Ue.trim()||void 0}]:wt=[{id:Mh(),type:"create-task",name:u.trim(),taskTitle:O.trim()||void 0,taskDescription:Q.trim(),taskColumn:de,modelProvider:ie.trim()||void 0,modelId:Ue.trim()||void 0}]:wt=T;const Et={name:u.trim(),agentId:e?.agentId??"",description:m.trim()||void 0,trigger:pt,command:gt,steps:wt,timeoutMs:ue,executionPolicy:S,catchUpPolicy:_,enabled:B,scope:Ze};await n(Et)}finally{Ae.current&&pe(!1)}}},[ye,n,u,m,f,g,y,E,j,U,Y,N,W,ie,Ue,O,Q,de,T,ue,S,_,B,oe,r,e?.scope,e?.agentId]),Re="routine-name-error",be="routine-cron-error",Pe="routine-webhook-error",Ye="routine-endpoint-error",$e="routine-command-error",ft="routine-prompt-error",Z="routine-task-description-error",re="routine-model-error",je="routine-timeout-error",rt=a.useCallback(te=>{x(te),te!=="custom"&&b(Eg[te])},[]);return t.jsxs("form",{className:"routine-form",onSubmit:ce,noValidate:!0,children:[t.jsx("h4",{className:"settings-section-heading",children:l?"Edit Routine":"New Routine"}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-name",children:"Name"}),t.jsx("input",{id:"routine-name",type:"text",placeholder:"e.g. Daily standup reminder",value:u,onChange:te=>d(te.target.value),"aria-invalid":!!se.name,"aria-describedby":se.name?Re:void 0}),se.name&&t.jsx("small",{id:Re,className:"field-error",children:se.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:te=>h(te.target.value),rows:2})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Scope"}),t.jsxs("div",{className:"routine-scope-toggle",role:"radiogroup","aria-label":"Routine scope",children:[t.jsxs("button",{type:"button",className:`routine-scope-btn${oe==="global"?" active":""}`,onClick:()=>{Ne("global"),o?.("global")},role:"radio","aria-checked":oe==="global"?"true":"false",disabled:!!e?.scope,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:"Global scope",children:[t.jsx(Qo,{size:12}),"Global"]}),t.jsxs("button",{type:"button",className:`routine-scope-btn${oe==="project"?" active":""}`,onClick:()=>{Ne("project"),o?.("project")},role:"radio","aria-checked":oe==="project"?"true":"false",disabled:!!e?.scope||!r,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:r?"Project scope":"Select a project to enable project scope",children:[t.jsx(Xn,{size:12}),"Project"]})]}),t.jsx("small",{children:!r&&!e?.scope?"No active project. Routines will be created at global scope.":oe==="project"&&r?"This routine will be scoped to the current project.":"This routine will be created at global scope."}),se.scope&&t.jsx("small",{className:"field-error",children:se.scope})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Trigger Type"}),t.jsxs("div",{className:"routine-trigger-type-selector",role:"radiogroup","aria-label":"Trigger type",children:[t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="cron"?" active":""}`,onClick:()=>p("cron"),role:"radio","aria-checked":f==="cron",children:[t.jsx(up,{size:14}),"Cron"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="webhook"?" active":""}`,onClick:()=>p("webhook"),role:"radio","aria-checked":f==="webhook",children:[t.jsx(kp,{size:14}),"Webhook"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="api"?" active":""}`,onClick:()=>p("api"),role:"radio","aria-checked":f==="api",children:[t.jsx(mp,{size:14}),"API"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="manual"?" active":""}`,onClick:()=>p("manual"),role:"radio","aria-checked":f==="manual",children:[t.jsx(Qn,{size:14}),"Manual"]})]})]}),f==="cron"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-frequency",children:"Frequency"}),t.jsx("select",{id:"routine-frequency",value:v,onChange:te=>rt(te.target.value),children:Object.entries(PT).map(([te,Ze])=>t.jsx("option",{value:te,children:Ze},te))}),t.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),t.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:g,onChange:te=>b(te.target.value),disabled:v!=="custom","aria-invalid":!!se.cronExpression,"aria-describedby":se.cronExpression?be:void 0}),se.cronExpression?t.jsx("small",{id:be,className:"field-error",children:se.cronExpression}):t.jsx("small",{children:v==="custom"?t.jsxs(t.Fragment,{children:["min hour day month weekday — ",t.jsx("a",{href:"https://crontab.guru",target:"_blank",rel:"noopener noreferrer",children:"crontab.guru"})]}):`Auto-filled from preset: ${g}`})]}),f==="webhook"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-path",children:"Webhook Path"}),t.jsx("input",{id:"routine-webhook-path",type:"text",placeholder:"/trigger/my-routine",value:y,onChange:te=>w(te.target.value),"aria-invalid":!!se.webhookPath,"aria-describedby":se.webhookPath?Pe:void 0}),se.webhookPath?t.jsx("small",{id:Pe,className:"field-error",children:se.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:E,onChange:te=>C(te.target.value)}),t.jsx("small",{children:"HMAC secret for signature verification. Leave empty for unauthenticated webhooks."})]})]}),f==="api"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-endpoint",children:"API Endpoint"}),t.jsx("input",{id:"routine-endpoint",type:"text",placeholder:"/api/routine/my-routine",value:j,onChange:te=>A(te.target.value),"aria-invalid":!!se.endpoint,"aria-describedby":se.endpoint?Ye:void 0}),se.endpoint?t.jsx("small",{id:Ye,className:"field-error",children:se.endpoint}):t.jsx("small",{children:"API endpoint path that triggers this routine"})]}),f==="manual"&&t.jsx("div",{className:"form-group",children:t.jsx("small",{className:"routine-trigger-info",children:"This routine will be triggered manually via the dashboard or API."})}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Action Mode"}),t.jsxs("div",{className:"schedule-mode-toggle",role:"radiogroup","aria-label":"Action mode",children:[t.jsx("button",{type:"button",className:`schedule-mode-btn${U==="simple"?" active":""}`,onClick:()=>G("simple"),role:"radio","aria-checked":U==="simple",children:"Simple"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${U==="advanced"?" active":""}`,onClick:()=>G("advanced"),role:"radio","aria-checked":U==="advanced",children:"Multi-Step"})]}),t.jsx("small",{children:U==="simple"?"Run one command, prompt, or task creation action":"Run multiple actions sequentially"})]}),U==="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${Y==="command"?" active":""}`,onClick:()=>ee("command"),role:"radio","aria-checked":Y==="command",children:"Command"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${Y==="ai-prompt"?" active":""}`,onClick:()=>ee("ai-prompt"),role:"radio","aria-checked":Y==="ai-prompt",children:"AI Prompt"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${Y==="create-task"?" active":""}`,onClick:()=>ee("create-task"),role:"radio","aria-checked":Y==="create-task",children:"Create Task"})]})]}),Y==="command"?t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-command",children:"Command"}),t.jsx("input",{id:"routine-command",type:"text",placeholder:"e.g. npx runfusion.ai backup --create",value:N,onChange:te=>I(te.target.value),"aria-invalid":!!se.command,"aria-describedby":se.command?$e:void 0}),se.command?t.jsx("small",{id:$e,className:"field-error",children:se.command}):t.jsx("small",{children:"Shell command to execute."})]}):Y==="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:W,onChange:te=>he(te.target.value),rows:3,"aria-invalid":!!se.prompt,"aria-describedby":se.prompt?ft:void 0}),se.prompt?t.jsx("small",{id:ft,className:"field-error",children:se.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(Zn,{id:"routine-model",label:"Model",models:at,value:Je,onChange:it,placeholder:"Use default",disabled:Ve}),De&&t.jsx("small",{className:"field-error",children:De}),se.model&&t.jsx("small",{id:re,className:"field-error",children:se.model})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-title",children:"Task Title (optional)"}),t.jsx("input",{id:"routine-task-title",type:"text",placeholder:"e.g. Review weekly dependencies",value:O,onChange:te=>ne(te.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:Q,onChange:te=>ge(te.target.value),rows:4,"aria-invalid":!!se.taskDescription,"aria-describedby":se.taskDescription?Z:void 0}),se.taskDescription?t.jsx("small",{id:Z,className:"field-error",children:se.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:de,onChange:te=>me(te.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(Zn,{id:"routine-task-model",label:"Executor Model",models:at,value:Je,onChange:it,placeholder:"Use default",disabled:Ve}),De&&t.jsx("small",{className:"field-error",children:De}),se.model&&t.jsx("small",{id:re,className:"field-error",children:se.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(TT,{steps:T,onChange:k,onEditingChange:J}),se.steps&&t.jsx("small",{className:"field-error",children:se.steps}),se.stepsEditing&&t.jsx("small",{className:"field-error",children:se.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:ue,onChange:te=>fe(Number(te.target.value)),"aria-invalid":!!se.timeoutMs,"aria-describedby":se.timeoutMs?je:void 0}),se.timeoutMs?t.jsx("small",{id:je,className:"field-error",children:se.timeoutMs}):t.jsx("small",{children:"Maximum execution time in milliseconds."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-execution-policy",children:"Execution Policy"}),t.jsx("select",{id:"routine-execution-policy",value:S,onChange:te=>z(te.target.value),children:zT.map(te=>t.jsx("option",{value:te.value,children:te.label},te.value))}),t.jsx("small",{children:"How to handle concurrent executions of this routine"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-catchup-policy",children:"Catch-up Policy"}),t.jsx("select",{id:"routine-catchup-policy",value:_,onChange:te=>R(te.target.value),children:FT.map(te=>t.jsx("option",{value:te.value,children:te.label},te.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:B,onChange:te=>K(te.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:Le,children:"Cancel"}),t.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:Le,children:Le?"Saving…":l?"Save Changes":"Create Routine"})]})]})}const OT=3e4;function UT({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,f]=a.useState(null),[p,g]=a.useState({}),b=a.useRef(null);di(b,!0,"fusion:automation-modal-size");const v=a.useMemo(()=>({scope:i,projectId:i==="project"?s:void 0}),[i,s]),x=a.useCallback(async()=>{try{const L=await Xj(v);l(L),g($=>{const U={...$};for(const G of L){const Y=U[G.id];if(!Y||!G.lastRunResult)continue;const ee=G.lastRunResult;ee.success===Y.success&&(ee.output||"")===Y.output&&(ee.error||"")===(Y.error||"")&&delete U[G.id]}return U})}catch(L){n(we(L)||"Failed to load routines","error")}},[n,v]);a.useEffect(()=>{x()},[x]),a.useEffect(()=>{const L=setInterval(()=>{x()},OT);return()=>clearInterval(L)},[x]),a.useEffect(()=>{const L=$=>{$.key==="Escape"&&(c!=="list"?(u("list"),m(void 0)):e())};return document.addEventListener("keydown",L),()=>document.removeEventListener("keydown",L)},[e,c]);const y=Mi(e),w=a.useCallback(async L=>{try{await Zj(L,v),n("Routine created","success"),u("list"),await x()}catch($){n(we($)||"Failed to create routine","error")}},[n,x,v]),E=a.useCallback(L=>{m(L),u("edit")},[]),C=a.useCallback(async L=>{if(d)try{await du(d.id,L,v),n("Routine updated","success"),u("list"),m(void 0),await x()}catch($){n(we($)||"Failed to update routine","error")}},[d,n,x,v]),j=a.useCallback(async L=>{try{await ek(L.id,v),n(`Deleted "${L.name}"`,"success"),await x()}catch($){n(we($)||"Failed to delete routine","error")}},[n,x,v]),A=a.useCallback(async L=>{f(L.id);try{const{result:$}=await tk(L.id,v);g(U=>({...U,[L.id]:{output:$.output||"",error:$.error,success:$.success}})),$.success?n(`"${L.name}" completed successfully`,"success"):n(`"${L.name}" failed: ${$.error||"Unknown error"}`,"error"),await x()}catch($){n(we($)||"Failed to run routine","error")}finally{f(null)}},[n,x,v]),S=a.useCallback(async L=>{try{await du(L.id,{enabled:!L.enabled},v),n(`"${L.name}" ${L.enabled?"disabled":"enabled"}`,"success"),await x()}catch($){n(we($)||"Failed to toggle routine","error")}},[n,x,v]),z=a.useCallback(()=>{u("list"),m(void 0)},[]);a.useEffect(()=>{c!=="list"&&g({})},[c]);const _=a.useCallback(L=>{r(L),u("list"),m(void 0),g({})},[]),R=()=>c==="create"?t.jsx(Ah,{onSubmit:w,onCancel:z,scope:i,projectId:s}):c==="edit"&&d?t.jsx(Ah,{routine:d,onSubmit:C,onCancel:z,scope:i,projectId:s}):o.length===0?t.jsxs("div",{className:"routine-empty-state",children:[t.jsx(Qn,{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(rn,{size:14}),"Create your first automation"]})]}):t.jsx("div",{className:"routine-list",children:o.map(L=>t.jsx(_T,{routine:L,onEdit:E,onDelete:j,onRun:A,onToggle:S,running:h===L.id,lastRunOutput:p[L.id]??null},L.id))}),B=()=>R(),K=c==="list"&&o.length>0;return t.jsx("div",{className:"modal-overlay open",...y,children:t.jsxs("div",{ref:b,className:"modal modal-lg automation-modal",role:"dialog","aria-modal":"true","aria-labelledby":"schedules-modal-title",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(Qn,{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(Ht,{size:20})})]}),t.jsxs("div",{className:"scheduling-toolbar","aria-live":"polite",children:[t.jsxs("div",{className:"scheduling-toolbar-left",role:"group","aria-label":"Scheduling scope",children:[t.jsxs("div",{className:"scheduling-scope-selector",children:[t.jsxs("button",{type:"button",className:`scope-btn${i==="global"?" active":""}`,onClick:()=>_("global"),"aria-pressed":i==="global",title:"Global (user-level) automations",children:[t.jsx(Qo,{size:14}),"Global"]}),t.jsxs("button",{type:"button",className:`scope-btn${i==="project"?" active":""}`,onClick:()=>_("project"),"aria-pressed":i==="project",title:"Project-scoped automations",children:[t.jsx(Xn,{size:14}),"Project"]})]}),t.jsxs("span",{className:"scheduling-count",children:[t.jsx(Qn,{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(rn,{size:14}),"New Automation"]})})]}),t.jsx("div",{className:"schedule-modal-content",id:"scheduled-tasks-content",children:B()})]})})}const BT=3e4,id=new Map,bc=new Map;function Rh(e){return e??"default"}function Th(e){const n=id.get(e);return n?Date.now()>=n.expiresAt?(id.delete(e),null):n:null}function HT(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 qT(e){const n=bc.get(e);if(n)return n;const s=Sr().then(({providers:i,ghCli:r})=>{const l={...HT(i,r),ghCli:r,expiresAt:Date.now()+BT};return id.set(e,l),l}).finally(()=>{bc.delete(e)});return bc.set(e,s),s}function _g(e){const n=Rh(e),s=Th(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 f=Rh(e),p=Th(f);if(p)return r(p.hasAiProvider),l(p.hasGithub),c(p.ghCli),d(!1),m.current=!0,()=>{h=!0};m.current=!1;async function g(){!m.current&&d(!0);try{const v=await qT(f);if(h)return;r(v.hasAiProvider),l(v.hasGithub),c(v.ghCli)}catch{}finally{h||(m.current=!0,d(!1))}}return g(),()=>{h=!0}},[e]),a.useMemo(()=>({hasAiProvider:i,hasGithub:o,loading:u,hasWarnings:!i||!o}),[i,o,u])}function Mg({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(Ht,{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 VT({isOpen:e,onClose:n,projectId:s,tasks:i,onCreateTask:r,addToast:o,onPlanningMode:l,onSubtaskBreakdown:c}){const{confirm:u}=Ks(),[d,m]=a.useState(""),[h,f]=a.useState([]),[p,g]=a.useState([]),[b,v]=a.useState(!1),[x,y]=a.useState(""),[w,E]=a.useState(""),[C,j]=a.useState(""),[A,S]=a.useState(""),[z,_]=a.useState(""),[R,B]=a.useState("default"),[K,L]=a.useState(!1),[$,U]=a.useState([]),[G,Y]=a.useState(!1),[ee,N]=a.useState(void 0),[I,T]=a.useState(_s),[k,H]=a.useState(void 0),[J,ue]=a.useState(null),[fe,W]=a.useState([]),[he,O]=a.useState(!1),[ne,Q]=a.useState(!1),ge=a.useRef(null),[de,me]=a.useState(!1),[ie,Ee]=a.useState(""),Ue=a.useRef(null),{hasAiProvider:Te,hasGithub:at,loading:et}=_g(s),{nodes:Ve}=ol(),Xe=a.useCallback(ye=>{Y(!0),U(ye)},[]),De=a.useCallback(()=>{Y(!1)},[]),Be=a.useCallback(async()=>{if(fe.length>0){O(!0);return}Q(!0);try{const ye=await Ra(void 0,s);W(ye),O(!0)}catch(ye){const ce=we(ye);o(ce?`Failed to load agents: ${ce}`:"Failed to load agents","error"),O(!1)}finally{Q(!1)}},[fe.length,s,o]);a.useEffect(()=>{if(!he)return;const ye=ce=>{ge.current&&!ge.current.contains(ce.target)&&O(!1)};return document.addEventListener("mousedown",ye),()=>document.removeEventListener("mousedown",ye)},[he]),a.useEffect(()=>{if(!de)return;const ye=ce=>{Ue.current&&!Ue.current.contains(ce.target)&&(me(!1),Ee(""))};return document.addEventListener("mousedown",ye),()=>document.removeEventListener("mousedown",ye)},[de]);const oe=i.filter(ye=>!h.includes(ye.id)).sort((ye,ce)=>{const Re=ce.createdAt.localeCompare(ye.createdAt);if(Re!==0)return Re;const be=parseInt(ye.id.slice(ye.id.lastIndexOf("-")+1),10)||0;return(parseInt(ce.id.slice(ce.id.lastIndexOf("-")+1),10)||0)-be}),Ne=ie?oe.filter(ye=>ye.id.toLowerCase().includes(ie.toLowerCase())||ye.title&&ye.title.toLowerCase().includes(ie.toLowerCase())||ye.description&&ye.description.toLowerCase().includes(ie.toLowerCase())):oe,se=(ye,ce)=>ye.length>ce?ye.slice(0,ce)+"…":ye;a.useEffect(()=>{const ye=d.trim()!==""||h.length>0||p.length>0||x!==""||w!==""||C!==""||A!==""||$.length>0||J!==null||ee!==void 0||I!==_s||k!==void 0;L(ye)},[d,h,p,x,w,C,A,$,J,ee,I,k]);const Me=a.useCallback(async()=>{K&&!await u({title:"Discard Changes",message:"You have unsaved changes. Discard them?",danger:!0})||(p.forEach(ye=>URL.revokeObjectURL(ye.previewUrl)),g([]),m(""),f([]),y(""),E(""),j(""),S(""),_(""),B("default"),U([]),Y(!1),ue(null),O(!1),N(void 0),T(_s),H(void 0),L(!1),n())},[K,n,p,u]),Le=a.useCallback(async()=>{const ye=d.trim();if(!(!ye||b)){v(!0);try{const ce=x.indexOf("/"),Re=w.indexOf("/"),be=C.indexOf("/"),Pe=await r({title:void 0,description:ye,column:"triage",dependencies:h.length?h:void 0,enabledWorkflowSteps:G?$.length>0?$:[]:void 0,...J?{assignedAgentId:J}:{},modelPresetId:R==="preset"&&z||void 0,modelProvider:x&&ce!==-1?x.slice(0,ce):void 0,modelId:x&&ce!==-1?x.slice(ce+1):void 0,validatorModelProvider:w&&Re!==-1?w.slice(0,Re):void 0,validatorModelId:w&&Re!==-1?w.slice(Re+1):void 0,planningModelProvider:C&&be!==-1?C.slice(0,be):void 0,planningModelId:C&&be!==-1?C.slice(be+1):void 0,thinkingLevel:A!==""?A:void 0,reviewLevel:ee,priority:I,nodeId:k});if(p.length>0){const Ye=[];for(const $e of p)try{await Nr(Pe.id,$e.file,s)}catch{Ye.push($e.file.name)}Ye.length>0&&o(`Failed to upload: ${Ye.join(", ")}`,"error")}p.forEach(Ye=>URL.revokeObjectURL(Ye.previewUrl)),g([]),m(""),f([]),y(""),E(""),j(""),S(""),_(""),B("default"),U([]),Y(!1),ue(null),O(!1),N(void 0),T(_s),H(void 0),o(`Created ${Pe.id}`,"success"),n()}catch(ce){o(we(ce)||"Failed to create task","error")}finally{v(!1)}}},[d,h,p,x,w,C,A,b,r,o,n,s,R,z,$,G,J,ee,I,k]),pe=a.useCallback(ye=>{ye.key==="Escape"&&(ye.preventDefault(),Me())},[Me]),Je=(J?fe.find(ye=>ye.id===J):void 0)?.name??J,it=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:Ue,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>me(ye=>!ye),disabled:b,"data-testid":"dep-trigger",children:h.length>0?`${h.length} selected`:"Add dependencies"}),de&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:ie,onChange:ye=>Ee(ye.target.value),onClick:ye=>ye.stopPropagation()}),Ne.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Ne.map(ye=>t.jsxs("div",{className:`dep-dropdown-item${h.includes(ye.id)?" selected":""}`,onClick:()=>{f(h.includes(ye.id)?h.filter(ce=>ce!==ye.id):[...h,ye.id]),me(!1),Ee("")},onMouseDown:ce=>ce.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:ye.id}),t.jsx("span",{className:"dep-dropdown-title",children:se(ye.title||ye.description||ye.id,30)})]},ye.id))]})]}),h.length>0&&t.jsx("div",{className:"selected-deps",children:h.map(ye=>t.jsxs("span",{className:"dep-chip",children:[ye,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>f(h.filter(ce=>ce!==ye)),disabled:b,children:"×"})]},ye))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Assign Agent"}),t.jsxs("div",{className:"agent-trigger-wrap",ref:ge,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{he?O(!1):Be()},disabled:b,"data-testid":"new-task-agent-button",children:[t.jsx(Sn,{size:12,style:{verticalAlign:"middle"}}),Je?` ${Je}`:" Assign agent"]}),he&&t.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:ye=>ye.preventDefault(),children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),ne&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!ne&&fe.filter(ye=>ye.state!=="terminated").map(ye=>t.jsxs("div",{className:`dep-dropdown-item${J===ye.id?" selected":""}`,onMouseDown:ce=>ce.preventDefault(),onClick:()=>{ue(ye.id===J?null:ye.id),O(!1)},"data-testid":`agent-option-${ye.id}`,children:[t.jsx(Sn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:ye.role}),t.jsx("span",{className:"dep-dropdown-title",children:ye.name})]},ye.id)),!ne&&fe.filter(ye=>ye.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),J&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:ye=>ye.preventDefault(),onClick:()=>{ue(null),O(!1)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return e?t.jsx("div",{className:"modal-overlay open",onClick:Me,onKeyDown:pe,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:ye=>ye.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:"New Task"}),t.jsx("button",{className:"modal-close",onClick:Me,disabled:b,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!et&&t.jsx(Mg,{hasAiProvider:Te,hasGithub:at}),t.jsx(xg,{mode:"create",description:d,onDescriptionChange:m,dependencies:h,onDependenciesChange:f,executorModel:x,onExecutorModelChange:y,validatorModel:w,onValidatorModelChange:E,presetMode:R,onPresetModeChange:B,selectedPresetId:z,onSelectedPresetIdChange:_,selectedWorkflowSteps:$,onWorkflowStepsChange:Xe,onDefaultOnApplied:De,pendingImages:p,onImagesChange:g,tasks:i,projectId:s,disabled:b,addToast:o,isActive:e,onPlanningMode:l,onSubtaskBreakdown:c,onClose:Me,planningModel:C,onPlanningModelChange:j,thinkingLevel:A,onThinkingLevelChange:S,reviewLevel:ee,onReviewLevelChange:N,priority:I,onPriorityChange:T,nodeId:k,onNodeIdChange:H,nodeOptions:Ve,renderBelowPrimary:it,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:Me,disabled:b,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Le,disabled:!d.trim()||b,children:b?"Creating...":"Create Task"})]})]})}):null}function Bs(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 Ph(e,n){return!Number.isFinite(e)||!Number.isFinite(n)||n<=0?"—":`${(e/n*100).toFixed(1)}%`}function WT(e,n){if(n<=0)return"normal";const s=e/n;return s>=.85?"critical":s>=.65?"warning":"normal"}function KT(e,n){if(n<=0)return"normal";const s=e/n;return s>=.5?"critical":s>=.25?"warning":"normal"}function GT(e,n){if(n<=0)return"normal";const s=e/n;return s>=.9?"critical":s>=.75?"warning":"normal"}function xc(e){return e==="critical"?"system-stats-modal__value--critical":e==="warning"?"system-stats-modal__value--warning":""}function JT(e){if(!e)return"Not yet";const n=new Date(e);return Number.isNaN(n.getTime())?"Not yet":n.toLocaleString()}function YT({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,f]=a.useState(90),[p,g]=a.useState(!1),[b,v]=a.useState(!1),[x,y]=a.useState(null),[w,E]=a.useState(null),[C,j]=a.useState(null),A=a.useCallback(async H=>{l(!0);try{const J=await Ek(s);r(J),u(null),j(Date.now()),H?.preserveKillResult||y(null)}catch(J){u(J instanceof Error?J.message:"Failed to load system stats")}finally{l(!1)}},[s]);a.useEffect(()=>{if(!e)return;A();const H=window.setInterval(()=>{A()},5e3);return()=>{window.clearInterval(H)}},[e,A]),a.useEffect(()=>{if(!e)return;(async()=>{try{const J=await Ji();m(J.vitestAutoKillEnabled??!0),f(J.vitestKillThresholdPct??90),E(null)}catch(J){E(J instanceof Error?J.message:"Failed to load vitest settings")}})()},[e]),a.useEffect(()=>{if(!e)return;const H=J=>{J.key==="Escape"&&n()};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[e,n]);const S=a.useMemo(()=>{if(!i)return[];const H=i.systemStats,J=xc(WT(H.heapUsed,H.heapLimit)),ue=xc(KT(H.rss,H.systemTotalMem));return[{label:"RSS",value:Bs(H.rss),detail:Ph(H.rss,H.systemTotalMem),className:ue},{label:"Heap Used",value:Bs(H.heapUsed),detail:`of ${Bs(H.heapTotal)}`,className:J},{label:"Heap Limit",value:Bs(H.heapLimit),detail:"V8 limit"},{label:"External",value:Bs(H.external)},{label:"Array Buffers",value:Bs(H.arrayBuffers)}]},[i]),z=a.useCallback(async H=>{m(H);try{await pn({vitestAutoKillEnabled:H}),E(null)}catch(J){E(J instanceof Error?J.message:"Failed to save vitest settings")}},[]),_=a.useCallback(async H=>{const J=Math.min(99,Math.max(50,Number.isFinite(H)?Math.round(H):90));f(J);try{await pn({vitestKillThresholdPct:J}),E(null)}catch(ue){E(ue instanceof Error?ue.message:"Failed to save vitest settings")}},[]),R=a.useCallback(async()=>{if(!p){if(!b){v(!0);return}g(!0);try{const H=await _k(s);y(H),v(!1),await A({preserveKillResult:!0})}catch(H){u(H instanceof Error?H.message:"Failed to kill vitest processes")}finally{g(!1)}}},[b,p,A,s]);if(!e)return null;const B=i?.systemStats,K=o&&!!i,L=C?`Updated ${new Date(C).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`:"Waiting for first update",$=i?.taskStats,U=B?B.systemTotalMem-B.systemFreeMem:0,G=B?GT(U,B.systemTotalMem):"normal",Y=B?xc(G):"",ee=B&&Number.isFinite(B.systemTotalMem)&&B.systemTotalMem>0?Math.max(0,Math.min(100,U/B.systemTotalMem*100)):0,N=B?`System memory used: ${ee.toFixed(1)}% (${Bs(U)} of ${Bs(B.systemTotalMem)})`:"System memory usage unavailable",I=i?.vitestProcessCount,T=x?x.killed>0?"system-stats-modal__kill-result system-stats-modal__kill-result--success":"system-stats-modal__kill-result system-stats-modal__kill-result--error":"",k=JT(i?.vitestLastAutoKillAt);return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"system-stats-modal-title",onClick:H=>{H.target===H.currentTarget&&n()},"data-testid":"system-stats-modal-overlay",children:t.jsxs("div",{className:"modal modal-lg system-stats-modal","data-testid":"system-stats-modal",children:[t.jsxs("div",{className:"modal-header system-stats-modal__header",children:[t.jsxs("h2",{id:"system-stats-modal-title",className:"system-stats-modal__title",children:[t.jsx(jr,{}),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:L})]}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>void A(),title:"Refresh","aria-label":"Refresh system stats",children:t.jsx(Ln,{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(Ht,{})})]})]}),o&&!i&&t.jsx("div",{className:"system-stats-modal__state",children:"Loading system stats…"}),c&&!i&&t.jsx("div",{className:"system-stats-modal__state system-stats-modal__state--error",role:"alert",children:c}),i&&t.jsxs("div",{className:"system-stats-modal__content",children:[t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Process stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Process"}),t.jsx("dl",{className:"system-stats-modal__grid",children:S.map(H=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:H.label}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${H.className}`.trim(),children:H.value}),H.detail?t.jsx("span",{className:"system-stats-modal__detail",children:H.detail}):null]})]},H.label))})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"CPU and load stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"CPU & Load"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Load Avg"}),t.jsx("dd",{children:B?.loadAvg.map(H=>H.toFixed(2)).join(" ")??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Cores"}),t.jsx("dd",{children:B?.cpuCount??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Platform"}),t.jsx("dd",{children:B?.platform??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Node"}),t.jsx("dd",{children:B?.nodeVersion??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"PID"}),t.jsx("dd",{children:B?.pid??"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"System memory stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"System"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row system-stats-modal__row--memory-used",children:[t.jsx("dt",{children:"Memory Used"}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${Y}`.trim(),children:B?Bs(U):"—"}),t.jsx("span",{className:"system-stats-modal__detail",children:B?`${Ph(U,B.systemTotalMem)} of ${Bs(B.systemTotalMem)}`:""})]}),t.jsx("div",{className:"system-stats-modal__memory-progress-wrapper",children:t.jsx("div",{className:`system-stats-modal__memory-progress-track system-stats-modal__memory-progress-track--${G}`,role:"progressbar","aria-valuenow":Math.round(ee),"aria-valuemin":0,"aria-valuemax":100,"aria-label":N,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${G}`,style:{width:`${ee}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Memory Free"}),t.jsx("dd",{children:B?Bs(B.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:$?.total??0})]}),Object.entries($?.byColumn??{}).map(([H,J])=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:H}),t.jsx("dd",{children:J})]},H))]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Agent stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Agents"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"idle"}),t.jsx("dd",{children:$?.agents.idle??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"active"}),t.jsx("dd",{children:$?.agents.active??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"running"}),t.jsx("dd",{children:$?.agents.running??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"error"}),t.jsx("dd",{children:$?.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(gv,{}),t.jsx("span",{children:"Vitest Controls"})]}),t.jsx("dl",{className:"system-stats-modal__grid system-stats-modal__vitest-controls",children:t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Vitest Processes"}),t.jsx("dd",{children:I??"—"})]})}),t.jsxs("div",{className:"system-stats-modal__vitest-controls",children:[t.jsx("div",{className:"system-stats-modal__kill-row",children:t.jsxs("button",{type:"button",className:"btn btn-danger",onClick:()=>void R(),disabled:p||I===0,children:[t.jsx(yv,{}),t.jsx("span",{children:b?"Confirm Kill?":"Kill Vitest Processes"})]})}),t.jsxs("label",{className:"system-stats-modal__toggle-row",children:[t.jsx("input",{type:"checkbox",checked:d,onChange:H=>{z(H.target.checked)}}),t.jsx("span",{children:"Auto-kill vitest on memory pressure"})]}),t.jsxs("div",{className:"system-stats-modal__threshold-row",children:[t.jsx("label",{htmlFor:"vitest-threshold-number",children:"Kill threshold (%)"}),t.jsxs("div",{className:"system-stats-modal__threshold-controls",children:[t.jsx("input",{id:"vitest-threshold-range",type:"range",min:50,max:99,value:h,"aria-label":"Kill threshold slider (%)",onChange:H=>{const J=Number.parseInt(H.target.value,10);_(Number.isNaN(J)?90:J)}}),t.jsx("input",{id:"vitest-threshold-number",type:"number",className:"input",min:50,max:99,value:h,"aria-label":"Kill threshold (%)",onChange:H=>{const J=Number.parseInt(H.target.value,10);_(Number.isNaN(J)?90:J)},onBlur:()=>{_(h)}})]})]}),x&&t.jsxs("p",{className:T,children:["Killed ",x.killed," processes"]}),t.jsxs("p",{className:"system-stats-modal__last-kill",children:["Last auto-kill: ",k]}),w&&t.jsx("p",{className:"system-stats-modal__kill-result system-stats-modal__kill-result--error",children:w})]})]})]}),c&&i&&t.jsxs("div",{className:"system-stats-modal__footer-error",children:["Latest refresh failed: ",c]})]})})}const QT=5e3;function XT(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),[f,p]=a.useState(!1),g=a.useRef(null),b=a.useRef(void 0),v=a.useCallback(async()=>{try{d(!0),h(null);let w;o?w=await bu({limit:i,projectId:n,type:s}):w=(await uu({limit:i,type:s,projectId:n})).map(C=>({...C,projectId:n??"",projectName:""})),c(w),p(w.length===i),w.length>0&&(b.current=w[w.length-1].timestamp)}catch(w){h(w instanceof Error?w.message:"Failed to load activity log")}finally{d(!1)}},[i,n,s,o]),x=a.useCallback(async()=>{if(b.current)try{d(!0);let w;o?w=await bu({limit:i,projectId:n,type:s,since:b.current}):w=(await uu({limit:i,type:s,since:b.current,projectId:n})).map(C=>({...C,projectId:n??"",projectName:""})),c(E=>[...E,...w]),p(w.length===i),w.length>0&&(b.current=w[w.length-1].timestamp)}catch(w){h(w instanceof Error?w.message:"Failed to load more entries")}finally{d(!1)}},[i,n,s,o]),y=a.useCallback(()=>{c([]),p(!1),b.current=void 0},[]);return a.useEffect(()=>{v()},[v]),a.useEffect(()=>{if(r)return g.current=setInterval(()=>{v()},QT),()=>{g.current&&(clearInterval(g.current),g.current=null)}},[r,v]),{entries:l,loading:u,error:m,refresh:v,clear:y,hasMore:f,loadMore:x}}const vc={"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"},ZT={"task:created":t.jsx(rn,{size:14,className:"activity-icon created"}),"task:moved":t.jsx(Pr,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx(Ln,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(Ht,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx(wn,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(Ir,{size:14,className:"activity-icon failed"}),"settings:updated":t.jsx(pr,{size:14,className:"activity-icon settings"})};function eP(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 tP({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"),[f,p]=a.useState(!1);a.useEffect(()=>{h(r||"all")},[r]);const g=u==="all"?void 0:u,b=m==="all"?void 0:m,v=!c&&o.length>0,{entries:x,loading:y,error:w,refresh:E,hasMore:C}=XT({projectId:b,type:g,limit:100,autoRefresh:e,useCentralFeed:v}),j=x.map(R=>({id:R.id,timestamp:R.timestamp,type:R.type,taskId:R.taskId,taskTitle:R.taskTitle,details:R.details,metadata:R.metadata,projectId:R.projectId,projectName:R.projectName})),A=async()=>{try{await nk(),E(),p(!1)}catch{p(!1)}},S=R=>{i&&i(R)},z=R=>{h(R),l?.(R==="all"?void 0:R)};a.useEffect(()=>{if(!e)return;const R=B=>{B.key==="Escape"&&(f?p(!1):n())};return document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)},[e,n,f]);const _=u!=="all"||m!=="all";return e?t.jsx("div",{className:"modal-overlay open",onClick:R=>{R.target===R.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(yr,{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(Xn,{size:14}),t.jsxs("select",{value:m,onChange:R=>z(R.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[t.jsx("option",{value:"all",children:"All Projects"}),o.map(R=>t.jsx("option",{value:R.id,children:R.name},R.id))]})]}),t.jsxs("div",{className:"activity-log-filter",children:[t.jsx(To,{size:14}),t.jsxs("select",{value:u,onChange:R=>d(R.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:"All Events"}),Object.entries(vc).map(([R,B])=>t.jsx("option",{value:R,children:B},R))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>E(),title:"Refresh","data-testid":"activity-refresh",children:y?t.jsx(ot,{size:14,className:"spin"}):t.jsx(Ln,{size:14})}),j.length>0&&t.jsx("button",{className:"activity-log-clear",onClick:()=>p(!0),title:"Clear Log","data-testid":"activity-clear",children:t.jsx(an,{size:14})})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",title:"Close","data-testid":"activity-close",children:"×"})]}),_&&t.jsxs("div",{className:"activity-log-active-filters",children:[t.jsx("span",{className:"activity-log-filter-label",children:"Active filters:"}),m!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Project: ",o.find(R=>R.id===m)?.name||m]}),u!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",vc[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:[w&&t.jsxs("div",{className:"activity-log-error","data-testid":"activity-error",children:[t.jsx(gs,{size:16}),t.jsx("span",{children:w})]}),j.length===0&&!y&&!w&&t.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[t.jsx(yr,{size:48,className:"activity-log-empty-icon"}),t.jsx("p",{children:_?"No activity matches the current filters":"No activity recorded yet"}),_&&t.jsx("button",{className:"btn btn-secondary",onClick:()=>{d("all"),h("all"),l?.(void 0)},children:"Clear Filters"})]}),t.jsx("div",{className:"activity-log-list",children:j.map(R=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:ZT[R.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:vc[R.type]}),t.jsx("span",{className:"activity-log-entry-time",children:eP(R.timestamp)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[R.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>S(R.taskId),"data-testid":"activity-task-link",children:R.taskId}),R.taskTitle&&t.jsx("span",{className:"activity-log-task-title",children:R.taskTitle}),t.jsx("span",{className:"activity-log-entry-text",children:R.details})]}),R.metadata&&Object.keys(R.metadata).length>0&&t.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof R.metadata.from=="string"&&typeof R.metadata.to=="string"&&t.jsxs("span",{className:"activity-log-metadata-item",children:[R.metadata.from," → ",R.metadata.to]}),typeof R.metadata.merged=="boolean"&&t.jsx("span",{className:`activity-log-metadata-item ${R.metadata.merged?"success":"error"}`,children:R.metadata.merged?"Merged":"Not merged"})]})]})]},R.id))}),C&&!y&&t.jsx("button",{className:"activity-log-load-more",onClick:E,"data-testid":"activity-load-more",children:"Load More"}),y&&j.length>0&&t.jsx("div",{className:"activity-log-loading",children:t.jsx(ot,{size:20,className:"spin"})})]}),f&&t.jsx("div",{className:"activity-log-confirm-overlay",children:t.jsxs("div",{className:"activity-log-confirm-dialog",children:[t.jsx("h3",{children:"Clear Activity Log?"}),t.jsx("p",{children:"This will permanently delete all activity log entries. This action cannot be undone."}),t.jsxs("div",{className:"activity-log-confirm-actions",children:[t.jsx("button",{className:"activity-log-confirm-cancel",onClick:()=>p(!1),children:"Cancel"}),t.jsx("button",{className:"activity-log-confirm-clear",onClick:A,children:"Clear Log"})]})]})})]})}):null}const nr=[{id:"status",label:"Status",icon:vp},{id:"changes",label:"Changes",icon:Ac},{id:"commits",label:"Commits",icon:$r},{id:"branches",label:"Branches",icon:Ws},{id:"worktrees",label:"Worktrees",icon:jx},{id:"stashes",label:"Stashes",icon:Rr},{id:"remotes",label:"Remotes",icon:fp}];function Ih({status:e}){switch(e){case"added":case"untracked":return t.jsx(nx,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(hp,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(Zb,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return t.jsx(Bi,{size:14,className:"gm-file-icon gm-file-renamed"});default:return t.jsx(ix,{size:14,className:"gm-file-icon"})}}function $h({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 nP(e){return a.useCallback(async(n,s)=>{try{await navigator.clipboard.writeText(n),e(`Copied ${s||"to clipboard"}`,"success")}catch{e("Failed to copy","error")}},[e])}function wa(e){if(!e)return"—";const n=new Date(e);if(isNaN(n.getTime()))return"—";const i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4);if(r<1)return"just now";if(r<60)return`${r}m ago`;const o=Math.floor(r/60);if(o<24)return`${o}h ago`;const l=Math.floor(o/24);return l<30?`${l}d ago`:n.toLocaleDateString()}function sP({isOpen:e,onClose:n,tasks:s,addToast:i,projectId:r}){const o=Ks(),[l,c]=a.useState("status"),[u,d]=a.useState(!1),[m,h]=a.useState(null),f=a.useRef(null);di(f,e,"fusion:git-modal-size");const p=Mi(n),g=nP(i),[b,v]=a.useState(null),[x,y]=a.useState([]),[w,E]=a.useState(new Set),[C,j]=a.useState(""),[A,S]=a.useState(!1),[z,_]=a.useState(null),[R,B]=a.useState(!1),[K,L]=a.useState(null),[$,U]=a.useState(null),G=a.useRef(0),[Y,ee]=a.useState([]),[N,I]=a.useState(null),[T,k]=a.useState(null),[H,J]=a.useState(!1),[ue,fe]=a.useState(20),[W,he]=a.useState(""),[O,ne]=a.useState([]),[Q,ge]=a.useState(""),[de,me]=a.useState(""),[ie,Ee]=a.useState(""),[Ue,Te]=a.useState(null),[at,et]=a.useState([]),[Ve,Xe]=a.useState(!1),[De,Be]=a.useState(null),[oe,Ne]=a.useState(null),[se,Me]=a.useState(!1),[Le,pe]=a.useState([]),[Ae,Je]=a.useState([]),[it,ye]=a.useState(""),[ce,Re]=a.useState(null),[be,Pe]=a.useState(null),[Ye,$e]=a.useState(null),ft=a.useCallback(async()=>{if(e){d(!0),h(null);try{switch(l){case"status":{const xe=await Us(r);v(xe);break}case"changes":{const[xe,Fe]=await Promise.all([Us(r),ia(r)]);v(xe),y(Fe),E(new Set),U(null),_(null),L(null);break}case"commits":{const xe=await oj(ue,r);ee(xe);break}case"branches":{const[xe,Fe]=await Promise.all([Ba(r),Us(r)]);ne(xe),v(Fe);break}case"worktrees":{const xe=await uj(r);pe(xe);break}case"stashes":{const xe=await to(r);Je(xe);break}case"remotes":{const xe=await Us(r);v(xe);break}}}catch(xe){h(we(xe)||"Failed to fetch git data"),i(we(xe)||"Failed to fetch git data","error")}finally{d(!1)}}},[l,e,ue,i,r]);a.useEffect(()=>{e&&ft()},[ft,e]),a.useEffect(()=>{if(!e)return;const xe=Fe=>{if(Fe.key==="Escape"){n();return}if((Fe.key==="ArrowUp"||Fe.key==="ArrowDown")&&Fe.altKey){Fe.preventDefault();const ct=nr.findIndex(D=>D.id===l);Fe.key==="ArrowUp"&&ct>0?c(nr[ct-1].id):Fe.key==="ArrowDown"&&ct<nr.length-1&&c(nr[ct+1].id)}};return document.addEventListener("keydown",xe),()=>document.removeEventListener("keydown",xe)},[e,n,l]);const Z=a.useCallback(async xe=>{try{await ru(xe,r),i(`Staged ${xe.length} file(s)`,"success");const Fe=await ia(r);y(Fe),E(new Set),U(null),_(null),L(null)}catch(Fe){i(we(Fe)||"Failed to stage files","error")}},[i,r]),re=a.useCallback(async xe=>{try{await jj(xe,r),i(`Unstaged ${xe.length} file(s)`,"success");const Fe=await ia(r);y(Fe),E(new Set),U(null),_(null),L(null)}catch(Fe){i(we(Fe)||"Failed to unstage files","error")}},[i,r]),je=a.useCallback(async xe=>{if(await o.confirm({title:"Discard Changes",message:`Discard changes to ${xe.length} file(s)? This cannot be undone.`,danger:!0}))try{await kj(xe,r),i(`Discarded changes to ${xe.length} file(s)`,"success");const[ct,D]=await Promise.all([ia(r),Us(r)]);y(ct),v(D),E(new Set),U(null),_(null),L(null)}catch(ct){i(we(ct)||"Failed to discard changes","error")}},[i,r,confirm]),rt=a.useCallback(async xe=>{if(xe.preventDefault(),!!C.trim()){S(!0);try{const Fe=await ou(C.trim(),r);i(`Committed: ${Fe.hash}`,"success"),j("");const[ct,D]=await Promise.all([ia(r),Us(r)]);y(ct),v(D),U(null),_(null),L(null)}catch(Fe){i(we(Fe)||"Failed to commit","error")}finally{S(!1)}}},[C,i,r]),te=a.useCallback(async()=>{if(C.trim()){S(!0);try{const xe=x.filter(F=>!F.staged).map(F=>F.file);xe.length>0&&await ru(xe,r);const Fe=await ou(C.trim(),r);i(`Committed: ${Fe.hash}`,"success"),j("");const[ct,D]=await Promise.all([ia(r),Us(r)]);y(ct),v(D),U(null),_(null),L(null)}catch(xe){i(we(xe)||"Failed to commit","error")}finally{S(!1)}}},[C,x,i,r]),Ze=a.useCallback(async(xe,Fe)=>{U({file:xe,staged:Fe}),B(!0),L(null);const ct=G.current+1;G.current=ct;try{const D=await yj(xe,Fe,r);if(G.current!==ct)return;_(D)}catch(D){if(G.current!==ct)return;const F=we(D)||"Failed to load file diff";_(null),L(F),i(F,"error")}finally{G.current===ct&&B(!1)}},[i,r]),pt=a.useCallback(xe=>{E(Fe=>{const ct=new Set(Fe);return ct.has(xe)?ct.delete(xe):ct.add(xe),ct})},[]),gt=a.useCallback(async xe=>{if(N===xe){I(null),k(null);return}I(xe),J(!0);try{const Fe=await $o(xe,r);k(Fe)}catch(Fe){i(we(Fe)||"Failed to load diff","error"),k(null)}finally{J(!1)}},[N,i,r]),wt=a.useCallback(()=>{fe(xe=>Math.min(xe+20,100))},[]),Et=a.useMemo(()=>{if(!W.trim())return Y;const xe=W.toLowerCase();return Y.filter(Fe=>Fe.message.toLowerCase().includes(xe)||Fe.author.toLowerCase().includes(xe)||Fe.shortHash.toLowerCase().includes(xe))},[Y,W]),mt=a.useCallback(async xe=>{if(xe.preventDefault(),!!Q.trim()){d(!0);try{await mj(Q.trim(),de.trim()||void 0,r),i(`Created branch ${Q}`,"success"),ge(""),me("");const Fe=await Ba(r);ne(Fe)}catch(Fe){i(we(Fe)||"Failed to create branch","error")}finally{d(!1)}}},[Q,de,i,r]),Nt=a.useCallback(async xe=>{d(!0);try{await hj(xe,r),i(`Switched to ${xe}`,"success");const[Fe,ct]=await Promise.all([Us(r),Ba(r)]);v(Fe),ne(ct)}catch(Fe){i(we(Fe)||"Failed to checkout branch","error")}finally{d(!1)}},[i,r]),Tt=a.useCallback(async xe=>{if(await o.confirm({title:"Delete Branch",message:`Delete branch "${xe}"?`,danger:!0})){d(!0);try{await au(xe,void 0,r),i(`Deleted branch ${xe}`,"success");const ct=await Ba(r);ne(ct)}catch(ct){if(we(ct).includes("not fully merged")){if(await o.confirm({title:"Force Delete Branch",message:"Branch has unmerged commits. Force delete?",danger:!0}))try{await au(xe,!0,r),i(`Force deleted branch ${xe}`,"success");const F=await Ba(r);ne(F)}catch(F){i(we(F)||"Failed to delete branch","error")}}else i(we(ct)||"Failed to delete branch","error")}finally{d(!1)}}},[i,r,confirm]),qt=a.useMemo(()=>{if(!ie.trim())return O;const xe=ie.toLowerCase();return O.filter(Fe=>Fe.name.toLowerCase().includes(xe))},[O,ie]),Pt=a.useCallback(async xe=>{if(Ue===xe){Te(null),et([]),Be(null),Ne(null);return}Te(xe),et([]),Be(null),Ne(null),Xe(!0);try{const Fe=await dj(xe,10,r);et(Fe)}catch{et([])}finally{Xe(!1)}},[Ue,r]),At=a.useCallback(async xe=>{if(De===xe){Be(null),Ne(null);return}Be(xe),Ne(null),Me(!0);try{const Fe=await $o(xe,r);Ne(Fe)}catch{Ne(null)}finally{Me(!1)}},[De,r]),Bt=a.useCallback(()=>{Te(null),et([]),Be(null),Ne(null)},[]),Ft=a.useCallback(async xe=>{xe.preventDefault(),Re("create");try{await bj(it.trim()||void 0,r),i("Changes stashed","success"),ye("");const Fe=await to(r);Je(Fe)}catch(Fe){i(we(Fe)||"Failed to stash changes","error")}finally{Re(null)}},[it,i,r]),Dt=a.useCallback(async(xe,Fe=!1)=>{Re(`apply-${xe}`);try{await xj(xe,Fe,r),i(Fe?"Stash popped":"Stash applied","success");const ct=await to(r);Je(ct)}catch(ct){i(we(ct)||"Failed to apply stash","error")}finally{Re(null)}},[i,r]),Mt=a.useCallback(async xe=>{if(await o.confirm({title:"Drop Stash",message:`Drop stash@{${xe}}? This cannot be undone.`,danger:!0})){Re(`drop-${xe}`);try{await vj(xe,r),i("Stash dropped","success");const ct=await to(r);Je(ct)}catch(ct){i(we(ct)||"Failed to drop stash","error")}finally{Re(null)}}},[i,r,confirm]),St=a.useCallback(async()=>{Pe("fetch");try{const xe=await pj(void 0,r);$e(xe),i(xe.message||"Fetch completed",xe.fetched?"success":"info");const Fe=await Us(r);v(Fe)}catch(xe){i(we(xe)||"Fetch failed","error")}finally{Pe(null)}},[i,r]),Wt=a.useCallback(async()=>{Pe("pull");try{const xe=await fj(r);$e(xe),xe.conflict?i("Merge conflict detected. Resolve manually.","error"):i(xe.message||"Pull completed","success");const Fe=await Us(r);v(Fe)}catch(xe){i(we(xe)||"Pull failed","error")}finally{Pe(null)}},[i,r]),It=a.useCallback(async()=>{Pe("push");try{const xe=await gj(r);$e(xe),i(xe.message||"Push completed","success");const Fe=await Us(r);v(Fe)}catch(xe){i(we(xe)||"Push failed","error")}finally{Pe(null)}},[i,r]),Yt=a.useMemo(()=>x.filter(xe=>xe.staged),[x]),Rt=a.useMemo(()=>x.filter(xe=>!xe.staged),[x]);return e?t.jsx("div",{className:"modal-overlay open",...p,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal gm-modal",ref:f,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h3",{children:[t.jsx(Rc,{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:ft,disabled:u,title:"Refresh",children:t.jsx(Ln,{size:14,className:u?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Ht,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:nr.map(xe=>{const Fe=xe.icon;return t.jsxs("button",{role:"tab","aria-selected":l===xe.id,className:`gm-nav-item${l===xe.id?" active":""}`,onClick:()=>c(xe.id),children:[t.jsx(Fe,{size:16}),t.jsx("span",{className:"gm-nav-label",children:xe.label})]},xe.id)})}),t.jsxs("div",{className:"gm-content",role:"tabpanel",children:[u&&t.jsxs("div",{className:"gm-loading",children:[t.jsx(ot,{size:24,className:"spin"}),t.jsx("span",{children:"Loading..."})]}),m&&!u&&t.jsxs("div",{className:"gm-error",children:[t.jsx(gs,{size:18}),t.jsx("span",{children:m}),t.jsx("button",{className:"btn btn-sm",onClick:ft,children:"Retry"})]}),l==="status"&&!u&&b&&t.jsx(iP,{status:b,copyToClipboard:g}),l==="changes"&&!u&&t.jsx(aP,{status:b,stagedFiles:Yt,unstagedFiles:Rt,selectedFiles:w,toggleFileSelection:pt,onStageFiles:Z,onUnstageFiles:re,onDiscardChanges:je,onSelectDiffFile:Ze,selectedDiffTarget:$,changeDiff:z,loadingChangeDiff:R,changeDiffError:K,commitMessage:C,setCommitMessage:j,onCommit:rt,onStageAllAndCommit:te,committing:A}),l==="commits"&&!u&&t.jsx(rP,{commits:Et,commitSearch:W,setCommitSearch:he,selectedCommit:N,commitDiff:T,loadingDiff:H,onCommitClick:gt,onLoadMore:wt,canLoadMore:Y.length>=ue&&ue<100,copyToClipboard:g}),l==="branches"&&!u&&t.jsx(oP,{branches:qt,branchSearch:ie,setBranchSearch:Ee,newBranchName:Q,setNewBranchName:ge,branchBase:de,setBranchBase:me,onCreateBranch:mt,onCheckoutBranch:Nt,onDeleteBranch:Tt,loading:u,allBranches:O,selectedBranch:Ue,branchCommits:at,loadingBranchCommits:Ve,expandedBranchCommit:De,branchCommitDiff:oe,loadingBranchCommitDiff:se,onSelectBranch:Pt,onBranchCommitClick:At,onCloseBranchDetails:Bt}),l==="worktrees"&&!u&&t.jsx(lP,{worktrees:Le}),l==="stashes"&&!u&&t.jsx(cP,{stashes:Ae,stashMessage:it,setStashMessage:ye,onCreateStash:Ft,onApplyStash:Dt,onDropStash:Mt,stashLoading:ce}),l==="remotes"&&!u&&t.jsx(dP,{status:b,remoteLoading:be,lastRemoteResult:Ye,onFetch:St,onPull:Wt,onPush:It,addToast:i,projectId:r,copyToClipboard:g})]})]})]})}):null}function iP({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(Ws,{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(Ui,{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(gs,{size:12}),"Modified"]}):t.jsxs(t.Fragment,{children:[t.jsx(wn,{size:12}),"Clean"]})})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Remote Sync"}),t.jsxs("span",{className:"gm-status-value",children:[e.ahead>0&&t.jsxs("span",{className:"gm-ahead",title:`${e.ahead} commit(s) ahead`,children:[t.jsx(Fi,{size:12}),e.ahead]}),e.behind>0&&t.jsxs("span",{className:"gm-behind",title:`${e.behind} commit(s) behind`,children:[t.jsx(Tr,{size:12}),e.behind]}),e.ahead===0&&e.behind===0&&t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(wn,{size:12}),"Up to date"]})]})]})]})]})}function aP({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:f,commitMessage:p,setCommitMessage:g,onCommit:b,onStageAllAndCommit:v,committing:x}){const y=s.filter(E=>i.has(`unstaged:${E.file}`)),w=n.filter(E=>i.has(`staged:${E.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(Ws,{size:14}),e.branch]}),e.isDirty&&t.jsx("span",{className:"gm-dirty-badge",children:"Modified"})]}),t.jsxs("div",{className:"gm-changes-split",children:[t.jsxs("div",{className:"gm-changes-lists",children:[t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Unstaged Changes (",s.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[y.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>o(y.map(E=>E.file)),title:"Stage selected",children:[t.jsx(rn,{size:12})," Stage (",y.length,")"]}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>c(y.map(E=>E.file)),title:"Discard selected",children:t.jsx(Ir,{size:12})})]}),s.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>o(s.map(E=>E.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(E=>{const C=d?.file===E.file&&d.staged===!1;return t.jsxs("div",{className:`gm-file-item${C?" active":""}`,onClick:()=>u(E.file,!1),role:"button",tabIndex:0,onKeyDown:j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),u(E.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:j=>j.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`unstaged:${E.file}`),onChange:()=>r(`unstaged:${E.file}`)})}),t.jsx(Ih,{status:E.status}),t.jsx("span",{className:"gm-file-name",title:E.file,children:t.jsx("bdo",{dir:"ltr",children:E.file})}),t.jsx($h,{status:E.status}),t.jsx("button",{className:"gm-icon-btn",onClick:j=>{j.stopPropagation(),o([E.file])},title:"Stage file",children:t.jsx(rn,{size:12})})]},`unstaged:${E.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:[w.length>0&&t.jsxs("button",{className:"btn btn-sm",onClick:()=>l(w.map(E=>E.file)),title:"Unstage selected",children:["Unstage (",w.length,")"]}),n.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(n.map(E=>E.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(E=>{const C=d?.file===E.file&&d.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${C?" active":""}`,onClick:()=>u(E.file,!0),role:"button",tabIndex:0,onKeyDown:j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),u(E.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:j=>j.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`staged:${E.file}`),onChange:()=>r(`staged:${E.file}`)})}),t.jsx(Ih,{status:E.status}),t.jsx("span",{className:"gm-file-name",title:E.file,children:t.jsx("bdo",{dir:"ltr",children:E.file})}),t.jsx($h,{status:E.status}),t.jsx("button",{className:"gm-icon-btn",onClick:j=>{j.stopPropagation(),l([E.file])},title:"Unstage file",children:t.jsx(Ht,{size:12})})]},`staged:${E.file}`)})})]})]}),t.jsx("div",{className:"gm-changes-diff",children:d||h||m||f?t.jsxs("div",{className:"gm-diff-section",children:[d&&t.jsxs("div",{className:"gm-diff-target",children:[t.jsx(Ac,{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(ot,{size:16,className:"spin"}),"Loading diff..."]}),f&&!h&&t.jsx("div",{className:"gm-diff-error",children:f}),m&&!h&&t.jsxs("div",{className:"gm-diff-viewer",children:[m.stat&&t.jsx("pre",{className:"gm-diff-stat",children:m.stat}),t.jsx("pre",{className:"gm-diff-patch",children:m.patch})]})]}):t.jsxs("div",{className:"gm-diff-empty",children:[t.jsx(Ac,{size:20}),t.jsx("span",{children:"Select a file to view its diff"})]})})]}),t.jsxs("form",{className:"gm-commit-form",onSubmit:b,children:[t.jsx("textarea",{className:"gm-commit-input",placeholder:"Commit message...",value:p,onChange:E=>g(E.target.value),rows:3,disabled:x}),t.jsxs("div",{className:"gm-commit-actions",children:[t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:x||!p.trim()||n.length===0,title:n.length===0?"No staged changes to commit":"Commit staged changes",children:[x?t.jsx(ot,{size:14,className:"spin"}):t.jsx(zi,{size:14}),"Commit"]}),s.length>0&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:v,disabled:x||!p.trim(),title:"Stage all and commit",children:"Stage All & Commit"})]})]})]})}function rP({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(Ni,{size:14}),t.jsx("input",{type:"text",placeholder:"Search commits...",value:n,onChange:m=>s(m.target.value)})]})]}),t.jsx("div",{className:"gm-commits-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:n?"No matching commits":"No commits found"}):e.map((m,h)=>t.jsxs("div",{className:"gm-commit-item",children:[t.jsxs("div",{className:"gm-commit-graph",children:[t.jsx("div",{className:"gm-commit-dot"}),h<e.length-1&&t.jsx("div",{className:"gm-commit-line"})]}),t.jsxs("div",{className:"gm-commit-body",children:[t.jsxs("button",{className:"gm-commit-header",onClick:()=>l(m.hash),children:[t.jsxs("div",{className:"gm-commit-top-row",children:[t.jsx("code",{className:"gm-hash",children:m.shortHash}),t.jsx("span",{className:"gm-commit-message",title:m.message,children:m.message})]}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:m.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:wa(m.date)}),m.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),t.jsx("div",{className:"gm-commit-actions-row",children:t.jsx("button",{className:"gm-icon-btn",onClick:()=>d(m.hash,"commit hash"),title:"Copy full hash",children:t.jsx(Ui,{size:12})})}),i===m.hash&&t.jsx("div",{className:"gm-commit-diff",children:o?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(ot,{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 oP({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:f,branchCommits:p,loadingBranchCommits:g,expandedBranchCommit:b,branchCommitDiff:v,loadingBranchCommitDiff:x,onSelectBranch:y,onBranchCommitClick:w,onCloseBranchDetails:E}){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(Ni,{size:14}),t.jsx("input",{type:"text",placeholder:"Filter branches...",value:n,onChange:C=>s(C.target.value)})]})]}),t.jsxs("form",{className:"gm-create-form",onSubmit:c,children:[t.jsx("input",{type:"text",placeholder:"New branch name",value:i,onChange:C=>r(C.target.value),disabled:m}),t.jsxs("select",{value:o,onChange:C=>l(C.target.value),disabled:m,className:"gm-branch-select",children:[t.jsx("option",{value:"",children:"Base: HEAD"}),h.map(C=>t.jsx("option",{value:C.name,children:C.name},C.name))]}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:m||!i.trim(),children:[t.jsx(rn,{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(C=>t.jsxs("div",{children:[t.jsxs("div",{className:`gm-branch-item${C.isCurrent?" current":""}${f===C.name?" selected":""}`,onClick:()=>y(C.name),children:[t.jsxs("div",{className:"gm-branch-info",children:[t.jsxs("span",{className:"gm-branch-name",children:[C.isCurrent&&t.jsx(Vn,{size:14,className:"gm-current-icon"}),C.name]}),C.remote&&t.jsxs("span",{className:"gm-branch-remote",children:["→ ",C.remote]}),C.lastCommitDate&&t.jsx("span",{className:"gm-branch-date",children:wa(C.lastCommitDate)})]}),t.jsx("div",{className:"gm-branch-actions",children:!C.isCurrent&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:j=>{j.stopPropagation(),u(C.name)},disabled:m,title:"Checkout",children:t.jsx(Ws,{size:14})}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:j=>{j.stopPropagation(),d(C.name)},disabled:m,title:"Delete",children:t.jsx(an,{size:14})})]})})]}),f===C.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($r,{size:14}),"Commits on ",C.name]}),t.jsx("button",{className:"gm-icon-btn",onClick:E,title:"Close","data-testid":"close-branch-details",children:t.jsx(Ht,{size:14})})]}),g?t.jsxs("div",{className:"gm-branch-details-loading",children:[t.jsx(ot,{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(j=>t.jsxs("div",{className:"gm-branch-commit",children:[t.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>w(j.hash),"data-testid":`branch-commit-${j.shortHash}`,children:[t.jsx("span",{className:"gm-commit-hash",children:j.shortHash}),t.jsx("span",{className:"gm-commit-message",title:j.message,children:j.message}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:j.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:wa(j.date)}),j.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),b===j.hash&&t.jsx("div",{className:"gm-commit-diff",children:x?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(ot,{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"})})]},j.hash))})]})]},C.name))})]})}function lP({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:jd(n.path)||n.path})]}),t.jsxs("div",{className:"gm-worktree-detail",children:[n.branch&&t.jsxs("span",{className:"gm-worktree-branch",children:[t.jsx(Ws,{size:12}),n.branch]}),n.taskId&&t.jsx("span",{className:"gm-worktree-task",children:n.taskId})]})]})},n.path))})]})}function cP({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(ot,{size:14,className:"spin"}):t.jsx(Rr,{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(Ws,{size:12}),c.branch]}),t.jsx("span",{children:wa(c.date)})]})]}),t.jsxs("div",{className:"gm-stash-actions",children:[t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>r(c.index,!1),disabled:l!==null,title:"Apply stash (keep)",children:l===`apply-${c.index}`?t.jsx(ot,{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(ot,{size:14,className:"spin"}):t.jsx(an,{size:14})})]})]},c.index))})]})}function dP({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:i,onPull:r,onPush:o,addToast:l,projectId:c,copyToClipboard:u}){const d=se=>{try{return new URL(se).hostname}catch{return se.replace(/^git@/,"").split(":")[0]||se}},[m,h]=a.useState([]),[f,p]=a.useState(!1),[g,b]=a.useState(null),[v,x]=a.useState(""),[y,w]=a.useState(""),[E,C]=a.useState(null),[j,A]=a.useState(""),[S,z]=a.useState(""),[_,R]=a.useState(!1),[B,K]=a.useState([]),[L,$]=a.useState(!1),[U,G]=a.useState(null),[Y,ee]=a.useState([]),[N,I]=a.useState(!1),[T,k]=a.useState(null),H=m.find(se=>se.name===U),[J,ue]=a.useState(null),[fe,W]=a.useState(null),[he,O]=a.useState(!1),[ne,Q]=a.useState(null),[ge,de]=a.useState(null),[me,ie]=a.useState(!1);a.useEffect(()=>{Ee()},[]),a.useEffect(()=>{e&&e.ahead>0?Ue():e&&e.ahead===0&&K([])},[e?.ahead]),a.useEffect(()=>{m.length>0&&!U&&G(m[0].name)},[m]),a.useEffect(()=>{U?Te(U):(ee([]),k(null))},[U]),a.useEffect(()=>{U&&!m.find(se=>se.name===U)&&G(m.length>0?m[0].name:null)},[m,U]);const Ee=async()=>{p(!0);try{const se=await Xy(c);h(se)}catch(se){l(we(se)||"Failed to load remotes","error")}finally{p(!1)}},Ue=async()=>{$(!0);try{const se=await lj(c);K(se)}catch{K([])}finally{$(!1)}},Te=async se=>{I(!0),k(null);try{const Me=await cj(se,void 0,10,c);ee(Me)}catch(Me){k(we(Me)||"Failed to load remote commits"),ee([])}finally{I(!1)}},at=Ks(),et=async se=>{if(se.preventDefault(),!(!v.trim()||!y.trim())){b("add");try{await Zy(v.trim(),y.trim(),c),l(`Remote '${v}' added successfully`,"success"),x(""),w(""),R(!1),await Ee()}catch(Me){l(we(Me)||"Failed to add remote","error")}finally{b(null)}}},Ve=async se=>{if(await at.confirm({title:"Remove Remote",message:`Are you sure you want to remove remote '${se}'?`,danger:!0})){b(`remove-${se}`);try{await ej(se,c),l(`Remote '${se}' removed`,"success"),await Ee()}catch(Le){l(we(Le)||"Failed to remove remote","error")}finally{b(null)}}},Xe=async se=>{if(S.trim()){b(`rename-${se}`);try{await tj(se,S.trim(),c),l(`Remote renamed to '${S.trim()}'`,"success"),C(null),z(""),await Ee()}catch(Me){l(we(Me)||"Failed to rename remote","error")}finally{b(null)}}},De=async se=>{if(j.trim()){b(`url-${se}`);try{await nj(se,j.trim(),c),l("Remote URL updated","success"),C(null),A(""),await Ee()}catch(Me){l(we(Me)||"Failed to update remote URL","error")}finally{b(null)}}},Be=a.useCallback(async(se,Me)=>{if(Me==="ahead"){if(J===se){ue(null),W(null);return}ue(se),W(null),O(!0);try{const Le=await $o(se);W(Le)}catch{W(null)}finally{O(!1)}}else{if(ne===se){Q(null),de(null);return}Q(se),de(null),ie(!0);try{const Le=await $o(se);de(Le)}catch{de(null)}finally{ie(!1)}}},[J,ne]),oe=se=>{C(`url-${se.name}`),A(se.pushUrl||se.fetchUrl)},Ne=se=>{C(`name-${se.name}`),z(se.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:()=>R(!_),disabled:g!==null,title:_?"Cancel":"Add Remote",children:_?t.jsx(Ht,{size:14}):t.jsx(rn,{size:14})})]}),_&&t.jsxs("form",{className:"gm-remote-form",onSubmit:et,children:[t.jsx("input",{type:"text",placeholder:"Remote name",value:v,onChange:se=>x(se.target.value),disabled:g==="add",className:"gm-input"}),t.jsx("input",{type:"text",placeholder:"Repository URL",value:y,onChange:se=>w(se.target.value),disabled:g==="add",className:"gm-input gm-input-url"}),t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:!v.trim()||!y.trim()||g==="add",children:[g==="add"?t.jsx(ot,{size:12,className:"spin"}):t.jsx(rn,{size:12}),"Add"]})]}),f?t.jsxs("div",{className:"gm-loading",children:[t.jsx(ot,{size:16,className:"spin"}),"Loading..."]}):m.length===0?t.jsx("div",{className:"gm-empty",children:"No remotes"}):m.map(se=>t.jsxs("div",{className:`gm-remote-selector-item${U===se.name?" selected":""}`,onClick:()=>G(se.name),role:"button",tabIndex:0,children:[t.jsxs("div",{className:"gm-remote-selector-info",children:[t.jsxs("span",{className:"gm-remote-selector-name",children:[se.name,se.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),t.jsx("span",{className:"gm-remote-selector-host",children:d(se.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:Me=>{Me.stopPropagation(),Ve(se.name)},disabled:g!==null,title:"Remove remote",children:t.jsx(an,{size:14})})]},se.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[U&&H?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"gm-remote-sync-card","data-testid":"remote-sync-card",children:[t.jsxs("div",{className:"gm-remote-sync-card-header",children:[t.jsx("span",{className:"gm-remote-sync-card-title",children:U}),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(Fi,{size:14}),e.ahead," to push"]}),e.behind>0&&t.jsxs("div",{className:"gm-remote-indicator behind",children:[t.jsx(Tr,{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||f,children:[n==="fetch"?t.jsx(ot,{size:14,className:"spin"}):t.jsx(Ln,{size:14}),"Fetch"]}),t.jsxs("button",{className:"btn btn-primary",onClick:r,disabled:n!==null||f,children:[n==="pull"?t.jsx(ot,{size:14,className:"spin"}):t.jsx(Es,{size:14}),"Pull"]}),t.jsxs("button",{className:"btn btn-primary",onClick:o,disabled:n!==null||f,children:[n==="push"?t.jsx(ot,{size:14,className:"spin"}):t.jsx(Fi,{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:"}),E===`url-${U}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:j,onChange:se=>A(se.target.value),className:"gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>De(U),disabled:g===`url-${U}`,children:g===`url-${U}`?t.jsx(ot,{size:12,className:"spin"}):t.jsx(Vn,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{C(null),A("")},title:"Cancel",children:t.jsx(Ht,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:H.fetchUrl,children:H.fetchUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>u(H.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:t.jsx(Ui,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>oe(H),disabled:g!==null,title:"Edit remote URL",children:t.jsx(hs,{size:14})})]})]}),H.pushUrl&&H.pushUrl!==H.fetchUrl&&t.jsxs("div",{className:"gm-remote-detail-url-row",children:[t.jsx("span",{className:"gm-url-label",children:"Push:"}),t.jsx("span",{className:"gm-url-value",title:H.pushUrl,children:H.pushUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>u(H.pushUrl,"push URL"),title:"Copy push URL",children:t.jsx(Ui,{size:14})})]})]}),t.jsx("div",{className:"gm-remote-detail-name-row",children:E===`name-${U}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:S,onChange:se=>z(se.target.value),className:"gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Xe(U),disabled:g===`rename-${U}`,children:g===`rename-${U}`?t.jsx(ot,{size:12,className:"spin"}):t.jsx(Vn,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{C(null),z("")},title:"Cancel",children:t.jsx(Ht,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>Ne(H),disabled:g!==null,title:"Edit remote name",children:t.jsx(hs,{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(Fi,{size:14}),"Commits to Push (",e.ahead,")"]})}),L?t.jsxs("div",{className:"gm-loading",children:[t.jsx(ot,{size:14,className:"spin"}),"Loading..."]}):B.length>0?t.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:B.map(se=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>Be(se.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:se.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:se.message,children:se.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:se.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:wa(se.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:J===se.hash?t.jsx(Xt,{size:14}):t.jsx(xn,{size:14})})]}),J===se.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:he?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(ot,{size:16,className:"spin"}),"Loading diff..."]}):fe?t.jsxs(t.Fragment,{children:[se.message&&t.jsx("div",{className:"gm-commit-message-full",children:se.message}),fe.stat&&t.jsx("pre",{className:"gm-diff-stat",children:fe.stat}),t.jsx("pre",{className:"gm-diff-patch",children:fe.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},se.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(vp,{size:14}),"Recent commits on ",U]})}),N?t.jsxs("div",{className:"gm-loading",children:[t.jsx(ot,{size:14,className:"spin"}),"Loading commits..."]}):T?t.jsxs("div",{className:"gm-error",children:[t.jsx(gs,{size:14}),T]}):Y.length===0?t.jsxs("div",{className:"gm-empty",children:["No commits found on ",U,". Try fetching first."]}):t.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:Y.map(se=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>Be(se.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:se.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:se.message,children:se.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:se.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:wa(se.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:ne===se.hash?t.jsx(Xt,{size:14}):t.jsx(xn,{size:14})})]}),ne===se.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:me?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(ot,{size:16,className:"spin"}),"Loading diff..."]}):ge?t.jsxs(t.Fragment,{children:[se.message&&t.jsx("div",{className:"gm-commit-message-full",children:se.message}),ge.stat&&t.jsx("pre",{className:"gm-diff-stat",children:ge.stat}),t.jsx("pre",{className:"gm-diff-patch",children:ge.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},se.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 sr={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function uP(e,n){return e&&n?`${e}/${n}`:""}function mP(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 hP(e){switch(e){case"file-text":return Bi;case"check-circle":return wn;case"shield":return xv;case"zap":return Qn;case"eye":return Ma;case"globe":return Qo;case"layout-grid":return qi;default:return wn}}function pP(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 fP({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),[f,p]=a.useState("my-steps"),[g,b]=a.useState(null),[v,x]=a.useState(!1),[y,w]=a.useState(sr),[E,C]=a.useState(!1),[j,A]=a.useState(!1),[S,z]=a.useState(null),[_,R]=a.useState(null),[B,K]=a.useState({}),[L,$]=a.useState([]),U=a.useRef(null);di(U,e,"fusion:workflow-steps-modal-size");const G=a.useCallback(async()=>{try{d(!0);const O=await sl(i);o(O)}catch(O){s(we(O)||"Failed to load workflow steps","error")}finally{d(!1)}},[s,i]),Y=a.useCallback(async()=>{try{const O=await Cr(i);K(O||{})}catch{}},[i]),ee=a.useCallback(async()=>{try{const O=await bs();$(O.models||[])}catch{}},[]),N=a.useCallback(async()=>{try{h(!0);const O=await rk();c(O.templates)}catch(O){s(we(O)||"Failed to load templates","error")}finally{h(!1)}},[s]);a.useEffect(()=>{e&&(G(),N(),Y(),ee())},[e,G,N,Y,ee]);const I=a.useCallback(()=>{x(!0),b(null),w(sr)},[]),T=a.useCallback(O=>{b(O.id),x(!1),w({name:O.name,description:O.description,mode:O.mode||"prompt",phase:O.phase||"pre-merge",prompt:O.prompt,scriptName:O.scriptName||"",enabled:O.enabled,defaultOn:O.defaultOn||!1,modelProvider:O.modelProvider||"",modelId:O.modelId||""})},[]),k=a.useCallback(()=>{b(null),x(!1),w(sr)},[]),H=a.useCallback(async()=>{if(!y.name.trim()||!y.description.trim()){s("Name and description are required","error");return}C(!0);try{const O=y.mode==="prompt"&&y.modelProvider&&y.modelId?{modelProvider:y.modelProvider,modelId:y.modelId}:y.mode==="prompt"?{modelProvider:void 0,modelId:void 0}:{};if(v){const 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,...O};await mu(ne,i),s("Workflow step created","success")}else g&&(await sk(g,{name:y.name.trim(),description:y.description.trim(),mode:y.mode,phase:y.phase,prompt:y.mode==="prompt"?y.prompt:"",scriptName:y.mode==="script"?y.scriptName.trim():void 0,enabled:y.enabled,defaultOn:y.defaultOn,...O},i),s("Workflow step updated","success"));x(!1),b(null),w(sr),await G()}catch(O){s(we(O)||"Failed to save workflow step","error")}finally{C(!1)}},[y,v,g,s,G]),J=a.useCallback(async O=>{try{await ik(O,i),s("Workflow step deleted","success"),z(null),g===O&&(b(null),w(sr)),await G()}catch(ne){s(we(ne)||"Failed to delete workflow step","error")}},[g,s,G]),ue=a.useCallback(async()=>{if(!(!g&&!v)&&y.mode==="prompt"){if(v){if(!y.name.trim()||!y.description.trim()){s("Name and description are required before refining","error");return}C(!0);try{const O=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,...O},Q=await mu(ne,i);x(!1),b(Q.id),A(!0);const ge=await hu(Q.id,i);w(de=>({...de,prompt:ge.prompt})),s("Prompt refined with AI","success"),await G()}catch(O){s(we(O)||"Failed to refine prompt","error")}finally{C(!1),A(!1)}return}if(g){A(!0);try{const O=await hu(g,i);w(ne=>({...ne,prompt:O.prompt})),s("Prompt refined with AI","success"),await G()}catch(O){s(we(O)||"Failed to refine prompt","error")}finally{A(!1)}}}},[g,v,y,s,G]),fe=a.useCallback(async O=>{R(O.id);try{await ok(O.id,i),s(`Added ${O.name} workflow step`,"success"),await G(),p("my-steps")}catch(ne){const Q=we(ne);Q?.includes("already exists")?s(`A workflow step named '${O.name}' already exists`,"error"):s(Q||"Failed to add workflow step from template","error")}finally{R(null)}},[s,G]),W=Mi(n);if(!e)return null;const he=v||g!==null;return t.jsx("div",{className:"modal-overlay open",...W,"data-testid":"workflow-step-manager",children:t.jsxs("div",{ref:U,className:"modal workflow-step-manager-modal",role:"dialog","aria-modal":"true","aria-label":"Workflow Steps",children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h2",{children:"Workflow Steps"}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]}),t.jsx("div",{className:"wfm-body",children:u?t.jsx("div",{className:"wfm-loading",children:"Loading..."}):t.jsxs(t.Fragment,{children:[!he&&t.jsxs("div",{className:"wfm-tab-row",children:[t.jsxs("button",{className:`btn ${f==="my-steps"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>p("my-steps"),"data-testid":"tab-my-steps",children:[t.jsx(hb,{size:14}),"My Workflow Steps (",r.length,")"]}),t.jsxs("button",{className:`btn ${f==="templates"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>p("templates"),"data-testid":"tab-templates",children:[t.jsx(qi,{size:14}),"Templates (",l.length,")"]})]}),f==="my-steps"&&!he&&t.jsxs(t.Fragment,{children:[r.length===0&&t.jsx("div",{className:"wfm-empty","data-testid":"empty-state",children:"No workflow steps defined. Create one to get started, or add one from the Templates tab."}),r.length>0&&t.jsx("div",{className:"wfm-step-list",children:r.map(O=>t.jsx("div",{className:"wfm-step-card","data-testid":`workflow-step-${O.id}`,children:t.jsxs("div",{className:"wfm-step-card-top",children:[t.jsxs("div",{className:"wfm-step-card-info",children:[t.jsxs("div",{className:"wfm-step-card-title-row",children:[t.jsx("span",{className:"wfm-step-card-name",children:O.name}),t.jsx("span",{className:`wfm-badge ${O.enabled?"wfm-badge-enabled":"wfm-badge-disabled"}`,children:O.enabled?"Enabled":"Disabled"}),t.jsx("span",{className:`wfm-badge ${(O.mode||"prompt")==="script"?"wfm-badge-script":"wfm-badge-prompt"}`,children:(O.mode||"prompt")==="script"?"Script":"AI Prompt"}),t.jsx("span",{className:`wfm-badge ${(O.phase||"pre-merge")==="post-merge"?"wfm-badge-post-merge":"wfm-badge-pre-merge"}`,children:(O.phase||"pre-merge")==="post-merge"?"Post-merge":"Pre-merge"}),O.defaultOn&&t.jsx("span",{className:"wfm-badge wfm-badge-default-on",children:"Default on"})]}),t.jsx("div",{className:"wfm-step-card-desc",children:O.description})]}),t.jsxs("div",{className:"wfm-step-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>T(O),title:"Edit","aria-label":`Edit ${O.name}`,children:t.jsx(hs,{size:14})}),S===O.id?t.jsxs("div",{className:"wfm-delete-confirm",children:[t.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>J(O.id),title:"Confirm delete","aria-label":`Confirm delete ${O.name}`,children:t.jsx(Vn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>z(null),title:"Cancel delete","aria-label":"Cancel delete",children:t.jsx(Ht,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>z(O.id),title:"Delete","aria-label":`Delete ${O.name}`,children:t.jsx(an,{size:14})})]})]})},O.id))})]}),f==="templates"&&!he&&t.jsx(t.Fragment,{children:m?t.jsxs("div",{className:"wfm-loading",children:[t.jsx(ot,{size:24,className:"spin wfm-spinner"}),"Loading templates..."]}):l.length===0?t.jsx("div",{className:"wfm-empty","data-testid":"no-templates-state",children:"No templates available."}):t.jsx("div",{className:"wfm-template-list",children:l.map(O=>{const ne=hP(O.icon),Q=pP(O.category),ge=_===O.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`template-${O.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(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:O.name}),t.jsx("span",{className:Q,children:O.category})]}),t.jsx("div",{className:"wfm-template-desc",children:O.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>fe(O),disabled:ge,"data-testid":`add-template-${O.id}`,children:ge?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(rn,{size:12}),"Add"]})})]})]})},O.id)})})}),he&&t.jsxs("div",{className:"wfm-form","data-testid":"workflow-step-form",children:[t.jsx("h3",{className:"wfm-form-title",children:v?"New Workflow Step":"Edit Workflow Step"}),t.jsxs("div",{className:"wfm-form-fields",children:[t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Name"}),t.jsx("input",{type:"text",value:y.name,onChange:O=>w(ne=>({...ne,name:O.target.value})),placeholder:"e.g. Documentation Review","data-testid":"workflow-step-name"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{value:y.description,onChange:O=>w(ne=>({...ne,description:O.target.value})),placeholder:"Brief description of what this step does",rows:2,"data-testid":"workflow-step-description"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Execution Mode"}),t.jsxs("div",{className:"wfm-mode-selector","data-testid":"workflow-step-mode-selector",children:[t.jsxs("button",{className:`btn ${y.mode==="prompt"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>w(O=>({...O,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[t.jsx(Si,{size:14}),"AI Prompt"]}),t.jsxs("button",{className:`btn ${y.mode==="script"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>w(O=>({...O,mode:"script",prompt:"",modelProvider:"",modelId:""})),"data-testid":"mode-script",children:[t.jsx(gi,{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:()=>w(O=>({...O,phase:"pre-merge"})),"data-testid":"phase-pre-merge",children:"Pre-merge"}),t.jsx("button",{className:`btn ${y.phase==="post-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>w(O=>({...O,phase:"post-merge"})),"data-testid":"phase-post-merge",children:"Post-merge"})]}),t.jsx("div",{className:"wfm-field-hint",children:y.phase==="pre-merge"?"Runs before merge — can block merge on failure":"Runs after merge success — failures are logged but do not block"})]}),y.mode==="prompt"&&t.jsxs("div",{className:"wfm-field",children:[t.jsxs("div",{className:"wfm-prompt-header",children:[t.jsx("label",{children:"Agent Prompt"}),t.jsxs("button",{className:"btn-icon wfm-refine-btn",onClick:ue,disabled:!y.description.trim()||j,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[j?t.jsx(ot,{size:12,className:"spin"}):t.jsx(cs,{size:12}),t.jsx("span",{children:"Refine with AI"})]})]}),t.jsx("textarea",{value:y.prompt,onChange:O=>w(ne=>({...ne,prompt:O.target.value})),placeholder:"Leave empty to use AI refinement",rows:6,className:"wfm-prompt-textarea","data-testid":"workflow-step-prompt"})]}),y.mode==="prompt"&&t.jsxs("div",{className:"wfm-field","data-testid":"workflow-step-model-field",children:[t.jsxs("div",{className:"wfm-model-header",children:[t.jsx("label",{children:"Model Override"}),y.modelProvider&&y.modelId&&t.jsxs("button",{type:"button",className:"btn-icon wfm-model-clear-btn",onClick:()=>w(O=>({...O,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[t.jsx(Ht,{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(Zn,{models:L,value:uP(y.modelProvider,y.modelId),onChange:O=>{const ne=mP(O);w(Q=>({...Q,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(B).length===0?t.jsx("div",{className:"wfm-no-scripts","data-testid":"no-scripts-message",children:"No scripts configured. Add scripts in Settings → Scripts first."}):t.jsxs("select",{value:y.scriptName,onChange:O=>w(ne=>({...ne,scriptName:O.target.value})),"data-testid":"workflow-step-script-select",children:[t.jsx("option",{value:"",children:"Select a script…"}),Object.entries(B).map(([O,ne])=>t.jsxs("option",{value:O,children:[O," (",ne,")"]},O))]})]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:y.enabled,onChange:O=>w(ne=>({...ne,enabled:O.target.checked})),"data-testid":"workflow-step-enabled"}),"Enabled (available for selection on new tasks)"]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:y.defaultOn,onChange:O=>w(ne=>({...ne,defaultOn:O.target.checked})),"data-testid":"workflow-step-default-on"}),"Default on for new tasks"]}),t.jsxs("div",{className:"wfm-form-actions",children:[t.jsx("button",{className:"btn btn-secondary",onClick:k,disabled:E,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:H,disabled:E||!y.name.trim()||!y.description.trim()||y.mode==="script"&&!y.scriptName.trim(),"data-testid":"save-workflow-step",children:E?"Saving...":v?"Create":"Save"})]})]})]})]})}),!he&&t.jsx("div",{className:"wfm-footer",children:t.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:I,"data-testid":"add-workflow-step",children:[t.jsx(rn,{size:14}),"Add Workflow Step"]})})]})})}const gP=36e5,bP=3e5,yc=[{value:3e5,label:"5m"},{value:9e5,label:"15m"},{value:18e5,label:"30m"},{value:36e5,label:"1h"},{value:108e5,label:"3h"},{value:216e5,label:"6h"},{value:432e5,label:"12h"},{value:864e5,label:"24h"},{value:1728e5,label:"48h"},{value:2592e5,label:"72h"},{value:6048e5,label:"1w"}];function xP(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 vP(e){return typeof e!="number"||!Number.isFinite(e)?gP:Math.max(bP,Math.round(e))}function x3(e){if(yc.some(s=>s.value===e))return[...yc];const n={value:e,label:`${xP(e)} (custom)`};return[...yc,n].sort((s,i)=>s.value-i.value)}const yP=4,jP=5*6e4;function kP(e){const n=vP(e?.heartbeatIntervalMs);return Math.max(n*yP,jP)}function wP(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 NP(e){const{state:n,lastHeartbeatAt:s,lastError:i,pauseReason:r,runtimeConfig:o}=e,l=wP(e),c=l||o?.enabled!==!1;if(n==="terminated")return{label:"Terminated",icon:t.jsx(Cs,{size:14}),color:"var(--state-error-text)",stateDerived:!0};if(n==="error")return{label:i??"Error",icon:t.jsx(Ds,{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(Ds,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!c)return{label:"Heartbeat Disabled",icon:t.jsx(qs,{size:14}),color:"var(--state-paused-text)",stateDerived:!1};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:t.jsx(Sn,{size:14}),color:"var(--text-secondary)",stateDerived:!1};const u=new Date(s).getTime(),d=Date.now()-u,m=kP(o);return d>m?{label:"Unresponsive",icon:t.jsx(Ds,{size:14}),color:"var(--state-error-text)",stateDerived:!1}:{label:"Healthy",icon:t.jsx(wx,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}const ir=[{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 SP({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(""),[f,p]=a.useState("custom"),[g,b]=a.useState("all"),[v,x]=a.useState(()=>{if(typeof window>"u")return"list";const T=Wn("fn-agent-view",i);return T==="board"||T==="list"?T:"list"});a.useEffect(()=>{const T=Wn("fn-agent-view",i);if(T==="board"||T==="list"){x(T);return}x("list")},[i]),a.useEffect(()=>{fs("fn-agent-view",v,i)},[i,v]);const[y,w]=a.useState(null),E=a.useRef(null),[C,j]=a.useState(new Set),[A,S]=a.useState(new Map),{confirm:z}=Ks(),_=a.useMemo(()=>A.size===0?r:r.map(T=>{const k=A.get(T.id);return k?{...T,state:k}:T}),[r,A]),R=a.useMemo(()=>g==="all"?_.filter(T=>T.state!=="terminated"):_,[_,g]),B=a.useCallback(async()=>{c(!0);try{const k=await Ra(g!=="all"?{state:g}:void 0,i);o(k)}catch(T){s(`Failed to load agents: ${we(T)}`,"error")}finally{c(!1)}},[g,s,i]);a.useEffect(()=>{e&&B()},[e,B]),a.useEffect(()=>{if(!e)return;const T=setInterval(()=>{B()},3e4);return()=>{clearInterval(T)}},[e,B]);const K=async()=>{if(m.trim())try{await gk({name:m.trim(),role:f},i),s(`Agent "${m}" created`,"success"),h(""),d(!1),B()}catch(T){s(`Failed to create agent: ${we(T)}`,"error")}},L=async(T,k)=>{if(!C.has(T)){j(H=>new Set(H).add(T)),S(H=>{const J=new Map(H);return J.set(T,k),J});try{await xk(T,k,i),s(`Agent state updated to ${k}`,"success"),await B(),S(H=>{const J=new Map(H);return J.delete(T),J})}catch(H){S(J=>{const ue=new Map(J);return ue.delete(T),ue}),s(`Failed to update state: ${we(H)}`,"error")}finally{j(H=>{const J=new Set(H);return J.delete(T),J})}}},$=async(T,k)=>{if(await z({title:"Delete Agent",message:`Delete agent "${k}"? This cannot be undone.`,danger:!0}))try{await vk(T,i),s(`Agent "${k}" deleted`,"success"),B()}catch(J){s(`Failed to delete agent: ${we(J)}`,"error")}},U=async(T,k)=>{const H=r.find(J=>J.id===T);if(H){if(H.role===k){w(null);return}try{await bk(T,{role:k},i),s(`Agent role updated to ${ir.find(J=>J.value===k)?.label??k}`,"success"),w(null),B()}catch(J){s(`Failed to update role: ${we(J)}`,"error")}}},G=(T,k)=>{T.key==="Escape"&&w(null)},Y=T=>ir.find(k=>k.value===T)?.label??T,ee=T=>ir.find(k=>k.value===T)?.icon??"◆",N=T=>NP(T),I=T=>T.color==="var(--state-active-text)"?"active":T.color==="var(--state-paused-text)"?"paused":T.color==="var(--state-error-text)"?"error":"muted";return e?t.jsx("div",{className:"modal-overlay open",onClick:T=>T.target===T.currentTarget&&n(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal--wide agent-list-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{className:"modal-title",children:[t.jsx(Sn,{size:20}),"Agents"]}),t.jsxs("div",{className:"modal-actions",children:[t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${v==="board"?" active":""}`,onClick:()=>x("board"),title:"Board view","aria-label":"Board view","aria-pressed":v==="board",children:t.jsx(qi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${v==="list"?" active":""}`,onClick:()=>x("list"),title:"List view","aria-label":"List view","aria-pressed":v==="list",children:t.jsx(Tc,{size:16})})]}),t.jsx("button",{className:"btn-icon",onClick:()=>void B(),title:"Refresh",disabled:l,children:t.jsx(Ln,{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:g,onChange:T=>b(T.target.value),"aria-label":"Filter agents by state",children:[t.jsx("option",{value:"all",children:"All States"}),t.jsx("option",{value:"idle",children:"Idle"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"running",children:"Running"}),t.jsx("option",{value:"paused",children:"Paused"}),t.jsx("option",{value:"error",children:"Error"}),t.jsx("option",{value:"terminated",children:"Terminated"})]})]}),t.jsxs("button",{className:"btn btn-task-create btn-sm",onClick:()=>d(!u),children:[t.jsx(rn,{size:16}),u?"Cancel":"New Agent"]})]}),u&&t.jsxs("div",{className:"agent-create-form",children:[t.jsx("input",{type:"text",placeholder:"Agent name...",value:m,onChange:T=>h(T.target.value),onKeyDown:T=>T.key==="Enter"&&K(),className:"input",autoFocus:!0}),t.jsx("select",{className:"select",value:f,onChange:T=>p(T.target.value),children:ir.map(T=>t.jsxs("option",{value:T.value,children:[T.icon," ",T.label]},T.value))}),t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:()=>void K(),children:"Create"})]}),t.jsx("div",{className:v==="board"?"agent-board":"agent-list",children:R.length===0?t.jsxs("div",{className:"agent-empty",children:[t.jsx(Sn,{size:48,opacity:.3}),t.jsx("p",{children:"No agents found"}),t.jsx("p",{className:"text-secondary",children:"Create an agent to get started"})]}):v==="board"?R.map(T=>{const k=N(T),H=I(k);return t.jsxs("div",{className:"agent-board-card","data-state":T.state,children:[t.jsxs("div",{className:"agent-board-header",children:[t.jsx("span",{className:"agent-board-icon",children:ee(T.role)}),t.jsx("span",{className:"agent-board-badge","data-state":T.state,children:T.state}),t.jsx("span",{className:"agent-board-health","data-health":H,title:k.label,children:k.icon})]}),t.jsx("div",{className:"agent-board-name",title:T.name,children:T.name}),t.jsx("div",{className:"agent-board-id",children:T.id}),t.jsxs("div",{className:"agent-board-actions",children:[T.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void L(T.id,"active"),disabled:C.has(T.id),title:"Activate",children:t.jsx(Cn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(T.id,T.name),title:"Delete",children:t.jsx(an,{size:14})})]}),T.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void L(T.id,"paused"),disabled:C.has(T.id),title:"Pause",children:t.jsx(qs,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void L(T.id,"terminated"),disabled:C.has(T.id),title:"Stop",children:t.jsx(Cs,{size:14})})]}),T.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void L(T.id,"active"),disabled:C.has(T.id),title:"Resume",children:t.jsx(Cn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void L(T.id,"terminated"),disabled:C.has(T.id),title:"Stop",children:t.jsx(Cs,{size:14})})]}),T.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void L(T.id,"paused"),disabled:C.has(T.id),title:"Pause",children:t.jsx(qs,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void L(T.id,"terminated"),disabled:C.has(T.id),title:"Stop",children:t.jsx(Cs,{size:14})})]}),T.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void L(T.id,"active"),disabled:C.has(T.id),title:"Retry",children:t.jsx(Cn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void L(T.id,"terminated"),disabled:C.has(T.id),title:"Stop",children:t.jsx(Cs,{size:14})})]}),T.state==="terminated"&&t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(T.id,T.name),title:"Delete",children:t.jsx(an,{size:14})})]})]},T.id)}):R.map(T=>{const k=N(T),H=I(k);return t.jsxs("div",{className:"agent-card","data-state":T.state,children:[t.jsxs("div",{className:"agent-card-header",children:[t.jsxs("div",{className:"agent-info",children:[y===T.id?t.jsx("select",{ref:E,className:"select agent-role-select",value:T.role,onChange:J=>void U(T.id,J.target.value),onKeyDown:J=>G(J,T.id),onBlur:()=>w(null),autoFocus:!0,children:ir.map(J=>t.jsxs("option",{value:J.value,children:[J.icon," ",J.label]},J.value))}):t.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>w(T.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:J=>{(J.key==="Enter"||J.key===" ")&&w(T.id)},children:ee(T.role)}),t.jsxs("div",{className:"agent-meta",children:[t.jsx("span",{className:"agent-name",children:T.name}),t.jsx("span",{className:"agent-id text-secondary",children:T.id})]})]}),t.jsxs("div",{className:"agent-badges",children:[t.jsx("span",{className:"badge agent-list-state-badge","data-state":T.state,children:T.state}),t.jsxs("span",{className:"badge agent-list-health-badge","data-health":H,title:k.label,children:[k.icon,!k.stateDerived&&` ${k.label}`]}),t.jsx("span",{className:"badge text-secondary",children:Y(T.role)})]})]}),t.jsxs("div",{className:"agent-card-body",children:[T.taskId&&t.jsxs("div",{className:"agent-task",children:[t.jsx("span",{className:"text-secondary",children:"Working on:"}),t.jsx("span",{className:"badge",children:T.taskId})]}),T.lastHeartbeatAt&&t.jsxs("div",{className:"agent-heartbeat",children:[t.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),t.jsx("span",{children:new Date(T.lastHeartbeatAt).toLocaleString()})]})]}),t.jsxs("div",{className:"agent-card-actions",children:[T.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void L(T.id,"active"),disabled:C.has(T.id),title:"Activate",children:[t.jsx(Cn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(T.id,T.name),title:"Delete",children:[t.jsx(an,{size:14})," Delete"]})]}),T.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void L(T.id,"paused"),disabled:C.has(T.id),title:"Pause",children:[t.jsx(qs,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void L(T.id,"terminated"),disabled:C.has(T.id),title:"Stop",children:[t.jsx(Cs,{size:14})," Stop"]})]}),T.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void L(T.id,"active"),disabled:C.has(T.id),title:"Resume",children:[t.jsx(Cn,{size:14})," Resume"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void L(T.id,"terminated"),disabled:C.has(T.id),title:"Stop",children:[t.jsx(Cs,{size:14})," Stop"]})]}),T.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void L(T.id,"paused"),disabled:C.has(T.id),title:"Pause",children:[t.jsx(qs,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void L(T.id,"terminated"),disabled:C.has(T.id),title:"Stop",children:[t.jsx(Cs,{size:14})," Stop"]})]}),T.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void L(T.id,"active"),disabled:C.has(T.id),title:"Retry",children:[t.jsx(Cn,{size:14})," Retry"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void L(T.id,"terminated"),disabled:C.has(T.id),title:"Stop",children:[t.jsx(Cs,{size:14})," Stop"]})]}),T.state==="terminated"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm btn-task-create",onClick:()=>void L(T.id,"active"),disabled:C.has(T.id),title:"Start",children:[t.jsx(Cn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(T.id,T.name),title:"Delete",children:[t.jsx(an,{size:14})," Delete"]})]})]})]},T.id)})})]})]})}):null}function CP({authenticated:e,onToggled:n,compact:s=!1}){const[i,r]=a.useState(null),[o,l]=a.useState(null),[c,u]=a.useState(null),d=a.useRef(!0);a.useEffect(()=>(d.current=!0,()=>{d.current=!1}),[]);const m=a.useCallback(async()=>{try{const x=await Py();return d.current&&r(x),x}catch(x){return d.current&&u({kind:"error",message:x instanceof Error?x.message:String(x)}),null}},[]);a.useEffect(()=>{m()},[m]);const h=a.useCallback(async()=>{l("testing"),u(null),await m(),d.current&&l(null)},[m]),f=a.useCallback(async x=>{l(x?"enabling":"disabling"),u(null);try{const y=await Ly(x);d.current&&u({kind:y.enabled?"enabled":"disabled",restartRequired:y.restartRequired}),n?.(y.enabled),await m()}catch(y){d.current&&u({kind:"error",message:y instanceof Error?y.message:String(y)})}finally{d.current&&l(null)}},[n,m]),p=i?.binary.available??!1,g=i?.enabled??e,b=t.jsxs("span",{className:"onboarding-provider-card__description",children:["Route AI calls through your locally-installed ",t.jsx("code",{children:"claude"})," CLI. Uses your existing Claude subscription / quota instead of an API key."]}),v=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:12,className:"animate-spin"}),"Testing…"]}):"Test"}),g?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void f(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void f(!0),disabled:o!==null||!p,title:p?void 0:"`claude` binary not detected on PATH — install Claude CLI first.",children:o==="enabling"?"Enabling…":"Enable"})]});return s?t.jsxs("div",{className:`auth-provider-card auth-provider-card--cli${e?" auth-provider-card--authenticated":""}`,"data-testid":"claude-cli-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(An,{provider:"claude-cli",size:"sm"}),t.jsx("strong",{children:"Anthropic — via Claude CLI"}),t.jsx(EP,{status:i,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:v})]}),t.jsxs("details",{className:"auth-provider-cli-details",children:[t.jsx("summary",{children:"Details"}),t.jsxs("div",{className:"auth-provider-cli-details-body",children:[b,t.jsx(Dh,{status:i,authenticated:e}),c&&t.jsx(Lh,{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(An,{provider:"claude-cli",size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:"Anthropic — via Claude CLI"}),b,t.jsx(Dh,{status:i,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(Lh,{action:c})]})}function EP({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 Dh({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(ot,{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 Lh({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 _P({authenticated:e,onToggled:n,compact:s=!1}){const[i,r]=a.useState(null),[o,l]=a.useState(null),[c,u]=a.useState(null),d=a.useRef(!0);a.useEffect(()=>(d.current=!0,()=>{d.current=!1}),[]);const m=a.useCallback(async()=>{try{const x=await Dy();return d.current&&r(x),x}catch(x){return d.current&&u({kind:"error",message:x instanceof Error?x.message:String(x)}),null}},[]);a.useEffect(()=>{m()},[m]);const h=a.useCallback(async()=>{l("testing"),u(null),await m(),d.current&&l(null)},[m]),f=a.useCallback(async x=>{l(x?"enabling":"disabling"),u(null);try{const y=await zy(x);d.current&&u({kind:y.enabled?"enabled":"disabled",restartRequired:y.restartRequired}),n?.(y.enabled),await m()}catch(y){d.current&&u({kind:"error",message:y instanceof Error?y.message:String(y)})}finally{d.current&&l(null)}},[n,m]),p=i?.binary.available??!1,g=i?.enabled??e,b=t.jsxs("span",{className:"onboarding-provider-card__description",children:["Route AI calls through your locally-installed ",t.jsx("code",{children:"droid"})," CLI. Uses your existing Factory AI subscription / quota instead of an API key."]}),v=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:12,className:"animate-spin"}),"Testing…"]}):"Test"}),g?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void f(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void f(!0),disabled:o!==null||!p,title:p?void 0:"`droid` binary not detected on PATH — install Droid CLI first.",children:o==="enabling"?"Enabling…":"Enable"})]});return s?t.jsxs("div",{className:`auth-provider-card auth-provider-card--cli${e?" auth-provider-card--authenticated":""}`,"data-testid":"droid-cli-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(An,{provider:"droid-cli",size:"sm"}),t.jsx("strong",{children:"Factory AI — via Droid CLI"}),t.jsx(MP,{status:i,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:v})]}),t.jsxs("details",{className:"auth-provider-cli-details",children:[t.jsx("summary",{children:"Details"}),t.jsxs("div",{className:"auth-provider-cli-details-body",children:[b,t.jsx(zh,{status:i,authenticated:e}),c&&t.jsx(Fh,{action:c})]})]})]}):t.jsxs("div",{className:`onboarding-provider-card${e?" onboarding-provider-card--connected":""}`,"data-testid":"droid-cli-provider-card",children:[t.jsx("div",{className:"onboarding-provider-card__icon",children:t.jsx(An,{provider:"droid-cli",size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:"Factory AI — via Droid CLI"}),b,t.jsx(zh,{status:i,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(Fh,{action:c})]})}function MP({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 zh({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(ot,{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:"droid"})," ",s.version?`(${s.version})`:""," detected",s.binaryPath?` at ${s.binaryPath}`:"",". Click Enable to route AI calls through it."]}):t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--error",children:["✗ ",s.reason??"`droid` not found on PATH"]})}function Fh({action:e}){if(e.kind==="error")return t.jsx("p",{className:"onboarding-helper-text onboarding-helper-text--error",children:e.message});const n=e.kind==="enabled"?"Enabled":"Disabled";return t.jsxs("p",{className:"onboarding-helper-text",children:[n,"."," ",e.kind==="enabled"?"Factory AI (via Droid CLI) models are now visible in the model picker.":"Factory AI (via Droid CLI) models are hidden from the model picker.",e.restartRequired?" Restart required: restart your active CLI/chat session for routing changes to take effect.":""]})}function AP(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 jc({instructions:e,"data-testid":n}){const[s,i]=a.useState(!1),r=AP(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(Vn,{size:12}):t.jsx(Ui,{size:12})})]})]},d))}):e})}const RP=new Set(["anthropic","claude-cli","pi-claude-cli","openai","openai-codex","google","gemini","google-antigravity","antigravity","google-vertex","vertex","google-cloud-code","cloud-code","google-gemini-cli","google-generative-ai","ollama","github","github-copilot","openrouter","minimax","minimax-cn","zai","kimi","moonshot","kimi-coding","bedrock","amazon-bedrock","xai","grok","opencode","opencode-go","qwen","qwen-ai","qwen-coder","alibaba","tongyi","lmstudio","lm-studio","huggingface","hugging-face","hf","mistral","mistral-ai","azure","azure-openai","azure-openai-responses","fireworks","fireworks-ai","fireworksai","cerebras","groq","vercel","vercel-ai-gateway","hermes","hermes-agent","hermesagent","openclaw","open-claw","paperclip","paperclipai","paperclip-ai"]),TP=/^[a-z][a-z0-9-]*$/,Oh=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function Uh(){return{id:"",name:"",reasoning:!1}}function PP({initialConfig:e,onSave:n,onCancel:s,saving:i=!1,error:r}){const o=!!e,[l,c]=a.useState(e?.id??""),[u,d]=a.useState(e?.name??""),[m,h]=a.useState(e?.baseUrl??""),[f,p]=a.useState(e?.api??"openai-completions"),[g,b]=a.useState(e?.apiKey??""),[v,x]=a.useState(e?.models?.length?e.models:[Uh()]),[y,w]=a.useState(null),E=v.length>1,C=a.useMemo(()=>y??r??null,[y,r]);function j(_,R){x(B=>B.map((K,L)=>L===_?{...K,...R}:K))}function A(_){x(R=>R.length<=1?R:R.filter((B,K)=>K!==_))}function S(){if(!l.trim())return"Provider ID is required.";if(!TP.test(l.trim()))return"Provider ID must be kebab-case.";if(!o&&RP.has(l.trim()))return"Provider ID conflicts with a built-in provider.";if(!m.trim())return"Base URL is required.";try{const _=new URL(m.trim());if(_.protocol!=="http:"&&_.protocol!=="https:")return"Base URL must use http or https."}catch{return"Base URL must be a valid URL."}return Oh.includes(f)?v.length===0?"At least one model is required.":v.some(_=>!_.id?.trim())?"Each model must have a model ID.":null:"API type is required."}async function z(_){_.preventDefault();const R=S();w(R),!R&&await n({id:l.trim(),name:u.trim()||void 0,baseUrl:m.trim(),api:f,apiKey:g.trim()||void 0,models:v.map(B=>({id:B.id.trim(),name:B.name?.trim()||void 0,reasoning:!!B.reasoning,contextWindow:B.contextWindow,maxTokens:B.maxTokens}))})}return t.jsxs("form",{onSubmit:z,className:"custom-provider-form","aria-label":"custom-provider-form",children:[t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-id",children:"Provider ID"}),t.jsx("input",{id:"custom-provider-id",className:"input",value:l,onChange:_=>c(_.target.value),disabled:o||i})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-name",children:"Display Name"}),t.jsx("input",{id:"custom-provider-name",className:"input",value:u,onChange:_=>d(_.target.value),disabled:i})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-base-url",children:"Base URL"}),t.jsx("input",{id:"custom-provider-base-url",className:"input",value:m,onChange:_=>h(_.target.value),disabled:i})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-api",children:"API Type"}),t.jsx("select",{id:"custom-provider-api",className:"select",value:f,onChange:_=>p(_.target.value),disabled:i,children:Oh.map(_=>t.jsx("option",{value:_,children:_},_))})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-api-key",children:"API Key"}),t.jsx("input",{id:"custom-provider-api-key",className:"input",placeholder:"sk-..., MY_API_KEY, or !command",value:g,onChange:_=>b(_.target.value),disabled:i})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{children:"Models"}),t.jsx("div",{className:"custom-provider-form__models",children:v.map((_,R)=>t.jsxs("div",{className:"custom-provider-form__model-row",children:[t.jsx("input",{className:"input","aria-label":`Model ID ${R+1}`,placeholder:"Model ID",value:_.id,onChange:B=>j(R,{id:B.target.value}),disabled:i}),t.jsx("input",{className:"input","aria-label":`Model name ${R+1}`,placeholder:"Display name",value:_.name??"",onChange:B=>j(R,{name:B.target.value}),disabled:i}),t.jsxs("label",{className:"checkbox-label custom-provider-form__toggle",children:[t.jsx("input",{type:"checkbox",checked:!!_.reasoning,onChange:B=>j(R,{reasoning:B.target.checked}),disabled:i}),"Reasoning"]}),t.jsx("input",{className:"input","aria-label":`Context window ${R+1}`,placeholder:"Context window",type:"number",value:_.contextWindow??"",onChange:B=>j(R,{contextWindow:B.target.value?Number(B.target.value):void 0}),disabled:i}),t.jsx("input",{className:"input","aria-label":`Max tokens ${R+1}`,placeholder:"Max tokens",type:"number",value:_.maxTokens??"",onChange:B=>j(R,{maxTokens:B.target.value?Number(B.target.value):void 0}),disabled:i}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>A(R),disabled:i||!E,"aria-label":`Remove model ${R+1}`,children:"×"})]},`${R}-model`))}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>x(_=>[..._,Uh()]),disabled:i,children:"+ Add model"})]}),C?t.jsx("div",{className:"form-error",children:C}):null,t.jsxs("div",{className:"custom-provider-form__actions",children:[s?t.jsx("button",{type:"button",className:"btn",onClick:s,disabled:i,children:"Cancel"}):null,t.jsx("button",{type:"submit",className:"btn btn-primary",disabled:i,children:i?"Saving...":"Save Provider"})]})]})}const Gi="fusion_model_onboarding_state",Na=[],Sa=[],Wo=!1,Ko=!1,Ca={},IP=void 0,wi=["ai-setup","github","project-setup","first-task"],$P={"ai-setup":"AI Setup",github:"GitHub","project-setup":"Project","first-task":"First Task",complete:"Complete"};function As(){if(typeof window>"u")return null;try{const e=localStorage.getItem(Gi);if(!e)return null;const n=JSON.parse(e);return n&&typeof n=="object"&&"currentStep"in n&&typeof n.currentStep=="string"?DP(n):null}catch{return null}}function DP(e){const n=e.postOnboardingDismissedAt??IP;return{...e,completedSteps:e.completedSteps??Na,skippedSteps:e.skippedSteps??Sa,dismissed:e.dismissed??Wo,completed:e.completed??Ko,stepData:e.stepData??Ca,...n?{postOnboardingDismissedAt:n}:{}}}function jo(e,n){if(!(typeof window>"u")){if(!n){const s={currentStep:e,updatedAt:new Date().toISOString(),completedSteps:Na,skippedSteps:Sa,dismissed:Wo,completed:Ko,stepData:Ca};try{localStorage.setItem(Gi,JSON.stringify(s))}catch{}return}try{const s=As(),i=new Date().toISOString(),r=n.completed??Ko;let o=n.dismissed??Wo;r&&(o=!1);const l=n.completedSteps??s?.completedSteps??Na,c=n.skippedSteps??s?.skippedSteps??Sa,u={...s?.stepData??Ca};if(n.stepData)for(const[m,h]of Object.entries(n.stepData))h!==void 0&&(u[m]={...u[m]??{},...h});const d={currentStep:e,updatedAt:i,completedSteps:l,skippedSteps:c,dismissed:o,completed:r,stepData:u};localStorage.setItem(Gi,JSON.stringify(d))}catch{}}}function LP(e){if(!(typeof window>"u"))try{const n=As(),s=new Date().toISOString();if(!n){const o={currentStep:e,updatedAt:s,completedSteps:Na,skippedSteps:[e],dismissed:Wo,completed:Ko,stepData:Ca};localStorage.setItem(Gi,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(Gi,JSON.stringify(r))}catch{}}function Bh(){if(!(typeof window>"u"))try{const e=As(),n=new Date().toISOString(),s=e?{...e,completedAt:n,completed:!0,dismissed:!1,updatedAt:n}:{currentStep:"complete",updatedAt:n,completedAt:n,completedSteps:Na,skippedSteps:Sa,dismissed:!1,completed:!0,stepData:Ca};localStorage.setItem(Gi,JSON.stringify(s))}catch{}}function Ea(){const e=As();return e?e.completed===!0?!0:typeof e.completedAt=="string"&&e.completedAt.length>0:!1}function zP(){if(!(typeof window>"u"))try{const e=As(),n=new Date().toISOString(),s=e?{...e,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:Na,skippedSteps:Sa,dismissed:!1,completed:!1,stepData:Ca,postOnboardingDismissedAt:n};localStorage.setItem(Gi,JSON.stringify(s))}catch{}}function Ag(){const e=As();return e?typeof e.postOnboardingDismissedAt=="string"&&e.postOnboardingDismissedAt.length>0:!1}function FP(){const e=As();return!e||Ea()?!1:e.currentStep!=="complete"}function OP(){const e=As();if(!e||Ea()||e.currentStep==="complete")return null;const n=e.currentStep,s=$P[n]??HP(e.currentStep);return{currentStep:e.currentStep,label:s,completedSteps:e.completedSteps}}function UP(){const e=As();return e?e.skippedSteps:Sa}function BP(e){const n=As();return!n||!n.stepData?null:n.stepData[e]??null}function HP(e){return e.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const Rg="fusion_onboarding_events",Hh="fusion_onboarding_session_id",qP=200,VP=50;function Is(e,n={}){if(!(typeof window>"u"))try{const s=KP(),i=YP(n.step),r={type:e,timestamp:new Date().toISOString(),...i?{step:i}:{},metadata:n,sessionId:WP()},o=JP([...s,r]);GP(o)}catch{}}function WP(){if(typeof window>"u")return"server-session";try{const e=sessionStorage.getItem(Hh);if(e)return e;const n=qh();return sessionStorage.setItem(Hh,n),n}catch{return qh()}}function qh(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function KP(){try{const e=localStorage.getItem(Rg);if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(QP):[]}catch{return[]}}function GP(e){try{localStorage.setItem(Rg,JSON.stringify(e))}catch{}}function JP(e){const n=[...e];for(;n.length>qP;)n.splice(0,VP);return n}function YP(e){if(e==="ai-setup"||e==="github"||e==="first-task"||e==="complete")return e}function QP(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 XP=e=>({id:e.id,name:e.name,baseUrl:e.baseUrl,api:"api"in e?e.api:e.apiType==="anthropic-compatible"?"anthropic-messages":"openai-responses",apiKey:e.apiKey,models:e.models?.map(n=>({id:n.id,name:n.name}))??[]}),ZP={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"}}},Tg={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:"..."}},eI={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},Vh={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 ad(e){if(Vh[e])return Vh[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 kc=["anthropic","openai","google","gemini","ollama"],tI=["anthropic","claude-cli","droid-cli","openai-codex","gemini","minimax","kimi","zai"],nI={anthropic:"anthropic","claude-cli":"claude-cli","droid-cli":"droid-cli","openai-codex":"openai-codex",google:"gemini",gemini:"gemini",minimax:"minimax",kimi:"kimi",moonshot:"kimi","kimi-coding":"kimi",zai:"zai"},sI={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function rd(e){return nI[e]??e}function Wh(e){const n=rd(e),s=tI.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function Kh(e,n){if(e.authenticated!==n.authenticated)return e.authenticated?-1:1;const s=Wh(e.id),i=Wh(n.id);if(s!==i)return s-i;const r=rd(e.id),o=rd(n.id);if(r!==o)return r.localeCompare(o);const l=sI[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 iI(e,n){const s=n.trim();if(!s)return"API key is required";const i=Tg[e]??eI;return i.pattern.test(s)?null:`${ad(e)} keys should follow this format: ${i.hint} (e.g. ${i.example})`}const Pg={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"},aI={description:"AI provider — connect to start using AI models",apiKeyInfo:Pg};function od(e){return ZP[e]??aI}function rI(e){return od(e.id).apiKeyInfo??Pg}function si({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(xn,{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 oI({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 lI({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(),f=Tg[e.id],p=`input onboarding-apikey-input${r?" onboarding-apikey-input--error":""}${o?" onboarding-apikey-input--success":""}`,g=t.jsxs(t.Fragment,{children:[f&&t.jsxs("small",{className:"onboarding-apikey-hint",children:["Format: ",f.hint]}),t.jsx("p",{className:"onboarding-apikey-instructions",children:n.setupInstructions}),n.dashboardUrl&&t.jsx("a",{href:n.dashboardUrl,target:"_blank",rel:"noreferrer",className:"onboarding-apikey-dashboard-link",children:"Get your API key →"}),t.jsx("p",{className:"onboarding-apikey-usage",children:n.usageDescription})]});return l?t.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${e.id}`,children:[t.jsxs("div",{className:"onboarding-apikey-connected-header",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:n.fieldLabel}),t.jsx("span",{className:"auth-status-badge connected",children:"✓ API key saved"})]}),t.jsx("button",{className:"btn btn-sm",onClick:()=>d(e.id),disabled:i,children:i?"Removing…":"Remove Key"}),t.jsx(si,{summary:"Advanced setup details",children:g}),r&&t.jsx("small",{className:"field-error",children:r})]}):t.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${e.id}`,children:[t.jsx("label",{htmlFor:m,className:"onboarding-apikey-field-label",children:n.fieldLabel}),t.jsxs("div",{className:"onboarding-apikey-input-row",children:[t.jsx("input",{id:m,type:"password",className:p,placeholder:n.inputPlaceholder??"Enter API key",value:s,onChange:b=>c(e.id,b.target.value),onKeyDown:b=>{b.key==="Enter"&&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(si,{summary:"Advanced setup details",children:g})]})}const cI=150;function dI({onComplete:e,addToast:n,projectId:s,onOpenSetupWizard:i,onOpenNewTask:r,onOpenGitHubImport:o,firstCreatedTask:l,onViewTask:c}){const u=As(),d=u?.currentStep,m=d==="complete"?"ai-setup":wi.includes(d)?d:"ai-setup",h=u?.completedSteps??[],f=u?.skippedSteps??UP(),[p,g]=a.useState(!0),[b,v]=a.useState(m),[x,y]=a.useState(h),[w,E]=a.useState(f),[C,j]=a.useState(!1),[A,S]=a.useState(""),[z,_]=a.useState(!1),[R,B]=a.useState(null),[K,L]=a.useState(null),[$,U]=a.useState([]),[G,Y]=a.useState(void 0),[ee,N]=a.useState(!0),[I,T]=a.useState(null),[k,H]=a.useState({}),[J,ue]=a.useState([]),[fe,W]=a.useState(""),[he,O]=a.useState(!1),[ne,Q]=a.useState({}),[ge,de]=a.useState({}),[me,ie]=a.useState({}),[Ee,Ue]=a.useState([]),[Te,at]=a.useState(!1),[et,Ve]=a.useState(!1),[Xe,De]=a.useState(),Be=a.useRef({}),oe=a.useRef(null),Ne=a.useRef(null),se=a.useRef(null),[Me,Le]=a.useState({}),[pe,Ae]=a.useState(()=>As()?.stepData?.github?.skipped===!0),Je=a.useRef(0),it=a.useRef(l),ye=a.useRef(!1),ce=u?.currentStep,Re=!!u&&u.currentStep!=="complete";di(Ne,p,"fusion:model-onboarding-modal-size"),a.useEffect(()=>{const M=oe.current;M&&(M.scrollTop=0)},[b]);const[be,Pe]=a.useState(()=>As()?.stepData?.["ai-setup"]?.skippedProviders??{}),Ye=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"project-setup",label:"Project"},{key:"first-task",label:"First Task"}],$e=Ye.findIndex(M=>M.key===b),ft=b==="complete"?Ye.length:$e;a.useEffect(()=>{b!=="complete"&&jo(b,{completedSteps:x,skippedSteps:w})},[b,x,w]),a.useEffect(()=>{ye.current||(ye.current=!0,Is("onboarding:wizard-opened",{source:Re?"resume":"initial",resumedFromStep:ce}))},[Re,ce]),a.useEffect(()=>{const M=it.current!=null,le=l!=null;!M&&le&&j(!0),le||j(!1),it.current=l},[l]);const Z=a.useRef(m);a.useEffect(()=>{if(Z.current==="ai-setup"&&b!=="ai-setup"&&!$.some(le=>le.id!=="github"&&le.authenticated)){const le={};for(const Se of $)Se.id!=="github"&&!Se.authenticated&&!be[Se.id]&&(le[Se.id]=!0);if(Object.keys(le).length>0){const Se={...be,...le};Pe(Se),jo(b,{stepData:{"ai-setup":{skippedProviders:Se}}})}}Z.current=b},[b,$,be]);const re=a.useCallback(async()=>{try{const{providers:M,ghCli:le}=await Sr();U(M),Y(le),H(Se=>{const Qe={};for(const[ht,bt]of Object.entries(Se)){const zt=M.find(yn=>yn.id===ht);zt&&!zt.authenticated&&zt.loginInProgress&&(Qe[ht]=bt)}return Object.keys(Qe).length===Object.keys(Se).length?Se:Qe}),Le(Se=>{let Qe=!1;const ht={...Se};for(const[bt,zt]of Object.entries(Se)){if(zt!=="pending")continue;M.find(ts=>ts.id===bt)?.loginInProgress||(delete ht[bt],Qe=!0)}return Qe?ht:Se}),Pe(Se=>{const Qe={...Se};for(const ht of M)ht.authenticated&&Qe[ht.id]&&delete Qe[ht.id];return Object.keys(Qe).length===Object.keys(Se).length?Se:Qe})}catch{}},[]),je=a.useCallback(async()=>{try{const M=await Fy();Ue((M.providers??[]).map(XP))}catch{}},[]),rt=a.useCallback(async M=>{Ve(!0),De(void 0);try{await Uy(M),await je(),await bs().then(le=>ue(le.models??[])),at(!1)}catch(le){De(we(le)||"Failed to create custom provider")}finally{Ve(!1)}},[je]),te=a.useRef(!1);a.useEffect(()=>{b==="ai-setup"&&je(),te.current&&re(),te.current=b!=="ai-setup"},[b,re,je]),a.useEffect(()=>{if(!$.some(Se=>Se.loginInProgress))return;const le=setInterval(()=>{re()},2e3);return()=>clearInterval(le)},[$,re]);const Ze=$.find(M=>M.id==="github"),pt=!!Ze,gt=Ze?.authenticated??!1,wt=Ze?.loginInProgress??!1,Et=G?.authenticated??!1,mt=gt||Et,Nt=!gt&&Et,Tt=a.useCallback(M=>{if(M.authenticated)return"connected";const le=Me?.[M.id];return le==="timeout"||le==="failed"?"retry":be[M.id]?"skipped":"not-connected"},[Me,be]);function qt({status:M}){const le={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:Se,className:Qe}=le[M];return t.jsx("span",{"data-testid":"provider-status-badge",className:Qe,"data-status":M,children:Se})}const Pt=a.useCallback(()=>{if(mt)return"connected";const M=Me.github;return M==="pending"?"pending":M==="failed"||M==="timeout"?"failed":pe?"skipped":"not-connected"},[mt,Me,pe]);function At({status:M}){const le={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:Se,className:Qe}=le[M];return t.jsx("span",{"data-testid":"github-status-badge",className:Qe,"data-status":M,children:Se})}const Bt=a.useCallback(async()=>{try{const M=await bs();ue(M.models)}catch{}},[]),Ft=a.useCallback(async()=>{try{const M=await Ji();if(M.defaultProvider&&M.defaultModelId){const le=`${M.defaultProvider}/${M.defaultModelId}`;W(le)}}catch{}},[]);a.useEffect(()=>{Promise.all([re(),Bt(),Ft()]).finally(()=>N(!1))},[re,Bt,Ft]),a.useEffect(()=>{const M=BP("ai-setup");if(M?.loginOutcomes){const le=M.loginOutcomes,Se={};for(const[Qe,ht]of Object.entries(le))ht!=="pending"&&(Se[Qe]=ht);Object.keys(Se).length>0&&Le(Se)}},[]);const Dt=a.useCallback((M,le)=>{jo(b,{completedSteps:x,stepData:{"ai-setup":{loginOutcomes:{[M]:le}}}})},[b,x]);a.useEffect(()=>{const M=Object.entries(Me).filter(([le,Se])=>Se!=="pending");for(const[le,Se]of M)Dt(le,Se)},[Me,Dt]),a.useEffect(()=>()=>{se.current&&clearInterval(se.current),Object.values(Be.current).forEach(clearTimeout),Be.current={}},[]);const Mt=a.useCallback(M=>{Ae(M),jo(b,{completedSteps:x,stepData:{github:{skipped:M}}})},[b,x]),St=a.useCallback(M=>M==="complete"?-1:wi.indexOf(M),[]),Wt=a.useCallback(()=>{y(le=>[...new Set([...le,b])]),E(le=>le.filter(Se=>Se!==b)),Is("onboarding:step-completed",{step:b}),b==="github"&&!gt&&Mt(!1);const M=St(b);M>=0&&M<wi.length-1&&v(wi[M+1])},[b,gt,Mt,St]),It=a.useCallback(()=>{E(le=>[...new Set([...le,b])]),LP(b),Is("onboarding:step-skipped",{step:b}),b==="github"&&!gt&&Mt(!0);const M=St(b);M>=0&&M<wi.length-1&&v(wi[M+1])},[b,gt,Mt,St]),Yt=a.useCallback(()=>{const M=b;y(Se=>Se.filter(Qe=>Qe!==M)),E(Se=>Se.filter(Qe=>Qe!==M)),M==="github"&&!gt&&Mt(!1);const le=St(b);le>0&&v(wi[le-1])},[b,gt,Mt,St]),Rt=a.useCallback(()=>{It()},[It]),xe=a.useCallback(async M=>{Le(le=>{const Se=le[M];if(Se&&Se!=="pending"){const{[M]:Qe,...ht}=le;return ht}return le}),H(le=>{if(!(M in le))return le;const Se={...le};return delete Se[M],Se}),Le(le=>({...le,[M]:"pending"})),T(M),Je.current=0;try{const{url:le,instructions:Se}=await By(M);Se?.trim()&&H(Qe=>({...Qe,[M]:Se})),window.open(oi(le),"_blank"),se.current=setInterval(async()=>{if(Je.current++,Je.current>=cI){se.current&&(clearInterval(se.current),se.current=null),T(null),Le(Qe=>({...Qe,[M]:"timeout"})),H(Qe=>{if(!(M in Qe))return Qe;const ht={...Qe};return delete ht[M],ht}),n("Login timed out. Please try again.","warning");return}try{const{providers:Qe,ghCli:ht}=await Sr();U(Qe),Y(ht),Qe.find(zt=>zt.id===M)?.authenticated&&(se.current&&(clearInterval(se.current),se.current=null),T(null),Le(zt=>({...zt,[M]:"success"})),H(zt=>{if(!(M in zt))return zt;const yn={...zt};return delete yn[M],yn}),M==="github"&&Mt(!1),n("Login successful","success"))}catch{}},2e3)}catch(le){le instanceof Error&&le.message.includes("already in progress")||le&&typeof le=="object"&&"status"in le&&le.status===409?(n("Login already in progress. Cancel it to retry.","warning"),Le(Qe=>({...Qe,[M]:"pending"})),re()):(n(le instanceof Error?le.message:"Login failed","error"),Le(Qe=>({...Qe,[M]:"failed"}))),T(null),H(Qe=>{if(!(M in Qe))return Qe;const ht={...Qe};return delete ht[M],ht})}},[n,re,Mt]),Fe=a.useCallback(async M=>{se.current&&(clearInterval(se.current),se.current=null),T(M),Je.current=0;try{await qy(M),await re(),Le(le=>({...le,[M]:"cancelled"})),n("Login cancelled","success")}catch(le){n(we(le)||"Failed to cancel login","error")}finally{T(null),H(le=>{if(!(M in le))return le;const Se={...le};return delete Se[M],Se})}},[n,re]),ct=a.useCallback((M,le)=>{Q(Qe=>({...Qe,[M]:le}));const Se=Be.current[M];Se&&(clearTimeout(Se),delete Be.current[M]),de(Qe=>{if(!Qe[M])return Qe;const ht={...Qe};return delete ht[M],ht}),ie(Qe=>{if(!Qe[M])return Qe;const ht={...Qe};return delete ht[M],ht})},[]),D=a.useCallback(()=>{const M=oe.current;if(!M)return;const le=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof M.scrollTo=="function"){M.scrollTo({top:0,behavior:le?"auto":"smooth"});return}}catch{}M.scrollTop=0},[]),F=a.useCallback(async(M,le)=>{const Se=(le??ne[M]??"").trim(),Qe=iI(M,Se);if(Qe){de(bt=>({...bt,[M]:Qe}));return}const ht=Be.current[M];ht&&(clearTimeout(ht),delete Be.current[M]),T(M),de(bt=>{const zt={...bt};return delete zt[M],zt}),ie(bt=>{if(!bt[M])return bt;const zt={...bt};return delete zt[M],zt});try{await Vy(M,Se),await re(),D(),Q(bt=>{const zt={...bt};return delete zt[M],zt}),de(bt=>{if(!bt[M])return bt;const zt={...bt};return delete zt[M],zt}),ie(bt=>({...bt,[M]:"✓ Key saved"})),Be.current[M]=setTimeout(()=>{ie(bt=>{if(!bt[M])return bt;const zt={...bt};return delete zt[M],zt}),delete Be.current[M]},3e3),n("API key saved","success")}catch(bt){const zt=bt instanceof TypeError&&bt.message.includes("Failed to fetch")?"Could not reach the server. Check your connection and try again.":bt instanceof Error?bt.message:"Failed to save API key";de(yn=>({...yn,[M]:zt})),ie(yn=>{if(!yn[M])return yn;const ts={...yn};return delete ts[M],ts}),n(zt,"error")}finally{T(null)}},[ne,n,re,D]),ve=a.useCallback(async M=>{T(M);try{await Wy(M),await re(),n("API key removed","success")}catch(le){n(le instanceof Error?le.message:"Failed to clear API key","error")}finally{T(null)}},[n,re]),ze=a.useCallback(async M=>{T(M);try{await Hy(M),await re(),n("Logged out","success")}catch(le){n(le instanceof Error?le.message:"Logout failed","error")}finally{T(null)}},[n,re]),Oe=a.useCallback(M=>{W(M)},[]),Ge=a.useCallback(async()=>{try{const M={modelOnboardingComplete:!0};if(fe){const le=fe.indexOf("/"),Se=le!==-1?fe.slice(0,le):void 0,Qe=le!==-1?fe.slice(le+1):fe,ht=J.find(bt=>bt.id===Qe);ht?(M.defaultProvider=ht.provider,M.defaultModelId=ht.id):Se&&Qe&&(M.defaultProvider=Se,M.defaultModelId=Qe)}await pn(M),Bh()}catch{}},[fe,J,pn,Bh]),dt=a.useCallback(async()=>{const M=[...new Set([...x,"first-task"])];O(!0);try{await Ge(),Is("onboarding:completed",{completedSteps:M,skippedSteps:w}),y(M),E(le=>le.filter(Se=>Se!=="first-task")),v("complete")}finally{O(!1)}},[Ge,x,w]),Zt=a.useCallback(async()=>{if(!s)return;const M=A.trim();if(!M){B("Please enter a task description.");return}B(null),_(!0);let le=!1;try{const Se=await Np({description:M,source:{sourceType:"dashboard_ui"}},s);L(Se),j(!0),Is("onboarding:first-task-created",{taskId:Se?.id}),n("Task created","success"),le=!0}catch(Se){const Qe=Se instanceof Error?Se.message:"Something went wrong creating your task. Please try again.";B(Qe),n(Qe,"error")}finally{_(!1)}le&&Ge()},[s,A,n,Ge]),Nn=a.useCallback(async()=>{O(!0);try{await Ge()}finally{O(!1)}Is("onboarding:open-new-task",{}),r?.()},[Ge,r]),un=a.useCallback(async()=>{if(mt){O(!0);try{await Ge()}finally{O(!1)}g(!1),e(),Is("onboarding:open-github-import",{}),o?.()}},[Ge,mt,e,o]),Kt=a.useCallback(async()=>{Is("onboarding:dismissed",{currentStep:b,completedSteps:x,skippedSteps:w}),O(!0);try{await pn({modelOnboardingComplete:!0})}catch{}g(!1),e()},[b,x,w,e]),mn=a.useCallback(()=>{Is("onboarding:finished",{}),g(!1),e()},[e]),ke=a.useCallback(()=>{const M=l??K;M&&(Ge(),c?.(M),e())},[l,K,Ge,c,e]),ut=a.useCallback(()=>{Ge(),e()},[Ge,e]);if(!p)return null;const Lt=Pt(),En=$.filter(M=>M.id!=="github"),hn=[...En].sort(Kh),Rn=hn.some(M=>!M.type||M.type==="oauth"),is=hn.some(M=>M.type==="api_key"),Dn=En.filter(M=>M.authenticated),nn=Dn.length>0,cn=!!s,Hn=b==="github"&&!nn,fn=(()=>{if(!fe)return"";const M=fe.indexOf("/"),le=M===-1?void 0:fe.slice(0,M),Se=M===-1?fe:fe.slice(M+1),Qe=J.find(ht=>ht.id===Se&&(!le||ht.provider===le));return Qe?.name?Qe.name:le?`${ad(le)} ${Se}`:fe})(),dn=[];if(cn?dn.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):dn.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),nn){const M=ad(Dn[0]?.id??"");dn.push({label:"AI Provider",status:"connected",detail:`${M} connected — AI agents can work on tasks`})}else En.length>0&&En.some(M=>be[M.id])?dn.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):dn.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});mt?dn.push({label:"GitHub",status:"connected",detail:Nt?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!pt||pe?dn.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):dn.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),fn&&dn.push({label:"Default Model",status:"connected",detail:fn});const _n=l??K,zn=_n?.description?.split(`
661
+ `)[0]?.trim()||_n?.title||"",es=new Set(kc),Fn=hn.filter(M=>es.has(M.id)).sort((M,le)=>{const Se=kc.indexOf(M.id),Qe=kc.indexOf(le.id);return Se!==Qe?Se-Qe:Kh(M,le)}),Qt=hn.filter(M=>M.authenticated&&!es.has(M.id)),yt=hn.filter(M=>!M.authenticated&&!es.has(M.id)),on=M=>{if(M.id==="droid-cli"&&M.type==="cli")return t.jsx(_P,{authenticated:M.authenticated,onToggled:()=>{re()}},M.id);if(M.id==="claude-cli"&&M.type==="cli")return t.jsx(CP,{authenticated:M.authenticated,onToggled:()=>{re()}},M.id);if(M.type==="api_key"){const le=od(M.id),Se=rI(M);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${M.id}`,className:`onboarding-provider-card${M.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${M.id}`,"aria-hidden":"true",children:t.jsx(An,{provider:M.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(bp,{size:14,className:"onboarding-provider-key-icon"}),M.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:le.description}),t.jsx(qt,{status:Tt(M)}),M.authenticated&&M.keyHint&&t.jsxs("span",{className:"auth-key-hint",children:["Key: ",M.keyHint]})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx(lI,{provider:M,apiKeyInfo:Se,inputValue:ne[M.id]??"",isSaving:I===M.id,error:ge[M.id],success:me[M.id],isConnected:M.authenticated,onInputChange:ct,onSave:F,onClear:ve})})]},M.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${M.id}`,className:`onboarding-provider-card${M.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${M.id}`,"aria-hidden":"true",children:t.jsx(An,{provider:M.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:M.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:od(M.id).description}),t.jsx(qt,{status:Tt(M)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:I===M.id?M.authenticated?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void Fe(M.id),children:"Cancel"})]}):M.loginInProgress?t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void Fe(M.id),children:"Cancel"})]}):M.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>ze(M.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>xe(M.id),children:"Login"})}),(I===M.id||M.loginInProgress)&&k[M.id]&&t.jsx(jc,{instructions:k[M.id],"data-testid":`onboarding-login-instructions-${M.id}`}),Me[M.id]==="timeout"&&I!==M.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),Me[M.id]==="failed"&&I!==M.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},M.id)};return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"onboarding-title",children:t.jsxs("div",{className:"modal model-onboarding-modal",ref:Ne,children:[t.jsxs("div",{className:"model-onboarding-header",children:[t.jsxs("h2",{id:"onboarding-title",className:"model-onboarding-title",children:[b==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(Qn,{size:24})," Set Up AI ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),b==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(Es,{size:24})," Connect GitHub ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),b==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(Jd,{size:24})," Set Up Your Project"]}),b==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(Jd,{size:24})," Create Your First Task"]}),b==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx(wn,{size:24})," All Set!"]})]}),b!=="complete"&&t.jsx("button",{className:"modal-close",onClick:Kt,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(Ht,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:Ye.map((M,le)=>{const Se=ft>le,Qe=x.includes(M.key)&&Se,ht=w.includes(M.key)&&!x.includes(M.key)&&Se,bt=Qe||ht;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[le>0&&t.jsx("div",{className:`model-onboarding-step-connector ${le<=ft?"done":""}`}),bt?t.jsxs("button",{className:`model-onboarding-step-indicator ${b===M.key?"active":""} ${Qe?"done":""} ${ht?"skipped":""}`,onClick:()=>v(M.key),"aria-label":`Go back to ${M.label}`,title:`Review ${M.label}`,children:[t.jsx("span",{className:"step-number",children:Qe?t.jsx(wn,{size:14}):ht?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):le+1}),t.jsx("span",{className:"step-label",children:M.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${b===M.key?"active":""} ${Qe?"done":""} ${ht?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:Qe?t.jsx(wn,{size:14}):ht?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):le+1}),t.jsx("span",{className:"step-label",children:M.label})]})]},M.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:oe,children:[b==="ai-setup"&&t.jsxs("div",{className:"model-onboarding-ai-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Fusion uses AI models to plan, write, and review code for you. Connect an AI provider below to get started — you can use a hosted service or enter an API key."}),t.jsx("p",{className:"onboarding-helper-text model-onboarding-primary-helper",children:"You only need one provider to get started."}),!ee&&$.length>0&&(()=>{const M=$.filter(bt=>bt.id!=="github"&&bt.authenticated).length,le=$.filter(bt=>bt.id!=="github").length,Se=Object.keys(be).filter(bt=>!$.find(zt=>zt.id===bt)?.authenticated).length;if(le===0)return null;let Qe="onboarding-provider-summary",ht="";return M>0?(Qe+=" onboarding-provider-summary--connected",ht=`✓ ${M} of ${le} provider${le!==1?"s":""} connected`):Se>0?(Qe+=" onboarding-provider-summary--skipped",ht=`${Se} provider${Se!==1?"s":""} skipped`):(Qe+=" onboarding-provider-summary--none",ht="No providers connected yet"),t.jsx("div",{className:Qe,"data-testid":"provider-summary",children:ht})})(),t.jsx(si,{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."})}),$.length>0&&!$.some(M=>M.authenticated)&&t.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),ee?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(ot,{size:24,className:"animate-spin"}),t.jsx("span",{children:"Loading providers…"})]}):$.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"}),Fn.length>0?t.jsx("div",{className:"model-onboarding-providers",children:Fn.map(M=>on(M))}):t.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),Qt.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:Qt.map(M=>on(M))})]}),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(si,{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."})}),J.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(Zn,{models:J,value:fe,onChange:Oe,placeholder:"Select a default model…",label:"Default model"})}),fe&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",J.find(M=>M.id===fe)?.name??fe]})})]}),t.jsx(si,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:t.jsxs("div",{"data-testid":"onboarding-advanced-provider-settings",children:[yt.length>0?t.jsx("div",{className:"model-onboarding-providers",children:yt.map(M=>on(M))}):t.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."}),Ee.length>0?t.jsx("div",{className:"onboarding-custom-provider-list",children:Ee.map(M=>t.jsxs("div",{className:"onboarding-custom-provider-item",children:[t.jsx(An,{provider:M.id,size:"sm"}),t.jsx("span",{children:M.name||M.id})]},M.id))}):null,Te?t.jsx(PP,{onSave:rt,onCancel:()=>{at(!1),De(void 0)},saving:et,error:Xe}):t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>at(!0),children:"Add custom provider"})]})}),Rn&&t.jsx(si,{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."})}),is&&t.jsx(si,{summary:"What is an API key?",children:t.jsx("p",{className:"onboarding-helper-text",children:"An API key is a secret token that authenticates Fusion with the provider. You can find your key in the provider's dashboard under API settings. Keys are stored securely on your machine."})})]})]}),b==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[mt?t.jsx("p",{className:"model-onboarding-description",children:Nt?"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."}),!mt&&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(si,{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."})}),pt?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(Es,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(At,{status:Lt})})]}),gt&&(I==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>ze("github"),children:"Disconnect"}))]}),(Lt==="not-connected"||Lt==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[I==="github"||wt?t.jsxs("div",{className:"onboarding-github-connect-actions",children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void Fe("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>xe("github"),children:[t.jsx(Es,{size:16}),"Connect"]}),(I==="github"||wt)&&k.github&&t.jsx(jc,{instructions:k.github,"data-testid":"onboarding-login-instructions-github"})]}),Lt==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:Nt?"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."}),Lt==="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:()=>xe("github"),children:"Retry"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Rt,children:"Skip for now"})]})]}),Lt==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),Lt==="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:()=>xe("github"),children:"Connect anyway"})})]}),Lt==="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(An,{provider:"github",size:"lg"})}),Nt?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:Nt?"Continue with gh CLI auth →":"Continue without GitHub →"}),Nt&&(I==="github"||wt?t.jsxs("button",{className:"btn btn-sm",disabled:!0,children:[t.jsx(ot,{size:14,className:"onboarding-spinner"}),"Waiting for OAuth login…"]}):t.jsxs("button",{className:"btn btn-sm",onClick:()=>xe("github"),children:[t.jsx(An,{provider:"github",size:"sm"}),"Connect OAuth (optional)"]}))]}),Nt&&(I==="github"||wt)&&k.github&&t.jsx(jc,{instructions:k.github,"data-testid":"onboarding-login-instructions-github"})]})]}),b==="project-setup"&&t.jsxs("div",{className:"model-onboarding-project-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Choose your first project before creating or importing tasks. You can register an existing local directory or clone a GitHub repository URL through the setup wizard."}),cn?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(si,{summary:"What does project setup do?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Project setup registers a workspace so Fusion knows where to read files, run commands, and track task changes."})})]}),b==="first-task"&&t.jsxs("div",{className:"model-onboarding-first-task",children:[t.jsx("p",{className:"model-onboarding-description",children:"Create your first task to start the board and launch AI execution."}),C&&_n?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx(wn,{size:56,className:"success-icon"}),t.jsx("h3",{className:"onboarding-task-created__title",children:"Your first task is ready!"}),t.jsx("div",{className:"onboarding-task-created__task-id",children:_n.id}),zn&&t.jsx("p",{className:"onboarding-task-created__description",children:zn}),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:ke,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:ut,children:"Go to Dashboard"})]})]}):t.jsxs(t.Fragment,{children:[cn?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"onboarding-first-task-form",children:[t.jsx("label",{className:"onboarding-first-task-form__label",htmlFor:"onboarding-first-task-input",children:"Describe your first task"}),t.jsx("textarea",{id:"onboarding-first-task-input",className:"input onboarding-first-task-form__input","data-testid":"onboarding-first-task-input",value:A,onChange:M=>{S(M.target.value),B(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:Zt,disabled:z,"data-testid":"onboarding-first-task-submit",children:z?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),R&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:R}),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(oI,{items:dn}),cn&&t.jsxs(t.Fragment,{children:[t.jsx(si,{summary:"What happens when I create a task?",children:t.jsx("p",{className:"onboarding-helper-text",children:"A task describes something you want done. Fusion's AI agents will read your description and work on implementing it. You can track progress on the board and review the results."})}),t.jsxs("div",{className:"onboarding-cta-options",children:[t.jsxs("button",{className:"onboarding-cta-card primary",onClick:Nn,disabled:he,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(rn,{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${mt?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:un,disabled:he||!mt,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(Es,{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"}),!mt&&t.jsx("small",{className:"onboarding-cta-note",children:"Requires GitHub connection"})]})]})]}),t.jsxs("p",{className:"onboarding-skip-note",children:["You can create tasks anytime from the board, or use"," ",t.jsx("code",{children:"fn task create"})," in the terminal."]})]})]})]}),b==="complete"&&t.jsxs("div",{className:"model-onboarding-complete",children:[t.jsx(wn,{size:48,className:"success-icon"}),t.jsx("p",{children:"Setup complete! Head to the board to create your first task, or explore the dashboard to see what's available."})]})]}),t.jsxs("div",{className:"model-onboarding-footer",children:[b==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Kt,disabled:he,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:It,children:"Skip setup →"}),t.jsx("button",{className:"btn btn-primary",onClick:Wt,children:"Next →"})]}),b==="github"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Yt,children:"← Back"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:It,children:"Skip GitHub →"}),t.jsx("button",{className:"btn btn-primary",onClick:Wt,children:"Next →"})]}),b==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Yt,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:Wt,disabled:!cn,children:"Next →"})]}),b==="first-task"&&!C&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Yt,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:dt,disabled:he,children:he?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),b==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:mn,children:[t.jsx(wn,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function Ig({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 uI=a.lazy(()=>ln(()=>import("./SetupWizardModal-CLkY9HFL.js"),__vite__mapDeps([12,1,13,14,15,6,7,16])).then(e=>({default:e.SetupWizardModal}))),mI=a.lazy(()=>ln(()=>import("./SettingsModal-1ET586M3.js"),__vite__mapDeps([17,1,18,19,20,2,6,7,21])).then(e=>({default:e.SettingsModal})));function hI(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{ln(()=>import("./SettingsModal-1ET586M3.js"),__vite__mapDeps([17,1,18,19,20,2,6,7,21]))},{timeout:1500})}function pI({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:f,onSettingsClose:p,onReopenOnboarding:g}){const[b,v]=a.useState(null),x=c.detailTask?(()=>{const A=n.find(S=>S.id===c.detailTask?.id);return A?"prompt"in c.detailTask?{...c.detailTask,...A,prompt:c.detailTask.prompt,log:c.detailTask.log}:A:c.detailTask})():null,y=p??c.closeSettings,w=a.useCallback(()=>{c.openNewTask()},[c]),E=a.useCallback(()=>{c.openGitHubImport()},[c]),C=a.useCallback(A=>{v(null),c.closeModelOnboarding(),c.openDetailTask(A)},[c]),j=a.useCallback(async A=>{const S=await d.handleModalCreate(A);return c.modelOnboardingOpen&&v(S),S},[d.handleModalCreate,c.modelOnboardingOpen]);return a.useEffect(()=>{!c.modelOnboardingOpen&&b&&v(null)},[c.modelOnboardingOpen,b]),a.useEffect(()=>{hI()},[]),t.jsxs(t.Fragment,{children:[x&&t.jsx($i,{children:t.jsx(sR,{task:x,projectId:e,tasks:n,onClose:h.handleDetailClose,onOpenDetail:c.openDetailTask,onMoveTask:m.moveTask,onDeleteTask:m.deleteTask,onMergeTask:m.mergeTask,onRetryTask:m.retryTask,onResetTask:m.resetTask,onDuplicateTask:m.duplicateTask,onTaskUpdated:c.updateDetailTask,addToast:r,prAuthAvailable:f.prAuthAvailable,initialTab:c.detailTaskInitialTab})}),c.settingsOpen&&t.jsx($i,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(mI,{onClose:y,addToast:r,initialSection:c.settingsInitialSection,projectId:e,themeMode:f.themeMode,colorTheme:f.colorTheme,onThemeModeChange:f.setThemeMode,onColorThemeChange:f.setColorTheme,dashboardFontScalePct:f.dashboardFontScalePct,onDashboardFontScaleChange:f.setDashboardFontScalePct,onReopenOnboarding:g})})}),t.jsx(aR,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:d.handleGitHubImport,tasks:n,projectId:e}),t.jsx($i,{children:t.jsx(dR,{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($i,{children:t.jsx(yR,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:d.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx(BR,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx(qR,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx(mT,{initialWorkspace:c.fileBrowserWorkspace,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),t.jsx(jT,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e,anchorRect:c.usageAnchorRect}),t.jsx(YT,{isOpen:c.systemStatsOpen,onClose:c.closeSystemStats,projectId:e}),c.schedulesOpen&&t.jsx(UT,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx($i,{children:t.jsx(VT,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:j,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan,onSubtaskBreakdown:c.openSubtaskBreakdown})}),t.jsx(tP,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:i,onOpenTaskDetail:A=>{const S=n.find(z=>z.id===A);S&&c.openDetailTask(S)}}),t.jsx($i,{children:t.jsx(sP,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx($i,{children:t.jsx(fP,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(SP,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(a.Suspense,{fallback:null,children:t.jsx(uI,{onProjectRegistered:u.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(dI,{onComplete:u.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:u.handleAddProject,onOpenNewTask:w,onOpenGitHubImport:E,firstCreatedTask:b,onViewTask:C}),t.jsx(Ig,{toasts:o,onRemove:l})]})}function fI({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 ld=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function gI(e,n){if(n==="ready")return"done";const s=ld.findIndex(r=>r.id===n),i=ld.findIndex(r=>r.id===e);return i<s?"done":i===s?"active":"pending"}function bI({stage:e}){const[n]=a.useState(()=>zv());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:ld.map(s=>{const i=gI(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(ot,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:s.label})]},s.id)})})]})})}const xI=5e3;function vI(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function yI(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++,zo(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 jI(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),f=a.useCallback(async()=>{h.current&&h.current.abort(),h.current=new AbortController;try{c(!0),d(null);const v=await Ck(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(()=>(f(),()=>{h.current&&h.current.abort()}),[f]),a.useEffect(()=>(m.current&&clearInterval(m.current),m.current=setInterval(()=>{f()},xI),()=>{m.current&&(clearInterval(m.current),m.current=null)}),[f]);const p=yI(e,s,i),g=vI(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:g,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:u,refresh:f}}const kI={planning:ri,subtask:Hi,mission_interview:ws,milestone_interview:ws,slice_interview:ws},wI={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function NI({sessions:e,generating:n,needsInput:s,onOpenSession:i,onDismissSession:r}){const{confirm:o}=Ks(),[l,c]=a.useState(!1),[u,d]=a.useState(new Set),m=a.useRef(null),h=a.useRef(new Map),f=a.useRef(null),{activeTabMap:p}=Ia(),g=a.useMemo(()=>Yi(),[]);if(a.useEffect(()=>{if(!l)return;const x=y=>{m.current&&!m.current.contains(y.target)&&c(!1)};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[l]),a.useEffect(()=>{const x=new Set,y=new Map;for(const w of e){const E=p.get(w.id),C=[w.status,w.updatedAt,E?.tabId??w.lockedByTab??"",E?.stale?"stale":"fresh"].join("|"),j=h.current.get(w.id);j&&j!==C&&x.add(w.id),y.set(w.id,C)}if(h.current=y,x.size!==0)return d(x),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{d(new Set),f.current=null},500),()=>{f.current&&(clearTimeout(f.current),f.current=null)}},[p,e]),e.length===0)return null;const b=e.length,v=s>0;return t.jsxs("div",{ref:m,className:"background-tasks-indicator",children:[t.jsxs("button",{className:`background-tasks-indicator__pill${v?" background-tasks-indicator__pill--attention":""}`,onClick:()=>c(x=>!x),title:`${b} background AI task${b!==1?"s":""}${s>0?` (${s} need${s!==1?"":"s"} input)`:""}`,children:[n>0&&t.jsx(ot,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&t.jsx(_c,{size:12}),t.jsxs("span",{children:["AI ",b]})]}),l&&t.jsxs("div",{className:"background-tasks-indicator__popover",children:[t.jsx("div",{className:"background-tasks-indicator__popover-header",children:"Background Tasks"}),t.jsx("div",{className:"background-tasks-indicator__popover-list",children:e.map(x=>{const y=kI[x.type],w=x.status==="generating",E=x.status==="awaiting_input",C=x.status==="error",j=p.get(x.id),A=j?.tabId??x.lockedByTab??null,S=!!(A&&A!==g&&!j?.stale),z=u.has(x.id);return t.jsxs("div",{className:`background-tasks-indicator__item${z?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:z?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:z?"translateY(-1px)":void 0},onClick:async()=>{S&&!await o({title:"Open Active Session",message:"This session is active in another tab. Open anyway?"})||(i(x),c(!1))},children:[C?t.jsx(gs,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--color-error)"}}):t.jsx(y,{size:14,className:"background-tasks-indicator__session-icon"}),t.jsxs("div",{className:"background-tasks-indicator__session-content",children:[t.jsx("div",{className:"background-tasks-indicator__session-title",children:x.title}),t.jsxs("div",{className:"background-tasks-indicator__session-meta",children:[C?"Failed":wI[x.type],w&&" — generating...",E&&!S&&" — needs input",E&&S&&" — active in another tab"]})]}),w&&t.jsx(ot,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),E&&!S&&t.jsx(_c,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),E&&S&&t.jsx(Zo,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),t.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:_=>{_.stopPropagation(),r(x.id)},title:"Dismiss",children:t.jsx(Ht,{size:12})})]},x.id)})})]})]})}function SI(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 CI(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:Cn};case"paused":return{label:"Paused",color:"var(--triage)",icon:qs};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:Qn}}}function EI({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:f,error:p}=jI(e,n,s,u),[g,b]=a.useState(!1),v=a.useMemo(()=>CI(h.executorState),[h.executorState]),x=a.useMemo(()=>SI(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(pd,{size:14}),p]})}):f&&h.runningTaskCount===0?t.jsx("div",{className:"executor-status-bar executor-status-bar--loading",role:"status","aria-label":"Executor status",children:t.jsx("span",{className:"executor-status-bar__loading-text",children:"Loading..."})}):t.jsxs("div",{className:`executor-status-bar ${h.executorState==="running"?"executor-status-bar--running":""}`,role:"status","aria-label":"Executor status",children:[i&&i.length>0&&l&&c&&t.jsxs(t.Fragment,{children:[t.jsx(NI,{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${g?" executor-status-bar__folder-toggle--active":""}`,onClick:()=>b(w=>!w),"aria-label":g?"Hide project directory":"Show project directory","aria-expanded":g,"data-testid":"executor-project-path-toggle",title:g?"Hide project directory":"Show project directory",children:t.jsx(Xn,{size:12,"aria-hidden":"true"})}),g&&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(Ei,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__time",children:x})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx(y,{size:12,style:{color:v.color},"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__state",style:{color:v.color},children:v.label})]})]})}const _I={planning:ri,subtask:Hi,mission_interview:ws,milestone_interview:ws,slice_interview:ws},MI={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},$g="fusion:session-banner-dismissed";function hr(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function AI(){if(typeof window>"u")return new Map;try{const e=window.localStorage.getItem($g);if(!e)return new Map;const n=JSON.parse(e),s=new Map;for(const[i,r]of Object.entries(n)){const o=typeof r=="number"?r:hr(r);s.set(i,o)}return s}catch{return new Map}}function RI(e){if(!(typeof window>"u"))try{const n={};for(const[s,i]of e)n[s]=i;window.localStorage.setItem($g,JSON.stringify(n))}catch{}}const fi=AI();function TI({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:i}){const[r,o]=a.useState(0),l=()=>{RI(fi),o(g=>g+1)};a.useEffect(()=>{if(fi.size===0)return;const g=new Map(e.map(v=>[v.id,v]));let b=!1;for(const[v,x]of fi){const y=g.get(v);if(!y)continue;if(!(y.status==="awaiting_input"||y.status==="error")){fi.delete(v),b=!0;continue}hr(y.updatedAt)>x&&(fi.delete(v),b=!0)}b&&l()},[e]);const c=a.useMemo(()=>e.filter(g=>{if(g.status!=="awaiting_input"&&g.status!=="error")return!1;const b=fi.get(g.id);return b===void 0?!0:hr(g.updatedAt)>b}),[e,r]);if(c.length===0)return null;const u=c.filter(g=>g.status==="awaiting_input").length,d=c.filter(g=>g.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=g=>{fi.set(g.id,Math.max(hr(g.updatedAt),Date.now())),l()},f=g=>{fi.delete(g.id),l(),n(g)},p=()=>{const g=Date.now();for(const b of c)fi.set(b.id,Math.max(hr(b.updatedAt),g));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(gs,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:m})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[t.jsx(Ht,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Dismiss all"})]})]}),t.jsx("div",{className:"session-notification-banner__list",children:c.map(g=>{const b=_I[g.type],v=g.status==="error";return t.jsxs("article",{className:`session-notification-banner__item${v?" session-notification-banner__item--error":""}`,"data-session-type":g.type,"data-session-status":g.status,children:[t.jsxs("div",{className:"session-notification-banner__item-main",children:[v?t.jsx(gs,{size:16,className:"session-notification-banner__type-icon session-notification-banner__type-icon--error","aria-hidden":"true"}):t.jsx(b,{size:16,className:"session-notification-banner__type-icon","aria-hidden":"true"}),t.jsxs("div",{className:"session-notification-banner__text",children:[t.jsx("p",{className:"session-notification-banner__title",title:g.title,children:g.title}),t.jsx("p",{className:"session-notification-banner__meta",children:v?"Failed":MI[g.type]})]})]}),t.jsxs("div",{className:"session-notification-banner__actions",children:[t.jsx("button",{className:"session-notification-banner__resume",onClick:()=>f(g),children:v?"Retry":"Resume"}),t.jsx("button",{className:"session-notification-banner__dismiss",onClick:()=>{h(g),s(g.id)},"aria-label":`Dismiss ${g.title}`,children:t.jsx(Ht,{size:14,"aria-hidden":"true"})})]})]},g.id)})})]})}const Dg="fusion:cli-binary-banner-dismissed";function PI(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Dg)==="1"}catch{return!1}}function II(){if(!(typeof window>"u"))try{window.localStorage.setItem(Dg,"1")}catch{}}function $I({onOpenSettings:e}){const[n,s]=a.useState(null),[i,r]=a.useState(()=>PI()),[o,l]=a.useState(!1),[c,u]=a.useState(null);a.useEffect(()=>{if(i)return;let h=!1;return Iy().then(f=>{h||s(f)}).catch(()=>{}),()=>{h=!0}},[i]);const d=a.useCallback(async()=>{l(!0),u(null);try{const h=await $y();s({binary:h.binary,expectedVersion:h.expectedVersion,state:h.state,install:h.install}),h.installResult.success||u(h.installResult.permissionsHint||h.installResult.stderr||`Install failed (exit ${h.installResult.exitCode??"n/a"})`)}catch(h){u(h instanceof Error?h.message:String(h))}finally{l(!1)}},[]),m=a.useCallback(()=>{II(),r(!0)},[]);return i||!n||n.state==="installed"?null:t.jsxs("div",{className:"cli-binary-banner",role:"status",children:[t.jsxs("div",{className:"cli-binary-banner__body",children:[t.jsx("div",{className:"cli-binary-banner__title",children:"Install the Fusion CLI"}),t.jsxs("div",{className:"cli-binary-banner__text",children:["Get the ",t.jsx("code",{children:"fn"})," and ",t.jsx("code",{children:"fusion"})," commands on your terminal so you can drive Fusion from anywhere. One click below or copy the command into your shell."]}),t.jsxs("div",{className:"cli-binary-banner__actions",children:[t.jsx("button",{type:"button",className:"cli-binary-banner__primary",onClick:()=>void d(),disabled:o,children:o?"Installing…":"Install with npm"}),t.jsx("button",{type:"button",className:"cli-binary-banner__secondary",onClick:e,children:"Open Settings"})]}),c&&t.jsx("div",{className:"cli-binary-banner__error",children:c})]}),t.jsx("button",{type:"button",className:"cli-binary-banner__dismiss","aria-label":"Dismiss",onClick:m,children:t.jsx(Ht,{size:16})})]})}function DI({latestVersion:e,currentVersion:n,onDismiss:s}){return t.jsxs("div",{className:"update-available-banner",role:"status","aria-live":"polite",children:[t.jsxs("p",{className:"update-available-banner__text",children:["Update available: v",e," (current: v",n,"). Run ",t.jsx("code",{children:"npm i -g @runfusion/fusion"})," to update. "," ",t.jsx("a",{className:"update-available-banner__link",href:"https://github.com/Runfusion/Fusion/blob/main/CHANGELOG.md",target:"_blank",rel:"noreferrer",children:"Release notes"})," ","·"," ",t.jsx("a",{className:"update-available-banner__link",href:"https://runfusion.ai",target:"_blank",rel:"noreferrer",children:"Learn more"})]}),t.jsx("button",{type:"button",className:"update-available-banner__dismiss touch-target","aria-label":"Dismiss update notice",onClick:s,children:t.jsx(Ht,{size:16,"aria-hidden":"true"})})]})}function LI({onResume:e}){const n=OP();if(!n)return null;const s=n.completedSteps.length,i=wi.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(cs,{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:()=>{Is("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),e()},children:[t.jsx(Cn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function zI({onOpenSettings:e,onOpenModelOnboarding:n}){const s=Ea(),i=Ag(),[r,o]=a.useState(!0),[l,c]=a.useState(!1),[u,d]=a.useState(!1),[m,h]=a.useState({needsAiProvider:!1,needsDefaultModel:!1,needsGitHub:!1});a.useEffect(()=>{if(!s||i){o(!1);return}let x=!1;return(async()=>{try{o(!0),c(!1);const[w,E]=await Promise.all([Sr(),Ji()]);if(x)return;const C=w.providers??[],j=C.find(R=>R.id==="github"),S=!C.some(R=>R.id!=="github"&&R.authenticated),z=!E.defaultProvider&&!E.defaultModelId,_=j?!j.authenticated:!1;h({needsAiProvider:S,needsDefaultModel:z,needsGitHub:_})}catch{x||c(!0)}finally{x||o(!1)}})(),()=>{x=!0}},[s,i]);const f=a.useCallback(()=>{zP(),d(!0)},[]),p=a.useCallback(()=>{n()},[n]),g=a.useCallback(()=>{e("global-models")},[e]),b=a.useCallback(()=>{e("authentication")},[e]),v=a.useMemo(()=>{const x=[];return m.needsAiProvider&&x.push({id:"ai-provider",title:"Connect AI Provider",description:"Connect an AI provider to enable AI agents for task planning and code generation",actionLabel:"Set Up AI",onAction:p,icon:Qn}),m.needsDefaultModel&&x.push({id:"default-model",title:"Select Default Model",description:"Choose a default AI model for task execution",actionLabel:"Choose Model",onAction:g,icon:bp}),m.needsGitHub&&x.push({id:"github",title:"Connect GitHub",description:"Connect GitHub to import issues and track pull requests",actionLabel:"Connect GitHub",onAction:b,icon:Es}),x},[m.needsAiProvider,m.needsDefaultModel,m.needsGitHub,b,g,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(ri,{size:18,"aria-hidden":!0})}),t.jsxs("div",{className:"post-onboarding-recommendations__content",children:[t.jsx("h2",{className:"post-onboarding-recommendations__title",children:"Recommended Next Steps"}),t.jsx("p",{className:"post-onboarding-recommendations__description",children:"Complete these setup items to get the most out of Fusion."}),t.jsx("ul",{className:"post-onboarding-recommendations__list",children:v.map(x=>{const y=x.icon;return t.jsxs("li",{className:"post-onboarding-recommendations__item",children:[t.jsxs("span",{className:"post-onboarding-recommendations__item-icon","aria-hidden":"true",children:[t.jsx(gs,{size:14,"aria-hidden":!0}),t.jsx(y,{size:14,"aria-hidden":!0})]}),t.jsxs("span",{className:"post-onboarding-recommendations__item-text",children:[t.jsx("strong",{children:x.title}),t.jsx("span",{children:x.description})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-primary",onClick:x.onAction,children:x.actionLabel})]},x.id)})})]})]}),t.jsx("button",{type:"button",className:"post-onboarding-recommendations__dismiss",onClick:f,"aria-label":"Dismiss recommendations",children:t.jsx(Ht,{size:16,"aria-hidden":!0})})]})}function FI({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 wc(e){return e>99?"99+":String(e)}function OI({view:e,onChangeView:n,footerVisible:s,modalOpen:i=!1,keyboardOpen:r=!1,onOpenSettings:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:u,mailboxUnreadCount:d=0,onOpenGitManager:m,onOpenWorkflowSteps:h,onOpenSchedules:f,onOpenScripts:p,onToggleTerminal:g,onOpenFiles:b,onOpenGitHubImport:v,onOpenPlanning:x,onResumePlanning:y,activePlanningSessionCount:w=0,onOpenUsage:E,onRunScript:C,projectId:j,onViewAllProjects:A,showSkillsTab:S,experimentalFeatures:z}){const _=Ta(),[R,B]=a.useState(!1),[K,L]=a.useState(!1),[$,U]=a.useState({}),[G,Y]=a.useState(!1),ee=a.useMemo(()=>Object.entries($).sort(([O],[ne])=>O.localeCompare(ne)),[$]);a.useEffect(()=>{if(!K)return;let O=!1;return Y(!0),Cr(j).then(ne=>{O||U(ne)}).catch(()=>{O||U({})}).finally(()=>{O||Y(!1)}),()=>{O=!0}},[K,j]);const N=a.useCallback(()=>B(!1),[]),I=a.useCallback(O=>{N(),O?.()},[N]);if(a.useEffect(()=>{if(!R)return;const O=ne=>{ne.key==="Escape"&&B(!1)};return document.addEventListener("keydown",O),()=>document.removeEventListener("keydown",O)},[R]),_!=="mobile"||i||r)return null;const T=w>0&&y?y:x,k=!!z?.roadmap,H=!!S,J=!!z?.todoView,ue=k&&(!H||e==="roadmaps"),fe=H&&(!k||e!=="roadmaps"),W=H&&!fe,he=e==="documents"||e==="research"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||e==="todos"&&J||e==="roadmaps"&&!ue||e==="skills"&&!fe;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(qi,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Tasks"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="agents"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-agents",role:"tab","aria-selected":e==="agents",onClick:()=>n("agents"),children:[t.jsx(Sn,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Agents"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="missions"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-missions",role:"tab","aria-selected":e==="missions",onClick:()=>n("missions"),children:[t.jsx(ws,{}),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(Si,{}),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(ba,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),d>0&&t.jsx("span",{className:"mobile-nav-tab-badge",children:wc(d)})]}),fe&&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(Qn,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),ue&&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(Pc,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Roadmaps"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${he?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>B(O=>!O),children:[t.jsx(Mc,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),R&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mobile-more-sheet-backdrop",onClick:N}),t.jsxs("div",{className:"mobile-more-sheet",children:[t.jsx("div",{className:"mobile-more-sheet-handle"}),t.jsx("div",{className:"mobile-more-sheet-title",children:"Navigate"}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-mailbox",onClick:()=>I(u),children:[t.jsx(ba,{}),t.jsx("span",{children:"Mailbox"}),d>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:wc(d)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>I(l),children:[t.jsx(Ds,{}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-system-stats",onClick:()=>I(c),children:[t.jsx(jr,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>I(m),children:[t.jsx(Ws,{}),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:()=>I(g),children:[t.jsx(gi,{}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>L(O=>!O),"aria-expanded":K,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(xn,{size:14,className:`mobile-more-chevron${K?" mobile-more-chevron--open":""}`})})]}),K&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:G?t.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[t.jsx(ot,{className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):ee.length>0?t.jsxs(t.Fragment,{children:[ee.map(([O,ne])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${O}`,onClick:()=>{C&&C(O,ne),N(),L(!1)},children:[t.jsx(Cn,{}),t.jsx("span",{children:O})]},O)),p&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{N(),L(!1),p()},children:[t.jsx(Hs,{}),t.jsx("span",{children:"Manage Scripts…"})]})]}):p&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":"mobile-more-scripts-manage",onClick:()=>{N(),L(!1),p()},children:[t.jsx(Hs,{}),t.jsx("span",{children:"No scripts — add one…"})]})}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-files",onClick:()=>I(b),children:[t.jsx(Xn,{}),t.jsx("span",{children:"Files"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>I(T),children:[t.jsx(ri,{}),t.jsx("span",{children:"Planning"}),w>0&&t.jsx("span",{className:"mobile-more-item-badge",children:wc(w)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>I(h),children:[t.jsx($c,{}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>I(f),children:[t.jsx(Ei,{}),t.jsx("span",{children:"Automation"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>I(v),children:[t.jsx(FI,{}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>I(E),children:[t.jsx(Ds,{}),t.jsx("span",{children:"Usage"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>I(A),children:[t.jsx(gp,{}),t.jsx("span",{children:"Projects"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>I(()=>n("documents")),children:[t.jsx(Bi,{}),t.jsx("span",{children:"Documents"})]}),W&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>I(()=>n("skills")),children:[t.jsx(Qn,{}),t.jsx("span",{children:"Skills"})]}),k&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-roadmaps",onClick:()=>I(()=>n("roadmaps")),children:[t.jsx(Pc,{}),t.jsx("span",{children:"Roadmaps"})]}),z?.researchView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-research",onClick:()=>I(()=>n("research")),children:[t.jsx(Ni,{}),t.jsx("span",{children:"Research"})]}),z?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>I(()=>n("insights")),children:[t.jsx(cs,{}),t.jsx("span",{children:"Insights"})]}),z?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>I(()=>n("memory")),children:[t.jsx(Ro,{}),t.jsx("span",{children:"Memory"})]}),z?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{I(()=>n("dev-server"))},children:[t.jsx(jr,{}),t.jsx("span",{children:"Dev Server"})]}),J&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-todos",onClick:()=>I(()=>n("todos")),children:[t.jsx(jp,{}),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:()=>I(o),children:[t.jsx(pr,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function UI({agents:e,filter:n,highlightedIndex:s,visible:i,onSelect:r,position:o="below"}){const l=a.useMemo(()=>{const c=n.trim().toLowerCase();return c?e.filter(u=>u.name.toLowerCase().includes(c)):e},[e,n]);return i?t.jsx("div",{className:`agent-mention-popup agent-mention-popup--${o}`,"data-testid":"agent-mention-popup",role:"listbox","aria-label":"Agent mention suggestions",children:l.length===0?t.jsx("div",{className:"agent-mention-empty",children:"No agents found"}):l.map((c,u)=>t.jsxs("button",{type:"button",className:`agent-mention-item${u===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${c.id}`,onMouseDown:d=>d.preventDefault(),onClick:()=>r(c),role:"option","aria-selected":u===s,children:[t.jsx(Sn,{size:14,"aria-hidden":"true"}),t.jsx("span",{className:"agent-mention-name",children:c.name}),t.jsx("span",{className:"agent-mention-role",children:c.role})]},c.id))}):null}const vr="__fn_agent__";function Lg(e,n){const s=typeof e=="string"?e.trim():"",i=typeof n=="string"?n.trim():"";return!s||!i?{}:{modelProvider:s,modelId:i}}function ko(e,n,s){const i=typeof e=="string"?e.trim():"",r=Lg(n,s),o=i||(r.modelProvider&&r.modelId?vr:"");return o?{agentId:o,...r}:null}function wo(e,n,s){const i=Lg(n,s),r=i.modelProvider??"",o=i.modelId??"";return`${e}::${r}/${o}`}function BI(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 Gh(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:BI(e.metadata),createdAt:e.createdAt}}function HI(e,n){const[s,i]=a.useState(null),[r,o]=a.useState([]),[l,c]=a.useState(!1),[u,d]=a.useState([]),[m,h]=a.useState(!1),[f,p]=a.useState(!1),[g,b]=a.useState(""),[v,x]=a.useState(""),[y,w]=a.useState([]),[E,C]=a.useState(""),j=a.useRef(null),A=a.useRef(!1),S=a.useRef(null),z=a.useRef(""),_=a.useRef(null),R=a.useRef(""),B=a.useRef(null);a.useEffect(()=>{z.current=E},[E]);const K=a.useCallback(async()=>{c(!0);try{const ue=await yu(e);o(ue.sessions)}catch(ue){console.error("[useQuickChat] Failed to refresh sessions:",ue)}finally{c(!1)}},[e]),L=a.useCallback(async ue=>{const fe={agentId:ue.agentId};return ue.modelProvider&&ue.modelId&&(fe.modelProvider=ue.modelProvider,fe.modelId=ue.modelId),(await Bw(fe,e)).session},[e]),$=a.useCallback(async(ue,fe,W)=>{const he=ko(ue,fe,W);if(!he)return;const O=wo(he.agentId,he.modelProvider,he.modelId);c(!0);try{const{session:ne}=await Uw({agentId:he.agentId,modelProvider:he.modelProvider,modelId:he.modelId},e);if(ne)i(ne),R.current=O;else{const Q=await L(he);i(Q),R.current=O}}catch(ne){console.error("[useQuickChat] Failed to initialize session:",ne),n?.("Failed to initialize chat","error")}finally{c(!1)}},[e,n,L]),U=a.useCallback(async()=>{if(s){h(!0);try{const ue=await ju(s.id,{limit:50},e);d(ue.messages.map(Gh))}catch(ue){console.error("[useQuickChat] Failed to load messages:",ue)}finally{h(!1)}}},[s,e]);a.useEffect(()=>{s?U():d([])},[s,U]);const G=a.useCallback(async()=>{if(s){h(!0);try{const ue=await ju(s.id,{limit:50},e);d(ue.messages.map(Gh))}catch(ue){console.error("[useQuickChat] Failed to reload messages:",ue)}finally{h(!1)}}},[s,e]),Y=a.useCallback(()=>{S.current?.(),S.current=null,z.current="",C(""),b(""),x(""),w([]),p(!1)},[]),ee=a.useCallback(async(ue,fe,W)=>{const he=ko(ue,fe,W);if(!he)return;const O=wo(he.agentId,he.modelProvider,he.modelId);B.current=he;const ne=O===R.current&&s;if(ne||(j.current&&(j.current.close(),j.current=null),Y()),ne){await G();return}i(null),d([]),R.current=O,await $(he.agentId,he.modelProvider,he.modelId)},[s,$,G,Y]),N=a.useCallback(async ue=>{const fe=ko(ue.agentId,ue.modelProvider??void 0,ue.modelId??void 0);fe&&(B.current=fe,R.current=wo(fe.agentId,fe.modelProvider,fe.modelId),j.current&&(j.current.close(),j.current=null),Y(),i(ue))},[Y]),I=a.useCallback(async(ue,fe)=>{await ee(vr,ue,fe)},[ee]),T=a.useCallback(async(ue,fe,W)=>{const O=ko(ue??"",fe,W)??B.current;if(!O)return;B.current=O;const ne=wo(O.agentId,O.modelProvider,O.modelId);j.current&&(j.current.close(),j.current=null),Y(),d([]),i(null),c(!0);try{const Q=await L(O);i(Q),R.current=ne;const ge=await yu(e);o(ge.sessions)}catch(Q){console.error("[useQuickChat] Failed to start a fresh session:",Q),n?.("Failed to start a new chat","error")}finally{c(!1)}},[n,L,e,Y]),k=a.useCallback(()=>{s&&(A.current=!0,S.current?.(),S.current=null,j.current?.close(),j.current=null,Hw(s.id,e).catch(()=>{}),p(!1),b(""),x(""),w([]))},[s,e]),H=a.useCallback(()=>{z.current="",C("")},[]),J=a.useCallback((ue,fe)=>{if(!s||!ue.trim()&&(!fe||fe.length===0))return Promise.resolve();if(f)return fe&&fe.length>0?Promise.reject(new Error("Cannot send attachments while a response is streaming")):(z.current=ue,C(ue),Promise.resolve());const W=new Promise((he,O)=>{_.current={resolve:he,reject:O},A.current=!1,j.current&&(j.current.close(),j.current=null);const Q={id:`temp-${Date.now()}`,sessionId:s.id,role:"user",content:ue,createdAt:new Date().toISOString()};d(Ve=>[...Ve,Q]),b(""),x(""),w([]),p(!0);let ge="",de="",me=[],ie=null,Ee=null;const Ue=()=>{ie=null,b(ge)},Te=()=>{Ee=null,x(de)},at=()=>{ie!==null&&(cancelAnimationFrame(ie),ie=null),Ee!==null&&(cancelAnimationFrame(Ee),Ee=null)};S.current=at;const et={onThinking:Ve=>{de+=Ve,Ee===null&&(Ee=requestAnimationFrame(Te))},onText:Ve=>{ge+=Ve,ie===null&&(ie=requestAnimationFrame(Ue))},onToolStart:Ve=>{me=[...me,{toolName:Ve.toolName,args:Ve.args,isError:!1,status:"running"}],w(me)},onToolEnd:Ve=>{const Xe=[...me];for(let De=Xe.length-1;De>=0;De--){const Be=Xe[De];if(Be?.toolName===Ve.toolName&&Be.status==="running"){Xe[De]={...Be,status:"completed",isError:Ve.isError,result:Ve.result},me=Xe,w(Xe);return}}me=[...Xe,{toolName:Ve.toolName,isError:Ve.isError,result:Ve.result,status:"completed"}],w(me)},onDone:Ve=>{at();const Xe={id:Ve.messageId||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:ge,thinkingOutput:de||void 0,toolCalls:me.length>0?me:void 0,createdAt:new Date().toISOString()};d(Be=>[...Be,Xe]),b(""),x(""),w([]),p(!1),j.current=null,_.current?.resolve(),_.current=null;const De=z.current.trim();De&&(z.current="",C(""),J(De))},onError:Ve=>{if(at(),b(""),x(""),w([]),p(!1),j.current=null,console.error("[useQuickChat] Stream error:",Ve),n?.("Failed to get response","error"),_.current?.reject(new Error(typeof Ve=="string"?Ve:"Failed to get response")),_.current=null,!A.current){const Xe=z.current.trim();Xe&&(z.current="",C(""),J(Xe))}G()}};j.current=qw(s.id,ue,et,fe,e)});return W.catch(()=>{}),W},[s,f,e,n,G]);return a.useEffect(()=>()=>{j.current&&(j.current.close(),j.current=null)},[]),a.useMemo(()=>({activeSession:s,sessions:r,sessionsLoading:l,messages:u,messagesLoading:m,isStreaming:f,streamingText:g,streamingThinking:v,streamingToolCalls:y,pendingMessage:E,sendMessage:J,stopStreaming:k,clearPendingMessage:H,switchSession:ee,selectSession:N,startModelChat:I,startFreshSession:T,refreshSessions:K,loadMessages:U,reloadMessages:G}),[s,r,l,u,m,f,g,v,y,E,J,k,H,ee,N,I,T,K,U,G])}function qI(e,n){const[s,i]=a.useState([]),[r,o]=a.useState(null),[l,c]=a.useState(!1),u=a.useCallback(async f=>{c(!0);try{const p=n?.filterState,g=p&&p!=="all"?{state:p}:void 0,b=n?.showSystemAgents??!1,v=await Ra({...g,...f,includeEphemeral:f?.includeEphemeral??b},e),x=Array.from(new Map(v.map(y=>[y.id,y])).values());i(x)}catch(p){console.error("Failed to load agents:",p)}finally{c(!1)}},[e,n?.filterState,n?.showSystemAgents]),d=a.useCallback(async()=>{try{const f=await yk(e);o(f)}catch(f){console.error("Failed to load agent stats:",f)}},[e]);a.useEffect(()=>{u(),d()},[u,d]),a.useEffect(()=>{const f=e?`?projectId=${encodeURIComponent(e)}`:"",p=()=>{u(),d()};return Gs(`/api/events${f}`,{events:{"agent:created":p,"agent:updated":p,"agent:deleted":p,"agent:stateChanged":p}})},[e,u,d]);const m=n?.showSystemAgents??!1,h=s.filter(f=>f.state!=="active"&&f.state!=="running"?!1:m||!uN(f));return{agents:s,activeAgents:h,stats:r,isLoading:l,loadAgents:u,loadStats:d}}function VI({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=Yw(l.path),d=l.name;return t.jsxs("li",{className:`file-mention-popup-item${c===i?" file-mention-popup-item--selected":""}`,onClick:()=>r(l),onMouseEnter:()=>{},role:"option","aria-selected":c===i,"data-testid":`file-mention-item-${c}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(pp,{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 WI=200;function KI(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,f]=a.useState(!1),[p,g]=a.useState(0),b=a.useRef(null),v=a.useRef(null);a.useEffect(()=>()=>{b.current&&clearTimeout(b.current),v.current?.abort()},[]);const x=a.useCallback((j,A)=>{if(A<0||A>j.length){r(!1);return}const S=z=>/[a-zA-Z0-9/_.-]/.test(z);for(let z=A-1;z>=0;z--){if(j[z]==="#")if(z===0){const _=j.slice(z+1,A);u(z),l(_),g(0),r(!0);return}else{const _=j[z-1];if(/[\s,.;:!?'"()[\]{}]/.test(_)){const R=j.slice(z+1,A);u(z),l(R),g(0),r(!0);return}r(!1);return}if(!S(j[z])){r(!1);return}}r(!1)},[]),y=a.useCallback(()=>{r(!1),l(""),u(-1),m([]),g(0),f(!1)},[]),w=a.useCallback(async j=>{if(!j.trim()){m([]),f(!1);return}v.current?.abort(),v.current=new AbortController;try{f(!0);const A=await Ej(j,s,n);m(A.files),g(0)}catch(A){A.name!=="AbortError"&&m([])}finally{f(!1)}},[s,n]);a.useEffect(()=>{if(i)return b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{w(o)},WI),()=>{b.current&&clearTimeout(b.current)}},[o,i,w]);const E=a.useCallback((j,A)=>{if(!i||c<0)return A;const S=A.slice(0,c),z=A.slice(c+1),_=z.match(/[\s]|$/),R=_?_.index:z.length,B=z.slice(R);return`${S}#${j.path}${B}`},[i,c]),C=a.useCallback((j,A)=>{if(!i||d.length===0)return!1;switch(j.key){case"ArrowDown":return j.preventDefault(),g(S=>Math.min(S+1,d.length-1)),!0;case"ArrowUp":return j.preventDefault(),g(S=>Math.max(S-1,0)),!0;case"Enter":case"Tab":return d[p]?(j.preventDefault(),!0):!1;case"Escape":return j.preventDefault(),y(),!0;default:return!1}},[i,d,p,y]);return{mentionActive:i,files:d,loading:h,mentionQuery:o,selectedIndex:p,setSelectedIndex:g,detectMention:x,selectFile:E,dismissMention:y,handleKeyDown:C}}const GI=30,JI=16,YI=16;function QI(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let _o=null;function zg(){return _o===null&&(_o=window.visualViewport?.height??window.innerHeight),_o}function XI(e){const n=zg();e>n&&(_o=e)}function ZI(e){return e?e instanceof HTMLTextAreaElement?!0:e instanceof HTMLInputElement?!new Set(["checkbox","radio","button","submit","reset","file","range","color","hidden"]).has(e.type):e instanceof HTMLElement&&e.isContentEditable:!1}function e4(){if(typeof window>"u"||!window.visualViewport)return{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0};const e=window.visualViewport,n=ZI(document.activeElement),s=e.offsetTop;n||XI(e.height);const i=Math.max(0,window.innerHeight-e.offsetTop-e.height);if(i>0)return{overlap:i,open:!0,vvHeight:e.height,vvOffsetTop:s};const r=zg(),o=Math.max(0,r-e.offsetTop-e.height);if(o>=GI)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};if(o>=JI&&n)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};const l=Math.max(0,r-e.height);return n&&l>=YI?{overlap:0,open:!0,vvHeight:e.height,vvOffsetTop:s}:{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0}}function Fg({enabled:e=!0}={}){const[n,s]=a.useState(0),[i,r]=a.useState(null),[o,l]=a.useState(0),[c,u]=a.useState(!1);return a.useEffect(()=>{if(!e||!QI()){s(0),r(null),l(0),u(!1);return}const d=window.visualViewport;if(!d){s(0),r(null),l(0),u(!1);return}const m=()=>{const h=e4();s(h.overlap),r(h.vvHeight),l(h.vvOffsetTop),u(h.open)};return m(),d.addEventListener("resize",m),d.addEventListener("scroll",m),document.addEventListener("focusin",m),document.addEventListener("focusout",m),()=>{d.removeEventListener("resize",m),d.removeEventListener("scroll",m),document.removeEventListener("focusin",m),document.removeEventListener("focusout",m),s(0),r(null),l(0),u(!1)}},[e]),{keyboardOverlap:n,viewportHeight:i,viewportOffsetTop:o,keyboardOpen:c}}function t4(e){return`${e.name?.trim()||e.id} (${e.role})`}function No(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 n4(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 Mo(e,n){return e.length<=n?e:`${e.slice(0,n)}…`}function s4(e){if(!e)return null;const n=Object.entries(e);return n.length===0?null:n.map(([s,i])=>{const r=typeof i=="string"?i:(()=>{try{return JSON.stringify(i)}catch{return String(i)}})();return`${s}=${Mo(r,50)}`}).join(", ")}function i4(e){if(e===void 0)return null;if(typeof e=="string")return Mo(e,200);try{return Mo(JSON.stringify(e),200)}catch{return Mo(String(e),200)}}function Og(e,n=!1){if(!e||e.length===0)return null;const s=(f,p)=>{const g=f.status==="running",b=f.status==="completed"&&f.isError,v=s4(f.args),x=i4(f.result),y=g?v:x?`result: ${x}`:v?`args: ${v}`:null,w=n?null:y,E=g?"running":b?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${g?" chat-tool-call--running":""}${b?" chat-tool-call--error":""}`,open:g,children:[t.jsxs("summary",{children:[t.jsx("span",{className:"chat-tool-call-status-dot","aria-hidden":"true"}),t.jsx("span",{className:"chat-tool-call-name",title:f.toolName,children:f.toolName}),w&&t.jsx("span",{className:"chat-tool-call-preview",title:w,children:w}),t.jsx("span",{className:"chat-tool-call-status-text",children:E})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[v&&t.jsxs("div",{className:"chat-tool-call-row",children:[t.jsx("span",{className:"chat-tool-call-label",children:"args"}),t.jsx("span",{className:"chat-tool-call-value",children:v})]}),x&&t.jsxs("div",{className:`chat-tool-call-row${b?" chat-tool-call-row--error":""}`,children:[t.jsx("span",{className:"chat-tool-call-label",children:"result"}),t.jsx("span",{className:"chat-tool-call-value",children:x})]})]})]},`${f.toolName}-${p}`)},i=`chat-tool-calls${n?" chat-tool-calls--compact":""}`;if(e.length===1)return t.jsxs("div",{className:i,"data-testid":"chat-tool-calls",children:[t.jsxs("div",{className:"chat-tool-calls-header",children:[t.jsx(Qd,{size:12,"aria-hidden":"true"}),t.jsx("span",{children:"Tool calls"})]}),s(e[0],0)]});const r=e.filter(f=>f.status==="running").length,o=e.filter(f=>f.status==="completed"&&f.isError).length,l=r>0,c=Array.from(new Set(e.map(f=>f.toolName))),u=c.slice(0,5),d=Math.max(0,c.length-u.length),m=d>0?`${u.join(", ")}, +${d} more`:u.join(", "),h=l?`(${r} running)`:o>0?`(${o} ${o===1?"error":"errors"})`:null;return t.jsx("div",{className:i,"data-testid":"chat-tool-calls",children:t.jsxs("details",{className:`chat-tool-calls-group${n?" chat-tool-calls-group--compact":""}`,"data-testid":"chat-tool-calls-group",open:l,children:[t.jsxs("summary",{className:"chat-tool-calls-group-summary",children:[t.jsx(Qd,{size:12,"aria-hidden":"true"}),t.jsxs("span",{className:"chat-tool-calls-count",children:[e.length," tool calls"]}),t.jsx("span",{className:"chat-tool-calls-names",title:m,children:m}),h&&t.jsx("span",{className:"chat-tool-calls-group-status",children:h})]}),e.map((f,p)=>s(f,p))]})})}const Ug={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 a4(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 So={width:320,height:400},r4=new Set(["image/png","image/jpeg","image/gif","image/webp","text/plain","application/json","text/yaml","text/x-log","text/csv","application/xml","text/markdown"]),o4=[".png",".jpg",".jpeg",".gif",".webp",".txt",".json",".yaml",".yml",".log",".csv",".xml",".md"];function l4(e){return e.type.startsWith("image/")}function c4(e){if(r4.has(e.type))return!0;const n=e.name.toLowerCase();return o4.some(s=>n.endsWith(s))}const da={width:280,height:260},os=768,ua=8;function d4(e,n){const s=a.useCallback(()=>{if(typeof window>"u")return 0;const b=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return b&&parseFloat(b)||0},[]),i=a.useCallback(()=>typeof window<"u"&&window.innerWidth<=768?{x:4,y:4+s()}:{x:24,y:24+s()},[s]),[r,o]=a.useState(()=>{if(typeof window>"u")return i();const b=`fusion-quick-chat-position-${e||"default"}`;try{const v=localStorage.getItem(b);if(v){const x=JSON.parse(v);if(typeof x.x=="number"&&typeof x.y=="number"&&!isNaN(x.x)&&!isNaN(x.y))return x}}catch{}return i()}),[l,c]=a.useState(!1),u=a.useRef(null),d=n??a.useRef(!1),m=a.useCallback(b=>{if(typeof window>"u")return b;const v=48,x=window.innerWidth<=768?4:8,y=window.innerWidth<=768?44:0,w=window.innerWidth>768?s():0,E=window.innerWidth-v-x,C=window.innerHeight-v-x-y-w;return{x:Math.max(x,Math.min(E,b.x)),y:Math.max(x,Math.min(C,b.y))}},[s]),h=a.useCallback(b=>{if(typeof window>"u")return;const v=`fusion-quick-chat-position-${e||"default"}`;try{localStorage.setItem(v,JSON.stringify(b))}catch{}},[e]),f=a.useCallback(b=>{if(b.button!==0&&b.pointerType==="mouse")return;const x=b.target.closest(".quick-chat-fab");x&&(b.preventDefault(),typeof x.setPointerCapture=="function"&&x.setPointerCapture(b.pointerId),u.current={x:r.x,y:r.y,pointerX:b.clientX,pointerY:b.clientY},d.current=!1,c(!0),document.body.style.userSelect="none")},[r]),p=a.useCallback(b=>{if(!u.current||!l)return;const v=b.clientX-u.current.pointerX,x=b.clientY-u.current.pointerY;if((Math.abs(v)>=5||Math.abs(x)>=5)&&(d.current=!0),d.current){const y=u.current.x-v,w=u.current.y-x,E=m({x:y,y:w});o(E)}},[l,m]),g=a.useCallback(b=>{if(!u.current)return;const v=b.target.closest(".quick-chat-fab");if(v&&typeof v.releasePointerCapture=="function"&&v.releasePointerCapture(b.pointerId),c(!1),document.body.style.userSelect="",!d.current){u.current=null;return}h(r),u.current=null,d.current=!1},[r,h]);return{position:r,isDragging:l,handlePointerDown:f,handlePointerMove:p,handlePointerUp:g}}function u4(e,n,s){const i=`fusion:quick-chat-size-${e||"default"}`,r=a.useCallback(()=>typeof window<"u"&&window.innerWidth>os,[]),o=a.useCallback((f,p,g)=>{if(typeof window>"u")return f;const b=Math.max(da.width,window.innerWidth-p-ua),v=Math.max(da.height,window.innerHeight-g-ua);return{width:Math.max(da.width,Math.min(b,f.width)),height:Math.max(da.height,Math.min(v,f.height))}},[]),l=a.useCallback(()=>{if(typeof window>"u"||window.innerWidth<=os)return So;try{const f=localStorage.getItem(i);if(!f)return So;const p=JSON.parse(f);return typeof p.width!="number"||typeof p.height!="number"?So:{width:p.width,height:p.height}}catch{return So}},[i]),[c,u]=a.useState(l),[d,m]=a.useState({right:0,bottom:0});a.useEffect(()=>{if(!r())return;const f={right:n+d.right,bottom:s+d.bottom};u(p=>o(p,f.right,f.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(f=>{if(!r())return;const p=f.currentTarget.dataset.resizeDirection;if(!p)return;f.preventDefault(),f.stopPropagation();const g=f.currentTarget;typeof g.setPointerCapture=="function"&&g.setPointerCapture(f.pointerId);const b={pointerX:f.clientX,pointerY:f.clientY,width:c.width,height:c.height,anchorRight:d.right,anchorBottom:d.bottom};document.body.style.userSelect="none";const v=y=>{const w=y.clientX-b.pointerX,E=y.clientY-b.pointerY;let C=b.width,j=b.height,A=b.anchorRight,S=b.anchorBottom;if(p.includes("w")&&(C=b.width-w),p.includes("e")){const L=w;C=b.width+L,A=b.anchorRight-L}if(p.includes("n")&&(j=b.height-E),p.includes("s")){const L=E;j=b.height+L,S=b.anchorBottom-L}const z=n+A,_=s+S,R=o({width:C,height:j},z,_),B=Math.max(ua-n,Math.min(window.innerWidth-n-da.width-ua,A)),K=Math.max(ua-s,Math.min(window.innerHeight-s-da.height-ua,S));u(R),m({right:B,bottom:K})},x=y=>{typeof g.releasePointerCapture=="function"&&g.releasePointerCapture(y.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",x);try{localStorage.setItem(i,JSON.stringify({width:c.width,height:c.height}))}catch{}};document.addEventListener("pointermove",v),document.addEventListener("pointerup",x)},[d.bottom,d.right,o,s,n,r,c.height,c.width,i]);return{panelSize:c,anchorOffset:d,handleResizeStart:h}}const m4=a.memo(function({message:n,forcePlain:s,mentionAgentsByName:i,onToggleRender:r}){const o=n.role==="user",l=a.useMemo(()=>{if(!o)return null;const u=n.content,d=/@([\w-]+)/g,m=[];let h=0,f=d.exec(u);for(;f;){const[p,g=""]=f,b=f.index;b>h&&m.push(u.slice(h,b));const v=g.replace(/_/g," ").toLowerCase(),x=i.get(v);x?m.push(t.jsxs("span",{className:"chat-mention-chip",children:["@",x.name.replace(/\s+/g,"_")]},`${x.id}-${b}`)):m.push(p),h=b+p.length,f=d.exec(u)}return h<u.length&&m.push(u.slice(h)),m.length===0?u:m},[o,n.content,i]),c=a.useMemo(()=>o?null:s?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:n.content}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(li,{remarkPlugins:[ci],components:Ug,children:n.content})}),[o,s,n.content]);return t.jsxs("div",{className:`quick-chat-panel-message ${o?"quick-chat-panel-message--sent":"quick-chat-panel-message--received"}`,"data-testid":`quick-chat-message-${n.id}`,children:[o?t.jsx("p",{children:l}):t.jsxs(t.Fragment,{children:[c,t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${s?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":s?"Show rendered markdown":"Show plain text",onClick:()=>r(n.id),children:s?t.jsx(md,{size:14}):t.jsx(Ma,{size:14})})]}),Og(n.toolCalls,!0)]})});function h4({projectId:e,addToast:n,showFAB:s=!0,open:i,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:c,onToggleModelFavorite:u}){const{agents:d}=qI(e),[m,h]=a.useState(!1),f=i!==void 0,p=f?i:m,g=f?M=>{r?.(typeof M=="function"?M(p):M)}:h;Fg({enabled:p});const b=Ta(),[v,x]=a.useState("agent"),[y,w]=a.useState(""),[E,C]=a.useState(!1),[j,A]=a.useState("model"),[S,z]=a.useState(""),[_,R]=a.useState(""),[B,K]=a.useState([]),[L,$]=a.useState(!1),[U,G]=a.useState(""),[Y,ee]=a.useState(""),[N,I]=a.useState(""),[T,k]=a.useState(""),[H,J]=a.useState(!1),[ue,fe]=a.useState(0),[W,he]=a.useState(-1),[O,ne]=a.useState(()=>new Set),[Q,ge]=a.useState([]),[de,me]=a.useState(!1),[,ie]=a.useState(!1),[Ee,Ue]=a.useState({top:0,left:0}),Te=KI({projectId:e}),at=a.useCallback(M=>{if(!M||!Te.mentionActive)return;const le=M.getBoundingClientRect();Ue({top:le.top-260,left:le.left+8})},[Te.mentionActive]),et=a.useRef(!1),Ve=a.useRef(!1),Xe=a.useRef(""),De=a.useRef(0),Be=a.useRef(null),oe=a.useRef(0),{position:Ne,isDragging:se,handlePointerDown:Me,handlePointerMove:Le,handlePointerUp:pe}=d4(e,et),Ae=Ne.y+60,{panelSize:Je,anchorOffset:it,handleResizeStart:ye}=u4(e,Ne.x,Ae),ce=typeof window<"u"&&window.innerWidth>os,{activeSession:Re,messages:be,isStreaming:Pe,streamingText:Ye,streamingThinking:$e,streamingToolCalls:ft,sessions:Z,sessionsLoading:re,messagesLoading:je,sendMessage:rt,stopStreaming:te,pendingMessage:Ze,clearPendingMessage:pt,switchSession:gt,selectSession:wt,startModelChat:Et,startFreshSession:mt,refreshSessions:Nt}=HI(e,n),Tt=a.useRef(null),qt=a.useRef(null),Pt=a.useRef(null),At=a.useRef(null),Bt=a.useRef(null),Ft=a.useRef([]),Dt=a.useRef(!1),Mt=a.useRef(!1),St=a.useRef(!1),Wt=a.useRef(null),It=a.useRef(!1);a.useEffect(()=>{if(!p||typeof window>"u"||typeof document>"u"||window.innerWidth>os)return;const M=window.scrollY,le=document.documentElement,Se=document.body,Qe={htmlOverflow:le.style.overflow,bodyOverflow:Se.style.overflow};return window.scrollTo(0,0),le.style.overflow="hidden",Se.style.overflow="hidden",()=>{le.style.overflow=Qe.htmlOverflow,Se.style.overflow=Qe.bodyOverflow,window.scrollTo(0,M)}},[p]),a.useLayoutEffect(()=>{if(!p||typeof window>"u"||!window.visualViewport)return;const M=Tt.current;if(!M)return;const le=window.visualViewport,Se=()=>{It.current||(M.style.setProperty("--vv-height",`${le.height}px`),M.style.setProperty("--vv-offset-top",`${le.offsetTop||0}px`))};return Se(),le.addEventListener("resize",Se),le.addEventListener("scroll",Se),()=>{le.removeEventListener("resize",Se),le.removeEventListener("scroll",Se)}},[p]);const Yt=U||Y,Rt=a.useMemo(()=>No(Yt),[Yt]),xe=a.useMemo(()=>B.find(M=>`${M.provider}/${M.id}`===Yt)??null,[B,Yt]),Fe=a.useMemo(()=>n4(xe,Rt),[xe,Rt]),ct=a.useMemo(()=>v==="model"?Rt?`${vr}::${Rt.modelProvider}/${Rt.modelId}`:"":y?`${y}::`:"",[v,Rt,y]),F=!(v==="agent"?!!y:!!Rt)||!Re;a.useEffect(()=>{if(d.length===0){w(""),x("model");return}d.some(le=>le.id===y)||w(d[0]?.id??"")},[d,y]),a.useEffect(()=>{!p||Ve.current||(Ve.current=!0,$(!0),bs().then(M=>{const le=M.models??[];if(K(le),U||le.length===0)return;const Se=M.defaultProvider,Qe=M.defaultModelId;if(Se&&Qe){const bt=`${Se}/${Qe}`;if(le.some(yn=>`${yn.provider}/${yn.id}`===bt)){ee(bt),G(bt),x("model");return}}ee("");const ht=le[0];ht&&G(`${ht.provider}/${ht.id}`)}).catch(M=>{console.error("[QuickChatFAB] Failed to load models:",M),K([]),ee("")}).finally(()=>{$(!1)}))},[p,d.length,U]),a.useEffect(()=>{p&&Nt()},[p,Nt]),a.useEffect(()=>{if(!p){Xe.current="";return}if(!ct){Xe.current="";return}const M=ct===Xe.current&&!Re&&!re;if(!(ct===Xe.current&&!M)){if(Xe.current=ct,v==="model"&&Rt){Et(Rt.modelProvider,Rt.modelId);return}v==="agent"&&y&&gt(y)}},[p,v,Rt,y,ct,Re,re,Et,gt]),a.useEffect(()=>{p||(J(!1),k(""),he(-1),Ft.current.forEach(M=>{M.previewUrl&&URL.revokeObjectURL(M.previewUrl)}),ge([]))},[p]),a.useEffect(()=>{Ft.current=Q},[Q]),a.useEffect(()=>{if(!p){Dt.current=!1;return}typeof window>"u"||(Dt.current=window.innerWidth<=os)},[p]),a.useEffect(()=>{if(!p||F||!Dt.current)return;const M=At.current;if(!M)return;const le=document.activeElement,Se=le?Tt.current?.contains(le):!1,Qe=le===document.body,ht=le===Wt.current;if(!Se&&!Qe&&!ht){Dt.current=!1;return}if(ht){M.focus({preventScroll:!0}),Dt.current=!1;return}const bt=requestAnimationFrame(()=>{M.focus(),Dt.current=!1});return()=>cancelAnimationFrame(bt)},[p,F]),a.useEffect(()=>()=>{Ft.current.forEach(M=>{M.previewUrl&&URL.revokeObjectURL(M.previewUrl)})},[]);const ve=a.useCallback(()=>{C(!0),A("model"),z(d[0]?.id??""),R(U||Y||"")},[d,Y,U]),ze=a.useMemo(()=>d.find(M=>M.id===y)??null,[d,y]),Oe=a.useMemo(()=>{const M=T.trim().toLowerCase();return M?d.filter(le=>le.name.toLowerCase().includes(M)):d},[d,T]),Ge=a.useMemo(()=>{const M=new Map;for(const le of d)M.set(le.name.toLowerCase(),le);return M},[d]);a.useEffect(()=>{fe(0)},[T,H]),a.useEffect(()=>()=>{Be.current!==null&&(window.clearTimeout(Be.current),Be.current=null)},[]),a.useEffect(()=>{if(!p)return;const M=Se=>{const Qe=Se.target;Tt.current?.contains(Qe)||qt.current?.contains(Qe)||Qe.closest(".model-combobox-dropdown--portal")||g(!1)},le=Se=>{Se.key==="Escape"&&g(!1)};return document.addEventListener("mousedown",M),document.addEventListener("keydown",le),()=>{document.removeEventListener("mousedown",M),document.removeEventListener("keydown",le)}},[p,g]),a.useEffect(()=>{if(!p)return;const M=Pt.current;M&&(M.scrollTop=M.scrollHeight)},[be,Ye,$e,p]);const dt=a.useMemo(()=>Z.map((M,le)=>({id:M.id,label:M.title?.trim()||`Session ${le+1}`})),[Z]),Zt=a.useMemo(()=>v==="agent"?ze?`Message ${ze.name||ze.id}`:"Select an agent to start chatting":Fe?`Message ${Fe}`:"Select a model to start chatting",[v,ze,Fe]),Nn=a.useCallback(M=>{const le=Z.find(Se=>Se.id===M);le&&(le.modelProvider&&le.modelId?(x("model"),G(`${le.modelProvider}/${le.modelId}`)):(x("agent"),w(le.agentId)),wt(le))},[wt,Z]),un=a.useCallback(async()=>{if(!re){if(j==="agent"){if(!S)return;x("agent"),w(S),await mt(S)}else{const M=No(_||U||Y);if(!M)return;x("model"),G(`${M.modelProvider}/${M.modelId}`),await mt(vr,M.modelProvider,M.modelId)}await Nt(),C(!1),A("model")}},[Y,S,j,_,Nt,U,re,mt]),Kt=Ze.length>50?`${Ze.slice(0,50)}…`:Ze,mn=a.useCallback(M=>{if(!M||M.length===0)return;const le=[];for(let Se=0;Se<M.length;Se+=1){const Qe=M[Se];c4(Qe)&&le.push({file:Qe,previewUrl:l4(Qe)?URL.createObjectURL(Qe):""})}le.length>0&&ge(Se=>[...Se,...le])},[]),ke=a.useCallback(M=>{ge(le=>{const Se=le[M];return Se?.previewUrl&&URL.revokeObjectURL(Se.previewUrl),le.filter((Qe,ht)=>ht!==M)})},[]),ut=a.useCallback(M=>{mn(M.clipboardData?.files)},[mn]),Lt=a.useCallback(()=>{if(typeof window>"u"||window.innerWidth>os)return;const M=At.current;!M||M.disabled||M.focus({preventScroll:!0})},[]),En=a.useCallback(()=>{typeof window>"u"||window.innerWidth>os||(St.current=!0)},[]),hn=a.useCallback(async()=>{const M=N.trim(),le=Ft.current;if(!(!M&&le.length===0)&&!F){if(I(""),J(!1),k(""),he(-1),M==="/clear"){te(),pt(),le.forEach(Se=>{Se.previewUrl&&URL.revokeObjectURL(Se.previewUrl)}),ge(Se=>Se.filter(Qe=>!le.includes(Qe)));try{if(v==="model"){const Se=No(Yt);if(!Se)return;await mt(vr,Se.modelProvider,Se.modelId)}else y&&await mt(y)}catch{n("Failed to clear conversation","error")}finally{Lt(),St.current=!1}return}try{await rt(M,le.map(Se=>Se.file)),le.forEach(Se=>{Se.previewUrl&&URL.revokeObjectURL(Se.previewUrl)}),ge(Se=>Se.filter(Qe=>!le.includes(Qe)))}catch{}finally{Lt(),St.current=!1}}},[n,v,pt,Lt,F,N,Yt,y,rt,mt,te]),Rn=a.useCallback(M=>{M.preventDefault(),oe.current+=1,me(!0)},[]),is=a.useCallback(M=>{M.preventDefault(),M.dataTransfer.dropEffect="copy",me(!0)},[]),Dn=a.useCallback(M=>{M.preventDefault(),oe.current=Math.max(0,oe.current-1),oe.current===0&&me(!1)},[]),nn=a.useCallback(M=>{M.preventDefault(),oe.current=0,me(!1),mn(M.dataTransfer?.files)},[mn]),cn=a.useCallback((M,le)=>{const Se=a4(M,le);if(Se){J(!0),k(Se.filter),he(Se.start);return}J(!1),k(""),he(-1)},[]),Hn=a.useCallback(M=>{const le=At.current;if(!le||W<0)return;const Se=le.selectionStart??De.current,Qe=le.selectionEnd??Se,ht=Math.max(Se,Qe),bt=Math.min(W,ht),yn=`${`@${M.name.replace(/\s+/g,"_")}`} `,ts=N.slice(0,bt)+yn+N.slice(ht),as=bt+yn.length;I(ts),J(!1),k(""),fe(0),he(-1),window.requestAnimationFrame(()=>{At.current&&(At.current.focus(),At.current.setSelectionRange(as,as))})},[W,N]),fn=a.useCallback(M=>{const le=M.target.value,Se=M.target.selectionStart??le.length;De.current=Se,I(le),cn(le,Se),Te.detectMention(le,Se),ie(Te.mentionActive),Te.mentionActive&&at(M.target)},[cn,Te,at]),dn=a.useCallback(()=>{if(St.current){window.requestAnimationFrame(()=>{Lt()});return}typeof window<"u"&&window.innerWidth<=os&&Tt.current&&(It.current=!0,Tt.current.style.removeProperty("--vv-height"),Tt.current.style.removeProperty("--vv-offset-top"),window.setTimeout(()=>{It.current=!1},450)),Be.current!==null&&window.clearTimeout(Be.current),Be.current=window.setTimeout(()=>{J(!1),k(""),he(-1),ie(!1),Te.dismissMention(),Be.current=null},120)},[Te,Lt]),_n=a.useCallback(()=>{It.current=!1,Be.current!==null&&(window.clearTimeout(Be.current),Be.current=null)},[]),zn=a.useCallback(M=>{const le=M.currentTarget,Se=le.selectionStart??le.value.length;De.current=Se,cn(le.value,Se),Te.detectMention(le.value,Se),ie(Te.mentionActive),Te.mentionActive&&at(le)},[cn,Te,at]),es=a.useCallback(M=>{M.key!=="Escape"&&zn(M)},[zn]),Fn=a.useCallback(M=>{ne(le=>{const Se=new Set(le);return Se.has(M)?Se.delete(M):Se.add(M),Se})},[]),Qt=a.useCallback((M,le=!1)=>le?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:M}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(li,{remarkPlugins:[ci],components:Ug,children:M})}),[]),yt=a.useCallback(M=>{if(De.current=M.currentTarget.selectionStart??De.current,Te.mentionActive&&Te.files.length>0){if(Te.handleKeyDown(M,N),M.key==="Enter"||M.key==="Tab"){const le=Te.files[Te.selectedIndex];if(le){const Se=Te.selectFile(le,N);I(Se),Te.dismissMention(),ie(!1)}}return}if(H&&M.key==="ArrowDown"){M.preventDefault(),Oe.length>0&&fe(le=>(le+1)%Oe.length);return}if(H&&M.key==="ArrowUp"){M.preventDefault(),Oe.length>0&&fe(le=>le===0?Oe.length-1:le-1);return}if(H&&M.key==="Enter"){M.preventDefault();const le=Oe[ue]??Oe[0];le&&Hn(le);return}if(H&&M.key==="Escape"){M.preventDefault(),M.stopPropagation(),J(!1),k(""),he(-1);return}M.key!=="Enter"||M.shiftKey||(M.preventDefault(),hn())},[H,Oe,ue,Hn,hn,Te,N]),on=a.useCallback(()=>{if(et.current){et.current=!1;return}if(p){g(!1);return}typeof window<"u"&&window.innerWidth<=os&&Wt.current?.focus({preventScroll:!0}),g(!0)},[p,g]);return t.jsxs(t.Fragment,{children:[t.jsx("input",{ref:Wt,type:"text",className:"quick-chat-stealth-input","aria-hidden":"true",tabIndex:-1}),s&&t.jsx("button",{ref:qt,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":se?"true":"false",style:{right:Ne.x,bottom:Ne.y},onPointerDown:Me,onPointerMove:Le,onPointerUp:pe,onClick:on,children:t.jsx(Si,{size:24})}),p&&t.jsxs("div",{className:"quick-chat-panel",ref:Tt,"data-testid":"quick-chat-panel",style:{...ce?{right:Ne.x+it.right,bottom:Ae+it.bottom,width:Je.width,height:Je.height}:{}},children:[ce&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"n","data-testid":"quick-chat-resize-n",onPointerDown:ye,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:ye,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:ye,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:ye,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:ye,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:ye,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:ye,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:ye,role:"separator","aria-label":"Resize panel from bottom-right corner"})]}),t.jsxs("div",{className:"quick-chat-panel-header",children:[t.jsxs("div",{className:"quick-chat-panel-title-wrap",children:[t.jsx("h3",{children:"Quick Chat"}),v==="model"&&Fe&&(()=>{const M=xe?.provider??Rt?.modelProvider??"";return b==="mobile"&&Fe.length>12&&M?t.jsx("span",{className:"quick-chat-model-tag quick-chat-model-tag--icon","data-testid":"quick-chat-model-tag",title:Fe,"aria-label":Fe,children:t.jsx(An,{provider:M,size:"sm"})}):t.jsx("span",{className:"quick-chat-model-tag","data-testid":"quick-chat-model-tag",title:Fe,children:Fe})})()]}),t.jsxs("div",{className:"quick-chat-panel-header-actions",children:[t.jsx("button",{type:"button",className:"btn-icon quick-chat-new-chat-btn","data-testid":"quick-chat-new-thread","aria-label":"Start a new chat",onClick:ve,disabled:re,children:t.jsx(rn,{size:16})}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":"Close quick chat","data-testid":"quick-chat-close",onClick:()=>g(!1),children:t.jsx(Ht,{size:16})})]})]}),t.jsxs("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-session-select",children:[t.jsx("label",{htmlFor:"quick-chat-session-select",className:"visually-hidden",children:"Select session"}),t.jsxs("select",{id:"quick-chat-session-select",value:Re?.id??"",onChange:M=>Nn(M.target.value),"data-testid":"quick-chat-session-dropdown",children:[t.jsx("option",{value:"",disabled:!0,children:re?"Loading sessions…":"Select a session"}),dt.map(M=>t.jsx("option",{value:M.id,children:M.label},M.id))]})]}),E&&t.jsxs("div",{className:"quick-chat-new-session-chooser","data-testid":"quick-chat-new-session-chooser",children:[t.jsxs("div",{className:"quick-chat-inline-mode-toggle","data-testid":"quick-chat-inline-mode-toggle",children:[t.jsx("button",{type:"button",className:`quick-chat-mode-btn${j==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-model",onClick:()=>A("model"),children:"Model"}),t.jsx("button",{type:"button",className:`quick-chat-mode-btn${j==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-agent",onClick:()=>A("agent"),children:"Agent"})]}),j==="agent"?t.jsxs("div",{className:"quick-chat-panel-agent-select",children:[t.jsx("label",{htmlFor:"quick-chat-new-agent-select",className:"visually-hidden",children:"Select agent for new chat"}),t.jsx("select",{id:"quick-chat-new-agent-select",value:S,onChange:M=>z(M.target.value),"data-testid":"quick-chat-new-agent-select",children:d.map(M=>t.jsx("option",{value:M.id,children:t4(M)},M.id))})]}):t.jsx("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-new-model-select",children:t.jsx(Zn,{id:"quick-chat-new-model-select",models:B,value:_,onChange:R,label:"Select model override",placeholder:L?"Loading models…":"Select a model",disabled:L||B.length===0,favoriteProviders:o,favoriteModels:l,onToggleFavorite:c,onToggleModelFavorite:u})}),t.jsxs("div",{className:"quick-chat-new-session-actions",children:[t.jsx("button",{type:"button",className:"btn","data-testid":"quick-chat-new-session-cancel",onClick:()=>{C(!1),A("model")},children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary","data-testid":"quick-chat-new-session-submit",onClick:()=>void un(),disabled:re||(j==="agent"?!S:!No(_||U||Y)),children:"Create"})]})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:Pt,"data-testid":"quick-chat-messages",children:re||je?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):be.length===0&&!Ye&&!$e&&!Pe?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[be.map(M=>t.jsx(m4,{message:M,forcePlain:M.role!=="user"&&O.has(M.id),mentionAgentsByName:Ge,onToggleRender:Fn},M.id)),Pe&&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:[Ye?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:Qt(Ye,O.has("__streaming__"))}),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${O.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":O.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>Fn("__streaming__"),children:O.has("__streaming__")?t.jsx(md,{size:14}):t.jsx(Ma,{size:14})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:"Thinking…"}),Og(ft,!0),$e&&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:$e})]})]})]})}),Q.length>0&&t.jsx("div",{className:"quick-chat-attachment-previews","data-testid":"quick-chat-attachment-previews",children:Q.map((M,le)=>t.jsxs("div",{className:"quick-chat-attachment-preview","data-testid":`quick-chat-attachment-preview-${le}`,children:[M.previewUrl?t.jsx("img",{src:M.previewUrl,alt:M.file.name}):t.jsx("span",{className:"quick-chat-attachment-preview-name",children:M.file.name}),t.jsx("button",{type:"button",className:"quick-chat-attachment-remove","data-testid":`quick-chat-attachment-remove-${le}`,"aria-label":`Remove ${M.file.name}`,onClick:()=>ke(le),children:"×"})]},`${M.file.name}-${le}`))}),t.jsx("div",{className:"quick-chat-panel-input",children:t.jsxs("div",{className:`quick-chat-input-wrapper${de?" quick-chat-input-wrapper--dragover":""}`,onDragEnter:Rn,onDragOver:is,onDragLeave:Dn,onDrop:nn,children:[t.jsx("input",{ref:Bt,type:"file",accept:"image/*,.txt,.json,.yaml,.yml,.log,.csv,.xml,.md",multiple:!0,tabIndex:-1,"aria-hidden":"true",className:"quick-chat-attachment-input",onChange:M=>{mn(M.target.files),M.target.value=""}}),t.jsxs("div",{className:"quick-chat-input-row","data-testid":"quick-chat-input-row",children:[t.jsx("button",{type:"button",className:"btn-icon quick-chat-attach-btn","data-testid":"quick-chat-attach-btn","aria-label":"Attach files",onClick:()=>Bt.current?.click(),children:t.jsx(xp,{size:16})}),t.jsx("input",{ref:At,type:"text",value:N,onChange:fn,onKeyDown:yt,onKeyUp:es,onClick:zn,onBlur:dn,onFocus:_n,onPaste:ut,onTouchStart:M=>{typeof window>"u"||window.innerWidth>os||document.activeElement!==M.currentTarget&&(M.preventDefault(),M.currentTarget.focus({preventScroll:!0}))},placeholder:Zt,disabled:F,"data-testid":"quick-chat-input"}),Pe?t.jsx("button",{type:"button",className:"chat-input-stop quick-chat-send-btn",onPointerDown:M=>{typeof window>"u"||window.innerWidth>os||(M.preventDefault(),M.pointerType&&M.pointerType!=="mouse"&&(Mt.current=!0,te()))},onTouchStart:M=>{typeof window>"u"||window.innerWidth>os||(M.preventDefault(),Mt.current=!0,te())},onMouseDown:M=>{typeof window>"u"||window.innerWidth>os||M.preventDefault()},onClick:()=>{if(Mt.current){Mt.current=!1;return}te()},"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:t.jsx(Cs,{size:14})}):t.jsx("button",{type:"button",className:"quick-chat-send-btn",onPointerDown:M=>{typeof window>"u"||window.innerWidth>os||(M.preventDefault(),M.pointerType&&M.pointerType!=="mouse"&&(Mt.current=!0,En(),Lt(),hn()))},onTouchStart:M=>{typeof window>"u"||window.innerWidth>os||(M.preventDefault(),Mt.current=!0,En(),Lt(),hn())},onMouseDown:M=>{typeof window>"u"||window.innerWidth>os||M.preventDefault()},onClick:()=>{if(Mt.current){Mt.current=!1;return}hn()},disabled:F||N.trim().length===0&&Q.length===0,"data-testid":"quick-chat-send",children:t.jsx(zi,{size:16})})]}),t.jsx(UI,{agents:d,filter:T,highlightedIndex:ue,visible:H,onSelect:Hn,position:"above"}),t.jsx(VI,{visible:Te.mentionActive&&!H,position:Ee,files:Te.files,selectedIndex:Te.selectedIndex,onSelect:M=>{const le=Te.selectFile(M,N);I(le),Te.dismissMention(),ie(!1),At.current?.focus()},loading:Te.loading}),Ze&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${Kt}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:pt,children:"×"})]})]})})]})]})}function ar(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function Jh(e){return e.status==="generating"||e.status==="awaiting_input"}function rr(e){return e==="complete"||e==="error"}function p4(e){const[n,s]=a.useState([]),i=a.useRef(new Map),r=a.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:c,requestSync:u}=Ia(),d=a.useCallback(()=>{xd(e).then(p=>{const g=p.filter(v=>{const x=ar(v.updatedAt),y=r.current.get(v.id);return y===void 0?!0:x<=y?!1:(r.current.delete(v.id),!0)}),b=new Map;for(const v of g)b.set(v.id,ar(v.updatedAt));i.current=b,s(g)}).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 g=!1;const b=new Map(p.map(v=>[v.id,v]));for(const v of o.values()){if(e&&v.projectId&&v.projectId!==e)continue;const x=v.lastEventTimestamp,y=i.current.get(v.sessionId)??0;if(x<y)continue;const w=r.current.get(v.sessionId);if(w!==void 0&&x<=w)continue;if(w!==void 0&&x>w&&!rr(v.status)&&r.current.delete(v.sessionId),rr(v.status)){b.delete(v.sessionId)&&(g=!0),i.current.set(v.sessionId,x);continue}const E=b.get(v.sessionId),C=v.type??E?.type,j=v.title??E?.title;if(!E&&(!C||!j))continue;const A={id:v.sessionId,type:C??"planning",status:v.status,title:j??"AI Session",projectId:v.projectId??E?.projectId??e??null,lockedByTab:v.owningTabId??E?.lockedByTab??null,updatedAt:v.updatedAt??E?.updatedAt??new Date(x).toISOString()},S=b.get(v.sessionId);(!S||S.status!==A.status||S.title!==A.title||S.type!==A.type||S.projectId!==A.projectId||S.lockedByTab!==A.lockedByTab||S.updatedAt!==A.updatedAt)&&(b.set(v.sessionId,A),i.current.set(v.sessionId,x),g=!0)}return g?[...b.values()].sort((v,x)=>ar(x.updatedAt)-ar(v.updatedAt)):p})},[e,o]),a.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",g=v=>{try{const x=JSON.parse(v.data),y=ar(x.updatedAt)||Date.now();s(w=>{const E=i.current.get(x.id)??0;if(y<E)return w;const C=r.current.get(x.id);if(C!==void 0&&y<=C)return w;if(C!==void 0&&y>C&&!rr(x.status)&&r.current.delete(x.id),i.current.set(x.id,y),rr(x.status))return w.filter(A=>A.id!==x.id);const j=w.findIndex(A=>A.id===x.id);if(j>=0){const A=[...w];return A[j]=x,A}return Jh(x)?[x,...w]:w}),l({sessionId:x.id,status:x.status,needsInput:x.status==="awaiting_input",type:x.type,title:x.title,projectId:x.projectId,owningTabId:x.lockedByTab,updatedAt:x.updatedAt,timestamp:y}),rr(x.status)&&c({sessionId:x.id,status:x.status,timestamp:y})}catch{}},b=v=>{try{const x=JSON.parse(v.data),y=Date.now();r.current.set(x,y),i.current.set(x,Math.max(i.current.get(x)??0,y)),c({sessionId:x,status:"complete",timestamp:y}),s(w=>w.filter(E=>E.id!==x))}catch{}};return Gs(`/api/events${p}`,{events:{"ai_session:updated":g,"ai_session:deleted":b},onReconnect:()=>{d()}})},[c,l,e,d]);const m=a.useCallback(async p=>{const b=n.find(w=>w.id===p)?.type,v=Yi();let x=!1;if(b==="planning")try{await _p(p,e,v)}catch(w){x=!0,w instanceof Error&&w.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of planning session ${p} despite lock by another tab`)}else if(b==="subtask")try{await Rp(p,e,v)}catch(w){x=!0,w instanceof Error&&w.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of subtask session ${p} despite lock by another tab`)}else if(b==="mission_interview")try{await $p(p,e,v)}catch(w){x=!0,w instanceof Error&&w.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of mission interview session ${p} despite lock by another tab`)}x&&console.warn(`[useBackgroundSessions] Cancellation failed for session ${p}, attempting delete anyway`);const y=Date.now();r.current.set(p,y),i.current.set(p,Math.max(i.current.get(p)??0,y)),c({sessionId:p,status:"complete",timestamp:y});try{await Dp(p)}catch{}s(w=>w.filter(E=>E.id!==p))},[c,e,n]),h=a.useMemo(()=>n.filter(p=>Jh(p)),[n]),f=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:f,dismissSession:m,refresh:d}}const Go="fusion:hide-session-banners",cd="fusion:session-banner-pref-changed";function f4(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Go)==="1"}catch{return!1}}function g4(e){if(typeof window>"u")return()=>{};const n=i=>{i.key===Go&&e()},s=()=>e();return window.addEventListener("storage",n),window.addEventListener(cd,s),()=>{window.removeEventListener("storage",n),window.removeEventListener(cd,s)}}function v3(e){if(!(typeof window>"u"))try{e?window.localStorage.setItem(Go,"1"):window.localStorage.removeItem(Go),window.dispatchEvent(new Event(cd))}catch{}}function b4(){return a.useSyncExternalStore(g4,f4,()=>!1)}function Yn(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 Yh(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function x4(e,n){return{...n,columnMovedAt:e.columnMovedAt??n.columnMovedAt,executionStartedAt:e.executionStartedAt??n.executionStartedAt,executionCompletedAt:e.executionCompletedAt??n.executionCompletedAt,worktree:n.worktree??e.worktree,modifiedFiles:n.modifiedFiles??e.modifiedFiles,timedExecutionMs:n.timedExecutionMs??e.timedExecutionMs,workflowStepResults:n.workflowStepResults??e.workflowStepResults,tokenUsage:n.tokenUsage??e.tokenUsage,mergeDetails:n.mergeDetails??e.mergeDetails}}function Nc(e,n){if(Yh(n.updatedAt,e.updatedAt)<0)return e;if(e.column===n.column)return x4(e,n);const i=Yh(e.columnMovedAt,n.columnMovedAt);return e.columnMovedAt&&!n.columnMovedAt?{...n,column:e.column,columnMovedAt:e.columnMovedAt}:i>0?{...n,column:e.column,columnMovedAt:e.columnMovedAt}:n}function v4(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),f=a.useRef(s),p=a.useRef(null),g=a.useRef(void 0),b=a.useRef(0),v=a.useRef(n);d.current=r,f.current=s,v.current!==n&&(v.current=n,b.current++);const x=1e3,y=a.useCallback(async Y=>{const ee=++m.current,N=n,I=Y?.searchQueryOverride??f.current,T=Y?.includeArchivedOverride??u.current;try{const k=await ry(void 0,void 0,N,I,T);if(m.current!==ee||n!==N)return;o(k.map(Yn)),g.current=Date.now()}catch{if(m.current!==ee||n!==N)return;if(Y?.clearOnError){o([]);return}o(k=>k)}},[n]);p.current=y;const w=a.useCallback(async()=>{u.current||(c(!0),u.current=!0,await p.current({includeArchivedOverride:!0}))},[]),E=a.useRef(s);a.useEffect(()=>{if(s===void 0&&E.current===void 0)return;E.current=s;const Y=setTimeout(()=>{y({searchQueryOverride:s})},300);return()=>clearTimeout(Y)},[s]),a.useEffect(()=>{y({clearOnError:!0});const Y=()=>{if(document.visibilityState!=="visible")return;const ee=Date.now();ee-h.current<x||(h.current=ee,y())};return document.addEventListener("visibilitychange",Y),()=>{document.removeEventListener("visibilitychange",Y)}},[y]),a.useEffect(()=>{if(i===!1)return;const Y=b.current,ee=n?`?projectId=${encodeURIComponent(n)}`:"",N=()=>b.current!==Y;let I=!0;const T=W=>{if(N())return;const he=Yn(JSON.parse(W.data));if(f.current){p.current({searchQueryOverride:f.current});return}o(O=>{const ne=O.findIndex(me=>me.id===he.id);if(ne===-1)return[...O,he];const Q=O[ne],ge=Nc(Q,he);if(ge===Q)return O;const de=[...O];return de[ne]=ge,de}),g.current=Date.now()},k=W=>{if(N())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:he,to:O}=JSON.parse(W.data),ne=Yn(he);o(Q=>Q.map(ge=>ge.id===ne.id?{...ne,column:O}:ge)),g.current=Date.now()},H=W=>{if(N())return;if(f.current){p.current({searchQueryOverride:f.current});return}const he=Yn(JSON.parse(W.data));o(O=>O.map(ne=>ne.id!==he.id?ne:Nc(ne,he))),g.current=Date.now()},J=W=>{if(N())return;if(f.current){p.current({searchQueryOverride:f.current});return}const he=Yn(JSON.parse(W.data));o(O=>O.filter(ne=>ne.id!==he.id))},ue=W=>{if(N())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:he}=JSON.parse(W.data),O=Yn(he);o(ne=>ne.map(Q=>Q.id===O.id?{...O,column:"done"}:Q))},fe=Gs(`/api/events${ee}`,{events:{"task:created":T,"task:moved":k,"task:updated":H,"task:deleted":J,"task:merged":ue},onReconnect:()=>{I&&(N()||p.current())}});return()=>{I=!1,fe()}},[n,i]);const C=a.useCallback(async Y=>{const ee=Yn(await Np(Y,n));return o(N=>N.some(I=>I.id===ee.id)?N:[...N,ee]),ee},[n]),j=a.useCallback(async(Y,ee)=>Yn(await ly(Y,ee,n)),[n]),A=a.useCallback(async Y=>Yn(await Sp(Y,n)),[n]),S=a.useCallback(async Y=>Yn(await cy(Y,n)),[n]),z=a.useCallback(async Y=>dy(Y,n),[n]),_=a.useCallback(async Y=>Yn(await uy(Y,n)),[n]),R=a.useCallback(async Y=>Yn(await my(Y,n)),[n]),B=a.useCallback(async Y=>{const ee=Yn(await hy(Y,n));return o(N=>N.some(I=>I.id===ee.id)?N:[...N,ee]),ee},[n]),K=a.useCallback(async(Y,ee)=>{const N=d.current.find(T=>T.id===Y),I=N?{...N,...ee,updatedAt:new Date().toISOString()}:void 0;I&&o(T=>T.map(k=>k.id===Y?I:k));try{const T=Yn(await ii(Y,ee,n));return o(k=>k.map(H=>H.id===Y?T:H)),T}catch(T){throw N&&o(k=>k.map(H=>H.id===Y?N:H)),T}},[n]),L=a.useCallback(async Y=>{const ee=Yn(await fy(Y,n));return o(N=>N.map(I=>I.id===Y?ee:I)),ee},[n]),$=a.useCallback(async Y=>{const ee=Yn(await gy(Y,n));return o(N=>N.map(I=>I.id===Y?ee:I)),ee},[n]),U=a.useCallback(async()=>{const ee=(await by(n)).map(Yn);return o(N=>N.map(I=>ee.find(k=>k.id===I.id)||I)),ee},[n]),G=a.useCallback(Y=>{if(Y.length===0)return;if(f.current){p.current({searchQueryOverride:f.current});return}const ee=Y.map(Yn);o(N=>{let I=N;for(const T of ee){const k=I.findIndex(ue=>ue.id===T.id);if(k===-1){I===N&&(I=[...N]),I.push(T);continue}const H=I[k],J=Nc(H,T);J!==H&&(I===N&&(I=[...N]),I[k]=J)}return I}),g.current=Date.now()},[]);return{tasks:r,createTask:C,moveTask:j,pauseTask:A,deleteTask:S,mergeTask:z,retryTask:_,resetTask:R,duplicateTask:B,updateTask:K,archiveTask:L,unarchiveTask:$,archiveAllDone:U,loadArchivedTasks:w,includeArchived:l,ingestCreatedTasks:G,lastFetchTimeMs:g.current}}const y4=5e3,j4=1e3;function k4(){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 f=await fu();n(f)}catch(f){o(f instanceof Error?f.message:"Failed to fetch projects")}},[]);a.useEffect(()=>{let f=!1;async function p(){i(!0);const b=performance.now();try{const v=await fu(),y=`initial fetchProjectsAcrossNodes took ${Math.round(performance.now()-b)}ms (${v.length} projects)`;console.log(`[useProjects] ${y}`),fr("[useProjects]",y),f||(n(v),o(null))}catch(v){const y=`initial fetch failed after ${Math.round(performance.now()-b)}ms: ${v instanceof Error?v.message:String(v)}`;console.warn(`[useProjects] ${y}`),fr("[useProjects]",y),f||o(v instanceof Error?v.message:"Failed to fetch projects")}finally{f||i(!1)}}p();const g=()=>{if(document.visibilityState!=="visible")return;const b=Date.now();b-c.current<j4||(c.current=b,u())};return document.addEventListener("visibilitychange",g),()=>{f=!0,document.removeEventListener("visibilitychange",g)}},[u]),a.useEffect(()=>{if(!s)return l.current=setInterval(()=>{u()},y4),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async f=>{const p=await Sk(f);return n(g=>[...g,p]),p},[]),m=a.useCallback(async(f,p)=>{const g=await Rk(f,p);return n(b=>b.map(v=>v.id===f?g:v)),g},[]),h=a.useCallback(async f=>{await Tp(f),n(p=>p.filter(g=>g.id!==f))},[]);return{projects:e,loading:s,error:r,refresh:u,register:d,update:m,unregister:h}}const w4="kb-dashboard-current-project";function N4(e){return e??"local"}function S4(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=N4(s);a.useEffect(()=>{let p=!1;async function g(){try{const b=await Ji();if(p)return;d.current=b.dashboardCurrentProjectIdByNode??{};const v=d.current[m];if(v){const x=e.find(y=>y.id===v);x&&(r(x),c.current=!0)}if(!v)try{const x=localStorage.getItem(w4);if(x){const y=JSON.parse(x);y?.id&&e.some(E=>E.id===y.id)&&(r(y),c.current=!0,d.current={...d.current,[m]:y.id},await pn({dashboardCurrentProjectIdByNode:d.current}).catch(()=>{}))}}catch{}}catch{}finally{p||l(!1)}}return g(),()=>{p=!0}},[m,e]),a.useEffect(()=>{if(!o){if(i){if(!e.some(b=>b.id===i.id)&&e.length>0){const b=e.find(v=>v.status==="active");r(b||e[0]||null);return}const g={...d.current,[m]:i.id};d.current=g,pn({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}else if(e.length>0&&!u.current){const p=e.find(g=>g.status==="active");p&&r(p)}}},[i,e,o,m]);const h=a.useCallback(p=>{if(u.current=!1,r(p),p){const g={...d.current,[m]:p.id};d.current=g,pn({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}},[m]),f=a.useCallback(()=>{u.current=!0,r(null);const p={...d.current};delete p[m],d.current=p,pn({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[m]);return{currentProject:i,setCurrentProject:h,clearCurrentProject:f,loading:o}}const Bg=a.createContext(null);function C4({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()},[]),Ao.createElement(Bg.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function E4(){const e=a.useContext(Bg);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const Hg="kb-dashboard-theme-mode",qg="kb-dashboard-color-theme",Vg="kb-dashboard-font-scale-pct",dd=100,_4=85,M4=125,Wg=[...cN],ud="theme-data",Sc="theme-data.css";function A4(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.endsWith("/")?e.slice(0,-1)+`/${Sc}`:e.replace(/\/[^/]+$/,`/${Sc}`):`/${Sc}`}const ks=typeof window<"u",R4=ks?a.useLayoutEffect:a.useEffect;function Kg(e){return e==="dark"||e==="light"||e==="system"}function Qh(){if(!ks)return"dark";try{const e=localStorage.getItem(Hg);if(Kg(e))return e}catch{}return"dark"}function Xh(){if(!ks)return"default";try{const e=localStorage.getItem(qg);if(e&&Wg.includes(e))return e}catch{}return"default"}function Zh(e){if(ks)try{localStorage.setItem(Hg,e)}catch{}}function ep(e){if(ks)try{localStorage.setItem(qg,e)}catch{}}function Ar(e){return typeof e!="number"||!Number.isFinite(e)?dd:Math.min(M4,Math.max(_4,Math.round(e)))}function tp(){if(!ks)return dd;try{const e=Number(localStorage.getItem(Vg));return Ar(e)}catch{return dd}}function np(e){if(ks)try{localStorage.setItem(Vg,String(Ar(e)))}catch{}}function T4(e,n){return e==="system"?n?"dark":"light":e}function P4(e,n,s,i){if(!ks)return;const r=T4(e,i);document.documentElement.setAttribute("data-theme",r),document.documentElement.setAttribute("data-color-theme",n),document.documentElement.style.fontSize=`${Ar(s)}%`}function sp(){if(!ks)return;const e=A4(),n=document.getElementById(ud);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=ud,document.head.appendChild(s)}function ip(){if(!ks)return;const e=document.getElementById(ud);e&&e.remove()}function I4(){const[e,n]=a.useState(()=>Qh()),[s,i]=a.useState(()=>Xh()),[r,o]=a.useState(()=>tp()),[l,c]=a.useState(!0),[u,d]=a.useState(()=>ks?window.matchMedia("(prefers-color-scheme: dark)").matches:!0),m=a.useRef(e),h=a.useRef(s),f=a.useRef(r),p=a.useRef(!1),g=a.useRef(!1),b=a.useRef(!1);a.useEffect(()=>{m.current=e},[e]),a.useEffect(()=>{h.current=s},[s]),a.useEffect(()=>{f.current=r},[r]),a.useEffect(()=>{if(!ks||!l)return;let w=!1;return Ji().then(E=>{if(!w&&(Kg(E.themeMode)&&!p.current&&(m.current!==E.themeMode&&(m.current=E.themeMode,n(E.themeMode)),Qh()!==E.themeMode&&Zh(E.themeMode)),E.colorTheme&&Wg.includes(E.colorTheme)&&!g.current&&(h.current!==E.colorTheme&&(h.current=E.colorTheme,i(E.colorTheme)),Xh()!==E.colorTheme&&ep(E.colorTheme)),!b.current)){const C=Ar(E.dashboardFontScalePct);f.current!==C&&(f.current=C,o(C)),tp()!==C&&np(C)}}).catch(E=>{console.warn("[useTheme] Failed to hydrate theme from global settings",E)}).finally(()=>{w||c(!1)}),()=>{w=!0}},[l]),a.useEffect(()=>{if(!ks)return;const w=window.matchMedia("(prefers-color-scheme: dark)"),E=C=>{d(C.matches)};return w.addEventListener("change",E),()=>w.removeEventListener("change",E)},[]),R4(()=>{P4(e,s,r,u)},[e,s,r,u]),a.useEffect(()=>{!ks||l||(s!=="default"?sp():ip())},[s,l]);const v=a.useCallback(w=>{p.current=!0,m.current=w,n(w),Zh(w),pn({themeMode:w}).catch(E=>{console.warn("[useTheme] Failed to persist themeMode to global settings",E)})},[]),x=a.useCallback(w=>{g.current=!0,h.current=w,i(w),ep(w),w!=="default"?sp():ip(),pn({colorTheme:w}).catch(E=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",E)})},[]),y=a.useCallback(w=>{const E=Ar(w);b.current=!0,f.current=E,o(E),np(E),pn({dashboardFontScalePct:E}).catch(C=>{console.warn("[useTheme] Failed to persist dashboardFontScalePct to global settings",C)})},[]);return{themeMode:e,colorTheme:s,dashboardFontScalePct:r,setThemeMode:v,setColorTheme:x,setDashboardFontScalePct:y,isSystemDark:u}}function $4(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),[f,p]=a.useState(null),[g,b]=a.useState(void 0),[v,x]=a.useState(null),[y,w]=a.useState("definition"),[E,C]=a.useState(!1),[j,A]=a.useState(void 0),[S,z]=a.useState(!1),[_,R]=a.useState(!1),[B,K]=a.useState(!1),[L,$]=a.useState(null),[U,G]=a.useState(!1),[Y,ee]=a.useState(!1),[N,I]=a.useState(void 0),[T,k]=a.useState(!1),[H,J]=a.useState("project"),[ue,fe]=a.useState(!1),[W,he]=a.useState(!1),[O,ne]=a.useState(!1),[Q,ge]=a.useState(!1),[de,me]=a.useState(!1),[ie,Ee]=a.useState(!1),[Ue,Te]=a.useState(!1),at=!!(v||E||s||r||m||Y||T||ue||W||O||de||Q||B||U||S||_||ie||Ue),et=a.useCallback(()=>i(!0),[]),Ve=a.useCallback(()=>i(!1),[]),Xe=a.useCallback(()=>o(!0),[]),De=a.useCallback(xe=>{c(xe),o(!0)},[]),Be=a.useCallback(()=>{const xe=n[0];xe&&(d(xe.id),o(!0))},[n]),oe=a.useCallback(xe=>{d(xe),o(!0)},[]),Ne=a.useCallback(()=>{o(!1),c(null),d(void 0)},[]),se=a.useCallback(xe=>{p(xe),h(!0)},[]),Me=a.useCallback(xe=>{b(xe),h(!0)},[]),Le=a.useCallback(()=>{h(!1),p(null),b(void 0)},[]),pe=a.useCallback((xe,Fe="definition")=>{x(xe),w(Fe)},[]),Ae=a.useCallback(xe=>{x(xe),w("changes")},[]),Je=a.useCallback(xe=>{x(Fe=>Fe&&{...Fe,...xe})},[]),it=a.useCallback(()=>{x(null)},[]),ye=a.useCallback(xe=>{A(xe),C(!0)},[]),ce=a.useCallback(()=>{C(!1),A(void 0)},[]),Re=a.useCallback(()=>z(!0),[]),be=a.useCallback(()=>z(!1),[]),Pe=a.useCallback(()=>R(!0),[]),Ye=a.useCallback(()=>R(!1),[]),$e=a.useCallback(xe=>{$(xe??null),K(!0)},[]),ft=a.useCallback(()=>{K(!1),$(null)},[]),Z=a.useCallback(()=>G(!0),[]),re=a.useCallback(()=>G(!1),[]),je=a.useCallback(()=>{ee(xe=>!xe)},[]),rt=a.useCallback(()=>{ee(!1),I(void 0)},[]),te=a.useCallback(()=>k(!0),[]),Ze=a.useCallback(()=>k(!1),[]),pt=a.useCallback(xe=>{J(xe)},[]),gt=a.useCallback(()=>fe(!0),[]),wt=a.useCallback(()=>fe(!1),[]),Et=a.useCallback(()=>he(!0),[]),mt=a.useCallback(()=>he(!1),[]),Nt=a.useCallback(()=>ne(!0),[]),Tt=a.useCallback(()=>ne(!1),[]),qt=a.useCallback(()=>ge(!0),[]),Pt=a.useCallback(()=>ge(!1),[]),At=a.useCallback(()=>me(!0),[]),Bt=a.useCallback(()=>me(!1),[]),Ft=a.useCallback(async(xe,Fe)=>{me(!1),I(Fe),ee(!0)},[]),Dt=a.useCallback(()=>Ee(!0),[]),Mt=a.useCallback(()=>Ee(!1),[]),St=a.useCallback(()=>Te(!0),[]),Wt=a.useCallback(()=>Te(!1),[]),It=a.useCallback((xe,Fe)=>{Fe(`Created ${xe.id} from planning mode`,"success"),o(!1),c(null)},[]),Yt=a.useCallback((xe,Fe)=>{const ct=xe.map(D=>D.id).join(", ");Fe(`Created ${ct} from planning mode`,"success"),o(!1),c(null)},[]),Rt=a.useCallback((xe,Fe)=>{const ct=xe.map(D=>D.id).join(", ");Fe(`Created ${ct} from subtask breakdown`,"success"),h(!1),p(null)},[]);return{newTaskModalOpen:s,isPlanningOpen:r,planningInitialPlan:l,planningResumeSessionId:u,isSubtaskOpen:m,subtaskInitialDescription:f,subtaskResumeSessionId:g,detailTask:v,detailTaskInitialTab:y,settingsOpen:E,settingsInitialSection:j,schedulesOpen:S,githubImportOpen:_,usageOpen:B,usageAnchorRect:L,systemStatsOpen:U,terminalOpen:Y,terminalInitialCommand:N,filesOpen:T,fileBrowserWorkspace:H,activityLogOpen:ue,gitManagerOpen:W,workflowStepsOpen:O,agentsOpen:Q,scriptsOpen:de,setupWizardOpen:ie,modelOnboardingOpen:Ue,anyModalOpen:at,openNewTask:et,closeNewTask:Ve,openPlanning:Xe,openPlanningWithInitialPlan:De,resumePlanning:Be,openPlanningWithSession:oe,closePlanning:Ne,openSubtaskBreakdown:se,openSubtaskWithSession:Me,closeSubtask:Le,openDetailTask:pe,openDetailWithChangesTab:Ae,updateDetailTask:Je,closeDetailTask:it,openSettings:ye,closeSettings:ce,openSchedules:Re,closeSchedules:be,openGitHubImport:Pe,closeGitHubImport:Ye,openUsage:$e,closeUsage:ft,openSystemStats:Z,closeSystemStats:re,toggleTerminal:je,closeTerminal:rt,openFiles:te,closeFiles:Ze,setFileWorkspace:pt,openActivityLog:gt,closeActivityLog:wt,openGitManager:Et,closeGitManager:mt,openWorkflowSteps:Nt,closeWorkflowSteps:Tt,openAgents:qt,closeAgents:Pt,openScripts:At,closeScripts:Bt,runScript:Ft,openSetupWizard:Dt,closeSetupWizard:Mt,openModelOnboarding:St,closeModelOnboarding:Wt,onPlanningTaskCreated:It,onPlanningTasksCreated:Yt,onSubtaskTasksCreated:Rt}}function D4(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,f]=a.useState(void 0),[p,g]=a.useState(!1),[b,v]=a.useState(!1),[x,y]=a.useState(!1),[w,E]=a.useState({}),[C,j]=a.useState(!1),[A,S]=a.useState(!1),[z,_]=a.useState(!1),[R,B]=a.useState(!1),[K,L]=a.useState(!1),$=a.useCallback(async()=>{const[N,I]=await Promise.allSettled([yy(e),nl(e)]);if(N.status==="fulfilled"&&(s(N.value.maxConcurrent),r(N.value.rootDir)),I.status==="fulfilled"){const T=I.value;l(!!T.autoMerge),u(!!T.globalPause),m(!!T.enginePaused),v(!!T.prAuthAvailable),f(T.taskStuckTimeoutMs),g(T.showQuickChatFAB===!0),E(T.experimentalFeatures??{});const k=T.experimentalFeatures??{};j(k.insights===!0),S(k.roadmap===!0),_(k.memoryView===!0),B(k.devServerView===!0||k.devServer===!0),L(k.todoView===!0)}y(!0)},[e]);a.useEffect(()=>{y(!1),E({}),j(!1),S(!1),_(!1),B(!1),L(!1),$()},[$]);const U=a.useCallback(async()=>{const N=!o;l(N);try{await Zr({autoMerge:N},e)}catch{l(!N)}},[o,e]),G=a.useCallback(async()=>{const N=!c;u(N);try{await Zr({globalPause:N,globalPauseReason:N?"manual":void 0},e)}catch{u(!N)}},[c,e]),Y=a.useCallback(async()=>{const N=!d;m(N);try{await Zr({enginePaused:N},e)}catch{m(!N)}},[d,e]),ee=a.useCallback(async()=>{const N=!p;g(N);try{await Zr({showQuickChatFAB:N},e)}catch{g(!N)}},[p,e]);return{maxConcurrent:n,rootDir:i,autoMerge:o,globalPaused:c,enginePaused:d,taskStuckTimeoutMs:h,showQuickChatFAB:p,prAuthAvailable:b,settingsLoaded:x,experimentalFeatures:w,insightsEnabled:C,roadmapEnabled:A,memoryEnabled:z,devServerEnabled:R,todosEnabled:K,toggleAutoMerge:U,toggleGlobalPause:G,toggleEnginePause:Y,toggleShowQuickChatFAB:ee,refresh:$}}function L4(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 f=new URLSearchParams(window.location.search),p=f.get("project"),g=f.get("task");if(!g||i)return;if(p){const v=s.find(x=>x.id===p);if(!v){l(`Project '${p}' not found`,"error");return}r?.id!==v.id&&o(v)}if(d.current)return;d.current=!0,wr(g,p??n).then(v=>{c(v),m.current=g}).catch(()=>{l(`Task ${g} not found`,"error")})},[n,s,i,r,o,l,c]),{handleDetailClose:a.useCallback(()=>{if(m.current){const f=new URLSearchParams(window.location.search);f.delete("task");const p=f.toString();window.history.replaceState(null,"",p?`${window.location.pathname}?${p}`:window.location.pathname),m.current=null}u()},[u])}}function z4(){const[e,n]=a.useState([]),[s,i]=a.useState([]),[r,o]=a.useState([]),l=a.useRef(s),c=a.useRef(r);a.useEffect(()=>{bs().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(g=>g!==m):[m,...h];l.current=p,i(()=>p);try{await pn({favoriteProviders:p,favoriteModels:c.current})}catch(g){throw l.current=h,i(()=>h),g}},[]),d=a.useCallback(async m=>{const h=c.current,p=h.includes(m)?h.filter(g=>g!==m):[m,...h];c.current=p,o(()=>p);try{await pn({favoriteProviders:l.current,favoriteModels:p})}catch(g){throw c.current=h,o(()=>h),g}},[]);return{availableModels:e,favoriteProviders:s,favoriteModels:r,toggleFavoriteProvider:u,toggleFavoriteModel:d}}function F4({projectId:e,setupWizardOpen:n,openModelOnboarding:s,openSettings:i}){const r=a.useRef(!1),o=a.useRef(n);o.current=n,a.useEffect(()=>{if(n||!e||r.current)return;r.current=!0;let l=!1,c=!1;Sr().then(({providers:u})=>{const d=u.some(h=>h.authenticated);if(u.length>0&&!d||u.length>0&&d)return Ji().then(h=>{const f=!!(h.defaultProvider&&h.defaultModelId);(h.modelOnboardingComplete===!1||h.modelOnboardingComplete===void 0)&&(!d||!f)&&!Ea()?l=!0:!d&&!Ea()&&(c=!0)})}).then(()=>{if(o.current){r.current=!1;return}l?(Is("onboarding:auto-triggered",{trigger:"first-run"}),s()):c&&(Is("onboarding:auto-triggered",{trigger:"missing-provider"}),i("authentication"))}).catch(()=>{})},[e,n,s,i])}const ap="kb-update-banner-dismissed";function O4(){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(ap)==="true";d(h);let f=!1;return jy().then(p=>{f||p.disabled||(i(p.updateAvailable===!0),o(typeof p.latestVersion=="string"?p.latestVersion:null),c(typeof p.currentVersion=="string"?p.currentVersion:null))}).catch(()=>{}).finally(()=>{f||n(!1)}),()=>{f=!0}},[]);const m=a.useCallback(()=>{d(!0),sessionStorage.setItem(ap,"true")},[]);return{updateAvailable:s,latestVersion:r,currentVersion:l,loading:e,dismissed:u,dismiss:m}}const U4=["board","list","agents","missions","chat","documents","research","roadmaps","skills","mailbox","insights","memory","devserver","dev-server","todos"];function rp(e){return e!==null&&U4.includes(e)}function B4(e){return e==="devserver"?"dev-server":e}function H4(e){const{projectsLoading:n,projectsError:s,currentProjectLoading:i,currentProject:r,projectsLength:o,setupWizardOpen:l,openSetupWizard:c,themeMode:u,setThemeMode:d}=e,[m,h]=a.useState(()=>{if(typeof window<"u"){const x=window.localStorage.getItem("kb-dashboard-view-mode");if(x==="overview"||x==="project")return x}return"overview"}),[f,p]=a.useState(()=>{const x=Wn("kb-dashboard-task-view");return rp(x)?x:"board"}),g=a.useRef(!1);a.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",m)},[m]),a.useEffect(()=>{const x=Wn("kb-dashboard-task-view",r?.id);if(rp(x)){const y=!g.current&&x==="devserver";p(y?"devserver":B4(x))}else p("board");r?.id&&(g.current=!0)},[r?.id]),a.useEffect(()=>{fs("kb-dashboard-task-view",f,r?.id)},[r?.id,f]),a.useEffect(()=>{n||i||r&&m==="overview"&&h("project")},[n,i,r,m]),a.useEffect(()=>{if(n||i||l||s||o>0||r)return;const x=window.setTimeout(()=>{c()},500);return()=>window.clearTimeout(x)},[n,s,o,i,r,l,c]);const b=a.useCallback(x=>{p(x)},[]),v=a.useCallback(()=>{const x=["dark","light","system"],y=x.indexOf(u),w=x[(y+1)%x.length];d(w)},[u,d]);return{viewMode:m,setViewMode:h,taskView:f,setTaskView:p,handleChangeTaskView:b,handleToggleTheme:v}}function q4(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:f}=e,p=a.useCallback(S=>{n(S),i("project")},[n,i]),g=a.useCallback(()=>{s(),i("overview")},[s,i]),b=a.useCallback(()=>{d()},[d]),v=a.useCallback(()=>{m()},[m]),x=a.useCallback(S=>{h(),n(S),i("project"),u(`Project ${S.name} registered successfully`,"success"),o()},[h,n,i,u,o]),y=a.useCallback(()=>{f()},[f]),w=a.useCallback(async S=>{try{await Mk(S.id),u(`Project ${S.name} paused`,"success"),await o()}catch{u(`Failed to pause project ${S.name}`,"error")}},[u,o]),E=a.useCallback(async S=>{try{await Ak(S.id),u(`Project ${S.name} resumed`,"success"),await o()}catch{u(`Failed to resume project ${S.name}`,"error")}},[u,o]),C=a.useCallback(async S=>{try{await Tp(S.id),u(`Project ${S.name} removed`,"success"),r?.id===S.id&&(s(),i("overview")),await o()}catch{u(`Failed to remove project ${S.name}`,"error")}},[r,s,i,u,o]),j=a.useCallback(async S=>{try{await l(S)}catch{u("Failed to update favorites","error")}},[l,u]),A=a.useCallback(async S=>{try{await c(S)}catch{u("Failed to update model favorites","error")}},[c,u]);return{handleSelectProject:p,handleViewAllProjects:g,handleOpenSettings:b,handleAddProject:v,handleSetupComplete:x,handleModelOnboardingComplete:y,handlePauseProject:w,handleResumeProject:E,handleRemoveProject:C,handleToggleFavorite:j,handleToggleModelFavorite:A}}function V4(e){const{createTask:n,ingestCreatedTasks:s,onPlanningTaskCreated:i,onPlanningTasksCreated:r,onSubtaskTasksCreated:o,addToast:l}=e,c=a.useCallback(async p=>n({...p,column:"triage",source:{sourceType:"dashboard_ui"}}),[n]),u=a.useCallback(async p=>await n({...p,column:"triage",source:{sourceType:"dashboard_ui"}}),[n]),d=a.useCallback(p=>{s([p]),i(p,l)},[l,s,i]),m=a.useCallback(p=>{s(p),r(p,l)},[l,s,r]),h=a.useCallback(p=>{s(p),o(p,l)},[l,s,o]),f=a.useCallback(p=>{l(`Imported ${p.id} from GitHub`,"success")},[l]);return{handleBoardQuickCreate:c,handleModalCreate:u,handlePlanningTaskCreated:d,handlePlanningTasksCreated:m,handleSubtaskTasksCreated:h,handleGitHubImport:f}}async function W4(e){return il("/health",{nodeId:e})}async function K4(e){return il("/projects",{nodeId:e})}async function G4(e,n,s){const i=new URLSearchParams({projectId:n});return s&&s.trim()&&i.set("q",s.trim()),il(`/tasks?${i.toString()}`,{nodeId:e})}async function J4(e,n){return il(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:e})}async function y3(e){return P(`/nodes/${encodeURIComponent(e)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function j3(e){return P(`/nodes/${encodeURIComponent(e)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function k3(e){return P(`/nodes/${encodeURIComponent(e)}/settings/sync-status`)}async function w3(e){return P(`/nodes/${encodeURIComponent(e)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}function Y4(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),[f,p]=a.useState(null),g=a.useRef(null),b=a.useCallback(async()=>{if(!e){o([]),c([]),d(null),h(!1),p(null);return}g.current?.abort();const x=new AbortController;g.current=x,h(!0),p(null);try{const y=[W4(e),K4(e)];s&&(y.push(G4(e,s,i)),y.push(J4(e,s)));const w=await Promise.allSettled(y);if(x.signal.aborted)return;const E=w[0],C=w[1];if(E.status==="rejected"){p(`Failed to fetch node health: ${E.reason}`),h(!1);return}if(d(E.value),C.status==="rejected"){p(`Failed to fetch projects: ${C.reason}`),h(!1);return}if(o(C.value),s&&w[2]){const j=w[2];if(j.status==="rejected"){p(`Failed to fetch tasks: ${j.reason}`),h(!1);return}j.status==="fulfilled"&&c(j.value)}h(!1)}catch(y){x.signal.aborted||(p(y instanceof Error?y.message:"Unknown error"),h(!1))}},[e,s,i]);a.useEffect(()=>(b(),()=>{g.current?.abort()}),[b]);const v=a.useCallback(()=>{b()},[b]);return{projects:r,tasks:l,health:u,loading:m,error:f,refresh:v}}function Q4(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 Gs(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 X4="fusion-dashboard-current-node",Gg=a.createContext(null);function Z4({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 f=await Ji();if(m)return;l.current=f.dashboardCurrentNodeId;const p=f.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const g=localStorage.getItem(X4);if(g){const b=JSON.parse(g);b?.id&&b?.type==="remote"&&(l.current=b.id,await pn({dashboardCurrentNodeId:b.id}).catch(()=>{}))}}catch{}}catch{}finally{m||r(!1)}}return h(),()=>{m=!0}},[]),a.useEffect(()=>{if(!i)if(n&&n.type==="remote"&&n.id){const m=n.id;l.current!==m&&(l.current=m,pn({dashboardCurrentNodeId:m}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,pn({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,i]);const c=a.useCallback(m=>{s(m)},[]),u=a.useCallback(()=>{s(null),l.current=void 0,pn({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),d={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:u};return t.jsx(Gg.Provider,{value:d,children:e})}function e$(){const e=a.useContext(Gg);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}function t$({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&&(Jv(l),window.location.reload())},[n]),o=a.useCallback(()=>{Yv(),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 n$=200,s$=a.lazy(()=>ln(()=>import("./AgentsView-DPezXQ-U.js"),__vite__mapDeps([22,1,3,4,23,14,6,7,24])).then(e=>({default:e.AgentsView}))),i$=a.lazy(()=>ln(()=>import("./DocumentsView-i72qJzwd.js"),__vite__mapDeps([25,1,6,7,26])).then(e=>({default:e.DocumentsView}))),a$=a.lazy(()=>ln(()=>import("./InsightsView-BL5eZJ0a.js"),__vite__mapDeps([27,1,20,6,7,28])).then(e=>({default:e.InsightsView}))),r$=a.lazy(()=>ln(()=>import("./ResearchView-B_QPUEjB.js"),__vite__mapDeps([29,1,6,7,30])).then(e=>({default:e.ResearchView}))),o$=a.lazy(()=>ln(()=>import("./NodesView-D6eJ15zc.js"),__vite__mapDeps([31,1,23,6,7,32])).then(e=>({default:e.NodesView}))),l$=a.lazy(()=>ln(()=>import("./ChatView-5N4-EuhD.js"),__vite__mapDeps([33,1,6,7])).then(e=>({default:e.ChatView}))),c$=a.lazy(()=>ln(()=>import("./RoadmapsView-DBNLaEsK.js"),__vite__mapDeps([34,1,6,7,35])).then(e=>({default:e.RoadmapsView}))),d$=a.lazy(()=>ln(()=>import("./SkillsView-umVjRq6o.js"),__vite__mapDeps([36,1,6,7,37])).then(e=>({default:e.SkillsView}))),u$=a.lazy(()=>ln(()=>import("./MemoryView-pl8Cdg_p.js"),__vite__mapDeps([38,1,18,19,6,7,39])).then(e=>({default:e.MemoryView}))),m$=a.lazy(()=>ln(()=>import("./DevServerView-Daft4YFc.js"),__vite__mapDeps([40,1,6,7,41])).then(e=>({default:e.DevServerView}))),h$=a.lazy(()=>ln(()=>import("./TodoView-CFifSvrD.js"),__vite__mapDeps([42,1,5,6,7,43])).then(e=>({default:e.TodoView})));function p$(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{ln(()=>import("./AgentsView-DPezXQ-U.js"),__vite__mapDeps([22,1,3,4,23,14,6,7,24])),ln(()=>import("./DocumentsView-i72qJzwd.js"),__vite__mapDeps([25,1,6,7,26])),ln(()=>import("./InsightsView-BL5eZJ0a.js"),__vite__mapDeps([27,1,20,6,7,28])),ln(()=>import("./ResearchView-B_QPUEjB.js"),__vite__mapDeps([29,1,6,7,30])),ln(()=>import("./NodesView-D6eJ15zc.js"),__vite__mapDeps([31,1,23,6,7,32])),ln(()=>import("./ChatView-5N4-EuhD.js"),__vite__mapDeps([33,1,6,7])),ln(()=>import("./RoadmapsView-DBNLaEsK.js"),__vite__mapDeps([34,1,6,7,35])),ln(()=>import("./SkillsView-umVjRq6o.js"),__vite__mapDeps([36,1,6,7,37])),ln(()=>import("./MemoryView-pl8Cdg_p.js"),__vite__mapDeps([38,1,18,19,6,7,39])),ln(()=>import("./DevServerView-Daft4YFc.js"),__vite__mapDeps([40,1,6,7,41])),ln(()=>import("./TodoView-CFifSvrD.js"),__vite__mapDeps([42,1,5,6,7,43]))})}const Cc="kb-setup-warning-dismissed";function f$(){const{toasts:e,addToast:n,removeToast:s}=E4(),i=typeof window<"u"&&!!window.electronAPI;a.useEffect(()=>{p$()},[]);const{projects:r,loading:o,error:l,refresh:c}=k4(),{nodes:u}=ol(),{currentNode:d,currentNodeId:m,isRemote:h,setCurrentNode:f,clearCurrentNode:p}=e$(),{currentProject:g,setCurrentProject:b,clearCurrentProject:v,loading:x}=S4(r,{nodeId:m}),{hasAiProvider:y,hasGithub:w,loading:E,hasWarnings:C}=_g(g?.id),{updateAvailable:j,latestVersion:A,currentVersion:S,dismissed:z,dismiss:_}=O4();a.useEffect(()=>{if(m&&!d&&u.length>0){const nt=u.find($t=>$t.id===m);if(nt){f(nt);return}}m&&u.length>0&&(u.some($t=>$t.id===m)||p())},[m,d,u,f,p]);const[R,B]=a.useState(""),K=Y4(m,{projectId:g?.id,searchQuery:R||void 0});Q4(m);const L=h&&K.projects.length>0?K.projects:r,{themeMode:$,colorTheme:U,dashboardFontScalePct:G,setThemeMode:Y,setColorTheme:ee,setDashboardFontScalePct:N}=I4(),{sessions:I,generating:T,needsInput:k,planningSessions:H,dismissSession:J}=p4(g?.id),ue=I.filter(nt=>nt.status==="awaiting_input"||nt.status==="error"),fe=b4(),W=$4({projectId:g?.id,planningSessions:H}),{viewMode:he,setViewMode:O,taskView:ne,handleChangeTaskView:Q}=H4({projectsLoading:o,projectsError:l,currentProjectLoading:x,currentProject:g,projectsLength:r.length,setupWizardOpen:W.setupWizardOpen,openSetupWizard:W.openSetupWizard,themeMode:$,setThemeMode:Y}),ge=a.useCallback(nt=>{nt==="missions"&&(wt(void 0),mt(void 0),Tt(void 0)),Q(nt)},[Q]),de=ne==="board"||ne==="list",{tasks:me,createTask:ie,moveTask:Ee,pauseTask:Ue,deleteTask:Te,mergeTask:at,retryTask:et,resetTask:Ve,updateTask:Xe,duplicateTask:De,archiveTask:Be,unarchiveTask:oe,archiveAllDone:Ne,loadArchivedTasks:se,ingestCreatedTasks:Me,lastFetchTimeMs:Le}=v4({...g?{projectId:g.id}:{},searchQuery:R||void 0,sseEnabled:de}),[pe,Ae]=a.useState(!1),[Je,it]=a.useState(0),ye=a.useRef(performance.now()),ce=a.useRef(!1),Re=a.useRef(!1),be=a.useMemo(()=>o?"projects":x?"project":"tasks",[o,x]);a.useEffect(()=>{if(!o&&!ce.current){ce.current=!0;const nt=`projects loaded at ${Math.round(performance.now()-ye.current)}ms from mount`;console.log(`[App] ${nt}`),fr("[App]",nt)}if(!x&&!Re.current){Re.current=!0;const nt=`current-project resolved at ${Math.round(performance.now()-ye.current)}ms from mount`;console.log(`[App] ${nt}`),fr("[App]",nt)}},[o,x]),a.useEffect(()=>{if(pe||o||x)return;const nt=performance.now(),$t=window.setTimeout(()=>{const Tn=`dashboard ready at ${Math.round(performance.now()-ye.current)}ms from mount (settle delay=${Math.round(performance.now()-nt)}ms)`;console.log(`[App] ${Tn}`),fr("[App]",Tn),Ae(!0)},n$);return()=>{window.clearTimeout($t)}},[pe,o,x]);const Ye=Ta()==="mobile",{keyboardOpen:$e}=Fg({enabled:Ye}),ft=Ye&&$e,[Z,re]=a.useState(0),je=a.useCallback(()=>{Lp(g?.id).then(nt=>{re(nt.unreadCount)}).catch(nt=>{console.warn("[App] Failed to fetch mailbox unread count:",nt)})},[g?.id]);a.useEffect(()=>{je();const nt=new URLSearchParams;g?.id&&nt.set("projectId",g.id);const $t=nt.size>0?`?${nt.toString()}`:"";return Gs(`/api/events${$t}`,{events:{"message:sent":je,"message:received":je,"message:read":je,"message:deleted":je}})},[g?.id,je]);const[rt,te]=a.useState(!1),[Ze,pt]=a.useState(!1),[gt,wt]=a.useState(void 0),[Et,mt]=a.useState(void 0),[Nt,Tt]=a.useState(void 0),[qt,Pt]=a.useState(!1),[At,Bt]=a.useState(!1),[Ft,Dt]=a.useState(()=>Wn(Cc,g?.id)==="true");a.useEffect(()=>{Dt(Wn(Cc,g?.id)==="true")},[g?.id]),a.useEffect(()=>{const nt=()=>{Bt(!0)};return window.addEventListener(zc,nt),()=>{window.removeEventListener(zc,nt)}},[]);const Mt=a.useCallback(()=>{fs(Cc,"true",g?.id),Dt(!0)},[g?.id]),{maxConcurrent:St,autoMerge:Wt,globalPaused:It,enginePaused:Yt,taskStuckTimeoutMs:Rt,showQuickChatFAB:xe,prAuthAvailable:Fe,settingsLoaded:ct,experimentalFeatures:D,insightsEnabled:F,roadmapEnabled:ve,memoryEnabled:ze,devServerEnabled:Oe,todosEnabled:Ge,toggleAutoMerge:dt,toggleGlobalPause:Zt,toggleEnginePause:Nn,refresh:un}=D4(g?.id),Kt=D.skillsView===!0,mn=D.nodesView===!0,ke=D.researchView===!0,ut=D.agentOnboarding===!0,Lt=!0;a.useEffect(()=>{ct&&(ne==="skills"&&!Kt&&Q("board"),ne==="insights"&&!F&&Q("board"),ne==="roadmaps"&&!ve&&Q("board"),ne==="memory"&&!ze&&Q("board"),(ne==="devserver"||ne==="dev-server")&&!Oe&&Q("board"),ne==="todos"&&!Ge&&Q("board"),ne==="research"&&!ke&&Q("board"))},[ne,ct,Kt,F,ve,Q,Lt,ze,Oe,Ge,ke]),a.useEffect(()=>{rt&&!mn&&te(!1)},[rt,mn]);const{availableModels:En,favoriteProviders:hn,favoriteModels:Rn,toggleFavoriteProvider:is,toggleFavoriteModel:Dn}=z4();F4({projectId:g?.id,setupWizardOpen:W.setupWizardOpen,openModelOnboarding:W.openModelOnboarding,openSettings:W.openSettings});const{handleSelectProject:nn,handleViewAllProjects:cn,handleOpenSettings:Hn,handleAddProject:fn,handleSetupComplete:dn,handleModelOnboardingComplete:_n,handlePauseProject:zn,handleResumeProject:es,handleRemoveProject:Fn,handleToggleFavorite:Qt,handleToggleModelFavorite:yt}=q4({setCurrentProject:b,clearCurrentProject:v,setViewMode:O,currentProject:g,refreshProjects:c,toggleFavoriteProvider:is,toggleFavoriteModel:Dn,addToast:n,openSettings:W.openSettings,openSetupWizard:W.openSetupWizard,closeSetupWizard:W.closeSetupWizard,closeModelOnboarding:W.closeModelOnboarding}),{handleDetailClose:on}=L4({projectId:g?.id,projects:r,projectsLoading:o,currentProject:g,setCurrentProject:b,addToast:n,openTaskDetail:W.openDetailTask,closeTaskDetail:W.closeDetailTask}),{handleBoardQuickCreate:M,handleModalCreate:le,handlePlanningTaskCreated:Se,handlePlanningTasksCreated:Qe,handleSubtaskTasksCreated:ht,handleGitHubImport:bt}=V4({createTask:ie,ingestCreatedTasks:Me,onPlanningTaskCreated:W.onPlanningTaskCreated,onPlanningTasksCreated:W.onPlanningTasksCreated,onSubtaskTasksCreated:W.onSubtaskTasksCreated,addToast:n}),zt=a.useCallback((nt,$t)=>{if($t==="changes"){W.openDetailWithChangesTab(nt);return}W.openDetailTask(nt,$t)},[W]),yn=a.useCallback(async nt=>{try{const $t=await wr(nt,g?.id);W.openDetailTask($t,"logs")}catch($t){n(`Failed to open task logs: ${$t.message}`,"error")}},[W,g?.id,n]),ts=a.useCallback(()=>{mn&&te(nt=>!nt)},[mn]),as=a.useCallback(()=>{W.setFileWorkspace("project"),W.openFiles()},[W]),Js=a.useCallback(async()=>{pt(!0);try{await c()}finally{pt(!1)}},[c]),ae=a.useCallback(nt=>{mt(nt),wt(void 0),Q("missions")},[Q]),_e=a.useCallback(nt=>{nt.type==="planning"?W.openPlanningWithSession(nt.id):nt.type==="subtask"?W.openSubtaskWithSession(nt.id):nt.type==="mission_interview"?(mt(void 0),wt(nt.id),Tt(void 0),Q("missions")):(nt.type==="milestone_interview"||nt.type==="slice_interview")&&(wt(void 0),mt(void 0),Tt(nt.id),Q("missions"))},[Q,W]),tt=a.useCallback(()=>{},[]),jt=a.useCallback(()=>{},[]),kt=!o&&!x&&r.length===0&&!g&&!!l,gn=()=>kt?t.jsx(fI,{errorMessage:l??"Failed to fetch projects",isRetrying:Ze,onRetry:Js}):rt?t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(rs,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(o$,{addToast:n,onClose:()=>te(!1)})})})}):he==="overview"?t.jsx(rs,{children:t.jsx(U1,{projects:r,loading:o,onSelectProject:nn,onAddProject:fn,onPauseProject:zn,onResumeProject:es,onRemoveProject:Fn,nodes:u})}):ne==="skills"?!ct||!Kt?null:t.jsx(rs,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(d$,{addToast:n,projectId:g?.id,onClose:()=>Q("board")})})}):ne==="chat"?t.jsx(rs,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(l$,{addToast:n,projectId:g?.id})})}):ne==="mailbox"?t.jsx(rs,{children:t.jsx(PS,{projectId:g?.id,addToast:n,onUnreadCountChange:re})}):ne==="roadmaps"?!ct||!ve?null:t.jsx(rs,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(c$,{addToast:n,projectId:g?.id})})}):ne==="missions"?t.jsx(rs,{children:t.jsx(MS,{isInline:!0,isOpen:!0,onClose:()=>{mt(void 0),wt(void 0),Tt(void 0),Q("board")},addToast:n,projectId:g?.id,onSelectTask:nt=>{const $t=me.find(Tn=>Tn.id===nt);$t&&W.openDetailTask($t)},availableTasks:me.map(nt=>({id:nt.id,title:nt.title})),resumeSessionId:gt,targetMissionId:Et,milestoneSliceResumeSessionId:Nt,onMilestoneSliceResumeFetchError:()=>Tt(void 0)})}):ne==="agents"&&Lt?t.jsx(rs,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(s$,{addToast:n,projectId:g?.id,onOpenTaskLogs:yn,agentOnboardingEnabled:ut})})}):ne==="documents"?t.jsx(rs,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(i$,{projectId:g?.id,addToast:n,onOpenDetail:W.openDetailTask})})}):ne==="insights"?!ct||!F?null:t.jsx(rs,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(a$,{projectId:g?.id,addToast:n,onClose:()=>Q("board")})})}):ne==="research"?!ct||!ke?null:t.jsx(rs,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(r$,{projectId:g?.id,addToast:n,onOpenSettings:nt=>W.openSettings(nt),readinessVersion:Je})})}):ne==="memory"?!ct||!ze?null:t.jsx(rs,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(u$,{addToast:n,projectId:g?.id})})}):ne==="todos"?!ct||!Ge?null:t.jsx(rs,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(h$,{addToast:n,projectId:g?.id,onPlanningMode:W.openPlanningWithInitialPlan})})}):ne==="devserver"||ne==="dev-server"?!ct||!Oe?null:t.jsx(rs,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(m$,{addToast:n,projectId:g?.id})})}):ne==="board"?t.jsx(rs,{children:t.jsx(E1,{tasks:h&&K.tasks.length>0?K.tasks:me,projectId:g?.id,maxConcurrent:St,onMoveTask:Ee,onPauseTask:Ue,onOpenDetail:W.openDetailTask,addToast:n,onQuickCreate:M,onNewTask:W.openNewTask,onPlanningMode:W.openPlanningWithInitialPlan,onSubtaskBreakdown:W.openSubtaskBreakdown,autoMerge:Wt,onToggleAutoMerge:dt,globalPaused:It,onUpdateTask:Xe,onRetryTask:et,onArchiveTask:Be,onUnarchiveTask:oe,onDeleteTask:Te,onArchiveAllDone:Ne,onLoadArchivedTasks:se,searchQuery:R,availableModels:En,onOpenDetailWithTab:zt,favoriteProviders:hn,favoriteModels:Rn,onToggleFavorite:Qt,onToggleModelFavorite:yt,taskStuckTimeoutMs:Rt,onOpenMission:ae,lastFetchTimeMs:Le})}):t.jsx(rs,{children:t.jsx(R1,{tasks:h&&K.tasks.length>0?K.tasks:me,projectId:g?.id,onMoveTask:Ee,onRetryTask:et,onOpenDetail:W.openDetailTask,addToast:n,globalPaused:It,onNewTask:W.openNewTask,onQuickCreate:M,onPlanningMode:W.openPlanningWithInitialPlan,onSubtaskBreakdown:W.openSubtaskBreakdown,availableModels:En,favoriteProviders:hn,favoriteModels:Rn,onToggleFavorite:Qt,onToggleModelFavorite:yt,taskStuckTimeoutMs:Rt,searchQuery:R,lastFetchTimeMs:Le})});if(!pe)return t.jsxs(t.Fragment,{children:[t.jsx(bI,{stage:be}),t.jsx(Ig,{toasts:e,onRemove:s})]});const sn=!W.modelOnboardingOpen&&FP(),en=!W.modelOnboardingOpen&&!sn&&Ea()&&!Ag();return t.jsxs(t.Fragment,{children:[t.jsx(eN,{isElectron:i,onOpenSettings:Hn,onOpenGitHubImport:W.openGitHubImport,onOpenPlanning:W.openPlanning,onResumePlanning:W.resumePlanning,activePlanningSessionCount:H.length,onOpenUsage:W.openUsage,onOpenActivityLog:W.openActivityLog,onOpenSystemStats:W.openSystemStats,onOpenMailbox:()=>ge("mailbox"),mailboxUnreadCount:Z,onOpenSchedules:W.openSchedules,onOpenGitManager:W.openGitManager,onOpenNodes:ts,showNodesButton:mn,onOpenWorkflowSteps:W.openWorkflowSteps,onOpenScripts:W.openScripts,onRunScript:W.runScript,onToggleTerminal:W.toggleTerminal,onOpenFiles:W.openFiles,filesOpen:W.filesOpen,globalPaused:It,enginePaused:Yt,onToggleGlobalPause:Zt,onToggleEnginePause:Nn,view:ne,onChangeView:he==="project"&&g?ge:void 0,showSkillsTab:Kt,showAgentsTab:Lt,searchQuery:R,onSearchChange:B,projects:L,currentProject:g,onSelectProject:nn,onViewAllProjects:cn,projectId:g?.id,mobileNavEnabled:Ye,availableNodes:u,currentNode:d,onSelectNode:nt=>{nt===null?p():f(nt)},isRemote:h,experimentalFeatures:{insights:F,roadmap:ve,memoryView:ze,devServer:Oe,devServerView:Oe,todoView:Ge,researchView:ke}}),he==="project"&&g&&!rt&&ne!=="missions"&&!W.isPlanningOpen&&!fe&&t.jsx(TI,{sessions:ue,onResumeSession:_e,onDismissSession:tt,onDismissAll:jt}),he==="project"&&g&&t.jsx($I,{onOpenSettings:()=>W.openSettings("general")}),he==="project"&&g&&sn&&t.jsx(LI,{onResume:W.openModelOnboarding}),he==="project"&&g&&en&&t.jsx(zI,{onOpenModelOnboarding:W.openModelOnboarding,onOpenSettings:nt=>W.openSettings(nt)}),he==="project"&&g&&j&&A&&S&&!z&&t.jsx(DI,{latestVersion:A,currentVersion:S,onDismiss:_}),he==="project"&&g&&!E&&C&&!Ft&&t.jsx(Mg,{hasAiProvider:y,hasGithub:w,onDismiss:Mt}),t.jsx("div",{className:`project-content${he==="project"&&g?" project-content--with-footer":""}${Ye&&!ft?" project-content--with-mobile-nav":""}`,children:gn()}),he==="project"&&g&&!rt&&t.jsx(EI,{tasks:h&&K.tasks.length>0?K.tasks:me,projectId:g.id,taskStuckTimeoutMs:Rt,backgroundSessions:I,backgroundGenerating:T,backgroundNeedsInput:k,onOpenBackgroundSession:_e,onDismissBackgroundSession:J,lastFetchTimeMs:Le,currentProjectPath:g.path,onOpenProjectDirectory:as}),t.jsx(OI,{view:ne,onChangeView:he==="project"&&g?ge:()=>{},footerVisible:he==="project"&&!!g,modalOpen:W.anyModalOpen,keyboardOpen:ft,onOpenSettings:Hn,onOpenActivityLog:W.openActivityLog,onOpenSystemStats:W.openSystemStats,onOpenMailbox:()=>ge("mailbox"),mailboxUnreadCount:Z,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:H.length,onOpenUsage:()=>W.openUsage(null),onViewAllProjects:cn,onRunScript:W.runScript,projectId:g?.id,showSkillsTab:Kt,experimentalFeatures:{insights:F,roadmap:ve,memoryView:ze,devServer:Oe,devServerView:Oe,todoView:Ge,researchView:ke}}),he==="project"&&g&&ne!=="chat"&&ne!=="mailbox"&&ne!=="insights"&&ne!=="devserver"&&ne!=="dev-server"&&t.jsx(h4,{projectId:g.id,addToast:n,showFAB:xe,open:qt,onOpenChange:Pt,favoriteProviders:hn,favoriteModels:Rn,onToggleFavorite:Qt,onToggleModelFavorite:yt}),t.jsx(pI,{projectId:g?.id,tasks:me,projects:r,currentProject:g,addToast:n,toasts:e,removeToast:s,modalManager:W,projectActions:{handleAddProject:fn,handleSetupComplete:dn,handleModelOnboardingComplete:_n},taskHandlers:{handleModalCreate:le,handlePlanningTaskCreated:Se,handlePlanningTasksCreated:Qe,handleSubtaskTasksCreated:ht,handleGitHubImport:bt},taskOperations:{moveTask:Ee,deleteTask:Te,mergeTask:at,retryTask:et,resetTask:Ve,duplicateTask:De},deepLink:{handleDetailClose:on},settings:{prAuthAvailable:Fe,themeMode:$,colorTheme:U,dashboardFontScalePct:G,setThemeMode:Y,setColorTheme:ee,setDashboardFontScalePct:N},onSettingsClose:()=>{W.closeSettings(),it(nt=>nt+1),un()},onReopenOnboarding:()=>{W.closeSettings(),W.openModelOnboarding()}}),t.jsx(t$,{open:At})]})}function g$(){return t.jsx(C4,{children:t.jsx(Z4,{children:t.jsx(pN,{children:t.jsx(f$,{})})})})}function Jg(e){e.postMessage({type:"SKIP_WAITING"})}function op(e){e.addEventListener("statechange",()=>{e.state==="installed"&&navigator.serviceWorker.controller&&Jg(e)})}function b$(){if(!("serviceWorker"in navigator))return;let e=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{e||(e=!0,fd("service worker activated new version"))}),navigator.serviceWorker.register("/sw.js").then(n=>{console.log("SW registered:",n.scope),n.waiting&&navigator.serviceWorker.controller&&Jg(n.waiting),n.installing&&op(n.installing),n.addEventListener("updatefound",()=>{const s=n.installing;s&&op(s)})}).catch(n=>{console.log("SW registration failed:",n)})}sy();Bv();Yg.createRoot(document.getElementById("root")).render(t.jsx(a.StrictMode,{children:t.jsx(Hv,{children:t.jsx(g$,{})})}));b$();export{bP as $,Ds as A,Sn as B,wn as C,uN as D,qD as E,Bi as F,Qo as G,Tc as H,Ws as I,rn as J,To as K,ot as L,x3 as M,xn as N,yc as O,An as P,Cn as Q,Ln as R,Ni as S,pd as T,qs as U,an as V,Xt as W,Ht as X,NP as Y,Qn as Z,bk as _,fs as a,Cs as a$,xP as a0,xk as a1,UD as a2,vk as a3,ln as a4,nD as a5,sD as a6,Sj as a7,md as a8,Ma as a9,y3 as aA,j3 as aB,w3 as aC,kr as aD,xv as aE,pr as aF,Bb as aG,hs as aH,yp as aI,ol as aJ,k4 as aK,yu as aL,ju as aM,Er as aN,Bw as aO,QL as aP,XL as aQ,Hw as aR,qw as aS,KI as aT,Ta as aU,Fg as aV,KL as aW,Jo as aX,xp as aY,UI as aZ,VI as a_,_a as aa,li as ab,ci as ac,bi as ad,ZL as ae,n3 as af,t3 as ag,e3 as ah,s3 as ai,cs as aj,gs as ak,Mv as al,ri as am,Kb as an,Rr as ao,Ei as ap,i3 as aq,r3 as ar,u3 as as,d3 as at,c3 as au,l3 as av,o3 as aw,a3 as ax,Sr as ay,k3 as az,YD as b,kL as b$,zi as b0,Si as b1,pp as b2,Qd as b3,iL as b4,rL as b5,aL as b6,oL as b7,lL as b8,cL as b9,B$ as bA,F$ as bB,z$ as bC,P$ as bD,q$ as bE,aT as bF,wD as bG,kD as bH,MD as bI,jD as bJ,ND as bK,SD as bL,CD as bM,ED as bN,Gj as bO,_D as bP,bd as bQ,Vj as bR,Wj as bS,Kj as bT,qj as bU,yD as bV,Dr as bW,el as bX,gv as bY,jr as bZ,cv as b_,dL as ba,uL as bb,mL as bc,hL as bd,pL as be,fL as bf,gL as bg,bL as bh,vL as bi,yL as bj,xL as bk,Vn as bl,hd as bm,Ui as bn,JL as bo,GL as bp,YL as bq,D$ as br,$$ as bs,I$ as bt,L$ as bu,W$ as bv,K$ as bw,H$ as bx,O$ as by,U$ as bz,Ke as c,sT as c$,wL as c0,NL as c1,SL as c2,CL as c3,EL as c4,_L as c5,jL as c6,Np as c7,xa as c8,Sk as c9,G$ as cA,nL as cB,y$ as cC,j$ as cD,QD as cE,k$ as cF,N$ as cG,T$ as cH,R$ as cI,Xy as cJ,By as cK,oi as cL,qy as cM,Hy as cN,Vy as cO,Wy as cP,Q$ as cQ,XD as cR,ZD as cS,eL as cT,Mi as cU,h3 as cV,p3 as cW,sL as cX,S$ as cY,_c as cZ,Xn as c_,Jv as ca,Yv as cb,Iy as cc,$y as cd,HL as ce,aD as cf,iD as cg,qL as ch,rD as ci,pD as cj,uD as ck,oD as cl,mD as cm,lD as cn,hD as co,cD as cp,dD as cq,hb as cr,Fy as cs,fD as ct,Oy as cu,gD as cv,rR as cw,di as cx,b4 as cy,VR as cz,GD as d,Y$ as d$,CP as d0,_P as d1,jc as d2,al as d3,E$ as d4,w$ as d5,_$ as d6,C$ as d7,M$ as d8,A$ as d9,VD as dA,hp as dB,DD as dC,$D as dD,gP as dE,BD as dF,Ir as dG,lA as dH,PD as dI,TD as dJ,Cj as dK,ID as dL,LD as dM,LL as dN,RD as dO,zL as dP,ov as dQ,Ic as dR,VL as dS,UL as dT,OL as dU,BL as dV,FL as dW,tL as dX,m3 as dY,X$ as dZ,J$ as d_,Vi as da,v3 as db,oN as dc,rl as dd,f3 as de,dh as df,g3 as dg,b3 as dh,V$ as di,ML as dj,RL as dk,IL as dl,TL as dm,AL as dn,PL as dp,$L as dq,Oc as dr,nu as ds,wx as dt,DL as du,HD as dv,zD as dw,OD as dx,FD as dy,WD as dz,JD as e,eD as e0,tD as e1,Z$ as e2,wr as f,Wn as g,bs as h,Ra as i,WL as j,Zn as k,gk as l,AD as m,Ls as n,vD as o,bD as p,xD as q,vP as r,Gs as s,KD as t,pn as u,qI as v,Ks as w,nl as x,Zr as y,we as z};