@runfusion/fusion 0.15.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +3 -19
  2. package/dist/bin.js +7005 -2992
  3. package/dist/client/assets/AgentDetailView-DGqT1oDt.js +18 -0
  4. package/dist/client/assets/AgentDetailView-yu8Xltqk.css +1 -0
  5. package/dist/client/assets/AgentsView-BmemrfrO.js +517 -0
  6. package/dist/client/assets/AgentsView-Bs03ptrd.css +1 -0
  7. package/dist/client/assets/ChatView-CZQUBFlV.js +1 -0
  8. package/dist/client/assets/{DevServerView-CV_PpbnZ.js → DevServerView-C3Q0XqDA.js} +1 -1
  9. package/dist/client/assets/{DirectoryPicker-DPfkGnj5.js → DirectoryPicker-BZWVA9ND.js} +1 -1
  10. package/dist/client/assets/{DocumentsView-CESb6RI7.js → DocumentsView-DO48ivSq.js} +1 -1
  11. package/dist/client/assets/InsightsView-CAngTfMf.js +11 -0
  12. package/dist/client/assets/MemoryView-B3rNcAOW.js +2 -0
  13. package/dist/client/assets/NodesView-BnV1LWa8.js +14 -0
  14. package/dist/client/assets/NodesView-DuAXX_0j.css +1 -0
  15. package/dist/client/assets/{PiExtensionsManager-C4fTzemh.js → PiExtensionsManager-C3_Lw4sa.js} +3 -3
  16. package/dist/client/assets/{PluginManager-C2-dExUL.js → PluginManager-Vv3nzrJ1.js} +1 -1
  17. package/dist/client/assets/ResearchView-BzCcDAS4.css +1 -0
  18. package/dist/client/assets/ResearchView-Dfdsuc21.js +1 -0
  19. package/dist/client/assets/RoadmapsView-BiIpE-b8.js +6 -0
  20. package/dist/client/assets/RoadmapsView-DdGlfuu-.css +1 -0
  21. package/dist/client/assets/SettingsModal-BN00HYJ2.js +31 -0
  22. package/dist/client/assets/{SettingsModal-BGnSAeqa.js → SettingsModal-CK4w8Ztb.js} +1 -1
  23. package/dist/client/assets/SettingsModal-Dq4a5KSX.css +1 -0
  24. package/dist/client/assets/{SetupWizardModal-C_d9clJp.js → SetupWizardModal-Dw6N4UvY.js} +1 -1
  25. package/dist/client/assets/{SkillsView-C096TB7i.js → SkillsView-C1196wgA.js} +1 -1
  26. package/dist/client/assets/{folder-open-CKivQd8c.js → folder-open-WVtgE4k3.js} +1 -1
  27. package/dist/client/assets/index-BIJgrHEn.css +1 -0
  28. package/dist/client/assets/index-Bv0TGzDH.js +682 -0
  29. package/dist/client/assets/{star-damu_EYz.js → star-MSImEC8V.js} +1 -1
  30. package/dist/client/assets/{upload-uH6CHlEw.js → upload-Dmvy3xXd.js} +1 -1
  31. package/dist/client/assets/{users-CUySbfji.js → users-CncYvHNf.js} +1 -1
  32. package/dist/client/index.html +2 -2
  33. package/dist/client/version.json +1 -1
  34. package/dist/extension.js +6220 -3829
  35. package/dist/pi-claude-cli/package.json +1 -1
  36. package/dist/pi-claude-cli/src/__tests__/process-manager.test.ts +11 -0
  37. package/dist/pi-claude-cli/src/__tests__/provider.test.ts +25 -0
  38. package/dist/plugins/fusion-plugin-dependency-graph/manifest.json +16 -0
  39. package/dist/plugins/fusion-plugin-dependency-graph/package.json +34 -0
  40. package/dist/plugins/fusion-plugin-dependency-graph/src/DependencyGraphView.css +132 -0
  41. package/dist/plugins/fusion-plugin-dependency-graph/src/DependencyGraphView.tsx +428 -0
  42. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/DependencyGraphView.test.tsx +261 -0
  43. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/storage.test.ts +31 -0
  44. package/dist/plugins/fusion-plugin-dependency-graph/src/index.ts +25 -0
  45. package/dist/plugins/fusion-plugin-dependency-graph/src/storage.ts +23 -0
  46. package/package.json +8 -4
  47. package/skill/fusion/SKILL.md +5 -5
  48. package/skill/fusion/references/engine-tools.md +4 -4
  49. package/skill/fusion/references/extension-tools.md +3 -3
  50. package/skill/fusion/references/fusion-capabilities.md +1 -1
  51. package/skill/fusion/references/skill-patterns.md +1 -1
  52. package/skill/fusion/workflows/dashboard-cli.md +3 -3
  53. package/skill/fusion/workflows/task-management.md +1 -1
  54. package/dist/client/assets/AgentDetailView-B1zViykq.js +0 -18
  55. package/dist/client/assets/AgentDetailView-B5tq9ius.css +0 -1
  56. package/dist/client/assets/AgentsView-Bl9JH5C8.js +0 -522
  57. package/dist/client/assets/AgentsView-V5GhlBYu.css +0 -1
  58. package/dist/client/assets/ChatView-liNErE53.js +0 -1
  59. package/dist/client/assets/InsightsView-BKhvyEyQ.js +0 -11
  60. package/dist/client/assets/MemoryView-DB-l2miV.js +0 -2
  61. package/dist/client/assets/NodesView-DCoS6iYh.css +0 -1
  62. package/dist/client/assets/NodesView-DgTXO8mm.js +0 -14
  63. package/dist/client/assets/ResearchView-BzRdUzNq.css +0 -1
  64. package/dist/client/assets/ResearchView-CkVwRDVA.js +0 -1
  65. package/dist/client/assets/RoadmapsView-BOYnyMCh.css +0 -1
  66. package/dist/client/assets/RoadmapsView-Cu85_XrQ.js +0 -6
  67. package/dist/client/assets/SettingsModal-C0DokcId.js +0 -31
  68. package/dist/client/assets/SettingsModal-DcGFm6NR.css +0 -1
  69. package/dist/client/assets/SkillMultiselect-DDHJnrkn.css +0 -1
  70. package/dist/client/assets/SkillMultiselect-DwGWYZi6.js +0 -1
  71. package/dist/client/assets/TodoView-CUiAt2mR.js +0 -6
  72. package/dist/client/assets/TodoView-SeO9o7km.css +0 -1
  73. package/dist/client/assets/index-B4StE1qN.js +0 -662
  74. package/dist/client/assets/index-DYJk0WDc.css +0 -1
  75. package/dist/client/assets/list-checks-B3oufblU.js +0 -6
@@ -0,0 +1,682 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AgentDetailView-DGqT1oDt.js","assets/vendor-react-K0fH_qHe.js","assets/star-MSImEC8V.js","assets/AgentDetailView-yu8Xltqk.css","assets/vendor-xterm-DzcZoU0P.js","assets/vendor-xterm-LZoznX6r.css","assets/addon-fit-C7jRorKK.js","assets/addon-web-links-CkJwd4cQ.js","assets/addon-webgl-BjvOw43o.js","assets/SetupWizardModal-Dw6N4UvY.js","assets/DirectoryPicker-BZWVA9ND.js","assets/folder-open-WVtgE4k3.js","assets/DirectoryPicker-DzKVmxOf.css","assets/SetupWizardModal-DRF5fOoR.css","assets/SettingsModal-BN00HYJ2.js","assets/SettingsModal-CK4w8Ztb.js","assets/SettingsModal-Dq4a5KSX.css","assets/users-CncYvHNf.js","assets/SettingsModal-D_AFkDJa.css","assets/AgentsView-BmemrfrO.js","assets/upload-Dmvy3xXd.js","assets/AgentsView-Bs03ptrd.css","assets/DocumentsView-DO48ivSq.js","assets/DocumentsView-BrhyOdeE.css","assets/InsightsView-CAngTfMf.js","assets/InsightsView-4KiUKzbz.css","assets/ResearchView-Dfdsuc21.js","assets/ResearchView-BzCcDAS4.css","assets/NodesView-BnV1LWa8.js","assets/NodesView-DuAXX_0j.css","assets/ChatView-CZQUBFlV.js","assets/RoadmapsView-BiIpE-b8.js","assets/RoadmapsView-DdGlfuu-.css","assets/SkillsView-C1196wgA.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-B3rNcAOW.js","assets/MemoryView-DiajLXby.css","assets/DevServerView-C3Q0XqDA.js","assets/DevServerView-DlZpuAnj.css"])))=>i.map(i=>d[i]);
2
+ import{r as i,j as t,R as Jo,a as Qi,g as Wp,c as Db}from"./vendor-react-K0fH_qHe.js";import"./vendor-xterm-DzcZoU0P.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))a(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&a(l)}).observe(document,{childList:!0,subtree:!0});function s(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function a(r){if(r.ep)return;r.ep=!0;const o=s(r);fetch(r.href,o)}})();/**
3
+ * @license lucide-react v1.7.0 - ISC
4
+ *
5
+ * This source code is licensed under the ISC license.
6
+ * See the LICENSE file in the root directory of this source tree.
7
+ */const Kp=(...e)=>e.filter((n,s,a)=>!!n&&n.trim()!==""&&a.indexOf(n)===s).join(" ").trim();/**
8
+ * @license lucide-react v1.7.0 - ISC
9
+ *
10
+ * This source code is licensed under the ISC license.
11
+ * See the LICENSE file in the root directory of this source tree.
12
+ */const Lb=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 Ob=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(n,s,a)=>a?a.toUpperCase():s.toLowerCase());/**
18
+ * @license lucide-react v1.7.0 - ISC
19
+ *
20
+ * This source code is licensed under the ISC license.
21
+ * See the LICENSE file in the root directory of this source tree.
22
+ */const yu=e=>{const n=Ob(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 Vl={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 zb=e=>{for(const n in e)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},Fb=i.createContext({}),Ub=()=>i.useContext(Fb),Bb=i.forwardRef(({color:e,size:n,strokeWidth:s,absoluteStrokeWidth:a,className:r="",children:o,iconNode:l,...c},d)=>{const{size:u=24,strokeWidth:m=2,absoluteStrokeWidth:h=!1,color:f="currentColor",className:p=""}=Ub()??{},g=a??h?Number(s??m)*24/Number(n??u):s??m;return i.createElement("svg",{ref:d,...Vl,width:n??u??Vl.width,height:n??u??Vl.height,stroke:e??f,strokeWidth:g,className:Kp("lucide",p,r),...!o&&!zb(c)&&{"aria-hidden":"true"},...c},[...l.map(([x,v])=>i.createElement(x,v)),...Array.isArray(o)?o:[o]])});/**
33
+ * @license lucide-react v1.7.0 - ISC
34
+ *
35
+ * This source code is licensed under the ISC license.
36
+ * See the LICENSE file in the root directory of this source tree.
37
+ */const et=(e,n)=>{const s=i.forwardRef(({className:a,...r},o)=>i.createElement(Bb,{ref:o,iconNode:n,className:Kp(`lucide-${Lb(yu(e))}`,`lucide-${e}`,a),...r}));return s.displayName=yu(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 Hb=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],Fs=et("activity",Hb);/**
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 qb=[["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"}]],Vb=et("archive-restore",qb);/**
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 Wb=[["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"}]],Br=et("archive",Wb);/**
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 Kb=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],Hr=et("arrow-down",Kb);/**
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 Gb=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],la=et("arrow-left",Gb);/**
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 Jb=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],qr=et("arrow-right",Jb);/**
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 Yb=[["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"}]],Gp=et("arrow-up-down",Yb);/**
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 Qb=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Zi=et("arrow-up",Qb);/**
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 Xb=[["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"}]],Zb=et("book-open",Xb);/**
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 ex=[["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"}]],Rn=et("bot",ex);/**
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 tx=[["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"}]],td=et("box",tx);/**
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 nx=[["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"}]],Rr=et("brain",nx);/**
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 sx=[["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"}]],Jp=et("calendar",sx);/**
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 ix=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],ax=et("check-check",ix);/**
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 rx=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Yn=et("check",rx);/**
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 ox=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],un=et("chevron-down",ox);/**
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 lx=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],bl=et("chevron-left",lx);/**
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 cx=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Tn=et("chevron-right",cx);/**
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 dx=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],ri=et("chevron-up",dx);/**
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 ux=[["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"}]],Rs=et("circle-alert",ux);/**
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 mx=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],Ln=et("circle-check-big",mx);/**
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 hx=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],xl=et("circle-dot",hx);/**
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 px=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]],fx=et("circle-plus",px);/**
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 gx=[["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"}]],nd=et("circle-question-mark",gx);/**
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 bx=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],xx=et("circle-stop",bx);/**
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 vx=[["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"}]],Vr=et("circle-x",vx);/**
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 yx=[["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"}]],wx=et("clipboard-list",yx);/**
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 kx=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],_i=et("clock",kx);/**
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 jx=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Yp=et("code",jx);/**
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 Nx=[["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"}]],wu=et("columns-3",Nx);/**
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 Sx=[["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"}]],ta=et("copy",Sx);/**
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 Cx=[["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"}]],Ex=et("cpu",Cx);/**
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 Mx=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],_x=et("download",Mx);/**
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 Ax=[["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"}]],Px=et("ellipsis-vertical",Ax);/**
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 Rx=[["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"}]],sd=et("ellipsis",Rx);/**
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 Tx=[["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"}]],Ix=et("external-link",Tx);/**
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 $x=[["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"}]],Ud=et("eye-off",$x);/**
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 Dx=[["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"}]],Va=et("eye",Dx);/**
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 Lx=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}]],si=et("file-code",Lx);/**
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 Ox=[["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"}]],id=et("file-diff",Ox);/**
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 zx=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}]],Fx=et("file-minus",zx);/**
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 Ux=[["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"}]],Qp=et("file-pen",Ux);/**
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 Bx=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],Hx=et("file-plus",Bx);/**
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 qx=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M12 17h.01",key:"p32p05"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}]],Vx=et("file-question-mark",qx);/**
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 Wx=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Fi=et("file-text",Wx);/**
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 Kx=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"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"}]],Gx=et("file-type",Kx);/**
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 Jx=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}]],Xp=et("file",Jx);/**
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 Yx=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528",key:"1jaruq"}]],Qx=et("flag",Yx);/**
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 Xx=[["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"}]],ad=et("folder-git-2",Xx);/**
283
+ * @license lucide-react v1.7.0 - ISC
284
+ *
285
+ * This source code is licensed under the ISC license.
286
+ * See the LICENSE file in the root directory of this source tree.
287
+ */const Zx=[["path",{d:"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"}]],ku=et("folder-root",Zx);/**
288
+ * @license lucide-react v1.7.0 - ISC
289
+ *
290
+ * This source code is licensed under the ISC license.
291
+ * See the LICENSE file in the root directory of this source tree.
292
+ */const ev=[["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"}]],os=et("folder",ev);/**
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 tv=[["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"}]],Yo=et("funnel",tv);/**
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 nv=[["path",{d:"M15 6a9 9 0 0 0-9 9V3",key:"1cii5b"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}]],Hs=et("git-branch",nv);/**
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 sv=[["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"}]],Wr=et("git-commit-horizontal",sv);/**
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 iv=[["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"}]],Zp=et("git-merge",iv);/**
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 av=[["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"}]],zs=et("git-pull-request",av);/**
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 rv=[["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"}]],vl=et("globe",rv);/**
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 ov=[["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"}]],yl=et("grid-3x3",ov);/**
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 lv=[["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"}]],wl=et("grip-vertical",lv);/**
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 cv=[["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"}]],dv=et("hard-drive",cv);/**
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 uv=[["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"}]],mv=et("heart",uv);/**
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 hv=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],Tr=et("history",hv);/**
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 pv=[["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"}]],vr=et("inbox",pv);/**
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 fv=[["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"}]],ef=et("key",fv);/**
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 gv=[["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"}]],bv=et("keyboard",gv);/**
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 xv=[["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"}]],na=et("layers",xv);/**
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 vv=[["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"}]],Ui=et("layout-grid",vv);/**
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 yv=[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]],oi=et("lightbulb",yv);/**
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 wv=[["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"}]],Pa=et("link",wv);/**
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 kv=[["path",{d:"M13 5h8",key:"a7qcls"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 19h8",key:"c3s6r1"}],["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["path",{d:"m3 7 2 2 4-4",key:"1obspn"}]],rd=et("list-checks",kv);/**
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 jv=[["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"}]],Nv=et("list-plus",jv);/**
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 Sv=[["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"}]],kl=et("list-tree",Sv);/**
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 Cv=[["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"}]],od=et("list",Cv);/**
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 Ev=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],gt=et("loader-circle",Ev);/**
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 Mv=[["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"}]],jl=et("lock",Mv);/**
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 _v=[["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"}]],sa=et("mail",_v);/**
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 Av=[["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"}]],ld=et("map",Av);/**
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 Pv=[["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"}]],Nl=et("maximize-2",Pv);/**
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 Rv=[["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"}]],Tv=et("message-square-plus",Rv);/**
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 Iv=[["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"}]],Ei=et("message-square",Iv);/**
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 $v=[["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"}]],Kr=et("minimize-2",$v);/**
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 Dv=[["path",{d:"M5 12h14",key:"1ays0h"}]],Lv=et("minus",Dv);/**
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 Ov=[["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"}]],Ra=et("monitor",Ov);/**
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 zv=[["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"}]],Fv=et("move",zv);/**
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 Uv=[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]],Bv=et("network",Uv);/**
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 Hv=[["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"}]],cd=et("package",Hv);/**
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 qv=[["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"}]],tf=et("paperclip",qv);/**
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 Vv=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1",key:"kaeet6"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1",key:"1wsw3u"}]],ii=et("pause",Vv);/**
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 Wv=[["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"}]],xs=et("pencil",Wv);/**
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 Kv=[["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"}]],Hn=et("play",Kv);/**
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 Gv=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Sn=et("plus",Gv);/**
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 Jv=[["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"}]],nf=et("radio",Jv);/**
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 Yv=[["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"}]],ns=et("refresh-cw",Yv);/**
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 Qv=[["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"}]],ju=et("rocket",Qv);/**
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 Xv=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]],Zv=et("rotate-ccw",Xv);/**
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 ey=[["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"}]],ty=et("rotate-cw",ey);/**
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 ny=[["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"}]],sf=et("save",ny);/**
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 sy=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Ci=et("search",sy);/**
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 iy=[["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"}]],Xi=et("send",iy);/**
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 ay=[["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"}]],Ir=et("server",ay);/**
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 ry=[["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"}]],Cr=et("settings",ry);/**
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 oy=[["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"}]],ly=et("shield-alert",oy);/**
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 cy=[["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"}]],dy=et("shield",cy);/**
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 uy=[["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"}]],my=et("skull",uy);/**
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 hy=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],ms=et("sparkles",hy);/**
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 py=[["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"}]],Qo=et("square-check-big",py);/**
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 fy=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],Os=et("square",fy);/**
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 gy=[["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=et("target",gy);/**
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 by=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],Mi=et("terminal",by);/**
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 xy=[["path",{d:"m16 16-3 3 3 3",key:"117b85"}],["path",{d:"M3 12h14.5a1 1 0 0 1 0 7H13",key:"18xa6z"}],["path",{d:"M3 19h6",key:"1ygdsz"}],["path",{d:"M3 5h18",key:"1u36vt"}]],Xo=et("text-wrap",xy);/**
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 vy=[["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"}]],Cn=et("trash-2",vy);/**
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 yy=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],wy=et("trending-up",yy);/**
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 ky=[["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"}]],Sl=et("triangle-alert",ky);/**
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 jy=[["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"}]],Nu=et("unlink",jy);/**
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 Ny=[["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"}]],ba=et("user",Ny);/**
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 Sy=[["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"}]],af=et("webhook",Sy);/**
618
+ * @license lucide-react v1.7.0 - ISC
619
+ *
620
+ * This source code is licensed under the ISC license.
621
+ * See the LICENSE file in the root directory of this source tree.
622
+ */const Cy=[["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"}]],Zo=et("workflow",Cy);/**
623
+ * @license lucide-react v1.7.0 - ISC
624
+ *
625
+ * This source code is licensed under the ISC license.
626
+ * See the LICENSE file in the root directory of this source tree.
627
+ */const Ey=[["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"}]],Su=et("wrench",Ey);/**
628
+ * @license lucide-react v1.7.0 - ISC
629
+ *
630
+ * This source code is licensed under the ISC license.
631
+ * See the LICENSE file in the root directory of this source tree.
632
+ */const My=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Jt=et("x",My);/**
633
+ * @license lucide-react v1.7.0 - ISC
634
+ *
635
+ * This source code is licensed under the ISC license.
636
+ * See the LICENSE file in the root directory of this source tree.
637
+ */const _y=[["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"}]],Xn=et("zap",_y),dd="fusion:version-reload",ud="fusion:version-update";let Bd=!0;function Wl(e){Bd=e}function Ay(){try{if(sessionStorage.getItem(ud))return sessionStorage.removeItem(ud),!0}catch{}return!1}function Hd(e){if(sessionStorage.getItem(dd)){console.warn("[versionCheck] reload already attempted, suppressing",e);return}if(sessionStorage.setItem(dd,"1"),!Bd){console.info("[versionCheck] auto-reload disabled by setting, skipping reload:",e);return}console.info("[versionCheck] reloading:",e),window.location.reload()}function Py(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 Ry(e){return Py(e)?(Hd(`chunk load error: ${e?.message??e}`),!0):!1}async function Ty(){try{const e=await fetch("/version.json",{cache:"no-store",headers:{Accept:"application/json"}});if(!e.ok||!(e.headers.get("content-type")??"").includes("application/json"))return null;const s=await e.json();return typeof s.version=="string"?s.version:null}catch{return null}}async function Iy(){try{const e=new AbortController,n=setTimeout(()=>e.abort(),3e3),s=await fetch("/api/settings",{headers:{Accept:"application/json"},signal:e.signal});clearTimeout(n),s.ok&&(await s.json()).autoReloadOnVersionChange===!1&&(Bd=!1)}catch{}}const $y=6e4;let Cu=0,Kl=!1;async function Gl(){if(!(Kl||document.visibilityState!=="visible")&&!(Date.now()-Cu<$y)){Cu=Date.now(),Kl=!0;try{const e=await Ty();if(e&&e!=="519248abe-5d33d77b"){try{sessionStorage.setItem(ud,"1")}catch{}Hd(`build version changed: 519248abe-5d33d77b -> ${e}`)}}finally{Kl=!1}}}function Dy(){Iy(),window.setTimeout(()=>sessionStorage.removeItem(dd),5e3),document.addEventListener("visibilitychange",()=>{Gl()}),window.addEventListener("focus",()=>{Gl()}),window.setTimeout(()=>void Gl(),2e3)}class Cl extends i.Component{constructor(n){super(n),this.state={hasError:!1,error:null}}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,s){console.error("[ErrorBoundary]",n,s),!Ry(n)&&this.props.onError?.(n,s)}resetErrorBoundary=()=>{this.setState({hasError:!1,error:null})};render(){if(!this.state.hasError)return this.props.children;if(this.props.fallback)return this.props.fallback;const n=this.props.level??"page",a=n==="modal"?"This section encountered an error":"Something went wrong";return t.jsxs("div",{className:`error-boundary error-boundary--${n}`,children:[t.jsx("div",{className:"error-boundary__icon",children:t.jsx(Sl,{size:40})}),t.jsx("div",{className:"error-boundary__title",children:a}),this.state.error&&t.jsx("pre",{className:"error-boundary__message",children:this.state.error.message}),t.jsxs("div",{className:"error-boundary__actions",children:[t.jsx("button",{className:"btn btn-primary",onClick:this.resetErrorBoundary,children:"Retry"}),t.jsx("button",{className:"btn",onClick:()=>window.location.reload(),children:"Reload page"})]})]})}}function vs({children:e,onError:n}){return t.jsx(Cl,{level:"page",onError:n,children:e})}function Ki({children:e,onError:n}){return t.jsx(Cl,{level:"modal",onError:n,children:e})}function Ly({children:e,onError:n}){return t.jsx(Cl,{level:"root",onError:n,children:e})}const Oy="modulepreload",zy=function(e){return"/"+e},Eu={},Mn=function(n,s,a){let r=Promise.resolve();if(s&&s.length>0){let l=function(u){return Promise.all(u.map(m=>Promise.resolve(m).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),d=c?.nonce||c?.getAttribute("nonce");r=l(s.map(u=>{if(u=zy(u),u in Eu)return;Eu[u]=!0;const m=u.endsWith(".css"),h=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${h}`))return;const f=document.createElement("link");if(f.rel=m?"stylesheet":Oy,m||(f.as="script"),f.crossOrigin="",f.href=u,d&&f.setAttribute("nonce",d),document.head.appendChild(f),m)return new Promise((p,g)=>{f.addEventListener("load",p),f.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${u}`)))})}))}function o(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return r.then(l=>{for(const c of l||[])c.status==="rejected"&&o(c.reason);return n().catch(o)})},qd="fn.authToken",Mu="token",Fy="fn_token";let Ma,_u=!1,el=!1;const md="fn:auth-token-recovery-required";function Uy(){try{const e=window.localStorage.getItem(qd);return e&&e.length>0?e:void 0}catch{return}}function rf(e){try{window.localStorage.setItem(qd,e)}catch{}}function By(){if(!(_u||typeof window>"u")){_u=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(Mu);if(!n)return;rf(n),e.searchParams.delete(Mu);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function Ta(){if(Ma!==void 0)return Ma;const e=By();if(e)return Ma=e,e;const n=Uy();if(n)return Ma=n,n}function Hy(e){Ma=e,el=!1,rf(e)}function qy(){Ma=void 0,el=!1;try{window.localStorage.removeItem(qd)}catch{}}function Au(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function Vy(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function Wy(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!Vy(e.protocol))return!1;const s=e.hostname===n.hostname,a=e.port===n.port,r=Au(e.protocol)===Au(n.protocol);return s&&a&&r}function Ky(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 xi(e){const n=Ta();if(!n||typeof window>"u")return e;const s=Ky(e);return!s||!Wy(s.parsed)?e:(s.parsed.searchParams.set(Fy,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function Ai(e){const n=Ta();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function Gy(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function Jy(){typeof window>"u"||el||(el=!0,window.dispatchEvent(new CustomEvent(md)))}async function Yy(e){if(e.status===401)try{const n=e.clone();if(!(n.headers.get("content-type")??"").toLowerCase().includes("application/json"))return;const a=await n.json();Gy(a)&&Jy()}catch{}}function Qy(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,Ta();const e=window.fetch.bind(window);window.fetch=function(s,a){const r=Ta(),o=typeof s=="string"?s:s instanceof URL?s.toString():s.url;if(!(()=>{try{const d=new URL(o,window.location.origin);return d.origin!==window.location.origin?!1:d.pathname.startsWith("/api/")||d.pathname==="/api"}catch{return o.startsWith("/api/")||o==="/api"}})())return e(s,a);const c=new Headers(a?.headers??(s instanceof Request?s.headers:void 0));return r&&!c.has("Authorization")&&c.set("Authorization",`Bearer ${r}`),e(s,{...a,headers:c}).then(d=>(Yy(d),d))}}class Xy extends Error{status;details;constructor(n,s,a){super(n),this.name="ApiRequestError",this.status=s,this.details=a}}function Zy(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function js(e){return`/api${e}`}async function D(e,n={}){const s=js(e),a=Ta(),r=(()=>{if(a){const f=new Headers(n.headers??{});return f.has("Content-Type")||f.set("Content-Type","application/json"),Ai(f)}if(!n.headers)return{"Content-Type":"application/json"};const h=new Headers(n.headers);return h.has("Content-Type")||h.set("Content-Type","application/json"),Object.fromEntries(h.entries())})(),o=await fetch(s,{...n,headers:r});if(o.status===204){if(!o.ok)throw new Error(`Request failed for ${s}: ${o.status} ${o.statusText}`);return}const l=o.headers.get("content-type")??"",c=await o.text(),d=l.includes("application/json");if(l.includes("text/html")||Zy(c))throw new Error(`API returned HTML instead of JSON for ${s}. The endpoint may not be properly configured. (${o.status} ${o.statusText})`);if(!d){const h=c.length>160?`${c.slice(0,160)}...`:c;throw new Error(`API returned ${l||"an unknown content type"} instead of JSON for ${s}. (${o.status} ${o.statusText})${h?` Response: ${h}`:""}`)}let m;try{m=c?JSON.parse(c):null}catch{throw new Error(`API returned invalid JSON for ${s}. (${o.status} ${o.statusText})`)}if(!o.ok){const h=m;throw new Xy(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return m}function nL(){return D("/health")}function sL(){return D("/updates/check")}function ew(e,n,s,a,r){const o=new URLSearchParams;e!==void 0&&o.set("limit",String(e)),n!==void 0&&o.set("offset",String(n)),s&&o.set("projectId",s),a&&o.set("q",a),r&&o.set("includeArchived","1");const l=o.size>0?`?${o.toString()}`:"";return D(`/tasks${l}`)}async function Ia(e,n){const a=js(V(`/tasks/${e}`,n));for(let r=1;r<=2;r++){const o=await fetch(a,{headers:Ai({"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 tl(e,n){const{title:s,description:a,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:d,modelPresetId:u,modelProvider:m,modelId:h,validatorModelProvider:f,validatorModelId:p,planningModelProvider:g,planningModelId:x,thinkingLevel:v,summarize:b,reviewLevel:y,executionMode:j,priority:C,source:A}=e;return D(V("/tasks",n),{method:"POST",body:JSON.stringify({title:s,description:a,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:d,modelPresetId:u,modelProvider:m,modelId:h,validatorModelProvider:f,validatorModelId:p,planningModelProvider:g,planningModelId:x,thinkingLevel:v,summarize:b,reviewLevel:y,executionMode:j,priority:C,source:A})})}function ni(e,n,s){return D(V(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function tw(e,n,s,a,r,o,l,c,d){return D(V("/tasks/batch-update-models",d),{method:"POST",body:JSON.stringify({taskIds:e,modelProvider:n,modelId:s,validatorModelProvider:a,validatorModelId:r,planningModelProvider:o,planningModelId:l,nodeId:c})})}function nw(e,n,s,a){return D(V(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n,...typeof a=="object"&&a?.preserveProgress?{preserveProgress:!0}:{}})})}function sw(e,n,s){const a=new URLSearchParams,r=a.size>0?`?${a.toString()}`:"";return D(V(`/tasks/${e}${r}`,n),{method:"DELETE"})}function iw(e,n){return D(V(`/tasks/${e}/merge`,n),{method:"POST"})}function aw(e,n){return D(V(`/tasks/${e}/retry`,n),{method:"POST"})}function rw(e,n){return D(V(`/tasks/${e}/reset`,n),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({confirm:!0})})}function ow(e,n){return D(V(`/tasks/${e}/duplicate`,n),{method:"POST"})}function of(e,n){return D(V(`/tasks/${e}/pause`,n),{method:"POST"})}function lw(e,n){return D(V(`/tasks/${e}/unpause`,n),{method:"POST"})}function cw(e,n){return D(V(`/tasks/${e}/archive`,n),{method:"POST"})}function dw(e,n){return D(V(`/tasks/${e}/unarchive`,n),{method:"POST"})}function uw(e){return D(V("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function mw(e,n){return D(V(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function hw(e,n){return D(V(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function pw(e){return D(V("/config",e))}function El(e){return D(V("/settings",e))}function mo(e,n){return D(V("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function fw(e){return D(V("/update-check",e))}function iL(e){return D(V("/remote/settings",e))}function aL(e,n){return D(V("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function rL(e){return D(V("/remote/status",e))}function oL(e){return D(V("/remote/install-cloudflared",e),{method:"POST"})}function lL(e){return D(V("/remote/tunnel/start",e),{method:"POST"})}function cL(e){return D(V("/remote/tunnel/stop",e),{method:"POST"})}function dL(e){return D(V("/remote/tunnel/kill-external",e),{method:"POST"})}function uL(e){return D(V("/remote/token/persistent/regenerate",e),{method:"POST"})}function mL(e,n){return D(V("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function lf(e,n,s){const a=new URLSearchParams;e&&a.set("format",e),a.set("tokenType",n),n==="short-lived"&&typeof s=="number"&&Number.isFinite(s)&&a.set("ttlMs",String(s));const r=a.toString();return r?`?${r}`:""}function hL(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:a}=e,r=lf(null,s,a);return D(V(`/remote/url${r}`,n))}function pL(e="text",n={}){const{projectId:s,tokenType:a="persistent",ttlMs:r}=n,o=lf(e,a,r);return D(V(`/remote/qr${o}`,s))}function fL(e){return D(V("/memory",e))}function gL(e,n){return D(V("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function bL(e){return D(V("/memory/files",e))}function xL(e,n){const s=`path=${encodeURIComponent(e)}`;return D(V(`/memory/file?${s}`,n))}function vL(e,n,s){return D(V("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function yL(e,n){let s,a=n;if(n!==void 0)s=e;else if(typeof e=="string"&&e.trim().length>0){const r=e.trim();r.includes("/")||r.endsWith(".md")||r.startsWith(".")?s=r:a=r}return D(V("/memory/compact",a),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function wL(e){return D(V("/memory/dream",e),{method:"POST"})}function kL(e){return D(V("/memory/insights",e))}function jL(e,n){return D(V("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function NL(e){return D(V("/memory/extract",e),{method:"POST"})}function SL(e){return D(V("/memory/audit",e))}function CL(e){return D(V("/memory/stats",e))}function EL(e){return D(V("/memory/backend",e))}function ML(e){return D(V("/memory/install-qmd",e),{method:"POST"})}function _L(e,n){return D(V("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function ca(){return D("/settings/global")}function _n(e){return D("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function AL(e){return D(V("/settings/scopes",e))}function PL(e){return D(V("/settings/pi-extensions",e))}function RL(e,n){return D(V("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function TL(e,n,s){return D(V("/settings/test-notification",s),{method:"POST",body:JSON.stringify({providerId:e,...n??{}})})}function IL(){return D("/pi-settings")}async function $L(e){return D("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function DL(e){return D("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function LL(e){return D(V("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function $r(e,n,s){const a=new FormData;a.append("file",n);const r=await fetch(js(V(`/tasks/${e}/attachments`,s)),{method:"POST",headers:Ai(),body:a}),o=await r.json();if(!r.ok)throw new Error(o.error||"Upload failed");return o}async function gw(e,n,s){return D(V(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function Pu(e,n,s){const a=new URLSearchParams;s?.limit!==void 0&&a.set("limit",String(s.limit)),s?.offset!==void 0&&a.set("offset",String(s.offset));const r=a.toString()?`?${a.toString()}`:"",o=V(`/tasks/${e}/logs${r}`,n),l=await fetch(js(o),{headers:Ai()});if(!l.ok){const m=await l.json().catch(()=>({error:"Failed to fetch agent logs"}));throw new Error(m.error||`HTTP ${l.status}`)}const c=await l.json(),d=l.headers.has("X-Total-Count")?parseInt(l.headers.get("X-Total-Count"),10):c.length,u=l.headers.has("X-Has-More")?l.headers.get("X-Has-More")==="true":!1;return{entries:c,total:d,hasMore:u}}function bw(e,n,s,a){return D(V(`/tasks/${e}/comments/${n}`,a),{method:"PATCH",body:JSON.stringify({text:s})})}function xw(e,n,s){return D(V(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function vw(e,n){return D(V(`/tasks/${e}/documents`,n))}function yw(e,n,s){return D(V(`/tasks/${e}/documents/${n}/revisions`,s))}async function OL(e,n){const s=new URLSearchParams;e?.q&&s.set("q",e.q),e?.limit!==void 0&&s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset));const a=s.toString(),r=`/documents${a?`?${a}`:""}`;return D(V(r,n))}function zL(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const a=s.toString(),r=`/files/markdown-list${a?`?${a}`:""}`;return D(V(r,e))}function Ru(e,n,s,a,r){return D(V(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:a?.author,metadata:a?.metadata})})}function ww(e,n,s){return D(V(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function kw(e,n,s){return D(V(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function jw(e,n,s){return D(V(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Nw(e,n){return D(V(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function Sw(e,n,s){return D(V(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Ms(){return D("/models")}function Cw(){return D("/usage")}function Ew(){return D("/providers/claude-cli/status")}function Mw(){return D("/system/fn-binary/status")}function _w(){return D("/system/fn-binary/install",{method:"POST"})}function Aw(){return D("/providers/droid-cli/status")}async function FL(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return D(`/providers/hermes/status${n}`)}async function UL(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return(await D(`/providers/hermes/profiles${n}`)).profiles??[]}async function BL(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return D(`/providers/openclaw/status${n}`)}async function HL(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),D(`/providers/paperclip/status?${n.toString()}`)}async function qL(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),(await D(`/providers/paperclip/companies?${n.toString()}`)).companies??[]}async function VL(e){const n=new URLSearchParams({apiUrl:e.apiUrl,companyId:e.companyId});return e.apiKey&&n.set("apiKey",e.apiKey),(await D(`/providers/paperclip/agents?${n.toString()}`)).agents??[]}async function WL(e){return D("/providers/paperclip/cli-mint-key",{method:"POST",body:JSON.stringify(e)})}async function KL(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return D(`/providers/paperclip/cli-status${s?`?${s}`:""}`)}async function GL(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return(await D(`/providers/paperclip/cli-companies${s?`?${s}`:""}`)).companies??[]}async function JL(e){const n=new URLSearchParams({companyId:e.companyId});return e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath),(await D(`/providers/paperclip/cli-agents?${n.toString()}`)).agents??[]}async function YL(e={}){const n=new URLSearchParams;e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return D(`/providers/paperclip/cli-discovery${s?`?${s}`:""}`)}function Pw(e){return D("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function Rw(e){return D("/auth/droid-cli",{method:"POST",body:JSON.stringify({enabled:e})})}async function Tw(){const n=(await D("/custom-providers")).map(s=>({id:s.id,name:s.name,baseUrl:s.baseUrl,api:s.apiType==="anthropic-compatible"?"anthropic-messages":"openai-completions",apiKey:s.apiKey,models:(s.models??[]).map(a=>({id:a.id,name:a.name}))}));return Object.assign(n,{providers:n})}function Iw(e){return D("/custom-providers",{method:"POST",body:JSON.stringify(e)})}function QL(e,n){const s=n,a={...typeof s.name=="string"?{name:s.name}:{},...typeof s.baseUrl=="string"?{baseUrl:s.baseUrl}:{},...typeof s.apiKey=="string"?{apiKey:s.apiKey}:{},...Array.isArray(s.models)?{models:s.models.map(r=>({id:r.id,name:r.name??r.id}))}:{},...s.api?{apiType:s.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible"}:{},..."apiType"in n?{apiType:n.apiType}:{}};return D(`/custom-providers/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(a)})}function XL(e){return D(`/custom-providers/${encodeURIComponent(e)}`,{method:"DELETE"})}function $w(e){const n=e.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible";return Iw({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 Dr(){return D("/auth/status")}function Dw(e){return D("/auth/login",{method:"POST",body:JSON.stringify({provider:e,origin:window.location.origin})})}function Lw(e){return D("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function Ow(e){return D("/auth/cancel",{method:"POST",body:JSON.stringify({provider:e})})}function zw(e,n){return D("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function Fw(e){return D("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function Uw(e,n,s,a){return D("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:a})})}function Bw(e,n,s,a){return D(V("/github/issues/import",a),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function Hw(e,n,s){return D("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function qw(e,n,s,a){return D(V("/github/pulls/import",a),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function Vw(e){return D(V("/git/remotes",e))}function Ww(e){return D(V("/git/remotes/detailed",e))}function Kw(e,n,s){return D(V("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function Gw(e,n){return D(V(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Jw(e,n,s){return D(V(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function Yw(e,n,s){return D(V(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function Qw(e,n,s){return D(V(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function Xw(e,n){return D(V(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}async function Zw(e,n){return(await D(V("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:e})})).results}function ho(e,n,s,a){return D(V("/terminal/sessions",a),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function Tu(e,n){return D(V(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function ek(e){return D(V("/terminal/sessions",e))}function ei(e){return D(V("/git/status",e))}function tk(e,n){const s=e?`?limit=${e}`:"";return D(V(`/git/commits${s}`,n))}function nl(e,n){return D(V(`/git/commits/${e}/diff`,n))}function nk(e){return D(V("/git/commits/ahead",e))}function sk(e,n,s,a){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return D(V(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,a))}function nr(e){return D(V("/git/branches",e))}function ik(e,n,s){const a=`?limit=${n}`;return D(V(`/git/branches/${encodeURIComponent(e)}/commits${a}`,s))}function ak(e){return D(V("/git/worktrees",e))}function rk(e,n,s){return D(V("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function ok(e,n){return D(V(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function Iu(e,n,s){const a=n?"?force=true":"";return D(V(`/git/branches/${encodeURIComponent(e)}${a}`,s),{method:"DELETE"})}function lk(e,n){return D(V("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function ck(e){return D(V("/git/pull",e),{method:"POST"})}function dk(e){return D(V("/git/push",e),{method:"POST"})}function po(e){return D(V("/git/stashes",e))}function uk(e,n){return D(V("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function mk(e,n,s){return D(V(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function hk(e,n){return D(V(`/git/stashes/${e}`,n),{method:"DELETE"})}function pk(e,n,s){const a=new URLSearchParams;return a.set("path",e),a.set("staged",String(n)),D(V(`/git/diff/file?${a.toString()}`,s))}function xa(e){return D(V("/git/changes",e))}function $u(e,n){return D(V("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function fk(e,n){return D(V("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function Du(e,n){return D(V("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function gk(e,n){return D(V("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function bk(e){return D(V("/workspaces",e))}function xk(e,n,s){const a=new URLSearchParams({workspace:e});return n&&a.set("path",n),s&&a.set("projectId",s),D(`/files?${a.toString()}`)}function vk(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),D(`/files/${encodeURIComponent(n)}?${a.toString()}`)}function yk(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),D(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function wk(e,n,s){const a=new URLSearchParams({q:e});return n&&a.set("workspace",n),s&&a.set("projectId",s),D(`/files/search?${a.toString()}`)}function kk(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),D(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function jk(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),D(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function Nk(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),D(`/files/${encodeURIComponent(n)}/delete?${a.toString()}`,{method:"POST"})}function Sk(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),D(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function cf(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${a.toString()}`}function Ck(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${a.toString()}`}function Ek(e,n,s){return D(V("/planning/create-draft",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function Mk(e,n,s,a,r){return D(V("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId,planningDepth:a?.planningDepth,customQuestionCount:a?.customQuestionCount,...r?{existingSessionId:r}:{}})})}function _k(e,n,s,a){return D(V("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function Ak(e,n,s){return D(V(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Pk(e,n,s){return D(V(`/planning/${encodeURIComponent(e)}/stop`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function df(e,n,s){return D(V("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function ZL(e,n,s,a){return D(V("/agents/onboarding/start-streaming",s),{method:"POST",body:JSON.stringify({intent:e,context:n,planningModelProvider:a?.planningModelProvider,planningModelId:a?.planningModelId})})}function eO(e,n,s){return D(V("/agents/onboarding/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n})})}function tO(e,n){return D(V("/agents/onboarding/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function Rk(e,n,s){return D(V("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Tk(e,n,s){return D(V("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Ik(e,n,s){return D(V("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const hd=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(hd))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function $k(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function Wa(e,n,s={}){const a=s.maxReconnectAttempts??10;let r=null,o=!1,l=0,c=null,d=null,u=!1;const m=p=>{const g=p.lastEventId;if(!g)return!0;const x=Number.parseInt(g,10);return Number.isFinite(x)?d!==null&&x<=d?!1:(d=x,!0):!0},h=()=>{if(o)return;const p=$k(e,d),g=new EventSource(xi(p));r=g,g.onopen=()=>{l=0,u=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},g.onmessage=x=>{const v=x;m(v)&&n.onMessage?.(v)};for(const[x,v]of Object.entries(n.events??{}))g.addEventListener(x,b=>{const y=b;m(y)&&v(y)});g.onerror=()=>{if(o||r!==g)return;if(g.readyState===EventSource.CONNECTING){u||(u=!0,s.onConnectionStateChange?.("reconnecting"));return}if(g.close(),l>=a){s.onFatalError?.("Connection lost");return}u=!0,s.onConnectionStateChange?.("reconnecting"),l+=1;const v=Math.min(1e3*2**(l-1),3e4);c=setTimeout(()=>{c=null,h()},v)}};h();const f={close:()=>{o=!0,c&&(clearTimeout(c),c=null),r?.close(),hd.delete(f)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return hd.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,a=e.name,r=typeof e.packagePath=="string"&&e.packagePath.trim().length>0?e.packagePath.trim():s,o=typeof e.confidence=="number"?e.confidence:1,l=n==="root"?"root":n,c=typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():"project";return{name:e.name,command:e.command,scriptName:a,packagePath:r,confidence:o,cwd:s,source:n,workspaceName:typeof e.packageName=="string"?e.packageName:void 0,label:`${c} · ${a} (${l})`}}function $a(e){const n=e.status,s=n==="starting"||n==="running"||n==="failed"||n==="stopped"?n:"stopped",a=typeof e.previewUrl=="string"?e.previewUrl:e.detectedUrl,r=typeof e.manualPreviewUrl=="string"?e.manualPreviewUrl:e.manualUrl;return{id:typeof e.id=="string"?e.id:"",name:typeof e.name=="string"&&e.name.length>0?e.name:"default",status:s,command:typeof e.command=="string"?e.command:"",scriptName:typeof e.scriptId=="string"?e.scriptId:"",cwd:typeof e.cwd=="string"?e.cwd:"",pid:e.pid,startedAt:e.startedAt,previewUrl:a,detectedUrl:typeof e.detectedUrl=="string"?e.detectedUrl:a,detectedPort:e.detectedPort,manualPreviewUrl:r,manualUrl:typeof e.manualUrl=="string"?e.manualUrl:r,logs:Array.isArray(e.logHistory)?e.logHistory:[],exitCode:e.exitCode}}function Dk(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 Lk(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((a,r)=>Dk(a,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function Ok(e,n){const s=typeof n.maxLines=="number"&&Number.isFinite(n.maxLines)?Math.max(1,Math.floor(n.maxLines)):100,a=typeof n.offset=="number"&&Number.isFinite(n.offset)?Math.max(0,Math.floor(n.offset)):0,r=typeof n.lastEventId=="number"&&Number.isFinite(n.lastEventId)?Math.max(0,Math.floor(n.lastEventId)):null,o=e.length,l=e.map((u,m)=>({id:m+1,text:u,stream:"stdout",timestamp:""}));if(r!==null)return{lines:l.filter(u=>u.id>r).slice(0,s),totalLines:o};const c=Math.max(o-a,0),d=Math.max(c-s,0);return{lines:l.slice(d,c),totalLines:o}}function Ou(e){return Array.isArray(e)?e.map(Lu):(e.candidates??[]).map(Lu)}async function zk(e){try{const n=await D(V("/dev-server/candidates",e));return Ou(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await D(V("/dev-server/detect",e));return Ou(s)}throw n}}function Vd(e){return D(V("/dev-server/status",e)).then($a)}async function nO(e={},n){const s=new URLSearchParams;typeof e.maxLines=="number"&&Number.isFinite(e.maxLines)&&s.set("maxLines",String(Math.max(1,Math.floor(e.maxLines)))),typeof e.offset=="number"&&Number.isFinite(e.offset)&&s.set("offset",String(Math.max(0,Math.floor(e.offset)))),typeof e.lastEventId=="number"&&Number.isFinite(e.lastEventId)&&s.set("lastEventId",String(Math.max(0,Math.floor(e.lastEventId))));const a=s.size>0?`?${s.toString()}`:"";try{const r=await D(V(`/dev-server/logs/history${a}`,n));return Lk(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await Vd(n);return Ok(o.logs,e)}throw r}}function Fk(e,n){const s=e.cwd??e.packagePath??".",a=e.scriptName;return D(V("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:a,scriptId:a,cwd:s,packagePath:e.packagePath})}).then($a)}function Uk(e){return D(V("/dev-server/stop",e),{method:"POST"}).then($a)}function Bk(e){return D(V("/dev-server/restart",e),{method:"POST"}).then($a)}async function Hk(e,n){const s=typeof e=="string"?{url:e}:e;try{const a=await D(V("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return $a(a)}catch(a){if(a instanceof Error&&/\/dev-server\/preview-url/.test(a.message)){const r=await D(V("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return $a(r)}throw a}}function sO(e){return js(V("/dev-server/logs/stream",e))}async function iO(e){try{return(await D(V("/devserver",e))).sessions??[]}catch{try{const n=await Vd(e);return[{config:{id:n.id??"default",name:n.name??"Dev Server",command:n.command??"",cwd:n.cwd??"."},status:n.status,runtime:n.pid?{pid:n.pid,startedAt:n.startedAt??new Date().toISOString(),exitCode:n.exitCode??void 0,previewUrl:n.previewUrl}:void 0,previewUrl:n.previewUrl??n.detectedUrl??void 0,logHistory:(n.logs??[]).map(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}]}catch{return[]}}}async function aO(e,n){try{return await D(V(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await Vd(n);return!e||e==="default"||e===s.id?{config:{id:s.id??"default",name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}:null}catch{return null}}}async function rO(e,n){try{return await D(V(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await Fk({command:""},n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}}}async function oO(e,n){try{return await D(V(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await Uk(n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}}}async function lO(e,n){try{return await D(V(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await Bk(n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}}}async function cO(e,n,s){try{const a=await D(V(`/devserver/${encodeURIComponent(e)}/preview`,s),{method:"POST",body:JSON.stringify({url:n})});return{url:a.url??null,source:a.source??null}}catch{const a=await Hk({url:n},s);return{url:a.previewUrl??a.manualUrl??null,source:"manual"}}}async function dO(e){try{return(await D(V("/devserver/detect",e))).candidates??[]}catch{try{return(await zk(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function uO(e,n){return js(V(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function Gr(e,n,s=25e3){const a=setInterval(()=>{IN(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(a)}}}function qk(e,n){return js(V(`/planning/${encodeURIComponent(e)}/stream`,n))}function Vk(e,n){return js(V(`/agents/onboarding/${encodeURIComponent(e)}/stream`,n))}function mO(e,n,s,a){const r=Vk(e,n),o=Wa(r,{events:{thinking:l=>{try{s.onThinking?.(JSON.parse(l.data))}catch{s.onThinking?.(l.data)}},question:l=>{try{s.onQuestion?.(JSON.parse(l.data))}catch{}},summary:l=>{try{s.onSummary?.(JSON.parse(l.data))}catch{}},error:l=>{try{const c=JSON.parse(l.data);s.onError?.(c.message||c)}catch{s.onError?.(l.data||"Stream error")}},complete:()=>{s.onComplete?.()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:l=>s.onError?.(l)});return{close:o.close,isConnected:o.isConnected}}function Wk(e,n,s,a){const r=qk(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Wa(r,{onOpen:()=>{c(),o=Gr(e,n)},onMessage:u=>{u.data.startsWith(":")},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},question:u=>{try{s.onQuestion?.(JSON.parse(u.data))}catch(m){console.error("[planning] Failed to parse question event:",m)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(m){console.error("[planning] Failed to parse summary event:",m)}},error:u=>{try{const m=JSON.parse(u.data);s.onError?.(m.message||m)}catch{s.onError?.(u.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{c(),s.onError?.(u)}});return l={close:()=>{c(),d.close()},isConnected:d.isConnected},l}function Jr(e,n){const s=new URLSearchParams;n?.scope&&s.set("scope",n.scope),n?.projectId&&s.set("projectId",n.projectId);const a=s.toString();return a?`${e}?${a}`:e}function Kk(e){return D(Jr("/routines",e))}function Gk(e,n){return D(Jr("/routines",n),{method:"POST",body:JSON.stringify(e)})}function zu(e,n,s){return D(Jr(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function Jk(e,n){await D(Jr(`/routines/${e}`,n),{method:"DELETE"})}function Yk(e,n){return D(Jr(`/routines/${e}/trigger`,n),{method:"POST"})}function Fu(e){const n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e.limit)),e?.since!==void 0&&n.set("since",e.since),e?.type!==void 0&&n.set("type",e.type),e?.projectId&&n.set("projectId",e.projectId);const s=n.size>0?`?${n.toString()}`:"";return D(`/activity${s}`)}function Qk(e){const n=V("/activity",e);return D(n,{method:"DELETE"})}function Yr(e){return D(V("/workflow-steps",e))}function Uu(e,n){return D(V("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function Xk(e,n,s){return D(V(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Zk(e,n){return D(V(`/workflow-steps/${e}`,n),{method:"DELETE"})}function Bu(e,n){return D(V(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function ej(e,n){return D(V(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function tj(){return D("/workflow-step-templates")}function nj(e,n){return D(V(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function Lr(e){return D(V("/scripts",e))}function sj(e,n,s){return D(V("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function ij(e,n){return D(V(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function uf(e,n,s){return(await D(V("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const fo={RATE_LIMIT:"Too many refinement requests. Please wait an hour.",INVALID_TYPE:"Invalid refinement option selected.",NETWORK:"Failed to refine text. Please try again."};function mf(e){if(!(e instanceof Error))return fo.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?fo.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?fo.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:fo.NETWORK}function aj(e,n){return D(V("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function rj(e,n,s){return D(V(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function oj(e,n){return js(V(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function lj(e,n,s,a){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=Wa(oj(e,n),{onOpen:()=>{l(),r=Gr(e,n)},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},subtasks:d=>{try{s.onSubtasks?.(JSON.parse(d.data))}catch(u){console.error("[subtasks] Failed to parse subtasks event:",u)}},error:d=>{try{const u=JSON.parse(d.data),m=typeof u=="string"&&u.length>0?u:null;s.onError?.(m||"Stream error")}catch{s.onError?.("Stream error")}o?.close()},complete:()=>{s.onComplete?.(),o?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{l(),s.onError?.(d)}});return o={close:()=>{l(),c.close()},isConnected:c.isConnected},o}function cj(e,n,s,a){return D(V("/subtasks/create-tasks",a),{method:"POST",body:JSON.stringify({sessionId:e,parentTaskId:s,subtasks:n.map(r=>({tempId:r.id,title:r.title,description:r.description,size:r.suggestedSize,dependsOn:r.dependsOn}))})})}function hf(e,n,s){return D(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 dj(e,n,s){if(!n||n===s)return e;const a="/api",r=e.startsWith(a)?e.slice(a.length):e;return`/proxy/${encodeURIComponent(n)}${r}`}function Ml(e,n){const{nodeId:s,localNodeId:a,...r}=n??{},o=dj(e,s,a);return D(o,r)}function da(e,n){const s=new URLSearchParams;e?.state&&s.set("state",e.state),e?.role&&s.set("role",e.role),e?.includeEphemeral===!0&&s.set("includeEphemeral","true"),n&&s.set("projectId",n);const a=s.size>0?`?${s.toString()}`:"";return D(`/agents${a}`)}function pd(e,n){return D(V(`/agents/${encodeURIComponent(e)}`,n))}function uj(e,n){return D(V("/agents",n),{method:"POST",body:JSON.stringify(e)})}function mj(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function hO(e,n){return D(V(`/agents/${encodeURIComponent(e)}/upgrade-heartbeat-procedure`,n),{method:"POST"})}function pO(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function fO(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function gO(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function bO(e,n){return D(V(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function xO(e,n,s){const a=`path=${encodeURIComponent(n)}`;return D(V(`/agents/${encodeURIComponent(e)}/memory/file?${a}`,s))}function vO(e,n,s,a){return D(V(`/agents/${encodeURIComponent(e)}/memory/file`,a),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function hj(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function pj(e,n){return D(V(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function yO(e,n,s){const a=new URLSearchParams;n!==void 0&&a.set("limit",String(n)),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return D(`/agents/${encodeURIComponent(e)}/runs${r}`)}function wO(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function kO(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function jO(e,n,s){const a=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return D(V(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:a,triggerDetail:r})})}function NO(e,n){return D(V(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function fj(e){return D(V("/agents/stats",e))}function SO(e,n){return D(V(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function CO(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeEphemeral&&s.set("includeEphemeral","true");const a=s.toString();return D(`/agents/org-tree${a?`?${a}`:""}`)}function EO(e,n){return D(V(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function Hu(e,n,s){return D(V(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function MO(e,n){return D(V(`/agents/${encodeURIComponent(e)}/tasks`,n))}function _O(){return D("/agents/companies")}function AO(e,n){return D(V("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function PO(e,n){return D(V("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function RO(e,n){return D(V(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function TO(e){return D(V("/backups",e))}function IO(e){return D(V("/backups",e),{method:"POST"})}function $O(e,n){const s=V("/settings/export",n),a=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return D(a)}function DO(e,n,s){return D(V("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}function qu(){return D("/projects/across-nodes")}function Er(e,n){D("/_perf/dashboard-load",{method:"POST",body:JSON.stringify({source:e,message:n})}).catch(()=>{})}function sl(){return D("/nodes")}function LO(){return D("/docker-nodes")}function OO(e){return D("/docker-nodes",{method:"POST",body:JSON.stringify(e)})}function gj(e){return D("/nodes",{method:"POST",body:JSON.stringify(e)})}function bj(e,n){return D(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function xj(e){return D(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function vj(e){const n=await D(`/nodes/${encodeURIComponent(e)}/health-check`,{method:"POST"});return{nodeId:n.nodeId??e,status:n.status,responseTimeMs:n.responseTimeMs,error:n.error,checkedAt:n.checkedAt??new Date().toISOString()}}function zO(e,n,s,a){const r=s&&s!==a?s:void 0,o=new URLSearchParams;e&&o.set("path",e),n&&o.set("showHidden","true"),r&&o.set("nodeId",r);const l=Ta();l&&o.set("fn_token",l);const c=o.toString(),d=`/browse-directory${c?`?${c}`:""}`;return D(d)}function yj(e){return D("/projects",{method:"POST",body:JSON.stringify(e)})}function pf(e){return D(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function Vu(e){return D(`/projects/${encodeURIComponent(e)}/health`)}function wj(e){return D(V("/executor/stats",e))}function kj(e){return D(V("/system-stats",e))}function jj(e){return D(V("/kill-vitest",e),{method:"POST"})}function Wu(e){const n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e.limit)),e?.since&&n.set("since",e.since),e?.projectId&&n.set("projectId",e.projectId),e?.type&&n.set("type",e.type);const s=n.size>0?`?${n.toString()}`:"";return D(`/activity-feed${s}`)}function Nj(e){return D(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function Sj(e){return D(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function FO(){return D("/global-concurrency")}function UO(e){return D("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function Cj(e,n){return D(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function ff(e,n,s){const a=new URLSearchParams;n&&a.set("worktree",n),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return D(`/tasks/${encodeURIComponent(e)}/diff${r}`)}function Ej(e){return D(V("/missions",e))}function Mj(e,n){return D(V("/missions",n),{method:"POST",body:JSON.stringify(e)})}function gf(e,n){return D(V(`/missions/${encodeURIComponent(e)}`,n))}function _j(e,n,s){return D(V(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Aj(e,n){return D(V(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Pj(e,n,s){const a=new URLSearchParams;a.set("limit",String(n.limit)),n?.offset!==void 0&&a.set("offset",String(n.offset));const r=a.size>0?`?${a.toString()}`:"";return D(V(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function Rj(e){return D(V("/missions/health",e))}function Tj(e,n,s){return D(V(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function Ij(e,n,s){return D(V(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function $j(e,n){return D(V(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Dj(e,n,s){return D(V(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function Lj(e,n,s){return D(V(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Oj(e,n){return D(V(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function zj(e,n){return D(V(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function Fj(e,n,s){return D(V(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function Uj(e,n,s){return D(V(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Bj(e,n){return D(V(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Hj(e,n,s){return D(V(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function qj(e,n){return D(V(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function Vj(e,n,s,a){return D(V(`/missions/features/${encodeURIComponent(e)}/triage`,a),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s})})}function Wj(e,n){return D(V(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST"})}function Jl(e,n){return D(V(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function Kj(e,n,s){return D(V(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function Gj(e,n,s){return D(V(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Jj(e,n,s){return D(V(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function Yj(e,n,s){return D(V(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function Qj(e,n){return D(V(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function Yl(e,n){return D(V(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function Ku(e,n){return D(V(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function Xj(e,n){return D(V(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function Gu(e,n){return D(V(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function Zj(e,n,s){const a=new URLSearchParams;a.set("limit",String(n.limit)),n?.offset!==void 0&&a.set("offset",String(n.offset));const r=a.size>0?`?${a.toString()}`:"";return D(V(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function eN(e,n){return D(V(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function tN(e,n){return D(V(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function nN(e,n){return D(V(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function sN(e,n){return D(V(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function iN(e,n,s){return D(V(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function aN(e,n,s){return D(V("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function rN(e,n,s,a){return D(V("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function oN(e,n,s){return D(V(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function bf(e,n,s){return D(V("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function lN(e,n,s){return D(V("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function cN(e,n,s,a){const r=js(V(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Wa(r,{onOpen:()=>{c(),o=Gr(e,n)},onMessage:u=>{u.data.startsWith(":")},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},question:u=>{try{s.onQuestion?.(JSON.parse(u.data))}catch(m){console.error("[mission-interview] Failed to parse question event:",m)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(m){console.error("[mission-interview] Failed to parse summary event:",m)}},error:u=>{try{const m=JSON.parse(u.data);s.onError?.(m.message||m)}catch{s.onError?.(u.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{c(),s.onError?.(u)}});return l={close:()=>{c(),d.close()},isConnected:d.isConnected},l}function Qr(e,n,s){return V(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function Xr(e,n,s){return V(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function dN(e,n){return D(Qr(e,"/start",n),{method:"POST"})}function uN(e,n,s,a){return D(Qr(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function mN(e,n,s,a){const r=js(Qr(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Wa(r,{onOpen:()=>{c(),o=Gr(e,n)},onMessage:u=>{u.data.startsWith(":")},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},question:u=>{try{s.onQuestion?.(JSON.parse(u.data))}catch(m){console.error("[milestone-interview] Failed to parse question event:",m)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(m){console.error("[milestone-interview] Failed to parse summary event:",m)}},error:u=>{try{const m=JSON.parse(u.data);s.onError?.(m.message||m)}catch{s.onError?.(u.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{c(),s.onError?.(u)}});return l={close:()=>{c(),d.close()},isConnected:d.isConnected},l}function hN(e,n,s){return D(Qr(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function pN(e,n){return D(Qr(e,"/skip",n),{method:"POST"})}function fN(e,n){return D(Xr(e,"/start",n),{method:"POST"})}function gN(e,n,s,a){return D(Xr(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function bN(e,n,s,a){const r=js(Xr(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Wa(r,{onOpen:()=>{c(),o=Gr(e,n)},onMessage:u=>{u.data.startsWith(":")},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},question:u=>{try{s.onQuestion?.(JSON.parse(u.data))}catch(m){console.error("[slice-interview] Failed to parse question event:",m)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(m){console.error("[slice-interview] Failed to parse summary event:",m)}},error:u=>{try{const m=JSON.parse(u.data);s.onError?.(m.message||m)}catch{s.onError?.(u.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{c(),s.onError?.(u)}});return l={close:()=>{c(),d.close()},isConnected:d.isConnected},l}function xN(e,n,s){return D(Xr(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function vN(e,n){return D(Xr(e,"/skip",n),{method:"POST"})}async function yN(e,n){try{return await D(V(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function BO(e){return D(V("/roadmaps",e))}function HO(e,n){return D(V("/roadmaps",n),{method:"POST",body:JSON.stringify(e)})}function qO(e,n){return D(V(`/roadmaps/${encodeURIComponent(e)}`,n))}function VO(e,n,s){return D(V(`/roadmaps/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function WO(e,n){return D(V(`/roadmaps/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function KO(e,n,s){return D(V(`/roadmaps/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function GO(e,n,s){return D(V(`/roadmaps/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function JO(e,n){return D(V(`/roadmaps/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function YO(e,n,s){return D(V(`/roadmaps/milestones/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function QO(e,n,s){return D(V(`/roadmaps/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function XO(e,n){return D(V(`/roadmaps/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function ZO(e,n,s){return D(V(`/roadmaps/${encodeURIComponent(e)}/milestones/reorder`,s),{method:"POST",body:JSON.stringify({orderedMilestoneIds:n})})}function ez(e,n,s){return D(V(`/roadmaps/milestones/${encodeURIComponent(e)}/features/reorder`,s),{method:"POST",body:JSON.stringify({orderedFeatureIds:n})})}function tz(e,n,s,a){return D(V(`/roadmaps/features/${encodeURIComponent(e)}/move`,a),{method:"POST",body:JSON.stringify({targetMilestoneId:n,targetIndex:s})})}function nz(e,n){return D(V(`/roadmaps/${encodeURIComponent(e)}/handoff`,n))}function sz(e,n,s,a){return D(V(`/roadmaps/${encodeURIComponent(e)}/suggestions/milestones`,a),{method:"POST",body:JSON.stringify({goalPrompt:n.trim(),...s!==void 0?{count:s}:{}})})}function iz(e,n,s){return D(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 wN(e){return D(V("/todos",e))}function kN(e,n){const s={title:e};return D(V("/todos",n),{method:"POST",body:JSON.stringify(s)})}function jN(e,n,s){const a={title:n};return D(V(`/todos/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(a)})}function NN(e,n){return D(V(`/todos/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function SN(e,n,s){const a={text:n};return D(V(`/todos/${encodeURIComponent(e)}/items`,s),{method:"POST",body:JSON.stringify(a)})}function CN(e,n,s){const a=n;return D(V(`/todos/items/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(a)})}function EN(e,n){return D(V(`/todos/items/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function MN(e,n,s){return D(V(`/todos/${encodeURIComponent(e)}/items/reorder`,s),{method:"POST",body:JSON.stringify({itemIds:n})})}function Da(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function Wd(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeCompleted&&s.set("includeCompleted","1"),n?.includeArchived&&s.set("includeArchived","1");const a=s.toString(),r=await fetch(js(`/ai-sessions${a?`?${a}`:""}`),{headers:Ai()});return r.ok?(await r.json()).sessions??[]:[]}async function _N(e){return D(`/ai-sessions/${encodeURIComponent(e)}/archive`,{method:"POST"})}async function AN(e){return D(`/ai-sessions/${encodeURIComponent(e)}/unarchive`,{method:"POST"})}async function bi(e){const n=await fetch(js(`/ai-sessions/${encodeURIComponent(e)}`),{headers:Ai()});return n.ok?n.json():null}async function PN(e,n){const s=await D(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function RN(e,n){return D(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function TN(e,n){return D(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function xf(e){await fetch(js(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:Ai()})}function IN(e,n){return D(V(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function $N(e,n,s){return D(V(`/ai-sessions/${encodeURIComponent(e)}/draft`,s),{method:"PATCH",body:JSON.stringify(n)})}function DN(e,n){return D(V(`/planning/${encodeURIComponent(e)}/summarize-draft-title`,n),{method:"POST"})}function LN(e,n){const s=new URLSearchParams;s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),e?.unreadOnly&&s.set("unreadOnly","true"),e?.type&&s.set("type",e.type),n&&s.set("projectId",n);const a=s.size>0?`?${s.toString()}`:"";return D(`/messages/inbox${a}`)}function ON(e,n){const s=new URLSearchParams;s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),e?.type&&s.set("type",e.type),n&&s.set("projectId",n);const a=s.size>0?`?${s.toString()}`:"";return D(`/messages/outbox${a}`)}function vf(e){return D(V("/messages/unread-count",e))}function zN(e,n){return D(V("/messages",n),{method:"POST",body:JSON.stringify(e)})}function FN(e,n){return D(V(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function UN(e){return D(V("/messages/read-all",e),{method:"POST"})}function BN(e,n){return D(V(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function HN(e,n,s){const a=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return D(V(a,s))}function qN(e,n){return D(V(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function az(e,n,s){const a=new URLSearchParams;a.set("limit",String(n)),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return D(`/agents/${encodeURIComponent(e)}/reflections${r}`)}function rz(e,n){return D(V(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function oz(e,n,s){const a=new URLSearchParams;s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return D(`/agents/${encodeURIComponent(e)}/performance${r}`)}function lz(e,n,s){const a=new URLSearchParams;a.set("limit",String(n.limit)),n?.category&&a.set("category",n.category),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return D(`/agents/${encodeURIComponent(e)}/ratings${r}`)}function cz(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function dz(e,n){return D(V(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function uz(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function mz(e,n){return D(V(`/agents/${encodeURIComponent(e)}/budget`,n))}function hz(e,n){return D(V(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function pz(e){return D(V("/plugins",e))}async function fz(e,n){return D(V("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function gz(e,n){return D(V(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function bz(e,n){return D(V(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function xz(e,n){return D(V(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function vz(e,n){return D(V(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function yz(e,n,s){return D(V(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function wz(e,n){return D(V(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function VN(e){return D(V("/plugins/ui-slots",e))}async function WN(e){return D(V("/plugins/dashboard-views",e))}async function kz(e){return D(V("/plugins/runtimes",e))}async function KN(e){return(await D(V("/skills/discovered",e))).skills}async function jz(e,n,s){return D(V("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function Nz(e,n,s){const a=new URLSearchParams;e&&a.set("q",e),a.set("limit",String(n));const r=a.size>0?`?${a.toString()}`:"";return D(V(`/skills/catalog${r}`,s))}async function Sz(e,n){return(await D(V(`/skills/${encodeURIComponent(e)}/content`,n))).content}function Ju(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const a=s.toString();return D(`/chat/sessions${a?`?${a}`:""}`)}async function GN(e,n){const s=e.agentId.trim();if(!s)throw new Error("agentId is required");const a=e.modelProvider?.trim(),r=e.modelId?.trim();if(a&&!r||!a&&r)throw new Error("Both modelProvider and modelId must be provided together, or neither should be provided");const o=new URLSearchParams;return o.set("lookup","resume"),o.set("agentId",s),n&&o.set("projectId",n),a&&r&&(o.set("modelProvider",a),o.set("modelId",r)),{session:(await D(`/chat/sessions?${o.toString()}`)).sessions[0]??null}}function JN(e,n){return D(V("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function YN(e,n){return D(V(`/chat/sessions/${encodeURIComponent(e)}`,n))}function Cz(e,n,s){return D(V(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Ez(e,n){return D(V(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Ql(e,n,s){const a=new URLSearchParams;n?.limit!==void 0&&a.set("limit",String(n.limit)),n?.offset!==void 0&&a.set("offset",String(n.offset)),n?.before&&a.set("before",n.before);const r=a.toString();return D(V(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function QN(e,n){return D(V(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function XN(e,n,s,a,r,o){const l=js(V(`/chat/sessions/${encodeURIComponent(e)}/messages`,r)),c=new AbortController;let d=!1;const u=(m,h)=>{if(m)switch(m){case"thinking":try{s.onThinking?.(JSON.parse(h))}catch{s.onThinking?.(h)}break;case"text":try{s.onText?.(JSON.parse(h))}catch{s.onText?.(h)}break;case"tool_start":try{s.onToolStart?.(JSON.parse(h))}catch{}break;case"tool_end":try{s.onToolEnd?.(JSON.parse(h))}catch{}break;case"done":try{s.onDone?.(JSON.parse(h))}catch{s.onDone?.({messageId:""})}break;case"error":try{const f=JSON.parse(h);s.onError?.(f.message||f)}catch{s.onError?.(h||"Stream error")}break}};return(async()=>{try{const m=Array.isArray(a)&&a.length>0,h=m?(()=>{const j=new FormData;return j.append("content",n),a.forEach(C=>j.append("attachments",C)),j})():JSON.stringify({content:n}),f=await fetch(l,{method:"POST",headers:m?Ai():Ai({"Content-Type":"application/json"}),body:h,signal:c.signal});if(!f.ok){const j=await f.text();let C=`Request failed: ${f.status}`;try{C=JSON.parse(j).error||C}catch{}s.onError?.(C);return}if(!f.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected");const p=f.body.getReader(),g=new TextDecoder;let x="",v="",b=[];const y=(j,C=!1)=>{x+=j;const A=x.split(`
638
+ `);x=A.pop()||"",C&&x.length>0&&(A.push(x),x="");for(const N of A){const S=N.endsWith("\r")?N.slice(0,-1):N;if(S.startsWith("event:"))v=S.slice(6).trim();else if(S.startsWith("data:")){const _=S.slice(5);b.push(_.startsWith(" ")?_.slice(1):_)}else if(S===""){const _=b.join(`
639
+ `);u(v,_),v="",b=[]}}if(C&&v&&b.length>0){const N=b.join(`
640
+ `);u(v,N),v="",b=[]}};for(;;){const{done:j,value:C}=await p.read();if(j){y(g.decode(),!0);break}y(g.decode(C,{stream:!0}))}}catch(m){if(m instanceof DOMException&&m.name==="AbortError"){d||s.onError?.("Connection aborted");return}if(d)return;s.onError?.(m instanceof Error?m.message:"Connection error")}})(),{close:()=>{d=!0,c.abort()},isConnected:()=>!d}}function Mz(e={},n){const s=new URLSearchParams;e.category&&s.set("category",e.category),e.status&&s.set("status",e.status),e.runId&&s.set("runId",e.runId),e.limit!==void 0&&s.set("limit",String(e.limit)),e.offset!==void 0&&s.set("offset",String(e.offset));const a=s.size>0?`?${s.toString()}`:"";return D(V(`/insights${a}`,n))}function _z(e,n){return D(V(`/insights/${encodeURIComponent(e)}/dismiss`,n),{method:"POST"})}function Az(e="manual",n,s){return D(V("/insights/run",s),{method:"POST",body:JSON.stringify({trigger:e,inputMetadata:n})})}function Pz(e){return D(V("/insights/runs",e))}function Rz(e,n){return D(V(`/insights/${encodeURIComponent(e)}/create-task`,n),{method:"POST"})}function Tz(e={},n){const s=new URLSearchParams;e.q&&s.set("q",e.q),e.status&&s.set("status",e.status),e.limit!==void 0&&s.set("limit",String(e.limit));const a=s.size>0?`?${s.toString()}`:"";return D(V(`/research/runs${a}`,n))}function Iz(e,n){return D(V("/research/runs",n),{method:"POST",body:JSON.stringify(e)})}function $z(e,n){return D(V(`/research/runs/${encodeURIComponent(e)}`,n))}function Dz(e,n){return D(V(`/research/runs/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function Lz(e,n){return D(V(`/research/runs/${encodeURIComponent(e)}/retry`,n),{method:"POST"})}function Oz(e,n,s){return D(V(`/research/runs/${encodeURIComponent(e)}/export?format=${encodeURIComponent(n)}`,s))}function zz(e,n,s){const a=n.findingId??"finding-1";return D(V(`/research/runs/${encodeURIComponent(e)}/findings/${encodeURIComponent(a)}/task`,s),{method:"POST",body:JSON.stringify({title:n.title,description:n.description,priority:n.priority,attachExport:n.attachExport})})}function Fz(e,n,s){const a=n.findingId??"finding-1";return D(V(`/research/runs/${encodeURIComponent(e)}/findings/${encodeURIComponent(a)}/tasks/${encodeURIComponent(n.taskId)}/enrich`,s),{method:"POST",body:JSON.stringify({attachExport:n.attachExport})})}function ZN(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 e1({node:e,showDetails:n=!1}){if(!e||e.type==="local")return t.jsx("div",{className:"node-status-indicator node-status-indicator--local",children:t.jsx("span",{className:"node-status-indicator__label",children:"Local"})});const{label:s,dotClass:a}=ZN(e.status),r=e.status==="connecting";return t.jsxs("div",{className:"node-status-indicator node-status-indicator--remote",children:[t.jsx("span",{className:`node-status-indicator__dot ${a}`,children:r&&t.jsx("span",{className:"node-status-indicator__spinner"})}),t.jsx("span",{className:"node-status-indicator__name",children:e.name}),n&&t.jsxs("span",{className:"node-status-indicator__details",children:[e.type," · ",s]})]})}function t1(e){return e.charAt(0).toUpperCase()+e.slice(1)}function ia({status:e,showLabel:n=!1,className:s,compact:a=!1}){const r=t1(e);return t.jsxs("span",{className:`node-health-dot${a?" node-health-dot--compact":""}${s?` ${s}`:""}`,title:r,"aria-label":`Node status: ${r}`,children:[t.jsx("span",{className:`status-dot status-dot--${e}`}),n?t.jsx("span",{className:"node-health-dot__label",children:r}):null]})}const Yu=new Map,n1=6e4;function yf(e){const[n,s]=i.useState([]),[a,r]=i.useState(!0),[o,l]=i.useState(null),c=i.useRef(!1),d=i.useRef(!1),u=i.useCallback(m=>n.filter(h=>h.slot.slotId===m),[n]);return i.useEffect(()=>{const m=e??"default";let h=!1;async function f(){const p=Yu.get(m);if(p&&Date.now()<p.expiresAt){if(h||d.current)return;s(p.slots),r(!1);return}!c.current&&r(!0),l(null);try{const x=await VN(e);if(h||d.current)return;Yu.set(m,{slots:x,expiresAt:Date.now()+n1}),s(x),c.current=!0}catch(x){if(h||d.current)return;l(x instanceof Error?x.message:"Failed to fetch UI slots"),c.current=!0}finally{!h&&!d.current&&r(!1)}}return f(),()=>{h=!0}},[e]),i.useEffect(()=>{c.current=!1,d.current=!1},[e]),i.useEffect(()=>()=>{d.current=!0},[]),i.useMemo(()=>({slots:n,getSlotsForId:u,loading:a,error:o}),[n,u,a,o])}function Oi({slotId:e,projectId:n,pluginIds:s}){const{getSlotsForId:a,loading:r,error:o}=yf(n);if(r||o||!e)return null;const l=a(e).filter(c=>s&&s.length>0?s.includes(c.pluginId):!0);return l.length===0?null:t.jsx(Cl,{level:"page",children:t.jsx(t.Fragment,{children:l.map((c,d)=>t.jsxs("section",{className:"plugin-slot-shell","data-plugin-slot":!0,"data-slot-id":c.slot.slotId,"data-plugin-id":c.pluginId,"aria-label":c.slot.label,children:[t.jsx("p",{className:"plugin-slot-shell__title",children:c.slot.label}),t.jsx("p",{className:"plugin-slot-shell__message",children:"Extension content available."})]},`${c.pluginId}-${c.slot.slotId}-${d}`))})})}function s1(){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 Pi(){const[e,n]=i.useState(s1);return i.useEffect(()=>{if(typeof window>"u")return;const s=window.matchMedia("(max-width: 768px)"),a=window.matchMedia("(min-width: 769px) and (max-width: 1024px)"),r=()=>{s.matches?n("mobile"):a.matches?n("tablet"):n("desktop")};return s.addEventListener("change",r),a.addEventListener("change",r),()=>{s.removeEventListener("change",r),a.removeEventListener("change",r)}},[]),e}function Ka(e){return e.replace(/\\/g,"/")}function Kd(e){return e.replace(/[\\/]+$/g,"")}function Gd(e){const n=Ka(Kd(e));return n?n.split("/").filter(Boolean):[]}function Jd(e){const n=Ka(Kd(e));if(!n)return e;const s=n.split("/").filter(Boolean);return s[s.length-1]||n}function wf(e,n){const s=Gd(e);return s.length===0?Ka(e):s.slice(-2).join("/")}function i1(e){const n=Ka(Kd(e)),s=n.lastIndexOf("/");return s<0?"":n.slice(0,s+1)}function a1(e,n){return!e||e==="."?n:[...Gd(e),n].join("/")}function r1(e){const n=Gd(e);return n.length===0?".":(n.pop(),n.length===0?".":n.join("/"))}function Uz(e){const n=Ka(e),s=n.match(/^([A-Za-z]:)(?:\/(.*))?$/);if(s){const r=`${s[1]}/`,o=(s[2]??"").split("/").filter(Boolean),l=[{label:s[1],path:r}];for(let c=0;c<o.length;c+=1)l.push({label:o[c],path:`${r}${o.slice(0,c+1).join("/")}`});return l}if(n.startsWith("/")){const r=n.split("/").filter(Boolean),o=[{label:"/",path:"/"}];for(let l=0;l<r.length;l+=1)o.push({label:r[l],path:`/${r.slice(0,l+1).join("/")}`});return o}const a=n.split("/").filter(Boolean);return a.map((r,o)=>({label:r,path:a.slice(0,o+1).join("/")}))}const o1="dependency-graph-positions";function kf(e){return`kb:${e??"default"}:${o1}`}function l1(e){if(typeof window>"u")return{};try{const n=window.localStorage.getItem(kf(e));return n?JSON.parse(n)??{}:{}}catch{return{}}}function c1(e,n){typeof window>"u"||window.localStorage.setItem(kf(e),JSON.stringify(n))}const d1=new Set(["triage","todo","in-progress","in-review"]),va=18,Gi=9,u1=3,m1=4,Qu=.5,go=2,h1=2,bo=.4,xo=2,p1=.002,f1=768;function vo(e,n){return Math.hypot(e.x-n.x,e.y-n.y)}function g1(){return typeof window>"u"?!1:window.matchMedia(`(max-width: ${f1}px)`).matches}function b1({context:e}){const[n,s]=i.useState(1),[a,r]=i.useState({x:0,y:0}),[o,l]=i.useState({}),[c,d]=i.useState(null),[u,m]=i.useState(null),h=i.useMemo(()=>l1(e.projectId),[e.projectId]),f=i.useRef(null),p=i.useRef(new Map),g=i.useRef(null),x=i.useRef(null),v=i.useRef(!1),b=i.useMemo(()=>e.tasks.filter(z=>d1.has(z.column)),[e.tasks]),y=i.useMemo(()=>b.map((z,k)=>{const I=o[z.id]??h[z.id];return{task:z,x:I?.x??k%4*(va+u1),y:I?.y??Math.floor(k/4)*(Gi+m1)}}),[o,h,b]),j=i.useMemo(()=>new Map(y.map(z=>[z.task.id,z])),[y]),C=i.useMemo(()=>{const z=[];return y.forEach(k=>{(k.task.dependencies??[]).forEach(I=>{const $=j.get(I);$&&z.push({from:I,to:k.task.id,x1:$.x+va,y1:$.y+Gi/2,x2:k.x,y2:k.y+Gi/2})})}),z},[j,y]),A=i.useMemo(()=>{if(y.length===0)return{minX:0,minY:0,width:va*2,height:Gi*2};const z=Math.min(...y.map(w=>w.x))-go,k=Math.min(...y.map(w=>w.y))-go,I=Math.max(...y.map(w=>w.x+va))+go,$=Math.max(...y.map(w=>w.y+Gi))+go;return{minX:z,minY:k,width:Math.max(va*2,I-z),height:Math.max(Gi*2,$-k)}},[y]),N=i.useMemo(()=>y.map(z=>({...z,renderX:z.x-A.minX,renderY:z.y-A.minY})),[A.minX,A.minY,y]),S=i.useMemo(()=>C.map(z=>({...z,renderX1:z.x1-A.minX,renderY1:z.y1-A.minY,renderX2:z.x2-A.minX,renderY2:z.y2-A.minY})),[A.minX,A.minY,C]),_=i.useMemo(()=>{const z=new Map,k=new Map;return C.forEach(I=>{z.set(I.from,(z.get(I.from)??new Set).add(I.to)),k.set(I.to,(k.get(I.to)??new Set).add(I.from))}),{downstream:z,upstream:k}},[C]),T=u??c,M=i.useMemo(()=>{if(!T)return null;const z=new Set([T]),k=(I,$)=>{const w=[I];for(;w.length>0;){const H=w.shift();H&&($.get(H)??new Set).forEach(K=>{z.has(K)||(z.add(K),w.push(K))})}};return k(T,_.downstream),k(T,_.upstream),z},[_.downstream,_.upstream,T]),E=i.useCallback(()=>{const z=f.current;if(!z)return;const k=Number.parseFloat(globalThis.getComputedStyle(document.documentElement).fontSize)||16,I=A.width*k,$=A.height*k,w=h1*k,H=Math.max(1,z.clientWidth-w*2),K=Math.max(1,z.clientHeight-w*2),pe=Math.min(xo,Math.max(bo,Math.min(H/I,K/$))),le=(z.clientWidth-I*pe)/(2*k*pe),B=(z.clientHeight-$*pe)/(2*k*pe);s(pe),r({x:le,y:B})},[A.width,A.height]);i.useEffect(()=>{if(v.current||!g1()||y.length===0)return;const z=f.current;z&&(z.clientWidth===0||z.clientHeight===0||(v.current=!0,requestAnimationFrame(()=>{E()})))},[E,y.length]);const L=(z,k)=>{l(I=>({...I,[z]:k})),c1(e.projectId,{...h,...o,[z]:k})},F=(z,k)=>{if(d($=>$===z?null:z),k.button!==0)return;k.preventDefault(),k.stopPropagation();const I=j.get(z);I&&(p.current.set(k.pointerId,{x:k.clientX,y:k.clientY}),g.current={kind:"node",taskId:z,startPointer:{x:k.clientX,y:k.clientY},startNode:{x:I.x,y:I.y},moved:!1})},R=z=>{if(z.button===0){if(p.current.set(z.pointerId,{x:z.clientX,y:z.clientY}),p.current.size===2){g.current=null;const[k,I]=Array.from(p.current.values()),$=vo(k,I);x.current={startDistance:$,startScale:n};return}g.current={kind:"pan",startPointer:{x:z.clientX,y:z.clientY},startPan:a,moved:!1}}},P=z=>{if(p.current.has(z.pointerId)&&p.current.set(z.pointerId,{x:z.clientX,y:z.clientY}),p.current.size>=2&&x.current){const[w,H]=Array.from(p.current.values()),pe=vo(w,H)/x.current.startDistance,le=Math.min(xo,Math.max(bo,x.current.startScale*pe));s(le);return}const k=g.current;if(!k)return;const I={x:(z.clientX-k.startPointer.x)/16,y:(z.clientY-k.startPointer.y)/16};if(k.kind==="node"){if(vo({x:0,y:0},I)>Qu&&!k.moved&&(k.moved=!0),!k.moved)return;l(H=>({...H,[k.taskId]:{x:k.startNode.x+I.x/n,y:k.startNode.y+I.y/n}}));return}vo({x:0,y:0},I)>Qu&&!k.moved&&(k.moved=!0),k.moved&&r({x:k.startPan.x+I.x,y:k.startPan.y+I.y})},O=z=>{if(p.current.delete(z.pointerId),x.current){p.current.size<2&&(x.current=null);return}const k=g.current;if(g.current=null,!!k&&k.kind==="node"){const I=j.get(k.taskId);if(!I)return;if(!k.moved){e.openTaskDetail(I.task);return}L(k.taskId,{x:I.x,y:I.y})}},q=z=>{p.current.delete(z.pointerId),x.current=null,g.current=null},Z=z=>{z.preventDefault();const k=f.current;if(!k)return;const I=Number.parseFloat(globalThis.getComputedStyle(document.documentElement).fontSize)||16,$=-z.deltaY*p1,w=Math.min(xo,Math.max(bo,n*(1+$))),H=k.getBoundingClientRect(),K=z.clientX-H.left,pe=z.clientY-H.top,le=w/n,B=K/I*(1-le)/n,ye=pe/I*(1-le)/n;s(w),r(U=>({x:U.x+B*w/n,y:U.y+ye*w/n}))};return t.jsxs("section",{className:"dependency-graph-view",children:[t.jsxs("div",{className:"dependency-graph-controls",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>s(z=>Math.min(z+.1,xo)),children:"Zoom In"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>s(z=>Math.max(z-.1,bo)),children:"Zoom Out"}),t.jsx("button",{className:"btn btn-sm",onClick:E,children:"Fit"})]}),t.jsx("div",{className:"dependency-graph-canvas",ref:f,onPointerDown:R,onPointerMove:P,onPointerUp:O,onPointerCancel:q,onWheel:Z,children:b.length===0?t.jsx("div",{className:"dependency-graph-empty",children:t.jsx("p",{children:"No tasks to display. Tasks in Triage, Todo, In Progress, or In Review columns will appear here."})}):t.jsxs("div",{className:"dependency-graph-scene",style:{width:`${A.width}rem`,height:`${A.height}rem`,transform:`translate(${a.x}rem, ${a.y}rem) scale(${n})`,transformOrigin:"top left"},children:[t.jsx("svg",{className:"dependency-graph-edges",viewBox:`0 0 ${A.width} ${A.height}`,children:S.map(z=>t.jsx("line",{x1:z.renderX1,y1:z.renderY1,x2:z.renderX2,y2:z.renderY2,className:`dependency-graph-edge${M?M.has(z.from)&&M.has(z.to)?" is-related":" is-dimmed":""}`},`${z.from}-${z.to}`))}),N.map(z=>t.jsx("div",{className:`dependency-graph-node${c===z.task.id?" is-selected":""}${M?M.has(z.task.id)?" is-related":" is-dimmed":""}`,style:{width:`${va}rem`,minHeight:`${Gi}rem`,transform:`translate(${z.renderX}rem, ${z.renderY}rem)`},onPointerDown:k=>F(z.task.id,k),onPointerEnter:()=>m(z.task.id),onPointerLeave:()=>m(k=>k===z.task.id?null:k),children:e.renderTaskCard(z.task)},z.task.id))]})})]})}const x1=[{pluginId:"fusion-plugin-dependency-graph",viewId:"graph",component:b1}];function Mr(e,n){return`plugin:${e}:${n}`}function v1(e){if(!e.startsWith("plugin:"))return null;const[,n,...s]=e.split(":"),a=s.join(":");return!n||!a?null:{pluginId:n,viewId:a}}function y1(e,n){return x1.find(a=>a.pluginId===e&&a.viewId===n)?.component??null}function w1({pluginId:e,viewId:n}){return t.jsxs("section",{className:"card plugin-dashboard-view-missing",children:[t.jsxs("h2",{className:"plugin-dashboard-view-missing-title",children:[t.jsx(Sl,{}),"Plugin view unavailable"]}),t.jsxs("p",{className:"plugin-dashboard-view-missing-description",children:["The dashboard could not resolve ",t.jsxs("code",{children:[e,":",n]})," from the host registry."]})]})}const k1={activity:Fs,bot:Rn,brain:Rr,checksquare:Qo,clock:_i,filetext:Fi,folder:os,gitbranch:Hs,grid3x3:yl,layoutgrid:Ui,mail:sa,map:ld,messagesquare:Ei,monitor:Ra,search:Ci,sparkles:ms,target:ws,workflow:Zo,zap:Xn};function j1(e){return(e??"").trim().toLowerCase().replace(/[-_\s]/g,"")}function il(e){return k1[j1(e)]??yl}const jf={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function N1({projects:e,currentProject:n,onViewAll:s,onSelectProject:a}){const[r,o]=i.useState(!1),l=i.useRef(null);i.useEffect(()=>{if(!r)return;const d=u=>{l.current&&!l.current.contains(u.target)&&o(!1)};return document.addEventListener("mousedown",d),()=>document.removeEventListener("mousedown",d)},[r]),i.useEffect(()=>{if(!r)return;const d=u=>{u.key==="Escape"&&o(!1)};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[r]);const c=i.useCallback(d=>{a?.(d),o(!1)},[a]);return t.jsx("div",{className:"project-selector",ref:l,children:e.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:`project-selector-trigger${r?" project-selector-trigger--open":""}`,onClick:()=>o(d=>!d),title:n?.name?`Switch project (current: ${n.name})`:"Switch project","aria-label":"Switch project","aria-expanded":r,"aria-haspopup":"listbox","data-testid":"project-selector-trigger",children:[t.jsx("span",{className:"project-selector-trigger-label",children:n?.name??"Projects"}),t.jsx(un,{size:12,className:`project-selector-chevron${r?" project-selector-chevron--open":""}`})]}),r&&t.jsxs("div",{className:"project-selector-dropdown",role:"listbox","aria-label":"Select project","data-testid":"project-selector-dropdown",children:[e.map(d=>{const u=n?.id===d.id,m=jf[d.status]?.color;return t.jsxs("button",{className:`project-selector-item${u?" project-selector-item--current":""}`,onClick:()=>c(d),role:"option","aria-selected":u,children:[t.jsx("span",{className:"project-selector-dot",style:{backgroundColor:m||"var(--text-muted)"}}),t.jsxs("div",{className:"project-selector-info",children:[t.jsx("span",{className:"project-selector-name",children:d.name}),t.jsx("span",{className:"project-selector-path",children:wf(d.path)})]}),u&&t.jsx(Yn,{size:14,className:"project-selector-check"})]},d.id)}),t.jsx("div",{className:"project-selector-divider",role:"presentation"}),t.jsx("button",{className:"project-selector-manage",onClick:()=>{s(),o(!1)},"data-testid":"manage-projects-action",children:"Manage Projects"})]})]})})}function Xu({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 S1({onOpenSettings:e,onOpenGitHubImport:n,onOpenPlanning:s,onResumePlanning:a,activePlanningSessionCount:r=0,onOpenUsage:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:d,mailboxUnreadCount:u=0,onOpenSchedules:m,onOpenGitManager:h,onOpenNodes:f,showNodesButton:p,onOpenWorkflowSteps:g,onOpenScripts:x,onRunScript:v,onToggleTerminal:b,onOpenFiles:y,filesOpen:j,onOpenTodos:C,todosOpen:A,todosEnabled:N,globalPaused:S,enginePaused:_,onToggleGlobalPause:T,onToggleEnginePause:M,view:E="board",onChangeView:L,showSkillsTab:F,showAgentsTab:R,searchQuery:P="",onSearchChange:O,projects:q=[],currentProject:Z,onSelectProject:z,onViewAllProjects:k,projectId:I,isElectron:$=!1,mobileNavEnabled:w,availableNodes:H=[],currentNode:K,onSelectNode:pe,isRemote:le=!1,experimentalFeatures:B,pluginDashboardViews:ye=[]}){const U=Pi(),te=U==="mobile",ee=te||U==="tablet",ie=te&&w,[ge,se]=i.useState(!1),[Ae,xe]=i.useState(!1),[Se,qe]=i.useState(!1),[We,Qe]=i.useState(!1),[ve,Oe]=i.useState(!1),[ae,re]=i.useState(!1),[je,Q]=i.useState(!1),[Fe,Je]=i.useState(!1),[be,ze]=i.useState(!1),[tt,kt]=i.useState(!1),[ke,ce]=i.useState(!1),[Te,he]=i.useState({}),[Le,st]=i.useState(!1),[it,lt]=i.useState(-1),[$e,Ue]=i.useState(null),[Xe,wt]=i.useState({}),[Re,xt]=i.useState(!1),Pt=i.useRef(null),Ct=i.useRef(null),Ot=i.useRef(null),zt=i.useRef(null),Nt=i.useRef(null),jt=i.useRef(null),Yt=i.useRef(!1),Bt=i.useRef(null),qt=i.useRef(null),wn=i.useRef(null),mn=i.useRef(null),Xt=i.useRef(null),Vt=i.useRef(null),Ft=i.useRef(null),Zt=i.useRef(null),en=i.useRef(!1),cn=i.useMemo(()=>H.filter(fe=>fe.type==="remote"),[H]),we=cn.length>0,De=i.useMemo(()=>Object.entries(Te).sort(([fe],[ct])=>fe.localeCompare(ct)),[Te]),oe=De.length>0,Pe=De.length+(oe?1:0),Ce=i.useMemo(()=>Object.entries(Xe).sort(([fe],[ct])=>fe.localeCompare(ct)),[Xe]),J=i.useMemo(()=>ye.some(fe=>fe.pluginId==="fusion-plugin-roadmap"),[ye]),Ie=i.useMemo(()=>!!(B?.researchView||N||B?.insights||B?.roadmap&&!J||F||B?.memoryView||B?.devServerView||!ie||ye.some(fe=>fe.view.placement!=="primary")),[B,N,F,ie,ye,J]),de=i.useCallback(()=>{const fe=window.visualViewport;return fe&&fe.width>0&&fe.height>0?{width:fe.width,height:fe.height,offsetTop:fe.offsetTop,offsetLeft:fe.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),Ne=i.useCallback(()=>{const fe=Ft.current;if(!fe)return;const ct=fe.getBoundingClientRect(),hn=Zt.current,{width:zn,height:ue,offsetTop:ut,offsetLeft:yt}=de(),dt=16,at=16,vt=6,Ht=hn?.offsetWidth||Math.max(ct.width,260),Ut=Math.min(Ht,Math.max(zn-dt*2,160)),An=hn?.offsetHeight||280,Wt=Math.min(An,Math.max(ue-at*2,160)),Tt=ct.top-ut,G=ct.bottom-ut,He=ct.right-yt,mt=ue-G,ht=Tt,Et=mt<Wt&&ht>mt,St=Math.min(Math.max(He-Ut,dt),zn-dt-Ut)+yt,sn=Et?Math.max(at+ut,Tt-Wt-vt+ut):Math.min(G+vt+ut,ue+ut-at-Wt);Ue({top:sn,left:St,width:Ut})},[de]),Ye=i.useCallback((fe,ct)=>{v?.(fe,ct),ce(!1),lt(-1)},[v]),ft=i.useCallback(()=>{x?.(),ce(!1),lt(-1)},[x]),tn=i.useCallback(fe=>{switch(fe.key){case"ArrowDown":fe.preventDefault(),Pe>0&&lt(ct=>ct<Pe-1?ct+1:0);break;case"ArrowUp":fe.preventDefault(),Pe>0&&lt(ct=>ct>0?ct-1:Pe-1);break;case"Enter":if(fe.preventDefault(),it>=0)if(it<De.length){const[ct,hn]=De[it];Ye(ct,hn)}else oe&&it===De.length&&ft();break;case"Home":fe.preventDefault(),Pe>0&&lt(0);break;case"End":fe.preventDefault(),Pe>0&&lt(Pe-1);break}},[ft,Ye,it,De,oe,Pe]);i.useEffect(()=>{Yt.current=ve},[ve]),i.useEffect(()=>{en.current=ke},[ke]),i.useEffect(()=>{if(!ve||!ee)return;let fe=!1;return xt(!0),Lr(I).then(ct=>{fe||wt(ct)}).catch(()=>{fe||wt({})}).finally(()=>{fe||xt(!1)}),()=>{fe=!0}},[ve,ee,I]),i.useEffect(()=>{if(!ke||ee)return;let fe=!1;return st(!0),Lr(I).then(ct=>{fe||he(ct)}).catch(()=>{fe||he({})}).finally(()=>{fe||st(!1)}),()=>{fe=!0}},[ke,ee,I]),i.useEffect(()=>{if(!ke)return;const fe=ct=>{Vt.current&&!Vt.current.contains(ct.target)&&ce(!1)};return document.addEventListener("mousedown",fe),()=>document.removeEventListener("mousedown",fe)},[ke]),i.useEffect(()=>{if(!ke)return;const fe=ct=>{ct.key==="Escape"&&(ce(!1),Ft.current?.focus())};return document.addEventListener("keydown",fe),()=>document.removeEventListener("keydown",fe)},[ke]),i.useEffect(()=>{if(ke){lt(-1);const fe=window.setTimeout(()=>Zt.current?.focus(),0);return()=>window.clearTimeout(fe)}Ue(null)},[ke]),i.useEffect(()=>{if(!ke)return;const fe=requestAnimationFrame(()=>{Ne()});return()=>cancelAnimationFrame(fe)},[ke,Le,De.length,oe,Ne]),i.useEffect(()=>{if(!ke)return;const fe=()=>Ne();window.addEventListener("resize",fe),window.addEventListener("scroll",fe,!0);const ct=window.visualViewport;return ct&&(ct.addEventListener("resize",fe),ct.addEventListener("scroll",fe)),()=>{window.removeEventListener("resize",fe),window.removeEventListener("scroll",fe,!0),ct&&(ct.removeEventListener("resize",fe),ct.removeEventListener("scroll",fe))}},[ke,Ne]),i.useEffect(()=>{ee&&(ce(!1),lt(-1))},[ee]);const $t=ge||P.length>0,Rt=(Ae||P.length>0)&&!Se,Dt=(E==="board"||E==="list")&&!te&&O&&!Se&&P.length===0,En=(E==="board"||E==="list")&&!te&&O;i.useEffect(()=>{P===""&&qe(!1)},[P]),i.useEffect(()=>{if(!We)return;const fe=ct=>{Ct.current&&!Ct.current.contains(ct.target)&&Pt.current&&!Pt.current.contains(ct.target)&&Qe(!1)};return document.addEventListener("mousedown",fe),()=>document.removeEventListener("mousedown",fe)},[We]),i.useEffect(()=>{if(!be)return;const fe=ct=>{zt.current&&!zt.current.contains(ct.target)&&Ot.current&&!Ot.current.contains(ct.target)&&ze(!1)};return document.addEventListener("mousedown",fe),()=>document.removeEventListener("mousedown",fe)},[be]),i.useEffect(()=>{if(!ae)return;const fe=ct=>{Bt.current&&!Bt.current.contains(ct.target)&&re(!1)};return document.addEventListener("mousedown",fe),()=>document.removeEventListener("mousedown",fe)},[ae]),i.useEffect(()=>{const fe=ct=>{if(ct.key==="Escape"){if(Je(!1),ze(!1),Yt.current){Oe(!1);return}if(en.current){ce(!1),Ft.current?.focus();return}Qe(!1),se(!1),re(!1),Q(!1)}};return document.addEventListener("keydown",fe),()=>document.removeEventListener("keydown",fe)},[]),i.useEffect(()=>{if(!je)return;const fe=ct=>{qt.current&&!qt.current.contains(ct.target)&&Q(!1)};return document.addEventListener("mousedown",fe),()=>document.removeEventListener("mousedown",fe)},[je]),i.useEffect(()=>{if(!tt)return;const fe=ct=>{Xt.current&&!Xt.current.contains(ct.target)&&kt(!1)};return document.addEventListener("mousedown",fe),()=>document.removeEventListener("mousedown",fe)},[tt]),i.useEffect(()=>{if(!tt)return;const fe=ct=>{ct.key==="Escape"&&kt(!1)};return document.addEventListener("keydown",fe),()=>document.removeEventListener("keydown",fe)},[tt]),i.useEffect(()=>{if(!Fe)return;const fe=ct=>{wn.current&&!wn.current.contains(ct.target)&&mn.current&&!mn.current.contains(ct.target)&&Je(!1)};return document.addEventListener("mousedown",fe),()=>document.removeEventListener("mousedown",fe)},[Fe]);const bn=i.useCallback(()=>{se(fe=>!fe)},[]),Nn=i.useCallback(()=>{xe(!0),qe(!1)},[]),dn=i.useCallback(()=>{xe(!1),qe(!0),O&&O("")},[O]),xn=i.useCallback(()=>{Qe(fe=>!fe)},[]),rn=i.useCallback(fe=>{fe&&fe(),Qe(!1),Oe(!1)},[]),On=i.useCallback(()=>{se(!1),O&&O("")},[O]);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"})]}),te&&q.length>=1&&z&&t.jsxs("div",{className:"mobile-project-switch",ref:qt,children:[t.jsx("button",{className:`mobile-project-switch-trigger${je?" mobile-project-switch-trigger--open":""}`,onClick:()=>Q(fe=>!fe),title:"Switch project","aria-label":"Switch project","aria-expanded":je,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:t.jsx(un,{size:14,className:`mobile-project-switch-chevron${je?" mobile-project-switch-chevron--open":""}`})}),je&&t.jsx("div",{className:"mobile-project-switch-dropdown",role:"listbox","aria-label":"Select project","data-testid":"mobile-project-switch-dropdown",children:q.map(fe=>{const ct=Z?.id===fe.id,hn=jf[fe.status]?.color;return t.jsxs("button",{className:`mobile-project-switch-item${ct?" mobile-project-switch-item--current":""}`,onClick:()=>{z(fe),Q(!1)},role:"option","aria-selected":ct,"data-testid":`mobile-project-switch-item-${fe.id}`,children:[t.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:hn||"var(--text-muted)"}}),t.jsxs("div",{className:"mobile-project-switch-info",children:[t.jsx("span",{className:"mobile-project-switch-name",children:fe.name}),t.jsx("span",{className:"mobile-project-switch-path",children:wf(fe.path)})]}),ct&&t.jsx(Yn,{size:14,className:"mobile-project-switch-check"})]},fe.id)})})]}),!ee&&q.length>=1&&k&&t.jsx(N1,{projects:q,currentProject:Z??null,onViewAll:k,onSelectProject:z}),we&&t.jsxs("div",{className:`header-node-selector${te?" header-node-selector--mobile":""}`,ref:te?void 0:Bt,children:[t.jsx(e1,{node:K??null,showDetails:!te}),!te&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:`btn-icon node-selector-trigger${ae?" node-selector-trigger--open":""}`,onClick:()=>re(fe=>!fe),title:"Switch node","aria-label":"Switch node","aria-expanded":ae,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:t.jsx(Tn,{size:12,className:`node-selector-chevron${ae?" node-selector-chevron--open":""}`})}),ae&&t.jsxs("div",{className:"node-selector-dropdown",role:"listbox","aria-label":"Select node",children:[t.jsxs("button",{className:`node-selector-option${le?"":" node-selector-option--active"}`,onClick:()=>{pe?.(null),re(!1)},role:"option","aria-selected":!le,"data-testid":"node-option-local",children:[t.jsx(ia,{status:"online",compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:"Local"})]}),cn.map(fe=>t.jsxs("button",{className:`node-selector-option${K?.id===fe.id?" node-selector-option--active":""}`,onClick:()=>{pe?.(fe),re(!1)},role:"option","aria-selected":K?.id===fe.id,"data-testid":`node-option-${fe.id}`,children:[t.jsx(ia,{status:fe.status,compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:fe.name}),t.jsx("span",{className:"node-selector-option-status",children:fe.status})]},fe.id))]})]})]})]}),t.jsxs("div",{className:"header-actions",children:[ie&&L&&(E==="board"||E==="list")&&t.jsxs("div",{className:"view-toggle","data-testid":"mobile-view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${E==="board"?" active":""}`,onClick:()=>L("board"),title:"Board view","aria-label":"Board view","aria-pressed":E==="board","data-testid":"mobile-view-toggle-board",children:t.jsx(Ui,{size:16})}),t.jsx("button",{className:`view-toggle-btn${E==="list"?" active":""}`,onClick:()=>L("list"),title:"List view","aria-label":"List view","aria-pressed":E==="list","data-testid":"mobile-view-toggle-list",children:t.jsx(od,{size:16})})]}),O&&te&&(ie||E==="board"||E==="list")&&!$t&&t.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:bn,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:t.jsx(Ci,{size:16})}),Dt&&t.jsx("button",{className:"btn-icon",onClick:Nn,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:t.jsx(Ci,{size:16})}),te&&ie&&o&&t.jsx("button",{className:"btn-icon",onClick:fe=>o(fe.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"mobile-header-usage-btn",children:t.jsx(Fs,{size:16})}),!ie&&L&&t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${E==="board"?" active":""}`,onClick:()=>L("board"),title:"Board view","aria-label":"Board view","aria-pressed":E==="board",children:t.jsx(Ui,{size:16})}),t.jsx("button",{className:`view-toggle-btn${E==="list"?" active":""}`,onClick:()=>L("list"),title:"List view","aria-label":"List view","aria-pressed":E==="list",children:t.jsx(od,{size:16})}),R&&t.jsx("button",{className:`view-toggle-btn${E==="agents"?" active":""}`,onClick:()=>L("agents"),title:"Agents view","aria-label":"Agents view","aria-pressed":E==="agents",children:t.jsx(Rn,{size:16})}),t.jsx("button",{className:`view-toggle-btn${E==="missions"?" active":""}`,onClick:()=>L("missions"),title:"Missions view","aria-label":"Missions view","aria-pressed":E==="missions",children:t.jsx(ws,{size:16})}),t.jsx("button",{className:`view-toggle-btn${E==="chat"?" active":""}`,onClick:()=>L("chat"),title:"Chat view","aria-label":"Chat view","aria-pressed":E==="chat",children:t.jsx(Ei,{size:16})}),t.jsx("button",{className:`view-toggle-btn${E==="documents"?" active":""}`,onClick:()=>L("documents"),title:"Documents view","aria-label":"Documents view","aria-pressed":E==="documents",children:t.jsx(Fi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${E==="mailbox"?" active":""}`,onClick:()=>L("mailbox"),title:"Mailbox view","aria-label":"Mailbox view","aria-pressed":E==="mailbox",children:t.jsx(sa,{size:16})}),ye.filter(fe=>fe.view.placement==="primary").sort((fe,ct)=>(fe.view.order??Number.MAX_SAFE_INTEGER)-(ct.view.order??Number.MAX_SAFE_INTEGER)).map(fe=>{const ct=Mr(fe.pluginId,fe.view.viewId),hn=il(fe.view.icon);return t.jsx("button",{className:`view-toggle-btn${E===ct?" active":""}`,onClick:()=>L(ct),title:`${fe.view.label} view`,"aria-label":`${fe.view.label} view`,"aria-pressed":E===ct,"data-testid":`view-toggle-plugin-${fe.pluginId}-${fe.view.viewId}`,children:t.jsx(hn,{size:16})},`${fe.pluginId}:${fe.view.viewId}`)}),Ie&&t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:mn,className:`view-toggle-btn${["research","skills","roadmaps","insights","memory","dev-server","devserver"].includes(E)||N&&A||E.startsWith("plugin:")?" active":""}`,onClick:()=>Je(fe=>!fe),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":Fe,"data-testid":"view-toggle-overflow-trigger",children:t.jsx(un,{size:12})}),Fe&&t.jsxs("div",{ref:wn,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[B?.researchView&&t.jsxs("button",{className:`view-toggle-overflow-item${E==="research"?" active":""}`,onClick:()=>{L("research"),Je(!1)},role:"menuitem","data-testid":"view-overflow-research",children:[t.jsx(Ci,{size:14}),t.jsx("span",{children:"Research"})]}),B?.insights&&t.jsxs("button",{className:`view-toggle-overflow-item${E==="insights"?" active":""}`,onClick:()=>{L("insights"),Je(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[t.jsx(ms,{size:14}),t.jsx("span",{children:"Insights"})]}),B?.roadmap&&!J&&t.jsx("button",{className:`view-toggle-overflow-item${E==="roadmaps"?" active":""}`,onClick:()=>{L("roadmaps"),Je(!1)},role:"menuitem","data-testid":"view-overflow-roadmaps",children:t.jsx("span",{children:"Roadmaps"})}),F&&t.jsxs("button",{className:`view-toggle-overflow-item${E==="skills"?" active":""}`,onClick:()=>{L("skills"),Je(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[t.jsx(Xn,{size:14}),t.jsx("span",{children:"Skills"})]}),B?.memoryView&&t.jsxs("button",{className:`view-toggle-overflow-item${E==="memory"?" active":""}`,onClick:()=>{L("memory"),Je(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[t.jsx(Rr,{size:14}),t.jsx("span",{children:"Memory"})]}),B?.devServerView&&t.jsxs("button",{className:`view-toggle-overflow-item${E==="dev-server"||E==="devserver"?" active":""}`,onClick:()=>{L("devserver"),Je(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[t.jsx(Ra,{size:14}),t.jsx("span",{children:"Dev Server"}),t.jsx("span",{className:"visually-hidden","data-testid":"view-toggle-dev-server"})]}),N&&C&&t.jsxs("button",{className:`view-toggle-overflow-item${A?" active":""}`,onClick:()=>{C(),Je(!1)},role:"menuitem","data-testid":"view-overflow-todos",children:[t.jsx(Qo,{size:14}),t.jsx("span",{children:"Todos"})]}),ye.filter(fe=>fe.view.placement!=="primary").sort((fe,ct)=>(fe.view.order??Number.MAX_SAFE_INTEGER)-(ct.view.order??Number.MAX_SAFE_INTEGER)).map(fe=>{const ct=Mr(fe.pluginId,fe.view.viewId),hn=il(fe.view.icon);return t.jsxs("button",{className:`view-toggle-overflow-item${E===ct?" active":""}`,onClick:()=>{L(ct),Je(!1)},role:"menuitem","data-testid":`view-overflow-plugin-${fe.pluginId}-${fe.view.viewId}`,children:[t.jsx(hn,{size:14}),t.jsx("span",{children:fe.view.label})]},`${fe.pluginId}:${fe.view.viewId}`)})]})]})]}),!ee&&o&&t.jsx("button",{className:"btn-icon",onClick:fe=>o(fe.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"desktop-header-usage-btn",children:t.jsx(Fs,{size:16})}),!ee&&c&&t.jsx("button",{className:"btn-icon",onClick:c,title:"System Stats","data-testid":"desktop-header-system-stats-btn",children:t.jsx(Ra,{size:16})}),!ee&&l&&t.jsx("button",{className:"btn-icon",onClick:l,title:"View Activity Log",children:t.jsx(Tr,{size:16})}),!ee&&!$&&t.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:t.jsx(Xu,{size:16})}),!ee&&t.jsxs("button",{className:`btn-icon${r>0?" btn-icon--has-indicator":""}`,onClick:r>0&&a?a:s,title:r>0?"Resume planning session":"Create a task with AI planning","data-testid":"planning-btn",style:{position:"relative"},children:[t.jsx(oi,{size:16}),r>0&&t.jsx("span",{className:"header-badge header-badge--pulse","data-testid":"planning-badge","aria-label":`${r} active planning session${r!==1?"s":""}`,children:r})]}),!ee&&t.jsxs("div",{className:"terminal-split-btn",ref:Vt,children:[t.jsx("button",{className:"btn-icon btn-icon--terminal terminal-split-btn__main",onClick:b,title:"Open Terminal","data-testid":"terminal-toggle-btn",children:t.jsx(Mi,{size:16})}),x&&v&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"terminal-split-btn__divider"}),t.jsx("button",{ref:Ft,className:`btn-icon terminal-split-btn__chevron${ke?" btn-icon--active":""}`,onClick:()=>ce(fe=>!fe),title:"Scripts","aria-haspopup":"listbox","aria-expanded":ke,"aria-label":"Quick scripts","data-testid":"scripts-btn",children:t.jsx(un,{size:12,className:`quick-scripts-dropdown__trigger-chevron${ke?" rotate":""}`})}),ke&&t.jsx("div",{ref:Zt,tabIndex:-1,className:"quick-scripts-dropdown__menu",role:"listbox","aria-label":"Scripts",onKeyDown:tn,"data-testid":"quick-scripts-dropdown",style:$e?{position:"fixed",top:`${$e.top}px`,left:`${$e.left}px`,width:`${$e.width}px`,right:"auto"}:void 0,children:Le?t.jsxs("div",{className:"quick-scripts-dropdown__loading","data-testid":"quick-scripts-loading",children:[t.jsx(gt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts..."})]}):De.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(Mi,{size:16})}),t.jsx("p",{children:"No scripts configured"}),t.jsx("button",{className:"quick-scripts-dropdown__empty-action btn",onClick:ft,children:"Add your first script"})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-scripts-dropdown__list",children:De.map(([fe,ct],hn)=>t.jsxs("button",{className:`quick-scripts-dropdown__item ${it===hn?"highlighted":""}`,onClick:()=>Ye(fe,ct),role:"option","aria-selected":it===hn,"data-testid":`quick-script-item-${fe}`,children:[t.jsx(Hn,{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:fe}),t.jsx("span",{className:"quick-scripts-dropdown__item-command",title:ct,children:ct.length>50?`${ct.slice(0,50)}...`:ct})]})]},fe))}),t.jsx("div",{className:"quick-scripts-dropdown__footer",children:t.jsxs("button",{className:`quick-scripts-dropdown__manage ${oe&&it===De.length?"highlighted":""}`,onClick:ft,"data-testid":"quick-scripts-manage",children:[t.jsx(Cr,{size:14}),t.jsx("span",{children:"Manage Scripts..."})]})})]})})]})]}),!ee&&y&&t.jsx("button",{className:`btn-icon${j?" btn-icon--active":""}`,onClick:y,title:"Browse files","data-testid":"files-toggle-btn",children:t.jsx(os,{size:16})}),!ee&&N&&C&&t.jsx("button",{className:`btn-icon${A?" btn-icon--active":""}`,onClick:C,title:"Open todos","data-testid":"todos-toggle-btn",children:t.jsx(Qo,{size:16})}),!ee&&h&&t.jsx("button",{className:"btn-icon",onClick:h,title:"Git Manager","data-testid":"git-manager-btn",children:t.jsx(Hs,{size:16})}),!ee&&g&&t.jsx("button",{className:"btn-icon",onClick:g,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:t.jsx(Zo,{size:16})}),!ee&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{ref:Ot,className:"btn-icon",onClick:()=>ze(fe=>!fe),title:"More actions","aria-label":"More actions","aria-expanded":be,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:t.jsx(sd,{size:16})}),be&&t.jsxs("div",{ref:zt,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[f&&p!==!1&&t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{f(),ze(!1)},role:"menuitem","data-testid":"desktop-overflow-nodes-btn",children:[t.jsx(Ir,{size:14}),t.jsx("span",{children:"Nodes"})]}),t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{rn(m),ze(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[t.jsx(_i,{size:14}),t.jsx("span",{children:"Automation"})]})]})]}),t.jsxs("div",{className:"engine-control-split-btn",ref:Xt,children:[t.jsx("button",{className:`btn-icon engine-control-split-btn__main${S?" btn-icon--stopped":""}`,onClick:T,title:S?"Start AI engine":"Stop AI engine","data-testid":"engine-control-main-btn",children:S?t.jsx(Hn,{size:16}):t.jsx(Os,{size:16})}),t.jsx("span",{className:"engine-control-split-btn__divider"}),t.jsx("button",{className:`btn-icon engine-control-split-btn__chevron${tt?" btn-icon--active":""}`,onClick:()=>kt(fe=>!fe),title:"Engine options","aria-haspopup":"menu","aria-expanded":tt,"data-testid":"engine-control-chevron-btn",children:t.jsx(un,{size:12})}),tt&&t.jsx("div",{className:"engine-control-split-btn__menu",role:"menu",children:t.jsxs("button",{className:`engine-control-split-btn__menu-item${_?" engine-control-split-btn__menu-item--active":""}`,onClick:()=>{M?.(),kt(!1)},role:"menuitem",title:_?"Resume scheduling":"Pause triage",disabled:!!S,"data-testid":"engine-control-pause-triage-btn",children:[_?t.jsx(Hn,{size:14}):t.jsx(ii,{size:14}),t.jsx("span",{children:_?"Resume scheduling":"Pause triage"})]})})]}),!ee&&t.jsx("button",{className:"btn-icon",onClick:e,title:"Settings",children:t.jsx(Cr,{size:16})}),t.jsx(Oi,{slotId:"header-action",projectId:I}),ee&&!ie&&t.jsx("button",{ref:Pt,className:"btn-icon compact-overflow-trigger",onClick:xn,title:"More header actions","aria-label":"More header actions","aria-expanded":We,"aria-haspopup":"menu",children:t.jsx(sd,{size:16})}),ee&&!ie&&We&&t.jsxs("div",{ref:Ct,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[q.length>=1&&k&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>rn(k),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[t.jsx(yl,{size:16}),t.jsx("span",{children:"Projects"})]}),y&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>rn(y),role:"menuitem","data-testid":"overflow-files-btn",children:[t.jsx(os,{size:16}),t.jsx("span",{children:"Browse Files"})]}),t.jsxs("button",{className:`mobile-overflow-item${r>0?" mobile-overflow-item--has-indicator":""}`,onClick:()=>rn(r>0&&a?a:s),role:"menuitem","data-testid":"overflow-planning-btn",children:[t.jsxs("span",{className:"mobile-overflow-icon-wrapper",children:[t.jsx(oi,{size:16}),r>0&&t.jsx("span",{className:"header-badge header-badge--pulse","data-testid":"overflow-planning-badge",children:r})]}),t.jsx("span",{children:r>0?`Resume planning session (${r})`:"Create a task with AI planning"})]}),h&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>rn(h),role:"menuitem","data-testid":"overflow-git-btn",children:[t.jsx(Hs,{size:16}),t.jsx("span",{children:"Git Manager"})]}),f&&p!==!1&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>rn(f),role:"menuitem","data-testid":"overflow-nodes-btn",children:[t.jsx(Ir,{size:16}),t.jsx("span",{children:"Nodes"})]}),!$&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>rn(n),role:"menuitem",children:[t.jsx(Xu,{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:()=>rn(b),role:"menuitem","data-testid":"overflow-terminal-primary-btn",children:[t.jsx(Mi,{size:16}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{className:"mobile-overflow-split-toggle",onClick:()=>Oe(fe=>!fe),role:"menuitem","aria-expanded":ve,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:t.jsx(Tn,{size:14,className:`mobile-overflow-chevron${ve?" mobile-overflow-chevron--open":""}`})})]}),ve&&t.jsx("div",{className:"mobile-overflow-submenu",role:"menu","aria-label":"Scripts submenu",children:Re?t.jsxs("div",{className:"mobile-overflow-submenu-loading","data-testid":"overflow-scripts-loading",children:[t.jsx(gt,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):Ce.length>0?t.jsxs(t.Fragment,{children:[Ce.map(([fe,ct])=>t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{v&&v(fe,ct),Qe(!1),Oe(!1)},role:"menuitem","data-testid":`overflow-script-item-${fe}`,children:[t.jsx(Hn,{size:14}),t.jsx("span",{children:fe})]},fe)),x&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>rn(x),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(si,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):x&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>rn(x),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(si,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>rn(m),role:"menuitem","data-testid":"overflow-schedules-btn",children:[t.jsx(_i,{size:16}),t.jsx("span",{children:"Automation"})]}),l&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>rn(l),role:"menuitem","data-testid":"overflow-activity-log-btn",children:[t.jsx(Tr,{size:16}),t.jsx("span",{children:"View Activity Log"})]}),d&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>rn(d),role:"menuitem","data-testid":"overflow-mailbox-btn",children:[t.jsx(sa,{size:16}),t.jsxs("span",{children:["Mailbox",u>0?` (${u})`:""]})]}),o&&t.jsxs("button",{className:"mobile-overflow-item",onClick:fe=>rn(()=>o(fe.currentTarget.getBoundingClientRect())),role:"menuitem","data-testid":"overflow-usage-btn",children:[t.jsx(Fs,{size:16}),t.jsx("span",{children:"View Usage"})]}),g&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>rn(g),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[t.jsx(Zo,{size:16}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>rn(e),role:"menuitem",children:[t.jsx(Cr,{size:16}),t.jsx("span",{children:"Settings"})]})]})]})]}),En&&Rt&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{className:"header-search",children:[t.jsx(Ci,{size:14,className:"header-search-icon"}),t.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:P,onChange:fe=>O(fe.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:dn,"aria-label":"Close search",children:t.jsx(Jt,{size:14})})]})}),O&&te&&$t&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{ref:Nt,className:"header-search mobile-search-expanded",children:[t.jsx(Ci,{size:14,className:"header-search-icon"}),t.jsx("input",{ref:jt,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:P,onChange:fe=>O(fe.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:On,"aria-label":"Close search",children:t.jsx(Jt,{size:14})})]})})]})}const C1={themeMode:"dark",colorTheme:"default",dashboardFontScalePct:100,defaultProvider:void 0,defaultModelId:void 0,fallbackProvider:void 0,fallbackModelId:void 0,defaultThinkingLevel:void 0,ntfyEnabled:!1,ntfyTopic:void 0,ntfyBaseUrl:void 0,ntfyEvents:["in-review","merged","failed","awaiting-approval","awaiting-user-review","planning-awaiting-input","gridlock","fallback-used"],ntfyDashboardHost:void 0,webhookEnabled:!1,webhookUrl:void 0,webhookFormat:"generic",webhookEvents:[],notificationProviders:[],customProviders:[],defaultProjectId:void 0,setupComplete:void 0,favoriteProviders:void 0,favoriteModels:void 0,openrouterModelSync:!0,updateCheckEnabled:!0,fnBinaryCheckEnabled:!0,updateCheckFrequency:"daily",autoReloadOnVersionChange:!0,showGitHubStarButton:!0,modelOnboardingComplete:void 0,useClaudeCli:void 0,useDroidCli:void 0,executionGlobalProvider:void 0,executionGlobalModelId:void 0,planningGlobalProvider:void 0,planningGlobalModelId:void 0,validatorGlobalProvider:void 0,validatorGlobalModelId:void 0,titleSummarizerGlobalProvider:void 0,titleSummarizerGlobalModelId:void 0,daemonToken:void 0,daemonPort:4040,daemonHost:"127.0.0.1",settingsSyncEnabled:!1,settingsSyncAuth:!1,settingsSyncInterval:9e5,settingsSyncConflictResolution:"last-write-wins",dashboardCurrentNodeId:void 0,dashboardCurrentProjectIdByNode:void 0,vitestAutoKillEnabled:!0,vitestKillThresholdPct:90,persistAgentToolOutput:!0,researchGlobalDefaults:{searchProvider:void 0,synthesisProvider:void 0,synthesisModelId:void 0,enabledSources:{webSearch:!0,pageFetch:!0,github:!1,localDocs:!0,llmSynthesis:!0},maxSourcesPerRun:20,defaultExportFormat:"markdown"},researchGlobalEnabled:!0,researchGlobalMaxConcurrentRuns:3,researchGlobalDefaultTimeout:3e5,researchGlobalMaxSourcesPerRun:20,researchGlobalMaxSynthesisRounds:2,researchWebSearchProvider:"none",researchSearxngUrl:void 0,researchBraveApiKey:void 0,researchGoogleSearchApiKey:void 0,researchGoogleSearchCx:void 0,researchTavilyApiKey:void 0,researchGitHubEnabled:!1,researchLocalDocsEnabled:!0,researchMaxSearchResults:10,researchFetchTimeoutMs:3e4,researchUserAgent:"FusionResearchBot/1.0",remoteAccess:{activeProvider:null,providers:{tailscale:{enabled:!1,hostname:"",targetPort:0,acceptRoutes:!1},cloudflare:{enabled:!1,quickTunnel:!0,tunnelName:"",tunnelToken:null,ingressUrl:""}},tokenStrategy:{persistent:{enabled:!0,token:null},shortLived:{enabled:!1,ttlMs:9e5,maxTtlMs:864e5}},lifecycle:{rememberLastRunning:!1,wasRunningOnShutdown:!1,lastRunningProvider:null}},experimentalFeatures:{}},E1={globalPause:!1,globalPauseReason:void 0,enginePaused:!1,maxConcurrent:2,maxTriageConcurrent:2,globalMaxConcurrent:4,maxWorktrees:4,pollIntervalMs:15e3,heartbeatMultiplier:1,groupOverlappingFiles:!0,overlapIgnorePaths:[],autoMerge:!0,mergeStrategy:"direct",requirePrApproval:!1,pushAfterMerge:!1,pushRemote:"origin",unavailableNodePolicy:"block",defaultNodeId:void 0,worktreeInitCommand:void 0,testCommand:void 0,buildCommand:void 0,recycleWorktrees:!1,worktreeNaming:"random",taskPrefix:"FN",includeTaskIdInCommit:!0,commitAuthorEnabled:!0,commitAuthorName:"Fusion",commitAuthorEmail:"noreply@runfusion.ai",planningProvider:void 0,planningModelId:void 0,planningFallbackProvider:void 0,planningFallbackModelId:void 0,defaultProviderOverride:void 0,defaultModelIdOverride:void 0,executionProvider:void 0,executionModelId:void 0,validatorProvider:void 0,validatorModelId:void 0,validatorFallbackProvider:void 0,validatorFallbackModelId:void 0,modelPresets:[],autoSelectModelPreset:!1,completionDocumentationMode:"off",defaultPresetBySize:{},autoResolveConflicts:!0,smartConflictResolution:!0,worktreeRebaseBeforeMerge:!0,worktreeRebaseRemote:"",worktreeRebaseLocalBase:!0,mergeConflictStrategy:"smart-prefer-main",workflowStepTimeoutMs:36e4,strictScopeEnforcement:!1,buildRetryCount:0,verificationFixRetries:3,buildTimeoutMs:3e5,requirePlanApproval:!1,specStalenessEnabled:!1,specStalenessMaxAgeMs:360*60*1e3,taskStuckTimeoutMs:void 0,aiSessionTtlMs:10080*60*1e3,aiSessionCleanupIntervalMs:3600*1e3,autoUnpauseEnabled:!0,autoUnpauseBaseDelayMs:3e5,autoUnpauseMaxDelayMs:36e5,maxStuckKills:6,maxPostReviewFixes:1,maxSpawnedAgentsPerParent:5,maxSpawnedAgentsGlobal:20,maintenanceIntervalMs:3e5,autoArchiveDoneTasksEnabled:!0,autoArchiveDoneAfterMs:2880*60*1e3,archiveAgentLogMode:"compact",autoUpdatePrStatus:!1,githubCommentOnDone:!1,githubCommentTemplate:void 0,autoBackupEnabled:!1,autoBackupSchedule:"0 2 * * *",autoBackupRetention:7,autoBackupDir:".fusion/backups",autoSummarizeTitles:!1,useAiMergeCommitSummary:!0,titleSummarizerProvider:void 0,titleSummarizerModelId:void 0,titleSummarizerFallbackProvider:void 0,titleSummarizerFallbackModelId:void 0,scripts:void 0,setupScript:void 0,insightExtractionEnabled:!1,insightExtractionSchedule:"0 2 * * *",insightExtractionMinIntervalMs:864e5,memoryEnabled:!0,memoryBackendType:"qmd",memoryAutoSummarizeEnabled:!1,memoryAutoSummarizeThresholdChars:5e4,memoryAutoSummarizeSchedule:"0 3 * * *",memoryDreamsEnabled:!1,memoryDreamsSchedule:"0 4 * * *",tokenCap:void 0,runStepsInNewSessions:!1,maxParallelSteps:2,missionStaleThresholdMs:6e5,missionMaxTaskRetries:3,missionHealthCheckIntervalMs:3e5,agentPrompts:void 0,promptOverrides:void 0,reflectionEnabled:!1,reflectionIntervalMs:36e5,reflectionAfterTask:!0,reviewHandoffPolicy:"disabled",showQuickChatFAB:!1,researchSettings:{enabled:!0,searchProvider:void 0,synthesisProvider:void 0,synthesisModelId:void 0,enabledSources:{webSearch:!0,pageFetch:!0,github:!1,localDocs:!0,llmSynthesis:!0},limits:{maxConcurrentRuns:3,maxSourcesPerRun:20,maxDurationMs:3e5,requestTimeoutMs:3e4}},researchEnabled:!0,researchMaxConcurrentRuns:3,researchDefaultTimeout:3e5,researchMaxSourcesPerRun:20,researchMaxSynthesisRounds:2},M1=Object.freeze(Object.keys(C1)),_1=Object.freeze(Object.keys(E1));function Bz(e){return M1.includes(e)}function Hz(e){return _1.includes(e)}function _e(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function A1(e){return!!(e?.provider&&e?.modelId)}function Bi(...e){for(const n of e)if(A1(n))return{provider:n.provider,modelId:n.modelId};return{}}function _l(e){return Bi({provider:e?.defaultProviderOverride,modelId:e?.defaultModelIdOverride},{provider:e?.defaultProvider,modelId:e?.defaultModelId})}function P1(e){return Bi({provider:e?.executionProvider,modelId:e?.executionModelId},{provider:e?.executionGlobalProvider,modelId:e?.executionGlobalModelId},_l(e))}function R1(e){return Bi({provider:e?.planningProvider,modelId:e?.planningModelId},{provider:e?.planningGlobalProvider,modelId:e?.planningGlobalModelId},_l(e))}function T1(e){return Bi({provider:e?.validatorProvider,modelId:e?.validatorModelId},{provider:e?.validatorGlobalProvider,modelId:e?.validatorGlobalModelId},_l(e))}function qz(e){return Bi({provider:e?.titleSummarizerProvider,modelId:e?.titleSummarizerModelId},{provider:e?.titleSummarizerGlobalProvider,modelId:e?.titleSummarizerGlobalModelId},{provider:e?.planningProvider,modelId:e?.planningModelId},_l(e))}function Nf(e,n){return Bi({provider:e.modelProvider,modelId:e.modelId},P1(n))}function Sf(e,n){return Bi({provider:e.validatorModelProvider,modelId:e.validatorModelId},T1(n))}function Cf(e,n){return Bi({provider:e.planningModelProvider,modelId:e.planningModelId},R1(n))}const Vz=["off","minimal","low","medium","high"],ea=["triage","todo","in-progress","in-review","done","archived"],Zr=["low","normal","high","urgent"],Cs="normal",I1=["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"],Qn={triage:"Planning",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},$1={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"},fd={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 D1(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 L1(e,n=1400){const s=i.useRef(null),[a,r]=i.useState(!1),o=i.useRef(null);return i.useEffect(()=>(s.current!==null&&e>s.current&&(r(!0),o.current=setTimeout(()=>r(!1),n)),s.current=e,()=>{o.current!==null&&clearTimeout(o.current)}),[e,n]),a}function O1({isOpen:e,options:n,onConfirm:s,onCancel:a}){const r=i.useRef(null);return i.useEffect(()=>{if(!e)return;r.current?.focus();const o=l=>{l.key==="Escape"&&(l.preventDefault(),a())};return document.addEventListener("keydown",o),()=>document.removeEventListener("keydown",o)},[e,a]),!e||!n?null:t.jsx("div",{className:"modal-overlay open",onClick:a,children:t.jsxs("div",{className:"modal confirm-dialog",onClick:o=>o.stopPropagation(),role:"dialog","aria-modal":"true","aria-label":n.title,children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:n.title}),t.jsx("button",{className:"modal-close",onClick:a,"aria-label":"Close confirmation dialog",children:"×"})]}),t.jsx("div",{className:"confirm-dialog__body",children:n.message}),t.jsxs("div",{className:"modal-actions confirm-dialog__actions",children:[t.jsx("button",{ref:r,className:"btn",onClick:a,children:n.cancelLabel??"Cancel"}),t.jsx("button",{className:`btn ${n.danger?"btn-danger":"btn-primary"}`,onClick:s,children:n.confirmLabel??"Confirm"})]})]})})}const Ef=i.createContext(null);function z1({children:e}){const[n,s]=i.useState([]),a=i.useRef([]),r=i.useCallback(u=>{s(m=>{const h=u(m);return a.current=h,h})},[]),o=i.useCallback(u=>new Promise(m=>{r(h=>[...h,{options:u,resolve:m}])}),[r]),l=i.useCallback(u=>{const m=a.current[0];m&&(m.resolve(u),r(h=>h.slice(1)))},[r]),c=n[0]??null,d=i.useMemo(()=>({confirm:o}),[o]);return Jo.createElement(Ef.Provider,{value:d},e,Jo.createElement(O1,{isOpen:c!==null,options:c?.options??null,onConfirm:()=>l(!0),onCancel:()=>l(!1)}))}function qs(){const e=i.useContext(Ef);return e||{confirm:async n=>!1}}function F1(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 Mf({prInfo:e,issueInfo:n,onIssueRefresh:s}){const a=()=>{e?.url&&window.open(e.url,"_blank","noopener,noreferrer")},r=()=>{n?.url&&window.open(n.url,"_blank","noopener,noreferrer")};return t.jsxs(t.Fragment,{children:[e&&t.jsxs("span",{className:`card-github-badge card-github-badge--${e.status}`,title:`PR #${e.number}: ${e.title}`,onClick:a,children:[t.jsx(zs,{size:12}),t.jsxs("span",{children:["#",e.number]})]}),n&&t.jsxs("span",{className:`card-github-badge ${F1(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,onClick:r,children:[t.jsx(xl,{size:12}),t.jsxs("span",{children:["#",n.number]})]})]})}function yo(e,n){return`${e??"default"}:${n}`}class U1{ws=null;listeners=new Set;badgeUpdates=new Map;subscriptionsByTask=new Map;reconnectTimeout=null;reconnectDelayMs=1e3;shouldReconnect=!1;isConnected=!1;projectId=null;snapshot={badgeUpdates:new Map,isConnected:!1};previousProjectIdRef=null;projectContextVersionRef=0;contextVersionAtStart=0;subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}getSnapshot(){return this.snapshot}setProjectId(n){if(this.projectId===n)return;this.previousProjectIdRef=this.projectId,this.projectContextVersionRef++,this.contextVersionAtStart=this.projectContextVersionRef;const s=this.subscriptionsByTask.size>0,a=[];for(const[r,o]of this.subscriptionsByTask){const l=r.split(":").slice(1).join(":");for(const c of o)a.push({hookId:c,taskId:l})}if(this.projectId=n,this.reset(),s){for(const{hookId:r,taskId:o}of a){const l=yo(this.projectId,o);this.subscriptionsByTask.set(l,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const a=yo(this.projectId,s),r=this.subscriptionsByTask.get(a)??new Set,o=!r.has(n);r.add(n),this.subscriptionsByTask.set(a,r),this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect(),o&&this.send({type:"subscribe",taskId:s,projectId:this.projectId})}unsubscribeTask(n,s){const a=yo(this.projectId,s),r=this.subscriptionsByTask.get(a);r&&(r.delete(n),r.size===0&&(this.subscriptionsByTask.delete(a),this.badgeUpdates.delete(a),this.send({type:"unsubscribe",taskId:s,projectId:this.projectId}),this.emit()),this.shouldReconnect=this.subscriptionsByTask.size>0,this.shouldReconnect||this.disconnect())}cleanupHook(n){for(const s of[...this.subscriptionsByTask.keys()]){const a=s.split(":").slice(1).join(":");this.unsubscribeTask(n,a)}}reset(){this.disconnect(),this.badgeUpdates.clear(),this.subscriptionsByTask.clear(),this.shouldReconnect=!1,this.emit()}connect(){if(!this.shouldReconnect||typeof window>"u"||this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))return;const n=this.projectContextVersionRef;let a=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/ws`;this.projectId&&(a+=`?projectId=${encodeURIComponent(this.projectId)}`);const r=new WebSocket(xi(a));this.ws=r,r.onopen=()=>{if(this.projectContextVersionRef!==n){r.close();return}this.isConnected=!0,this.reconnectDelayMs=1e3,this.emit();const o=new Set;for(const l of this.subscriptionsByTask.keys()){const c=l.split(":").slice(1).join(":");o.add(c)}for(const l of o)this.send({type:"subscribe",taskId:l,projectId:this.projectId})},r.onmessage=o=>{if(this.projectContextVersionRef===n)try{const l=JSON.parse(o.data);if(l.type!=="badge:updated"||l.projectId!==void 0&&l.projectId!==this.projectId)return;const c=yo(this.projectId,l.taskId),d=this.badgeUpdates.get(c);this.badgeUpdates.set(c,{prInfo:Zu(l,"prInfo")?l.prInfo??null:d?.prInfo,issueInfo:Zu(l,"issueInfo")?l.issueInfo??null:d?.issueInfo,timestamp:l.timestamp}),this.emit()}catch{}},r.onclose=()=>{this.projectContextVersionRef===n&&(this.ws=null,this.isConnected&&(this.isConnected=!1,this.emit()),this.shouldReconnect&&this.scheduleReconnect(n))},r.onerror=()=>{}}disconnect(){if(this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.ws){const n=this.ws;this.ws=null,n.close()}this.isConnected&&(this.isConnected=!1,this.emit())}scheduleReconnect(n){if(this.reconnectTimeout)return;const s=n??this.projectContextVersionRef,a=Math.min(this.reconnectDelayMs,5e3);this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.projectContextVersionRef===s&&this.shouldReconnect&&this.connect()},a),this.reconnectDelayMs=Math.min(this.reconnectDelayMs*2,5e3)}send(n){!this.ws||this.ws.readyState!==WebSocket.OPEN||this.ws.send(JSON.stringify(n))}emit(){this.snapshot={badgeUpdates:new Map(this.badgeUpdates),isConnected:this.isConnected};for(const n of this.listeners)n()}}const Ji=new U1;let B1=0;function Zu(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function _f(e){const n=i.useRef(null);n.current===null&&(n.current=`badge-hook-${B1++}`);const s=i.useSyncExternalStore(o=>Ji.subscribe(o),()=>Ji.getSnapshot(),()=>Ji.getSnapshot()),a=i.useCallback(o=>{Ji.subscribeTask(n.current,o)},[]),r=i.useCallback(o=>{Ji.unsubscribeTask(n.current,o)},[]);return i.useEffect(()=>{Ji.setProjectId(e??null)},[e]),i.useEffect(()=>()=>{Ji.cleanupHook(n.current)},[]),{badgeUpdates:s.badgeUpdates,isConnected:s.isConnected,subscribeToBadge:a,unsubscribeFromBadge:r}}function al(e,n,s,a){return e===void 0||!n?s:!a||n>=a?e??void 0:s}function H1({taskId:e,prInfo:n,issueInfo:s,updatedAt:a,isInViewport:r,projectId:o}){const{badgeUpdates:l,subscribeToBadge:c,unsubscribeFromBadge:d}=_f(o),u=!!(n||s);i.useEffect(()=>{if(!u||!r){d(e);return}return c(e),()=>{d(e)}},[u,r,o,c,e,d]);const m=l.get(`${o??"default"}:${e}`),h=al(m?.prInfo,m?.timestamp,n,n?.lastCheckedAt??a),f=al(m?.issueInfo,m?.timestamp,s,s?.lastCheckedAt??a);return!h&&!f?null:t.jsx(Mf,{prInfo:h,issueInfo:f})}const q1=i.memo(H1);q1.displayName="TaskCardBadge";const V1={sm:16,md:20,lg:24};function W1({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 em({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 hi({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 K1({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 tm({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 G1({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 Xl({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 nm({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 sm({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 im({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 sr({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 am({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 Zl({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 rm({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 ec({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 J1({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 Y1({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 om({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 tc({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 Q1({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 lm({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 nc({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 cm({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 sc({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 dm({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 X1({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 Z1={anthropic:{component:W1,color:"var(--provider-anthropic)"},"claude-cli":{component:dm,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"pi-claude-cli":{component:dm,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"droid-cli":{component:X1,color:"var(--provider-openai)",label:"Factory AI — via Droid CLI"},openai:{component:em,color:"var(--provider-openai)"},"openai-codex":{component:em,color:"var(--provider-openai)",label:"OpenAI Codex"},google:{component:hi,color:"var(--provider-gemini)"},gemini:{component:hi,color:"var(--provider-gemini)"},"google-antigravity":{component:hi,color:"var(--provider-gemini)",label:"Google Gemini"},antigravity:{component:hi,color:"var(--provider-gemini)",label:"Google Gemini"},"google-vertex":{component:hi,color:"var(--provider-gemini)",label:"Google Vertex AI"},vertex:{component:hi,color:"var(--provider-gemini)",label:"Google Vertex AI"},"google-cloud-code":{component:hi,color:"var(--provider-gemini)",label:"Google Cloud Code"},"cloud-code":{component:hi,color:"var(--provider-gemini)",label:"Google Cloud Code"},"google-gemini-cli":{component:hi,color:"var(--provider-gemini)",label:"Google Gemini CLI"},"google-generative-ai":{component:hi,color:"var(--provider-gemini)",label:"Google Generative AI"},ollama:{component:K1,color:"var(--text)"},github:{component:lm,color:"var(--text)"},"github-copilot":{component:lm,color:"var(--text)",label:"GitHub Copilot"},openrouter:{component:Q1,color:"var(--provider-openrouter)"},minimax:{component:tm,color:"var(--provider-minimax)"},"minimax-cn":{component:tm,color:"var(--provider-minimax)",label:"MiniMax (CN)"},zai:{component:G1,color:"var(--provider-zai)"},kimi:{component:Xl,color:"var(--provider-kimi)"},moonshot:{component:Xl,color:"var(--provider-kimi)"},"kimi-coding":{component:Xl,color:"var(--provider-kimi)",label:"Kimi"},bedrock:{component:nm,color:"var(--provider-bedrock)"},"amazon-bedrock":{component:nm,color:"var(--provider-bedrock)",label:"Amazon Bedrock"},xai:{component:sm,color:"var(--text)"},grok:{component:sm,color:"var(--text)",label:"xAI"},opencode:{component:im,color:"var(--provider-opencode)"},"opencode-go":{component:im,color:"var(--provider-opencode)",label:"Opencode (Go)"},qwen:{component:sr,color:"var(--provider-qwen)"},"qwen-ai":{component:sr,color:"var(--provider-qwen)",label:"Qwen"},"qwen-coder":{component:sr,color:"var(--provider-qwen)",label:"Qwen Coder"},alibaba:{component:sr,color:"var(--provider-qwen)",label:"Qwen"},tongyi:{component:sr,color:"var(--provider-qwen)",label:"Qwen"},lmstudio:{component:am,color:"var(--provider-lmstudio)",label:"LM Studio"},"lm-studio":{component:am,color:"var(--provider-lmstudio)",label:"LM Studio"},huggingface:{component:Zl,color:"var(--provider-huggingface)",label:"Hugging Face"},"hugging-face":{component:Zl,color:"var(--provider-huggingface)",label:"Hugging Face"},hf:{component:Zl,color:"var(--provider-huggingface)",label:"Hugging Face"},mistral:{component:rm,color:"var(--provider-mistral)",label:"Mistral AI"},"mistral-ai":{component:rm,color:"var(--provider-mistral)",label:"Mistral AI"},azure:{component:ec,color:"var(--provider-azure)"},"azure-openai":{component:ec,color:"var(--provider-azure)",label:"Azure OpenAI"},"azure-openai-responses":{component:ec,color:"var(--provider-azure)",label:"Azure OpenAI"},fireworks:{component:tc,color:"var(--provider-fireworks)",label:"Fireworks AI"},"fireworks-ai":{component:tc,color:"var(--provider-fireworks)",label:"Fireworks AI"},fireworksai:{component:tc,color:"var(--provider-fireworks)",label:"Fireworks AI"},cerebras:{component:J1,color:"var(--provider-cerebras)"},groq:{component:Y1,color:"var(--provider-groq)"},vercel:{component:om,color:"var(--provider-vercel)"},"vercel-ai-gateway":{component:om,color:"var(--provider-vercel)",label:"Vercel AI Gateway"},hermes:{component:nc,color:"var(--provider-hermes)",label:"Hermes"},"hermes-agent":{component:nc,color:"var(--provider-hermes)",label:"Hermes"},hermesagent:{component:nc,color:"var(--provider-hermes)",label:"Hermes"},openclaw:{component:cm,color:"var(--provider-openclaw)",label:"OpenClaw"},"open-claw":{component:cm,color:"var(--provider-openclaw)",label:"OpenClaw"},paperclip:{component:sc,color:"var(--provider-paperclip)",label:"Paperclip"},paperclipai:{component:sc,color:"var(--provider-paperclip)",label:"Paperclip"},"paperclip-ai":{component:sc,color:"var(--provider-paperclip)",label:"Paperclip"}};function qn({provider:e,size:n="sm"}){const s=e.toLowerCase(),a=Z1[s],r=a?.component,o=a?.color??"var(--text-muted)",l=a?.label,c=V1[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(Ex,{size:c})})}const Ks={data:new Map,pendingPromise:null,lastFetchTime:null},eS=5e3;function Vo(e,n){return n?`${n}::${e}`:e}function tS(e,n){const s=Ks.data.get(Vo(e,n));if(!(!s||Date.now()-s.timestamp>eS))return s}function nS(e){const[n,s]=i.useState(!1),a=i.useRef(null),r=i.useCallback(async c=>{let u=null;for(let m=0;m<3;m++)try{return await Zw(c,e)}catch(h){u=h instanceof Error?h:new Error(String(h));const f=_e(h);if(f?.includes("429")||f?.toLowerCase().includes("rate limit")){const p=Math.min(1e3*Math.pow(2,m),3e4);await new Promise(g=>setTimeout(g,p));continue}break}if(u)throw u;return{}},[e]),o=i.useCallback(async c=>{if(c.length===0)return;const u=Date.now()-5e3;if(c.every(f=>{const p=Ks.data.get(Vo(f,e));return p&&p.timestamp>u})&&Ks.lastFetchTime&&Ks.lastFetchTime>u)return;if(a.current&&(clearTimeout(a.current),a.current=null),Ks.pendingPromise){s(!0);try{await Ks.pendingPromise}finally{s(!1)}return}s(!0);const h=r(c);Ks.pendingPromise=h;try{const f=await h,p=Date.now();for(const[g,x]of Object.entries(f))Ks.data.set(Vo(g,e),{result:x,timestamp:p});Ks.lastFetchTime=p}catch{}finally{Ks.pendingPromise=null,s(!1)}},[r,e]),l=i.useCallback(c=>Ks.data.get(Vo(c,e)),[e]);return{fetchBatch:o,isLoading:n,lastFetchTime:Ks.lastFetchTime,getBatchData:l}}const gd=new Map,sS=3e4;function Af(e,n,s,a){return`${e}:${n??""}:${s??""}:${a??""}`}function iS(e,n,s,a){const r=Af(e,n,s,a),o=gd.get(r);return o?Date.now()>o.expiresAt?(gd.delete(r),null):o.stats:null}function aS(e,n,s,a,r){const o=Af(e,n,s,a);gd.set(o,{stats:r,expiresAt:Date.now()+sS})}function rS(e,n,s,a,r={}){const o=r.enabled??!0,l=r.worktree,c=r.stepVersion,d=r.pollIntervalMs,[u,m]=i.useState(null),[h,f]=i.useState(!1);return i.useEffect(()=>{if(!o){m(null),f(!1);return}const p=n==="done"&&!!s,g=(n==="in-progress"||n==="in-review")&&!!l;if(!e||!p&&!g){m(null),f(!1);return}const x=g?l:void 0,v=c!==void 0?String(c):void 0;let b=!1;async function y(C=!1){if(!C){const A=iS(e,a,x,v);if(A){b||(m(A),f(!1));return}}f(!0);try{const A=await ff(e,x,a);b||(m(A.stats),aS(e,a,x,v,A.stats))}catch{b||m(null)}finally{b||f(!1)}}y();let j;return d&&g&&(j=setInterval(()=>{y(!0)},d)),()=>{b=!0,j&&clearInterval(j)}},[e,n,s,a,o,l,c,d]),{stats:u,loading:h}}const oS=new Set(["failed","stuck-killed"]);function rl(e,n,s){if(e.column!=="in-progress"||e.status&&oS.has(e.status)||!n||n<=0)return!1;const a=new Date(e.updatedAt).getTime();return(s??Date.now())-a>n}function lS(e){switch(e){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function cS(e){return e==="done"||e==="skipped"}function dS(e,n,s){const a=s?.get(e)?.trim();if(a)return a;const r=n?.workflowStepName?.trim();return r||e}function Pf(e,n){const s=(e.steps??[]).map((d,u)=>({id:`step-${u}`,name:d.name,status:d.status,source:"step",phase:"pre-merge"})),a=new Map((e.workflowStepResults??[]).map(d=>[d.workflowStepId,d])),r=(e.enabledWorkflowSteps??[]).map(d=>{const u=a.get(d);return{id:`workflow-${d}`,name:dS(d,u,n),status:u?lS(u.status):"pending",source:"workflow",phase:u?.phase??"pre-merge"}}),o=[...s,...r],l=o.length,c=o.filter(d=>cS(d.status)).length;return{total:l,completed:c,items:o}}function uS(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 Rf(e){return e.filter(n=>{const s=typeof n.action=="string"?n.action:"",a=typeof n.outcome=="string"?n.outcome:"";return s.includes("[timing]")||a.includes("[timing]")}).map(n=>{const a=`${n.action??""}
641
+ ${n.outcome??""}`.match(/(\d+(?:\.\d+)?)ms\b/i),r=a?Number(a[1]):void 0;return{timestamp:n.timestamp,durationMs:Number.isFinite(r)?r:void 0,summary:uS(n)}})}function mS(e){if(!e||e.length===0)return null;let n=0,s=0;for(const a of Rf(e))typeof a.durationMs=="number"&&(n+=a.durationMs,s+=1);return s>0?n:null}const bd=new Map;async function hS(e,n){const s=bd.get(e);if(s)return s;try{const a=await gf(e,n);return bd.set(e,a.title),a.title}catch{return e}}const um=12;function pS(e){return e.length<=um?e:e.slice(0,um-3)+"..."}const xd=new Map;async function fS(e,n){const s=xd.get(e);if(s)return s;try{const a=await pd(e,n);return xd.set(e,a.name),a.name}catch{return e}}function gS(e){return typeof e=="string"&&Zr.includes(e)?e:Cs}function bS(e,n){return e.length<=n?e:e.slice(0,n-3)+"..."}const xS=new Set(["triage","todo"]),mm=new Set(["planning","researching","executing","finalizing","merging"]),hm=new Set(["merging","merging-pr"]),vS={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"},yS=new Set(["in-progress","in-review","done"]),wS=3e4;function aa(e){if(!e)return null;const n=Date.parse(e);return Number.isFinite(n)?n:null}function kS(e){const n=aa(e.columnMovedAt??e.updatedAt);if(n==null)return null;const s=Date.now();return n>s?null:n}function pm(e,n){const s=aa(e.columnMovedAt??e.updatedAt);return s==null?null:Math.max(0,n-s)}function yr(e,n){const s=aa(e.executionStartedAt);if(s==null)return null;const a=aa(e.executionCompletedAt),r=a!=null&&a>=s?a:n;return Math.max(0,r-s)}function jS(e){return e.column==="done"?kS(e):null}function Tf(e,n){const s=aa(e.updatedAt);return s==null?null:Math.max(0,n-s)}function NS(e,n){const s=yr(e,n);if(s!=null)return s;const a=Tf(e,n),r=wr(e,n);return r!=null?r+(a??0):a}function SS(e,n){const s=e.workflowStepResults;if(!s||s.length===0)return null;let a=0,r=0;for(const o of s){if(!o.startedAt)continue;const l=aa(o.startedAt);if(l==null)continue;let c;if(o.completedAt){const d=aa(o.completedAt);if(d==null||d<l)continue;c=d}else c=Math.max(l,n);a+=c-l,r+=1}return r>0?a:null}function wr(e,n){const s=typeof e.timedExecutionMs=="number"?e.timedExecutionMs:mS(e.log),a=SS(e,n);return s==null&&a==null?null:(s??0)+(a??0)}function fm(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 gm(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 bm(e,n){if(!e&&!n)return!0;if(!e||!n)return!1;const s=Object.keys(e),a=Object.keys(n);return s.length!==a.length?!1:s.every(r=>e[r]===n[r])}function CS(e,n){return e.length!==n.length?!1:e.every((s,a)=>s.name===n[a]?.name&&s.status===n[a]?.status)}function ES(e,n){return e.length!==n.length?!1:e.every((s,a)=>s===n[a])}function MS(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,a)=>s===n[a])}function _S(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}function AS(e){if(!(e instanceof Error))return null;const n=e.details;if(n?.code==="TASK_HAS_DEPENDENTS"&&Array.isArray(n.dependentIds))return{dependentIds:n.dependentIds.filter(a=>typeof a=="string")};const s=e.message.match(/[A-Z]+-\d+/g)??[];return s.length>1?{dependentIds:[...new Set(s.slice(1))]}:null}function PS(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,a)=>{const r=n[a];return r?s.workflowStepId===r.workflowStepId&&s.workflowStepName===r.workflowStepName&&s.phase===r.phase&&s.status===r.status&&s.output===r.output&&s.startedAt===r.startedAt&&s.completedAt===r.completedAt:!1})}function RS(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,a)=>{const r=n[a];return r?s.filename===r.filename&&s.mimeType===r.mimeType&&s.size===r.size:!1})}function TS(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,a)=>{const r=n[a];return r?s.author===r.author&&s.text===r.text&&s.createdAt===r.createdAt:!1})}function IS(e,n){const s=e.task,a=n.task;return e.queued===n.queued&&e.projectId===n.projectId&&e.globalPaused===n.globalPaused&&e.taskStuckTimeoutMs===n.taskStuckTimeoutMs&&e.onOpenDetail===n.onOpenDetail&&e.addToast===n.addToast&&e.onUpdateTask===n.onUpdateTask&&e.onArchiveTask===n.onArchiveTask&&e.onUnarchiveTask===n.onUnarchiveTask&&e.onDeleteTask===n.onDeleteTask&&e.onRetryTask===n.onRetryTask&&e.onOpenDetailWithTab===n.onOpenDetailWithTab&&e.onOpenMission===n.onOpenMission&&e.onMoveTask===n.onMoveTask&&e.workflowStepNameLookup===n.workflowStepNameLookup&&s.id===a.id&&s.title===a.title&&s.description===a.description&&s.column===a.column&&s.columnMovedAt===a.columnMovedAt&&s.timedExecutionMs===a.timedExecutionMs&&s.updatedAt===a.updatedAt&&s.createdAt===a.createdAt&&s.status===a.status&&s.priority===a.priority&&s.executionMode===a.executionMode&&s.paused===a.paused&&s.error===a.error&&s.size===a.size&&s.blockedBy===a.blockedBy&&s.worktree===a.worktree&&s.baseBranch===a.baseBranch&&s.breakIntoSubtasks===a.breakIntoSubtasks&&s.currentStep===a.currentStep&&s.modelProvider===a.modelProvider&&s.modelId===a.modelId&&s.validatorModelProvider===a.validatorModelProvider&&s.validatorModelId===a.validatorModelId&&s.planningModelProvider===a.planningModelProvider&&s.planningModelId===a.planningModelId&&s.reviewLevel===a.reviewLevel&&s.missionId===a.missionId&&s.assignedAgentId===a.assignedAgentId&&s.mergeRetries===a.mergeRetries&&s.sourceType===a.sourceType&&s.sourceMetadata?.issueUrl===a.sourceMetadata?.issueUrl&&RS(s.attachments,a.attachments)&&TS(s.comments,a.comments)&&ES(s.dependencies,a.dependencies)&&CS(s.steps,a.steps)&&MS(s.enabledWorkflowSteps,a.enabledWorkflowSteps)&&PS(s.workflowStepResults,a.workflowStepResults)&&bm(s.prInfo,a.prInfo)&&bm(s.issueInfo,a.issueInfo)}function $S({task:e,projectId:n,queued:s,onOpenDetail:a,addToast:r,globalPaused:o,onUpdateTask:l,onArchiveTask:c,onUnarchiveTask:d,onDeleteTask:u,onRetryTask:m,onOpenDetailWithTab:h,taskStuckTimeoutMs:f,onOpenMission:p,onMoveTask:g,lastFetchTimeMs:x,workflowStepNameLookup:v}){const[b,y]=i.useState(!1),[j,C]=i.useState(!1),[A,N]=i.useState(!1),[S,_]=i.useState(e.description||""),[T,M]=i.useState(!1),[E,L]=i.useState(e.column==="in-progress"||e.column==="triage"&&e.steps.some(de=>de.status==="done"||de.status==="skipped")),[F,R]=i.useState(null),[P,O]=i.useState(null),[q,Z]=i.useState(!1),[z,k]=i.useState(!1),[I,$]=i.useState(()=>Date.now()),w=i.useRef(null),H=i.useRef(!1),K=i.useRef(null),pe=i.useRef(null),[le,B]=i.useState(!1),{badgeUpdates:ye,subscribeToBadge:U,unsubscribeFromBadge:te}=_f(n),{confirm:ne}=qs(),ee=i.useRef(null),ie=i.useRef(!1),ge=i.useCallback(de=>de instanceof Element?!!de.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);i.useEffect(()=>{_(e.description||"")},[e.id,e.description]),i.useEffect(()=>{if(!q)return;const de=Ne=>{pe.current&&!pe.current.contains(Ne.target)&&Z(!1)};return document.addEventListener("click",de),()=>document.removeEventListener("click",de)},[q]),i.useEffect(()=>{if(!e.missionId){R(null);return}const de=bd.get(e.missionId);if(de){R(de);return}let Ne=!1;return hS(e.missionId,n).then(Ye=>{Ne||R(Ye)}),()=>{Ne=!0}},[e.missionId,n]),i.useEffect(()=>{if(!e.assignedAgentId){O(null);return}const de=xd.get(e.assignedAgentId);if(de){O(de);return}O(null);let Ne=!1;return fS(e.assignedAgentId,n).then(Ye=>{Ne||O(Ye)}),()=>{Ne=!0}},[e.assignedAgentId,n]),i.useEffect(()=>{if(A&&w.current){const de=w.current;de.focus(),de.style.height="auto",de.style.height=de.scrollHeight+"px"}},[A]),i.useEffect(()=>{if(typeof IntersectionObserver>"u"){B(!0);return}const de=K.current;if(!de)return;const Ne=new IntersectionObserver(([Ye])=>{B(Ye?.isIntersecting??!0)},{rootMargin:"200px"});return Ne.observe(de),()=>Ne.disconnect()},[A,e.id]);const se=i.useCallback(de=>{de.dataTransfer.setData("text/plain",e.id),de.dataTransfer.effectAllowed="move",y(!0)},[e.id]),Ae=i.useCallback(()=>{y(!1)},[]),xe=i.useCallback(de=>de.dataTransfer.types.includes("Files"),[]),Se=i.useCallback(de=>{xe(de)&&(de.preventDefault(),de.stopPropagation(),de.dataTransfer.dropEffect="copy",C(!0))},[xe]),qe=i.useCallback(de=>{xe(de)&&(de.preventDefault(),de.stopPropagation(),C(!1))},[xe]),We=i.useCallback(async de=>{if(!xe(de))return;de.preventDefault(),de.stopPropagation(),C(!1);const Ne=Array.from(de.dataTransfer.files);for(const Ye of Ne)try{await $r(e.id,Ye,n),r(`Attached ${Ye.name} to ${e.id}`,"success")}catch(ft){r(`Failed to attach ${Ye.name}: ${_e(ft)}`,"error")}},[e.id,xe,r]),Qe=i.useCallback(()=>{A||a(e)},[e,a,A]),ve=i.useCallback(de=>{if(H.current){H.current=!1;return}ge(de.target)||Qe()},[Qe,ge]),Oe=i.useCallback(de=>{const Ne=de.touches[0];Ne&&(ee.current={x:Ne.clientX,y:Ne.clientY,time:Date.now()},ie.current=!1)},[]),ae=i.useCallback(de=>{if(!ee.current)return;const Ne=de.touches[0];if(!Ne)return;const Ye=Math.abs(Ne.clientX-ee.current.x),ft=Math.abs(Ne.clientY-ee.current.y);(Ye>xm||ft>xm)&&(ie.current=!0)},[]),re=i.useCallback(de=>{if(ge(de.target)||!ee.current)return;const Ye=Date.now()-ee.current.time<DS,ft=!ie.current;Ye&&ft&&(H.current=!0,Qe()),ee.current=null,ie.current=!1},[Qe,ge]),je=i.useCallback(async(de,Ne)=>{de.stopPropagation();try{const Ye=await Ia(Ne,n);a(Ye)}catch{r(`Failed to load dependency ${Ne}`,"error")}},[a,r]),Q=e.status==="failed",Fe=e.paused===!0,Je=gS(e.priority),be=Je!==Cs,ze=rl(e,f,x),tt=e.column==="triage"&&e.status==="awaiting-approval",kt=e.column==="archived",ke=!o&&!s&&!Q&&!Fe&&!ze&&!tt&&(e.column==="in-progress"||mm.has(e.status)),ce=!s&&!Fe&&!A&&!kt,Te=xS.has(e.column)&&!ke&&!Fe&&!s&&l,he=!!(e.prInfo||e.issueInfo),Le=e.sourceType==="github_import",st=_S(e.sourceMetadata),it=!!(e.assignedAgentId&&P===null),lt=i.useMemo(()=>{const de=[];return e.modelProvider&&de.push(e.modelProvider),e.validatorModelProvider&&!de.includes(e.validatorModelProvider)&&de.push(e.validatorModelProvider),e.planningModelProvider&&!de.includes(e.planningModelProvider)&&de.push(e.planningModelProvider),de},[e.modelProvider,e.validatorModelProvider,e.planningModelProvider]),$e=i.useMemo(()=>Pf(e,v),[e.steps,e.enabledWorkflowSteps,e.workflowStepResults,v]),Ue=$e.total>0&&(e.status==="executing"||e.column==="in-progress");i.useEffect(()=>{if(e.column!=="in-progress"&&e.column!=="in-review")return;const de=e.status!=null&&hm.has(e.status);if(e.column==="in-progress"){const Ye=yr(e,Date.now()),ft=pm(e,Date.now()),tn=wr(e,Date.now());if(Ye==null&&ft==null&&tn==null)return}if(!de&&e.column==="in-review"){const Ye=yr(e,Date.now()),ft=wr(e,Date.now());if(Ye==null&&ft==null)return}$(Date.now());const Ne=window.setInterval(()=>{$(Date.now())},wS);return()=>window.clearInterval(Ne)},[e.column,e.status,e.columnMovedAt,e.updatedAt,e.workflowStepResults,e.timedExecutionMs,e.executionStartedAt,e.executionCompletedAt]);const Xe=i.useMemo(()=>{if(!yS.has(e.column))return null;if(e.status!=null&&hm.has(e.status)){const $t=NS(e,I);if($t!=null){const Rt=gm($t);if(Rt){const Dt=Tf(e,I),En=Dt==null?null:fm(Dt),bn=En?`Execution time ${Rt}. Merge phase ${En}`:`Execution time ${Rt}. Merging`;return{label:Rt,title:bn,ariaLabel:bn}}}}if(e.column==="in-progress"){const $t=yr(e,I)??pm(e,I)??wr(e,I);if($t==null)return null;const Rt=fm($t);return Rt?{label:Rt,title:`In progress ${Rt}`,ariaLabel:`In progress ${Rt}`}:null}const Ne=yr(e,I)??wr(e,I);if(Ne==null)return null;const Ye=gm(Ne);if(!Ye)return null;const ft=jS(e);if(ft==null)return{label:Ye,title:`Execution time ${Ye}`,ariaLabel:`Execution time ${Ye}`};const tn=new Date(ft).toLocaleString();return{label:Ye,title:`Execution time ${Ye}. Completed ${tn}`,ariaLabel:`Execution time ${Ye}. Completed ${tn}`}},[e.column,e.status,e.columnMovedAt,e.timedExecutionMs,e.updatedAt,e.workflowStepResults,e.log,e.executionStartedAt,e.executionCompletedAt,I]);i.useEffect(()=>{if(!he||!le){te(e.id);return}return U(e.id),()=>{te(e.id)}},[he,le,U,e.id,te]);const wt=ye.get(`${n??"default"}:${e.id}`),Re=e.column==="in-progress"||e.column==="in-review",xt=i.useMemo(()=>e.steps.map(de=>`${de.name}:${de.status}`).join("|"),[e.steps]),{stats:Pt}=rS(e.id,e.column,e.mergeDetails?.commitSha,n,{enabled:le,worktree:e.worktree,stepVersion:Re?xt:void 0,pollIntervalMs:Re?3e4:void 0}),Ct=i.useMemo(()=>tS(e.id,n),[e.id,n]),Ot=i.useMemo(()=>{const de=wt?.prInfo,Ne=wt?.timestamp,Ye=Ct?.result?.prInfo,ft=Ct?.timestamp?new Date(Ct.timestamp).toISOString():void 0,tn=e.prInfo,$t=e.prInfo?.lastCheckedAt??e.updatedAt;let Rt=al(de,Ne,tn,$t);const Dt=Ne&&Ne>=$t?Ne:$t;return Ye&&ft&&(!Dt||ft>Dt)&&(Rt=Ye),Rt},[wt,Ct,e.prInfo,e.updatedAt]),zt=i.useMemo(()=>{const de=wt?.issueInfo,Ne=wt?.timestamp,Ye=Ct?.result?.issueInfo,ft=Ct?.timestamp?new Date(Ct.timestamp).toISOString():void 0,tn=e.issueInfo,$t=e.issueInfo?.lastCheckedAt??e.updatedAt;let Rt=al(de,Ne,tn,$t);const Dt=Ne&&Ne>=$t?Ne:$t;return Ye&&ft&&(!Dt||ft>Dt)&&(Rt=Ye),Rt},[wt,Ct,e.issueInfo,e.updatedAt]),Nt=i.useCallback(de=>{de?.stopPropagation(),!(!Te||T)&&(N(!0),_(e.description||""))},[Te,T,e.description]),jt=i.useCallback(()=>{N(!1),_(e.description||"")},[e.description]),Yt=i.useCallback(()=>S!==(e.description||""),[S,e.description]),Bt=i.useCallback(async()=>{if(!(!l||T)){if(!Yt()){jt();return}M(!0);try{await l(e.id,{description:S.trim()||void 0}),r(`Updated ${e.id}`,"success"),N(!1)}catch(de){r(`Failed to update ${e.id}: ${_e(de)}`,"error")}finally{M(!1)}}},[l,e.id,S,T,Yt,jt,r]),qt=i.useCallback(de=>{de.key==="Enter"&&!de.shiftKey?(de.preventDefault(),Bt()):de.key==="Escape"&&(de.preventDefault(),jt())},[Bt,jt]),wn=i.useCallback(()=>{setTimeout(()=>{const de=document.activeElement;de===w.current||de?.closest(".card-editing-content")||(Yt()?Bt():jt())},0)},[Yt,Bt,jt]),mn=i.useCallback(de=>{Te&&(de.stopPropagation(),Nt(de))},[Te,Nt]),Xt=i.useCallback(de=>{de.stopPropagation(),Nt(de)},[Nt]),Vt=i.useCallback(de=>{_(de.target.value);const Ne=de.target;Ne.style.height="auto",Ne.style.height=Ne.scrollHeight+"px"},[]),Ft=i.useCallback(de=>{de.stopPropagation(),c&&c(e.id).then(()=>{r(`Archived ${e.id}`,"success")}).catch(Ne=>{r(`Failed to archive ${e.id}: ${_e(Ne)}`,"error")})},[r,c,e.id]),Zt=i.useCallback(de=>{de.stopPropagation(),d&&d(e.id).then(()=>{r(`Unarchived ${e.id}`,"success")}).catch(Ne=>{r(`Failed to unarchive ${e.id}: ${_e(Ne)}`,"error")})},[r,d,e.id]),en=i.useCallback(async de=>{if(de.stopPropagation(),!(!u||!await ne({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0})))try{await u(e.id),r(`Deleted ${e.id}`,"success")}catch(Ye){const ft=AS(Ye);if(!ft||ft.dependentIds.length===0){r(`Failed to delete ${e.id}: ${_e(Ye)}`,"error");return}const tn=ft.dependentIds.join(", ");if(!await ne({title:"Force Delete Task",message:`${e.id} is a dependency of ${tn}.
642
+
643
+ Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await u(e.id,{removeDependencyReferences:!0}),r(`Deleted ${e.id} after removing dependency references`,"success")}catch(Rt){r(`Failed to delete ${e.id}: ${_e(Rt)}`,"error")}}},[r,ne,u,e.id]),cn=i.useCallback(de=>{de.stopPropagation(),h?.(e,"changes")},[e,h]),we=i.useCallback(de=>{de.stopPropagation(),L(Ne=>!Ne)},[]),De=i.useCallback(de=>{de.stopPropagation(),e.missionId&&p&&p(e.missionId)},[e.missionId,p]),oe=i.useCallback(de=>{de.stopPropagation(),Z(Ne=>!Ne)},[]),Pe=i.useCallback(async(de,Ne)=>{if(de.stopPropagation(),Z(!1),!!g)try{const Ye=e.steps.some($t=>$t.status!=="pending"),ft=(Ne==="todo"||Ne==="triage")&&Ye;let tn;if(ft){if(await ne({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))tn={preserveProgress:!0};else if(!await ne({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await g(e.id,Ne,tn),r(`Moved ${e.id} to ${Qn[Ne]}`,"success")}catch(Ye){r(`Failed to move ${e.id}: ${_e(Ye)}`,"error")}},[r,ne,g,e.id,e.steps]),Ce=i.useCallback(async de=>{if(de.stopPropagation(),!(!m||z)){k(!0);try{await m(e.id)}catch(Ne){r(`Failed to retry ${e.id}: ${_e(Ne)}`,"error")}finally{k(!1)}}},[r,z,m,e.id]),J=`card${b?" dragging":""}${s?" queued":""}${ke?" agent-active":""}${Q?" failed":""}${Fe?" paused":""}${ze?" stuck":""}${tt?" awaiting-approval":""}${j?" file-drop-target":""}${A?" card-editing":""}${T?" card-saving":""}`,Ie=(()=>{if(e.column==="in-progress"){const de=Pt?.filesChanged,Ne=de==null||de===0?e.modifiedFiles?.length:void 0,Ye=de!=null&&de>0?de:Ne;return Ye==null||Ye===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:cn,disabled:!h,children:[t.jsx(os,{size:12}),t.jsxs("span",{children:[Ye," ",Ye===1?"file":"files"," changed"]})]})}if(e.column==="in-review"){const de=Pt?.filesChanged,Ne=de==null||de===0?e.modifiedFiles?.length:void 0,Ye=de!=null&&de>0?de:Ne;return Ye==null||Ye===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:cn,disabled:!h,children:[t.jsx(os,{size:12}),t.jsxs("span",{children:[Ye," ",Ye===1?"file":"files"," changed"]})]})}if(e.column==="done"){const de=Pt?.filesChanged,Ne=e.mergeDetails?.filesChanged,Ye=de??Ne;if(Ye!=null&&Ye>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:cn,disabled:!h,children:[t.jsx(os,{size:12}),t.jsxs("span",{children:[Ye," ",Ye===1?"file":"files"," changed"]})]});const ft=e.modifiedFiles?.length;if(ft!=null&&ft>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:cn,disabled:!h,children:[t.jsx(os,{size:12}),t.jsxs("span",{children:[ft," ",ft===1?"file":"files"," changed"]})]})}return null})();return A?t.jsx("div",{ref:K,className:J,"data-id":e.id,onDoubleClick:mn,children:t.jsxs("div",{className:"card-editing-content",children:[t.jsx("textarea",{ref:w,className:"card-edit-desc-textarea",placeholder:"Task description",value:S,onChange:Vt,onKeyDown:qt,onBlur:wn,disabled:T,rows:4}),T&&t.jsxs("div",{className:"card-edit-loading",children:[t.jsx("span",{className:"card-edit-loading-spinner"}),t.jsx("span",{className:"card-edit-loading-text",children:"Saving..."})]})]})}):t.jsxs("div",{ref:K,className:J,"data-id":e.id,draggable:ce,onDragStart:ce?se:void 0,onDragEnd:ce?Ae:void 0,onDragOver:Se,onDragLeave:qe,onDrop:We,onClick:ve,onTouchStart:Oe,onTouchMove:ae,onTouchEnd:re,onDoubleClick:mn,children:[t.jsxs("div",{className:"card-header",children:[t.jsx("span",{className:"card-id",children:e.id}),Fe&&t.jsx("span",{className:"card-status-badge paused",children:"paused"}),!Fe&&e.status&&e.status!=="queued"&&t.jsx("span",{className:`card-status-badge card-status-badge--${e.column}${tt?" awaiting-approval":""}${mm.has(e.status)?" pulsing":""}${Q?" failed":""}${ze?" stuck":""}`,children:ze?"Stuck":tt?"Awaiting Approval":e.status}),ze&&(Fe||!e.status||e.status==="queued")&&t.jsx("span",{className:"card-status-badge stuck",children:"Stuck"}),he&&t.jsx(Mf,{prInfo:Ot,issueInfo:zt}),be&&t.jsx("span",{className:`card-priority-badge card-priority-badge--${Je}`,children:Je}),e.executionMode==="fast"&&t.jsxs("span",{className:"card-execution-mode-badge card-execution-mode-badge--fast",title:"Fast mode","aria-label":"Fast mode",children:[t.jsx(Xn,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),e.missionId&&t.jsxs("span",{className:"card-mission-badge",onClick:De,title:`Mission: ${F??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}),pS(F??e.missionId)]}),t.jsxs("div",{className:"card-header-actions",children:[Te&&t.jsx("button",{className:"card-edit-btn",onClick:Xt,title:"Edit task","aria-label":"Edit task",children:t.jsx(xs,{size:12})}),e.column==="triage"&&u&&t.jsx("button",{className:"card-delete-btn",onClick:en,title:"Delete task","aria-label":"Delete task",children:t.jsx(Cn,{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"&&d&&t.jsx("button",{className:"card-unarchive-btn",onClick:Zt,title:"Unarchive task","aria-label":"Unarchive task",children:"Unarchive"}),e.column==="in-progress"&&g&&t.jsxs("div",{className:"card-send-back",ref:pe,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:oe,title:"Send back","aria-label":"Send back","aria-haspopup":"menu","aria-expanded":q,children:["Send back",t.jsx(un,{size:10})]}),q&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:fd["in-progress"].filter(de=>de!=="in-review").map(de=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:Ne=>Pe(Ne,de),children:Qn[de]},de))})]}),e.column==="in-review"&&g&&t.jsxs("div",{className:"card-send-back",ref:pe,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:oe,title:"Move task","aria-label":"Move task","aria-haspopup":"menu","aria-expanded":q,children:["Move",t.jsx(un,{size:10})]}),q&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:fd["in-review"].map(de=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:Ne=>Pe(Ne,de),children:de==="done"?"Done (no merge)":Qn[de]},de))})]}),e.size&&t.jsx("span",{className:`card-size-badge size-${e.size.toLowerCase()}`,children:e.size})]})]}),Q&&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:Ce,disabled:z,children:[t.jsx(ty,{size:12}),z?"Retrying…":"Retry"]})]}),t.jsx("div",{className:"card-title",title:e.title||e.description||void 0,children:ym(e.title,vm)||ym(e.description,vm)||e.id}),Ue&&(()=>{const de=$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:`${de}%`,backgroundColor:vS[e.column]}})}),t.jsxs("span",{className:"card-progress-label",children:[$e.completed,"/",$e.total]})]}),t.jsxs("button",{type:"button",className:"card-steps-toggle",onClick:we,"aria-expanded":E,"aria-label":E?"Hide steps":"Show steps",children:[t.jsxs("span",{children:[$e.total," step",$e.total===1?"":"s"]}),t.jsx(un,{size:14,className:`card-steps-toggle-icon${E?" expanded":""}`})]}),E&&t.jsx("div",{className:"card-steps-list",children:$e.items.map(Ne=>{const Ye=Ne.source==="workflow"&&Ne.status==="failed";return t.jsxs("div",{className:"card-step-item",children:[t.jsx("span",{className:`card-step-dot card-step-dot--${Ne.status}${Ye?" card-step-dot--workflow-failed":""}`,"aria-hidden":"true"}),t.jsx("span",{className:`card-step-name${Ne.status==="done"?" completed":""}`,children:Ne.name}),Ne.source==="workflow"&&t.jsx("span",{className:`card-step-workflow-badge card-step-workflow-badge--${Ne.phase}`,title:"Workflow check",children:"workflow"})]},Ne.id)})})]})})(),(Ie||Xe||Le)&&t.jsxs("div",{className:"card-footer-row",children:[Ie,Le&&t.jsx("span",{className:"card-source-provenance",title:st?`Imported from GitHub: ${st}`:"Imported from GitHub","aria-label":"Imported from GitHub",children:t.jsx(qn,{provider:"github",size:"sm"})}),Xe&&t.jsxs("span",{className:"card-time-indicator",title:Xe.title,"aria-label":Xe.ariaLabel,children:[t.jsx(_i,{size:12}),t.jsx("span",{children:Xe.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(de=>t.jsxs("span",{className:"card-dep-badge clickable",onClick:Ne=>void je(Ne,de),title:`Click to view ${de}`,children:[t.jsx(Pa,{size:12,style:{verticalAlign:"middle"}})," ",de]},de))}),e.blockedBy&&t.jsxs("span",{className:"card-scope-badge","data-tooltip":`Blocked by ${e.blockedBy} (file overlap)`,children:[t.jsx(na,{size:12,style:{verticalAlign:"middle"}})," ",e.blockedBy]}),(s||e.status==="queued")&&e.column!=="in-progress"&&t.jsxs("span",{className:"queued-badge",children:[t.jsx(_i,{size:12,style:{verticalAlign:"middle"}})," Queued"]})]}),(e.assignedAgentId||lt.length>0)&&t.jsxs("div",{className:"card-agent-row",children:[lt.length>0&&t.jsx("span",{className:"card-provider-icons","data-testid":"card-provider-icons",children:lt.map(de=>t.jsx(qn,{provider:de,size:"sm"},de))}),e.assignedAgentId&&t.jsxs("span",{className:`card-agent-badge${it?" card-agent-badge--loading":""}`,title:`Assigned to ${P??e.assignedAgentId}`,children:[t.jsx(Rn,{size:11}),t.jsx("span",{className:"card-agent-badge-text",children:bS(P??e.assignedAgentId,15)})]})]}),t.jsx(Oi,{slotId:"task-card-badge",projectId:n})]})}const xm=10,DS=300,vm=140;function ym(e,n){return e?e.length>n?e.slice(0,n)+"…":e:""}const Or=i.memo($S,IS);Or.displayName="TaskCard";function LS({label:e,activeTasks:n,queuedTasks:s,projectId:a,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:d,onOpenDetailWithTab:u,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p}){return t.jsxs("div",{className:"worktree-group",children:[t.jsxs("div",{className:"worktree-group-header",children:[t.jsx("span",{className:"worktree-icon",children:e==="Up Next"||e==="Unassigned"?t.jsx(wx,{size:14}):t.jsx(Hs,{size:14})}),t.jsx("span",{className:"worktree-label",children:e})]}),n.map(g=>t.jsx(Or,{task:g,projectId:a,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:d,onOpenDetailWithTab:u,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p},g.id)),s.map(g=>t.jsx(Or,{task:g,projectId:a,queued:!0,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:d,onOpenDetailWithTab:u,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p},g.id))]})}const If=i.memo(LS);If.displayName="WorktreeGroup";function wm(e){return e.toLowerCase().replace(/[-_./]/g,"")}function OS(e,n){let s=0;for(let a=0;a<n.length&&s<e.length;a++)e[s]===n[a]&&s++;return s===e.length}function zS(e,n,s){const a=e.length,r=n.length;if(a===0)return!0;if(r===0)return!1;let o=new Array(r+1).fill(0),l=new Array(r+1).fill(0);for(let c=1;c<=a;c++){const d=new Array(r+1);d[0]=c;for(let u=1;u<=r;u++){const m=e[c-1]===n[u-1]?0:1;d[u]=Math.min(l[u]+1,d[u-1]+1,l[u-1]+m),c>=2&&u>=2&&e[c-1]===n[u-2]&&e[c-2]===n[u-1]&&(d[u]=Math.min(d[u],o[u-2]+1))}o=l,l=d}for(let c=0;c<=r;c++)if(l[c]<=s)return!0;return!1}function FS(e,n){const s=wm(e),a=wm(n);if(s.length===0||a.includes(s))return!0;const r=a.split(/\s+/).filter(Boolean);for(const o of r)if(s.length>=3&&OS(s,o)||s.length>=4&&zS(s,o,1))return!0;return!1}function US(e,n){const s=n.toLowerCase().trim().split(/\s+/).filter(Boolean);return s.length===0?e:e.filter(a=>{const r=`${a.provider} ${a.id} ${a.name}`;return s.every(o=>FS(o,r))})}function hs({models:e,value:n,onChange:s,placeholder:a="Select a model…",disabled:r=!1,id:o,label:l,favoriteProviders:c=[],onToggleFavorite:d,favoriteModels:u=[],onToggleModelFavorite:m,noChangeValue:h,noChangeLabel:f="No change"}){const[p,g]=i.useState(!1),[x,v]=i.useState(""),[b,y]=i.useState(0),[j,C]=i.useState(null),[A,N]=i.useState(null),S=i.useRef(null),_=i.useRef(null),T=i.useRef(null),M=i.useRef(null),E=i.useRef(null),L=i.useMemo(()=>US(e,x),[e,x]),F=i.useMemo(()=>L.reduce((ne,ee)=>((ne[ee.provider]??=[]).push(ee),ne),{}),[L]),R=i.useMemo(()=>{const ne=[];for(const ee of u){const ie=ee.indexOf("/");if(ie===-1)continue;const ge=ee.slice(0,ie),se=ee.slice(ie+1),Ae=L.find(xe=>xe.provider===ge&&xe.id===se);Ae&&ne.push({model:Ae,fullId:ee})}return ne},[u,L]),P=i.useMemo(()=>{const ne=Object.entries(F),ee=new Set(c);return ne.sort(([ie],[ge])=>{const se=ee.has(ie),Ae=ee.has(ge);if(se&&!Ae)return-1;if(!se&&Ae)return 1;if(se&&Ae){const xe=c.indexOf(ie),Se=c.indexOf(ge);if(xe!==Se)return xe-Se}return ie.localeCompare(ge)})},[F,c]),O=typeof h=="string"&&h.length>0,q=i.useMemo(()=>{if(!n||O&&n===h)return null;const ne=n.indexOf("/");return ne===-1?null:n.slice(0,ne)},[O,h,n]),Z=i.useMemo(()=>{const ne=[];return O&&ne.push({type:"no-change",value:h,label:f}),ne.push({type:"default",value:"",label:"Use default"}),ne},[O,f,h]),z=i.useMemo(()=>{const ne=[...Z];for(const{model:ee,fullId:ie}of R)ne.push({type:"favorite",value:ie,label:ee.name,provider:ee.provider});return P.forEach(([ee,ie])=>{ne.push({type:"provider",value:`__group_${ee}`,label:ee,provider:ee}),ie.forEach(ge=>{ne.push({type:"model",value:`${ge.provider}/${ge.id}`,label:ge.name,provider:ge.provider})})}),ne},[R,P,Z]),k=i.useMemo(()=>{if(O&&n===h)return f;if(!n)return"Use default";const ne=n.indexOf("/");if(ne===-1)return n;const ee=n.slice(0,ne),ie=n.slice(ne+1);return e.find(se=>se.provider===ee&&se.id===ie)?.name||n},[O,f,h,n,e]),I=i.useMemo(()=>z.findIndex(ne=>ne.value===n),[z,n]),$=i.useCallback(()=>{const ne=window.visualViewport;return ne&&ne.height>0&&ne.width>0?{width:ne.width,height:ne.height,offsetTop:ne.offsetTop,offsetLeft:ne.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),w=i.useCallback(()=>{const{height:ne}=$(),ee=typeof window.matchMedia=="function",ie=ee?window.matchMedia("(max-width: 640px)").matches:!1,ge=ee?window.matchMedia("(max-width: 768px)").matches:!1;return ne<=0?320:ie?Math.min(ne*.6,360):ge?Math.min(ne*.7,420):320},[$]),H=i.useCallback(()=>{const ne=_.current;if(!ne)return;const ee=ne.getBoundingClientRect(),{width:ie,height:ge,offsetTop:se,offsetLeft:Ae}=$(),xe=16,Se=16,qe=4,We=w(),Qe=ee.bottom-se,ve=ee.top-se,Oe=ee.left-Ae,ae=ge-Qe,re=ve,je=Math.max(ae-Se-qe,160),Q=Math.max(re-Se-qe,160),Fe=ae<We&&re>ae,Je=Math.max(Math.min(Fe?Q:je,We),160),be=Math.min(ee.width,ie-xe*2),ze=Math.min(Math.max(Oe,xe),ie-xe-be)+Ae,tt=Fe?Math.max(Se+se,ve-Je-qe+se):Math.min(Qe+qe+se,ge+se-Se-Je);C({top:tt,left:ze,width:be,maxHeight:Je})},[$,w]);i.useEffect(()=>{N(document.body)},[]);const K=i.useRef(!1);i.useEffect(()=>{if(!p){K.current=!1;return}if(K.current||z.length===0)return;const ne=z.findIndex((ee,ie)=>ie>=(I>=0?I:0)&&ee.type!=="provider");y(ne>=0?ne:0),K.current=!0},[p,z,I]),i.useEffect(()=>{p&&K.current&&(y(0),E.current&&(E.current.scrollTop=0))},[x,p]),i.useEffect(()=>{if(!p)return;H();const ne=requestAnimationFrame(()=>M.current?.focus());return()=>cancelAnimationFrame(ne)},[p,H]),i.useEffect(()=>{if(!p)return;const ne=()=>H();window.addEventListener("resize",ne),window.addEventListener("scroll",ne,!0);const ee=window.visualViewport;return ee&&(ee.addEventListener("resize",ne),ee.addEventListener("scroll",ne)),()=>{window.removeEventListener("resize",ne),window.removeEventListener("scroll",ne,!0),ee&&(ee.removeEventListener("resize",ne),ee.removeEventListener("scroll",ne))}},[p,H]),i.useEffect(()=>{if(!p)return;const ne=ee=>{const ie=ee.target,ge=S.current?.contains(ie),se=T.current?.contains(ie);!ge&&!se&&(g(!1),v(""))};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[p]);const pe=i.useCallback(ne=>{switch(ne.key){case"ArrowDown":if(ne.preventDefault(),!p)g(!0);else{let ee=b;for(let ie=1;ie<=z.length;ie++){const ge=(b+ie)%z.length;if(z[ge]?.type!=="provider"){ee=ge;break}}y(ee)}break;case"ArrowUp":if(ne.preventDefault(),p){let ee=b;for(let ie=1;ie<=z.length;ie++){const ge=(b-ie+z.length)%z.length;if(z[ge]?.type!=="provider"){ee=ge;break}}y(ee)}break;case"Enter":if(ne.preventDefault(),p){const ee=z[b];ee&&ee.type!=="provider"&&ee.type!=="favorite"&&(s(ee.value),g(!1),v(""))}else g(!0);break;case"Escape":ne.preventDefault(),g(!1),v("");break;case"Tab":p&&(g(!1),v(""));break}},[p,b,z,s]),le=i.useCallback(ne=>{s(ne),g(!1),v("")},[s]),B=i.useCallback(()=>{v(""),M.current?.focus()},[]),ye=i.useCallback(()=>{r||g(ne=>!ne)},[r]);i.useEffect(()=>{if(p&&E.current){const ne=E.current.querySelector(`[data-index="${b}"]`);ne&&typeof ne.scrollIntoView=="function"&&ne.scrollIntoView({block:"nearest"})}},[b,p]);const U=x.length>0,te=p&&j?t.jsxs("div",{ref:T,className:"model-combobox-dropdown model-combobox-dropdown--portal",role:"listbox","data-testid":"model-combobox-portal",onKeyDown:pe,style:{top:`${j.top}px`,left:`${j.left}px`,width:`${j.width}px`,maxHeight:`${j.maxHeight}px`},children:[t.jsxs("div",{className:"model-combobox-search-wrapper",children:[t.jsx("input",{ref:M,type:"text",className:"model-combobox-search",placeholder:"Filter models…",value:x,onChange:ne=>v(ne.target.value),onClick:ne=>ne.stopPropagation()}),U&&t.jsx("button",{type:"button",className:"model-combobox-clear",onClick:B,"aria-label":"Clear filter",children:"×"})]}),t.jsxs("div",{className:"model-combobox-results-count",children:[L.length," model",L.length!==1?"s":""]}),t.jsxs("div",{ref:E,className:"model-combobox-list",children:[Z.map((ne,ee)=>t.jsx("div",{"data-index":ee,className:`model-combobox-option ${b===ee?"model-combobox-option--highlighted":""} ${n===ne.value?"model-combobox-option--selected":""}`,onClick:()=>le(ne.value),onMouseEnter:()=>y(ee),role:"option","aria-selected":n===ne.value,children:t.jsx("span",{className:"model-combobox-option-text model-combobox-option-text--default",children:ne.label})},`${ne.type}-${ne.value}`)),R.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"model-combobox-divider"}),R.map(({model:ne,fullId:ee},ie)=>{const ge=ie+Z.length,se=b===ge,Ae=n===ee;return t.jsxs("div",{"data-index":ge,className:`model-combobox-option model-combobox-option--favorite ${se?"model-combobox-option--highlighted":""} ${Ae?"model-combobox-option--selected":""}`,onClick:()=>le(ee),onMouseEnter:()=>y(ge),role:"option","aria-selected":Ae,children:[t.jsxs("span",{className:"model-combobox-option-main",children:[t.jsx("span",{className:"model-combobox-option-icon",children:t.jsx(qn,{provider:ne.provider,size:"sm"})}),t.jsx("span",{className:"model-combobox-option-text",children:ne.name})]}),t.jsx("span",{className:"model-combobox-option-id",children:ne.id}),m&&t.jsx("button",{type:"button",className:"model-combobox-option-favorite model-combobox-option-favorite--active",onClick:xe=>{xe.stopPropagation(),m(ee)},title:"Remove from favorites","aria-label":`Remove ${ne.name} from favorites`,children:"★"})]},ee)}),t.jsx("div",{className:"model-combobox-divider"})]}),P.map(([ne,ee])=>{const ie=z.findIndex(Ae=>Ae.value===`__group_${ne}`),ge=c.includes(ne),se=ee.filter(Ae=>{const xe=`${Ae.provider}/${Ae.id}`;return!u.includes(xe)});return se.length===0?null:t.jsxs("div",{className:"model-combobox-group",children:[t.jsxs("div",{className:"model-combobox-optgroup","data-index":ie,children:[t.jsx(qn,{provider:ne,size:"sm"}),t.jsx("span",{className:"model-combobox-optgroup-text",children:ne}),d&&t.jsx("button",{type:"button",className:`model-combobox-optgroup-favorite ${ge?"model-combobox-optgroup-favorite--active":""}`,onClick:Ae=>{Ae.stopPropagation(),d(ne)},title:ge?"Remove from favorites":"Add to favorites","aria-label":ge?`Remove ${ne} from favorites`:`Add ${ne} to favorites`,children:"★"})]}),se.map(Ae=>{const xe=`${Ae.provider}/${Ae.id}`,Se=z.findIndex(ve=>ve.value===xe),qe=b===Se,We=n===xe,Qe=u.includes(xe);return t.jsxs("div",{"data-index":Se,className:`model-combobox-option ${qe?"model-combobox-option--highlighted":""} ${We?"model-combobox-option--selected":""}`,onClick:()=>le(xe),onMouseEnter:()=>y(Se),role:"option","aria-selected":We,children:[t.jsx("span",{className:"model-combobox-option-text",children:Ae.name}),t.jsx("span",{className:"model-combobox-option-id",children:Ae.id}),m&&t.jsx("button",{type:"button",className:`model-combobox-option-favorite ${Qe?"model-combobox-option-favorite--active":""}`,onClick:ve=>{ve.stopPropagation(),m(xe)},title:Qe?"Remove from favorites":"Add to favorites","aria-label":Qe?`Remove ${Ae.name} from favorites`:`Add ${Ae.name} to favorites`,children:Qe?"★":"☆"})]},xe)})]},ne)}),L.length===0&&U&&t.jsxs("div",{className:"model-combobox-no-results",children:["No models match '",x,"'"]})]})]}):null;return t.jsxs(t.Fragment,{children:[t.jsx("div",{ref:S,className:"model-combobox",onKeyDown:pe,children:t.jsxs("button",{ref:_,type:"button",id:o,className:"model-combobox-trigger",onClick:ye,disabled:r,"aria-haspopup":"listbox","aria-expanded":p,"aria-label":l,children:[q&&t.jsx("span",{className:"model-combobox-trigger-icon",children:t.jsx(qn,{provider:q,size:"sm"})}),t.jsx("span",{className:"model-combobox-trigger-text",children:k||a}),t.jsx("span",{className:"model-combobox-trigger-arrow",children:"▼"})]})}),A&&te?Qi.createPortal(te,A):null]})}function Yd(e,n){return typeof n!="string"||n.length===0?e:`kb:${n}:${e}`}function Zn(e,n){return typeof window>"u"?null:window.localStorage.getItem(Yd(e,n))}function us(e,n,s){typeof window>"u"||window.localStorage.setItem(Yd(e,s),n)}function La(e,n){typeof window>"u"||window.localStorage.removeItem(Yd(e,n))}const BS=1e4,HS=1e3;function Al(){const[e,n]=i.useState([]),[s,a]=i.useState(!0),[r,o]=i.useState(null),l=i.useRef(null),c=i.useRef(0),d=i.useCallback(async()=>{try{o(null);const p=await sl();n(p)}catch(p){o(p instanceof Error?p.message:"Failed to fetch nodes")}},[]);i.useEffect(()=>{let p=!1;async function g(){a(!0);try{const v=await sl();p||(n(v),o(null))}catch(v){p||o(v instanceof Error?v.message:"Failed to fetch nodes")}finally{p||a(!1)}}g();const x=()=>{if(document.visibilityState!=="visible")return;const v=Date.now();v-c.current<HS||(c.current=v,d())};return document.addEventListener("visibilitychange",x),()=>{p=!0,document.removeEventListener("visibilitychange",x)}},[d]),i.useEffect(()=>{if(!s)return l.current=setInterval(()=>{d()},BS),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,d]);const u=i.useCallback(async p=>{const g=await gj(p);return n(x=>[...x,g]),g},[]),m=i.useCallback(async(p,g)=>{const x=await bj(p,g);return n(v=>v.map(b=>b.id===p?x:b)),x},[]),h=i.useCallback(async p=>{await xj(p),n(g=>g.filter(x=>x.id!==p))},[]),f=i.useCallback(async p=>{const g=await vj(p);n(x=>x.map(v=>v.id===p?{...v,status:g.status,updatedAt:g.checkedAt}:v))},[]);return{nodes:e,loading:s,error:r,refresh:d,register:u,update:m,unregister:h,healthCheck:f}}const ir="kb-quick-entry-text",qS=["image/png","image/jpeg","image/gif","image/webp"];function VS(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function ic(e,n){return e&&n?`${e}/${n}`:""}function ac(e){if(!e)return{provider:void 0,modelId:void 0};const n=e.indexOf("/");return n===-1?{provider:void 0,modelId:void 0}:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function $f({onCreate:e,addToast:n,tasks:s=[],availableModels:a,onPlanningMode:r,onSubtaskBreakdown:o,projectId:l,autoExpand:c=!0,favoriteProviders:d,favoriteModels:u,onToggleFavorite:m,onToggleModelFavorite:h}){const[f,p]=i.useState(()=>typeof window<"u"&&Zn(ir,l)||""),[g,x]=i.useState(!1),[v,b]=i.useState(!1),[y,j]=i.useState(!1),C=i.useRef(null),A=i.useRef(null),N=i.useRef(!1),S=i.useRef(l),[_,T]=i.useState([]),M=i.useRef([]),[E,L]=i.useState([]),[F,R]=i.useState(!1),[P,O]=i.useState(""),[q,Z]=i.useState(null),[z,k]=i.useState([]),[I,$]=i.useState(void 0),[w,H]=i.useState(!1),[K,pe]=i.useState(!1),[le,B]=i.useState(!1),[ye,U]=i.useState(!1),[te,ne]=i.useState(!1),[ee,ie]=i.useState(null),[ge,se]=i.useState(void 0),[Ae,xe]=i.useState(void 0),[Se,qe]=i.useState(void 0),[We,Qe]=i.useState(void 0),[ve,Oe]=i.useState(void 0),[ae,re]=i.useState(void 0),je=i.useRef(null),Q=i.useRef(null),Fe=i.useRef(null),Je=i.useRef(null),be=i.useRef(null),ze=i.useRef(null),tt=i.useRef(null),kt=i.useRef(null),[ke,ce]=i.useState(null),[Te,he]=i.useState(null),[Le,st]=i.useState(null),[it,lt]=i.useState(null),$e=i.useRef(null),Ue=i.useRef(null),[Xe,wt]=i.useState(null),[Re]=i.useState(()=>typeof document<"u"?document.body:null),[xt,Pt]=i.useState(!1),[Ct,Ot]=i.useState(null),[zt,Nt]=i.useState(a??[]),[jt,Yt]=i.useState([]),[Bt,qt]=i.useState([]),[wn,mn]=i.useState(null),[Xt,Vt]=i.useState(void 0),[Ft,Zt]=i.useState(!1),[en,cn]=i.useState(Cs),[we,De]=i.useState(void 0),{nodes:oe}=Al(),[Pe,Ce]=i.useState(!1),[J,Ie]=i.useState(!1),de=i.useRef(null),Ne=i.useRef(null),[Ye,ft]=i.useState(null),tn=d??jt,$t=u??Bt,Rt=!e;i.useEffect(()=>{if(a)Nt(a),Pt(!1),Ot(null);else{let X=!1;return Pt(!0),Ot(null),Ms().then(Me=>{X||(Nt(Me.models),d||Yt(Me.favoriteProviders),u||qt(Me.favoriteModels))}).catch(Me=>{X||Ot(_e(Me)||"Failed to load models")}).finally(()=>{X||Pt(!1)}),El(l).then(Me=>{X||mn(Me)}).catch(()=>{}),()=>{X=!0}}},[a,d,u,l]);const Dt=ic(ge,Ae),En=ic(Se,We),bn=ic(ve,ae),Nn=!!(ge&&Ae),dn=!!(Se&&We),xn=!!(ve&&ae),rn=Number(Nn)+Number(dn)+Number(xn),On=Xt?wn?.modelPresets?.find(X=>X.id===Xt)?.name??"Models":rn>0?`${rn} model${rn===1?"":"s"}`:"Models",fe=i.useCallback((X,Me)=>{if(!X||!Me)return"Using default";const rt=zt.find(Mt=>Mt.provider===X&&Mt.id===Me);return rt?`${rt.provider}/${rt.id}`:`${X}/${Me}`},[zt]);i.useEffect(()=>{p(Zn(ir,l)||"")},[l]),i.useEffect(()=>{typeof window<"u"&&us(ir,f,l)},[f,l]),i.useEffect(()=>{S.current!==l&&(S.current=l,k([]),$(void 0),Z(null),H(!1),ce(null))},[l]),i.useEffect(()=>{typeof window<"u"&&localStorage.removeItem("kb-quick-entry-expanded")},[]),i.useEffect(()=>{M.current=_},[_]),i.useEffect(()=>()=>{M.current.forEach(X=>URL.revokeObjectURL(X.previewUrl))},[]);const ct=i.useCallback(()=>{const X=C.current;if(!X)return;X.style.height="auto";const Me=Math.min(X.scrollHeight,200);X.style.height=`${Me}px`},[]);i.useEffect(()=>{v&&ct()},[f,v,ct]),i.useEffect(()=>{if(!g&&f===""&&C.current){const X=setTimeout(()=>{C.current?.focus()},0);return()=>clearTimeout(X)}},[g,f]),i.useEffect(()=>{F||O("")},[F]),i.useEffect(()=>{if(!Pe)return;const X=Me=>{const rt=Me.target,Mt=de.current?.contains(rt),Be=Ne.current?.contains(rt);!Mt&&!Be&&Ce(!1)};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[Pe]),i.useEffect(()=>{if(!te)return;const X=Me=>{const rt=Me.target,Mt=je.current?.contains(rt),Be=Q.current?.contains(rt),It=rt instanceof Element&&rt.closest?.(".model-combobox-dropdown--portal")!=null;!Mt&&!Be&&!It&&(ne(!1),ie(null))};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[te]),i.useEffect(()=>{if(!K)return;const X=Me=>{const rt=Me.target;be.current?.contains(rt)||ze.current?.contains(rt)||(pe(!1),he(null))};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[K]),i.useEffect(()=>{if(!w)return;const X=Me=>{const rt=Me.target;Fe.current?.contains(rt)||Je.current?.contains(rt)||(H(!1),ce(null))};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[w]),i.useEffect(()=>{if(!le)return;const X=Me=>{const rt=Me.target;tt.current?.contains(rt)||kt.current?.contains(rt)||(B(!1),st(null))};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[le]);const hn=i.useCallback(()=>{_.forEach(X=>URL.revokeObjectURL(X.previewUrl)),T([]),A.current&&(A.current.value=""),p(""),L([]),Z(null),H(!1),ce(null),pe(!1),he(null),B(!1),st(null),se(void 0),xe(void 0),qe(void 0),Qe(void 0),Oe(void 0),re(void 0),Vt(void 0),Zt(!1),cn(Cs),De(void 0),R(!1),ne(!1),lt(null),ie(null),Ce(!1),Ie(!1),b(!1),j(!1),N.current=!0,C.current&&(C.current.style.height="auto"),typeof window<"u"&&La(ir,l)},[_,l]),zn=i.useCallback(X=>{if(!X||X.length===0)return;const Me=[];for(let rt=0;rt<X.length;rt++){const Mt=X[rt];qS.includes(Mt.type)&&Me.push({file:Mt,previewUrl:URL.createObjectURL(Mt)})}Me.length>0&&T(rt=>[...rt,...Me])},[]),ue=i.useCallback(X=>{g||zn(X.clipboardData?.files)},[zn,g]),ut=i.useCallback(X=>{T(Me=>{const rt=Me[X];return rt&&URL.revokeObjectURL(rt.previewUrl),Me.filter((Mt,Be)=>Be!==X)})},[]),yt=i.useCallback(async()=>{const X=f.trim();if(!X||g||!e)return;const Me=f;x(!0),p("");try{const rt=await e({description:X,column:"triage",dependencies:E.length?E:void 0,...q?{assignedAgentId:q}:{},modelPresetId:Xt,modelProvider:Nn?ge:void 0,modelId:Nn?Ae:void 0,validatorModelProvider:dn?Se:void 0,validatorModelId:dn?We:void 0,planningModelProvider:xn?ve:void 0,planningModelId:xn?ae:void 0,...Ft?{executionMode:"fast"}:{},priority:en,nodeId:we});if(rt&&_.length>0){const Mt=[];for(const Be of _)try{await $r(rt.id,Be.file,l)}catch{Mt.push(Be.file.name)}Mt.length>0&&n(`Failed to upload: ${Mt.join(", ")}`,"error")}hn()}catch(rt){p(Me),n(_e(rt)||"Failed to create task","error")}finally{x(!1)}},[f,g,e,E,q,Nn,ge,Ae,dn,Se,We,xn,ve,ae,_,l,n,hn,Ft,en,we]),dt=i.useCallback(X=>{if(X.key==="Enter"){if(X.shiftKey&&v)return;X.preventDefault(),yt()}else if(X.key==="Escape"){if(X.preventDefault(),ee){ie(null);return}if(te){ne(!1),lt(null);return}if(F){R(!1);return}if(Pe){Ce(!1);return}if(K){pe(!1),he(null);return}if(le){B(!1),st(null);return}if(w){H(!1),ce(null);return}f.trim()&&(p(""),C.current&&(C.current.style.height="auto"),typeof window<"u"&&La(ir,l)),b(!1),j(!1),C.current?.blur()}},[yt,f,v,F,w,K,te,ee,Pe,le,l,j]),at=i.useCallback(()=>{N.current&&(N.current=!1)},[]),vt=i.useCallback(()=>{c&&b(!0)},[c]),Ht=i.useCallback(X=>{L(Me=>Me.includes(X)?Me.filter(rt=>rt!==X):[...Me,X])},[]),Ut=i.useCallback(()=>{const X=window.visualViewport;return X&&X.width>0&&X.height>0?{width:X.width,height:X.height,offsetTop:X.offsetTop,offsetLeft:X.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),An=i.useCallback(()=>{const X=je.current;if(!X)return;const Me=X.getBoundingClientRect(),{width:rt,height:Mt,offsetTop:Be,offsetLeft:It}=Ut(),Gt=16,vn=16,ln=4,Kn=rt<=768,Gn=Math.min(Kn?Mt*.6:Mt*.5,360),ps=Math.max(Me.width*1.35,320),Fn=Kn?Math.min(rt-Gt*2,360):ps,Vn=Math.min(Fn,Math.max(rt-Gt*2,240)),Pn=Me.top-Be,fs=Me.bottom-Be,es=Me.left-It,Wn=Mt-fs,gs=Pn,Jn=Math.max(Wn-vn-ln,160),bs=Math.max(gs-vn-ln,160),ts=Wn<Gn&&gs>Wn,$s=Math.max(Math.min(ts?bs:Jn,Gn),160),Ds=Math.min(Math.max(es,Gt),rt-Gt-Vn)+It,ha=ts?Math.max(vn+Be,Pn-$s-ln+Be):Math.min(fs+ln+Be,Mt+Be-vn-$s);lt({top:ha,left:Ds,width:Vn,maxHeight:$s})},[Ut]),Wt=i.useCallback(()=>{const X=de.current?.querySelector(".refine-button");if(!X)return;const Me=X.getBoundingClientRect(),{width:rt,height:Mt,offsetTop:Be,offsetLeft:It}=Ut(),Gt=8,vn=12,ln=4,Kn=Math.min(200,Math.max(Mt-vn*2,160)),Gn=Math.min(200,rt-Gt*2),ps=Me.top-Be,Fn=Me.bottom-Be,Vn=Me.left-It,Pn=Mt-Fn,fs=ps,es=Pn<Kn&&fs>Pn,Wn=Math.min(Math.max(Vn,Gt),rt-Gt-Gn)+It,gs=es?Math.max(vn+Be,ps-Kn-ln+Be):Math.min(Fn+ln+Be,Mt+Be-vn-Kn);ft({top:gs,left:Wn})},[Ut]),Tt=i.useCallback(()=>{const X=$e.current;if(!X)return;const Me=X.getBoundingClientRect(),{width:rt,height:Mt,offsetTop:Be,offsetLeft:It}=Ut(),Gt=16,vn=16,ln=4,Kn=rt<=768,Gn=Math.min(Kn?Mt*.6:Mt*.5,320),ps=Kn?Math.min(rt-Gt*2,360):Math.max(Me.width,280),Fn=Math.min(ps,Math.max(rt-Gt*2,240)),Vn=Me.top-Be,Pn=Me.bottom-Be,fs=Me.left-It,es=Mt-Pn,Wn=Vn,gs=Math.max(es-vn-ln,200),Jn=Math.max(Wn-vn-ln,200),bs=es<Gn&&Wn>es,ts=Math.max(Math.min(bs?Jn:gs,Gn),200),$s=Math.min(Math.max(fs,Gt),rt-Gt-Fn)+It,Ds=bs?Math.max(vn+Be,Vn-ts-ln+Be):Math.min(Pn+ln+Be,Mt+Be-vn-ts);wt({top:Ds,left:$s,width:Fn,maxHeight:ts})},[Ut]),G=i.useCallback(()=>{const X=Fe.current?.querySelector("button");if(!X)return;const Me=X.getBoundingClientRect(),{width:rt,height:Mt,offsetTop:Be,offsetLeft:It}=Ut(),Gt=16,vn=16,ln=4,Kn=rt<=768,Gn=Math.min(Kn?Mt*.6:Mt*.5,320),ps=Kn?Math.min(rt-Gt*2,280):Math.max(Me.width,240),Fn=Math.min(ps,Math.max(rt-Gt*2,200)),Vn=Me.top-Be,Pn=Me.bottom-Be,fs=Me.left-It,es=Mt-Pn,Wn=Vn,gs=Math.max(es-vn-ln,160),Jn=Math.max(Wn-vn-ln,160),bs=es<Gn&&Wn>es,ts=Math.max(Math.min(bs?Jn:gs,Gn),160),$s=Math.min(Math.max(fs,Gt),rt-Gt-Fn)+It,Ds=bs?Math.max(vn+Be,Vn-ts-ln+Be):Math.min(Pn+ln+Be,Mt+Be-vn-ts);ce({top:Ds,left:$s,width:Fn,maxHeight:ts})},[Ut]),He=i.useCallback(()=>{const X=be.current?.querySelector("button");if(!X)return;const Me=X.getBoundingClientRect(),{width:rt,height:Mt,offsetTop:Be,offsetLeft:It}=Ut(),Gt=16,vn=16,ln=4,Kn=rt<=768,Gn=Math.min(Kn?Mt*.6:Mt*.5,320),ps=Kn?Math.min(rt-Gt*2,280):Math.max(Me.width,240),Fn=Math.min(ps,Math.max(rt-Gt*2,200)),Vn=Me.top-Be,Pn=Me.bottom-Be,fs=Me.left-It,es=Mt-Pn,Wn=Vn,gs=Math.max(es-vn-ln,160),Jn=Math.max(Wn-vn-ln,160),bs=es<Gn&&Wn>es,ts=Math.max(Math.min(bs?Jn:gs,Gn),160),$s=Math.min(Math.max(fs,Gt),rt-Gt-Fn)+It,Ds=bs?Math.max(vn+Be,Vn-ts-ln+Be):Math.min(Pn+ln+Be,Mt+Be-vn-ts);he({top:Ds,left:$s,width:Fn,maxHeight:ts})},[Ut]),mt=i.useCallback(()=>{const X=tt.current?.querySelector("button");if(!X)return;const Me=X.getBoundingClientRect(),{width:rt,height:Mt,offsetTop:Be,offsetLeft:It}=Ut(),Gt=16,vn=16,ln=4,Kn=220,Gn=Math.min(Math.max(Me.width,200),Math.max(rt-Gt*2,200)),ps=Me.top-Be,Fn=Me.bottom-Be,Vn=Me.left-It,Pn=Mt-Fn,fs=ps,es=Math.max(Pn-vn-ln,160),Wn=Math.max(fs-vn-ln,160),gs=Pn<Kn&&fs>Pn,Jn=Math.max(Math.min(gs?Wn:es,Kn),160),bs=Math.min(Math.max(Vn,Gt),rt-Gt-Gn)+It,ts=gs?Math.max(vn+Be,ps-Jn-ln+Be):Math.min(Fn+ln+Be,Mt+Be-vn-Jn);st({top:ts,left:bs,width:Gn,maxHeight:Jn})},[Ut]);i.useEffect(()=>{if(!te)return;const X=()=>An();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const Me=window.visualViewport;return Me&&(Me.addEventListener("resize",X),Me.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),Me&&(Me.removeEventListener("resize",X),Me.removeEventListener("scroll",X))}},[te,An]),i.useEffect(()=>{if(!Pe)return;const X=()=>Wt();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const Me=window.visualViewport;return Me&&(Me.addEventListener("resize",X),Me.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),Me&&(Me.removeEventListener("resize",X),Me.removeEventListener("scroll",X))}},[Pe,Wt]),i.useEffect(()=>{if(!F)return;const X=()=>Tt();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const Me=window.visualViewport;return Me&&(Me.addEventListener("resize",X),Me.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),Me&&(Me.removeEventListener("resize",X),Me.removeEventListener("scroll",X))}},[F,Tt]),i.useEffect(()=>{if(!w)return;const X=()=>G();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const Me=window.visualViewport;return Me&&(Me.addEventListener("resize",X),Me.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),Me&&(Me.removeEventListener("resize",X),Me.removeEventListener("scroll",X))}},[w,G]),i.useEffect(()=>{if(!K)return;const X=()=>He();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const Me=window.visualViewport;return Me&&(Me.addEventListener("resize",X),Me.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),Me&&(Me.removeEventListener("resize",X),Me.removeEventListener("scroll",X))}},[K,He]),i.useEffect(()=>{if(!le)return;const X=()=>mt();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const Me=window.visualViewport;return Me&&(Me.addEventListener("resize",X),Me.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),Me&&(Me.removeEventListener("resize",X),Me.removeEventListener("scroll",X))}},[le,mt]);const ht=i.useCallback(X=>{const Me=ac(X);Oe(Me.provider),re(Me.modelId)},[]),Et=i.useCallback(X=>{const Me=ac(X);se(Me.provider),xe(Me.modelId)},[]),St=i.useCallback(X=>{const Me=ac(X);qe(Me.provider),Qe(Me.modelId)},[]),sn=i.useCallback(async X=>{if(m){m(X);return}const Me=jt,Mt=Me.includes(X)?Me.filter(Be=>Be!==X):[X,...Me];Yt(Mt);try{await _n({favoriteProviders:Mt,favoriteModels:Bt})}catch{Yt(Me)}},[jt,Bt,m]),nn=i.useCallback(async X=>{if(h){h(X);return}const Me=Bt,Mt=Me.includes(X)?Me.filter(Be=>Be!==X):[X,...Me];qt(Mt);try{await _n({favoriteProviders:jt,favoriteModels:Mt})}catch{qt(Me)}},[Bt,jt,h]),as=i.useCallback(()=>{const X=f.trim();if(!X){n("Enter a description first","error");return}r?.(X),hn()},[f,r,n,hn]),Is=i.useCallback(()=>{const X=f.trim();if(!X){n("Enter a description first","error");return}o?.(X),hn()},[f,o,n,hn]),_s=i.useCallback(()=>{yt()},[yt]),ls=i.useCallback(async X=>{const Me=f.trim();if(!(!Me||J)){Ce(!1),Ie(!0);try{const rt=await uf(Me,X,l);p(rt),n("Description refined with AI","success"),C.current&&(C.current.style.height="auto",C.current.style.height=`${Math.min(C.current.scrollHeight,200)}px`)}catch(rt){const Mt=mf(rt);n(Mt,"error")}finally{Ie(!1)}}},[f,J,n,l]),Xs=(X,Me)=>X.length>Me?X.slice(0,Me)+"…":X,ci=i.useCallback(async()=>{if(a){Nt(a),Ot(null),Pt(!1);return}Pt(!0),Ot(null);try{const X=await Ms();Nt(X.models),d||Yt(X.favoriteProviders),u||qt(X.favoriteModels)}catch(X){Ot(_e(X)||"Failed to load models")}finally{Pt(!1)}},[a,d,u]),pn=i.useCallback(async()=>{if(z.length>0&&I===l){H(!0),G();return}U(!0);try{const X=await da(void 0,l);k(X),$(l),H(!0),G()}catch(X){const Me=_e(X);n(Me?`Failed to load agents: ${Me}`:"Failed to load agents","error"),H(!1)}finally{U(!1)}},[z.length,I,l,n,G]),Ve=(q?z.find(X=>X.id===q):void 0)?.name??q,ot=we?oe.find(X=>X.id===we):void 0,on=y,Un=i.useCallback(()=>{j(X=>{const Me=!X;return b(Me),Me})},[]);return t.jsxs("div",{className:`quick-entry-box ${y?"quick-entry-box--expanded":"quick-entry-box--collapsed"}`,"data-testid":"quick-entry-box",children:[t.jsx("div",{className:"description-with-refine",children:t.jsxs("div",{className:"quick-entry-main-row",children:[t.jsx("div",{className:"quick-entry-textarea-wrap",children:t.jsx("textarea",{ref:C,className:`quick-entry-input ${v?"quick-entry-input--expanded":""}`,placeholder:g?"Creating...":"Add a task...",value:f,onChange:X=>p(X.target.value),onKeyDown:dt,onPaste:ue,onFocus:vt,onBlur:at,disabled:g||Rt,"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:Un,"aria-expanded":y,"aria-controls":"quick-entry-controls","data-testid":"quick-entry-toggle",title:y?"Collapse":"Expand",children:y?t.jsx(ri,{size:14}):t.jsx(un,{size:14})})]})}),t.jsxs("div",{id:"quick-entry-controls",className:"quick-entry-controls",hidden:!on,"aria-hidden":!on,children:[on&&!g&&t.jsxs("div",{className:"quick-entry-actions","data-testid":"quick-entry-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:as,onMouseDown:X=>X.preventDefault(),disabled:!f.trim(),"data-testid":"plan-button",title:"Open planning mode with current description",children:[t.jsx(oi,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Plan"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:Is,onMouseDown:X=>X.preventDefault(),disabled:!f.trim(),"data-testid":"subtask-button",title:"Break down into AI-generated subtasks",children:[t.jsx(kl,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Subtask"]}),t.jsxs("div",{className:"refine-trigger-wrap",ref:de,children:[t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${J?"refine-button--loading":""}`,onClick:()=>{Ce(X=>{const Me=!X;return Me?Wt():ft(null),Me})},disabled:!f.trim()||J,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(ms,{size:12,style:{verticalAlign:"middle"}}),J?"Refining...":"Refine"]}),Pe&&Re&&Ye&&Qi.createPortal(t.jsxs("div",{ref:Ne,className:"refine-menu refine-menu--portal",onMouseDown:X=>X.preventDefault(),style:{position:"fixed",top:`${Ye.top}px`,left:`${Ye.left}px`},children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>ls("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:()=>ls("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:()=>ls("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:()=>ls("simplify"),"data-testid":"refine-simplify",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Simplify"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Simplify and make more concise"})]})]}),Re)]}),t.jsx("div",{className:"dep-trigger-wrap",children:t.jsxs("button",{ref:$e,type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-deps",onClick:()=>{R(X=>{const Me=!X;return Me?(ne(!1),lt(null),ie(null),H(!1),ce(null),pe(!1),he(null),B(!1),st(null),Tt()):wt(null),Me})},children:[t.jsx(Pa,{size:12,style:{verticalAlign:"middle"}}),E.length>0?`${E.length} deps`:"Deps"]})}),F&&Re&&Xe&&(()=>{const X=P.toLowerCase(),Me=(X?s.filter(rt=>rt.id.toLowerCase().includes(X)||rt.title&&rt.title.toLowerCase().includes(X)||rt.description&&rt.description.toLowerCase().includes(X)):[...s]).sort((rt,Mt)=>{const Be=Mt.createdAt.localeCompare(rt.createdAt);if(Be!==0)return Be;const It=parseInt(rt.id.slice(rt.id.lastIndexOf("-")+1),10)||0;return(parseInt(Mt.id.slice(Mt.id.lastIndexOf("-")+1),10)||0)-It});return Qi.createPortal(t.jsxs("div",{ref:Ue,className:"dep-dropdown dep-dropdown--portal",onMouseDown:rt=>rt.preventDefault(),style:{position:"fixed",top:`${Xe.top}px`,left:`${Xe.left}px`,width:`${Xe.width}px`,maxHeight:Xe.maxHeight?`${Xe.maxHeight}px`:void 0,overflowY:Xe.maxHeight?"auto":void 0},children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:P,onChange:rt=>O(rt.target.value),onClick:rt=>rt.stopPropagation()}),Me.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No existing tasks"}):Me.map(rt=>t.jsxs("div",{className:`dep-dropdown-item${E.includes(rt.id)?" selected":""}`,onMouseDown:Mt=>Mt.preventDefault(),onClick:()=>Ht(rt.id),children:[t.jsx("span",{className:"dep-dropdown-id",children:rt.id}),t.jsx("span",{className:"dep-dropdown-title",children:Xs(rt.title||rt.description||rt.id,60)})]},rt.id))]}),Re)})(),t.jsxs("button",{type:"button",className:"btn btn-sm","data-testid":"quick-entry-attach",onClick:()=>A.current?.click(),children:[t.jsx(tf,{size:12,style:{verticalAlign:"middle"}}),_.length>0?`Attach (${_.length})`:"Attach"]}),t.jsxs("button",{ref:je,type:"button",className:"btn btn-sm","data-testid":"quick-entry-models",onClick:()=>{R(!1),H(!1),ce(null),pe(!1),he(null),B(!1),st(null),ie(null),ne(!0),An()},children:[t.jsx(Rr,{size:12,style:{verticalAlign:"middle"}}),On]}),t.jsx("div",{className:"node-trigger-wrap",ref:be,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-node-button",onClick:()=>{R(!1),H(!1),ce(null),ne(!1),lt(null),ie(null),B(!1),st(null),pe(X=>{const Me=!X;return Me?He():he(null),Me})},children:[t.jsx(Ir,{size:12,style:{verticalAlign:"middle"}}),` ${ot?.name??"Node"}`,ot&&t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(ia,{status:ot.status,showLabel:!0})})]})}),K&&Re&&Te&&Qi.createPortal(t.jsxs("div",{ref:ze,className:"dep-dropdown node-picker-dropdown node-picker-dropdown--portal",onMouseDown:X=>X.preventDefault(),style:{position:"fixed",top:`${Te.top}px`,left:`${Te.left}px`,width:`${Te.width}px`,maxHeight:Te.maxHeight?`${Te.maxHeight}px`:void 0,overflowY:Te.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select execution node"}),t.jsx("div",{className:`dep-dropdown-item node-picker-item${we==null?" selected":""}`,onMouseDown:X=>X.preventDefault(),onClick:()=>{De(void 0),pe(!1),he(null)},children:t.jsx("span",{className:"node-picker-item-name",children:"Project default / local"})}),oe.map(X=>t.jsxs("div",{className:`dep-dropdown-item node-picker-item${we===X.id?" selected":""}`,onMouseDown:Me=>Me.preventDefault(),onClick:()=>{De(X.id),pe(!1),he(null)},children:[t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(ia,{status:X.status})}),t.jsx("span",{className:"node-picker-item-name",children:X.name}),t.jsx("span",{className:"node-picker-item-status",children:VS(X.status)})]},X.id))]}),Re),t.jsx("div",{className:"agent-trigger-wrap",ref:Fe,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{w?(H(!1),ce(null)):(pe(!1),he(null),B(!1),st(null),pn())},"data-testid":"quick-entry-agent-button",children:[t.jsx(Rn,{size:12,style:{verticalAlign:"middle"}}),Ve?` ${Ve}`:" Agent"]})}),w&&Re&&ke&&Qi.createPortal(t.jsxs("div",{ref:Je,className:"dep-dropdown agent-picker-dropdown agent-picker-dropdown--portal",onMouseDown:X=>X.preventDefault(),style:{position:"fixed",top:`${ke.top}px`,left:`${ke.left}px`,width:`${ke.width}px`,maxHeight:ke.maxHeight?`${ke.maxHeight}px`:void 0,overflowY:ke.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),ye&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!ye&&z.filter(X=>X.state!=="terminated").map(X=>t.jsxs("div",{className:`dep-dropdown-item${q===X.id?" selected":""}`,onMouseDown:Me=>Me.preventDefault(),onClick:()=>{Z(X.id===q?null:X.id),H(!1),ce(null)},children:[t.jsx(Rn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:X.role}),t.jsx("span",{className:"dep-dropdown-title",children:X.name})]},X.id)),!ye&&z.filter(X=>X.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),q&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:X=>X.preventDefault(),onClick:()=>{Z(null),H(!1),ce(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]}),Re),t.jsx("div",{className:"priority-trigger-wrap",ref:tt,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-priority-button",onClick:()=>{R(!1),H(!1),ce(null),pe(!1),he(null),ne(!1),lt(null),ie(null),B(X=>{const Me=!X;return Me?mt():st(null),Me})},children:[t.jsx(Qx,{size:12,style:{verticalAlign:"middle"}}),` ${en[0].toUpperCase()}${en.slice(1)}`]})}),le&&Re&&Le&&Qi.createPortal(t.jsxs("div",{ref:kt,className:"dep-dropdown priority-picker-dropdown priority-picker-dropdown--portal",onMouseDown:X=>X.preventDefault(),style:{position:"fixed",top:`${Le.top}px`,left:`${Le.left}px`,width:`${Le.width}px`,maxHeight:Le.maxHeight?`${Le.maxHeight}px`:void 0,overflowY:Le.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select priority"}),Zr.map(X=>{const Me=`${X[0].toUpperCase()}${X.slice(1)}`;return t.jsx("div",{className:`dep-dropdown-item${en===X?" selected":""}`,"data-testid":`quick-entry-priority-option-${X}`,onMouseDown:rt=>rt.preventDefault(),onClick:()=>{cn(X),B(!1),st(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:Me})},X)})]}),Re),t.jsx("button",{type:"button",className:`btn btn-sm ${Ft?"btn-primary":""}`,onClick:()=>Zt(X=>!X),onMouseDown:X=>X.preventDefault(),"aria-pressed":Ft,"data-testid":"quick-entry-fast-toggle",title:"Toggle fast execution mode",children:"Fast"}),t.jsxs("button",{type:"button",className:"btn btn-task-create btn-sm",onClick:_s,onMouseDown:X=>X.preventDefault(),disabled:!f.trim()||g,"data-testid":"quick-entry-save",title:"Create task",children:[t.jsx(sf,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Save"]})]}),_.length>0&&t.jsx("div",{className:"inline-create-previews",children:_.map((X,Me)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:X.previewUrl,alt:X.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>ut(Me),disabled:g,title:"Remove image","data-testid":`quick-entry-preview-remove-${Me}`,children:"×"})]},X.previewUrl))}),te&&Re&&it&&Qi.createPortal(t.jsx("div",{ref:Q,className:"model-nested-menu model-nested-menu--portal",onMouseDown:X=>X.preventDefault(),"data-testid":"model-nested-menu",style:{position:"fixed",top:`${it.top}px`,left:`${it.left}px`,width:`${it.width}px`,maxHeight:it.maxHeight?`${it.maxHeight}px`:void 0,overflowY:it.maxHeight?"auto":void 0},children:ee===null?t.jsxs("div",{className:"model-menu-items",children:[t.jsxs("button",{type:"button",className:`model-menu-item ${xn?"model-menu-item--active":""}`,onClick:()=>ie("plan"),"data-testid":"model-menu-plan",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(oi,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Plan"]}),t.jsx("span",{className:"model-menu-item-value",children:xn?fe(ve,ae):"Using default"}),t.jsx(Tn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${Nn?"model-menu-item--active":""}`,onClick:()=>ie("executor"),"data-testid":"model-menu-executor",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(ms,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Executor"]}),t.jsx("span",{className:"model-menu-item-value",children:Nn?fe(ge,Ae):"Using default"}),t.jsx(Tn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${dn?"model-menu-item--active":""}`,onClick:()=>ie("validator"),"data-testid":"model-menu-validator",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(Rr,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Reviewer"]}),t.jsx("span",{className:"model-menu-item-value",children:dn?fe(Se,We):"Using default"}),t.jsx(Tn,{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:()=>ie(null),"data-testid":"model-submenu-back",children:[t.jsx(un,{size:12,style:{transform:"rotate(90deg)",marginRight:4}}),"Back"]}),t.jsxs("div",{className:"model-submenu-header",children:[ee==="plan"&&"Plan Model",ee==="executor"&&"Executor Model",ee==="validator"&&"Reviewer Model"]}),t.jsx(hs,{models:zt,value:ee==="plan"?bn:ee==="executor"?Dt:En,onChange:ee==="plan"?ht:ee==="executor"?Et:St,placeholder:"Using default",disabled:xt,id:`model-${ee}-select`,label:`${ee} model`,favoriteProviders:tn,onToggleFavorite:sn,favoriteModels:$t,onToggleModelFavorite:nn}),Ct&&t.jsxs("div",{className:"model-submenu-error",children:[t.jsx("span",{children:Ct}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:ci,children:"Retry"})]})]})}),Re)]}),t.jsx("input",{ref:A,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:X=>{zn(X.target.files),X.currentTarget.value=""},"data-testid":"quick-entry-file-input"}),t.jsx("div",{className:"quick-entry-hint",children:"Enter to create · Esc to cancel"})]})}function WS(e){return Jd(e)||e}function KS(e){const n=new Map(e.map(l=>[l.id,l])),s=[],a=new Set,r=new Set;function o(l){if(a.has(l)||r.has(l))return;r.add(l);const c=n.get(l);if(c)for(const d of c.dependencies||[])n.has(d)&&o(d);r.delete(l),a.add(l),s.push(l)}for(const l of e)o(l.id);return s}function GS(e,n,s){const a=e.filter(g=>g.worktree),r=e.filter(g=>!g.worktree),o=new Map;for(const g of a){const x=g.worktree,v=o.get(x)||[];v.push(g),o.set(x,v)}const l=new Map(n.map(g=>[g.id,g])),d=n.filter(g=>g.column==="todo").filter(g=>!g.paused&&(g.dependencies||[]).every(x=>{const v=l.get(x);return v&&(v.column==="done"||v.column==="in-review"||v.column==="archived")})),m=KS(d).map(g=>l.get(g)).filter(g=>g!==void 0&&d.includes(g)),h=[],f=Array.from(o.keys());for(const g of f)h.push({label:WS(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 km=100,rc=50,jm=25;function JS({column:e,tasks:n,projectId:s,maxConcurrent:a,onMoveTask:r,onPauseTask:o,onOpenDetail:l,addToast:c,onQuickCreate:d,onNewTask:u,autoMerge:m,onToggleAutoMerge:h,globalPaused:f,onUpdateTask:p,onRetryTask:g,onArchiveTask:x,onUnarchiveTask:v,onDeleteTask:b,onArchiveAllDone:y,collapsed:j,onToggleCollapse:C,allTasks:A,availableModels:N,onPlanningMode:S,onSubtaskBreakdown:_,onOpenDetailWithTab:T,favoriteProviders:M,favoriteModels:E,onToggleFavorite:L,onToggleModelFavorite:F,isSearchActive:R,taskStuckTimeoutMs:P,onOpenMission:O,lastFetchTimeMs:q,workflowStepNameLookup:Z}){const[z,k]=i.useState(!1),[I,$]=i.useState(rc),[w,H]=i.useState(!1),[K,pe]=i.useState(!1),[le,B]=i.useState(!1),[ye,U]=i.useState(!1),te=i.useRef(null),ne=L1(n.length),{confirm:ee}=qs();i.useEffect(()=>{if(!w)return;function ze(kt){te.current?.contains(kt.target)||H(!1)}function tt(kt){kt.key==="Escape"&&H(!1)}return document.addEventListener("mousedown",ze),document.addEventListener("keydown",tt),()=>{document.removeEventListener("mousedown",ze),document.removeEventListener("keydown",tt)}},[w]);const ie=e==="archived",ge=ie&&j,se=!ie&&!R&&e!=="in-progress"&&n.length>km;i.useEffect(()=>{$(ze=>e==="in-progress"||ie||n.length<=km?rc:Math.min(Math.max(ze,rc),n.length))},[e,ie,n.length]);const Ae=i.useCallback(ze=>{ie||(ze.preventDefault(),ze.dataTransfer.dropEffect="move",k(!0))},[ie]),xe=i.useCallback(ze=>{ze.currentTarget.contains(ze.relatedTarget)||k(!1)},[]),Se=i.useCallback(async ze=>{ze.preventDefault(),k(!1);const tt=ze.dataTransfer.getData("text/plain");if(!tt)return;const kt=n.find(ke=>ke.id===tt);if(!(kt&&kt.column===e))try{const ce=(A?.find(Le=>Le.id===tt)??kt)?.steps.some(Le=>Le.status!=="pending")??!1,Te=(e==="todo"||e==="triage")&&ce;let he;if(Te){if(await ee({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))he={preserveProgress:!0};else if(!await ee({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await r(tt,e,he)}catch(ke){c(_e(ke),"error")}},[c,A,e,ee,r,n]),qe=i.useMemo(()=>e!=="in-progress"?[]:GS(n,n,a),[e,n,a]),We=i.useMemo(()=>se?n.slice(0,I):n,[se,n,I]),Qe=Math.max(0,n.length-We.length),ve=i.useCallback(()=>{$(ze=>Math.min(ze+jm,n.length))},[n.length]),Oe=i.useCallback(async()=>{if(H(!1),!(n.length===0||!await ee({title:"Replan All Tasks",message:`Move all ${n.length} todo task${n.length===1?"":"s"} back to planning to be replanned?`}))){pe(!0);try{const tt=await Promise.allSettled(n.map(ce=>r(ce.id,"triage"))),kt=tt.filter(ce=>ce.status==="rejected").length,ke=tt.length-kt;kt===0?c(`Moved ${ke} task${ke===1?"":"s"} to planning for replanning`,"success"):c(`Moved ${ke} of ${tt.length} tasks; ${kt} failed`,"error")}finally{pe(!1)}}},[n,r,c,ee]),ae=i.useMemo(()=>n.filter(ze=>!ze.paused),[n]),re=ae.length,je=e==="todo"||e==="in-progress"||e==="in-review",Q=K||le||ye,Fe=i.useCallback(async()=>{if(!(!o||(H(!1),re===0)||!await ee({title:"Stop All Tasks",message:`Stop all ${re} ${Qn[e].toLowerCase()} task${re===1?"":"s"}?`,danger:!0}))){B(!0);try{const tt=await Promise.allSettled(ae.map(ce=>o(ce.id))),kt=tt.filter(ce=>ce.status==="rejected").length,ke=tt.length-kt;kt===0?c(`Stopped ${ke} task${ke===1?"":"s"}`,"success"):c(`Stopped ${ke} of ${tt.length} tasks; ${kt} failed`,"error")}finally{B(!1)}}},[o,re,e,ae,c,ee]),Je=i.useCallback(async()=>{if(H(!1),n.length===0||!await ee({title:"Move All to Todo",message:`Move all ${n.length} ${Qn[e].toLowerCase()} task${n.length===1?"":"s"} to Todo?`}))return;const tt=n.some(ke=>ke.steps.some(ce=>ce.status!=="pending"));let kt=!1;if(tt){if(await ee({title:"Preserve Progress?",message:"Some tasks have completed steps. Keep progress before moving to Todo?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))kt=!0;else if(!await ee({title:"Reset Progress?",message:"Reset step progress for tasks before moving to Todo?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}U(!0);try{const ke=await Promise.allSettled(n.map(he=>r(he.id,"todo",kt?{preserveProgress:!0}:void 0))),ce=ke.filter(he=>he.status==="rejected").length,Te=ke.length-ce;ce===0?c(`Moved ${Te} task${Te===1?"":"s"} to Todo`,"success"):c(`Moved ${Te} of ${ke.length} tasks to Todo; ${ce} failed`,"error")}finally{U(!1)}},[n,e,r,c,ee]),be=i.useCallback(async()=>{if(!(!y||n.length===0||!await ee({title:"Archive All Done",message:`Archive all ${n.length} done tasks?`,danger:!0})))try{const tt=await y();c(`Archived ${tt.length} tasks`,"success")}catch(tt){c(_e(tt)||"Failed to archive tasks","error")}},[y,n.length,c,ee]);return t.jsxs("div",{className:`column${z?" drag-over":""}${ie?" column-archived":""}${ge?" column-collapsed":""}`,"data-column":e,onDragOver:Ae,onDragLeave:xe,onDrop:Se,children:[t.jsxs("div",{className:"column-header",children:[t.jsx("div",{className:`column-dot dot-${e}`}),t.jsx("h2",{children:Qn[e]}),t.jsx("span",{className:`column-count${ne?" count-flash":""}`,children:n.length}),e==="in-review"&&h&&t.jsxs("label",{className:"auto-merge-toggle",title:m?"Auto-merge enabled":"Auto-merge disabled",children:[t.jsx("input",{type:"checkbox",checked:!!m,onChange:h}),t.jsx("span",{className:"toggle-slider"}),t.jsx("span",{className:"toggle-label",children:"Auto-merge"})]}),u&&t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:u,children:"+ New Task"}),e==="done"&&y&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:be,disabled:n.length===0,title:"Archive all done tasks","aria-label":"Archive all done tasks",children:t.jsx(Br,{})}),ie&&C&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:C,title:j?"Expand archived tasks":"Collapse archived tasks","aria-label":j?"Expand archived tasks":"Collapse archived tasks",children:j?t.jsx(un,{size:16}):t.jsx(ri,{size:16})}),je&&t.jsxs("div",{className:"column-menu",ref:te,children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>H(ze=>!ze),"aria-haspopup":"menu","aria-expanded":w,"aria-label":`${Qn[e]} column actions`,title:"Column actions",disabled:Q,children:t.jsx(Px,{})}),w&&t.jsxs("div",{className:"column-menu-popover",role:"menu",children:[e==="todo"&&t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Oe(),disabled:n.length===0||K,children:["Replan All",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Planning"]})]}),(e==="in-progress"||e==="in-review")&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Fe(),disabled:re===0||le||!o,children:["Stop All",t.jsx("span",{className:"column-menu-item-hint",children:n.length===0?"No tasks in this column":re===0?"All tasks are already paused":`Pause ${re} active task${re===1?"":"s"}`})]}),t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Je(),disabled:n.length===0||ye,children:["Move All to Todo",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Todo"]})]})]})]})]})]}),!ge&&t.jsx("p",{className:"column-desc",children:$1[e]}),!ge&&t.jsxs("div",{className:"column-body",children:[e==="triage"&&d&&t.jsx($f,{onCreate:d,addToast:c,tasks:A??[],availableModels:N,onPlanningMode:S,onSubtaskBreakdown:_,projectId:s,autoExpand:!1,favoriteProviders:M,favoriteModels:E,onToggleFavorite:L,onToggleModelFavorite:F}),e==="in-progress"?qe.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):qe.map(ze=>t.jsx(If,{label:ze.label,activeTasks:ze.activeTasks,queuedTasks:ze.queuedTasks,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onOpenDetailWithTab:T,taskStuckTimeoutMs:P,onOpenMission:O,lastFetchTimeMs:q,workflowStepNameLookup:Z},ze.label)):n.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):t.jsxs(t.Fragment,{children:[We.map(ze=>t.jsx(Or,{task:ze,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onArchiveTask:x,onUnarchiveTask:v,onDeleteTask:b,onOpenDetailWithTab:T,taskStuckTimeoutMs:P,onOpenMission:O,onMoveTask:r,lastFetchTimeMs:q,workflowStepNameLookup:Z},ze.id)),se&&Qe>0&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:ve,children:["Load ",Math.min(jm,Qe)," more (",Qe," remaining)"]})]}),t.jsx(Oi,{slotId:"board-column-footer",projectId:s})]})]})}const Df=i.memo(JS);Df.displayName="Column";function YS(e,n){return[...e].sort((s,a)=>{if(n==="in-review"){const r=s.status==="merging"||s.status==="merging-pr",o=a.status==="merging"||a.status==="merging-pr";if(r!==o)return r?-1:1}return s.columnMovedAt&&a.columnMovedAt?a.columnMovedAt.localeCompare(s.columnMovedAt):s.columnMovedAt&&!a.columnMovedAt?-1:!s.columnMovedAt&&a.columnMovedAt?1:s.createdAt.localeCompare(a.createdAt)})}function QS(e,n){return e.length!==n.length?!1:e.every((s,a)=>s===n[a])}const Nm=new Map;function XS(e,n){if(e.size!==n.size)return!1;for(const[s,a]of e)if(n.get(s)!==a)return!1;return!0}function ZS({tasks:e,projectId:n,maxConcurrent:s,onMoveTask:a,onPauseTask:r,onOpenDetail:o,addToast:l,onQuickCreate:c,onNewTask:d,autoMerge:u,onToggleAutoMerge:m,globalPaused:h,onUpdateTask:f,onRetryTask:p,onArchiveTask:g,onUnarchiveTask:x,onDeleteTask:v,onArchiveAllDone:b,onLoadArchivedTasks:y,searchQuery:j="",availableModels:C,onPlanningMode:A,onSubtaskBreakdown:N,onOpenDetailWithTab:S,favoriteProviders:_,favoriteModels:T,onToggleFavorite:M,onToggleModelFavorite:E,taskStuckTimeoutMs:L,onOpenMission:F,lastFetchTimeMs:R}){const[P,O]=i.useState(!0),q=i.useRef(!1),{fetchBatch:Z}=nS(n),z=i.useRef(null),[k,I]=i.useState(Nm),$=j.trim()!=="",w=i.useRef({triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]}),H=i.useCallback(()=>{O(le=>{const B=!le;return!B&&!q.current&&y&&(q.current=!0,y()),B})},[y]),K=i.useMemo(()=>{const le=Object.fromEntries(ea.map(U=>[U,[]]));for(const U of e)le[U.column].push(U);const B=w.current,ye={};for(const U of ea){const te=YS(le[U],U);ye[U]=QS(B[U],te)?B[U]:te}return w.current=ye,ye},[e]);i.useEffect(()=>{let le=!1;return Yr(n).then(B=>{if(le)return;const ye=new Map(B.map(U=>[U.id,U.name]));I(U=>XS(U,ye)?U:ye)}).catch(()=>{le||I(B=>B.size===0?B:Nm)}),()=>{le=!0}},[n]);const pe=i.useMemo(()=>e.filter(le=>le.prInfo||le.issueInfo).map(le=>le.id),[e]);return i.useEffect(()=>{if(pe.length!==0)return z.current&&clearTimeout(z.current),z.current=setTimeout(()=>{const le=[];for(let B=0;B<pe.length;B+=50)le.push(pe.slice(B,B+50));le.forEach(B=>{Z(B)})},500),()=>{z.current&&clearTimeout(z.current)}},[pe,Z]),t.jsx(t.Fragment,{children:t.jsx("main",{className:"board",id:"board",children:ea.map(le=>t.jsx(Df,{column:le,tasks:K[le],projectId:n,maxConcurrent:s,onMoveTask:a,onPauseTask:r,onOpenDetail:o,addToast:l,globalPaused:h,onUpdateTask:f,onRetryTask:p,onArchiveTask:g,onUnarchiveTask:x,onDeleteTask:v,allTasks:e,availableModels:C,onOpenDetailWithTab:S,favoriteProviders:_,favoriteModels:T,onToggleFavorite:M,onToggleModelFavorite:E,isSearchActive:$,taskStuckTimeoutMs:L,onOpenMission:F,lastFetchTimeMs:R,workflowStepNameLookup:k,...le==="triage"?{onQuickCreate:c,onNewTask:d,onPlanningMode:A,onSubtaskBreakdown:N}:{},...le==="in-review"?{autoMerge:u,onToggleAutoMerge:m}:{},...le==="done"?{onArchiveAllDone:b}:{},...le==="archived"?{collapsed:P,onToggleCollapse:H}:{}},le))})})}function wi(e,n,s){i.useEffect(()=>{if(!n)return;const a=e.current;if(!a)return;try{const d=localStorage.getItem(s);if(d){const{width:u,height:m}=JSON.parse(d);typeof u=="number"&&u>0&&(a.style.width=`${u}px`),typeof m=="number"&&m>0&&(a.style.height=`${m}px`)}}catch{}if(typeof ResizeObserver>"u")return;let r=a.offsetWidth,o=a.offsetHeight,l=null;const c=new ResizeObserver(()=>{const d=a.offsetWidth,u=a.offsetHeight;d===r&&u===o||(r=d,o=u,l&&clearTimeout(l),l=setTimeout(()=>{try{localStorage.setItem(s,JSON.stringify({width:d,height:u}))}catch{}},200))});return c.observe(a),()=>{c.disconnect(),l&&clearTimeout(l)}},[e,n,s])}function Ri(e){const n=i.useRef(!1),s=i.useCallback(r=>{n.current=r.target===r.currentTarget},[]),a=i.useCallback(r=>{const o=n.current&&r.target===r.currentTarget;n.current=!1,o&&e()},[e]);return{onMouseDown:s,onMouseUp:a}}function e0(e,n){const s={};return(e[e.length-1]===""?[...e,""]:e).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const t0=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,n0=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,s0={};function Sm(e,n){return(s0.jsx?n0:t0).test(e)}const i0=/[ \t\n\f\r]/g;function a0(e){return typeof e=="object"?e.type==="text"?Cm(e.value):!1:Cm(e)}function Cm(e){return e.replace(i0,"")===""}class eo{constructor(n,s,a){this.normal=s,this.property=n,a&&(this.space=a)}}eo.prototype.normal={};eo.prototype.property={};eo.prototype.space=void 0;function Lf(e,n){const s={},a={};for(const r of e)Object.assign(s,r.property),Object.assign(a,r.normal);return new eo(s,a,n)}function vd(e){return e.toLowerCase()}class Ts{constructor(n,s){this.attribute=s,this.property=n}}Ts.prototype.attribute="";Ts.prototype.booleanish=!1;Ts.prototype.boolean=!1;Ts.prototype.commaOrSpaceSeparated=!1;Ts.prototype.commaSeparated=!1;Ts.prototype.defined=!1;Ts.prototype.mustUseProperty=!1;Ts.prototype.number=!1;Ts.prototype.overloadedBoolean=!1;Ts.prototype.property="";Ts.prototype.spaceSeparated=!1;Ts.prototype.space=void 0;let r0=0;const an=ua(),is=ua(),yd=ua(),pt=ua(),Dn=ua(),Aa=ua(),Ls=ua();function ua(){return 2**++r0}const wd=Object.freeze(Object.defineProperty({__proto__:null,boolean:an,booleanish:is,commaOrSpaceSeparated:Ls,commaSeparated:Aa,number:pt,overloadedBoolean:yd,spaceSeparated:Dn},Symbol.toStringTag,{value:"Module"})),oc=Object.keys(wd);class Qd extends Ts{constructor(n,s,a,r){let o=-1;if(super(n,s),Em(this,"space",r),typeof a=="number")for(;++o<oc.length;){const l=oc[o];Em(this,oc[o],(a&wd[l])===wd[l])}}}Qd.prototype.defined=!0;function Em(e,n,s){s&&(e[n]=s)}function Ga(e){const n={},s={};for(const[a,r]of Object.entries(e.properties)){const o=new Qd(a,e.transform(e.attributes||{},a),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(a)&&(o.mustUseProperty=!0),n[a]=o,s[vd(a)]=a,s[vd(o.attribute)]=a}return new eo(n,s,e.space)}const Of=Ga({properties:{ariaActiveDescendant:null,ariaAtomic:is,ariaAutoComplete:null,ariaBusy:is,ariaChecked:is,ariaColCount:pt,ariaColIndex:pt,ariaColSpan:pt,ariaControls:Dn,ariaCurrent:null,ariaDescribedBy:Dn,ariaDetails:null,ariaDisabled:is,ariaDropEffect:Dn,ariaErrorMessage:null,ariaExpanded:is,ariaFlowTo:Dn,ariaGrabbed:is,ariaHasPopup:null,ariaHidden:is,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Dn,ariaLevel:pt,ariaLive:null,ariaModal:is,ariaMultiLine:is,ariaMultiSelectable:is,ariaOrientation:null,ariaOwns:Dn,ariaPlaceholder:null,ariaPosInSet:pt,ariaPressed:is,ariaReadOnly:is,ariaRelevant:null,ariaRequired:is,ariaRoleDescription:Dn,ariaRowCount:pt,ariaRowIndex:pt,ariaRowSpan:pt,ariaSelected:is,ariaSetSize:pt,ariaSort:null,ariaValueMax:pt,ariaValueMin:pt,ariaValueNow:pt,ariaValueText:null,role:null},transform(e,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function zf(e,n){return n in e?e[n]:n}function Ff(e,n){return zf(e,n.toLowerCase())}const o0=Ga({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Aa,acceptCharset:Dn,accessKey:Dn,action:null,allow:null,allowFullScreen:an,allowPaymentRequest:an,allowUserMedia:an,alt:null,as:null,async:an,autoCapitalize:null,autoComplete:Dn,autoFocus:an,autoPlay:an,blocking:Dn,capture:null,charSet:null,checked:an,cite:null,className:Dn,cols:pt,colSpan:null,content:null,contentEditable:is,controls:an,controlsList:Dn,coords:pt|Aa,crossOrigin:null,data:null,dateTime:null,decoding:null,default:an,defer:an,dir:null,dirName:null,disabled:an,download:yd,draggable:is,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:an,formTarget:null,headers:Dn,height:pt,hidden:yd,high:pt,href:null,hrefLang:null,htmlFor:Dn,httpEquiv:Dn,id:null,imageSizes:null,imageSrcSet:null,inert:an,inputMode:null,integrity:null,is:null,isMap:an,itemId:null,itemProp:Dn,itemRef:Dn,itemScope:an,itemType:Dn,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:an,low:pt,manifest:null,max:null,maxLength:pt,media:null,method:null,min:null,minLength:pt,multiple:an,muted:an,name:null,nonce:null,noModule:an,noValidate:an,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:an,optimum:pt,pattern:null,ping:Dn,placeholder:null,playsInline:an,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:an,referrerPolicy:null,rel:Dn,required:an,reversed:an,rows:pt,rowSpan:pt,sandbox:Dn,scope:null,scoped:an,seamless:an,selected:an,shadowRootClonable:an,shadowRootDelegatesFocus:an,shadowRootMode:null,shape:null,size:pt,sizes:null,slot:null,span:pt,spellCheck:is,src:null,srcDoc:null,srcLang:null,srcSet:null,start:pt,step:null,style:null,tabIndex:pt,target:null,title:null,translate:null,type:null,typeMustMatch:an,useMap:null,value:is,width:pt,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Dn,axis:null,background:null,bgColor:null,border:pt,borderColor:null,bottomMargin:pt,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:an,declare:an,event:null,face:null,frame:null,frameBorder:null,hSpace:pt,leftMargin:pt,link:null,longDesc:null,lowSrc:null,marginHeight:pt,marginWidth:pt,noResize:an,noHref:an,noShade:an,noWrap:an,object:null,profile:null,prompt:null,rev:null,rightMargin:pt,rules:null,scheme:null,scrolling:is,standby:null,summary:null,text:null,topMargin:pt,valueType:null,version:null,vAlign:null,vLink:null,vSpace:pt,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:an,disableRemotePlayback:an,prefix:null,property:null,results:pt,security:null,unselectable:null},space:"html",transform:Ff}),l0=Ga({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:Ls,accentHeight:pt,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:pt,amplitude:pt,arabicForm:null,ascent:pt,attributeName:null,attributeType:null,azimuth:pt,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:pt,by:null,calcMode:null,capHeight:pt,className:Dn,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:pt,diffuseConstant:pt,direction:null,display:null,dur:null,divisor:pt,dominantBaseline:null,download:an,dx:null,dy:null,edgeMode:null,editable:null,elevation:pt,enableBackground:null,end:null,event:null,exponent:pt,externalResourcesRequired:null,fill:null,fillOpacity:pt,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:Aa,g2:Aa,glyphName:Aa,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:pt,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:pt,horizOriginX:pt,horizOriginY:pt,id:null,ideographic:pt,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:pt,k:pt,k1:pt,k2:pt,k3:pt,k4:pt,kernelMatrix:Ls,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:pt,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:pt,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:pt,overlineThickness:pt,paintOrder:null,panose1:null,path:null,pathLength:pt,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Dn,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:pt,pointsAtY:pt,pointsAtZ:pt,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Ls,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Ls,rev:Ls,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Ls,requiredFeatures:Ls,requiredFonts:Ls,requiredFormats:Ls,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:pt,specularExponent:pt,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:pt,strikethroughThickness:pt,string:null,stroke:null,strokeDashArray:Ls,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:pt,strokeOpacity:pt,strokeWidth:null,style:null,surfaceScale:pt,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Ls,tabIndex:pt,tableValues:null,target:null,targetX:pt,targetY:pt,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Ls,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:pt,underlineThickness:pt,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:pt,values:null,vAlphabetic:pt,vMathematical:pt,vectorEffect:null,vHanging:pt,vIdeographic:pt,version:null,vertAdvY:pt,vertOriginX:pt,vertOriginY:pt,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:pt,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:zf}),Uf=Ga({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()}}),Bf=Ga({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Ff}),Hf=Ga({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,n){return"xml:"+n.slice(3).toLowerCase()}}),c0={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"},d0=/[A-Z]/g,Mm=/-[a-z]/g,u0=/^data[-\w.:]+$/i;function m0(e,n){const s=vd(n);let a=n,r=Ts;if(s in e.normal)return e.property[e.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&u0.test(n)){if(n.charAt(4)==="-"){const o=n.slice(5).replace(Mm,p0);a="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=n.slice(4);if(!Mm.test(o)){let l=o.replace(d0,h0);l.charAt(0)!=="-"&&(l="-"+l),n="data"+l}}r=Qd}return new r(a,n)}function h0(e){return"-"+e.toLowerCase()}function p0(e){return e.charAt(1).toUpperCase()}const f0=Lf([Of,o0,Uf,Bf,Hf],"html"),Xd=Lf([Of,l0,Uf,Bf,Hf],"svg");function g0(e){return e.join(" ").trim()}var ya={},lc,_m;function b0(){if(_m)return lc;_m=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,n=/\n/g,s=/^\s*/,a=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,r=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,l=/^[;\s]*/,c=/^\s+|\s+$/g,d=`
644
+ `,u="/",m="*",h="",f="comment",p="declaration";function g(v,b){if(typeof v!="string")throw new TypeError("First argument must be a string");if(!v)return[];b=b||{};var y=1,j=1;function C(R){var P=R.match(n);P&&(y+=P.length);var O=R.lastIndexOf(d);j=~O?R.length-O:j+R.length}function A(){var R={line:y,column:j};return function(P){return P.position=new N(R),T(),P}}function N(R){this.start=R,this.end={line:y,column:j},this.source=b.source}N.prototype.content=v;function S(R){var P=new Error(b.source+":"+y+":"+j+": "+R);if(P.reason=R,P.filename=b.source,P.line=y,P.column=j,P.source=v,!b.silent)throw P}function _(R){var P=R.exec(v);if(P){var O=P[0];return C(O),v=v.slice(O.length),P}}function T(){_(s)}function M(R){var P;for(R=R||[];P=E();)P!==!1&&R.push(P);return R}function E(){var R=A();if(!(u!=v.charAt(0)||m!=v.charAt(1))){for(var P=2;h!=v.charAt(P)&&(m!=v.charAt(P)||u!=v.charAt(P+1));)++P;if(P+=2,h===v.charAt(P-1))return S("End of comment missing");var O=v.slice(2,P-2);return j+=2,C(O),v=v.slice(P),j+=2,R({type:f,comment:O})}}function L(){var R=A(),P=_(a);if(P){if(E(),!_(r))return S("property missing ':'");var O=_(o),q=R({type:p,property:x(P[0].replace(e,h)),value:O?x(O[0].replace(e,h)):h});return _(l),q}}function F(){var R=[];M(R);for(var P;P=L();)P!==!1&&(R.push(P),M(R));return R}return T(),F()}function x(v){return v?v.replace(c,h):h}return lc=g,lc}var Am;function x0(){if(Am)return ya;Am=1;var e=ya&&ya.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(ya,"__esModule",{value:!0}),ya.default=s;const n=e(b0());function s(a,r){let o=null;if(!a||typeof a!="string")return o;const l=(0,n.default)(a),c=typeof r=="function";return l.forEach(d=>{if(d.type!=="declaration")return;const{property:u,value:m}=d;c?r(u,m,d):m&&(o=o||{},o[u]=m)}),o}return ya}var ar={},Pm;function v0(){if(Pm)return ar;Pm=1,Object.defineProperty(ar,"__esModule",{value:!0}),ar.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,n=/-([a-z])/g,s=/^[^-]+$/,a=/^-(webkit|moz|ms|o|khtml)-/,r=/^-(ms)-/,o=function(u){return!u||s.test(u)||e.test(u)},l=function(u,m){return m.toUpperCase()},c=function(u,m){return"".concat(m,"-")},d=function(u,m){return m===void 0&&(m={}),o(u)?u:(u=u.toLowerCase(),m.reactCompat?u=u.replace(r,c):u=u.replace(a,c),u.replace(n,l))};return ar.camelCase=d,ar}var rr,Rm;function y0(){if(Rm)return rr;Rm=1;var e=rr&&rr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},n=e(x0()),s=v0();function a(r,o){var l={};return!r||typeof r!="string"||(0,n.default)(r,function(c,d){c&&d&&(l[(0,s.camelCase)(c,o)]=d)}),l}return a.default=a,rr=a,rr}var w0=y0();const k0=Wp(w0),qf=Vf("end"),Zd=Vf("start");function Vf(e){return n;function n(s){const a=s&&s.position&&s.position[e]||{};if(typeof a.line=="number"&&a.line>0&&typeof a.column=="number"&&a.column>0)return{line:a.line,column:a.column,offset:typeof a.offset=="number"&&a.offset>-1?a.offset:void 0}}}function j0(e){const n=Zd(e),s=qf(e);if(n&&s)return{start:n,end:s}}function _r(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Tm(e.position):"start"in e||"end"in e?Tm(e):"line"in e||"column"in e?kd(e):""}function kd(e){return Im(e&&e.line)+":"+Im(e&&e.column)}function Tm(e){return kd(e&&e.start)+"-"+kd(e&&e.end)}function Im(e){return e&&typeof e=="number"?e:1}class Ns extends Error{constructor(n,s,a){super(),typeof s=="string"&&(a=s,s=void 0);let r="",o={},l=!1;if(s&&("line"in s&&"column"in s?o={place:s}:"start"in s&&"end"in s?o={place:s}:"type"in s?o={ancestors:[s],place:s.position}:o={...s}),typeof n=="string"?r=n:!o.cause&&n&&(l=!0,r=n.message,o.cause=n),!o.ruleId&&!o.source&&typeof a=="string"){const d=a.indexOf(":");d===-1?o.ruleId=a:(o.source=a.slice(0,d),o.ruleId=a.slice(d+1))}if(!o.place&&o.ancestors&&o.ancestors){const d=o.ancestors[o.ancestors.length-1];d&&(o.place=d.position)}const c=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=c?c.column:void 0,this.fatal=void 0,this.file="",this.message=r,this.line=c?c.line:void 0,this.name=_r(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}}Ns.prototype.file="";Ns.prototype.name="";Ns.prototype.reason="";Ns.prototype.message="";Ns.prototype.stack="";Ns.prototype.column=void 0;Ns.prototype.line=void 0;Ns.prototype.ancestors=void 0;Ns.prototype.cause=void 0;Ns.prototype.fatal=void 0;Ns.prototype.place=void 0;Ns.prototype.ruleId=void 0;Ns.prototype.source=void 0;const eu={}.hasOwnProperty,N0=new Map,S0=/[A-Z]/g,C0=new Set(["table","tbody","thead","tfoot","tr"]),E0=new Set(["td","th"]),Wf="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function M0(e,n){if(!n||n.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const s=n.filePath||void 0;let a;if(n.development){if(typeof n.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");a=D0(s,n.jsxDEV)}else{if(typeof n.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof n.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");a=$0(s,n.jsx,n.jsxs)}const r={Fragment:n.Fragment,ancestors:[],components:n.components||{},create:a,elementAttributeNameCase:n.elementAttributeNameCase||"react",evaluater:n.createEvaluater?n.createEvaluater():void 0,filePath:s,ignoreInvalidStyle:n.ignoreInvalidStyle||!1,passKeys:n.passKeys!==!1,passNode:n.passNode||!1,schema:n.space==="svg"?Xd:f0,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},o=Kf(r,e,void 0);return o&&typeof o!="string"?o:r.create(e,r.Fragment,{children:o||void 0},void 0)}function Kf(e,n,s){if(n.type==="element")return _0(e,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return A0(e,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return R0(e,n,s);if(n.type==="mdxjsEsm")return P0(e,n);if(n.type==="root")return T0(e,n,s);if(n.type==="text")return I0(e,n)}function _0(e,n,s){const a=e.schema;let r=a;n.tagName.toLowerCase()==="svg"&&a.space==="html"&&(r=Xd,e.schema=r),e.ancestors.push(n);const o=Jf(e,n.tagName,!1),l=L0(e,n);let c=nu(e,n);return C0.has(n.tagName)&&(c=c.filter(function(d){return typeof d=="string"?!a0(d):!0})),Gf(e,l,o,n),tu(l,c),e.ancestors.pop(),e.schema=a,e.create(n,o,l,s)}function A0(e,n){if(n.data&&n.data.estree&&e.evaluater){const a=n.data.estree.body[0];return a.type,e.evaluater.evaluateExpression(a.expression)}zr(e,n.position)}function P0(e,n){if(n.data&&n.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(n.data.estree);zr(e,n.position)}function R0(e,n,s){const a=e.schema;let r=a;n.name==="svg"&&a.space==="html"&&(r=Xd,e.schema=r),e.ancestors.push(n);const o=n.name===null?e.Fragment:Jf(e,n.name,!0),l=O0(e,n),c=nu(e,n);return Gf(e,l,o,n),tu(l,c),e.ancestors.pop(),e.schema=a,e.create(n,o,l,s)}function T0(e,n,s){const a={};return tu(a,nu(e,n)),e.create(n,e.Fragment,a,s)}function I0(e,n){return n.value}function Gf(e,n,s,a){typeof s!="string"&&s!==e.Fragment&&e.passNode&&(n.node=a)}function tu(e,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(e.children=s)}}function $0(e,n,s){return a;function a(r,o,l,c){const u=Array.isArray(l.children)?s:n;return c?u(o,l,c):u(o,l)}}function D0(e,n){return s;function s(a,r,o,l){const c=Array.isArray(o.children),d=Zd(a);return n(r,o,l,c,{columnNumber:d?d.column-1:void 0,fileName:e,lineNumber:d?d.line:void 0},void 0)}}function L0(e,n){const s={};let a,r;for(r in n.properties)if(r!=="children"&&eu.call(n.properties,r)){const o=z0(e,r,n.properties[r]);if(o){const[l,c]=o;e.tableCellAlignToStyle&&l==="align"&&typeof c=="string"&&E0.has(n.tagName)?a=c:s[l]=c}}if(a){const o=s.style||(s.style={});o[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=a}return s}function O0(e,n){const s={};for(const a of n.attributes)if(a.type==="mdxJsxExpressionAttribute")if(a.data&&a.data.estree&&e.evaluater){const o=a.data.estree.body[0];o.type;const l=o.expression;l.type;const c=l.properties[0];c.type,Object.assign(s,e.evaluater.evaluateExpression(c.argument))}else zr(e,n.position);else{const r=a.name;let o;if(a.value&&typeof a.value=="object")if(a.value.data&&a.value.data.estree&&e.evaluater){const c=a.value.data.estree.body[0];c.type,o=e.evaluater.evaluateExpression(c.expression)}else zr(e,n.position);else o=a.value===null?!0:a.value;s[r]=o}return s}function nu(e,n){const s=[];let a=-1;const r=e.passKeys?new Map:N0;for(;++a<n.children.length;){const o=n.children[a];let l;if(e.passKeys){const d=o.type==="element"?o.tagName:o.type==="mdxJsxFlowElement"||o.type==="mdxJsxTextElement"?o.name:void 0;if(d){const u=r.get(d)||0;l=d+"-"+u,r.set(d,u+1)}}const c=Kf(e,o,l);c!==void 0&&s.push(c)}return s}function z0(e,n,s){const a=m0(e.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=a.commaSeparated?e0(s):g0(s)),a.property==="style"){let r=typeof s=="object"?s:F0(e,String(s));return e.stylePropertyNameCase==="css"&&(r=U0(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&a.space?c0[a.property]||a.property:a.attribute,s]}}function F0(e,n){try{return k0(n,{reactCompat:!0})}catch(s){if(e.ignoreInvalidStyle)return{};const a=s,r=new Ns("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:a,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw r.file=e.filePath||void 0,r.url=Wf+"#cannot-parse-style-attribute",r}}function Jf(e,n,s){let a;if(!s)a={type:"Literal",value:n};else if(n.includes(".")){const r=n.split(".");let o=-1,l;for(;++o<r.length;){const c=Sm(r[o])?{type:"Identifier",name:r[o]}:{type:"Literal",value:r[o]};l=l?{type:"MemberExpression",object:l,property:c,computed:!!(o&&c.type==="Literal"),optional:!1}:c}a=l}else a=Sm(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(a.type==="Literal"){const r=a.value;return eu.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(a);zr(e)}function zr(e,n){const s=new Ns("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=Wf+"#cannot-handle-mdx-estrees-without-createevaluater",s}function U0(e){const n={};let s;for(s in e)eu.call(e,s)&&(n[B0(s)]=e[s]);return n}function B0(e){let n=e.replace(S0,H0);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function H0(e){return"-"+e.toLowerCase()}const cc={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"]},q0={};function su(e,n){const s=q0,a=typeof s.includeImageAlt=="boolean"?s.includeImageAlt:!0,r=typeof s.includeHtml=="boolean"?s.includeHtml:!0;return Yf(e,a,r)}function Yf(e,n,s){if(V0(e)){if("value"in e)return e.type==="html"&&!s?"":e.value;if(n&&"alt"in e&&e.alt)return e.alt;if("children"in e)return $m(e.children,n,s)}return Array.isArray(e)?$m(e,n,s):""}function $m(e,n,s){const a=[];let r=-1;for(;++r<e.length;)a[r]=Yf(e[r],n,s);return a.join("")}function V0(e){return!!(e&&typeof e=="object")}const Dm=document.createElement("i");function iu(e){const n="&"+e+";";Dm.innerHTML=n;const s=Dm.textContent;return s.charCodeAt(s.length-1)===59&&e!=="semi"||s===n?!1:s}function Us(e,n,s,a){const r=e.length;let o=0,l;if(n<0?n=-n>r?0:r+n:n=n>r?r:n,s=s>0?s:0,a.length<1e4)l=Array.from(a),l.unshift(n,s),e.splice(...l);else for(s&&e.splice(n,s);o<a.length;)l=a.slice(o,o+1e4),l.unshift(n,0),e.splice(...l),o+=1e4,n+=1e4}function Ys(e,n){return e.length>0?(Us(e,e.length,0,n),e):n}const Lm={}.hasOwnProperty;function Qf(e){const n={};let s=-1;for(;++s<e.length;)W0(n,e[s]);return n}function W0(e,n){let s;for(s in n){const r=(Lm.call(e,s)?e[s]:void 0)||(e[s]={}),o=n[s];let l;if(o)for(l in o){Lm.call(r,l)||(r[l]=[]);const c=o[l];K0(r[l],Array.isArray(c)?c:c?[c]:[])}}}function K0(e,n){let s=-1;const a=[];for(;++s<n.length;)(n[s].add==="after"?e:a).push(n[s]);Us(e,0,0,a)}function Xf(e,n){const s=Number.parseInt(e,n);return s<9||s===11||s>13&&s<32||s>126&&s<160||s>55295&&s<57344||s>64975&&s<65008||(s&65535)===65535||(s&65535)===65534||s>1114111?"�":String.fromCodePoint(s)}function ai(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Es=Hi(/[A-Za-z]/),ks=Hi(/[\dA-Za-z]/),G0=Hi(/[#-'*+\--9=?A-Z^-~]/);function ol(e){return e!==null&&(e<32||e===127)}const jd=Hi(/\d/),J0=Hi(/[\dA-Fa-f]/),Y0=Hi(/[!-/:-@[-`{-~]/);function Lt(e){return e!==null&&e<-2}function In(e){return e!==null&&(e<0||e===32)}function gn(e){return e===-2||e===-1||e===32}const Pl=Hi(/\p{P}|\p{S}/u),ra=Hi(/\s/);function Hi(e){return n;function n(s){return s!==null&&s>-1&&e.test(String.fromCharCode(s))}}function Ja(e){const n=[];let s=-1,a=0,r=0;for(;++s<e.length;){const o=e.charCodeAt(s);let l="";if(o===37&&ks(e.charCodeAt(s+1))&&ks(e.charCodeAt(s+2)))r=2;else if(o<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(o))||(l=String.fromCharCode(o));else if(o>55295&&o<57344){const c=e.charCodeAt(s+1);o<56320&&c>56319&&c<57344?(l=String.fromCharCode(o,c),r=1):l="�"}else l=String.fromCharCode(o);l&&(n.push(e.slice(a,s),encodeURIComponent(l)),a=s+r+1,l=""),r&&(s+=r,r=0)}return n.join("")+e.slice(a)}function jn(e,n,s,a){const r=a?a-1:Number.POSITIVE_INFINITY;let o=0;return l;function l(d){return gn(d)?(e.enter(s),c(d)):n(d)}function c(d){return gn(d)&&o++<r?(e.consume(d),c):(e.exit(s),n(d))}}const Q0={tokenize:X0};function X0(e){const n=e.attempt(this.parser.constructs.contentInitial,a,r);let s;return n;function a(c){if(c===null){e.consume(c);return}return e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),jn(e,n,"linePrefix")}function r(c){return e.enter("paragraph"),o(c)}function o(c){const d=e.enter("chunkText",{contentType:"text",previous:s});return s&&(s.next=d),s=d,l(c)}function l(c){if(c===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(c);return}return Lt(c)?(e.consume(c),e.exit("chunkText"),o):(e.consume(c),l)}}const Z0={tokenize:eC},Om={tokenize:tC};function eC(e){const n=this,s=[];let a=0,r,o,l;return c;function c(j){if(a<s.length){const C=s[a];return n.containerState=C[1],e.attempt(C[0].continuation,d,u)(j)}return u(j)}function d(j){if(a++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,r&&y();const C=n.events.length;let A=C,N;for(;A--;)if(n.events[A][0]==="exit"&&n.events[A][1].type==="chunkFlow"){N=n.events[A][1].end;break}b(a);let S=C;for(;S<n.events.length;)n.events[S][1].end={...N},S++;return Us(n.events,A+1,0,n.events.slice(C)),n.events.length=S,u(j)}return c(j)}function u(j){if(a===s.length){if(!r)return f(j);if(r.currentConstruct&&r.currentConstruct.concrete)return g(j);n.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return n.containerState={},e.check(Om,m,h)(j)}function m(j){return r&&y(),b(a),f(j)}function h(j){return n.parser.lazy[n.now().line]=a!==s.length,l=n.now().offset,g(j)}function f(j){return n.containerState={},e.attempt(Om,p,g)(j)}function p(j){return a++,s.push([n.currentConstruct,n.containerState]),f(j)}function g(j){if(j===null){r&&y(),b(0),e.consume(j);return}return r=r||n.parser.flow(n.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:o}),x(j)}function x(j){if(j===null){v(e.exit("chunkFlow"),!0),b(0),e.consume(j);return}return Lt(j)?(e.consume(j),v(e.exit("chunkFlow")),a=0,n.interrupt=void 0,c):(e.consume(j),x)}function v(j,C){const A=n.sliceStream(j);if(C&&A.push(null),j.previous=o,o&&(o.next=j),o=j,r.defineSkip(j.start),r.write(A),n.parser.lazy[j.start.line]){let N=r.events.length;for(;N--;)if(r.events[N][1].start.offset<l&&(!r.events[N][1].end||r.events[N][1].end.offset>l))return;const S=n.events.length;let _=S,T,M;for(;_--;)if(n.events[_][0]==="exit"&&n.events[_][1].type==="chunkFlow"){if(T){M=n.events[_][1].end;break}T=!0}for(b(a),N=S;N<n.events.length;)n.events[N][1].end={...M},N++;Us(n.events,_+1,0,n.events.slice(S)),n.events.length=N}}function b(j){let C=s.length;for(;C-- >j;){const A=s[C];n.containerState=A[1],A[0].exit.call(n,e)}s.length=j}function y(){r.write([null]),o=void 0,r=void 0,n.containerState._closeFlow=void 0}}function tC(e,n,s){return jn(e,e.attempt(this.parser.constructs.document,n,s),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Oa(e){if(e===null||In(e)||ra(e))return 1;if(Pl(e))return 2}function Rl(e,n,s){const a=[];let r=-1;for(;++r<e.length;){const o=e[r].resolveAll;o&&!a.includes(o)&&(n=o(n,s),a.push(o))}return n}const Nd={name:"attention",resolveAll:nC,tokenize:sC};function nC(e,n){let s=-1,a,r,o,l,c,d,u,m;for(;++s<e.length;)if(e[s][0]==="enter"&&e[s][1].type==="attentionSequence"&&e[s][1]._close){for(a=s;a--;)if(e[a][0]==="exit"&&e[a][1].type==="attentionSequence"&&e[a][1]._open&&n.sliceSerialize(e[a][1]).charCodeAt(0)===n.sliceSerialize(e[s][1]).charCodeAt(0)){if((e[a][1]._close||e[s][1]._open)&&(e[s][1].end.offset-e[s][1].start.offset)%3&&!((e[a][1].end.offset-e[a][1].start.offset+e[s][1].end.offset-e[s][1].start.offset)%3))continue;d=e[a][1].end.offset-e[a][1].start.offset>1&&e[s][1].end.offset-e[s][1].start.offset>1?2:1;const h={...e[a][1].end},f={...e[s][1].start};zm(h,-d),zm(f,d),l={type:d>1?"strongSequence":"emphasisSequence",start:h,end:{...e[a][1].end}},c={type:d>1?"strongSequence":"emphasisSequence",start:{...e[s][1].start},end:f},o={type:d>1?"strongText":"emphasisText",start:{...e[a][1].end},end:{...e[s][1].start}},r={type:d>1?"strong":"emphasis",start:{...l.start},end:{...c.end}},e[a][1].end={...l.start},e[s][1].start={...c.end},u=[],e[a][1].end.offset-e[a][1].start.offset&&(u=Ys(u,[["enter",e[a][1],n],["exit",e[a][1],n]])),u=Ys(u,[["enter",r,n],["enter",l,n],["exit",l,n],["enter",o,n]]),u=Ys(u,Rl(n.parser.constructs.insideSpan.null,e.slice(a+1,s),n)),u=Ys(u,[["exit",o,n],["enter",c,n],["exit",c,n],["exit",r,n]]),e[s][1].end.offset-e[s][1].start.offset?(m=2,u=Ys(u,[["enter",e[s][1],n],["exit",e[s][1],n]])):m=0,Us(e,a-1,s-a+3,u),s=a+u.length-m-2;break}}for(s=-1;++s<e.length;)e[s][1].type==="attentionSequence"&&(e[s][1].type="data");return e}function sC(e,n){const s=this.parser.constructs.attentionMarkers.null,a=this.previous,r=Oa(a);let o;return l;function l(d){return o=d,e.enter("attentionSequence"),c(d)}function c(d){if(d===o)return e.consume(d),c;const u=e.exit("attentionSequence"),m=Oa(d),h=!m||m===2&&r||s.includes(d),f=!r||r===2&&m||s.includes(a);return u._open=!!(o===42?h:h&&(r||!f)),u._close=!!(o===42?f:f&&(m||!h)),n(d)}}function zm(e,n){e.column+=n,e.offset+=n,e._bufferIndex+=n}const iC={name:"autolink",tokenize:aC};function aC(e,n,s){let a=0;return r;function r(p){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),o}function o(p){return Es(p)?(e.consume(p),l):p===64?s(p):u(p)}function l(p){return p===43||p===45||p===46||ks(p)?(a=1,c(p)):u(p)}function c(p){return p===58?(e.consume(p),a=0,d):(p===43||p===45||p===46||ks(p))&&a++<32?(e.consume(p),c):(a=0,u(p))}function d(p){return p===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.exit("autolink"),n):p===null||p===32||p===60||ol(p)?s(p):(e.consume(p),d)}function u(p){return p===64?(e.consume(p),m):G0(p)?(e.consume(p),u):s(p)}function m(p){return ks(p)?h(p):s(p)}function h(p){return p===46?(e.consume(p),a=0,m):p===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.exit("autolink"),n):f(p)}function f(p){if((p===45||ks(p))&&a++<63){const g=p===45?f:h;return e.consume(p),g}return s(p)}}const to={partial:!0,tokenize:rC};function rC(e,n,s){return a;function a(o){return gn(o)?jn(e,r,"linePrefix")(o):r(o)}function r(o){return o===null||Lt(o)?n(o):s(o)}}const Zf={continuation:{tokenize:lC},exit:cC,name:"blockQuote",tokenize:oC};function oC(e,n,s){const a=this;return r;function r(l){if(l===62){const c=a.containerState;return c.open||(e.enter("blockQuote",{_container:!0}),c.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(l),e.exit("blockQuoteMarker"),o}return s(l)}function o(l){return gn(l)?(e.enter("blockQuotePrefixWhitespace"),e.consume(l),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),n):(e.exit("blockQuotePrefix"),n(l))}}function lC(e,n,s){const a=this;return r;function r(l){return gn(l)?jn(e,o,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l):o(l)}function o(l){return e.attempt(Zf,n,s)(l)}}function cC(e){e.exit("blockQuote")}const eg={name:"characterEscape",tokenize:dC};function dC(e,n,s){return a;function a(o){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(o),e.exit("escapeMarker"),r}function r(o){return Y0(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),n):s(o)}}const tg={name:"characterReference",tokenize:uC};function uC(e,n,s){const a=this;let r=0,o,l;return c;function c(h){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(h),e.exit("characterReferenceMarker"),d}function d(h){return h===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(h),e.exit("characterReferenceMarkerNumeric"),u):(e.enter("characterReferenceValue"),o=31,l=ks,m(h))}function u(h){return h===88||h===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(h),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),o=6,l=J0,m):(e.enter("characterReferenceValue"),o=7,l=jd,m(h))}function m(h){if(h===59&&r){const f=e.exit("characterReferenceValue");return l===ks&&!iu(a.sliceSerialize(f))?s(h):(e.enter("characterReferenceMarker"),e.consume(h),e.exit("characterReferenceMarker"),e.exit("characterReference"),n)}return l(h)&&r++<o?(e.consume(h),m):s(h)}}const Fm={partial:!0,tokenize:hC},Um={concrete:!0,name:"codeFenced",tokenize:mC};function mC(e,n,s){const a=this,r={partial:!0,tokenize:A};let o=0,l=0,c;return d;function d(N){return u(N)}function u(N){const S=a.events[a.events.length-1];return o=S&&S[1].type==="linePrefix"?S[2].sliceSerialize(S[1],!0).length:0,c=N,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),m(N)}function m(N){return N===c?(l++,e.consume(N),m):l<3?s(N):(e.exit("codeFencedFenceSequence"),gn(N)?jn(e,h,"whitespace")(N):h(N))}function h(N){return N===null||Lt(N)?(e.exit("codeFencedFence"),a.interrupt?n(N):e.check(Fm,x,C)(N)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),f(N))}function f(N){return N===null||Lt(N)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),h(N)):gn(N)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),jn(e,p,"whitespace")(N)):N===96&&N===c?s(N):(e.consume(N),f)}function p(N){return N===null||Lt(N)?h(N):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(N))}function g(N){return N===null||Lt(N)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),h(N)):N===96&&N===c?s(N):(e.consume(N),g)}function x(N){return e.attempt(r,C,v)(N)}function v(N){return e.enter("lineEnding"),e.consume(N),e.exit("lineEnding"),b}function b(N){return o>0&&gn(N)?jn(e,y,"linePrefix",o+1)(N):y(N)}function y(N){return N===null||Lt(N)?e.check(Fm,x,C)(N):(e.enter("codeFlowValue"),j(N))}function j(N){return N===null||Lt(N)?(e.exit("codeFlowValue"),y(N)):(e.consume(N),j)}function C(N){return e.exit("codeFenced"),n(N)}function A(N,S,_){let T=0;return M;function M(P){return N.enter("lineEnding"),N.consume(P),N.exit("lineEnding"),E}function E(P){return N.enter("codeFencedFence"),gn(P)?jn(N,L,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(P):L(P)}function L(P){return P===c?(N.enter("codeFencedFenceSequence"),F(P)):_(P)}function F(P){return P===c?(T++,N.consume(P),F):T>=l?(N.exit("codeFencedFenceSequence"),gn(P)?jn(N,R,"whitespace")(P):R(P)):_(P)}function R(P){return P===null||Lt(P)?(N.exit("codeFencedFence"),S(P)):_(P)}}}function hC(e,n,s){const a=this;return r;function r(l){return l===null?s(l):(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),o)}function o(l){return a.parser.lazy[a.now().line]?s(l):n(l)}}const dc={name:"codeIndented",tokenize:fC},pC={partial:!0,tokenize:gC};function fC(e,n,s){const a=this;return r;function r(u){return e.enter("codeIndented"),jn(e,o,"linePrefix",5)(u)}function o(u){const m=a.events[a.events.length-1];return m&&m[1].type==="linePrefix"&&m[2].sliceSerialize(m[1],!0).length>=4?l(u):s(u)}function l(u){return u===null?d(u):Lt(u)?e.attempt(pC,l,d)(u):(e.enter("codeFlowValue"),c(u))}function c(u){return u===null||Lt(u)?(e.exit("codeFlowValue"),l(u)):(e.consume(u),c)}function d(u){return e.exit("codeIndented"),n(u)}}function gC(e,n,s){const a=this;return r;function r(l){return a.parser.lazy[a.now().line]?s(l):Lt(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),r):jn(e,o,"linePrefix",5)(l)}function o(l){const c=a.events[a.events.length-1];return c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?n(l):Lt(l)?r(l):s(l)}}const bC={name:"codeText",previous:vC,resolve:xC,tokenize:yC};function xC(e){let n=e.length-4,s=3,a,r;if((e[s][1].type==="lineEnding"||e[s][1].type==="space")&&(e[n][1].type==="lineEnding"||e[n][1].type==="space")){for(a=s;++a<n;)if(e[a][1].type==="codeTextData"){e[s][1].type="codeTextPadding",e[n][1].type="codeTextPadding",s+=2,n-=2;break}}for(a=s-1,n++;++a<=n;)r===void 0?a!==n&&e[a][1].type!=="lineEnding"&&(r=a):(a===n||e[a][1].type==="lineEnding")&&(e[r][1].type="codeTextData",a!==r+2&&(e[r][1].end=e[a-1][1].end,e.splice(r+2,a-r-2),n-=a-r-2,a=r+2),r=void 0);return e}function vC(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function yC(e,n,s){let a=0,r,o;return l;function l(h){return e.enter("codeText"),e.enter("codeTextSequence"),c(h)}function c(h){return h===96?(e.consume(h),a++,c):(e.exit("codeTextSequence"),d(h))}function d(h){return h===null?s(h):h===32?(e.enter("space"),e.consume(h),e.exit("space"),d):h===96?(o=e.enter("codeTextSequence"),r=0,m(h)):Lt(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),d):(e.enter("codeTextData"),u(h))}function u(h){return h===null||h===32||h===96||Lt(h)?(e.exit("codeTextData"),d(h)):(e.consume(h),u)}function m(h){return h===96?(e.consume(h),r++,m):r===a?(e.exit("codeTextSequence"),e.exit("codeText"),n(h)):(o.type="codeTextData",u(h))}}class wC{constructor(n){this.left=n?[...n]:[],this.right=[]}get(n){if(n<0||n>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+n+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return n<this.left.length?this.left[n]:this.right[this.right.length-n+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(n,s){const a=s??Number.POSITIVE_INFINITY;return a<this.left.length?this.left.slice(n,a):n>this.left.length?this.right.slice(this.right.length-a+this.left.length,this.right.length-n+this.left.length).reverse():this.left.slice(n).concat(this.right.slice(this.right.length-a+this.left.length).reverse())}splice(n,s,a){const r=s||0;this.setCursor(Math.trunc(n));const o=this.right.splice(this.right.length-r,Number.POSITIVE_INFINITY);return a&&or(this.left,a),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(n){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(n)}pushMany(n){this.setCursor(Number.POSITIVE_INFINITY),or(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),or(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);or(this.right,s.reverse())}else{const s=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);or(this.left,s.reverse())}}}function or(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 ng(e){const n={};let s=-1,a,r,o,l,c,d,u;const m=new wC(e);for(;++s<m.length;){for(;s in n;)s=n[s];if(a=m.get(s),s&&a[1].type==="chunkFlow"&&m.get(s-1)[1].type==="listItemPrefix"&&(d=a[1]._tokenizer.events,o=0,o<d.length&&d[o][1].type==="lineEndingBlank"&&(o+=2),o<d.length&&d[o][1].type==="content"))for(;++o<d.length&&d[o][1].type!=="content";)d[o][1].type==="chunkText"&&(d[o][1]._isInFirstContentOfListItem=!0,o++);if(a[0]==="enter")a[1].contentType&&(Object.assign(n,kC(m,s)),s=n[s],u=!0);else if(a[1]._container){for(o=s,r=void 0;o--;)if(l=m.get(o),l[1].type==="lineEnding"||l[1].type==="lineEndingBlank")l[0]==="enter"&&(r&&(m.get(r)[1].type="lineEndingBlank"),l[1].type="lineEnding",r=o);else if(!(l[1].type==="linePrefix"||l[1].type==="listItemIndent"))break;r&&(a[1].end={...m.get(r)[1].start},c=m.slice(r,s),c.unshift(a),m.splice(r,s-r+1,c))}}return Us(e,0,Number.POSITIVE_INFINITY,m.slice(0)),!u}function kC(e,n){const s=e.get(n)[1],a=e.get(n)[2];let r=n-1;const o=[];let l=s._tokenizer;l||(l=a.parser[s.contentType](s.start),s._contentTypeTextTrailing&&(l._contentTypeTextTrailing=!0));const c=l.events,d=[],u={};let m,h,f=-1,p=s,g=0,x=0;const v=[x];for(;p;){for(;e.get(++r)[1]!==p;);o.push(r),p._tokenizer||(m=a.sliceStream(p),p.next||m.push(null),h&&l.defineSkip(p.start),p._isInFirstContentOfListItem&&(l._gfmTasklistFirstContentOfListItem=!0),l.write(m),p._isInFirstContentOfListItem&&(l._gfmTasklistFirstContentOfListItem=void 0)),h=p,p=p.next}for(p=s;++f<c.length;)c[f][0]==="exit"&&c[f-1][0]==="enter"&&c[f][1].type===c[f-1][1].type&&c[f][1].start.line!==c[f][1].end.line&&(x=f+1,v.push(x),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(l.events=[],p?(p._tokenizer=void 0,p.previous=void 0):v.pop(),f=v.length;f--;){const b=c.slice(v[f],v[f+1]),y=o.pop();d.push([y,y+b.length-1]),e.splice(y,2,b)}for(d.reverse(),f=-1;++f<d.length;)u[g+d[f][0]]=g+d[f][1],g+=d[f][1]-d[f][0]-1;return u}const jC={resolve:SC,tokenize:CC},NC={partial:!0,tokenize:EC};function SC(e){return ng(e),e}function CC(e,n){let s;return a;function a(c){return e.enter("content"),s=e.enter("chunkContent",{contentType:"content"}),r(c)}function r(c){return c===null?o(c):Lt(c)?e.check(NC,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 EC(e,n,s){const a=this;return r;function r(l){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),jn(e,o,"linePrefix")}function o(l){if(l===null||Lt(l))return s(l);const c=a.events[a.events.length-1];return!a.parser.constructs.disable.null.includes("codeIndented")&&c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?n(l):e.interrupt(a.parser.constructs.flow,s,n)(l)}}function sg(e,n,s,a,r,o,l,c,d){const u=d||Number.POSITIVE_INFINITY;let m=0;return h;function h(b){return b===60?(e.enter(a),e.enter(r),e.enter(o),e.consume(b),e.exit(o),f):b===null||b===32||b===41||ol(b)?s(b):(e.enter(a),e.enter(l),e.enter(c),e.enter("chunkString",{contentType:"string"}),x(b))}function f(b){return b===62?(e.enter(o),e.consume(b),e.exit(o),e.exit(r),e.exit(a),n):(e.enter(c),e.enter("chunkString",{contentType:"string"}),p(b))}function p(b){return b===62?(e.exit("chunkString"),e.exit(c),f(b)):b===null||b===60||Lt(b)?s(b):(e.consume(b),b===92?g:p)}function g(b){return b===60||b===62||b===92?(e.consume(b),p):p(b)}function x(b){return!m&&(b===null||b===41||In(b))?(e.exit("chunkString"),e.exit(c),e.exit(l),e.exit(a),n(b)):m<u&&b===40?(e.consume(b),m++,x):b===41?(e.consume(b),m--,x):b===null||b===32||b===40||ol(b)?s(b):(e.consume(b),b===92?v:x)}function v(b){return b===40||b===41||b===92?(e.consume(b),x):x(b)}}function ig(e,n,s,a,r,o){const l=this;let c=0,d;return u;function u(p){return e.enter(a),e.enter(r),e.consume(p),e.exit(r),e.enter(o),m}function m(p){return c>999||p===null||p===91||p===93&&!d||p===94&&!c&&"_hiddenFootnoteSupport"in l.parser.constructs?s(p):p===93?(e.exit(o),e.enter(r),e.consume(p),e.exit(r),e.exit(a),n):Lt(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||Lt(p)||c++>999?(e.exit("chunkString"),m(p)):(e.consume(p),d||(d=!gn(p)),p===92?f:h)}function f(p){return p===91||p===92||p===93?(e.consume(p),c++,h):h(p)}}function ag(e,n,s,a,r,o){let l;return c;function c(f){return f===34||f===39||f===40?(e.enter(a),e.enter(r),e.consume(f),e.exit(r),l=f===40?41:f,d):s(f)}function d(f){return f===l?(e.enter(r),e.consume(f),e.exit(r),e.exit(a),n):(e.enter(o),u(f))}function u(f){return f===l?(e.exit(o),d(l)):f===null?s(f):Lt(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),jn(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),m(f))}function m(f){return f===l||f===null||Lt(f)?(e.exit("chunkString"),u(f)):(e.consume(f),f===92?h:m)}function h(f){return f===l||f===92?(e.consume(f),m):m(f)}}function Ar(e,n){let s;return a;function a(r){return Lt(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),s=!0,a):gn(r)?jn(e,a,s?"linePrefix":"lineSuffix")(r):n(r)}}const MC={name:"definition",tokenize:AC},_C={partial:!0,tokenize:PC};function AC(e,n,s){const a=this;let r;return o;function o(p){return e.enter("definition"),l(p)}function l(p){return ig.call(a,e,c,s,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function c(p){return r=ai(a.sliceSerialize(a.events[a.events.length-1][1]).slice(1,-1)),p===58?(e.enter("definitionMarker"),e.consume(p),e.exit("definitionMarker"),d):s(p)}function d(p){return In(p)?Ar(e,u)(p):u(p)}function u(p){return sg(e,m,s,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function m(p){return e.attempt(_C,h,h)(p)}function h(p){return gn(p)?jn(e,f,"whitespace")(p):f(p)}function f(p){return p===null||Lt(p)?(e.exit("definition"),a.parser.defined.push(r),n(p)):s(p)}}function PC(e,n,s){return a;function a(c){return In(c)?Ar(e,r)(c):s(c)}function r(c){return ag(e,o,s,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function o(c){return gn(c)?jn(e,l,"whitespace")(c):l(c)}function l(c){return c===null||Lt(c)?n(c):s(c)}}const RC={name:"hardBreakEscape",tokenize:TC};function TC(e,n,s){return a;function a(o){return e.enter("hardBreakEscape"),e.consume(o),r}function r(o){return Lt(o)?(e.exit("hardBreakEscape"),n(o)):s(o)}}const IC={name:"headingAtx",resolve:$C,tokenize:DC};function $C(e,n){let s=e.length-2,a=3,r,o;return e[a][1].type==="whitespace"&&(a+=2),s-2>a&&e[s][1].type==="whitespace"&&(s-=2),e[s][1].type==="atxHeadingSequence"&&(a===s-1||s-4>a&&e[s-2][1].type==="whitespace")&&(s-=a+1===s?2:4),s>a&&(r={type:"atxHeadingText",start:e[a][1].start,end:e[s][1].end},o={type:"chunkText",start:e[a][1].start,end:e[s][1].end,contentType:"text"},Us(e,a,s-a+1,[["enter",r,n],["enter",o,n],["exit",o,n],["exit",r,n]])),e}function DC(e,n,s){let a=0;return r;function r(m){return e.enter("atxHeading"),o(m)}function o(m){return e.enter("atxHeadingSequence"),l(m)}function l(m){return m===35&&a++<6?(e.consume(m),l):m===null||In(m)?(e.exit("atxHeadingSequence"),c(m)):s(m)}function c(m){return m===35?(e.enter("atxHeadingSequence"),d(m)):m===null||Lt(m)?(e.exit("atxHeading"),n(m)):gn(m)?jn(e,c,"whitespace")(m):(e.enter("atxHeadingText"),u(m))}function d(m){return m===35?(e.consume(m),d):(e.exit("atxHeadingSequence"),c(m))}function u(m){return m===null||m===35||In(m)?(e.exit("atxHeadingText"),c(m)):(e.consume(m),u)}}const LC=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Bm=["pre","script","style","textarea"],OC={concrete:!0,name:"htmlFlow",resolveTo:UC,tokenize:BC},zC={partial:!0,tokenize:qC},FC={partial:!0,tokenize:HC};function UC(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 BC(e,n,s){const a=this;let r,o,l,c,d;return u;function u(w){return m(w)}function m(w){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(w),h}function h(w){return w===33?(e.consume(w),f):w===47?(e.consume(w),o=!0,x):w===63?(e.consume(w),r=3,a.interrupt?n:k):Es(w)?(e.consume(w),l=String.fromCharCode(w),v):s(w)}function f(w){return w===45?(e.consume(w),r=2,p):w===91?(e.consume(w),r=5,c=0,g):Es(w)?(e.consume(w),r=4,a.interrupt?n:k):s(w)}function p(w){return w===45?(e.consume(w),a.interrupt?n:k):s(w)}function g(w){const H="CDATA[";return w===H.charCodeAt(c++)?(e.consume(w),c===H.length?a.interrupt?n:L:g):s(w)}function x(w){return Es(w)?(e.consume(w),l=String.fromCharCode(w),v):s(w)}function v(w){if(w===null||w===47||w===62||In(w)){const H=w===47,K=l.toLowerCase();return!H&&!o&&Bm.includes(K)?(r=1,a.interrupt?n(w):L(w)):LC.includes(l.toLowerCase())?(r=6,H?(e.consume(w),b):a.interrupt?n(w):L(w)):(r=7,a.interrupt&&!a.parser.lazy[a.now().line]?s(w):o?y(w):j(w))}return w===45||ks(w)?(e.consume(w),l+=String.fromCharCode(w),v):s(w)}function b(w){return w===62?(e.consume(w),a.interrupt?n:L):s(w)}function y(w){return gn(w)?(e.consume(w),y):M(w)}function j(w){return w===47?(e.consume(w),M):w===58||w===95||Es(w)?(e.consume(w),C):gn(w)?(e.consume(w),j):M(w)}function C(w){return w===45||w===46||w===58||w===95||ks(w)?(e.consume(w),C):A(w)}function A(w){return w===61?(e.consume(w),N):gn(w)?(e.consume(w),A):j(w)}function N(w){return w===null||w===60||w===61||w===62||w===96?s(w):w===34||w===39?(e.consume(w),d=w,S):gn(w)?(e.consume(w),N):_(w)}function S(w){return w===d?(e.consume(w),d=null,T):w===null||Lt(w)?s(w):(e.consume(w),S)}function _(w){return w===null||w===34||w===39||w===47||w===60||w===61||w===62||w===96||In(w)?A(w):(e.consume(w),_)}function T(w){return w===47||w===62||gn(w)?j(w):s(w)}function M(w){return w===62?(e.consume(w),E):s(w)}function E(w){return w===null||Lt(w)?L(w):gn(w)?(e.consume(w),E):s(w)}function L(w){return w===45&&r===2?(e.consume(w),O):w===60&&r===1?(e.consume(w),q):w===62&&r===4?(e.consume(w),I):w===63&&r===3?(e.consume(w),k):w===93&&r===5?(e.consume(w),z):Lt(w)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(zC,$,F)(w)):w===null||Lt(w)?(e.exit("htmlFlowData"),F(w)):(e.consume(w),L)}function F(w){return e.check(FC,R,$)(w)}function R(w){return e.enter("lineEnding"),e.consume(w),e.exit("lineEnding"),P}function P(w){return w===null||Lt(w)?F(w):(e.enter("htmlFlowData"),L(w))}function O(w){return w===45?(e.consume(w),k):L(w)}function q(w){return w===47?(e.consume(w),l="",Z):L(w)}function Z(w){if(w===62){const H=l.toLowerCase();return Bm.includes(H)?(e.consume(w),I):L(w)}return Es(w)&&l.length<8?(e.consume(w),l+=String.fromCharCode(w),Z):L(w)}function z(w){return w===93?(e.consume(w),k):L(w)}function k(w){return w===62?(e.consume(w),I):w===45&&r===2?(e.consume(w),k):L(w)}function I(w){return w===null||Lt(w)?(e.exit("htmlFlowData"),$(w)):(e.consume(w),I)}function $(w){return e.exit("htmlFlow"),n(w)}}function HC(e,n,s){const a=this;return r;function r(l){return Lt(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),o):s(l)}function o(l){return a.parser.lazy[a.now().line]?s(l):n(l)}}function qC(e,n,s){return a;function a(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(to,n,s)}}const VC={name:"htmlText",tokenize:WC};function WC(e,n,s){const a=this;let r,o,l;return c;function c(k){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(k),d}function d(k){return k===33?(e.consume(k),u):k===47?(e.consume(k),A):k===63?(e.consume(k),j):Es(k)?(e.consume(k),_):s(k)}function u(k){return k===45?(e.consume(k),m):k===91?(e.consume(k),o=0,g):Es(k)?(e.consume(k),y):s(k)}function m(k){return k===45?(e.consume(k),p):s(k)}function h(k){return k===null?s(k):k===45?(e.consume(k),f):Lt(k)?(l=h,q(k)):(e.consume(k),h)}function f(k){return k===45?(e.consume(k),p):h(k)}function p(k){return k===62?O(k):k===45?f(k):h(k)}function g(k){const I="CDATA[";return k===I.charCodeAt(o++)?(e.consume(k),o===I.length?x:g):s(k)}function x(k){return k===null?s(k):k===93?(e.consume(k),v):Lt(k)?(l=x,q(k)):(e.consume(k),x)}function v(k){return k===93?(e.consume(k),b):x(k)}function b(k){return k===62?O(k):k===93?(e.consume(k),b):x(k)}function y(k){return k===null||k===62?O(k):Lt(k)?(l=y,q(k)):(e.consume(k),y)}function j(k){return k===null?s(k):k===63?(e.consume(k),C):Lt(k)?(l=j,q(k)):(e.consume(k),j)}function C(k){return k===62?O(k):j(k)}function A(k){return Es(k)?(e.consume(k),N):s(k)}function N(k){return k===45||ks(k)?(e.consume(k),N):S(k)}function S(k){return Lt(k)?(l=S,q(k)):gn(k)?(e.consume(k),S):O(k)}function _(k){return k===45||ks(k)?(e.consume(k),_):k===47||k===62||In(k)?T(k):s(k)}function T(k){return k===47?(e.consume(k),O):k===58||k===95||Es(k)?(e.consume(k),M):Lt(k)?(l=T,q(k)):gn(k)?(e.consume(k),T):O(k)}function M(k){return k===45||k===46||k===58||k===95||ks(k)?(e.consume(k),M):E(k)}function E(k){return k===61?(e.consume(k),L):Lt(k)?(l=E,q(k)):gn(k)?(e.consume(k),E):T(k)}function L(k){return k===null||k===60||k===61||k===62||k===96?s(k):k===34||k===39?(e.consume(k),r=k,F):Lt(k)?(l=L,q(k)):gn(k)?(e.consume(k),L):(e.consume(k),R)}function F(k){return k===r?(e.consume(k),r=void 0,P):k===null?s(k):Lt(k)?(l=F,q(k)):(e.consume(k),F)}function R(k){return k===null||k===34||k===39||k===60||k===61||k===96?s(k):k===47||k===62||In(k)?T(k):(e.consume(k),R)}function P(k){return k===47||k===62||In(k)?T(k):s(k)}function O(k){return k===62?(e.consume(k),e.exit("htmlTextData"),e.exit("htmlText"),n):s(k)}function q(k){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(k),e.exit("lineEnding"),Z}function Z(k){return gn(k)?jn(e,z,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(k):z(k)}function z(k){return e.enter("htmlTextData"),l(k)}}const au={name:"labelEnd",resolveAll:YC,resolveTo:QC,tokenize:XC},KC={tokenize:ZC},GC={tokenize:e2},JC={tokenize:t2};function YC(e){let n=-1;const s=[];for(;++n<e.length;){const a=e[n][1];if(s.push(e[n]),a.type==="labelImage"||a.type==="labelLink"||a.type==="labelEnd"){const r=a.type==="labelImage"?4:2;a.type="data",n+=r}}return e.length!==s.length&&Us(e,0,e.length,s),e}function QC(e,n){let s=e.length,a=0,r,o,l,c;for(;s--;)if(r=e[s][1],o){if(r.type==="link"||r.type==="labelLink"&&r._inactive)break;e[s][0]==="enter"&&r.type==="labelLink"&&(r._inactive=!0)}else if(l){if(e[s][0]==="enter"&&(r.type==="labelImage"||r.type==="labelLink")&&!r._balanced&&(o=s,r.type!=="labelLink")){a=2;break}}else r.type==="labelEnd"&&(l=s);const d={type:e[o][1].type==="labelLink"?"link":"image",start:{...e[o][1].start},end:{...e[e.length-1][1].end}},u={type:"label",start:{...e[o][1].start},end:{...e[l][1].end}},m={type:"labelText",start:{...e[o+a+2][1].end},end:{...e[l-2][1].start}};return c=[["enter",d,n],["enter",u,n]],c=Ys(c,e.slice(o+1,o+a+3)),c=Ys(c,[["enter",m,n]]),c=Ys(c,Rl(n.parser.constructs.insideSpan.null,e.slice(o+a+4,l-3),n)),c=Ys(c,[["exit",m,n],e[l-2],e[l-1],["exit",u,n]]),c=Ys(c,e.slice(l+1)),c=Ys(c,[["exit",d,n]]),Us(e,o,e.length,c),e}function XC(e,n,s){const a=this;let r=a.events.length,o,l;for(;r--;)if((a.events[r][1].type==="labelImage"||a.events[r][1].type==="labelLink")&&!a.events[r][1]._balanced){o=a.events[r][1];break}return c;function c(f){return o?o._inactive?h(f):(l=a.parser.defined.includes(ai(a.sliceSerialize({start:o.end,end:a.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(f),e.exit("labelMarker"),e.exit("labelEnd"),d):s(f)}function d(f){return f===40?e.attempt(KC,m,l?m:h)(f):f===91?e.attempt(GC,m,l?u:h)(f):l?m(f):h(f)}function u(f){return e.attempt(JC,m,h)(f)}function m(f){return n(f)}function h(f){return o._balanced=!0,s(f)}}function ZC(e,n,s){return a;function a(h){return e.enter("resource"),e.enter("resourceMarker"),e.consume(h),e.exit("resourceMarker"),r}function r(h){return In(h)?Ar(e,o)(h):o(h)}function o(h){return h===41?m(h):sg(e,l,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function l(h){return In(h)?Ar(e,d)(h):m(h)}function c(h){return s(h)}function d(h){return h===34||h===39||h===40?ag(e,u,s,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):m(h)}function u(h){return In(h)?Ar(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 e2(e,n,s){const a=this;return r;function r(c){return ig.call(a,e,o,l,"reference","referenceMarker","referenceString")(c)}function o(c){return a.parser.defined.includes(ai(a.sliceSerialize(a.events[a.events.length-1][1]).slice(1,-1)))?n(c):s(c)}function l(c){return s(c)}}function t2(e,n,s){return a;function a(o){return e.enter("reference"),e.enter("referenceMarker"),e.consume(o),e.exit("referenceMarker"),r}function r(o){return o===93?(e.enter("referenceMarker"),e.consume(o),e.exit("referenceMarker"),e.exit("reference"),n):s(o)}}const n2={name:"labelStartImage",resolveAll:au.resolveAll,tokenize:s2};function s2(e,n,s){const a=this;return r;function r(c){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(c),e.exit("labelImageMarker"),o}function o(c){return c===91?(e.enter("labelMarker"),e.consume(c),e.exit("labelMarker"),e.exit("labelImage"),l):s(c)}function l(c){return c===94&&"_hiddenFootnoteSupport"in a.parser.constructs?s(c):n(c)}}const i2={name:"labelStartLink",resolveAll:au.resolveAll,tokenize:a2};function a2(e,n,s){const a=this;return r;function r(l){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(l),e.exit("labelMarker"),e.exit("labelLink"),o}function o(l){return l===94&&"_hiddenFootnoteSupport"in a.parser.constructs?s(l):n(l)}}const uc={name:"lineEnding",tokenize:r2};function r2(e,n){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),jn(e,n,"linePrefix")}}const Wo={name:"thematicBreak",tokenize:o2};function o2(e,n,s){let a=0,r;return o;function o(u){return e.enter("thematicBreak"),l(u)}function l(u){return r=u,c(u)}function c(u){return u===r?(e.enter("thematicBreakSequence"),d(u)):a>=3&&(u===null||Lt(u))?(e.exit("thematicBreak"),n(u)):s(u)}function d(u){return u===r?(e.consume(u),a++,d):(e.exit("thematicBreakSequence"),gn(u)?jn(e,c,"whitespace")(u):c(u))}}const As={continuation:{tokenize:u2},exit:h2,name:"list",tokenize:d2},l2={partial:!0,tokenize:p2},c2={partial:!0,tokenize:m2};function d2(e,n,s){const a=this,r=a.events[a.events.length-1];let o=r&&r[1].type==="linePrefix"?r[2].sliceSerialize(r[1],!0).length:0,l=0;return c;function c(p){const g=a.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(g==="listUnordered"?!a.containerState.marker||p===a.containerState.marker:jd(p)){if(a.containerState.type||(a.containerState.type=g,e.enter(g,{_container:!0})),g==="listUnordered")return e.enter("listItemPrefix"),p===42||p===45?e.check(Wo,s,u)(p):u(p);if(!a.interrupt||p===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),d(p)}return s(p)}function d(p){return jd(p)&&++l<10?(e.consume(p),d):(!a.interrupt||l<2)&&(a.containerState.marker?p===a.containerState.marker:p===41||p===46)?(e.exit("listItemValue"),u(p)):s(p)}function u(p){return e.enter("listItemMarker"),e.consume(p),e.exit("listItemMarker"),a.containerState.marker=a.containerState.marker||p,e.check(to,a.interrupt?s:m,e.attempt(l2,f,h))}function m(p){return a.containerState.initialBlankLine=!0,o++,f(p)}function h(p){return gn(p)?(e.enter("listItemPrefixWhitespace"),e.consume(p),e.exit("listItemPrefixWhitespace"),f):s(p)}function f(p){return a.containerState.size=o+a.sliceSerialize(e.exit("listItemPrefix"),!0).length,n(p)}}function u2(e,n,s){const a=this;return a.containerState._closeFlow=void 0,e.check(to,r,o);function r(c){return a.containerState.furtherBlankLines=a.containerState.furtherBlankLines||a.containerState.initialBlankLine,jn(e,n,"listItemIndent",a.containerState.size+1)(c)}function o(c){return a.containerState.furtherBlankLines||!gn(c)?(a.containerState.furtherBlankLines=void 0,a.containerState.initialBlankLine=void 0,l(c)):(a.containerState.furtherBlankLines=void 0,a.containerState.initialBlankLine=void 0,e.attempt(c2,n,l)(c))}function l(c){return a.containerState._closeFlow=!0,a.interrupt=void 0,jn(e,e.attempt(As,n,s),"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function m2(e,n,s){const a=this;return jn(e,r,"listItemIndent",a.containerState.size+1);function r(o){const l=a.events[a.events.length-1];return l&&l[1].type==="listItemIndent"&&l[2].sliceSerialize(l[1],!0).length===a.containerState.size?n(o):s(o)}}function h2(e){e.exit(this.containerState.type)}function p2(e,n,s){const a=this;return jn(e,r,"listItemPrefixWhitespace",a.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function r(o){const l=a.events[a.events.length-1];return!gn(o)&&l&&l[1].type==="listItemPrefixWhitespace"?n(o):s(o)}}const Hm={name:"setextUnderline",resolveTo:f2,tokenize:g2};function f2(e,n){let s=e.length,a,r,o;for(;s--;)if(e[s][0]==="enter"){if(e[s][1].type==="content"){a=s;break}e[s][1].type==="paragraph"&&(r=s)}else e[s][1].type==="content"&&e.splice(s,1),!o&&e[s][1].type==="definition"&&(o=s);const l={type:"setextHeading",start:{...e[a][1].start},end:{...e[e.length-1][1].end}};return e[r][1].type="setextHeadingText",o?(e.splice(r,0,["enter",l,n]),e.splice(o+1,0,["exit",e[a][1],n]),e[a][1].end={...e[o][1].end}):e[a][1]=l,e.push(["exit",l,n]),e}function g2(e,n,s){const a=this;let r;return o;function o(u){let m=a.events.length,h;for(;m--;)if(a.events[m][1].type!=="lineEnding"&&a.events[m][1].type!=="linePrefix"&&a.events[m][1].type!=="content"){h=a.events[m][1].type==="paragraph";break}return!a.parser.lazy[a.now().line]&&(a.interrupt||h)?(e.enter("setextHeadingLine"),r=u,l(u)):s(u)}function l(u){return e.enter("setextHeadingLineSequence"),c(u)}function c(u){return u===r?(e.consume(u),c):(e.exit("setextHeadingLineSequence"),gn(u)?jn(e,d,"lineSuffix")(u):d(u))}function d(u){return u===null||Lt(u)?(e.exit("setextHeadingLine"),n(u)):s(u)}}const b2={tokenize:x2};function x2(e){const n=this,s=e.attempt(to,a,e.attempt(this.parser.constructs.flowInitial,r,jn(e,e.attempt(this.parser.constructs.flow,r,e.attempt(jC,r)),"linePrefix")));return s;function a(o){if(o===null){e.consume(o);return}return e.enter("lineEndingBlank"),e.consume(o),e.exit("lineEndingBlank"),n.currentConstruct=void 0,s}function r(o){if(o===null){e.consume(o);return}return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),n.currentConstruct=void 0,s}}const v2={resolveAll:og()},y2=rg("string"),w2=rg("text");function rg(e){return{resolveAll:og(e==="text"?k2:void 0),tokenize:n};function n(s){const a=this,r=this.parser.constructs[e],o=s.attempt(r,l,c);return l;function l(m){return u(m)?o(m):c(m)}function c(m){if(m===null){s.consume(m);return}return s.enter("data"),s.consume(m),d}function d(m){return u(m)?(s.exit("data"),o(m)):(s.consume(m),d)}function u(m){if(m===null)return!0;const h=r[m];let f=-1;if(h)for(;++f<h.length;){const p=h[f];if(!p.previous||p.previous.call(a,a.previous))return!0}return!1}}}function og(e){return n;function n(s,a){let r=-1,o;for(;++r<=s.length;)o===void 0?s[r]&&s[r][1].type==="data"&&(o=r,r++):(!s[r]||s[r][1].type!=="data")&&(r!==o+2&&(s[o][1].end=s[r-1][1].end,s.splice(o+2,r-o-2),r=o+2),o=void 0);return e?e(s,a):s}}function k2(e,n){let s=0;for(;++s<=e.length;)if((s===e.length||e[s][1].type==="lineEnding")&&e[s-1][1].type==="data"){const a=e[s-1][1],r=n.sliceStream(a);let o=r.length,l=-1,c=0,d;for(;o--;){const u=r[o];if(typeof u=="string"){for(l=u.length;u.charCodeAt(l-1)===32;)c++,l--;if(l)break;l=-1}else if(u===-2)d=!0,c++;else if(u!==-1){o++;break}}if(n._contentTypeTextTrailing&&s===e.length&&(c=0),c){const u={type:s===e.length||d||c<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:o?l:a.start._bufferIndex+l,_index:a.start._index+o,line:a.end.line,column:a.end.column-c,offset:a.end.offset-c},end:{...a.end}};a.end={...u.start},a.start.offset===a.end.offset?Object.assign(a,u):(e.splice(s,0,["enter",u,n],["exit",u,n]),s+=2)}s++}return e}const j2={42:As,43:As,45:As,48:As,49:As,50:As,51:As,52:As,53:As,54:As,55:As,56:As,57:As,62:Zf},N2={91:MC},S2={[-2]:dc,[-1]:dc,32:dc},C2={35:IC,42:Wo,45:[Hm,Wo],60:OC,61:Hm,95:Wo,96:Um,126:Um},E2={38:tg,92:eg},M2={[-5]:uc,[-4]:uc,[-3]:uc,33:n2,38:tg,42:Nd,60:[iC,VC],91:i2,92:[RC,eg],93:au,95:Nd,96:bC},_2={null:[Nd,v2]},A2={null:[42,95]},P2={null:[]},R2=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:A2,contentInitial:N2,disable:P2,document:j2,flow:C2,flowInitial:S2,insideSpan:_2,string:E2,text:M2},Symbol.toStringTag,{value:"Module"}));function T2(e,n,s){let a={_bufferIndex:-1,_index:0,line:s&&s.line||1,column:s&&s.column||1,offset:s&&s.offset||0};const r={},o=[];let l=[],c=[];const d={attempt:S(A),check:S(N),consume:y,enter:j,exit:C,interrupt:S(N,{interrupt:!0})},u={code:null,containerState:{},defineSkip:x,events:[],now:g,parser:e,previous:null,sliceSerialize:f,sliceStream:p,write:h};let m=n.tokenize.call(u,d);return n.resolveAll&&o.push(n),u;function h(E){return l=Ys(l,E),v(),l[l.length-1]!==null?[]:(_(n,0),u.events=Rl(o,u.events,u),u.events)}function f(E,L){return $2(p(E),L)}function p(E){return I2(l,E)}function g(){const{_bufferIndex:E,_index:L,line:F,column:R,offset:P}=a;return{_bufferIndex:E,_index:L,line:F,column:R,offset:P}}function x(E){r[E.line]=E.column,M()}function v(){let E;for(;a._index<l.length;){const L=l[a._index];if(typeof L=="string")for(E=a._index,a._bufferIndex<0&&(a._bufferIndex=0);a._index===E&&a._bufferIndex<L.length;)b(L.charCodeAt(a._bufferIndex));else b(L)}}function b(E){m=m(E)}function y(E){Lt(E)?(a.line++,a.column=1,a.offset+=E===-3?2:1,M()):E!==-1&&(a.column++,a.offset++),a._bufferIndex<0?a._index++:(a._bufferIndex++,a._bufferIndex===l[a._index].length&&(a._bufferIndex=-1,a._index++)),u.previous=E}function j(E,L){const F=L||{};return F.type=E,F.start=g(),u.events.push(["enter",F,u]),c.push(F),F}function C(E){const L=c.pop();return L.end=g(),u.events.push(["exit",L,u]),L}function A(E,L){_(E,L.from)}function N(E,L){L.restore()}function S(E,L){return F;function F(R,P,O){let q,Z,z,k;return Array.isArray(R)?$(R):"tokenize"in R?$([R]):I(R);function I(pe){return le;function le(B){const ye=B!==null&&pe[B],U=B!==null&&pe.null,te=[...Array.isArray(ye)?ye:ye?[ye]:[],...Array.isArray(U)?U:U?[U]:[]];return $(te)(B)}}function $(pe){return q=pe,Z=0,pe.length===0?O:w(pe[Z])}function w(pe){return le;function le(B){return k=T(),z=pe,pe.partial||(u.currentConstruct=pe),pe.name&&u.parser.constructs.disable.null.includes(pe.name)?K():pe.tokenize.call(L?Object.assign(Object.create(u),L):u,d,H,K)(B)}}function H(pe){return E(z,k),P}function K(pe){return k.restore(),++Z<q.length?w(q[Z]):O}}}function _(E,L){E.resolveAll&&!o.includes(E)&&o.push(E),E.resolve&&Us(u.events,L,u.events.length-L,E.resolve(u.events.slice(L),u)),E.resolveTo&&(u.events=E.resolveTo(u.events,u))}function T(){const E=g(),L=u.previous,F=u.currentConstruct,R=u.events.length,P=Array.from(c);return{from:R,restore:O};function O(){a=E,u.previous=L,u.currentConstruct=F,u.events.length=R,c=P,M()}}function M(){a.line in r&&a.column<2&&(a.column=r[a.line],a.offset+=r[a.line]-1)}}function I2(e,n){const s=n.start._index,a=n.start._bufferIndex,r=n.end._index,o=n.end._bufferIndex;let l;if(s===r)l=[e[s].slice(a,o)];else{if(l=e.slice(s,r),a>-1){const c=l[0];typeof c=="string"?l[0]=c.slice(a):l.shift()}o>0&&l.push(e[r].slice(0,o))}return l}function $2(e,n){let s=-1;const a=[];let r;for(;++s<e.length;){const o=e[s];let l;if(typeof o=="string")l=o;else switch(o){case-5:{l="\r";break}case-4:{l=`
645
+ `;break}case-3:{l=`\r
646
+ `;break}case-2:{l=n?" ":" ";break}case-1:{if(!n&&r)continue;l=" ";break}default:l=String.fromCharCode(o)}r=o===-2,a.push(l)}return a.join("")}function D2(e){const a={constructs:Qf([R2,...(e||{}).extensions||[]]),content:r(Q0),defined:[],document:r(Z0),flow:r(b2),lazy:{},string:r(y2),text:r(w2)};return a;function r(o){return l;function l(c){return T2(a,o,c)}}}function L2(e){for(;!ng(e););return e}const qm=/[\0\t\n\r]/g;function O2(){let e=1,n="",s=!0,a;return r;function r(o,l,c){const d=[];let u,m,h,f,p;for(o=n+(typeof o=="string"?o.toString():new TextDecoder(l||void 0).decode(o)),h=0,n="",s&&(o.charCodeAt(0)===65279&&h++,s=void 0);h<o.length;){if(qm.lastIndex=h,u=qm.exec(o),f=u&&u.index!==void 0?u.index:o.length,p=o.charCodeAt(f),!u){n=o.slice(h);break}if(p===10&&h===f&&a)d.push(-3),a=void 0;else switch(a&&(d.push(-5),a=void 0),h<f&&(d.push(o.slice(h,f)),e+=f-h),p){case 0:{d.push(65533),e++;break}case 9:{for(m=Math.ceil(e/4)*4,d.push(-2);e++<m;)d.push(-1);break}case 10:{d.push(-4),e=1;break}default:a=!0,e=1}h=f+1}return c&&(a&&d.push(-5),n&&d.push(n),d.push(null)),d}}const z2=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function F2(e){return e.replace(z2,U2)}function U2(e,n,s){if(n)return n;if(s.charCodeAt(0)===35){const r=s.charCodeAt(1),o=r===120||r===88;return Xf(s.slice(o?2:1),o?16:10)}return iu(s)||e}const lg={}.hasOwnProperty;function B2(e,n,s){return n&&typeof n=="object"&&(s=n,n=void 0),H2(s)(L2(D2(s).document().write(O2()(e,n,!0))))}function H2(e){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(Se),autolinkProtocol:T,autolinkEmail:T,atxHeading:o(ge),blockQuote:o(U),characterEscape:T,characterReference:T,codeFenced:o(te),codeFencedFenceInfo:l,codeFencedFenceMeta:l,codeIndented:o(te,l),codeText:o(ne,l),codeTextData:T,data:T,codeFlowValue:T,definition:o(ee),definitionDestinationString:l,definitionLabelString:l,definitionTitleString:l,emphasis:o(ie),hardBreakEscape:o(se),hardBreakTrailing:o(se),htmlFlow:o(Ae,l),htmlFlowData:T,htmlText:o(Ae,l),htmlTextData:T,image:o(xe),label:l,link:o(Se),listItem:o(We),listItemValue:f,listOrdered:o(qe,h),listUnordered:o(qe),paragraph:o(Qe),reference:w,referenceString:l,resourceDestinationString:l,resourceTitleString:l,setextHeading:o(ge),strong:o(ve),thematicBreak:o(ae)},exit:{atxHeading:d(),atxHeadingSequence:A,autolink:d(),autolinkEmail:ye,autolinkProtocol:B,blockQuote:d(),characterEscapeValue:M,characterReferenceMarkerHexadecimal:K,characterReferenceMarkerNumeric:K,characterReferenceValue:pe,characterReference:le,codeFenced:d(v),codeFencedFence:x,codeFencedFenceInfo:p,codeFencedFenceMeta:g,codeFlowValue:M,codeIndented:d(b),codeText:d(P),codeTextData:M,data:M,definition:d(),definitionDestinationString:C,definitionLabelString:y,definitionTitleString:j,emphasis:d(),hardBreakEscape:d(L),hardBreakTrailing:d(L),htmlFlow:d(F),htmlFlowData:M,htmlText:d(R),htmlTextData:M,image:d(q),label:z,labelText:Z,lineEnding:E,link:d(O),listItem:d(),listOrdered:d(),listUnordered:d(),paragraph:d(),referenceString:H,resourceDestinationString:k,resourceTitleString:I,resource:$,setextHeading:d(_),setextHeadingLineSequence:S,setextHeadingText:N,strong:d(),thematicBreak:d()}};cg(n,(e||{}).mdastExtensions||[]);const s={};return a;function a(re){let je={type:"root",children:[]};const Q={stack:[je],tokenStack:[],config:n,enter:c,exit:u,buffer:l,resume:m,data:s},Fe=[];let Je=-1;for(;++Je<re.length;)if(re[Je][1].type==="listOrdered"||re[Je][1].type==="listUnordered")if(re[Je][0]==="enter")Fe.push(Je);else{const be=Fe.pop();Je=r(re,be,Je)}for(Je=-1;++Je<re.length;){const be=n[re[Je][0]];lg.call(be,re[Je][1].type)&&be[re[Je][1].type].call(Object.assign({sliceSerialize:re[Je][2].sliceSerialize},Q),re[Je][1])}if(Q.tokenStack.length>0){const be=Q.tokenStack[Q.tokenStack.length-1];(be[1]||Vm).call(Q,void 0,be[0])}for(je.position={start:$i(re.length>0?re[0][1].start:{line:1,column:1,offset:0}),end:$i(re.length>0?re[re.length-2][1].end:{line:1,column:1,offset:0})},Je=-1;++Je<n.transforms.length;)je=n.transforms[Je](je)||je;return je}function r(re,je,Q){let Fe=je-1,Je=-1,be=!1,ze,tt,kt,ke;for(;++Fe<=Q;){const ce=re[Fe];switch(ce[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{ce[0]==="enter"?Je++:Je--,ke=void 0;break}case"lineEndingBlank":{ce[0]==="enter"&&(ze&&!ke&&!Je&&!kt&&(kt=Fe),ke=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:ke=void 0}if(!Je&&ce[0]==="enter"&&ce[1].type==="listItemPrefix"||Je===-1&&ce[0]==="exit"&&(ce[1].type==="listUnordered"||ce[1].type==="listOrdered")){if(ze){let Te=Fe;for(tt=void 0;Te--;){const he=re[Te];if(he[1].type==="lineEnding"||he[1].type==="lineEndingBlank"){if(he[0]==="exit")continue;tt&&(re[tt][1].type="lineEndingBlank",be=!0),he[1].type="lineEnding",tt=Te}else if(!(he[1].type==="linePrefix"||he[1].type==="blockQuotePrefix"||he[1].type==="blockQuotePrefixWhitespace"||he[1].type==="blockQuoteMarker"||he[1].type==="listItemIndent"))break}kt&&(!tt||kt<tt)&&(ze._spread=!0),ze.end=Object.assign({},tt?re[tt][1].start:ce[1].end),re.splice(tt||Fe,0,["exit",ze,ce[2]]),Fe++,Q++}if(ce[1].type==="listItemPrefix"){const Te={type:"listItem",_spread:!1,start:Object.assign({},ce[1].start),end:void 0};ze=Te,re.splice(Fe,0,["enter",Te,ce[2]]),Fe++,Q++,kt=void 0,ke=!0}}}return re[je][1]._spread=be,Q}function o(re,je){return Q;function Q(Fe){c.call(this,re(Fe),Fe),je&&je.call(this,Fe)}}function l(){this.stack.push({type:"fragment",children:[]})}function c(re,je,Q){this.stack[this.stack.length-1].children.push(re),this.stack.push(re),this.tokenStack.push([je,Q||void 0]),re.position={start:$i(je.start),end:void 0}}function d(re){return je;function je(Q){re&&re.call(this,Q),u.call(this,Q)}}function u(re,je){const Q=this.stack.pop(),Fe=this.tokenStack.pop();if(Fe)Fe[0].type!==re.type&&(je?je.call(this,re,Fe[0]):(Fe[1]||Vm).call(this,re,Fe[0]));else throw new Error("Cannot close `"+re.type+"` ("+_r({start:re.start,end:re.end})+"): it’s not open");Q.position.end=$i(re.end)}function m(){return su(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function f(re){if(this.data.expectingFirstListItemValue){const je=this.stack[this.stack.length-2];je.start=Number.parseInt(this.sliceSerialize(re),10),this.data.expectingFirstListItemValue=void 0}}function p(){const re=this.resume(),je=this.stack[this.stack.length-1];je.lang=re}function g(){const re=this.resume(),je=this.stack[this.stack.length-1];je.meta=re}function x(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function v(){const re=this.resume(),je=this.stack[this.stack.length-1];je.value=re.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function b(){const re=this.resume(),je=this.stack[this.stack.length-1];je.value=re.replace(/(\r?\n|\r)$/g,"")}function y(re){const je=this.resume(),Q=this.stack[this.stack.length-1];Q.label=je,Q.identifier=ai(this.sliceSerialize(re)).toLowerCase()}function j(){const re=this.resume(),je=this.stack[this.stack.length-1];je.title=re}function C(){const re=this.resume(),je=this.stack[this.stack.length-1];je.url=re}function A(re){const je=this.stack[this.stack.length-1];if(!je.depth){const Q=this.sliceSerialize(re).length;je.depth=Q}}function N(){this.data.setextHeadingSlurpLineEnding=!0}function S(re){const je=this.stack[this.stack.length-1];je.depth=this.sliceSerialize(re).codePointAt(0)===61?1:2}function _(){this.data.setextHeadingSlurpLineEnding=void 0}function T(re){const Q=this.stack[this.stack.length-1].children;let Fe=Q[Q.length-1];(!Fe||Fe.type!=="text")&&(Fe=Oe(),Fe.position={start:$i(re.start),end:void 0},Q.push(Fe)),this.stack.push(Fe)}function M(re){const je=this.stack.pop();je.value+=this.sliceSerialize(re),je.position.end=$i(re.end)}function E(re){const je=this.stack[this.stack.length-1];if(this.data.atHardBreak){const Q=je.children[je.children.length-1];Q.position.end=$i(re.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(je.type)&&(T.call(this,re),M.call(this,re))}function L(){this.data.atHardBreak=!0}function F(){const re=this.resume(),je=this.stack[this.stack.length-1];je.value=re}function R(){const re=this.resume(),je=this.stack[this.stack.length-1];je.value=re}function P(){const re=this.resume(),je=this.stack[this.stack.length-1];je.value=re}function O(){const re=this.stack[this.stack.length-1];if(this.data.inReference){const je=this.data.referenceType||"shortcut";re.type+="Reference",re.referenceType=je,delete re.url,delete re.title}else delete re.identifier,delete re.label;this.data.referenceType=void 0}function q(){const re=this.stack[this.stack.length-1];if(this.data.inReference){const je=this.data.referenceType||"shortcut";re.type+="Reference",re.referenceType=je,delete re.url,delete re.title}else delete re.identifier,delete re.label;this.data.referenceType=void 0}function Z(re){const je=this.sliceSerialize(re),Q=this.stack[this.stack.length-2];Q.label=F2(je),Q.identifier=ai(je).toLowerCase()}function z(){const re=this.stack[this.stack.length-1],je=this.resume(),Q=this.stack[this.stack.length-1];if(this.data.inReference=!0,Q.type==="link"){const Fe=re.children;Q.children=Fe}else Q.alt=je}function k(){const re=this.resume(),je=this.stack[this.stack.length-1];je.url=re}function I(){const re=this.resume(),je=this.stack[this.stack.length-1];je.title=re}function $(){this.data.inReference=void 0}function w(){this.data.referenceType="collapsed"}function H(re){const je=this.resume(),Q=this.stack[this.stack.length-1];Q.label=je,Q.identifier=ai(this.sliceSerialize(re)).toLowerCase(),this.data.referenceType="full"}function K(re){this.data.characterReferenceType=re.type}function pe(re){const je=this.sliceSerialize(re),Q=this.data.characterReferenceType;let Fe;Q?(Fe=Xf(je,Q==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Fe=iu(je);const Je=this.stack[this.stack.length-1];Je.value+=Fe}function le(re){const je=this.stack.pop();je.position.end=$i(re.end)}function B(re){M.call(this,re);const je=this.stack[this.stack.length-1];je.url=this.sliceSerialize(re)}function ye(re){M.call(this,re);const je=this.stack[this.stack.length-1];je.url="mailto:"+this.sliceSerialize(re)}function U(){return{type:"blockquote",children:[]}}function te(){return{type:"code",lang:null,meta:null,value:""}}function ne(){return{type:"inlineCode",value:""}}function ee(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function ie(){return{type:"emphasis",children:[]}}function ge(){return{type:"heading",depth:0,children:[]}}function se(){return{type:"break"}}function Ae(){return{type:"html",value:""}}function xe(){return{type:"image",title:null,url:"",alt:null}}function Se(){return{type:"link",title:null,url:"",children:[]}}function qe(re){return{type:"list",ordered:re.type==="listOrdered",start:null,spread:re._spread,children:[]}}function We(re){return{type:"listItem",spread:re._spread,checked:null,children:[]}}function Qe(){return{type:"paragraph",children:[]}}function ve(){return{type:"strong",children:[]}}function Oe(){return{type:"text",value:""}}function ae(){return{type:"thematicBreak"}}}function $i(e){return{line:e.line,column:e.column,offset:e.offset}}function cg(e,n){let s=-1;for(;++s<n.length;){const a=n[s];Array.isArray(a)?cg(e,a):q2(e,a)}}function q2(e,n){let s;for(s in n)if(lg.call(n,s))switch(s){case"canContainEols":{const a=n[s];a&&e[s].push(...a);break}case"transforms":{const a=n[s];a&&e[s].push(...a);break}case"enter":case"exit":{const a=n[s];a&&Object.assign(e[s],a);break}}}function Vm(e,n){throw e?new Error("Cannot close `"+e.type+"` ("+_r({start:e.start,end:e.end})+"): a different token (`"+n.type+"`, "+_r({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+_r({start:n.start,end:n.end})+") is still open")}function V2(e){const n=this;n.parser=s;function s(a){return B2(a,{...n.data("settings"),...e,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function W2(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 K2(e,n){const s={type:"element",tagName:"br",properties:{},children:[]};return e.patch(n,s),[e.applyData(n,s),{type:"text",value:`
647
+ `}]}function G2(e,n){const s=n.value?n.value+`
648
+ `:"",a={},r=n.lang?n.lang.split(/\s+/):[];r.length>0&&(a.className=["language-"+r[0]]);let o={type:"element",tagName:"code",properties:a,children:[{type:"text",value:s}]};return n.meta&&(o.data={meta:n.meta}),e.patch(n,o),o=e.applyData(n,o),o={type:"element",tagName:"pre",properties:{},children:[o]},e.patch(n,o),o}function J2(e,n){const s={type:"element",tagName:"del",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function Y2(e,n){const s={type:"element",tagName:"em",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function Q2(e,n){const s=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",a=String(n.identifier).toUpperCase(),r=Ja(a.toLowerCase()),o=e.footnoteOrder.indexOf(a);let l,c=e.footnoteCounts.get(a);c===void 0?(c=0,e.footnoteOrder.push(a),l=e.footnoteOrder.length):l=o+1,c+=1,e.footnoteCounts.set(a,c);const d={type:"element",tagName:"a",properties:{href:"#"+s+"fn-"+r,id:s+"fnref-"+r+(c>1?"-"+c:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(l)}]};e.patch(n,d);const u={type:"element",tagName:"sup",properties:{},children:[d]};return e.patch(n,u),e.applyData(n,u)}function X2(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 Z2(e,n){if(e.options.allowDangerousHtml){const s={type:"raw",value:n.value};return e.patch(n,s),e.applyData(n,s)}}function dg(e,n){const s=n.referenceType;let a="]";if(s==="collapsed"?a+="[]":s==="full"&&(a+="["+(n.label||n.identifier)+"]"),n.type==="imageReference")return[{type:"text",value:"!["+n.alt+a}];const r=e.all(n),o=r[0];o&&o.type==="text"?o.value="["+o.value:r.unshift({type:"text",value:"["});const l=r[r.length-1];return l&&l.type==="text"?l.value+=a:r.push({type:"text",value:a}),r}function eE(e,n){const s=String(n.identifier).toUpperCase(),a=e.definitionById.get(s);if(!a)return dg(e,n);const r={src:Ja(a.url||""),alt:n.alt};a.title!==null&&a.title!==void 0&&(r.title=a.title);const o={type:"element",tagName:"img",properties:r,children:[]};return e.patch(n,o),e.applyData(n,o)}function tE(e,n){const s={src:Ja(n.url)};n.alt!==null&&n.alt!==void 0&&(s.alt=n.alt),n.title!==null&&n.title!==void 0&&(s.title=n.title);const a={type:"element",tagName:"img",properties:s,children:[]};return e.patch(n,a),e.applyData(n,a)}function nE(e,n){const s={type:"text",value:n.value.replace(/\r?\n|\r/g," ")};e.patch(n,s);const a={type:"element",tagName:"code",properties:{},children:[s]};return e.patch(n,a),e.applyData(n,a)}function sE(e,n){const s=String(n.identifier).toUpperCase(),a=e.definitionById.get(s);if(!a)return dg(e,n);const r={href:Ja(a.url||"")};a.title!==null&&a.title!==void 0&&(r.title=a.title);const o={type:"element",tagName:"a",properties:r,children:e.all(n)};return e.patch(n,o),e.applyData(n,o)}function iE(e,n){const s={href:Ja(n.url)};n.title!==null&&n.title!==void 0&&(s.title=n.title);const a={type:"element",tagName:"a",properties:s,children:e.all(n)};return e.patch(n,a),e.applyData(n,a)}function aE(e,n,s){const a=e.all(n),r=s?rE(s):ug(n),o={},l=[];if(typeof n.checked=="boolean"){const m=a[0];let h;m&&m.type==="element"&&m.tagName==="p"?h=m:(h={type:"element",tagName:"p",properties:{},children:[]},a.unshift(h)),h.children.length>0&&h.children.unshift({type:"text",value:" "}),h.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:n.checked,disabled:!0},children:[]}),o.className=["task-list-item"]}let c=-1;for(;++c<a.length;){const m=a[c];(r||c!==0||m.type!=="element"||m.tagName!=="p")&&l.push({type:"text",value:`
649
+ `}),m.type==="element"&&m.tagName==="p"&&!r?l.push(...m.children):l.push(m)}const d=a[a.length-1];d&&(r||d.type!=="element"||d.tagName!=="p")&&l.push({type:"text",value:`
650
+ `});const u={type:"element",tagName:"li",properties:o,children:l};return e.patch(n,u),e.applyData(n,u)}function rE(e){let n=!1;if(e.type==="list"){n=e.spread||!1;const s=e.children;let a=-1;for(;!n&&++a<s.length;)n=ug(s[a])}return n}function ug(e){const n=e.spread;return n??e.children.length>1}function oE(e,n){const s={},a=e.all(n);let r=-1;for(typeof n.start=="number"&&n.start!==1&&(s.start=n.start);++r<a.length;){const l=a[r];if(l.type==="element"&&l.tagName==="li"&&l.properties&&Array.isArray(l.properties.className)&&l.properties.className.includes("task-list-item")){s.className=["contains-task-list"];break}}const o={type:"element",tagName:n.ordered?"ol":"ul",properties:s,children:e.wrap(a,!0)};return e.patch(n,o),e.applyData(n,o)}function lE(e,n){const s={type:"element",tagName:"p",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function cE(e,n){const s={type:"root",children:e.wrap(e.all(n))};return e.patch(n,s),e.applyData(n,s)}function dE(e,n){const s={type:"element",tagName:"strong",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function uE(e,n){const s=e.all(n),a=s.shift(),r=[];if(a){const l={type:"element",tagName:"thead",properties:{},children:e.wrap([a],!0)};e.patch(n.children[0],l),r.push(l)}if(s.length>0){const l={type:"element",tagName:"tbody",properties:{},children:e.wrap(s,!0)},c=Zd(n.children[1]),d=qf(n.children[n.children.length-1]);c&&d&&(l.position={start:c,end:d}),r.push(l)}const o={type:"element",tagName:"table",properties:{},children:e.wrap(r,!0)};return e.patch(n,o),e.applyData(n,o)}function mE(e,n,s){const a=s?s.children:void 0,o=(a?a.indexOf(n):1)===0?"th":"td",l=s&&s.type==="table"?s.align:void 0,c=l?l.length:n.children.length;let d=-1;const u=[];for(;++d<c;){const h=n.children[d],f={},p=l?l[d]:void 0;p&&(f.align=p);let g={type:"element",tagName:o,properties:f,children:[]};h&&(g.children=e.all(h),e.patch(h,g),g=e.applyData(h,g)),u.push(g)}const m={type:"element",tagName:"tr",properties:{},children:e.wrap(u,!0)};return e.patch(n,m),e.applyData(n,m)}function hE(e,n){const s={type:"element",tagName:"td",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}const Wm=9,Km=32;function pE(e){const n=String(e),s=/\r?\n|\r/g;let a=s.exec(n),r=0;const o=[];for(;a;)o.push(Gm(n.slice(r,a.index),r>0,!0),a[0]),r=a.index+a[0].length,a=s.exec(n);return o.push(Gm(n.slice(r),r>0,!1)),o.join("")}function Gm(e,n,s){let a=0,r=e.length;if(n){let o=e.codePointAt(a);for(;o===Wm||o===Km;)a++,o=e.codePointAt(a)}if(s){let o=e.codePointAt(r-1);for(;o===Wm||o===Km;)r--,o=e.codePointAt(r-1)}return r>a?e.slice(a,r):""}function fE(e,n){const s={type:"text",value:pE(String(n.value))};return e.patch(n,s),e.applyData(n,s)}function gE(e,n){const s={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(n,s),e.applyData(n,s)}const bE={blockquote:W2,break:K2,code:G2,delete:J2,emphasis:Y2,footnoteReference:Q2,heading:X2,html:Z2,imageReference:eE,image:tE,inlineCode:nE,linkReference:sE,link:iE,listItem:aE,list:oE,paragraph:lE,root:cE,strong:dE,table:uE,tableCell:hE,tableRow:mE,text:fE,thematicBreak:gE,toml:wo,yaml:wo,definition:wo,footnoteDefinition:wo};function wo(){}const mg=-1,Tl=0,Pr=1,ll=2,ru=3,ou=4,lu=5,cu=6,hg=7,pg=8,Jm=typeof self=="object"?self:globalThis,xE=(e,n)=>{const s=(r,o)=>(e.set(o,r),r),a=r=>{if(e.has(r))return e.get(r);const[o,l]=n[r];switch(o){case Tl:case mg:return s(l,r);case Pr:{const c=s([],r);for(const d of l)c.push(a(d));return c}case ll:{const c=s({},r);for(const[d,u]of l)c[a(d)]=a(u);return c}case ru:return s(new Date(l),r);case ou:{const{source:c,flags:d}=l;return s(new RegExp(c,d),r)}case lu:{const c=s(new Map,r);for(const[d,u]of l)c.set(a(d),a(u));return c}case cu:{const c=s(new Set,r);for(const d of l)c.add(a(d));return c}case hg:{const{name:c,message:d}=l;return s(new Jm[c](d),r)}case pg: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 Jm[o](l),r)};return a},Ym=e=>xE(new Map,e)(0),wa="",{toString:vE}={},{keys:yE}=Object,lr=e=>{const n=typeof e;if(n!=="object"||!e)return[Tl,n];const s=vE.call(e).slice(8,-1);switch(s){case"Array":return[Pr,wa];case"Object":return[ll,wa];case"Date":return[ru,wa];case"RegExp":return[ou,wa];case"Map":return[lu,wa];case"Set":return[cu,wa];case"DataView":return[Pr,s]}return s.includes("Array")?[Pr,s]:s.includes("Error")?[hg,s]:[ll,s]},ko=([e,n])=>e===Tl&&(n==="function"||n==="symbol"),wE=(e,n,s,a)=>{const r=(l,c)=>{const d=a.push(l)-1;return s.set(c,d),d},o=l=>{if(s.has(l))return s.get(l);let[c,d]=lr(l);switch(c){case Tl:{let m=l;switch(d){case"bigint":c=pg,m=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+d);m=null;break;case"undefined":return r([mg],l)}return r([c,m],l)}case Pr:{if(d){let f=l;return d==="DataView"?f=new Uint8Array(l.buffer):d==="ArrayBuffer"&&(f=new Uint8Array(l)),r([d,[...f]],l)}const m=[],h=r([c,m],l);for(const f of l)m.push(o(f));return h}case ll:{if(d)switch(d){case"BigInt":return r([d,l.toString()],l);case"Boolean":case"Number":case"String":return r([d,l.valueOf()],l)}if(n&&"toJSON"in l)return o(l.toJSON());const m=[],h=r([c,m],l);for(const f of yE(l))(e||!ko(lr(l[f])))&&m.push([o(f),o(l[f])]);return h}case ru:return r([c,l.toISOString()],l);case ou:{const{source:m,flags:h}=l;return r([c,{source:m,flags:h}],l)}case lu:{const m=[],h=r([c,m],l);for(const[f,p]of l)(e||!(ko(lr(f))||ko(lr(p))))&&m.push([o(f),o(p)]);return h}case cu:{const m=[],h=r([c,m],l);for(const f of l)(e||!ko(lr(f)))&&m.push(o(f));return h}}const{message:u}=l;return r([c,{name:d,message:u}],l)};return o},Qm=(e,{json:n,lossy:s}={})=>{const a=[];return wE(!(n||s),!!n,new Map,a)(e),a},cl=typeof structuredClone=="function"?(e,n)=>n&&("json"in n||"lossy"in n)?Ym(Qm(e,n)):structuredClone(e):(e,n)=>Ym(Qm(e,n));function kE(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 jE(e,n){return"Back to reference "+(e+1)+(n>1?"-"+n:"")}function NE(e){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=e.options.footnoteBackContent||kE,a=e.options.footnoteBackLabel||jE,r=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",l=e.options.footnoteLabelProperties||{className:["sr-only"]},c=[];let d=-1;for(;++d<e.footnoteOrder.length;){const u=e.footnoteById.get(e.footnoteOrder[d]);if(!u)continue;const m=e.all(u),h=String(u.identifier).toUpperCase(),f=Ja(h.toLowerCase());let p=0;const g=[],x=e.footnoteCounts.get(h);for(;x!==void 0&&++p<=x;){g.length>0&&g.push({type:"text",value:" "});let y=typeof s=="string"?s:s(d,p);typeof y=="string"&&(y={type:"text",value:y}),g.push({type:"element",tagName:"a",properties:{href:"#"+n+"fnref-"+f+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof a=="string"?a:a(d,p),className:["data-footnote-backref"]},children:Array.isArray(y)?y:[y]})}const v=m[m.length-1];if(v&&v.type==="element"&&v.tagName==="p"){const y=v.children[v.children.length-1];y&&y.type==="text"?y.value+=" ":v.children.push({type:"text",value:" "}),v.children.push(...g)}else m.push(...g);const b={type:"element",tagName:"li",properties:{id:n+"fn-"+f},children:e.wrap(m,!0)};e.patch(u,b),c.push(b)}if(c.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...cl(l),id:"footnote-label"},children:[{type:"text",value:r}]},{type:"text",value:`
651
+ `},{type:"element",tagName:"ol",properties:{},children:e.wrap(c,!0)},{type:"text",value:`
652
+ `}]}}const Il=(function(e){if(e==null)return ME;if(typeof e=="function")return $l(e);if(typeof e=="object")return Array.isArray(e)?SE(e):CE(e);if(typeof e=="string")return EE(e);throw new Error("Expected function, string, or object as test")});function SE(e){const n=[];let s=-1;for(;++s<e.length;)n[s]=Il(e[s]);return $l(a);function a(...r){let o=-1;for(;++o<n.length;)if(n[o].apply(this,r))return!0;return!1}}function CE(e){const n=e;return $l(s);function s(a){const r=a;let o;for(o in e)if(r[o]!==n[o])return!1;return!0}}function EE(e){return $l(n);function n(s){return s&&s.type===e}}function $l(e){return n;function n(s,a,r){return!!(_E(s)&&e.call(this,s,typeof a=="number"?a:void 0,r||void 0))}}function ME(){return!0}function _E(e){return e!==null&&typeof e=="object"&&"type"in e}const fg=[],AE=!0,Sd=!1,PE="skip";function gg(e,n,s,a){let r;typeof n=="function"&&typeof s!="function"?(a=s,s=n):r=n;const o=Il(r),l=a?-1:1;c(e,void 0,[])();function c(d,u,m){const h=d&&typeof d=="object"?d:{};if(typeof h.type=="string"){const p=typeof h.tagName=="string"?h.tagName:typeof h.name=="string"?h.name:void 0;Object.defineProperty(f,"name",{value:"node ("+(d.type+(p?"<"+p+">":""))+")"})}return f;function f(){let p=fg,g,x,v;if((!n||o(d,u,m[m.length-1]||void 0))&&(p=RE(s(d,m)),p[0]===Sd))return p;if("children"in d&&d.children){const b=d;if(b.children&&p[0]!==PE)for(x=(a?b.children.length:-1)+l,v=m.concat(b);x>-1&&x<b.children.length;){const y=b.children[x];if(g=c(y,x,v)(),g[0]===Sd)return g;x=typeof g[1]=="number"?g[1]:x+l}}return p}}}function RE(e){return Array.isArray(e)?e:typeof e=="number"?[AE,e]:e==null?fg:[e]}function du(e,n,s,a){let r,o,l;typeof n=="function"&&typeof s!="function"?(o=void 0,l=n,r=s):(o=n,l=s,r=a),gg(e,o,c,r);function c(d,u){const m=u[u.length-1],h=m?m.children.indexOf(d):void 0;return l(d,h,m)}}const Cd={}.hasOwnProperty,TE={};function IE(e,n){const s=n||TE,a=new Map,r=new Map,o=new Map,l={...bE,...s.handlers},c={all:u,applyData:DE,definitionById:a,footnoteById:r,footnoteCounts:o,footnoteOrder:[],handlers:l,one:d,options:s,patch:$E,wrap:OE};return du(e,function(m){if(m.type==="definition"||m.type==="footnoteDefinition"){const h=m.type==="definition"?a:r,f=String(m.identifier).toUpperCase();h.has(f)||h.set(f,m)}}),c;function d(m,h){const f=m.type,p=c.handlers[f];if(Cd.call(c.handlers,f)&&p)return p(c,m,h);if(c.options.passThrough&&c.options.passThrough.includes(f)){if("children"in m){const{children:x,...v}=m,b=cl(v);return b.children=c.all(m),b}return cl(m)}return(c.options.unknownHandler||LE)(c,m,h)}function u(m){const h=[];if("children"in m){const f=m.children;let p=-1;for(;++p<f.length;){const g=c.one(f[p],m);if(g){if(p&&f[p-1].type==="break"&&(!Array.isArray(g)&&g.type==="text"&&(g.value=Xm(g.value)),!Array.isArray(g)&&g.type==="element")){const x=g.children[0];x&&x.type==="text"&&(x.value=Xm(x.value))}Array.isArray(g)?h.push(...g):h.push(g)}}}return h}}function $E(e,n){e.position&&(n.position=j0(e))}function DE(e,n){let s=n;if(e&&e.data){const a=e.data.hName,r=e.data.hChildren,o=e.data.hProperties;if(typeof a=="string")if(s.type==="element")s.tagName=a;else{const l="children"in s?s.children:[s];s={type:"element",tagName:a,properties:{},children:l}}s.type==="element"&&o&&Object.assign(s.properties,cl(o)),"children"in s&&s.children&&r!==null&&r!==void 0&&(s.children=r)}return s}function LE(e,n){const s=n.data||{},a="value"in n&&!(Cd.call(s,"hProperties")||Cd.call(s,"hChildren"))?{type:"text",value:n.value}:{type:"element",tagName:"div",properties:{},children:e.all(n)};return e.patch(n,a),e.applyData(n,a)}function OE(e,n){const s=[];let a=-1;for(n&&s.push({type:"text",value:`
653
+ `});++a<e.length;)a&&s.push({type:"text",value:`
654
+ `}),s.push(e[a]);return n&&e.length>0&&s.push({type:"text",value:`
655
+ `}),s}function Xm(e){let n=0,s=e.charCodeAt(n);for(;s===9||s===32;)n++,s=e.charCodeAt(n);return e.slice(n)}function Zm(e,n){const s=IE(e,n),a=s.one(e,void 0),r=NE(s),o=Array.isArray(a)?{type:"root",children:a}:a||{type:"root",children:[]};return r&&o.children.push({type:"text",value:`
656
+ `},r),o}function zE(e,n){return e&&"run"in e?async function(s,a){const r=Zm(s,{file:a,...n});await e.run(r,a)}:function(s,a){return Zm(s,{file:a,...e||n})}}function eh(e){if(e)throw e}var mc,th;function FE(){if(th)return mc;th=1;var e=Object.prototype.hasOwnProperty,n=Object.prototype.toString,s=Object.defineProperty,a=Object.getOwnPropertyDescriptor,r=function(u){return typeof Array.isArray=="function"?Array.isArray(u):n.call(u)==="[object Array]"},o=function(u){if(!u||n.call(u)!=="[object Object]")return!1;var m=e.call(u,"constructor"),h=u.constructor&&u.constructor.prototype&&e.call(u.constructor.prototype,"isPrototypeOf");if(u.constructor&&!m&&!h)return!1;var f;for(f in u);return typeof f>"u"||e.call(u,f)},l=function(u,m){s&&m.name==="__proto__"?s(u,m.name,{enumerable:!0,configurable:!0,value:m.newValue,writable:!0}):u[m.name]=m.newValue},c=function(u,m){if(m==="__proto__")if(e.call(u,m)){if(a)return a(u,m).value}else return;return u[m]};return mc=function d(){var u,m,h,f,p,g,x=arguments[0],v=1,b=arguments.length,y=!1;for(typeof x=="boolean"&&(y=x,x=arguments[1]||{},v=2),(x==null||typeof x!="object"&&typeof x!="function")&&(x={});v<b;++v)if(u=arguments[v],u!=null)for(m in u)h=c(x,m),f=c(u,m),x!==f&&(y&&f&&(o(f)||(p=r(f)))?(p?(p=!1,g=h&&r(h)?h:[]):g=h&&o(h)?h:{},l(x,{name:m,newValue:d(y,g,f)})):typeof f<"u"&&l(x,{name:m,newValue:f}));return x},mc}var UE=FE();const hc=Wp(UE);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 BE(){const e=[],n={run:s,use:a};return n;function s(...r){let o=-1;const l=r.pop();if(typeof l!="function")throw new TypeError("Expected function as last argument, not "+l);c(null,...r);function c(d,...u){const m=e[++o];let h=-1;if(d){l(d);return}for(;++h<r.length;)(u[h]===null||u[h]===void 0)&&(u[h]=r[h]);r=u,m?HE(m,c)(...u):l(null,...u)}}function a(r){if(typeof r!="function")throw new TypeError("Expected `middelware` to be a function, not "+r);return e.push(r),n}}function HE(e,n){let s;return a;function a(...l){const c=e.length>l.length;let d;c&&l.push(r);try{d=e.apply(this,l)}catch(u){const m=u;if(c&&s)throw m;return r(m)}c||(d&&d.then&&typeof d.then=="function"?d.then(o,r):d instanceof Error?r(d):o(d))}function r(l,...c){s||(s=!0,n(l,...c))}function o(l){r(null,l)}}const gi={basename:qE,dirname:VE,extname:WE,join:KE,sep:"/"};function qE(e,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');no(e);let s=0,a=-1,r=e.length,o;if(n===void 0||n.length===0||n.length>e.length){for(;r--;)if(e.codePointAt(r)===47){if(o){s=r+1;break}}else a<0&&(o=!0,a=r+1);return a<0?"":e.slice(s,a)}if(n===e)return"";let l=-1,c=n.length-1;for(;r--;)if(e.codePointAt(r)===47){if(o){s=r+1;break}}else l<0&&(o=!0,l=r+1),c>-1&&(e.codePointAt(r)===n.codePointAt(c--)?c<0&&(a=r):(c=-1,a=l));return s===a?a=l:a<0&&(a=e.length),e.slice(s,a)}function VE(e){if(no(e),e.length===0)return".";let n=-1,s=e.length,a;for(;--s;)if(e.codePointAt(s)===47){if(a){n=s;break}}else a||(a=!0);return n<0?e.codePointAt(0)===47?"/":".":n===1&&e.codePointAt(0)===47?"//":e.slice(0,n)}function WE(e){no(e);let n=e.length,s=-1,a=0,r=-1,o=0,l;for(;n--;){const c=e.codePointAt(n);if(c===47){if(l){a=n+1;break}continue}s<0&&(l=!0,s=n+1),c===46?r<0?r=n:o!==1&&(o=1):r>-1&&(o=-1)}return r<0||s<0||o===0||o===1&&r===s-1&&r===a+1?"":e.slice(r,s)}function KE(...e){let n=-1,s;for(;++n<e.length;)no(e[n]),e[n]&&(s=s===void 0?e[n]:s+"/"+e[n]);return s===void 0?".":GE(s)}function GE(e){no(e);const n=e.codePointAt(0)===47;let s=JE(e,!n);return s.length===0&&!n&&(s="."),s.length>0&&e.codePointAt(e.length-1)===47&&(s+="/"),n?"/"+s:s}function JE(e,n){let s="",a=0,r=-1,o=0,l=-1,c,d;for(;++l<=e.length;){if(l<e.length)c=e.codePointAt(l);else{if(c===47)break;c=47}if(c===47){if(!(r===l-1||o===1))if(r!==l-1&&o===2){if(s.length<2||a!==2||s.codePointAt(s.length-1)!==46||s.codePointAt(s.length-2)!==46){if(s.length>2){if(d=s.lastIndexOf("/"),d!==s.length-1){d<0?(s="",a=0):(s=s.slice(0,d),a=s.length-1-s.lastIndexOf("/")),r=l,o=0;continue}}else if(s.length>0){s="",a=0,r=l,o=0;continue}}n&&(s=s.length>0?s+"/..":"..",a=2)}else s.length>0?s+="/"+e.slice(r+1,l):s=e.slice(r+1,l),a=l-r-1;r=l,o=0}else c===46&&o>-1?o++:o=-1}return s}function no(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const YE={cwd:QE};function QE(){return"/"}function Md(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function XE(e){if(typeof e=="string")e=new URL(e);else if(!Md(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 ZE(e)}function ZE(e){if(e.hostname!==""){const a=new TypeError('File URL host must be "localhost" or empty on darwin');throw a.code="ERR_INVALID_FILE_URL_HOST",a}const n=e.pathname;let s=-1;for(;++s<n.length;)if(n.codePointAt(s)===37&&n.codePointAt(s+1)===50){const a=n.codePointAt(s+2);if(a===70||a===102){const r=new TypeError("File URL path must not include encoded / characters");throw r.code="ERR_INVALID_FILE_URL_PATH",r}}return decodeURIComponent(n)}const pc=["history","path","basename","stem","extname","dirname"];class bg{constructor(n){let s;n?Md(n)?s={path:n}:typeof n=="string"||eM(n)?s={value:n}:s=n:s={},this.cwd="cwd"in s?"":YE.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let a=-1;for(;++a<pc.length;){const o=pc[a];o in s&&s[o]!==void 0&&s[o]!==null&&(this[o]=o==="history"?[...s[o]]:s[o])}let r;for(r in s)pc.includes(r)||(this[r]=s[r])}get basename(){return typeof this.path=="string"?gi.basename(this.path):void 0}set basename(n){gc(n,"basename"),fc(n,"basename"),this.path=gi.join(this.dirname||"",n)}get dirname(){return typeof this.path=="string"?gi.dirname(this.path):void 0}set dirname(n){nh(this.basename,"dirname"),this.path=gi.join(n||"",this.basename)}get extname(){return typeof this.path=="string"?gi.extname(this.path):void 0}set extname(n){if(fc(n,"extname"),nh(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=gi.join(this.dirname,this.stem+(n||""))}get path(){return this.history[this.history.length-1]}set path(n){Md(n)&&(n=XE(n)),gc(n,"path"),this.path!==n&&this.history.push(n)}get stem(){return typeof this.path=="string"?gi.basename(this.path,this.extname):void 0}set stem(n){gc(n,"stem"),fc(n,"stem"),this.path=gi.join(this.dirname||"",n+(this.extname||""))}fail(n,s,a){const r=this.message(n,s,a);throw r.fatal=!0,r}info(n,s,a){const r=this.message(n,s,a);return r.fatal=void 0,r}message(n,s,a){const r=new Ns(n,s,a);return this.path&&(r.name=this.path+":"+r.name,r.file=this.path),r.fatal=!1,this.messages.push(r),r}toString(n){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(n||void 0).decode(this.value)}}function fc(e,n){if(e&&e.includes(gi.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+gi.sep+"`")}function gc(e,n){if(!e)throw new Error("`"+n+"` cannot be empty")}function nh(e,n){if(!e)throw new Error("Setting `"+n+"` requires `path` to be set too")}function eM(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const tM=(function(e){const a=this.constructor.prototype,r=a[e],o=function(){return r.apply(o,arguments)};return Object.setPrototypeOf(o,a),o}),nM={}.hasOwnProperty;class uu extends tM{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=BE()}copy(){const n=new uu;let s=-1;for(;++s<this.attachers.length;){const a=this.attachers[s];n.use(...a)}return n.data(hc(!0,{},this.namespace)),n}data(n,s){return typeof n=="string"?arguments.length===2?(vc("data",this.frozen),this.namespace[n]=s,this):nM.call(this.namespace,n)&&this.namespace[n]||void 0:n?(vc("data",this.frozen),this.namespace=n,this):this.namespace}freeze(){if(this.frozen)return this;const n=this;for(;++this.freezeIndex<this.attachers.length;){const[s,...a]=this.attachers[this.freezeIndex];if(a[0]===!1)continue;a[0]===!0&&(a[0]=void 0);const r=s.call(n,...a);typeof r=="function"&&this.transformers.use(r)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(n){this.freeze();const s=jo(n),a=this.parser||this.Parser;return bc("parse",a),a(String(s),s)}process(n,s){const a=this;return this.freeze(),bc("process",this.parser||this.Parser),xc("process",this.compiler||this.Compiler),s?r(void 0,s):new Promise(r);function r(o,l){const c=jo(n),d=a.parse(c);a.run(d,c,function(m,h,f){if(m||!h||!f)return u(m);const p=h,g=a.stringify(p,f);aM(g)?f.value=g:f.result=g,u(m,f)});function u(m,h){m||!h?l(m):o?o(h):s(void 0,h)}}}processSync(n){let s=!1,a;return this.freeze(),bc("processSync",this.parser||this.Parser),xc("processSync",this.compiler||this.Compiler),this.process(n,r),ih("processSync","process",s),a;function r(o,l){s=!0,eh(o),a=l}}run(n,s,a){sh(n),this.freeze();const r=this.transformers;return!a&&typeof s=="function"&&(a=s,s=void 0),a?o(void 0,a):new Promise(o);function o(l,c){const d=jo(s);r.run(n,d,u);function u(m,h,f){const p=h||n;m?c(m):l?l(p):a(void 0,p,f)}}}runSync(n,s){let a=!1,r;return this.run(n,s,o),ih("runSync","run",a),r;function o(l,c){eh(l),r=c,a=!0}}stringify(n,s){this.freeze();const a=jo(s),r=this.compiler||this.Compiler;return xc("stringify",r),sh(n),r(n,a)}use(n,...s){const a=this.attachers,r=this.namespace;if(vc("use",this.frozen),n!=null)if(typeof n=="function")d(n,s);else if(typeof n=="object")Array.isArray(n)?c(n):l(n);else throw new TypeError("Expected usable value, not `"+n+"`");return this;function o(u){if(typeof u=="function")d(u,[]);else if(typeof u=="object")if(Array.isArray(u)){const[m,...h]=u;d(m,h)}else l(u);else throw new TypeError("Expected usable value, not `"+u+"`")}function l(u){if(!("plugins"in u)&&!("settings"in u))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");c(u.plugins),u.settings&&(r.settings=hc(!0,r.settings,u.settings))}function c(u){let m=-1;if(u!=null)if(Array.isArray(u))for(;++m<u.length;){const h=u[m];o(h)}else throw new TypeError("Expected a list of plugins, not `"+u+"`")}function d(u,m){let h=-1,f=-1;for(;++h<a.length;)if(a[h][0]===u){f=h;break}if(f===-1)a.push([u,...m]);else if(m.length>0){let[p,...g]=m;const x=a[f][1];Ed(x)&&Ed(p)&&(p=hc(!0,x,p)),a[f]=[u,p,...g]}}}}const sM=new uu().freeze();function bc(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function xc(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function vc(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 sh(e){if(!Ed(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function ih(e,n,s){if(!s)throw new Error("`"+e+"` finished async. Use `"+n+"` instead")}function jo(e){return iM(e)?e:new bg(e)}function iM(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function aM(e){return typeof e=="string"||rM(e)}function rM(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const oM="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",ah=[],rh={allowDangerousHtml:!0},lM=/^(https?|ircs?|mailto|xmpp)$/i,cM=[{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 vi(e){const n=dM(e),s=uM(e);return mM(n.runSync(n.parse(s),s),e)}function dM(e){const n=e.rehypePlugins||ah,s=e.remarkPlugins||ah,a=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...rh}:rh;return sM().use(V2).use(s).use(zE,a).use(n)}function uM(e){const n=e.children||"",s=new bg;return typeof n=="string"&&(s.value=n),s}function mM(e,n){const s=n.allowedElements,a=n.allowElement,r=n.components,o=n.disallowedElements,l=n.skipHtml,c=n.unwrapDisallowed,d=n.urlTransform||hM;for(const m of cM)Object.hasOwn(n,m.from)&&(""+m.from+(m.to?"use `"+m.to+"` instead":"remove it")+oM+m.id,void 0);return du(e,u),M0(e,{Fragment:t.Fragment,components:r,ignoreInvalidStyle:!0,jsx:t.jsx,jsxs:t.jsxs,passKeys:!0,passNode:!0});function u(m,h,f){if(m.type==="raw"&&f&&typeof h=="number")return l?f.children.splice(h,1):f.children[h]={type:"text",value:m.value},h;if(m.type==="element"){let p;for(p in cc)if(Object.hasOwn(cc,p)&&Object.hasOwn(m.properties,p)){const g=m.properties[p],x=cc[p];(x===null||x.includes(m.tagName))&&(m.properties[p]=d(String(g||""),p,m))}}if(m.type==="element"){let p=s?!s.includes(m.tagName):o?o.includes(m.tagName):!1;if(!p&&a&&typeof h=="number"&&(p=!a(m,h,f)),p&&f&&typeof h=="number")return c&&m.children?f.children.splice(h,1,...m.children):f.children.splice(h,1),h}}}function hM(e){const n=e.indexOf(":"),s=e.indexOf("?"),a=e.indexOf("#"),r=e.indexOf("/");return n===-1||r!==-1&&n>r||s!==-1&&n>s||a!==-1&&n>a||lM.test(e.slice(0,n))?e:""}function oh(e,n){const s=String(e);if(typeof n!="string")throw new TypeError("Expected character");let a=0,r=s.indexOf(n);for(;r!==-1;)a++,r=s.indexOf(n,r+n.length);return a}function pM(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function fM(e,n,s){const r=Il((s||{}).ignore||[]),o=gM(n);let l=-1;for(;++l<o.length;)gg(e,"text",c);function c(u,m){let h=-1,f;for(;++h<m.length;){const p=m[h],g=f?f.children:void 0;if(r(p,g?g.indexOf(p):void 0,f))return;f=p}if(f)return d(u,m)}function d(u,m){const h=m[m.length-1],f=o[l][0],p=o[l][1];let g=0;const v=h.children.indexOf(u);let b=!1,y=[];f.lastIndex=0;let j=f.exec(u.value);for(;j;){const C=j.index,A={index:j.index,input:j.input,stack:[...m,u]};let N=p(...j,A);if(typeof N=="string"&&(N=N.length>0?{type:"text",value:N}:void 0),N===!1?f.lastIndex=C+1:(g!==C&&y.push({type:"text",value:u.value.slice(g,C)}),Array.isArray(N)?y.push(...N):N&&y.push(N),g=C+j[0].length,b=!0),!f.global)break;j=f.exec(u.value)}return b?(g<u.value.length&&y.push({type:"text",value:u.value.slice(g)}),h.children.splice(v,1,...y)):y=[u],v+y.length}}function gM(e){const n=[];if(!Array.isArray(e))throw new TypeError("Expected find and replace tuple or list of tuples");const s=!e[0]||Array.isArray(e[0])?e:[e];let a=-1;for(;++a<s.length;){const r=s[a];n.push([bM(r[0]),xM(r[1])])}return n}function bM(e){return typeof e=="string"?new RegExp(pM(e),"g"):e}function xM(e){return typeof e=="function"?e:function(){return e}}const yc="phrasing",wc=["autolink","link","image","label"];function vM(){return{transforms:[CM],enter:{literalAutolink:wM,literalAutolinkEmail:kc,literalAutolinkHttp:kc,literalAutolinkWww:kc},exit:{literalAutolink:SM,literalAutolinkEmail:NM,literalAutolinkHttp:kM,literalAutolinkWww:jM}}}function yM(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:yc,notInConstruct:wc},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:yc,notInConstruct:wc},{character:":",before:"[ps]",after:"\\/",inConstruct:yc,notInConstruct:wc}]}}function wM(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function kc(e){this.config.enter.autolinkProtocol.call(this,e)}function kM(e){this.config.exit.autolinkProtocol.call(this,e)}function jM(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 NM(e){this.config.exit.autolinkEmail.call(this,e)}function SM(e){this.exit(e)}function CM(e){fM(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,EM],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,MM]],{ignore:["link","linkReference"]})}function EM(e,n,s,a,r){let o="";if(!xg(r)||(/^w/i.test(n)&&(s=n+s,n="",o="http://"),!_M(s)))return!1;const l=AM(s+a);if(!l[0])return!1;const c={type:"link",title:null,url:o+n+l[0],children:[{type:"text",value:n+l[0]}]};return l[1]?[c,{type:"text",value:l[1]}]:c}function MM(e,n,s,a){return!xg(a,!0)||/[-\d_]$/.test(s)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+s,children:[{type:"text",value:n+"@"+s}]}}function _M(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 AM(e){const n=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!n)return[e,void 0];e=e.slice(0,n.index);let s=n[0],a=s.indexOf(")");const r=oh(e,"(");let o=oh(e,")");for(;a!==-1&&r>o;)e+=s.slice(0,a+1),s=s.slice(a+1),a=s.indexOf(")"),o++;return[e,s]}function xg(e,n){const s=e.input.charCodeAt(e.index-1);return(e.index===0||ra(s)||Pl(s))&&(!n||s!==47)}vg.peek=zM;function PM(){this.buffer()}function RM(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function TM(){this.buffer()}function IM(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function $M(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=ai(this.sliceSerialize(e)).toLowerCase(),s.label=n}function DM(e){this.exit(e)}function LM(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=ai(this.sliceSerialize(e)).toLowerCase(),s.label=n}function OM(e){this.exit(e)}function zM(){return"["}function vg(e,n,s,a){const r=s.createTracker(a);let o=r.move("[^");const l=s.enter("footnoteReference"),c=s.enter("reference");return o+=r.move(s.safe(s.associationId(e),{after:"]",before:o})),c(),l(),o+=r.move("]"),o}function FM(){return{enter:{gfmFootnoteCallString:PM,gfmFootnoteCall:RM,gfmFootnoteDefinitionLabelString:TM,gfmFootnoteDefinition:IM},exit:{gfmFootnoteCallString:$M,gfmFootnoteCall:DM,gfmFootnoteDefinitionLabelString:LM,gfmFootnoteDefinition:OM}}}function UM(e){let n=!1;return e&&e.firstLineBlank&&(n=!0),{handlers:{footnoteDefinition:s,footnoteReference:vg},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function s(a,r,o,l){const c=o.createTracker(l);let d=c.move("[^");const u=o.enter("footnoteDefinition"),m=o.enter("label");return d+=c.move(o.safe(o.associationId(a),{before:d,after:"]"})),m(),d+=c.move("]:"),a.children&&a.children.length>0&&(c.shift(4),d+=c.move((n?`
657
+ `:" ")+o.indentLines(o.containerFlow(a,c.current()),n?yg:BM))),u(),d}}function BM(e,n,s){return n===0?e:yg(e,n,s)}function yg(e,n,s){return(s?"":" ")+e}const HM=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];wg.peek=GM;function qM(){return{canContainEols:["delete"],enter:{strikethrough:WM},exit:{strikethrough:KM}}}function VM(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:HM}],handlers:{delete:wg}}}function WM(e){this.enter({type:"delete",children:[]},e)}function KM(e){this.exit(e)}function wg(e,n,s,a){const r=s.createTracker(a),o=s.enter("strikethrough");let l=r.move("~~");return l+=s.containerPhrasing(e,{...r.current(),before:l,after:"~"}),l+=r.move("~~"),o(),l}function GM(){return"~"}function JM(e){return e.length}function YM(e,n){const s=n||{},a=(s.align||[]).concat(),r=s.stringLength||JM,o=[],l=[],c=[],d=[];let u=0,m=-1;for(;++m<e.length;){const x=[],v=[];let b=-1;for(e[m].length>u&&(u=e[m].length);++b<e[m].length;){const y=QM(e[m][b]);if(s.alignDelimiters!==!1){const j=r(y);v[b]=j,(d[b]===void 0||j>d[b])&&(d[b]=j)}x.push(y)}l[m]=x,c[m]=v}let h=-1;if(typeof a=="object"&&"length"in a)for(;++h<u;)o[h]=lh(a[h]);else{const x=lh(a);for(;++h<u;)o[h]=x}h=-1;const f=[],p=[];for(;++h<u;){const x=o[h];let v="",b="";x===99?(v=":",b=":"):x===108?v=":":x===114&&(b=":");let y=s.alignDelimiters===!1?1:Math.max(1,d[h]-v.length-b.length);const j=v+"-".repeat(y)+b;s.alignDelimiters!==!1&&(y=v.length+y+b.length,y>d[h]&&(d[h]=y),p[h]=y),f[h]=j}l.splice(1,0,f),c.splice(1,0,p),m=-1;const g=[];for(;++m<l.length;){const x=l[m],v=c[m];h=-1;const b=[];for(;++h<u;){const y=x[h]||"";let j="",C="";if(s.alignDelimiters!==!1){const A=d[h]-(v[h]||0),N=o[h];N===114?j=" ".repeat(A):N===99?A%2?(j=" ".repeat(A/2+.5),C=" ".repeat(A/2-.5)):(j=" ".repeat(A/2),C=j):C=" ".repeat(A)}s.delimiterStart!==!1&&!h&&b.push("|"),s.padding!==!1&&!(s.alignDelimiters===!1&&y==="")&&(s.delimiterStart!==!1||h)&&b.push(" "),s.alignDelimiters!==!1&&b.push(j),b.push(y),s.alignDelimiters!==!1&&b.push(C),s.padding!==!1&&b.push(" "),(s.delimiterEnd!==!1||h!==u-1)&&b.push("|")}g.push(s.delimiterEnd===!1?b.join("").replace(/ +$/,""):b.join(""))}return g.join(`
658
+ `)}function QM(e){return e==null?"":String(e)}function lh(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 XM(e,n,s,a){const r=s.enter("blockquote"),o=s.createTracker(a);o.move("> "),o.shift(2);const l=s.indentLines(s.containerFlow(e,o.current()),ZM);return r(),l}function ZM(e,n,s){return">"+(s?"":" ")+e}function e_(e,n){return ch(e,n.inConstruct,!0)&&!ch(e,n.notInConstruct,!1)}function ch(e,n,s){if(typeof n=="string"&&(n=[n]),!n||n.length===0)return s;let a=-1;for(;++a<n.length;)if(e.includes(n[a]))return!0;return!1}function dh(e,n,s,a){let r=-1;for(;++r<s.unsafe.length;)if(s.unsafe[r].character===`
659
+ `&&e_(s.stack,s.unsafe[r]))return/[ \t]/.test(a.before)?"":" ";return`\\
660
+ `}function t_(e,n){const s=String(e);let a=s.indexOf(n),r=a,o=0,l=0;if(typeof n!="string")throw new TypeError("Expected substring");for(;a!==-1;)a===r?++o>l&&(l=o):o=1,r=a+n.length,a=s.indexOf(n,r);return l}function n_(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 s_(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 i_(e,n,s,a){const r=s_(s),o=e.value||"",l=r==="`"?"GraveAccent":"Tilde";if(n_(e,s)){const h=s.enter("codeIndented"),f=s.indentLines(o,a_);return h(),f}const c=s.createTracker(a),d=r.repeat(Math.max(t_(o,r)+1,3)),u=s.enter("codeFenced");let m=c.move(d);if(e.lang){const h=s.enter(`codeFencedLang${l}`);m+=c.move(s.safe(e.lang,{before:m,after:" ",encode:["`"],...c.current()})),h()}if(e.lang&&e.meta){const h=s.enter(`codeFencedMeta${l}`);m+=c.move(" "),m+=c.move(s.safe(e.meta,{before:m,after:`
661
+ `,encode:["`"],...c.current()})),h()}return m+=c.move(`
662
+ `),o&&(m+=c.move(o+`
663
+ `)),m+=c.move(d),u(),m}function a_(e,n,s){return(s?"":" ")+e}function mu(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 r_(e,n,s,a){const r=mu(s),o=r==='"'?"Quote":"Apostrophe",l=s.enter("definition");let c=s.enter("label");const d=s.createTracker(a);let u=d.move("[");return u+=d.move(s.safe(s.associationId(e),{before:u,after:"]",...d.current()})),u+=d.move("]: "),c(),!e.url||/[\0- \u007F]/.test(e.url)?(c=s.enter("destinationLiteral"),u+=d.move("<"),u+=d.move(s.safe(e.url,{before:u,after:">",...d.current()})),u+=d.move(">")):(c=s.enter("destinationRaw"),u+=d.move(s.safe(e.url,{before:u,after:e.title?" ":`
664
+ `,...d.current()}))),c(),e.title&&(c=s.enter(`title${o}`),u+=d.move(" "+r),u+=d.move(s.safe(e.title,{before:u,after:r,...d.current()})),u+=d.move(r),c()),l(),u}function o_(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 Fr(e){return"&#x"+e.toString(16).toUpperCase()+";"}function dl(e,n,s){const a=Oa(e),r=Oa(n);return a===void 0?r===void 0?s==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:r===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:a===1?r===void 0?{inside:!1,outside:!1}:r===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:r===void 0?{inside:!1,outside:!1}:r===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}kg.peek=l_;function kg(e,n,s,a){const r=o_(s),o=s.enter("emphasis"),l=s.createTracker(a),c=l.move(r);let d=l.move(s.containerPhrasing(e,{after:r,before:c,...l.current()}));const u=d.charCodeAt(0),m=dl(a.before.charCodeAt(a.before.length-1),u,r);m.inside&&(d=Fr(u)+d.slice(1));const h=d.charCodeAt(d.length-1),f=dl(a.after.charCodeAt(0),h,r);f.inside&&(d=d.slice(0,-1)+Fr(h));const p=l.move(r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+d+p}function l_(e,n,s){return s.options.emphasis||"*"}function c_(e,n){let s=!1;return du(e,function(a){if("value"in a&&/\r?\n|\r/.test(a.value)||a.type==="break")return s=!0,Sd}),!!((!e.depth||e.depth<3)&&su(e)&&(n.options.setext||s))}function d_(e,n,s,a){const r=Math.max(Math.min(6,e.depth||1),1),o=s.createTracker(a);if(c_(e,s)){const m=s.enter("headingSetext"),h=s.enter("phrasing"),f=s.containerPhrasing(e,{...o.current(),before:`
665
+ `,after:`
666
+ `});return h(),m(),f+`
667
+ `+(r===1?"=":"-").repeat(f.length-(Math.max(f.lastIndexOf("\r"),f.lastIndexOf(`
668
+ `))+1))}const l="#".repeat(r),c=s.enter("headingAtx"),d=s.enter("phrasing");o.move(l+" ");let u=s.containerPhrasing(e,{before:"# ",after:`
669
+ `,...o.current()});return/^[\t ]/.test(u)&&(u=Fr(u.charCodeAt(0))+u.slice(1)),u=u?l+" "+u:l,s.options.closeAtx&&(u+=" "+l),d(),c(),u}jg.peek=u_;function jg(e){return e.value||""}function u_(){return"<"}Ng.peek=m_;function Ng(e,n,s,a){const r=mu(s),o=r==='"'?"Quote":"Apostrophe",l=s.enter("image");let c=s.enter("label");const d=s.createTracker(a);let u=d.move("![");return u+=d.move(s.safe(e.alt,{before:u,after:"]",...d.current()})),u+=d.move("]("),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=s.enter("destinationLiteral"),u+=d.move("<"),u+=d.move(s.safe(e.url,{before:u,after:">",...d.current()})),u+=d.move(">")):(c=s.enter("destinationRaw"),u+=d.move(s.safe(e.url,{before:u,after:e.title?" ":")",...d.current()}))),c(),e.title&&(c=s.enter(`title${o}`),u+=d.move(" "+r),u+=d.move(s.safe(e.title,{before:u,after:r,...d.current()})),u+=d.move(r),c()),u+=d.move(")"),l(),u}function m_(){return"!"}Sg.peek=h_;function Sg(e,n,s,a){const r=e.referenceType,o=s.enter("imageReference");let l=s.enter("label");const c=s.createTracker(a);let d=c.move("![");const u=s.safe(e.alt,{before:d,after:"]",...c.current()});d+=c.move(u+"]["),l();const m=s.stack;s.stack=[],l=s.enter("reference");const h=s.safe(s.associationId(e),{before:d,after:"]",...c.current()});return l(),s.stack=m,o(),r==="full"||!u||u!==h?d+=c.move(h+"]"):r==="shortcut"?d=d.slice(0,-1):d+=c.move("]"),d}function h_(){return"!"}Cg.peek=p_;function Cg(e,n,s){let a=e.value||"",r="`",o=-1;for(;new RegExp("(^|[^`])"+r+"([^`]|$)").test(a);)r+="`";for(/[^ \r\n]/.test(a)&&(/^[ \r\n]/.test(a)&&/[ \r\n]$/.test(a)||/^`|`$/.test(a))&&(a=" "+a+" ");++o<s.unsafe.length;){const l=s.unsafe[o],c=s.compilePattern(l);let d;if(l.atBreak)for(;d=c.exec(a);){let u=d.index;a.charCodeAt(u)===10&&a.charCodeAt(u-1)===13&&u--,a=a.slice(0,u)+" "+a.slice(d.index+1)}}return r+a+r}function p_(){return"`"}function Eg(e,n){const s=su(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))}Mg.peek=f_;function Mg(e,n,s,a){const r=mu(s),o=r==='"'?"Quote":"Apostrophe",l=s.createTracker(a);let c,d;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"),d=s.enter("label");let u=l.move("[");return u+=l.move(s.containerPhrasing(e,{before:u,after:"](",...l.current()})),u+=l.move("]("),d(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(d=s.enter("destinationLiteral"),u+=l.move("<"),u+=l.move(s.safe(e.url,{before:u,after:">",...l.current()})),u+=l.move(">")):(d=s.enter("destinationRaw"),u+=l.move(s.safe(e.url,{before:u,after:e.title?" ":")",...l.current()}))),d(),e.title&&(d=s.enter(`title${o}`),u+=l.move(" "+r),u+=l.move(s.safe(e.title,{before:u,after:r,...l.current()})),u+=l.move(r),d()),u+=l.move(")"),c(),u}function f_(e,n,s){return Eg(e,s)?"<":"["}_g.peek=g_;function _g(e,n,s,a){const r=e.referenceType,o=s.enter("linkReference");let l=s.enter("label");const c=s.createTracker(a);let d=c.move("[");const u=s.containerPhrasing(e,{before:d,after:"]",...c.current()});d+=c.move(u+"]["),l();const m=s.stack;s.stack=[],l=s.enter("reference");const h=s.safe(s.associationId(e),{before:d,after:"]",...c.current()});return l(),s.stack=m,o(),r==="full"||!u||u!==h?d+=c.move(h+"]"):r==="shortcut"?d=d.slice(0,-1):d+=c.move("]"),d}function g_(){return"["}function hu(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 b_(e){const n=hu(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 Ag(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 v_(e,n,s,a){const r=s.enter("list"),o=s.bulletCurrent;let l=e.ordered?x_(s):hu(s);const c=e.ordered?l==="."?")":".":b_(s);let d=n&&s.bulletLastUsed?l===s.bulletLastUsed:!1;if(!e.ordered){const m=e.children?e.children[0]:void 0;if((l==="*"||l==="-")&&m&&(!m.children||!m.children[0])&&s.stack[s.stack.length-1]==="list"&&s.stack[s.stack.length-2]==="listItem"&&s.stack[s.stack.length-3]==="list"&&s.stack[s.stack.length-4]==="listItem"&&s.indexStack[s.indexStack.length-1]===0&&s.indexStack[s.indexStack.length-2]===0&&s.indexStack[s.indexStack.length-3]===0&&(d=!0),Ag(s)===l&&m){let h=-1;for(;++h<e.children.length;){const f=e.children[h];if(f&&f.type==="listItem"&&f.children&&f.children[0]&&f.children[0].type==="thematicBreak"){d=!0;break}}}}d&&(l=c),s.bulletCurrent=l;const u=s.containerFlow(e,a);return s.bulletLastUsed=l,s.bulletCurrent=o,r(),u}function y_(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 w_(e,n,s,a){const r=y_(s);let o=s.bulletCurrent||hu(s);n&&n.type==="list"&&n.ordered&&(o=(typeof n.start=="number"&&n.start>-1?n.start:1)+(s.options.incrementListMarker===!1?0:n.children.indexOf(e))+o);let l=o.length+1;(r==="tab"||r==="mixed"&&(n&&n.type==="list"&&n.spread||e.spread))&&(l=Math.ceil(l/4)*4);const c=s.createTracker(a);c.move(o+" ".repeat(l-o.length)),c.shift(l);const d=s.enter("listItem"),u=s.indentLines(s.containerFlow(e,c.current()),m);return d(),u;function m(h,f,p){return f?(p?"":" ".repeat(l))+h:(p?o:o+" ".repeat(l-o.length))+h}}function k_(e,n,s,a){const r=s.enter("paragraph"),o=s.enter("phrasing"),l=s.containerPhrasing(e,a);return o(),r(),l}const j_=Il(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function N_(e,n,s,a){return(e.children.some(function(l){return j_(l)})?s.containerPhrasing:s.containerFlow).call(s,e,a)}function S_(e){const n=e.options.strong||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize strong with `"+n+"` for `options.strong`, expected `*`, or `_`");return n}Pg.peek=C_;function Pg(e,n,s,a){const r=S_(s),o=s.enter("strong"),l=s.createTracker(a),c=l.move(r+r);let d=l.move(s.containerPhrasing(e,{after:r,before:c,...l.current()}));const u=d.charCodeAt(0),m=dl(a.before.charCodeAt(a.before.length-1),u,r);m.inside&&(d=Fr(u)+d.slice(1));const h=d.charCodeAt(d.length-1),f=dl(a.after.charCodeAt(0),h,r);f.inside&&(d=d.slice(0,-1)+Fr(h));const p=l.move(r+r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+d+p}function C_(e,n,s){return s.options.strong||"*"}function E_(e,n,s,a){return s.safe(e.value,a)}function M_(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 __(e,n,s){const a=(Ag(s)+(s.options.ruleSpaces?" ":"")).repeat(M_(s));return s.options.ruleSpaces?a.slice(0,-1):a}const Rg={blockquote:XM,break:dh,code:i_,definition:r_,emphasis:kg,hardBreak:dh,heading:d_,html:jg,image:Ng,imageReference:Sg,inlineCode:Cg,link:Mg,linkReference:_g,list:v_,listItem:w_,paragraph:k_,root:N_,strong:Pg,text:E_,thematicBreak:__};function A_(){return{enter:{table:P_,tableData:uh,tableHeader:uh,tableRow:T_},exit:{codeText:I_,table:R_,tableData:jc,tableHeader:jc,tableRow:jc}}}function P_(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 R_(e){this.exit(e),this.data.inTable=void 0}function T_(e){this.enter({type:"tableRow",children:[]},e)}function jc(e){this.exit(e)}function uh(e){this.enter({type:"tableCell",children:[]},e)}function I_(e){let n=this.resume();this.data.inTable&&(n=n.replace(/\\([\\|])/g,$_));const s=this.stack[this.stack.length-1];s.type,s.value=n,this.exit(e)}function $_(e,n){return n==="|"?n:e}function D_(e){const n=e||{},s=n.tableCellPadding,a=n.tablePipeAlign,r=n.stringLength,o=s?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
670
+ `,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:f,table:l,tableCell:d,tableRow:c}};function l(p,g,x,v){return u(m(p,x,v),p.align)}function c(p,g,x,v){const b=h(p,x,v),y=u([b]);return y.slice(0,y.indexOf(`
671
+ `))}function d(p,g,x,v){const b=x.enter("tableCell"),y=x.enter("phrasing"),j=x.containerPhrasing(p,{...v,before:o,after:o});return y(),b(),j}function u(p,g){return YM(p,{align:g,alignDelimiters:a,padding:s,stringLength:r})}function m(p,g,x){const v=p.children;let b=-1;const y=[],j=g.enter("table");for(;++b<v.length;)y[b]=h(v[b],g,x);return j(),y}function h(p,g,x){const v=p.children;let b=-1;const y=[],j=g.enter("tableRow");for(;++b<v.length;)y[b]=d(v[b],p,g,x);return j(),y}function f(p,g,x){let v=Rg.inlineCode(p,g,x);return x.stack.includes("tableCell")&&(v=v.replace(/\|/g,"\\$&")),v}}function L_(){return{exit:{taskListCheckValueChecked:mh,taskListCheckValueUnchecked:mh,paragraph:z_}}}function O_(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:F_}}}function mh(e){const n=this.stack[this.stack.length-2];n.type,n.checked=e.type==="taskListCheckValueChecked"}function z_(e){const n=this.stack[this.stack.length-2];if(n&&n.type==="listItem"&&typeof n.checked=="boolean"){const s=this.stack[this.stack.length-1];s.type;const a=s.children[0];if(a&&a.type==="text"){const r=n.children;let o=-1,l;for(;++o<r.length;){const c=r[o];if(c.type==="paragraph"){l=c;break}}l===s&&(a.value=a.value.slice(1),a.value.length===0?s.children.shift():s.position&&a.position&&typeof a.position.start.offset=="number"&&(a.position.start.column++,a.position.start.offset++,s.position.start=Object.assign({},a.position.start)))}}this.exit(e)}function F_(e,n,s,a){const r=e.children[0],o=typeof e.checked=="boolean"&&r&&r.type==="paragraph",l="["+(e.checked?"x":" ")+"] ",c=s.createTracker(a);o&&c.move(l);let d=Rg.listItem(e,n,s,{...a,...c.current()});return o&&(d=d.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,u)),d;function u(m){return m+l}}function U_(){return[vM(),FM(),qM(),A_(),L_()]}function B_(e){return{extensions:[yM(),UM(e),VM(),D_(e),O_()]}}const H_={tokenize:J_,partial:!0},Tg={tokenize:Y_,partial:!0},Ig={tokenize:Q_,partial:!0},$g={tokenize:X_,partial:!0},q_={tokenize:Z_,partial:!0},Dg={name:"wwwAutolink",tokenize:K_,previous:Og},Lg={name:"protocolAutolink",tokenize:G_,previous:zg},Ti={name:"emailAutolink",tokenize:W_,previous:Fg},ki={};function V_(){return{text:ki}}let Yi=48;for(;Yi<123;)ki[Yi]=Ti,Yi++,Yi===58?Yi=65:Yi===91&&(Yi=97);ki[43]=Ti;ki[45]=Ti;ki[46]=Ti;ki[95]=Ti;ki[72]=[Ti,Lg];ki[104]=[Ti,Lg];ki[87]=[Ti,Dg];ki[119]=[Ti,Dg];function W_(e,n,s){const a=this;let r,o;return l;function l(h){return!_d(h)||!Fg.call(a,a.previous)||pu(a.events)?s(h):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(h))}function c(h){return _d(h)?(e.consume(h),c):h===64?(e.consume(h),d):s(h)}function d(h){return h===46?e.check(q_,m,u)(h):h===45||h===95||ks(h)?(o=!0,e.consume(h),d):m(h)}function u(h){return e.consume(h),r=!0,d}function m(h){return o&&r&&Es(a.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),n(h)):s(h)}}function K_(e,n,s){const a=this;return r;function r(l){return l!==87&&l!==119||!Og.call(a,a.previous)||pu(a.events)?s(l):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(H_,e.attempt(Tg,e.attempt(Ig,o),s),s)(l))}function o(l){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),n(l)}}function G_(e,n,s){const a=this;let r="",o=!1;return l;function l(h){return(h===72||h===104)&&zg.call(a,a.previous)&&!pu(a.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),r+=String.fromCodePoint(h),e.consume(h),c):s(h)}function c(h){if(Es(h)&&r.length<5)return r+=String.fromCodePoint(h),e.consume(h),c;if(h===58){const f=r.toLowerCase();if(f==="http"||f==="https")return e.consume(h),d}return s(h)}function d(h){return h===47?(e.consume(h),o?u:(o=!0,d)):s(h)}function u(h){return h===null||ol(h)||In(h)||ra(h)||Pl(h)?s(h):e.attempt(Tg,e.attempt(Ig,m),s)(h)}function m(h){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),n(h)}}function J_(e,n,s){let a=0;return r;function r(l){return(l===87||l===119)&&a<3?(a++,e.consume(l),r):l===46&&a===3?(e.consume(l),o):s(l)}function o(l){return l===null?s(l):n(l)}}function Y_(e,n,s){let a,r,o;return l;function l(u){return u===46||u===95?e.check($g,d,c)(u):u===null||In(u)||ra(u)||u!==45&&Pl(u)?d(u):(o=!0,e.consume(u),l)}function c(u){return u===95?a=!0:(r=a,a=void 0),e.consume(u),l}function d(u){return r||a||!o?s(u):n(u)}}function Q_(e,n){let s=0,a=0;return r;function r(l){return l===40?(s++,e.consume(l),r):l===41&&a<s?o(l):l===33||l===34||l===38||l===39||l===41||l===42||l===44||l===46||l===58||l===59||l===60||l===63||l===93||l===95||l===126?e.check($g,n,o)(l):l===null||In(l)||ra(l)?n(l):(e.consume(l),r)}function o(l){return l===41&&a++,e.consume(l),r}}function X_(e,n,s){return a;function a(c){return c===33||c===34||c===39||c===41||c===42||c===44||c===46||c===58||c===59||c===63||c===95||c===126?(e.consume(c),a):c===38?(e.consume(c),o):c===93?(e.consume(c),r):c===60||c===null||In(c)||ra(c)?n(c):s(c)}function r(c){return c===null||c===40||c===91||In(c)||ra(c)?n(c):a(c)}function o(c){return Es(c)?l(c):s(c)}function l(c){return c===59?(e.consume(c),a):Es(c)?(e.consume(c),l):s(c)}}function Z_(e,n,s){return a;function a(o){return e.consume(o),r}function r(o){return ks(o)?s(o):n(o)}}function Og(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||In(e)}function zg(e){return!Es(e)}function Fg(e){return!(e===47||_d(e))}function _d(e){return e===43||e===45||e===46||e===95||ks(e)}function pu(e){let n=e.length,s=!1;for(;n--;){const a=e[n][1];if((a.type==="labelLink"||a.type==="labelImage")&&!a._balanced){s=!0;break}if(a._gfmAutolinkLiteralWalkedInto){s=!1;break}}return e.length>0&&!s&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),s}const eA={tokenize:lA,partial:!0};function tA(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:aA,continuation:{tokenize:rA},exit:oA}},text:{91:{name:"gfmFootnoteCall",tokenize:iA},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:nA,resolveTo:sA}}}}function nA(e,n,s){const a=this;let r=a.events.length;const o=a.parser.gfmFootnotes||(a.parser.gfmFootnotes=[]);let l;for(;r--;){const d=a.events[r][1];if(d.type==="labelImage"){l=d;break}if(d.type==="gfmFootnoteCall"||d.type==="labelLink"||d.type==="label"||d.type==="image"||d.type==="link")break}return c;function c(d){if(!l||!l._balanced)return s(d);const u=ai(a.sliceSerialize({start:l.end,end:a.now()}));return u.codePointAt(0)!==94||!o.includes(u.slice(1))?s(d):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),n(d))}}function sA(e,n){let s=e.length;for(;s--;)if(e[s][1].type==="labelImage"&&e[s][0]==="enter"){e[s][1];break}e[s+1][1].type="data",e[s+3][1].type="gfmFootnoteCallLabelMarker";const a={type:"gfmFootnoteCall",start:Object.assign({},e[s+3][1].start),end:Object.assign({},e[e.length-1][1].end)},r={type:"gfmFootnoteCallMarker",start:Object.assign({},e[s+3][1].end),end:Object.assign({},e[s+3][1].end)};r.end.column++,r.end.offset++,r.end._bufferIndex++;const o={type:"gfmFootnoteCallString",start:Object.assign({},r.end),end:Object.assign({},e[e.length-1][1].start)},l={type:"chunkString",contentType:"string",start:Object.assign({},o.start),end:Object.assign({},o.end)},c=[e[s+1],e[s+2],["enter",a,n],e[s+3],e[s+4],["enter",r,n],["exit",r,n],["enter",o,n],["enter",l,n],["exit",l,n],["exit",o,n],e[e.length-2],e[e.length-1],["exit",a,n]];return e.splice(s,e.length-s+1,...c),e}function iA(e,n,s){const a=this,r=a.parser.gfmFootnotes||(a.parser.gfmFootnotes=[]);let o=0,l;return c;function c(h){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),d}function d(h){return h!==94?s(h):(e.enter("gfmFootnoteCallMarker"),e.consume(h),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",u)}function u(h){if(o>999||h===93&&!l||h===null||h===91||In(h))return s(h);if(h===93){e.exit("chunkString");const f=e.exit("gfmFootnoteCallString");return r.includes(ai(a.sliceSerialize(f)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),n):s(h)}return In(h)||(l=!0),o++,e.consume(h),h===92?m:u}function m(h){return h===91||h===92||h===93?(e.consume(h),o++,u):u(h)}}function aA(e,n,s){const a=this,r=a.parser.gfmFootnotes||(a.parser.gfmFootnotes=[]);let o,l=0,c;return d;function d(g){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),u}function u(g){return g===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",m):s(g)}function m(g){if(l>999||g===93&&!c||g===null||g===91||In(g))return s(g);if(g===93){e.exit("chunkString");const x=e.exit("gfmFootnoteDefinitionLabelString");return o=ai(a.sliceSerialize(x)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),f}return In(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),jn(e,p,"gfmFootnoteDefinitionWhitespace")):s(g)}function p(g){return n(g)}}function rA(e,n,s){return e.check(to,n,e.attempt(eA,n,s))}function oA(e){e.exit("gfmFootnoteDefinition")}function lA(e,n,s){const a=this;return jn(e,r,"gfmFootnoteDefinitionIndent",5);function r(o){const l=a.events[a.events.length-1];return l&&l[1].type==="gfmFootnoteDefinitionIndent"&&l[2].sliceSerialize(l[1],!0).length===4?n(o):s(o)}}function cA(e){let s=(e||{}).singleTilde;const a={name:"strikethrough",tokenize:o,resolveAll:r};return s==null&&(s=!0),{text:{126:a},insideSpan:{null:[a]},attentionMarkers:{null:[126]}};function r(l,c){let d=-1;for(;++d<l.length;)if(l[d][0]==="enter"&&l[d][1].type==="strikethroughSequenceTemporary"&&l[d][1]._close){let u=d;for(;u--;)if(l[u][0]==="exit"&&l[u][1].type==="strikethroughSequenceTemporary"&&l[u][1]._open&&l[d][1].end.offset-l[d][1].start.offset===l[u][1].end.offset-l[u][1].start.offset){l[d][1].type="strikethroughSequence",l[u][1].type="strikethroughSequence";const m={type:"strikethrough",start:Object.assign({},l[u][1].start),end:Object.assign({},l[d][1].end)},h={type:"strikethroughText",start:Object.assign({},l[u][1].end),end:Object.assign({},l[d][1].start)},f=[["enter",m,c],["enter",l[u][1],c],["exit",l[u][1],c],["enter",h,c]],p=c.parser.constructs.insideSpan.null;p&&Us(f,f.length,0,Rl(p,l.slice(u+1,d),c)),Us(f,f.length,0,[["exit",h,c],["enter",l[d][1],c],["exit",l[d][1],c],["exit",m,c]]),Us(l,u-1,d-u+3,f),d=u+f.length-2;break}}for(d=-1;++d<l.length;)l[d][1].type==="strikethroughSequenceTemporary"&&(l[d][1].type="data");return l}function o(l,c,d){const u=this.previous,m=this.events;let h=0;return f;function f(g){return u===126&&m[m.length-1][1].type!=="characterEscape"?d(g):(l.enter("strikethroughSequenceTemporary"),p(g))}function p(g){const x=Oa(u);if(g===126)return h>1?d(g):(l.consume(g),h++,p);if(h<2&&!s)return d(g);const v=l.exit("strikethroughSequenceTemporary"),b=Oa(g);return v._open=!b||b===2&&!!x,v._close=!x||x===2&&!!b,c(g)}}}class dA{constructor(){this.map=[]}add(n,s,a){uA(this,n,s,a)}consume(n){if(this.map.sort(function(o,l){return o[0]-l[0]}),this.map.length===0)return;let s=this.map.length;const a=[];for(;s>0;)s-=1,a.push(n.slice(this.map[s][0]+this.map[s][1]),this.map[s][2]),n.length=this.map[s][0];a.push(n.slice()),n.length=0;let r=a.pop();for(;r;){for(const o of r)n.push(o);r=a.pop()}this.map.length=0}}function uA(e,n,s,a){let r=0;if(!(s===0&&a.length===0)){for(;r<e.map.length;){if(e.map[r][0]===n){e.map[r][1]+=s,e.map[r][2].push(...a);return}r+=1}e.map.push([n,s,a])}}function mA(e,n){let s=!1;const a=[];for(;n<e.length;){const r=e[n];if(s){if(r[0]==="enter")r[1].type==="tableContent"&&a.push(e[n+1][1].type==="tableDelimiterMarker"?"left":"none");else if(r[1].type==="tableContent"){if(e[n-1][1].type==="tableDelimiterMarker"){const o=a.length-1;a[o]=a[o]==="left"?"center":"right"}}else if(r[1].type==="tableDelimiterRow")break}else r[0]==="enter"&&r[1].type==="tableDelimiterRow"&&(s=!0);n+=1}return a}function hA(){return{flow:{null:{name:"table",tokenize:pA,resolveAll:fA}}}}function pA(e,n,s){const a=this;let r=0,o=0,l;return c;function c(M){let E=a.events.length-1;for(;E>-1;){const R=a.events[E][1].type;if(R==="lineEnding"||R==="linePrefix")E--;else break}const L=E>-1?a.events[E][1].type:null,F=L==="tableHead"||L==="tableRow"?N:d;return F===N&&a.parser.lazy[a.now().line]?s(M):F(M)}function d(M){return e.enter("tableHead"),e.enter("tableRow"),u(M)}function u(M){return M===124||(l=!0,o+=1),m(M)}function m(M){return M===null?s(M):Lt(M)?o>1?(o=0,a.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(M),e.exit("lineEnding"),p):s(M):gn(M)?jn(e,m,"whitespace")(M):(o+=1,l&&(l=!1,r+=1),M===124?(e.enter("tableCellDivider"),e.consume(M),e.exit("tableCellDivider"),l=!0,m):(e.enter("data"),h(M)))}function h(M){return M===null||M===124||In(M)?(e.exit("data"),m(M)):(e.consume(M),M===92?f:h)}function f(M){return M===92||M===124?(e.consume(M),h):h(M)}function p(M){return a.interrupt=!1,a.parser.lazy[a.now().line]?s(M):(e.enter("tableDelimiterRow"),l=!1,gn(M)?jn(e,g,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(M):g(M))}function g(M){return M===45||M===58?v(M):M===124?(l=!0,e.enter("tableCellDivider"),e.consume(M),e.exit("tableCellDivider"),x):A(M)}function x(M){return gn(M)?jn(e,v,"whitespace")(M):v(M)}function v(M){return M===58?(o+=1,l=!0,e.enter("tableDelimiterMarker"),e.consume(M),e.exit("tableDelimiterMarker"),b):M===45?(o+=1,b(M)):M===null||Lt(M)?C(M):A(M)}function b(M){return M===45?(e.enter("tableDelimiterFiller"),y(M)):A(M)}function y(M){return M===45?(e.consume(M),y):M===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(M),e.exit("tableDelimiterMarker"),j):(e.exit("tableDelimiterFiller"),j(M))}function j(M){return gn(M)?jn(e,C,"whitespace")(M):C(M)}function C(M){return M===124?g(M):M===null||Lt(M)?!l||r!==o?A(M):(e.exit("tableDelimiterRow"),e.exit("tableHead"),n(M)):A(M)}function A(M){return s(M)}function N(M){return e.enter("tableRow"),S(M)}function S(M){return M===124?(e.enter("tableCellDivider"),e.consume(M),e.exit("tableCellDivider"),S):M===null||Lt(M)?(e.exit("tableRow"),n(M)):gn(M)?jn(e,S,"whitespace")(M):(e.enter("data"),_(M))}function _(M){return M===null||M===124||In(M)?(e.exit("data"),S(M)):(e.consume(M),M===92?T:_)}function T(M){return M===92||M===124?(e.consume(M),_):_(M)}}function fA(e,n){let s=-1,a=!0,r=0,o=[0,0,0,0],l=[0,0,0,0],c=!1,d=0,u,m,h;const f=new dA;for(;++s<e.length;){const p=e[s],g=p[1];p[0]==="enter"?g.type==="tableHead"?(c=!1,d!==0&&(hh(f,n,d,u,m),m=void 0,d=0),u={type:"table",start:Object.assign({},g.start),end:Object.assign({},g.end)},f.add(s,0,[["enter",u,n]])):g.type==="tableRow"||g.type==="tableDelimiterRow"?(a=!0,h=void 0,o=[0,0,0,0],l=[0,s+1,0,0],c&&(c=!1,m={type:"tableBody",start:Object.assign({},g.start),end:Object.assign({},g.end)},f.add(s,0,[["enter",m,n]])),r=g.type==="tableDelimiterRow"?2:m?3:1):r&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")?(a=!1,l[2]===0&&(o[1]!==0&&(l[0]=l[1],h=No(f,n,o,r,void 0,h),o=[0,0,0,0]),l[2]=s)):g.type==="tableCellDivider"&&(a?a=!1:(o[1]!==0&&(l[0]=l[1],h=No(f,n,o,r,void 0,h)),o=l,l=[o[1],s,0,0])):g.type==="tableHead"?(c=!0,d=s):g.type==="tableRow"||g.type==="tableDelimiterRow"?(d=s,o[1]!==0?(l[0]=l[1],h=No(f,n,o,r,s,h)):l[1]!==0&&(h=No(f,n,l,r,s,h)),r=0):r&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")&&(l[3]=s)}for(d!==0&&hh(f,n,d,u,m),f.consume(n.events),s=-1;++s<n.events.length;){const p=n.events[s];p[0]==="enter"&&p[1].type==="table"&&(p[1]._align=mA(n.events,s))}return e}function No(e,n,s,a,r,o){const l=a===1?"tableHeader":a===2?"tableDelimiter":"tableData",c="tableContent";s[0]!==0&&(o.end=Object.assign({},Ea(n.events,s[0])),e.add(s[0],0,[["exit",o,n]]));const d=Ea(n.events,s[1]);if(o={type:l,start:Object.assign({},d),end:Object.assign({},d)},e.add(s[1],0,[["enter",o,n]]),s[2]!==0){const u=Ea(n.events,s[2]),m=Ea(n.events,s[3]),h={type:c,start:Object.assign({},u),end:Object.assign({},m)};if(e.add(s[2],0,[["enter",h,n]]),a!==2){const f=n.events[s[2]],p=n.events[s[3]];if(f[1].end=Object.assign({},p[1].end),f[1].type="chunkText",f[1].contentType="text",s[3]>s[2]+1){const g=s[2]+1,x=s[3]-s[2]-1;e.add(g,x,[])}}e.add(s[3]+1,0,[["exit",h,n]])}return r!==void 0&&(o.end=Object.assign({},Ea(n.events,r)),e.add(r,0,[["exit",o,n]]),o=void 0),o}function hh(e,n,s,a,r){const o=[],l=Ea(n.events,s);r&&(r.end=Object.assign({},l),o.push(["exit",r,n])),a.end=Object.assign({},l),o.push(["exit",a,n]),e.add(s+1,0,o)}function Ea(e,n){const s=e[n],a=s[0]==="enter"?"start":"end";return s[1][a]}const gA={name:"tasklistCheck",tokenize:xA};function bA(){return{text:{91:gA}}}function xA(e,n,s){const a=this;return r;function r(d){return a.previous!==null||!a._gfmTasklistFirstContentOfListItem?s(d):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(d),e.exit("taskListCheckMarker"),o)}function o(d){return In(d)?(e.enter("taskListCheckValueUnchecked"),e.consume(d),e.exit("taskListCheckValueUnchecked"),l):d===88||d===120?(e.enter("taskListCheckValueChecked"),e.consume(d),e.exit("taskListCheckValueChecked"),l):s(d)}function l(d){return d===93?(e.enter("taskListCheckMarker"),e.consume(d),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),c):s(d)}function c(d){return Lt(d)?n(d):gn(d)?e.check({tokenize:vA},n,s)(d):s(d)}}function vA(e,n,s){return jn(e,a,"whitespace");function a(r){return r===null?s(r):n(r)}}function yA(e){return Qf([V_(),tA(),cA(e),hA(),bA()])}const wA={};function yi(e){const n=this,s=e||wA,a=n.data(),r=a.micromarkExtensions||(a.micromarkExtensions=[]),o=a.fromMarkdownExtensions||(a.fromMarkdownExtensions=[]),l=a.toMarkdownExtensions||(a.toMarkdownExtensions=[]);r.push(yA(s)),o.push(U_()),l.push(B_(s))}const kA=45e3,jA=3e3,NA=2e3,SA=1500,ph="fusion:sse-client-id";let ka=null;const zi=new Map;function fh(){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 Ug(){if(!(typeof window>"u")){if(ka)return ka;try{const e=window.sessionStorage.getItem(ph);if(e)return ka=e,e;const n=fh();return window.sessionStorage.setItem(ph,n),ka=n,n}catch{return ka=fh(),ka}}}function Bg(e){if(!(typeof window>"u"))try{return{parsed:new URL(e,window.location.origin),preserveRelativePath:e.startsWith("/")}}catch{return}}function Hg(e){return e.origin===window.location.origin&&e.pathname==="/api/events"}function CA(e){const n=Ug();if(!n)return e;const s=Bg(e);return!s||!Hg(s.parsed)?e:(s.parsed.searchParams.set("clientId",n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function fu(e,n){const s=Ug();if(!s)return;const a=Bg(e);if(!a||!Hg(a.parsed))return;const r=new URL(`/api/events/${n}`,window.location.origin);r.searchParams.set("clientId",s);const o=a.parsed.searchParams.get("projectId");return o&&r.searchParams.set("projectId",o),xi(`${r.pathname}${r.search}${r.hash}`)}function EA(e){if(typeof window>"u")return;const n=fu(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 Dl(e){e.keepaliveTimer&&(clearInterval(e.keepaliveTimer),e.keepaliveTimer=null)}function gh(e){if(typeof window>"u"||typeof window.fetch!="function")return;const n=fu(e.url,"keepalive");if(!n)return;const s=typeof AbortController<"u"?new AbortController:null,a=s?window.setTimeout(()=>s.abort(),SA):null;window.fetch(n,{method:"POST",cache:"no-store",signal:s?.signal}).catch(()=>{}).finally(()=>{a!==null&&window.clearTimeout(a)})}function MA(e){Dl(e),fu(e.url,"keepalive")&&(gh(e),e.keepaliveTimer=window.setInterval(()=>{gh(e)},NA))}if(typeof window<"u"){const e=()=>{for(const s of Array.from(zi.values()))if(!s.closed){if(Dl(s),EA(s),s.es){try{s.es.close()}catch{}s.es=null}s.closed=!0}},n=s=>{if(s.persisted)for(const a of Array.from(zi.values()))a.subscribers.size!==0&&(a.closed=!1,gu(a))};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e),window.addEventListener("pageshow",n)}function kr(e){e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),e.heartbeatTimer=setTimeout(()=>{qg(e)},kA)}function qg(e){if(e.heartbeatTimer&&(clearTimeout(e.heartbeatTimer),e.heartbeatTimer=null),e.es&&(e.es.close(),e.es=null),Dl(e),e.nativeListeners.clear(),e.closed||e.subscribers.size===0||e.reconnectTimer)return;const n=zi.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=zi.get(e.url);s&&s===e&&e.subscribers.size>0&&gu(e)},jA)}}function gu(e){if(e.es||e.closed)return;e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=null);const n=new EventSource(xi(CA(e.url)));e.es=n,MA(e),n.addEventListener("open",()=>{kr(e);const s=e.hasOpenedOnce;e.hasOpenedOnce=!0;for(const a of e.subscribers)a.onOpen?.(),s&&a.onReconnect?.()}),n.addEventListener("error",s=>{for(const a of e.subscribers)a.onError?.(s);qg(e)}),n.addEventListener("message",()=>kr(e)),n.addEventListener("heartbeat",()=>kr(e)),Vg(e),kr(e)}function Vg(e){if(!e.es)return;const n=new Set;for(const s of e.subscribers)for(const a of s.events.keys())n.add(a);for(const s of n){if(e.nativeListeners.has(s))continue;const a=r=>{kr(e);const o=r;for(const l of e.subscribers){const c=l.events.get(s);if(c)for(const d of c)d(o)}};e.nativeListeners.set(s,a),e.es.addEventListener(s,a)}}function _A(e){e.closed=!0,e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),Dl(e),e.reconnectTimer&&clearTimeout(e.reconnectTimer),e.es&&e.es.close(),e.es=null,e.nativeListeners.clear(),zi.delete(e.url)}function li(e,n={}){let s=zi.get(e);s||(s={url:e,es:null,subscribers:new Set,nativeListeners:new Map,heartbeatTimer:null,keepaliveTimer:null,reconnectTimer:null,hasOpenedOnce:!1,closed:!1},zi.set(e,s));const a={events:new Map,onOpen:n.onOpen,onReconnect:n.onReconnect,onError:n.onError};if(n.events)for(const[l,c]of Object.entries(n.events)){let d=a.events.get(l);d||(d=new Set,a.events.set(l,d)),d.add(c)}s.subscribers.add(a);const r=!!s.es&&s.hasOpenedOnce;gu(s),Vg(s),r&&queueMicrotask(()=>{s.subscribers.has(a)&&a.onOpen?.()});let o=!0;return()=>{if(!o)return;o=!1;const l=zi.get(e);l&&(l.subscribers.delete(a),l.subscribers.size===0&&_A(l))}}const bh=100;function Wg(e,n,s){const[a,r]=i.useState([]),[o,l]=i.useState(!1),[c,d]=i.useState(!1),[u,m]=i.useState(null),[h,f]=i.useState(!1),p=i.useRef(null),g=i.useRef(!1),x=i.useRef(0),v=i.useRef(e),b=i.useRef(s),y=i.useRef(n),j=i.useRef(0);(v.current!==e||b.current!==s||y.current!==n)&&(v.current=e,b.current=s,y.current=n,x.current++,g.current=!0,r([]),l(!1),d(!1),m(null),f(!1),p.current&&(p.current(),p.current=null)),i.useEffect(()=>{if(!e||!n){p.current&&(p.current(),p.current=null);return}const S=x.current,_=++j.current;g.current=!1;const T=e,M=s;async function E(){if(!T)return;l(!0),f(!1);try{const F=await Pu(T,M,{limit:bh});if(g.current||x.current!==S||j.current!==_)return;r(F.entries),d(F.hasMore),m(F.total)}catch{if(g.current||x.current!==S||j.current!==_)return;r([]),d(!1),m(null)}finally{!g.current&&x.current===S&&j.current===_&&l(!1)}const L=M?`?projectId=${encodeURIComponent(M)}`:"";p.current=li(`/api/tasks/${T}/logs/stream${L}`,{events:{"agent:log":F=>{if(!(g.current||x.current!==S))try{const R=JSON.parse(F.data);r(P=>[...P,R]),m(P=>P!==null?P+1:null)}catch{}}}})}return E(),()=>{g.current=!0,p.current&&(p.current(),p.current=null)}},[e,n,s]);const A=i.useCallback(async()=>{if(!e||h)return;const S=x.current,_=a.length,T=e;f(!0);try{const M=await Pu(T,s,{limit:bh,offset:_});if(g.current||x.current!==S)return;r(E=>[...M.entries,...E]),d(M.hasMore),m(M.total)}catch{}finally{f(!1)}},[e,s,a.length,h]),N=i.useCallback(()=>r([]),[]);return{entries:a,loading:o,clear:N,loadMore:A,hasMore:c,total:u,loadingMore:h}}function AA(e){const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4),o=Math.floor(r/60),l=Math.floor(o/24);return r<1?"just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString()}const xh={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})},Kg=50,PA={triage:"Plan"};function vh(e){return e.scrollHeight-(e.scrollTop+e.clientHeight)<=Kg}function Ad(e){return[e.taskId,e.timestamp,e.agent??"",e.type,e.text,e.detail??""].join("|")}function RA(e){const n=new Map;return e.map(s=>{const a=Ad(s),r=n.get(a)??0;return n.set(a,r+1),`${a}|${r}`})}function TA(e){return e==="tool"||e==="tool_result"||e==="tool_error"}function Nc({detail:e}){const[n,s]=i.useState(!1),a=i.useId(),r=e.split(`
672
+ `).length,o=n?"Hide output":`Show output${r>1?` (${r} lines)`:""}`;return t.jsxs("div",{className:"agent-log-tool-detail-wrapper",children:[t.jsxs("button",{type:"button",className:"agent-log-tool-detail-toggle",onClick:()=>s(l=>!l),"aria-expanded":n,"aria-controls":a,"data-testid":"tool-detail-toggle",children:[n?t.jsx(un,{size:14}):t.jsx(Tn,{size:14}),t.jsx("span",{children:o})]}),t.jsx("div",{id:a,className:n?"agent-log-tool-detail-content":"agent-log-tool-detail-content agent-log-tool-detail-content--collapsed","data-testid":"tool-detail-content",children:t.jsx("pre",{className:"agent-log-tool-detail",children:e})})]})}function IA(e,n){return e.agent?TA(e.type)?!0:!n||n.agent!==e.agent||n.type!==e.type:!1}function $A(e,n){const s=[];for(let a=0;a<e.length;a+=1){const r=e[a],o=n[a]??`${Ad(r)}|fallback`,l=a>0?e[a-1]:void 0,c=IA(r,l);if(r.type==="text"||r.type==="thinking"){const d=[r];let u=a+1;for(;u<e.length;){const h=e[u];if(h.type!==r.type||h.agent!==r.agent)break;d.push(h),u+=1}const m=n[u-1]??`${Ad(e[u-1])}|fallback`;s.push({kind:r.type,entries:d,key:`${o}->${m}`,showBadge:c}),a=u-1;continue}s.push({kind:"single",entry:r,key:o,showBadge:c})}return s}function DA({entries:e,loading:n,executorModel:s,validatorModel:a,planningModel:r,hasMore:o=!1,onLoadMore:l,loadingMore:c=!1,totalCount:d=null}){const u=i.useRef(null),m=i.useRef(0),h=i.useRef(0),f=i.useRef(null),p=i.useRef(null),[g,x]=i.useState(!0),[v,b]=i.useState(!1),[y,j]=i.useState(!1),[C,A]=i.useState(!0),N=i.useMemo(()=>RA(e),[e]),S=i.useMemo(()=>$A(e,N),[e,N]);i.useLayoutEffect(()=>{const P=u.current;if(!P)return;const O=e.length,q=m.current,Z=h.current||P.scrollHeight,z=N[0]??null,k=N[N.length-1]??null,I=f.current!==z,$=p.current!==k;if(O>q)if(q===0)P.scrollTop=P.scrollHeight;else{const w=Z-(P.scrollTop+P.clientHeight)<=Kg,H=$&&!I,K=I&&!$;if(H&&w&&(P.scrollTop=P.scrollHeight),K){const pe=P.scrollHeight-Z;pe>0&&(P.scrollTop+=pe)}}m.current=O,h.current=P.scrollHeight,f.current=z,p.current=k,A(vh(P))},[e,N]);const _=i.useCallback(()=>{const P=u.current;P&&A(vh(P))},[]),T=i.useCallback(()=>{const P=u.current;P&&(P.scrollTop=P.scrollHeight,A(!0))},[]),M=i.useCallback(P=>{P.key==="Escape"&&v&&b(!1)},[v]);i.useEffect(()=>{if(v)return document.addEventListener("keydown",M),()=>{document.removeEventListener("keydown",M)}},[v,M]);const E=s?.provider&&s?.modelId,L=a?.provider&&a?.modelId,F=r?.provider&&r?.modelId,R=i.useMemo(()=>{const P=[];return E&&P.push({role:"Executor",provider:s.provider,modelId:s.modelId}),L&&P.push({role:"Reviewer",provider:a.provider,modelId:a.modelId}),F&&P.push({role:"Planning",provider:r.provider,modelId:r.modelId}),P},[E,s,L,a,F,r]);return n&&e.length===0?t.jsx("div",{className:"agent-log-viewer","data-testid":"agent-log-viewer",children:t.jsx("div",{className:"agent-log-loading",children:"Loading agent logs…"})}):e.length===0?t.jsx("div",{className:"agent-log-viewer","data-testid":"agent-log-viewer",children:t.jsx("div",{className:"agent-log-empty",children:"No agent output yet."})}):t.jsxs("div",{className:`agent-log-viewer agent-log-viewer--streaming${v?" agent-log-viewer--fullscreen":""}`,"data-testid":"agent-log-viewer",children:[t.jsxs("div",{className:"agent-log-model-header","data-testid":"agent-log-model-header",children:[t.jsxs("div",{className:"agent-log-model-icons",children:[R.map(P=>t.jsx(qn,{provider:P.provider,size:"sm"},`${P.role}-${P.provider}-${P.modelId??"default"}`)),t.jsx("button",{className:"agent-log-model-expand-btn",onClick:()=>j(P=>!P),"aria-label":y?"Collapse model details":"Expand model details","aria-expanded":y,"aria-controls":"agent-log-model-details","data-testid":"agent-log-model-expand",children:y?t.jsx(un,{size:14}):t.jsx(Tn,{size:14})})]}),t.jsxs("div",{className:"agent-log-model-header-toggle",children:[t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>x(P=>!P),"aria-label":g?"Switch to plain text mode":"Switch to markdown mode","aria-pressed":g,"data-testid":"agent-log-mode-toggle",title:g?"Show raw text":"Show formatted markdown",children:g?"Markdown":"Plain"}),t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>b(P=>!P),"aria-label":v?"Exit full screen":"Expand agent log to full screen","data-testid":"agent-log-fullscreen-toggle",title:v?"Exit full screen":"Expand agent log to full screen",children:v?t.jsx(Kr,{size:14}):t.jsx(Nl,{size:14})})]}),y&&t.jsxs("div",{id:"agent-log-model-details",className:"agent-log-model-details",children:[t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Executor:"}),E?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(qn,{provider:s.provider,size:"sm"}),t.jsxs("span",{children:[s.provider,"/",s.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]}),t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Reviewer:"}),L?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(qn,{provider:a.provider,size:"sm"}),t.jsxs("span",{children:[a.provider,"/",a.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]}),t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Planning:"}),F?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(qn,{provider:r.provider,size:"sm"}),t.jsxs("span",{children:[r.provider,"/",r.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]})]})]}),t.jsxs("div",{ref:u,className:"agent-log-viewer-scroll",onScroll:_,children:[d!==null&&t.jsxs("div",{className:"agent-log-summary","data-testid":"agent-log-summary",children:["Showing ",e.length," of ",d," entries"]}),o&&l&&t.jsx("div",{className:"agent-log-load-more","data-testid":"agent-log-load-more",children:t.jsx("button",{className:"agent-log-mode-toggle",onClick:l,disabled:c,"data-testid":"agent-log-load-more-button",children:c?t.jsxs(t.Fragment,{children:[t.jsx(gt,{size:14,className:"animate-spin"}),"Loading…"]}):"Load More"})}),S.map(P=>{const O=P.kind==="single"?P.entry:P.entries[0],q=P.showBadge?t.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:AA(O.timestamp)}):null,Z=P.showBadge?t.jsxs("span",{className:"agent-log-badge-row",children:[t.jsxs("span",{className:"agent-log-agent-badge",children:["[",PA[O.agent]??O.agent,"]"]}),q]}):null;if(P.kind==="single"){const{entry:k}=P;if(k.type==="tool")return t.jsxs("div",{className:"agent-log-tool",children:[Z,t.jsxs("div",{className:"agent-log-tool-title",children:["⚡ ",k.text]}),k.detail?t.jsx(Nc,{detail:k.detail,type:"tool"}):null]},P.key);if(k.type==="tool_result")return t.jsxs("div",{className:"agent-log-tool-result",children:[Z,t.jsxs("div",{className:"agent-log-tool-title",children:["✓ ",k.text]}),k.detail?t.jsx(Nc,{detail:k.detail,type:"tool_result"}):null]},P.key);if(k.type==="tool_error")return t.jsxs("div",{className:"agent-log-tool-error",children:[Z,t.jsxs("div",{className:"agent-log-tool-title",children:["✗ ",k.text]}),k.detail?t.jsx(Nc,{detail:k.detail,type:"tool_error"}):null]},P.key)}const z=P.kind==="single"?O.text:P.entries.map(k=>k.text).join("");return P.kind==="thinking"?t.jsxs("div",{className:"agent-log-thinking",children:[Z,g?t.jsx("div",{className:"markdown-body",children:t.jsx(vi,{remarkPlugins:[yi],components:xh,children:z})}):t.jsx("pre",{className:"agent-log-plain-block",children:z})]},P.key):t.jsxs("div",{className:"agent-log-text",children:[Z,g?t.jsx("div",{className:"markdown-body",children:t.jsx(vi,{remarkPlugins:[yi],components:xh,children:z})}):t.jsx("pre",{className:"agent-log-plain-block",children:z})]},P.key)}),!C&&t.jsxs("button",{type:"button",className:"agent-log-return-to-live",onClick:T,"data-testid":"agent-log-return-to-live",children:[t.jsx(un,{size:12}),t.jsx("span",{children:"Live"})]})]})]})}function za(e){return e??void 0}function So(e){return{provider:za(e.modelProvider),modelId:za(e.modelId)}}function Co(e){return{provider:za(e.validatorModelProvider),modelId:za(e.validatorModelId)}}function Eo(e){return{provider:za(e.planningModelProvider),modelId:za(e.planningModelId)}}function LA(e,n){return Nf(e,n)}function OA(e,n){return Sf(e,n)}function zA(e,n){return Cf(e,n)}function Sc(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 Cc(e){return e.provider&&e.modelId?`${e.provider}/${e.modelId}`:""}function Ec(e,n){return e.provider===n.provider&&e.modelId===n.modelId}function FA(e,n){const a={executor:"Executor",validator:"Reviewer",planning:"Planning"}[e]||e;return!n.provider||!n.modelId?`${a} model set to default`:`${a} model set to ${n.provider}/${n.modelId}`}function UA({task:e,addToast:n,onTaskUpdated:s,settings:a}){const[r,o]=i.useState([]),[l,c]=i.useState([]),[d,u]=i.useState([]),[m,h]=i.useState(!1),[f,p]=i.useState(null),[g,x]=i.useState(()=>So(e)),[v,b]=i.useState(()=>So(e)),[y,j]=i.useState(()=>Co(e)),[C,A]=i.useState(()=>Co(e)),[N,S]=i.useState(()=>Eo(e)),[_,T]=i.useState(()=>Eo(e)),[M,E]=i.useState(()=>e.thinkingLevel??null),[L,F]=i.useState(()=>e.thinkingLevel??null),[R,P]=i.useState(null),O=i.useRef(e.id);i.useEffect(()=>{h(!0),p(null),Ms().then(ie=>{o(ie.models),c(ie.favoriteProviders),u(ie.favoriteModels)}).catch(ie=>{p(ie.message||"Failed to load models")}).finally(()=>{h(!1)})},[]);const q=i.useCallback(async ie=>{const ge=l,Ae=ge.includes(ie)?ge.filter(xe=>xe!==ie):[ie,...ge];c(Ae);try{await _n({favoriteProviders:Ae,favoriteModels:d})}catch{c(ge),n("Failed to update favorites","error")}},[l,d,n]),Z=i.useCallback(async ie=>{const ge=d,Ae=ge.includes(ie)?ge.filter(xe=>xe!==ie):[ie,...ge];u(Ae);try{await _n({favoriteProviders:l,favoriteModels:Ae})}catch{u(ge),n("Failed to update model favorites","error")}},[d,l,n]);i.useEffect(()=>{O.current=e.id;const ie=So(e),ge=Co(e),se=Eo(e);x(ie),b(ie),j(ge),A(ge),S(se),T(se);const Ae=e.thinkingLevel??null;E(Ae),F(Ae),P(null)},[e.id,e.modelProvider,e.modelId,e.validatorModelProvider,e.validatorModelId,e.planningModelProvider,e.planningModelId,e.thinkingLevel]);const z=i.useMemo(()=>Cc(g),[g]),k=i.useMemo(()=>Cc(y),[y]),I=i.useMemo(()=>Cc(N),[N]),$=i.useMemo(()=>LA(e,a),[e,a]),w=i.useMemo(()=>OA(e,a),[e,a]),H=i.useMemo(()=>zA(e,a),[e,a]),K=R!==null,pe=i.useCallback(async(ie,ge)=>{const se=e.id,Ae=v,xe=C,Se=_;P(ie);try{const qe=s?ie==="executor"?{modelProvider:ge.provider??null,modelId:ge.modelId??null}:ie==="validator"?{validatorModelProvider:ge.provider??null,validatorModelId:ge.modelId??null}:{planningModelProvider:ge.provider??null,planningModelId:ge.modelId??null}:{modelProvider:(ie==="executor"?ge:v).provider??null,modelId:(ie==="executor"?ge:v).modelId??null,validatorModelProvider:(ie==="validator"?ge:C).provider??null,validatorModelId:(ie==="validator"?ge:C).modelId??null,planningModelProvider:(ie==="planning"?ge:_).provider??null,planningModelId:(ie==="planning"?ge:_).modelId??null},We=await ni(se,qe);if(O.current!==se)return;const Qe=So(We),ve=Co(We),Oe=Eo(We);b(Qe),x(Qe),A(ve),j(ve),T(Oe),S(Oe),s?.(We),n(FA(ie,{executor:Qe,validator:ve,planning:Oe}[ie]),"success")}catch(qe){if(O.current!==se)return;ie==="executor"?x(Ae):ie==="validator"?j(xe):S(Se),n(_e(qe)||"Failed to save model settings","error")}finally{O.current===se&&P(null)}},[e.id,v,C,_,n,s]),le=i.useCallback(ie=>{const ge=Sc(ie);x(ge),!Ec(ge,v)&&pe("executor",ge)},[v,pe]),B=i.useCallback(ie=>{const ge=Sc(ie);j(ge),!Ec(ge,C)&&pe("validator",ge)},[C,pe]),ye=i.useCallback(ie=>{const ge=Sc(ie);S(ge),!Ec(ge,_)&&pe("planning",ge)},[_,pe]),U=i.useCallback(async ie=>{const ge=e.id,se=L,Ae=ie===""?null:ie;E(Ae),P("thinking");try{const xe=await ni(ge,{thinkingLevel:Ae});if(O.current!==ge)return;const Se=xe.thinkingLevel??null;F(Se),E(Se),s?.(xe);const qe=a?.defaultThinkingLevel??"off";n(Se===null?`Thinking level set to default (${qe})`:`Thinking level set to ${Se}`,"success")}catch(xe){if(O.current!==ge)return;E(se),n(_e(xe)||"Failed to save thinking level","error")}finally{O.current===ge&&P(null)}},[e.id,L,a,n,s]),te=!v.provider&&!v.modelId,ne=!C.provider&&!C.modelId,ee=!_.provider&&!_.modelId;return t.jsxs("div",{className:"model-selector-tab",children:[t.jsx("h4",{children:"Model Configuration"}),t.jsx("p",{className:"model-selector-intro",children:"Override the AI models used for this task. When not specified, project or global defaults are used."}),m?t.jsx("div",{className:"model-selector-loading",children:"Loading available models…"}):f?t.jsxs("div",{className:"model-selector-error",children:["Error loading models: ",f,t.jsx("button",{className:"btn btn-sm",onClick:()=>{h(!0),p(null),Ms().then(ie=>{o(ie.models),c(ie.favoriteProviders),u(ie.favoriteModels)}).catch(ie=>p(ie.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:te?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",$.provider&&$.modelId?` (${$.provider}/${$.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[v.provider&&t.jsx(qn,{provider:v.provider,size:"sm"}),v.provider,"/",v.modelId]})}),t.jsx(hs,{id:"executorModel",label:"Executor Model",value:z,onChange:le,models:r,disabled:K,placeholder:"Select executor model…",favoriteProviders:l,onToggleFavorite:q,favoriteModels:d,onToggleModelFavorite:Z}),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:ne?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",w.provider&&w.modelId?` (${w.provider}/${w.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[C.provider&&t.jsx(qn,{provider:C.provider,size:"sm"}),C.provider,"/",C.modelId]})}),t.jsx(hs,{id:"validatorModel",label:"Reviewer Model",value:k,onChange:B,models:r,disabled:K,placeholder:"Select reviewer model…",favoriteProviders:l,onToggleFavorite:q,favoriteModels:d,onToggleModelFavorite:Z}),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:ee?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",H.provider&&H.modelId?` (${H.provider}/${H.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[_.provider&&t.jsx(qn,{provider:_.provider,size:"sm"}),_.provider,"/",_.modelId]})}),t.jsx(hs,{id:"planningModel",label:"Planning Model",value:I,onChange:ye,models:r,disabled:K,placeholder:"Select planning model…",favoriteProviders:l,onToggleFavorite:q,favoriteModels:d,onToggleModelFavorite:Z}),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:L===null?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default (",a?.defaultThinkingLevel??"off",")"]}):t.jsx("span",{className:"model-badge model-badge-custom",children:L})}),t.jsxs("select",{id:"thinkingLevel",value:M??"",onChange:ie=>U(ie.target.value),disabled:K,className:"thinking-level-select",children:[t.jsxs("option",{value:"",children:["Default (",a?.defaultThinkingLevel??"off",")"]}),t.jsx("option",{value:"off",children:"Off"}),t.jsx("option",{value:"minimal",children:"Minimal"}),t.jsx("option",{value:"low",children:"Low"}),t.jsx("option",{value:"medium",children:"Medium"}),t.jsx("option",{value:"high",children:"High"})]}),t.jsx("small",{children:"Controls the reasoning effort for the AI agent. Higher levels use more tokens."})]}),t.jsx("div",{className:"model-selector-status",children:te&&ne&&ee&&L===null?"Using project or global default models.":"Model settings are up to date."})]})]})}const BA={open:t.jsx(xl,{size:16}),closed:t.jsx(Vr,{size:16}),merged:t.jsx(Zp,{size:16})};function HA({taskId:e,projectId:n,prInfo:s,automationStatus:a,autoMerge:r=!1,prAuthAvailable:o,onPrCreated:l,onPrUpdated:c,addToast:d}){const[u,m]=i.useState(!1),[h,f]=i.useState(""),[p,g]=i.useState(""),[x,v]=i.useState(!1),[b,y]=i.useState(!1),[j,C]=i.useState(null),A=i.useCallback(async()=>{if(h.trim()){v(!0);try{const T=await Qw(e,{title:h.trim(),body:p.trim()||void 0},n);l(T),m(!1),f(""),g(""),d(`Created PR #${T.number}`,"success")}catch(T){d(_e(T)||"Failed to create PR","error")}finally{v(!1)}}},[e,h,p,n,l,d]),N=i.useCallback(async()=>{if(s){y(!0);try{const T=await Xw(e,n);C(T),c(T.prInfo),d("PR status refreshed","success")}catch(T){d(_e(T)||"Failed to refresh PR","error")}finally{y(!1)}}},[e,s,n,c,d]);if(!s)return a==="creating-pr"?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(zs,{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(zs,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsx("div",{className:"pr-hint pr-hint--muted",children:"Auto-merge will handle this task automatically."})]}):u?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(zs,{size:16,className:"pr-section-icon"}),"Create Pull Request"]}),t.jsxs("div",{className:"pr-form",children:[t.jsx("input",{type:"text",placeholder:"PR title",value:h,onChange:T=>f(T.target.value),disabled:x,className:"pr-input"}),t.jsx("textarea",{placeholder:"PR description (optional)",value:p,onChange:T=>g(T.target.value),disabled:x,className:"pr-textarea",rows:3}),t.jsxs("div",{className:"pr-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>m(!1),disabled:x,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:A,disabled:!h.trim()||x,children:x?"Creating…":"Create PR"})]})]})]}):t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(zs,{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(Sn,{size:14,className:"pr-section-icon--sm"}),"Create PR"]}),!o&&t.jsxs("div",{className:"pr-hint pr-hint--subtle",children:["Run ",t.jsx("code",{children:"gh auth login"})," to enable PR creation."]})]});const S=BA[s.status]??t.jsx(xl,{size:16}),_=j?.blockingReasons??[];return t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(zs,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsxs("div",{className:`pr-card pr-card--status-${s.status}`,children:[t.jsxs("div",{className:"pr-header",children:[t.jsx("span",{className:"pr-status-icon",children:S}),t.jsx("span",{className:`pr-status-badge pr-status-badge--${s.status}`,children:s.status}),t.jsxs("span",{className:"pr-number",children:["#",s.number]}),t.jsx("div",{className:"pr-spacer"}),t.jsx("button",{className:"btn btn-sm pr-refresh-btn",onClick:N,disabled:b,title:"Refresh PR status",children:t.jsx(ns,{size:14,style:{verticalAlign:"middle",opacity:b?.5:1}})})]}),t.jsx("div",{className:"pr-title",children:s.title}),t.jsxs("div",{className:"pr-meta",children:[t.jsx("span",{children:s.headBranch}),t.jsx("span",{className:"pr-meta-arrow",children:"→"}),t.jsx("span",{children:s.baseBranch})]}),a==="merging-pr"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:"fn is merging this pull request automatically."}),a==="awaiting-pr-checks"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:_.length>0?`Waiting for: ${_.join("; ")}`:"Waiting for required checks or review feedback before auto-merge."}),s.status==="merged"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:"This PR is merged. fn will finish local cleanup and move the task to Done."}),t.jsxs("div",{className:"pr-footer",children:[s.commentCount>0&&t.jsxs("span",{className:"pr-comments",children:[t.jsx(Ei,{size:14}),s.commentCount]}),t.jsxs("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"pr-link",children:[t.jsx(Ix,{size:14}),"View on GitHub"]})]})]})]})}const yh=2e3;function qA(e){const n=e.updatedAt||e.createdAt,s=new Date(n).toLocaleString();return e.updatedAt?`${s} (edited)`:s}function VA(e){return e==="agent"||e==="system"}function WA({task:e,onTaskUpdated:n,addToast:s,currentAuthor:a="user",projectId:r}){const[o,l]=i.useState(""),[c,d]=i.useState(null),[u,m]=i.useState(""),[h,f]=i.useState(!1),[p,g]=i.useState(null),x=i.useMemo(()=>[...e.comments||[]].sort((S,_)=>new Date(_.createdAt).getTime()-new Date(S.createdAt).getTime()),[e.comments]),v=o.length>yh;async function b(){const S=o.trim();if(S){f(!0);try{const _=await kw(e.id,S,r);l(""),n?.(_),s("Comment added","success")}catch(_){s(_e(_)||"Failed to add comment","error")}finally{f(!1)}}}async function y(S){const _=u.trim();if(_){f(!0);try{const T=await bw(e.id,S,_,r);d(null),m(""),n?.(T),s("Comment updated","success")}catch(T){s(_e(T)||"Failed to update comment","error")}finally{f(!1)}}}async function j(S){g(S);try{const _=await xw(e.id,S,r);n?.(_),s("Comment deleted","success")}catch(_){s(_e(_)||"Failed to delete comment","error")}finally{g(null)}}function C(S){S.key==="Enter"&&(S.ctrlKey||S.metaKey)&&(S.preventDefault(),b())}return t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Comments"}),x.length===0?t.jsx("div",{className:"detail-log-empty",children:"No comments yet."}):t.jsx("div",{className:"detail-activity-list",children:x.map(S=>{const _=S.author===a,T=c===S.id,M=VA(S.author);return t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header comments-header-row",children:[t.jsxs("div",{className:"comments-author-row",children:[M?t.jsx("span",{className:"ai-guidance-badge","data-testid":"ai-guidance-badge",children:"AI Guidance"}):t.jsx("strong",{children:S.author}),t.jsx("span",{className:"detail-log-timestamp",children:qA(S)})]}),_&&!T?t.jsxs("div",{className:"comments-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{d(S.id),m(S.text)},children:"Edit"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void j(S.id),disabled:p===S.id,children:p===S.id?"Deleting…":"Delete"})]}):null]}),T?t.jsxs("div",{className:"comments-edit-form",children:[t.jsx("textarea",{value:u,onChange:E=>m(E.target.value),rows:3,className:"comments-textarea"}),t.jsxs("div",{className:"comments-edit-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{d(null),m("")},disabled:h,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void y(S.id),disabled:h||!u.trim(),children:"Save"})]})]}):t.jsx("div",{className:"detail-log-outcome comments-outcome-text",children:S.text})]},S.id)})}),t.jsxs("div",{className:"comments-compose-form",children:[t.jsx("textarea",{value:o,onChange:S=>l(S.target.value),onKeyDown:C,rows:3,placeholder:"Add a comment",className:"comments-textarea"}),t.jsxs("div",{className:"comments-footer-row",children:[t.jsxs("span",{className:`comments-char-count${v?" comments-char-count--over":""}`,children:[o.length," / ",yh]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void b(),disabled:h||!o.trim()||v,children:h?"Posting…":"Add Comment"})]})]})]})}function KA(e){return e?e.slice(0,7):"Unknown"}function GA({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:KA(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(`
673
+ `).map((s,a)=>{let r="";return s.startsWith("+")&&!s.startsWith("+++")?r="diff-add":s.startsWith("-")&&!s.startsWith("---")?r="diff-del":s.startsWith("@@")&&(r="diff-hunk"),r?t.jsx("span",{className:r,children:`${s}
674
+ `},a):t.jsx(Jo.Fragment,{children:`${s}
675
+ `},a)})}function JA(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function YA({isOpen:e,taskId:n,files:s,stats:a,mergeDetails:r,column:o,onClose:l,onRefresh:c}){const[d,u]=i.useState(null),[m,h]=i.useState(!0),f=i.useRef(null);wi(f,e,"fusion:changes-diff-modal-size");const p=Ri(l);i.useEffect(()=>{s.length>0&&d===null&&u(0)},[s,d]);const g=i.useCallback(()=>{u(y=>y!==null&&y>0?y-1:y)},[]),x=i.useCallback(()=>{u(y=>y!==null&&y<s.length-1?y+1:y)},[]);if(i.useEffect(()=>{if(!e)return;const y=j=>{if(j.key==="Escape"){l();return}j.key==="ArrowUp"&&(j.metaKey||j.ctrlKey)&&(j.preventDefault(),g()),j.key==="ArrowDown"&&(j.metaKey||j.ctrlKey)&&(j.preventDefault(),x())};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[e,l,g,x]),!e)return null;const v=d!==null?s[d]:null,b=o==="done";return t.jsx("div",{className:"modal-overlay open",...p,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal changes-diff-modal",ref:f,children:[t.jsxs("div",{className:"modal-header changes-diff-modal-header",children:[t.jsxs("div",{className:"changes-diff-header-title",children:[t.jsx(si,{size:18}),t.jsxs("span",{children:["Changes — ",n]}),t.jsxs("span",{className:"changes-stat-summary",children:[t.jsxs("span",{className:"diff-add",children:["+",a.additions]})," ",t.jsxs("span",{className:"diff-del",children:["-",a.deletions]})]})]}),t.jsxs("div",{className:"changes-diff-header-actions",children:[s.length>0&&t.jsxs("div",{className:"changes-nav",children:[t.jsx("button",{className:"btn btn-sm btn-icon",onClick:g,disabled:d===null||d<=0,title:"Previous file (Ctrl+↑)","aria-label":"Previous file",children:t.jsx(bl,{})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:d!==null?`${d+1}/${s.length}`:`—/${s.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:x,disabled:d===null||d>=s.length-1,title:"Next file (Ctrl+↓)","aria-label":"Next file",children:t.jsx(Tn,{})})]}),t.jsx("button",{className:`btn btn-sm ${m?"btn-primary":""}`,onClick:()=>h(y=>!y),title:m?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(Xo,{size:14})}),c&&t.jsxs("button",{className:"btn btn-sm",onClick:c,children:[t.jsx(ns,{size:14}),"Refresh"]}),t.jsx("button",{className:"modal-close",onClick:l,"aria-label":"Close",children:t.jsx(Jt,{size:20})})]})]}),t.jsxs("div",{className:"changes-diff-body",children:[t.jsxs("div",{className:"changes-diff-sidebar",children:[b&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(Wr,{size:14}),t.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergeCommitMessage&&t.jsx("div",{className:"commit-diff-message",children:r.mergeCommitMessage}),r.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),t.jsx("div",{className:"changes-diff-file-list",children:s.map((y,j)=>t.jsxs("button",{className:`changes-diff-file-item ${d===j?"selected":""}`,onClick:()=>u(j),title:y.path,children:[t.jsx("span",{className:`changes-file-status changes-file-status--${y.status}`,children: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(si,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to view its diff"})]})})]})]})})}function Jg(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function Mc(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(Wr,{size:14}),t.jsx("code",{children:s.commitSha.slice(0,7)})]}),s.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(s.mergedAt).toLocaleString()]})]}),t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(si,{size:24}),t.jsxs("p",{children:[e.length," file",e.length===1?"":"s"," modified during execution."]}),t.jsx("span",{className:"task-changes-state-hint",children:n?"The recorded merge commit has no diff (likely collapsed into a squash on main). Showing file paths only — patches unavailable.":"The live worktree diff is empty. Showing the last file paths captured during execution — patches unavailable."})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:e.map(a=>t.jsx("div",{className:"changes-file-item",children:t.jsxs("div",{className:"changes-file-header changes-file-header--static",children:[t.jsx("span",{className:"changes-file-status changes-file-status--unknown",title:"status unknown",children:Jg("unknown")}),t.jsx("span",{className:"changes-file-path",title:a,children:t.jsx("bdo",{dir:"ltr",children:a})})]})},a))})]})}function QA({taskId:e,worktree:n,projectId:s,column:a,mergeDetails:r,modifiedFiles:o}){const[l,c]=i.useState([]),[d,u]=i.useState({filesChanged:0,additions:0,deletions:0}),[m,h]=i.useState(!0),[f,p]=i.useState(null),[g,x]=i.useState(new Set),[v,b]=i.useState(null),[y,j]=i.useState(!0),[C,A]=i.useState(!1),N=a==="done",S=N&&!!r?.commitSha,_=a==="in-progress"||a==="in-review"||S,T=i.useCallback(async()=>{if(!_){h(!1);return}try{h(!0),p(null);const R=await ff(e,void 0,s),P=R.files.map(O=>({path:O.path,status:O.status,additions:O.additions,deletions:O.deletions,patch:O.patch}));c(P),u(R.stats),P.length>0&&(x(new Set([P[0].path])),b(0))}catch(R){p(_e(R)||"Failed to load diff")}finally{h(!1)}},[e,s,_]);i.useEffect(()=>{T()},[T]);const M=R=>{x(P=>{const O=new Set(P);if(O.has(R))O.delete(R);else{O.add(R);const q=l.findIndex(Z=>Z.path===R);q!==-1&&b(q)}return O})},E=R=>{if(R<0||R>=l.length)return;const P=l[R].path;x(new Set([P])),b(R)},L=v!==null&&v>0,F=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(Rs,{size:16}),t.jsxs("span",{children:["Error loading changes: ",f]})]})});if(!N&&!n)return o&&o.length>0?Mc(o,!1):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(si,{size:24}),t.jsx("p",{children:"No worktree available for this task."}),t.jsx("span",{className:"task-changes-state-hint",children:"Changes will be shown once the task is in progress."})]})});if(N&&!S){if(o&&o.length>0)return Mc(o,!0,r);const R=r?.filesChanged,P=r?.insertions,O=r?.deletions,q=R!=null||P!=null||O!=null;return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(si,{size:24}),t.jsx("p",{children:"Detailed file changes unavailable."}),t.jsx("span",{className:"task-changes-state-hint",children:q?`Merge summary: ${R??0} file${(R??0)===1?"":"s"} changed, +${P??0} additions, -${O??0} deletions.`:"No merge commit was recorded for this task."})]})})}return l.length===0?o&&o.length>0?Mc(o,N,r):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(si,{size:24}),t.jsx("p",{children:"No files modified."}),t.jsx("span",{className:"task-changes-state-hint",children:N?"No file changes were recorded in the merge commit.":"The agent did not modify any files during execution."})]})}):t.jsxs("div",{className:"detail-section task-changes-tab",children:[N&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(Wr,{size:14}),t.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergeCommitMessage&&t.jsx("div",{className:"commit-diff-message",children:r.mergeCommitMessage}),r.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),t.jsxs("div",{className:"changes-header",children:[t.jsxs("div",{className:"task-changes-header-title",children:[t.jsxs("h4",{children:[t.jsx(si,{size:16}),"Files Changed (",d.filesChanged,")"]}),t.jsxs("span",{className:"task-changes-stats changes-stat-summary",children:[t.jsxs("span",{className:"diff-add",children:["+",d.additions]})," ",t.jsxs("span",{className:"diff-del",children:["-",d.deletions]})]})]}),t.jsxs("div",{className:"changes-header-actions-wrapper",children:[t.jsxs("div",{className:"changes-header-actions",children:[l.length>0&&t.jsxs("div",{className:"changes-nav",children:[t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>L&&E(v-1),disabled:!L,title:"Previous file","aria-label":"Previous file",children:t.jsx(bl,{})}),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:()=>F&&E(v+1),disabled:!F,title:"Next file","aria-label":"Next file",children:t.jsx(Tn,{})})]}),t.jsx("button",{className:`btn btn-sm ${y?"btn-primary":""}`,onClick:()=>j(R=>!R),title:y?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(Xo,{size:14})})]}),t.jsxs("div",{className:"changes-header-actions-secondary",children:[t.jsx("button",{className:"btn btn-sm",onClick:T,disabled:m,children:"Refresh"}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>A(!0),title:"Expand to full-screen diff view","aria-label":"Expand diff view",children:t.jsx(Nl,{})})]})]})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:l.map(R=>{const P=g.has(R.path);return t.jsxs("div",{className:`changes-file-item ${P?"expanded":""}`,children:[t.jsxs("button",{className:"changes-file-header",onClick:()=>M(R.path),children:[t.jsx("span",{className:"changes-file-toggle",children:P?t.jsx(un,{size:14}):t.jsx(Tn,{size:14})}),t.jsx("span",{className:`changes-file-status changes-file-status--${R.status}`,title:R.status,children:Jg(R.status)}),t.jsx("span",{className:"changes-file-path",title:R.path,children:t.jsx("bdo",{dir:"ltr",children:R.path})}),t.jsxs("span",{className:"changes-file-stat",title:`+${R.additions} -${R.deletions}`,children:["+",R.additions," -",R.deletions]})]}),P&&R.patch&&t.jsx("div",{className:"changes-file-content",children:t.jsx("pre",{className:`changes-diff-patch ${y?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:t.jsx("code",{children:Gg(R.patch)})})})]},R.path)})}),t.jsx(YA,{isOpen:C,taskId:e,files:l,stats:d,mergeDetails:r,column:a,onClose:()=>A(!1),onRefresh:T})]})}function wh(e){return{executorValue:e?.executorProvider&&e?.executorModelId?`${e.executorProvider}/${e.executorModelId}`:"",validatorValue:e?.validatorProvider&&e?.validatorModelId?`${e.validatorProvider}/${e.validatorModelId}`:""}}function XA(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function Wz(e,n){const s=XA(e),a=new Set(n.map(c=>c.id));if(!a.has(s))return s;const r=30;let o=s,l=1;for(;a.has(o)&&l<100;){const c=`-${l}`;o=`${s.slice(0,r-c.length)}${c}`,l++}return o}function ZA(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}const kh=["image/png","image/jpeg","image/gif","image/webp"];function eP(e,n,s){const a=e==="post-merge"?"phase-badge--post-merge":"phase-badge--pre-merge";return t.jsx("span",{className:`phase-badge ${a}`,"data-testid":`${s}-${n}`,children:e==="post-merge"?"Post-merge":"Pre-merge"})}function Yg({mode:e,description:n,onDescriptionChange:s,title:a,onTitleChange:r,dependencies:o,onDependenciesChange:l,nodeId:c,onNodeIdChange:d,nodeOptions:u,nodeOverrideDisabled:m=!1,nodeOverrideDisabledReason:h,priority:f,onPriorityChange:p,executorModel:g,onExecutorModelChange:x,validatorModel:v,onValidatorModelChange:b,planningModel:y,onPlanningModelChange:j,thinkingLevel:C,onThinkingLevelChange:A,presetMode:N,onPresetModeChange:S,selectedPresetId:_,onSelectedPresetIdChange:T,selectedWorkflowSteps:M,onWorkflowStepsChange:E,onDefaultOnApplied:L,pendingImages:F,onImagesChange:R,tasks:P,projectId:O,disabled:q=!1,addToast:Z,isActive:z=!0,onAutoSaveDescription:k,onPlanningMode:I,onSubtaskBreakdown:$,onClose:w,renderBelowPrimary:H,renderBelowModelConfiguration:K,hideDependencies:pe,autoExpandMoreOptionsOnSelection:le=!0,reviewLevel:B,onReviewLevelChange:ye,executionMode:U,onExecutionModeChange:te}){const ne=(pe?!1:o.length>0)||F.length>0||M.length>0||N!=="default"||(f??Cs)!==Cs||g!==""||v!==""||(y||"")!==""||(C||"")!==""||B!==void 0||U==="fast"||(c||"")!=="",[ee,ie]=i.useState(!1),[ge,se]=i.useState(le?ne:!1),[Ae,xe]=i.useState(""),[Se,qe]=i.useState([]),[We,Qe]=i.useState([]),[ve,Oe]=i.useState([]),[ae,re]=i.useState(!1),[je,Q]=i.useState(null),[Fe,Je]=i.useState([]),[be,ze]=i.useState("idle"),[tt,kt]=i.useState(!1),[ke,ce]=i.useState(!1),[Te,he]=i.useState(!1),Le=i.useRef(null),st=i.useRef(null),it=i.useRef(null),lt=i.useRef(null),$e=i.useRef(null),Ue=i.useRef(null),Xe=i.useRef(null),wt=i.useRef(!1),Re=i.useRef(ne),xt=i.useRef(n.trim()),Pt=i.useRef(n.trim());i.useEffect(()=>{z&&(re(!0),Ms().then(J=>{qe(J.models),Qe(J.favoriteProviders),Oe(J.favoriteModels)}).catch(()=>{}).finally(()=>re(!1)),El(O).then(J=>Q(J)).catch(()=>Q(null)),Yr(O).then(J=>Je(J.filter(Ie=>Ie.enabled))).catch(()=>Je([])))},[z,O]);const Ct=je?.modelPresets||[],Ot=Ct.find(J=>J.id===_),zt=(pe?!1:o.length>0)||F.length>0||M.length>0||N!=="default"||(f??Cs)!==Cs||g!==""||v!==""||(y||"")!==""||(C||"")!==""||B!==void 0||U==="fast"||(c||"")!=="";i.useEffect(()=>{if(e!=="create"||!z||!je?.autoSelectModelPreset)return;const J=(je.defaultPresetBySize,void 0);if(J){const Ie=wh(J);T(J.id),S("preset"),x(Ie.executorValue),b(Ie.validatorValue)}},[z,je,Ct,e]);const Nt=i.useRef(!1);i.useEffect(()=>{if(e!=="create"||!z||Nt.current||Fe.length===0)return;const J=Fe.filter(de=>de.defaultOn);if(J.length===0)return;Nt.current=!0;const Ie=J.map(de=>de.id);E(Ie),L?.(Ie)},[e,z,Fe]),i.useEffect(()=>{z||(Nt.current=!1)},[z]),i.useEffect(()=>{if(!le){Re.current=zt;return}zt&&!Re.current&&se(!0),Re.current=zt},[zt,le]),i.useEffect(()=>{ge||(ie(!1),xe(""))},[ge]),i.useEffect(()=>{e!=="edit"||!z||lt.current&&(lt.current.focus(),lt.current.select())},[e,z]),i.useEffect(()=>{if(!ee)return;const J=Ie=>{st.current&&!st.current.contains(Ie.target)&&ie(!1)};return document.addEventListener("mousedown",J),()=>document.removeEventListener("mousedown",J)},[ee]),i.useEffect(()=>{(e!=="edit"||q)&&he(!1)},[e,q]),i.useEffect(()=>{if(e!=="edit"){ze("idle");return}const J=n.trim();xt.current=J,Pt.current=J,ze("idle")},[e]),i.useEffect(()=>{if(e!=="edit"||!k||!z)return;const J=n.trim(),Ie=xt.current;if(J===Ie||J===Pt.current){Ue.current&&(clearTimeout(Ue.current),Ue.current=null),wt.current||ze("idle");return}return Ue.current&&clearTimeout(Ue.current),Ue.current=setTimeout(async()=>{if(!wt.current){wt.current=!0,ze("saving");try{await k(J),Pt.current=J,ze("saved"),Xe.current&&clearTimeout(Xe.current),Xe.current=setTimeout(()=>{ze("idle"),Xe.current=null},2e3)}catch{ze("idle")}finally{wt.current=!1,Ue.current=null}}},1500),()=>{Ue.current&&(clearTimeout(Ue.current),Ue.current=null)}},[e,n,k,z]),i.useEffect(()=>()=>{Ue.current&&clearTimeout(Ue.current),Xe.current&&clearTimeout(Xe.current)},[]),i.useEffect(()=>{if(!tt)return;const J=Ie=>{Le.current&&!Le.current.contains(Ie.target)&&kt(!1)};return document.addEventListener("mousedown",J),()=>document.removeEventListener("mousedown",J)},[tt]);const jt=i.useCallback(J=>{const Ie=J.clipboardData?.items;if(Ie)for(let de=0;de<Ie.length;de++){const Ne=Ie[de];if(Ne.type.startsWith("image/")){const Ye=Ne.getAsFile();if(Ye&&kh.includes(Ye.type)){J.preventDefault(),R([...F,{file:Ye,previewUrl:URL.createObjectURL(Ye)}]);return}}}},[F,R]),Yt=i.useCallback(J=>{J.preventDefault();const Ie=J.dataTransfer.files;for(let de=0;de<Ie.length;de++){const Ne=Ie[de];if(kh.includes(Ne.type)){R([...F,{file:Ne,previewUrl:URL.createObjectURL(Ne)}]);return}}},[F,R]),Bt=i.useCallback(J=>{const Ie=F[J];Ie&&URL.revokeObjectURL(Ie.previewUrl),R(F.filter((de,Ne)=>Ne!==J))},[F,R]),qt=i.useCallback(J=>{l(o.includes(J)?o.filter(Ie=>Ie!==J):[...o,J])},[o,l]),wn=(J,Ie)=>J.length>Ie?J.slice(0,Ie)+"…":J,mn=i.useCallback(J=>{s(J.target.value);const Ie=J.target;Ie.style.height="auto",Ie.style.height=Ie.scrollHeight+"px"},[s]),Xt=i.useCallback(()=>{he(J=>!J)},[]),Vt=i.useCallback(J=>{!Te||J.key!=="Escape"||(J.preventDefault(),J.stopPropagation(),he(!1))},[Te]),Ft=i.useCallback(async J=>{const Ie=n.trim();if(!(!Ie||ke)){ce(!0);try{const de=await uf(Ie,J,O);s(de),kt(!1),Z("Description refined with AI","success"),it.current&&(it.current.style.height="auto",it.current.style.height=it.current.scrollHeight+"px")}catch(de){const Ne=mf(de);Z(Ne,"error")}finally{ce(!1)}}},[n,ke,Z,s,O]),Zt=i.useCallback(async J=>{const Ie=We,Ne=Ie.includes(J)?Ie.filter(Ye=>Ye!==J):[J,...Ie];Qe(Ne);try{await _n({favoriteProviders:Ne,favoriteModels:ve})}catch{Qe(Ie)}},[We,ve]),en=i.useCallback(async J=>{const Ie=ve,Ne=Ie.includes(J)?Ie.filter(Ye=>Ye!==J):[J,...Ie];Oe(Ne);try{await _n({favoriteProviders:We,favoriteModels:Ne})}catch{Oe(Ie)}},[ve,We]),cn=i.useCallback(J=>{if(J<=0)return;const Ie=[...M];[Ie[J-1],Ie[J]]=[Ie[J],Ie[J-1]],E(Ie)},[M,E]),we=i.useCallback(J=>{if(J>=M.length-1)return;const Ie=[...M];[Ie[J],Ie[J+1]]=[Ie[J+1],Ie[J]],E(Ie)},[M,E]),De=i.useCallback(J=>{E(M.filter(Ie=>Ie!==J))},[M,E]),oe=new Map;for(const J of Fe)oe.set(J.id,{name:J.name,description:J.description});const Pe=P.filter(J=>!o.includes(J.id)).sort((J,Ie)=>{const de=Ie.createdAt.localeCompare(J.createdAt);if(de!==0)return de;const Ne=parseInt(J.id.slice(J.id.lastIndexOf("-")+1),10)||0;return(parseInt(Ie.id.slice(Ie.id.lastIndexOf("-")+1),10)||0)-Ne}),Ce=Ae?Pe.filter(J=>J.id.toLowerCase().includes(Ae.toLowerCase())||J.title&&J.title.toLowerCase().includes(Ae.toLowerCase())||J.description&&J.description.toLowerCase().includes(Ae.toLowerCase())):Pe;return t.jsxs("div",{className:"task-form",onDrop:Yt,onDragOver:J=>J.preventDefault(),onPaste:jt,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:lt,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:"Task title",value:a||"",onChange:J=>r(J.target.value),disabled:q})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:"task-form-description",className:"description-label-row",children:[t.jsx("span",{children:"Description"}),t.jsx("span",{className:`description-auto-save-status${be==="idle"?"":" is-visible"}`,"aria-live":"polite",children:be==="saving"?"Saving...":be==="saved"?"Saved":""})]}),t.jsxs("div",{className:`description-with-refine${Te?" description--fullscreen":""}`,ref:Le,onKeyDown:Vt,children:[Te&&t.jsxs("div",{className:"description-fullscreen-header",children:[t.jsx("span",{children:"Editing Description"}),t.jsx("button",{type:"button",className:"btn btn-sm description-expand-btn",onClick:Xt,"aria-label":"Collapse description",title:"Collapse description",children:t.jsx(Kr,{size:14})})]}),t.jsx("textarea",{ref:it,autoFocus:e==="create",id:"task-form-description",value:n,onChange:mn,placeholder:"What needs to be done?",rows:e==="edit"?8:5,disabled:q||ke}),(()=>{const J=!!n.trim()&&!q;return t.jsxs(t.Fragment,{children:[!Te&&t.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${J?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:Xt,"aria-label":"Expand description",title:"Expand description",children:t.jsx(Nl,{size:14})}),J&&t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${ke?"refine-button--loading":""}`,onClick:()=>kt(Ie=>!Ie),disabled:ke,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(ms,{size:12,style:{verticalAlign:"middle"}}),ke?"Refining...":"Refine"]})]})})(),tt&&t.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:J=>J.preventDefault(),children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>Ft("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:()=>Ft("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:()=>Ft("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:()=>Ft("simplify"),"data-testid":"refine-simplify",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Simplify"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Simplify and make more concise"})]})]})]})]}),e==="create"&&(I||$)&&t.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[I&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const J=n.trim();if(!J){Z("Enter a description first","error");return}w?.(),I(J)},disabled:q||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),$&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const J=n.trim();if(!J){Z("Enter a description first","error");return}w?.(),$(J)},disabled:q||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),H,t.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>se(J=>!J),"aria-expanded":ge,"aria-controls":"task-form-more-options",disabled:q,"data-testid":"task-form-more-options-toggle",children:[t.jsx("span",{children:"More options"}),ge?t.jsx(ri,{size:14}):t.jsx(un,{size:14})]}),t.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${ge?"":" collapsed"}`,"aria-hidden":!ge,hidden:!ge,"data-testid":"task-form-more-options",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Attachments"}),F.length>0&&t.jsx("div",{className:"inline-create-previews",children:F.map((J,Ie)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:J.previewUrl,alt:J.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>Bt(Ie),disabled:q,title:"Remove image",children:"×"})]},J.previewUrl))}),t.jsx("input",{ref:$e,type:"file",accept:"image/*",onChange:J=>{const Ie=J.target.files?.[0];Ie&&(R([...F,{file:Ie,previewUrl:URL.createObjectURL(Ie)}]),J.target.value="")},style:{display:"none"}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>$e.current?.click(),disabled:q,children:"Attach Screenshot"}),t.jsx("small",{children:"You can also paste images or drag & drop"})]}),d&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"task-node-select",children:"Execution Node Override"}),t.jsxs("select",{id:"task-node-select",className:"select",value:c??"",onChange:J=>d(J.target.value||void 0),disabled:q||m,children:[t.jsx("option",{value:"",children:"Use project default / local"}),(u??[]).map(J=>t.jsxs("option",{value:J.id,children:[J.name," (",ZA(J.status),")"]},J.id))]}),(()=>{const J=(u??[]).find(Ie=>Ie.id===c);return J?t.jsx("div",{className:"task-form-node-status",children:t.jsx(ia,{status:J.status,showLabel:!0})}):null})(),t.jsx("small",{children:h??"Task override takes priority over project default node routing."})]}),!pe&&t.jsx(t.Fragment,{children:t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"dep-trigger-wrap",ref:st,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>ie(J=>!J),disabled:q,children:o.length>0?`${o.length} selected`:"Add dependencies"}),ee&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Ae,onChange:J=>xe(J.target.value),onClick:J=>J.stopPropagation()}),Ce.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Ce.map(J=>t.jsxs("div",{className:`dep-dropdown-item${o.includes(J.id)?" selected":""}`,onClick:()=>qt(J.id),onMouseDown:Ie=>Ie.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:J.id}),t.jsx("span",{className:"dep-dropdown-title",children:wn(J.title||J.description||J.id,30)})]},J.id))]})]}),o.length>0&&t.jsx("div",{className:"selected-deps",children:o.map(J=>t.jsxs("span",{className:"dep-chip",children:[J,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>qt(J),disabled:q,children:"×"})]},J))})]})}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Model Configuration"}),p&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"task-priority",className:"model-select-label",children:"Priority"}),t.jsx("select",{id:"task-priority","data-testid":"task-priority-select",value:f??Cs,onChange:J=>p(J.target.value),disabled:q,children:Zr.map(J=>t.jsx("option",{value:J,children:J[0].toUpperCase()+J.slice(1)},J))})]}),te&&U!==void 0&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"task-execution-mode",className:"model-select-label",children:"Execution mode"}),t.jsxs("select",{id:"task-execution-mode","data-testid":"task-form-execution-mode-select",value:U,onChange:J=>te(J.target.value),disabled:q,children:[t.jsx("option",{value:"standard",children:"Standard"}),t.jsx("option",{value:"fast",children:"Fast"})]})]}),ae?t.jsx("div",{className:"model-selector-loading",children:"Loading models…"}):Se.length===0?t.jsx("small",{children:"No models available. Configure authentication in Settings."}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"model-preset",className:"model-select-label",children:"Preset"}),t.jsxs("select",{id:"model-preset",value:N==="preset"?_:N,onChange:J=>{const Ie=J.target.value;if(Ie==="default"){S("default"),T(""),x(""),b("");return}if(Ie==="custom"){S("custom"),T("");return}const de=Ct.find(Ye=>Ye.id===Ie),Ne=wh(de);S("preset"),T(Ie),x(Ne.executorValue),b(Ne.validatorValue)},disabled:q,children:[t.jsx("option",{value:"default",children:"Use default"}),Ct.length>0?t.jsx("option",{disabled:!0,children:"──────────"}):null,Ct.map(J=>t.jsx("option",{value:J.id,children:J.name},J.id)),t.jsx("option",{value:"custom",children:"Custom"})]})]}),N==="preset"&&Ot?t.jsxs("small",{children:["Using preset: ",Ot.name]}):null,N==="preset"?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>S("custom"),disabled:q,children:"Override"}):null,t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"executor-model",className:"model-select-label",children:"Executor"}),t.jsx(hs,{id:"executor-model",label:"Executor Model",value:g,onChange:J=>{S("custom"),T(""),x(J)},models:Se,disabled:q||N==="preset",favoriteProviders:We,onToggleFavorite:Zt,favoriteModels:ve,onToggleModelFavorite:en})]}),t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"validator-model",className:"model-select-label",children:"Reviewer"}),t.jsx(hs,{id:"validator-model",label:"Reviewer Model",value:v,onChange:J=>{S("custom"),T(""),b(J)},models:Se,disabled:q||N==="preset",favoriteProviders:We,onToggleFavorite:Zt,favoriteModels:ve,onToggleModelFavorite:en})]}),j&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"planning-model",className:"model-select-label",children:"Planning"}),t.jsx(hs,{id:"planning-model",label:"Planning Model",value:y||"",onChange:J=>{S("custom"),T(""),j(J)},models:Se,disabled:q||N==="preset",favoriteProviders:We,onToggleFavorite:Zt,favoriteModels:ve,onToggleModelFavorite:en})]}),A&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"thinking-level",className:"model-select-label",children:"Thinking"}),t.jsxs("select",{id:"thinking-level",value:C||"",onChange:J=>A(J.target.value),disabled:q||N==="preset",children:[t.jsxs("option",{value:"",children:["Default (",je?.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"})]})]}),ye&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"review-level",className:"model-select-label",children:"Review"}),t.jsxs("select",{id:"review-level",value:B??"",onChange:J=>ye(J.target.value===""?void 0:parseInt(J.target.value,10)),disabled:q,children:[t.jsx("option",{value:"",children:"Default (Auto — triage decides)"}),t.jsx("option",{value:"0",children:"0 — None"}),t.jsx("option",{value:"1",children:"1 — Plan Only"}),t.jsx("option",{value:"2",children:"2 — Plan and Code"}),t.jsx("option",{value:"3",children:"3 — Full"})]})]})]})]}),K,t.jsxs("div",{className:"form-group","data-testid":"workflow-steps-section",children:[t.jsx("label",{children:"Workflow Steps"}),t.jsxs("div",{className:"workflow-steps-section",children:[t.jsx("small",{className:"workflow-steps-description",children:"Select steps to run after task implementation completes"}),t.jsx("div",{className:"workflow-steps-list",children:Fe.length>0&&Fe.map(J=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${J.id}`,children:[t.jsx("input",{type:"checkbox",checked:M.includes(J.id),onChange:Ie=>{E(Ie.target.checked?[...M,J.id]:M.filter(de=>de!==J.id))},disabled:q}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[J.name,eP(J.phase||"pre-merge",J.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:J.description})]})]},J.id))})]}),M.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),M.map((J,Ie)=>{const de=oe.get(J);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${J}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:Ie+1}),t.jsx("span",{className:"workflow-step-order-name",children:de?.name||J}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>cn(Ie),disabled:q||Ie===0,"data-testid":`workflow-step-move-up-${J}`,title:"Move up",children:t.jsx(ri,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>we(Ie),disabled:q||Ie===M.length-1,"data-testid":`workflow-step-move-down-${J}`,title:"Move down",children:t.jsx(un,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>De(J),disabled:q,"data-testid":`workflow-step-remove-${J}`,title:"Remove",children:t.jsx(Jt,{})})]})]},J)})]})]})]})]})}const jh={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 tP(e){switch(e){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return e}}function nP(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 sP(e){return e?new Date(e).toLocaleString():null}function iP(e){const n=e.split(`
676
+ `);return n.length<=1?e:`${n.length} lines`}function Mo(e,n,s){const a=e==="post-merge"?"phase-badge--post-merge":"phase-badge--pre-merge";return t.jsx("span",{className:`phase-badge ${a}`,"data-testid":`${s}-${n}`,children:e==="post-merge"?"Post-merge":"Pre-merge"})}function aP({entries:e,startedAt:n,stepId:s}){const a=i.useRef(null),r=new Date(n).getTime(),o=e.filter(l=>new Date(l.timestamp).getTime()>=r);return i.useEffect(()=>{const l=a.current;l&&(l.scrollTop=l.scrollHeight)},[o.length]),e.length===0?t.jsx("div",{className:"workflow-live-log","data-testid":`workflow-live-log-${s}`,children:t.jsx("div",{className:"workflow-live-log-empty",children:"Waiting for agent output…"})}):t.jsx("div",{ref:a,className:"workflow-live-log","data-testid":`workflow-live-log-${s}`,children:o.map((l,c)=>l.type==="tool"?t.jsxs("div",{className:"workflow-live-log-tool",children:["⚡ ",l.text,l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",l.detail]})]},c):l.type==="tool_result"?t.jsxs("div",{className:"workflow-live-log-tool-result",children:["✓ ",l.text,l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",l.detail]})]},c):l.type==="tool_error"?t.jsxs("div",{className:"workflow-live-log-tool-error",children:["✗ ",l.text,l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",l.detail]})]},c):l.type==="thinking"?t.jsx("div",{className:"workflow-live-log-thinking",children:l.text},c):t.jsx("span",{className:"workflow-live-log-text",children:l.text},c))})}function rP({taskId:e,results:n,loading:s,enabledWorkflowSteps:a,canEdit:r,projectId:o,isTaskInProgress:l,onWorkflowStepsChange:c}){const[d,u]=i.useState({}),[m,h]=i.useState({}),[f,p]=i.useState(null),[g,x]=i.useState([]),[v,b]=i.useState(!1),y=n.some(w=>w.status==="pending"),{entries:j}=Wg(e,!!l&&y,o);i.useEffect(()=>{let w=!1;return Yr(o).then(H=>{w||x(H.filter(K=>K.enabled))}).catch(()=>{w||x([])}),()=>{w=!0}},[o]);const C=a??[],A=i.useMemo(()=>g.map(w=>({id:w.id,name:w.name,description:w.description,phase:w.phase||"pre-merge"})),[g]),N=i.useMemo(()=>new Map(A.map(w=>[w.id,w])),[A]),S=w=>{u(H=>({...H,[w]:!H[w]}))},_=w=>{h(H=>{const K=H[w]??"markdown";return{...H,[w]:K==="markdown"?"plain":"markdown"}})},T=w=>{p(w)},M=()=>{p(null)};i.useEffect(()=>{if(!f)return;const w=H=>{H.key==="Escape"&&M()};return document.addEventListener("keydown",w),()=>{document.removeEventListener("keydown",w)}},[f]);const E=i.useCallback((w,H)=>{if(c){if(H){if(C.includes(w)){c(C);return}c([...C,w]);return}c(C.filter(K=>K!==w))}},[c,C]),L=i.useCallback(w=>{if(!c||w<=0)return;const H=[...C];[H[w-1],H[w]]=[H[w],H[w-1]],c(H)},[c,C]),F=i.useCallback(w=>{if(!c||w>=C.length-1)return;const H=[...C];[H[w],H[w+1]]=[H[w+1],H[w]],c(H)},[c,C]),R=i.useCallback(w=>{c&&c(C.filter(H=>H!==w))},[c,C]),P=n.length>0,O=C.length>0;i.useEffect(()=>{r||b(!1)},[r]);const q=i.useMemo(()=>C.map(w=>{const H=N.get(w);return{id:w,name:H?.name||w,description:H?.description||"Step definition not found.",phase:H?.phase||"pre-merge"}}),[C,N]),Z=()=>!r||!v||s?null:t.jsxs("div",{className:"workflow-results-editor","data-testid":"workflow-steps-editor",children:[t.jsxs("div",{className:"workflow-steps-section",children:[t.jsx("small",{className:"workflow-steps-description",children:"Select steps to run after task implementation completes"}),t.jsx("div",{className:"workflow-steps-list",children:A.map(w=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${w.id}`,children:[t.jsx("input",{type:"checkbox",checked:C.includes(w.id),onChange:H=>E(w.id,H.target.checked)}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[w.name,Mo(w.phase,w.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:w.description})]})]},w.id))})]}),C.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),C.map((w,H)=>{const K=N.get(w);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${w}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:H+1}),t.jsx("span",{className:"workflow-step-order-name",children:K?.name||w}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>L(H),disabled:H===0,"data-testid":`workflow-step-move-up-${w}`,title:"Move up",children:t.jsx(ri,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>F(H),disabled:H===C.length-1,"data-testid":`workflow-step-move-down-${w}`,title:"Move down",children:t.jsx(un,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>R(w),"data-testid":`workflow-step-remove-${w}`,title:"Remove",children:t.jsx(Jt,{})})]})]},w)})]})]}),z=()=>{if(s)return t.jsxs("div",{className:"workflow-results-loading","data-testid":"workflow-results-loading",children:[t.jsx("div",{className:"workflow-results-spinner"}),t.jsx("span",{children:"Loading workflow results…"})]});if(!P)return t.jsxs("div",{className:"workflow-results-empty","data-testid":"workflow-results-empty",children:[t.jsx("p",{children:"No workflow steps configured for this task."}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."})]});const w=n.filter(B=>B.status==="passed").length,H=n.filter(B=>B.status==="failed").length,K=n.filter(B=>B.status==="skipped").length,pe=n.filter(B=>B.status==="pending").length,le=[`${n.length} step${n.length!==1?"s":""}`];return w>0&&le.push(`${w} passed`),H>0&&le.push(`${H} failed`),K>0&&le.push(`${K} skipped`),pe>0&&le.push(`${pe} 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:le.join(" · ")}),n.map((B,ye)=>{const U=B.phase||"pre-merge",te=d[B.workflowStepId]??!1;return t.jsxs("div",{className:`workflow-result-item workflow-result-item--${B.status}`,"data-testid":`workflow-result-item-${B.workflowStepId}`,children:[t.jsxs("div",{className:"workflow-result-header",children:[t.jsxs("div",{className:"workflow-result-name",children:[B.workflowStepName,Mo(U,B.workflowStepId,"workflow-result-phase")]}),t.jsx("span",{className:`workflow-result-badge workflow-result-badge--${B.status}`,"data-testid":`workflow-result-badge-${B.workflowStepId}`,children:tP(B.status)})]}),t.jsxs("div",{className:"workflow-result-meta",children:[B.startedAt&&t.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",sP(B.startedAt)]}),B.completedAt&&t.jsx("span",{className:"workflow-result-duration",children:nP(B.startedAt,B.completedAt)})]}),B.status==="pending"&&B.startedAt?t.jsx(aP,{entries:j,startedAt:B.startedAt,stepId:B.workflowStepId}):B.output?t.jsxs("div",{className:"workflow-result-output-section",children:[t.jsxs("div",{className:"workflow-result-output-header",children:[t.jsx("span",{className:"workflow-result-output-label",children:"Output:"}),t.jsx("button",{className:"workflow-result-toggle",onClick:()=>S(B.workflowStepId),"data-testid":`workflow-result-toggle-${B.workflowStepId}`,children:te?"Hide output":"Show output"}),!te&&t.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${B.workflowStepId}`,children:iP(B.output)}),te&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>_(B.workflowStepId),"data-testid":`workflow-result-mode-toggle-${B.workflowStepId}`,title:(m[B.workflowStepId]??"markdown")==="markdown"?"Switch to plain text":"Switch to markdown",children:(m[B.workflowStepId]??"markdown")==="markdown"?"Markdown":"Plain"}),t.jsx("button",{className:"workflow-result-expand-toggle",onClick:()=>T(B.workflowStepId),"data-testid":`workflow-result-expand-${B.workflowStepId}`,title:"Expand output",children:t.jsx(Nl,{size:12})})]})]}),te&&t.jsx("div",{className:`workflow-result-output${(m[B.workflowStepId]??"markdown")==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":`workflow-result-output-${B.workflowStepId}`,children:(m[B.workflowStepId]??"markdown")==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(vi,{remarkPlugins:[yi],components:jh,children:B.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:B.output})})]}):null]},`${B.workflowStepId}-${ye}`)})]})},k=r?t.jsx("button",{type:"button",className:"modal-edit-btn workflow-results-edit-toggle",onClick:()=>b(w=>!w),"data-testid":"workflow-steps-edit-toggle","aria-label":v?"Done editing workflow steps":"Edit workflow steps",title:v?"Done":"Edit",children:v?t.jsxs(t.Fragment,{children:[t.jsx(Yn,{size:14}),"Done"]}):t.jsxs(t.Fragment,{children:[t.jsx(xs,{size:14}),"Edit"]})}):null,I=!s&&!P&&O,$=r&&P;return t.jsxs("div",{className:"workflow-results-tab","data-task-id":e,children:[I?t.jsxs("div",{className:"workflow-configured-steps","data-testid":"workflow-configured-steps",children:[t.jsxs("div",{className:"workflow-configured-header","data-testid":"workflow-configured-header",children:[t.jsxs("div",{className:"workflow-configured-title-row",children:[t.jsx("h4",{children:"Configured Workflow Steps"}),t.jsxs("span",{className:"workflow-configured-count","data-testid":"workflow-configured-count",children:[q.length," step",q.length===1?"":"s"]})]}),k]}),t.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:q.map(w=>t.jsxs("div",{className:"workflow-configured-item","data-testid":`workflow-configured-step-${w.id}`,children:[t.jsxs("div",{className:"workflow-configured-name",children:[w.name,Mo(w.phase,w.id,"workflow-configured-phase")]}),t.jsx("p",{className:"workflow-configured-description",children:w.description})]},w.id))}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."}),Z()]}):t.jsxs(t.Fragment,{children:[$&&t.jsxs("div",{className:"workflow-results-edit-header","data-testid":"workflow-results-edit-header",children:[t.jsx("h4",{children:"Workflow Steps"}),k]}),z(),Z()]}),f&&(()=>{const w=n.find(pe=>pe.workflowStepId===f);if(!w)return null;const H=m[w.workflowStepId]??"markdown",K=w.phase||"pre-merge";return t.jsx("div",{className:"workflow-output-modal-overlay",onClick:pe=>{pe.target===pe.currentTarget&&M()},"data-testid":"workflow-output-modal",children:t.jsxs("div",{className:"workflow-output-modal",role:"dialog","aria-modal":"true",children:[t.jsxs("div",{className:"workflow-output-modal-header",children:[t.jsxs("div",{className:"workflow-output-modal-title",children:[t.jsx("span",{className:"workflow-output-modal-name",children:w.workflowStepName}),Mo(K,w.workflowStepId,"workflow-output-modal-phase")]}),t.jsxs("div",{className:"workflow-output-modal-controls",children:[t.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>_(w.workflowStepId),"data-testid":"workflow-output-modal-mode-toggle",title:H==="markdown"?"Switch to plain text":"Switch to markdown",children:H==="markdown"?"Markdown":"Plain"}),t.jsx("button",{className:"workflow-output-modal-close",onClick:M,"data-testid":"workflow-output-modal-close","aria-label":"Close",children:t.jsx(Jt,{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(vi,{remarkPlugins:[yi],components:jh,children:w.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:w.output})})})]})})})()]})}function oP(e){return e==="block"?"Block execution":e==="fallback-local"?"Fall back to local":"Not configured"}const lP=new Set(["planning","researching","executing","finalizing","merging"]);function cP(e){return e!==void 0&&e!=="online"}function dP({task:e,settings:n,addToast:s,onTaskUpdated:a}){const[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState(null),[m,h]=i.useState(e.nodeId??""),[f,p]=i.useState(!1),g=i.useRef(e.id);i.useEffect(()=>{g.current=e.id,h(e.nodeId??""),p(!1)},[e.id,e.nodeId]),i.useEffect(()=>{c(!0),u(null),sl().then(M=>{o(M)}).catch(M=>{u(_e(M)||"Failed to load nodes")}).finally(()=>{c(!1)})},[]);const x=i.useMemo(()=>new Map(r.map(M=>[M.id,M])),[r]),v=i.useMemo(()=>[...r].sort((M,E)=>M.name.localeCompare(E.name)),[r]),b=n,y=e.nodeId??b?.defaultNodeId??null,j=e.nodeId?"Per-task override":b?.defaultNodeId?"Project default":"No routing",C=y?x.get(y):void 0,A=C?`${C.name} (${C.type})`:y?`${y} (node unavailable or unknown)`:"Local (no routing configured)",N=e.column==="in-progress"||lP.has(e.status),S=N||f||l,_=i.useCallback(async M=>{if(M===m)return;const E=e.id,L=m;h(M),p(!0);try{const F=await ni(E,{nodeId:M||null});if(g.current!==E)return;h(F.nodeId??""),a?.(F),s(M?"Node override updated":"Node override cleared","success")}catch(F){if(g.current!==E)return;h(L),s(_e(F)||"Failed to update node override","error")}finally{g.current===E&&p(!1)}},[s,a,m,e.id]),T=i.useCallback(()=>{_("")},[_]);return t.jsxs("div",{className:"routing-tab",children:[t.jsx("h4",{children:"Task Routing"}),t.jsx("p",{className:"routing-tab__intro",children:"View the effective execution node and control per-task node override."}),t.jsxs("section",{className:"routing-tab__section",children:[t.jsx("h5",{children:"Routing Summary"}),t.jsxs("div",{className:"routing-summary-grid",role:"list",children:[t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Effective node"}),t.jsxs("span",{className:"routing-summary-value",children:[C?t.jsx(ia,{status:C.status,compact:!0}):null,A,cP(C?.status)?t.jsx("span",{className:"routing-summary-warning",children:"Unhealthy"}):null]})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Routing source"}),t.jsx("span",{className:"routing-summary-value",children:j})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Unavailable-node policy"}),t.jsx("span",{className:"routing-summary-value",children:oP(b?.unavailableNodePolicy)})]})]}),N&&y?t.jsx("div",{className:"routing-tab__info-banner",children:"Routing is locked while this task is active. Node override cannot be changed until the task is no longer active."}):null]}),t.jsxs("section",{className:"routing-tab__section",children:[t.jsx("h5",{children:"Node Override"}),N?t.jsx("div",{className:"routing-tab__warning-banner",children:"Node override cannot be changed while the task is active."}):null,t.jsx("label",{className:"routing-tab__selector-label",htmlFor:`routing-node-${e.id}`,children:"Select execution node"}),t.jsxs("select",{id:`routing-node-${e.id}`,className:"select routing-tab__selector",value:m,disabled:S,onChange:M=>{_(M.target.value)},children:[t.jsx("option",{value:"",children:"Use project default"}),v.map(M=>t.jsxs("option",{value:M.id,title:`Status: ${M.status}`,children:[M.name," (",M.type,") — ",M.status]},M.id))]}),d?t.jsx("div",{className:"routing-tab__error",children:d}):null,e.nodeId?t.jsxs("div",{className:"routing-tab__override-row",children:[t.jsxs("span",{className:"routing-tab__override-text",children:["Override set to: ",x.get(e.nodeId)?.name??e.nodeId]}),t.jsx("button",{type:"button",className:"btn btn-sm",disabled:N||f,onClick:T,children:"Clear override"})]}):null]})]})}const uP=/^[a-zA-Z0-9_-]{1,64}$/,mP=200;function Nh(e){return e?new Date(e).toLocaleString():""}function hP(e,n=mP){return e.length<=n?e:e.substring(0,n)+"…"}function pP({taskId:e,addToast:n,onTaskUpdated:s,projectId:a,canEdit:r=!1}){const[o,l]=i.useState([]),[c,d]=i.useState(!0),[u,m]=i.useState(null),[h,f]=i.useState(""),[p,g]=i.useState(null),[x,v]=i.useState(""),[b,y]=i.useState(null),[j,C]=i.useState([]),[A,N]=i.useState(!1),[S,_]=i.useState(!1),[T,M]=i.useState(""),[E,L]=i.useState(""),[F,R]=i.useState(!1),[P,O]=i.useState(null),[q,Z]=i.useState(null),[z,k]=i.useState(!1),I=i.useCallback(async()=>{try{const U=await vw(e,a);l(U)}catch(U){n(_e(U)||"Failed to load documents","error")}finally{d(!1)}},[e,a,n]);i.useEffect(()=>{I()},[I]);async function $(U){u===U.key?(m(null),f(""),g(null),v(""),y(null),C([]),k(!1)):(m(U.key),f(U.content),g(null),v(""),y(null),C([]),k(!1))}async function w(U){if(b===U)y(null),C([]);else{y(U),N(!0);try{const te=await yw(e,U,a);C(te)}catch(te){n(_e(te)||"Failed to load revisions","error")}finally{N(!1)}}}function H(){u&&(g(u),v(h))}function K(){g(null),v("")}async function pe(){if(!(!p||!x.trim())){R(!0);try{await Ru(e,p,x,{},a),g(null),v(""),await I();const U=o.find(te=>te.key===p);U&&f(U.content),n("Document saved","success")}catch(U){n(_e(U)||"Failed to save document","error")}finally{R(!1)}}}async function le(){const U=T.trim(),te=E.trim();if(!U){n("Document key is required","error");return}if(!uP.test(U)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!te){n("Content is required","error");return}R(!0);try{await Ru(e,U,te,{},a),_(!1),M(""),L(""),await I(),n("Document created","success")}catch(ne){n(_e(ne)||"Failed to create document","error")}finally{R(!1)}}async function B(U){O(U);try{await ww(e,U,a),Z(null),O(null),u===U&&(m(null),f("")),b===U&&(y(null),C([])),await I(),n("Document deleted","success")}catch(te){n(_e(te)||"Failed to delete document","error")}finally{O(null)}}function ye(U){f(U.content),g(null),v("")}return c?t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),t.jsx("div",{className:"detail-log-empty",children:"Loading documents…"})]}):t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),S&&t.jsxs("div",{className:"task-document-create-form",children:[t.jsx("h5",{children:"New Document"}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-key",children:"Key"}),t.jsx("input",{id:"doc-key",type:"text",className:"task-document-key-input",value:T,onChange:U=>M(U.target.value),placeholder:"e.g., plan, notes, research",disabled:F}),t.jsx("span",{className:"form-hint",children:"Alphanumeric, hyphens, underscores (1-64 chars)"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-content",children:"Content"}),t.jsx("textarea",{id:"doc-content",value:E,onChange:U=>L(U.target.value),rows:6,placeholder:"Enter document content…",disabled:F})]}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{_(!1),M(""),L("")},disabled:F,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void le(),disabled:F||!T.trim()||!E.trim(),children:F?"Creating…":"Create"})]})]}),o.length===0&&!S?t.jsx("div",{className:"detail-log-empty",children:"No documents yet."}):t.jsx("div",{className:"task-documents-list",children:o.map(U=>t.jsxs("div",{className:"task-document-card",children:[t.jsxs("div",{className:"task-document-card-header",children:[t.jsxs("div",{className:"task-document-card-title",children:[t.jsx(Fi,{size:14}),t.jsx("span",{className:"task-document-key",children:U.key}),t.jsxs("span",{className:"task-document-revision-badge",children:["v",U.revision]})]}),t.jsxs("div",{className:"task-document-meta",children:[t.jsx("span",{className:"task-document-author",children:U.author}),t.jsx("span",{className:"task-document-timestamp",children:Nh(U.updatedAt||U.createdAt)})]})]}),u===U.key&&p!==U.key&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"task-document-content-header",children:t.jsx("button",{className:"btn btn-sm document-mode-toggle",onClick:()=>k(te=>!te),"aria-label":z?"Switch to plain text":"Switch to markdown","aria-pressed":z,title:z?"Switch to plain text":"Switch to markdown",children:z?"Markdown":"Plain"})}),t.jsx("div",{className:"task-document-content",children:z?t.jsx("div",{className:"task-document-content-markdown",children:t.jsx("div",{className:"markdown-body",children:t.jsx(vi,{remarkPlugins:[yi],children:h})})}):t.jsx("pre",{className:"task-document-content-text",children:h})}),b===U.key&&t.jsxs("div",{className:"task-document-revisions",children:[t.jsx("h5",{children:"Revision History"}),A?t.jsx("div",{className:"detail-log-empty",children:"Loading…"}):j.length<=1?t.jsx("div",{className:"detail-log-empty",children:"No previous revisions."}):t.jsx("div",{className:"task-document-revision-list",children:j.filter(te=>te.revision<U.revision).sort((te,ne)=>ne.revision-te.revision).map(te=>t.jsxs("div",{className:"task-document-revision-item",onClick:()=>ye(te),children:[t.jsxs("div",{className:"revision-header",children:[t.jsxs("span",{className:"revision-badge",children:["v",te.revision]}),t.jsx("span",{className:"revision-author",children:te.author}),t.jsx("span",{className:"revision-timestamp",children:Nh(te.createdAt)})]}),t.jsx("div",{className:"revision-preview",children:hP(te.content,100)})]},te.id))})]})]}),p===U.key&&t.jsxs("div",{className:"task-document-edit-form",children:[t.jsx("textarea",{value:x,onChange:te=>v(te.target.value),rows:10,disabled:F}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:K,disabled:F,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void pe(),disabled:F||!x.trim(),children:F?"Saving…":"Save"})]})]}),t.jsxs("div",{className:"task-document-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>void $(U),children:u===U.key?t.jsxs(t.Fragment,{children:[t.jsx(ri,{size:14})," Collapse"]}):t.jsxs(t.Fragment,{children:[t.jsx(un,{size:14})," Expand"]})}),u===U.key&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>void w(U.key),children:[t.jsx(Tr,{size:14})," History"]}),r&&p!==U.key&&t.jsx("button",{className:"btn btn-sm",onClick:H,children:"Edit"}),r&&(q===U.key?t.jsxs("div",{className:"confirm-delete-actions",children:[t.jsx("span",{children:"Delete?"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void B(U.key),disabled:P===U.key,children:P===U.key?"…":"Yes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Z(null),disabled:P===U.key,children:"No"})]}):t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>Z(U.key),children:t.jsx(Cn,{size:14})}))]})]})]},U.key))}),r&&!S&&t.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>_(!0),children:[t.jsx(Sn,{size:14})," New Document"]})]})}function _o(e){return e.toLocaleString()}function _c(e){const n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString()}function cr(e){if(e<1e3)return`${Math.round(e)} ms`;const n=e/1e3;if(n<60)return`${n.toFixed(1)} s`;const s=Math.floor(n/60),a=Math.round(n%60);return`${s}m ${a}s`}function fP(e){const n=Date.now(),s=e.map(o=>{if(!o.startedAt)return null;const l=new Date(o.startedAt).getTime();if(Number.isNaN(l))return null;let c;if(o.completedAt){const d=new Date(o.completedAt).getTime();if(Number.isNaN(d)||d<l)return null;c=d}else c=Math.max(l,n);return{name:o.workflowStepName||o.workflowStepId,durationMs:c-l}}).filter(o=>o!==null),a=s.reduce((o,l)=>o+l.durationMs,0),r=s.reduce((o,l)=>!o||l.durationMs>o.durationMs?l:o,void 0);return{timedStepCount:s.length,totalDurationMs:a,longestStep:r}}function gP({tokenUsage:e,loading:n,task:s}){const a=Rf(s?.log??[]),r=a.filter(m=>typeof m.durationMs=="number"),o=r.reduce((m,h)=>m+(h.durationMs??0),0),l=Math.max(o,s?.timedExecutionMs??0),c=r.reduce((m,h)=>!m||(h.durationMs??0)>(m.durationMs??0)?h:m,void 0),d=fP(s?.workflowStepResults??[]),u=s?.steps?.length??0;return t.jsxs("section",{className:"task-token-stats-panel","aria-label":"Task execution statistics",children:[t.jsx("h4",{children:"Execution & Token Stats"}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Execution Timing"}),t.jsxs("div",{className:"task-token-stats-panel__grid",role:"list","aria-label":"Execution timing metrics",children:[t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Timing events"}),t.jsx("span",{className:"task-token-stats-panel__value",children:a.length.toLocaleString()})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Timed duration"}),t.jsx("span",{className:"task-token-stats-panel__value",children:cr(l)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Workflow timed steps"}),t.jsx("span",{className:"task-token-stats-panel__value",children:d.timedStepCount.toLocaleString()})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Workflow runtime"}),t.jsx("span",{className:"task-token-stats-panel__value",children:cr(d.totalDurationMs)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Total execution time"}),t.jsx("span",{className:"task-token-stats-panel__value",children:cr(l+d.totalDurationMs)})]})]}),t.jsxs("dl",{className:"task-token-stats-panel__timestamps",children:[t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Longest timing event"}),t.jsx("dd",{children:c?.durationMs?`${c.summary} (${cr(c.durationMs)})`:"No timed events recorded yet."})]}),t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Longest workflow step"}),t.jsx("dd",{children:d.longestStep?`${d.longestStep.name} (${cr(d.longestStep.durationMs)})`:"No completed workflow step timings yet."})]})]})]}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Execution Details"}),t.jsxs("dl",{className:"task-token-stats-panel__details",children:[t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Execution mode"}),t.jsx("dd",{children:s?.executionMode==="fast"?"Fast":"Standard"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Runtime status"}),t.jsx("dd",{children:s?.status??"Not set"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Paused"}),t.jsx("dd",{children:s?.paused?"Yes":"No"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Step progress"}),t.jsx("dd",{children:u>0?`${Math.min((s?.currentStep??0)+1,u)} / ${u}`:"No steps"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Retries (recovery / workflow / merge / task_done)"}),t.jsx("dd",{children:`${s?.recoveryRetryCount??0} / ${s?.workflowStepRetries??0} / ${s?.mergeRetries??0} / ${s?.taskDoneRetryCount??0}`})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Recovery state"}),t.jsx("dd",{children:s?.nextRecoveryAt?`Next recovery at ${_c(s.nextRecoveryAt)}`:"No scheduled recovery"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Self-heal counters"}),t.jsx("dd",{children:`stuck kills: ${s?.stuckKillCount??0}, post-review fixes: ${s?.postReviewFixCount??0}`})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Runtime links"}),t.jsx("dd",{children:[s?.assignedAgentId?`agent ${s.assignedAgentId}`:null,s?.checkedOutBy?`checkout ${s.checkedOutBy}`:null,s?.blockedBy?`blocked by ${s.blockedBy}`:null,s?.sessionFile?"has session":null].filter(Boolean).join(", ")||"No runtime links"})]})]})]}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Token Usage"}),!e&&n?t.jsx("div",{className:"task-token-stats-panel__loading",role:"status","aria-live":"polite",children:"Loading token statistics…"}):e?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"task-token-stats-panel__grid",role:"list","aria-label":"Task token totals",children:[t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Input"}),t.jsx("span",{className:"task-token-stats-panel__value",children:_o(e.inputTokens)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Output"}),t.jsx("span",{className:"task-token-stats-panel__value",children:_o(e.outputTokens)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Cached"}),t.jsx("span",{className:"task-token-stats-panel__value",children:_o(e.cachedTokens)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Total"}),t.jsx("span",{className:"task-token-stats-panel__value",children:_o(e.totalTokens)})]})]}),t.jsxs("dl",{className:"task-token-stats-panel__timestamps",children:[t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"First used"}),t.jsx("dd",{children:t.jsx("time",{dateTime:e.firstUsedAt,children:_c(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:_c(e.lastUsedAt)})})]})]})]}):t.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:"No token usage recorded for this task yet."})]})]})}const bP=new Set(["planning","researching","executing","finalizing","merging"]);function xP(e,n){return Nf(e,n)}function vP(e,n){return Sf(e,n)}function yP(e){let n=null;for(const s of e){if(s.agent!=="triage"||s.type!=="text")continue;const a=s.text.match(/^Triage using model: (.+?)\/(.+)$/);a&&(n={provider:a[1],modelId:a[2]})}return n}function wP(e,n,s){if(e.planningModelProvider&&e.planningModelId)return{provider:e.planningModelProvider,modelId:e.planningModelId};const a=yP(n);return a||Cf(e,s)}function kP(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 jP(e){const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4),o=Math.floor(r/60),l=Math.floor(o/24);return r<1?"just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString()}function NP(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function SP(e){if(!(e instanceof Error))return null;const n=e.details;if(n?.code==="TASK_HAS_DEPENDENTS"&&Array.isArray(n.dependentIds))return{dependentIds:n.dependentIds.filter(a=>typeof a=="string")};const s=e.message.match(/[A-Z]+-\d+/g)??[];return s.length>1?{dependentIds:[...new Set(s.slice(1))]}:null}function Sh(e,n){return e.length>n?e.slice(0,n)+"…":e}function Ch(e=[],n=[]){return e.length===n.length&&e.every((s,a)=>s===n[a])}function Ac(e){const n=e.indexOf("/");return!e||n===-1?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function Pc(e){return e.trim()}function CP(e){const n=e.trim();return n.length>0?n:void 0}function Ni(e){return typeof e=="string"&&Zr.includes(e)?e:Cs}function dr(e){return e==="fast"?"fast":"standard"}function EP(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}function MP(e){const n=e?.findingLabel;if(typeof n=="string"&&n.length>0)return n;const s=e?.runId;return typeof s=="string"&&s.length>0?s:void 0}const _P=i.lazy(()=>Mn(()=>import("./AgentDetailView-DGqT1oDt.js").then(e=>e.A),__vite__mapDeps([0,1,2,3])).then(e=>({default:e.AgentDetailView})));function AP(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:EP(e.sourceMetadata)};case"research":return{label:"Research",contextInfo:MP(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 Rc=200,PP=new Set(["triage","todo"]);function Qg({task:e,projectId:n,tasks:s=[],onOpenDetail:a,onMoveTask:r,onDeleteTask:o,onMergeTask:l,onRetryTask:c,onResetTask:d,onDuplicateTask:u,onTaskUpdated:m,addToast:h,prAuthAvailable:f,initialTab:p="definition",mobileHeaderMode:g="close",embedded:x=!1,onRequestClose:v}){const[b,y]=i.useState(p),[j,C]=i.useState(()=>"prompt"in e?e:null),[A,N]=i.useState(()=>!("prompt"in e));i.useEffect(()=>{if("prompt"in e){C(e),N(!1);return}let Y=!1;return N(!0),C(null),Ia(e.id,n).then(Ke=>{Y||(C(Ke),N(!1))}).catch(()=>{Y||N(!1)}),()=>{Y=!0}},[e.id,n]);const S=j?{...j,...e,prompt:j.prompt,log:j.log}:{...e,prompt:""},_=e.status==="failed"||e.status==="stuck-killed"||e.status==="planning"||e.status==="needs-replan"||(e.stuckKillCount??0)>0||(e.recoveryRetryCount??0)>0||!!e.nextRecoveryAt,[T,M]=i.useState(null),[E,L]=i.useState(null),F=AP(S,{sourceAgentName:T?.name});i.useEffect(()=>{y(p)},[p]),i.useEffect(()=>{q(!1)},[e.id]);const[R,P]=i.useState("activity"),[O,q]=i.useState(!1),[Z,z]=i.useState(e.attachments||[]),[k,I]=i.useState(!1),[$,w]=i.useState(e.dependencies||[]),[H,K]=i.useState(!1),[pe,le]=i.useState(""),[B,ye]=i.useState(null),[U,te]=i.useState([]),[ne,ee]=i.useState(!1),[ie,ge]=i.useState(!1),[se,Ae]=i.useState(!1),[xe,Se]=i.useState(!1),[qe,We]=i.useState(!1),[Qe,ve]=i.useState(S.prompt||""),[Oe,ae]=i.useState(""),[re,je]=i.useState(!1),[Q,Fe]=i.useState(""),[Je,be]=i.useState(!1),[ze,tt]=i.useState(!1),[kt,ke]=i.useState(e.title||""),[ce,Te]=i.useState(e.description||""),[he,Le]=i.useState(e.dependencies||[]),[st,it]=i.useState(""),[lt,$e]=i.useState(""),[Ue,Xe]=i.useState(""),[wt,Re]=i.useState(""),[xt,Pt]=i.useState("default"),[Ct,Ot]=i.useState(void 0),[zt,Nt]=i.useState(Cs),[jt,Yt]=i.useState(e.nodeId),[Bt,qt]=i.useState(dr(e.executionMode)),[wn,mn]=i.useState(""),[Xt,Vt]=i.useState(e.enabledWorkflowSteps||[]),[Ft,Zt]=i.useState(e.sourceIssue?.provider??""),[en,cn]=i.useState(e.sourceIssue?.repository??""),[we,De]=i.useState(e.sourceIssue?.externalIssueId??""),[oe,Pe]=i.useState(e.sourceIssue?.url??""),[Ce,J]=i.useState([]),[Ie,de]=i.useState(!1),[Ne,Ye]=i.useState(Ni(e.priority)),[ft,tn]=i.useState(!1),$t=i.useRef(!1),[Rt,Dt]=i.useState(!1),[En,bn]=i.useState(!1),[Nn,dn]=i.useState(!1),xn=i.useRef(null),rn=i.useRef(null),On=i.useRef(null),{getSlotsForId:fe}=yf(n),hn=fe("task-detail-tab").map((Y,Ke)=>({entry:Y,tabId:`plugin-${Y.pluginId}-${Ke}`})),zn=typeof b=="string"&&b.startsWith("plugin-")?hn.find(Y=>Y.tabId===b)??null:null;i.useEffect(()=>($t.current=!0,()=>{$t.current=!1}),[]);const[ue,ut]=i.useState(void 0),[yt,dt]=i.useState([]),[at,vt]=i.useState(!1),[Ht,Ut]=i.useState(e.enabledWorkflowSteps||[]),An=e.column==="in-progress"||bP.has(e.status);i.useEffect(()=>{ke(e.title||""),Te(e.description||""),Zt(e.sourceIssue?.provider??""),cn(e.sourceIssue?.repository??""),De(e.sourceIssue?.externalIssueId??""),Pe(e.sourceIssue?.url??""),qt(dr(e.executionMode)),dn(!1),tt(!1)},[e.id,e.title,e.description,e.sourceIssue,e.executionMode]),i.useEffect(()=>{Ut(e.enabledWorkflowSteps||[])},[e.id,e.enabledWorkflowSteps]),i.useEffect(()=>{Ye(Ni(e.priority))},[e.id,e.priority]),i.useEffect(()=>{let Y=!1;return El(n).then(Ke=>{Y||ut(Ke)}).catch(()=>{}),()=>{Y=!0}},[n]),i.useEffect(()=>{if(b!=="workflow")return;let Y=!1;return vt(!0),ej(e.id,n).then(Ke=>{Y||dt(Ke)}).catch(Ke=>{Y||h(`Failed to load workflow results: ${_e(Ke)}`,"error")}).finally(()=>{Y||vt(!1)}),()=>{Y=!0}},[b,e.id,n,h]),i.useEffect(()=>{if(b!=="workflow")return;const Y=n?`?projectId=${encodeURIComponent(n)}`:"",Ke=bt=>{try{const Kt=JSON.parse(bt.data);Kt.id===e.id&&Array.isArray(Kt.workflowStepResults)&&dt(Kt.workflowStepResults)}catch{}};return li(`/api/events${Y}`,{events:{"task:updated":Ke}})},[b,e.id,n]),i.useEffect(()=>{H||le("")},[H]),i.useEffect(()=>{if(!e.assignedAgentId){ye(null);return}const Y=U.find(bt=>bt.id===e.assignedAgentId);if(Y){ye(Y);return}let Ke=!1;return pd(e.assignedAgentId,n).then(bt=>{Ke||ye(bt)}).catch(()=>{Ke||ye(null)}),()=>{Ke=!0}},[e.assignedAgentId,n,U]),i.useEffect(()=>{if(!e.sourceAgentId){M(null);return}const Y=U.find(bt=>bt.id===e.sourceAgentId);if(Y){M(Y);return}let Ke=!1;return Promise.resolve(pd(e.sourceAgentId,n)).then(bt=>{Ke||M(bt??null)}).catch(()=>{Ke||M(null)}),()=>{Ke=!0}},[e.sourceAgentId,n,U]),i.useEffect(()=>{ee(!1)},[e.id]),i.useEffect(()=>{if(!(Rt||En))return;const Ke=bt=>{const Kt=bt.target,ss=xn.current?.contains(Kt),Vs=On.current?.contains(Kt);!ss&&Rt&&Dt(!1),!Vs&&En&&bn(!1)};return document.addEventListener("mousedown",Ke),()=>document.removeEventListener("mousedown",Ke)},[Rt,En]),i.useEffect(()=>{if(!(Rt||En))return;const Ke=bt=>{bt.key==="Escape"&&(bt.stopPropagation(),Rt&&Dt(!1),En&&bn(!1))};return document.addEventListener("keydown",Ke),()=>document.removeEventListener("keydown",Ke)},[Rt,En]),i.useEffect(()=>{We(!1),ve(S.prompt||""),ae("")},[e.id,S.prompt]);const Wt=PP.has(e.column)&&!Ie,Tt=i.useCallback(()=>{if(!Wt)return;tt(!0),ke(e.title||""),Te(e.description||""),Le(e.dependencies||[]);const Y=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"",Ke=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"",bt=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";it(Y),$e(Ke),Xe(bt),Re(e.thinkingLevel??""),Yt(e.nodeId),Pt(Y||Ke||bt?"custom":"default"),mn(""),Vt(e.enabledWorkflowSteps||[]),qt(dr(e.executionMode)),Zt(e.sourceIssue?.provider??""),cn(e.sourceIssue?.repository??""),De(e.sourceIssue?.externalIssueId??""),Pe(e.sourceIssue?.url??""),J([]),Ot(e.reviewLevel),Nt(Ni(e.priority))},[Wt,e]),G=i.useCallback(()=>{tt(!1),ke(e.title||""),Te(e.description||""),Le(e.dependencies||[]),Yt(e.nodeId),Zt(e.sourceIssue?.provider??""),cn(e.sourceIssue?.repository??""),De(e.sourceIssue?.externalIssueId??""),Pe(e.sourceIssue?.url??""),Nt(Ni(e.priority)),qt(dr(e.executionMode)),Ce.forEach(Y=>URL.revokeObjectURL(Y.previewUrl)),J([])},[e.title,e.description,e.dependencies,e.nodeId,e.priority,e.executionMode,Ce]),He=i.useCallback(async()=>{de(!0);try{const Y={},Ke=kt.trim(),bt=ce.trim();Ke&&Ke!==(e.title??"")&&(Y.title=Ke),bt&&bt!==(e.description??"")&&(Y.description=bt),Ch(he,e.dependencies??[])||(Y.dependencies=he),Ch(Xt,e.enabledWorkflowSteps??[])||(Y.enabledWorkflowSteps=Xt);const Kt=Ac(st),ss=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"";st!==ss&&(Y.modelProvider=Kt?.provider??null,Y.modelId=Kt?.modelId??null);const Vs=Ac(lt),ro=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"";lt!==ro&&(Y.validatorModelProvider=Vs?.provider??null,Y.validatorModelId=Vs?.modelId??null);const tr=Ac(Ue),oo=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";Ue!==oo&&(Y.planningModelProvider=tr?.provider??null,Y.planningModelId=tr?.modelId??null);const lo=e.thinkingLevel??"";wt!==lo&&(Y.thinkingLevel=wt!==""?wt:null),(e.nodeId??void 0)!==jt&&(Y.nodeId=jt??null);const co=e.reviewLevel;Ct!==co&&(Y.reviewLevel=Ct);const uo=Ni(e.priority);zt!==uo&&(Y.priority=zt);const W=dr(e.executionMode);Bt!==W&&(Y.executionMode=Bt==="fast"?"fast":null);const Ee=Pc(Ft),Ge=Pc(en),At=Pc(we),yn=CP(oe);if(Ee.length===0&&Ge.length===0&&At.length===0&&!yn)e.sourceIssue&&(Y.sourceIssue=null);else{if(!Ee||!Ge||!At){h("Source issue provider, repository, and issue identifier are required","error"),de(!1);return}const Ze=Number.parseInt(At,10),nt=e.sourceIssue?.issueNumber??Ze;if(!Number.isFinite(nt)||nt<=0){h("Source issue identifier must be numeric for new metadata","error"),de(!1);return}const _t={provider:Ee,repository:Ge,externalIssueId:At,issueNumber:nt,...yn?{url:yn}:{}},fn=e.sourceIssue;(!fn||fn.provider!==_t.provider||fn.repository!==_t.repository||fn.externalIssueId!==_t.externalIssueId||fn.issueNumber!==_t.issueNumber||(fn.url??void 0)!==_t.url)&&(Y.sourceIssue=_t)}if(Object.keys(Y).length>0){const Ze=await ni(e.id,Y,n);m?.(Ze)}if(Ce.length>0){const Ze=[];for(const nt of Ce)try{const _t=await $r(e.id,nt.file,n);z(fn=>[...fn,_t])}catch{Ze.push(nt.file.name)}Ze.length>0&&h(`Failed to upload: ${Ze.join(", ")}`,"error")}Ce.forEach(Ze=>URL.revokeObjectURL(Ze.previewUrl)),J([]),h(`Updated ${e.id}`,"success"),tt(!1)}catch(Y){h(`Failed to update ${e.id}: ${_e(Y)}`,"error")}finally{$t.current&&de(!1)}},[e,kt,ce,he,st,lt,Ue,wt,jt,Ct,zt,Bt,Xt,Ft,en,we,oe,Ce,h,n,m]),mt=i.useCallback(async Y=>{try{const Ke=await ni(e.id,{description:Y},n);m?.(Ke),h("Description saved","success")}catch(Ke){h(`Failed to save: ${_e(Ke)}`,"error")}},[e.id,h,n,m]),ht=i.useCallback(async Y=>{const Ke=Ni(Y),bt=Ni(e.priority);if(Ke===bt){Ye(bt);return}const Kt=Ne;Ye(Ke),tn(!0);try{const ss=await ni(e.id,{priority:Ke},n);Ye(Ni(ss.priority)),m?.(ss),h(`Priority updated to ${Ni(ss.priority)}`,"success")}catch(ss){Ye(Kt),h(`Failed to update ${e.id}: ${_e(ss)}`,"error")}finally{$t.current&&tn(!1)}},[e.id,e.priority,n,Ne,m,h]),Et=i.useCallback(Y=>{ze&&(Y.key==="Escape"?(Y.preventDefault(),G()):Y.key==="Enter"&&(Y.ctrlKey||Y.metaKey)&&(Y.preventDefault(),He()))},[ze,G,He]);i.useEffect(()=>{if(ze)return document.addEventListener("keydown",Et),()=>document.removeEventListener("keydown",Et)},[ze,Et]);const St=i.useRef(null),{nodes:sn}=Al(),{confirm:nn}=qs(),{entries:as,loading:Is,loadMore:_s,hasMore:ls,total:Xs,loadingMore:ci}=Wg(e.id,b==="logs"&&R==="agent-log",n),pn=i.useCallback(()=>{v?.()},[v]);i.useEffect(()=>{if(x)return;const Y=Ke=>{Ke.key==="Escape"&&!ze&&pn()};return document.addEventListener("keydown",Y),()=>document.removeEventListener("keydown",Y)},[x,pn,ze]);const me=i.useCallback(async Y=>{try{const Ke=e.steps.some(ss=>ss.status!=="pending"),bt=(Y==="todo"||Y==="triage")&&Ke;let Kt;if(bt){if(await nn({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))Kt={preserveProgress:!0};else if(!await nn({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await r(e.id,Y,Kt),pn(),h(`Moved to ${Qn[Y]}`,"success")}catch(Ke){h(_e(Ke),"error")}},[e.id,e.steps,r,pn,h,nn]),Ve=i.useCallback(async()=>{if(await nn({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0}))try{await o(e.id),pn(),h(`Deleted ${e.id}`,"info")}catch(Ke){const bt=SP(Ke);if(!bt||bt.dependentIds.length===0){h(_e(Ke),"error");return}const Kt=bt.dependentIds.join(", ");if(!await nn({title:"Force Delete Task",message:`${e.id} is a dependency of ${Kt}.
677
+
678
+ Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await o(e.id,{removeDependencyReferences:!0}),pn(),h(`Deleted ${e.id} after removing dependency references`,"info")}catch(Vs){h(_e(Vs),"error")}}},[e.id,o,pn,h,nn]),ot=i.useCallback(async()=>{await nn({title:"Merge Task",message:`Merge ${e.id} into the current branch?`})&&(pn(),h(`Merging ${e.id}...`,"info"),l(e.id).then(Ke=>{const bt=Ke.merged?`Merged ${e.id} (branch: ${Ke.branch})`:`Closed ${e.id} (${Ke.error||"no branch to merge"})`;h(bt,"success")}).catch(Ke=>{h(_e(Ke),"error")}))},[e.id,l,pn,h,nn]),on=i.useCallback(()=>{c&&(pn(),c(e.id).then(()=>{h(`Retried ${e.id}`,"success")}).catch(Y=>{h(_e(Y),"error")}))},[e.id,c,pn,h]),Un=i.useCallback(()=>{d&&window.confirm(`This will erase all progress for ${e.id} and start the task from scratch. Continue?`)&&(pn(),d(e.id).then(()=>{h(`Reset ${e.id} — fresh run will be allocated`,"success")}).catch(Y=>{h(_e(Y),"error")}))},[e.id,d,pn,h]),X=i.useCallback(async()=>{if(!(!u||!await nn({title:"Duplicate Task",message:`Duplicate ${e.id}? This will create a new task in Triage with the same description and prompt.`})))try{const Ke=await u(e.id);pn(),h(`Duplicated ${e.id} → ${Ke.id}`,"success")}catch(Ke){h(_e(Ke),"error")}},[e.id,u,pn,h,nn]),Me=i.useCallback(async()=>{try{e.paused?(await lw(e.id,n),h(`Unpaused ${e.id}`,"success")):(await of(e.id,n),h(`Paused ${e.id}`,"success")),pn()}catch(Y){h(_e(Y),"error")}},[e.id,e.paused,pn,h]),rt=i.useCallback(async()=>{try{await mw(e.id,n),h(`Plan approved — ${e.id} moved to Todo`,"success"),pn()}catch(Y){h(_e(Y),"error")}},[e.id,pn,h]),Mt=i.useCallback(async()=>{if(await nn({title:"Reject Plan",message:"Reject this plan? The specification will be discarded and regenerated.",danger:!0}))try{await hw(e.id,n),h(`Plan rejected — ${e.id} returned to Planning for replanning`,"info"),pn()}catch(Ke){h(_e(Ke),"error")}},[e.id,pn,h,nn]),Be=i.useCallback(async()=>{if(await nn({title:"Rebuild Plan",message:"Rebuild the plan for this task? The task will move to planning for replanning."}))try{await Nw(e.id,n),pn(),h(`Replanning ${e.id}...`,"info")}catch(Ke){h(_e(Ke),"error")}},[e.id,n,pn,h,nn]),It=i.useCallback(()=>{je(!0),Fe("")},[]),Gt=i.useCallback(()=>{Dt(!1),bn(!1)},[]),vn=i.useCallback(Y=>{Gt(),me(Y)},[Gt]),ln=i.useCallback(Y=>{Gt(),Y()},[Gt]),Kn=i.useCallback(()=>{Gt(),ot()},[Gt,ot]),Gn=i.useCallback(()=>{je(!1),Fe(""),be(!1)},[]),ps=i.useCallback(async()=>{if(!Q.trim()){h("Please enter feedback describing what needs refinement","error");return}if(Q.length>2e3){h("Feedback must be 2000 characters or less","error");return}be(!0);try{const Y=await Sw(e.id,Q.trim(),n);h(`Refinement task created: ${Y.id}`,"success"),pn()}catch(Y){h(_e(Y),"error")}finally{be(!1)}},[e.id,Q,h,pn]),Fn=i.useCallback(async Y=>{I(!0);try{const Ke=await $r(e.id,Y,n);z(bt=>[...bt,Ke]),h("Screenshot attached","success")}catch(Ke){h(_e(Ke),"error")}finally{I(!1)}},[e.id,h]),Vn=i.useCallback(async Y=>{const Ke=Y.target.files?.[0];Ke&&(await Fn(Ke),St.current&&(St.current.value=""))},[Fn]);i.useEffect(()=>{const Y=Ke=>{const bt=Ke.clipboardData?.items;if(bt)for(let Kt=0;Kt<bt.length;Kt++){const ss=bt[Kt];if(ss.type.startsWith("image/")){const Vs=ss.getAsFile();if(Vs){Ke.preventDefault(),Fn(Vs);return}}}};return document.addEventListener("paste",Y),()=>document.removeEventListener("paste",Y)},[Fn]);const Pn=i.useCallback(Y=>{Y.preventDefault()},[]),fs=i.useCallback(Y=>{Y.preventDefault();const Ke=Y.dataTransfer.files;for(let bt=0;bt<Ke.length;bt++){const Kt=Ke[bt];if(Kt.type.startsWith("image/")){Fn(Kt);return}}},[Fn]),es=i.useCallback(async Y=>{try{await gw(e.id,Y,n),z(Ke=>Ke.filter(bt=>bt.filename!==Y)),h("Attachment deleted","info")}catch(Ke){h(_e(Ke),"error")}},[e.id,h]),Wn=i.useCallback(async Y=>{const Ke=Ht;Ut(Y);try{const bt=await ni(e.id,{enabledWorkflowSteps:Y},n);h("Workflow steps updated","success"),m?.(bt)}catch(bt){Ut(Ke),h(`Failed to update workflow steps: ${_e(bt)}`,"error")}},[e.id,n,Ht,m,h]),gs=i.useCallback(async()=>{ge(!0);try{const Y=await da(void 0,n);te(Y),ee(!0)}catch(Y){h(`Failed to load agents: ${_e(Y)}`,"error"),ee(!1)}finally{ge(!1)}},[n,h]),Jn=i.useCallback(async Y=>{try{const Ke=await Hu(e.id,Y,n),bt=U.find(Kt=>Kt.id===Y)??null;ye(bt||(Kt=>Kt?.id===Y?Kt:null)),ee(!1),m?.(Ke),h("Assigned agent updated","success")}catch(Ke){h(`Failed to assign agent: ${_e(Ke)}`,"error")}},[e.id,n,U,m,h]),bs=i.useCallback(async()=>{try{const Y=await Hu(e.id,null,n);ye(null),ee(!1),m?.(Y),h("Agent unassigned","success")}catch(Y){h(`Failed to unassign agent: ${_e(Y)}`,"error")}},[e.id,n,m,h]),ts=i.useCallback(async Y=>{const Ke=[...$,Y];w(Ke);try{await ni(e.id,{dependencies:Ke},n)}catch(bt){w($),h(_e(bt),"error")}},[e.id,$,h]),$s=i.useCallback(async(Y,Ke)=>{Y.stopPropagation();const bt=$.filter(Kt=>Kt!==Ke);w(bt);try{await ni(e.id,{dependencies:bt},n)}catch(Kt){w($),h(_e(Kt),"error")}},[e.id,$,h]),Ds=i.useCallback(async Y=>{try{const Ke=await Ia(Y,n);a(Ke)}catch{h(`Failed to load dependency ${Y}`,"error")}},[a,h]),ha=i.useCallback(async Y=>{Ae(!0);try{await ni(S.id,{prompt:Y},n),h("Spec updated","success"),j&&(j.prompt=Y)}catch(Ke){throw h(_e(Ke),"error"),Ke}finally{Ae(!1)}},[S,j,h]),di=i.useCallback(async Y=>{Se(!0);try{await jw(e.id,Y,n),h("AI revision requested. Task moved to planning.","success"),pn()}catch(Ke){const bt=_e(Ke);bt.includes("done")||bt.includes("archived")?h("Cannot request revision: Task must be in 'triage', 'todo', 'in-progress', or 'in-review' column.","error"):h(bt,"error")}finally{Se(!1)}},[e.id,h,pn]),Ii=i.useCallback(()=>{We(!0),ve(S.prompt||""),ae("")},[S.prompt]),ui=i.useCallback(()=>{We(!1),ve(S.prompt||""),ae("")},[S.prompt]),pa=i.useCallback(async()=>{if(Qe===(S.prompt||"")){ui();return}We(!1);try{await ha(Qe)}catch(Y){throw We(!0),Y}},[Qe,S.prompt,ha,ui]),zl=i.useCallback(async()=>{Oe.trim()&&await di(Oe.trim())},[Oe,di]),Fl=i.useCallback(Y=>{Y.key==="Escape"?(Y.preventDefault(),ui()):Y.key==="Enter"&&(Y.ctrlKey||Y.metaKey)&&(Y.preventDefault(),pa())},[ui,pa]),Qa=s.filter(Y=>Y.id!==e.id&&!$.includes(Y.id)).sort((Y,Ke)=>{const bt=Ke.createdAt.localeCompare(Y.createdAt);if(bt!==0)return bt;const Kt=parseInt(Y.id.slice(Y.id.lastIndexOf("-")+1),10)||0;return(parseInt(Ke.id.slice(Ke.id.lastIndexOf("-")+1),10)||0)-Kt}),Xa=B?.name??e.assignedAgentId??null,Za=i.useMemo(()=>{const Y=[];return S.modelProvider&&Y.push(S.modelProvider),S.validatorModelProvider&&!Y.includes(S.validatorModelProvider)&&Y.push(S.validatorModelProvider),S.planningModelProvider&&!Y.includes(S.planningModelProvider)&&Y.push(S.planningModelProvider),Y},[S.modelProvider,S.validatorModelProvider,S.planningModelProvider]),Ul=fd[e.column]||[],so=["todo","in-progress"],io=e.column==="in-review"?so:Ul,rs=io[0],mi=io.slice(1),Ss=mi.length>0,er=i.useCallback(()=>{Dt(!1),rn.current?.focus()},[]),qi=i.useCallback(Y=>{if(!Ss){rs&&vn(rs);return}const Ke=Y.currentTarget.querySelector(".detail-move-btn__arrow");if(!!(Y.target instanceof Element&&Y.target.closest(".detail-move-btn__arrow")||Ke&&Y.clientX>0&&Y.clientX>=Ke.getBoundingClientRect().left)){Dt(Kt=>!Kt),bn(!1);return}rs&&vn(rs)},[Ss,rs,vn]),ao=i.useCallback(Y=>{!Ss||!(Y.key==="ArrowDown"||Y.altKey&&Y.key==="ArrowDown")||(Y.preventDefault(),Dt(!0),bn(!1))},[Ss]),fa=i.useCallback(Y=>{Y.key==="Escape"&&(Y.preventDefault(),Y.stopPropagation(),er())},[er]);i.useEffect(()=>{if(!Rt)return;xn.current?.querySelector(".detail-move-menu-item")?.focus()},[Rt]);const Bl={"creating-pr":"Creating PR…","awaiting-pr-checks":"Awaiting PR checks","merging-pr":"Merging PR…"},ga=e.status?Bl[e.status]:void 0;return t.jsxs("div",{className:x?"task-detail-content task-detail-content--embedded":"task-detail-content",onDragOver:Pn,onDrop:fs,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:Qn[e.column]})]}),t.jsxs("div",{className:"modal-header-actions",children:[!ze&&Wt&&t.jsx("button",{className:"modal-edit-btn",onClick:Tt,title:"Edit task","aria-label":"Edit task",children:t.jsx(xs,{size:14})}),!x&&g==="back"&&t.jsxs("button",{className:"modal-close task-detail-mobile-back",onClick:pn,"aria-label":"Back to task list",type:"button",children:[t.jsx(la,{"aria-hidden":"true"}),t.jsx("span",{children:"Back"})]}),!x&&g!=="back"&&t.jsx("button",{className:"modal-close",onClick:pn,"aria-label":"Close",type:"button",children:"×"})]})]}),t.jsxs("div",{className:`detail-body${b==="logs"&&R==="agent-log"&&!ze?" detail-body--agent-log":""}`,children:[ze?t.jsx("div",{className:"modal-edit-form",children:t.jsx(Yg,{mode:"edit",title:kt,onTitleChange:ke,description:ce,onDescriptionChange:Te,dependencies:he,onDependenciesChange:Le,executorModel:st,onExecutorModelChange:it,validatorModel:lt,onValidatorModelChange:$e,planningModel:Ue,onPlanningModelChange:Xe,thinkingLevel:wt,onThinkingLevelChange:Re,presetMode:xt,onPresetModeChange:Pt,selectedPresetId:wn,onSelectedPresetIdChange:mn,selectedWorkflowSteps:Xt,onWorkflowStepsChange:Vt,pendingImages:Ce,onImagesChange:J,tasks:s.filter(Y=>Y.id!==e.id),projectId:n,disabled:Ie,addToast:h,isActive:ze,onAutoSaveDescription:mt,reviewLevel:Ct,onReviewLevelChange:Ot,priority:zt,onPriorityChange:Nt,nodeId:jt,onNodeIdChange:Yt,nodeOptions:sn,nodeOverrideDisabled:An,nodeOverrideDisabledReason:An?"Execution node override is locked while a task is active/in progress.":void 0,executionMode:Bt,onExecutionModeChange:qt,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:Y=>Zt(Y.target.value),disabled:Ie,"data-testid":"task-source-provider-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Repository (e.g. owner/repo)",value:en,onChange:Y=>cn(Y.target.value),disabled:Ie,"data-testid":"task-source-repository-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Issue identifier",value:we,onChange:Y=>De(Y.target.value),disabled:Ie,"data-testid":"task-source-external-id-input"}),t.jsx("input",{type:"url",className:"modal-edit-input",placeholder:"Issue URL",value:oe,onChange:Y=>Pe(Y.target.value),disabled:Ie,"data-testid":"task-source-url-input"})]}),t.jsx("small",{children:"Leave all fields empty to clear source issue metadata."})]})})}):t.jsxs(t.Fragment,{children:[(()=>{const Y=e.title||e.description||e.id,Ke=!O&&Y.length>Rc;return t.jsxs(t.Fragment,{children:[t.jsx("h2",{className:"detail-title",children:Ke?Y.slice(0,Rc)+"…":Y}),Y.length>Rc&&t.jsx("button",{className:"detail-description-toggle",onClick:()=>q(!O),children:O?"Show less":"Show more"})]})})(),t.jsxs("div",{className:"detail-meta",children:["Created ",new Date(e.createdAt).toLocaleDateString()," · Updated"," ",new Date(e.updatedAt).toLocaleDateString()," ·",t.jsxs("label",{className:`card-priority-badge card-priority-badge--${Ne} detail-priority-chip ${ft?"detail-priority-chip--saving":""}`,children:[t.jsx("span",{children:"Priority:"}),t.jsx("select",{className:"detail-priority-select",value:Ne,onChange:Y=>{ht(Y.target.value)},disabled:ft,"aria-label":"Task priority",children:Zr.map(Y=>t.jsx("option",{value:Y,children:Y},Y))})]}),F&&t.jsxs("div",{className:"detail-provenance",children:[t.jsx(Hs,{"aria-hidden":"true"}),t.jsxs("span",{children:[S.sourceType==="agent_heartbeat"?t.jsxs(t.Fragment,{children:["Created by"," ",F.sourceAgentId?t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>L(F.sourceAgentId),children:F.label}):F.label]}):t.jsxs(t.Fragment,{children:["Created via ",F.label]}),F.parentTaskId&&t.jsxs(t.Fragment,{children:[" ","of"," ",t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>Ds(F.parentTaskId),children:F.parentTaskId})]}),F.contextInfo?` (${F.contextInfo})`:""]})]})]})]}),e.status==="failed"&&e.error&&t.jsxs("div",{className:"detail-error-alert",children:[t.jsx("span",{className:"detail-error-icon",children:"⚠"}),t.jsxs("div",{className:"detail-error-content",children:[t.jsx("div",{className:"detail-error-title",children:"Task Failed"}),t.jsx("div",{className:"detail-error-message",children:e.error})]})]}),!ze&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"detail-tabs",children:[t.jsx("button",{className:`detail-tab${b==="definition"?" detail-tab-active":""}`,onClick:()=>y("definition"),children:"Definition"}),t.jsx("button",{className:`detail-tab${b==="logs"?" detail-tab-active":""}`,onClick:()=>y("logs"),children:"Logs"}),(e.column==="in-progress"||e.column==="in-review"||e.column==="done")&&t.jsx("button",{className:`detail-tab${b==="changes"?" detail-tab-active":""}`,onClick:()=>y("changes"),children:"Changes"}),t.jsx("button",{className:`detail-tab${b==="comments"?" detail-tab-active":""}`,onClick:()=>y("comments"),children:"Comments"}),t.jsx("button",{className:`detail-tab${b==="documents"?" detail-tab-active":""}`,onClick:()=>y("documents"),children:"Documents"}),t.jsx("button",{className:`detail-tab${b==="model"?" detail-tab-active":""}`,onClick:()=>y("model"),children:"Model"}),t.jsx("button",{className:`detail-tab${b==="workflow"?" detail-tab-active":""}`,onClick:()=>y("workflow"),children:"Workflow"}),t.jsx("button",{className:`detail-tab${b==="stats"?" detail-tab-active":""}`,onClick:()=>y("stats"),children:"Stats"}),t.jsx("button",{className:`detail-tab${b==="routing"?" detail-tab-active":""}`,onClick:()=>y("routing"),children:"Routing"}),hn.map(({entry:Y,tabId:Ke})=>t.jsx("button",{className:`detail-tab${b===Ke?" detail-tab-active":""}`,onClick:()=>y(Ke),children:Y.slot.label},`plugin-tab-${Y.pluginId}-${Ke}`))]}),b==="workflow"?t.jsx("div",{className:"detail-section",children:t.jsx(rP,{taskId:e.id,results:yt,loading:at,enabledWorkflowSteps:Ht,canEdit:Wt,projectId:n,isTaskInProgress:e.column==="in-progress"&&e.status!=="paused",onWorkflowStepsChange:Wn})}):b==="model"?t.jsx("div",{className:"detail-section",children:t.jsx(UA,{task:e,addToast:h,onTaskUpdated:m,settings:ue})}):b==="logs"?t.jsxs("div",{className:`detail-section${R==="agent-log"?" detail-section--agent-log":""}`,children:[t.jsxs("div",{className:"log-subview-toggle",children:[t.jsx("button",{className:`log-subview-btn${R==="activity"?" log-subview-btn-active":""}`,onClick:()=>P("activity"),children:"Activity"}),t.jsx("button",{className:`log-subview-btn${R==="agent-log"?" log-subview-btn-active":""}`,onClick:()=>P("agent-log"),children:"Agent Log"})]}),R==="agent-log"?t.jsx(DA,{entries:as,loading:Is,executorModel:xP(e,ue),validatorModel:vP(e,ue),planningModel:wP(e,as,ue),hasMore:ls,onLoadMore:_s,loadingMore:ci,totalCount:Xs}):t.jsxs("div",{className:"detail-activity",children:[t.jsx("h4",{children:"Activity"}),S.activityLogTruncatedCount?t.jsxs("div",{className:"detail-log-truncated",children:["Showing the most recent ",S.log.length," activity entries."]}):null,S.log&&S.log.length>0?t.jsx("div",{className:"detail-activity-list",children:[...S.log].reverse().map((Y,Ke)=>t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-timestamp",children:jP(Y.timestamp)}),t.jsx("span",{className:"detail-log-action",children:Y.action})]}),Y.outcome&&t.jsx("div",{className:"detail-log-outcome",children:Y.outcome})]},Ke))}):t.jsx("div",{className:"detail-log-empty",children:"(no activity)"})]})]}):b==="changes"?t.jsx(QA,{taskId:e.id,worktree:e.worktree,projectId:n,column:e.column,mergeDetails:e.mergeDetails,modifiedFiles:e.modifiedFiles}):b==="comments"?t.jsx(WA,{task:e,addToast:h,projectId:n,onTaskUpdated:m}):b==="documents"?t.jsx(pP,{taskId:e.id,addToast:h,projectId:n,onTaskUpdated:m,canEdit:Wt}):zn?t.jsx("div",{className:"detail-section",children:t.jsx(Oi,{slotId:"task-detail-tab",projectId:n,pluginIds:[zn.entry.pluginId]})}):b==="stats"?t.jsx("div",{className:"detail-section",children:t.jsx(gP,{tokenUsage:S.tokenUsage,loading:A,task:S})}):b==="routing"?t.jsx("div",{className:"detail-section",children:t.jsx(dP,{task:e,settings:ue,addToast:h,onTaskUpdated:m})}):t.jsxs(t.Fragment,{children:[e.column==="done"&&e.summary&&t.jsxs("div",{className:"detail-section detail-summary",children:[t.jsx("h4",{children:"Summary"}),t.jsx("div",{className:"markdown-body",children:t.jsx(vi,{remarkPlugins:[yi],children:e.summary})})]}),t.jsx(GA,{task:e}),e.sourceIssue&&t.jsxs("div",{className:"detail-section detail-source-section",children:[t.jsxs("div",{className:"detail-source-header",children:[t.jsxs("div",{className:"detail-source-summary",children:[t.jsx("span",{className:"detail-source-label",children:"Source issue"}),e.sourceIssue.provider.toLowerCase()==="github"&&t.jsxs("span",{className:"detail-source-provider-badge","aria-label":"GitHub source issue",children:[t.jsx(Hs,{"aria-hidden":"true"}),t.jsx("span",{children:"GitHub"})]}),e.sourceIssue.url?t.jsx("a",{className:"detail-source-link detail-source-link--summary detail-source-number",href:e.sourceIssue.url,target:"_blank",rel:"noopener noreferrer",children:`(#${e.sourceIssue.issueNumber})`}):t.jsx("span",{className:"detail-source-number",children:`(#${e.sourceIssue.issueNumber})`})]}),t.jsx("button",{type:"button",className:"detail-source-toggle","aria-expanded":Nn,"aria-label":Nn?"Collapse source issue details":"Expand source issue details",onClick:()=>dn(Y=>!Y),children:t.jsx(Tn,{size:16,className:Nn?"detail-source-chevron--expanded":void 0})})]}),Nn&&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:[Za.length>0&&t.jsx("span",{className:"detail-provider-icons","data-testid":"detail-provider-icons",children:Za.map(Y=>t.jsx(qn,{provider:Y,size:"sm"},Y))}),t.jsxs("span",{className:"detail-meta-label",children:[t.jsx(Rn,{size:14,style:{verticalAlign:"middle",marginRight:6}}),"Agent"]})]}),t.jsxs("div",{className:"detail-agent-actions",children:[Xa?t.jsxs("span",{className:"detail-agent-chip",children:[t.jsx(Rn,{size:14}),Xa,t.jsx("button",{className:"detail-agent-clear",onClick:()=>void bs(),title:"Unassign agent",children:t.jsx(Jt,{size:12})})]}):t.jsx("button",{className:"btn btn-sm",onClick:()=>{ne?ee(!1):gs()},children:"Assign Agent"}),ne&&t.jsxs("div",{className:"agent-picker-dropdown",children:[ie&&t.jsx("div",{className:"agent-picker-loading",children:"Loading agents..."}),!ie&&U.filter(Y=>Y.state!=="terminated").map(Y=>t.jsxs("button",{className:`agent-picker-item${e.assignedAgentId===Y.id?" selected":""}`,onClick:()=>void Jn(Y.id),children:[t.jsx(Rn,{size:14}),t.jsx("span",{className:"agent-picker-name",children:Y.name}),t.jsx("span",{className:"agent-picker-role",children:Y.role})]},Y.id)),!ie&&U.filter(Y=>Y.state!=="terminated").length===0&&t.jsx("div",{className:"agent-picker-empty",children:"No agents available"})]})]})]})}),t.jsxs("div",{className:"detail-section detail-step-progress",children:[t.jsx("h4",{children:"Progress"}),S.steps&&S.steps.length>0?t.jsxs("div",{className:"step-progress-wrapper",children:[t.jsx("div",{className:"step-progress-bar",children:S.steps.map((Y,Ke)=>t.jsx("div",{className:`step-progress-segment step-progress-segment--${Y.status}`,"data-tooltip":`${Y.name} (${Y.status})`,style:{backgroundColor:kP(Y.status)}},Ke))}),t.jsxs("span",{className:"step-progress-label",children:[S.steps.filter(Y=>Y.status==="done").length,"/",S.steps.length," step",S.steps.length===1?"":"s"]})]}):t.jsx("div",{className:"step-progress-empty",children:"(no steps defined)"})]}),t.jsxs("div",{className:"detail-section",children:[!qe&&t.jsx("div",{className:"detail-spec-edit-trigger",children:t.jsx("button",{className:"btn btn-sm",onClick:Ii,children:"Edit"})}),qe?t.jsxs("div",{className:"spec-editor-edit-mode",children:[t.jsx("textarea",{className:"spec-editor-textarea",value:Qe,onChange:Y=>ve(Y.target.value),onKeyDown:Fl,disabled:se,placeholder:"Enter task specification in Markdown...",rows:12}),t.jsxs("div",{className:"spec-editor-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:ui,disabled:se,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void pa(),disabled:Qe===(S.prompt||"")||se,children:se?"Saving…":"Save"})]}),t.jsxs("div",{className:"spec-editor-hint",children:[t.jsx("kbd",{children:"Ctrl"}),"+",t.jsx("kbd",{children:"Enter"})," to save · ",t.jsx("kbd",{children:"Escape"})," to cancel"]}),t.jsxs("div",{className:"spec-editor-revision",children:[t.jsx("h4",{children:"Ask AI to Revise"}),t.jsx("p",{className:"spec-editor-revision-help",children:"Provide feedback for the AI to improve this specification. The task will move to planning for replanning."}),t.jsx("textarea",{className:"spec-editor-feedback",value:Oe,onChange:Y=>ae(Y.target.value),placeholder:"e.g., 'Add more details about error handling', 'Split this into smaller steps', 'Include tests for the API endpoints'...",disabled:xe,rows:4,maxLength:2e3}),t.jsxs("div",{className:"spec-editor-revision-actions",children:[t.jsxs("span",{className:"spec-editor-char-count",children:[Oe.length,"/2000"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void zl(),disabled:!Oe.trim()||xe,children:xe?"Requesting…":"Request AI Revision"})]})]})]}):A?t.jsx("div",{className:"spec-loading",children:"Loading specification…"}):S.prompt?t.jsx("div",{className:"markdown-body",children:t.jsx(vi,{remarkPlugins:[yi],children:S.prompt.replace(/^#\s+[^\n]*\n+/,"")})}):t.jsx("div",{className:"detail-prompt",children:"(no prompt)"})]}),t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Attachments"}),Z.length>0?t.jsx("div",{className:"detail-attachments-grid",children:Z.map(Y=>{const Ke=xi(`/api/tasks/${e.id}/attachments/${Y.filename}`);return t.jsxs("div",{className:"detail-attachment-card",children:[t.jsx("a",{className:"detail-attachment-link",href:Ke,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{src:Ke,alt:Y.originalName,className:"detail-attachment-image"})}),t.jsxs("div",{className:"detail-attachment-meta",children:[Y.originalName," (",NP(Y.size),")"]}),t.jsx("button",{className:"detail-attachment-delete",onClick:()=>es(Y.filename),title:"Delete attachment",children:"×"})]},Y.filename)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no attachments)"}),t.jsx("input",{className:"detail-hidden-file-input",ref:St,type:"file",accept:"image/*",onChange:Vn}),t.jsx("button",{className:"btn btn-sm",onClick:()=>St.current?.click(),disabled:k,children:k?"Uploading…":"Attach Screenshot"})]}),t.jsxs("div",{className:"detail-deps",children:[t.jsx("h4",{children:"Dependencies"}),$.length>0?t.jsx("ul",{className:"detail-dep-list",children:$.map(Y=>{const Ke=s.find(Kt=>Kt.id===Y),bt=Ke?.title||Ke?.description||Y;return t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>Ds(Y),onKeyDown:Kt=>{(Kt.key==="Enter"||Kt.key===" ")&&(Kt.preventDefault(),Ds(Y))},role:"link",tabIndex:0,title:`Click to view ${Y}`,children:[t.jsx("span",{className:"detail-dep-id",children:Y}),t.jsx("span",{className:"detail-dep-label",children:Sh(bt,40)})]}),t.jsx("button",{className:"dep-remove-btn",onClick:Kt=>$s(Kt,Y),title:`Remove dependency ${Y}`,children:"×"})]},Y)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no dependencies)"}),t.jsxs("div",{className:"dep-trigger-wrap",children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{H&&le(""),K(Y=>!Y)},children:"Add Dependency"}),H&&(()=>{const Y=pe.toLowerCase(),Ke=Y?Qa.filter(bt=>bt.id.toLowerCase().includes(Y)||bt.title&&bt.title.toLowerCase().includes(Y)||bt.description&&bt.description.toLowerCase().includes(Y)):Qa;return t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:pe,onChange:bt=>le(bt.target.value),onClick:bt=>bt.stopPropagation()}),Ke.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Ke.map(bt=>t.jsxs("div",{className:"dep-dropdown-item",onClick:()=>{ts(bt.id),K(!1)},children:[t.jsx("span",{className:"dep-dropdown-id",children:bt.id}),t.jsx("span",{className:"dep-dropdown-title",children:Sh(bt.title||bt.description||bt.id,30)})]},bt.id))]})})()]})]}),e.column==="in-review"&&t.jsx("div",{className:"detail-section detail-pr-section",children:t.jsx(HA,{taskId:e.id,projectId:n,prInfo:e.prInfo,automationStatus:e.status??null,autoMerge:ue?.autoMerge??!1,prAuthAvailable:f??!1,onPrCreated:Y=>{e.prInfo=Y,h(`PR #${Y.number} created`,"success")},onPrUpdated:Y=>{e.prInfo=Y},addToast:h})})]})]})]}),t.jsx("div",{className:"modal-actions",children:ze?t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"modal-edit-hint",children:[t.jsx("kbd",{children:"Ctrl+Enter"})," to save · ",t.jsx("kbd",{children:"Escape"})," to cancel"]}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("button",{className:"btn btn-sm",onClick:G,disabled:Ie,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:He,disabled:Ie,children:Ie?"Saving…":"Save"})]}):t.jsxs(t.Fragment,{children:[e.column==="triage"&&e.status==="awaiting-approval"&&S.prompt&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:rt,children:"Approve Plan"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:Mt,children:"Reject Plan"})]}),e.column==="triage"&&e.status!=="awaiting-approval"&&!_&&t.jsx("button",{className:"btn btn-sm btn-danger",onClick:Ve,"aria-label":"Delete task",title:"Delete task",children:"Delete"}),(e.column!=="triage"||e.status==="awaiting-approval"||_||e.paused)&&t.jsxs("div",{className:"detail-actions-dropdown",ref:On,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>{bn(Y=>!Y),Dt(!1)},"aria-haspopup":"menu","aria-expanded":En,children:["Actions",t.jsx(un,{size:12})]}),En&&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:()=>ln(Ve),children:"Delete"}),u&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ln(X),children:"Duplicate"}),(e.column==="done"||e.column==="in-review")&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ln(It),children:"Refine"}),t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ln(Be),children:"Respecify"}),_&&c&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ln(on),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:()=>ln(Un),children:"Reset"}),e.column!=="done"&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ln(Me),children:e.paused?"Unpause":"Pause"})]})]}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("div",{className:"detail-move-dropdown",ref:xn,children:e.column==="in-review"?t.jsxs("div",{className:"detail-move-actions-in-review",children:[t.jsxs("div",{children:[t.jsxs("button",{ref:rn,className:"btn btn-primary btn-sm detail-move-btn",onClick:qi,onKeyDown:ao,disabled:!rs,"aria-label":rs?`Move to ${Qn[rs]}`:void 0,"aria-haspopup":Ss?"menu":void 0,"aria-expanded":Ss?Rt:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",rs?Qn[rs]:""]}),Ss&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(un,{size:12})})]}),Rt&&Ss&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:fa,children:mi.map(Y=>t.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>vn(Y),onKeyDown:fa,children:Y==="in-progress"?"Back to In Progress":`Move to ${Qn[Y]}`},Y))})]}),ga?t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!0,children:ga}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Kn,children:"Merge & Close"})]}):t.jsxs("div",{children:[t.jsxs("button",{ref:rn,className:"btn btn-primary btn-sm detail-move-btn",onClick:qi,onKeyDown:ao,disabled:!rs,"aria-label":rs?`Move to ${Qn[rs]}`:void 0,"aria-haspopup":Ss?"menu":void 0,"aria-expanded":Ss?Rt:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",rs?Qn[rs]:""]}),Ss&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(un,{size:12})})]}),Rt&&Ss&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:fa,children:mi.map(Y=>t.jsxs("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>vn(Y),onKeyDown:fa,children:["Move to ",Qn[Y]]},Y))})]})})]})}),re&&t.jsx("div",{className:"modal-overlay open detail-refine-overlay",onClick:Gn,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal detail-refine-modal",onClick:Y=>Y.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:Gn,"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:Q,onChange:Y=>Fe(Y.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:[Q.length,"/2000 characters"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:ps,disabled:!Q.trim()||Je,children:Je?"Creating...":"Create Refinement Task"})]})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:Gn,disabled:Je,children:"Cancel"})})]})}),E&&t.jsx(i.Suspense,{fallback:null,children:t.jsx(_P,{agentId:E,projectId:n,onClose:()=>L(null),addToast:h})})]})}function RP({onClose:e,...n}){const s=i.useRef(null);wi(s,!0,"task-detail-modal-size");const a=Ri(e);return t.jsx("div",{className:"modal-overlay open",...a,role:"dialog","aria-modal":"true",children:t.jsx("div",{className:"modal modal-lg task-detail-modal",ref:s,children:t.jsx(Qg,{...n,onRequestClose:e})})})}const Ao={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-secondary)"},Eh=new Set(["planning","researching","executing","finalizing","merging"]),Xg=["title","status","column","dependencies","progress"],TP=["title","status","column"];function IP(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function $P(e){return e==="online"?"●":e==="connecting"?"◐":e==="error"?"✕":"○"}function Mh(e){try{const n=Zn("kb-dashboard-list-columns",e);if(n){const a=JSON.parse(n).filter(r=>Xg.includes(r));if(a.length>0)return new Set(a)}}catch{}return new Set(TP)}function _h(e){try{const n=Zn("kb-dashboard-hide-done",e);if(n!==null)return n==="true"}catch{}return!1}function Ah(e){try{const n=Zn("kb-dashboard-list-collapsed",e);if(n){const a=JSON.parse(n).filter(r=>ea.includes(r));if(a.length>0)return new Set(a)}}catch{}return new Set}function Ph(e){try{const n=Zn("kb-dashboard-selected-tasks",e);if(n){const s=JSON.parse(n);return new Set(s)}}catch{}return new Set}function Rh(e){try{const n=Zn("kb-dashboard-list-selected-task",e);if(typeof n=="string"&&n.trim().length>0)return n}catch{}return null}function Th(e){try{const s=Zn("kb-dashboard-list-sidebar-width",e);if(!s)return 400;const a=Number(s);if(Number.isFinite(a)&&a>0)return a}catch{}return 400}const ul=280,Pd=.65,Po=16;function Rd(e){return Math.max(ul,e*Pd)}function Ro(e,n){const s=Rd(n);return Math.min(Math.max(e,ul),s)}function DP(e){return e.status==="executing"||e.column==="in-progress"}function Ih(e){const n=Pf(e);return n.total===0||!DP(e)?{label:"-",percent:0,hasProgress:!1}:{label:`${n.completed}/${n.total}`,percent:n.completed/n.total*100,hasProgress:!0}}function LP({tasks:e,onMoveTask:n,onRetryTask:s,onDeleteTask:a,onMergeTask:r,onResetTask:o,onDuplicateTask:l,onOpenDetail:c,addToast:d,globalPaused:u,onNewTask:m,onQuickCreate:h,availableModels:f,favoriteProviders:p=[],favoriteModels:g=[],onToggleFavorite:x,onToggleModelFavorite:v,onPlanningMode:b,onSubtaskBreakdown:y,onTasksUpdated:j,projectId:C,projectName:A,taskStuckTimeoutMs:N,searchQuery:S="",lastFetchTimeMs:_,prAuthAvailable:T}){const[M,E]=i.useState("id"),[L,F]=i.useState("desc"),[R,P]=i.useState(null),[O,q]=i.useState(null),[Z,z]=i.useState(null),I=Pi()==="mobile",{confirm:$}=qs(),[w,H]=i.useState(()=>Mh(C)),[K,pe]=i.useState(()=>_h(C)),[le,B]=i.useState(()=>Ah(C));i.useEffect(()=>{typeof window<"u"&&us("kb-dashboard-list-columns",JSON.stringify([...w]),C)},[C,w]),i.useEffect(()=>{typeof window<"u"&&us("kb-dashboard-hide-done",K.toString(),C)},[K,C]),i.useEffect(()=>{typeof window<"u"&&us("kb-dashboard-list-collapsed",JSON.stringify([...le]),C)},[le,C]);const[ye,U]=i.useState(!1),[te,ne]=i.useState(!1),[ee,ie]=i.useState(()=>Ph(C)),[ge,se]=i.useState(()=>Rh(C)),[Ae,xe]=i.useState(null),[Se,qe]=i.useState(()=>Th(C)),We=i.useRef(null),Qe=i.useRef(null);i.useEffect(()=>{H(Mh(C)),pe(_h(C)),B(Ah(C)),ie(Ph(C));const we=Rh(C);se(we),xe(we?e.find(De=>De.id===we)??null:null),qe(Th(C))},[C,e]),i.useEffect(()=>{typeof window<"u"&&us("kb-dashboard-selected-tasks",JSON.stringify([...ee]),C)},[C,ee]),i.useEffect(()=>{if(!(typeof window>"u")){if(ge){us("kb-dashboard-list-selected-task",ge,C);return}La("kb-dashboard-list-selected-task",C)}},[C,ge]),i.useEffect(()=>{if(!ge){xe(null);return}const we=e.find(De=>De.id===ge);we&&xe(De=>!De||De.id!==ge?we:{...De,...we})},[ge,e]),i.useEffect(()=>{if(I||typeof ResizeObserver>"u")return;const we=We.current;if(!we)return;const De=()=>{const Pe=Ro(Se,we.clientWidth);Pe!==Se&&qe(Pe)};De();const oe=new ResizeObserver(De);return oe.observe(we),()=>oe.disconnect()},[I,Se]),i.useEffect(()=>{if(I||typeof ResizeObserver>"u")return;const we=Qe.current,De=We.current;if(!we||!De)return;let oe=null,Pe=we.offsetWidth;const Ce=new ResizeObserver(()=>{const J=Ro(we.offsetWidth,De.clientWidth);J!==Pe&&(Pe=J,oe&&clearTimeout(oe),oe=setTimeout(()=>{try{us("kb-dashboard-list-sidebar-width",String(J),C)}catch{}},200))});return Ce.observe(we),()=>{Ce.disconnect(),oe&&clearTimeout(oe)}},[I,C]);const ve=i.useCallback(()=>{ne(we=>(we&&ie(new Set),!we))},[]),Oe=i.useCallback(we=>{ie(De=>{const oe=new Set(De);return oe.has(we)?oe.delete(we):oe.add(we),oe})},[]),ae=i.useCallback(()=>{ie(new Set)},[]),re=i.useCallback(we=>{H(De=>{const oe=new Set(De);return oe.has(we)?oe.size>1&&oe.delete(we):oe.add(we),oe})},[]),je={title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},Q=i.useCallback(we=>{M===we?F(De=>De==="asc"?"desc":"asc"):(E(we),F("asc"))},[M]),Fe=i.useCallback(we=>{z(De=>De===we?null:we)},[]),Je=i.useCallback(we=>{B(De=>{const oe=new Set(De);return oe.has(we)?oe.delete(we):oe.add(we),oe})},[]),be=i.useCallback(()=>{z(null)},[]),ze=i.useMemo(()=>{let we=S?e.filter(Ce=>Ce.id.toLowerCase().includes(S.toLowerCase())||Ce.title&&Ce.title.toLowerCase().includes(S.toLowerCase())||Ce.description.toLowerCase().includes(S.toLowerCase())):[...e];K&&!Z&&(we=we.filter(Ce=>Ce.column!=="done"&&Ce.column!=="archived"));const oe=[...Z?we.filter(Ce=>Ce.column===Z):we].sort((Ce,J)=>{let Ie=0;switch(M){case"id":Ie=Ce.id.localeCompare(J.id);break;case"title":Ie=(Ce.title||Ce.description).localeCompare(J.title||J.description);break;case"status":Ie=(Ce.status||"").localeCompare(J.status||"");break;case"column":Ie=Ce.column.localeCompare(J.column);break}return L==="asc"?Ie:-Ie}),Pe={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};return oe.forEach(Ce=>Pe[Ce.column].push(Ce)),Pe},[e,S,M,L,K,Z]),tt=i.useMemo(()=>Object.values(ze).reduce((we,De)=>we+De.length,0),[ze]),kt=i.useMemo(()=>e.filter(we=>we.column==="done"||we.column==="archived").length,[e]),ke=i.useMemo(()=>K?kt:0,[K,kt]),ce=i.useCallback(()=>{const we=Object.values(ze).flat().filter(De=>De.column!=="archived").map(De=>De.id);ie(De=>{if(we.every(Pe=>De.has(Pe))){const Pe=new Set(De);return we.forEach(Ce=>Pe.delete(Ce)),Pe}else return new Set([...De,...we])})},[ze]),Te=i.useMemo(()=>{const we=Object.values(ze).flat().filter(De=>De.column!=="archived");return we.length===0?!1:we.every(De=>ee.has(De.id))},[ze,ee]),he=i.useMemo(()=>{const we=Object.values(ze).flat().filter(oe=>oe.column!=="archived");if(we.length===0)return!1;const De=we.filter(oe=>ee.has(oe.id)).length;return De>0&&De<we.length},[ze,ee]),[Le,st]=i.useState("__no_change__"),[it,lt]=i.useState("__no_change__"),[$e,Ue]=i.useState("__no_change__"),[Xe,wt]=i.useState([]),[Re,xt]=i.useState(!1),Pt=i.useMemo(()=>$e&&$e!=="__no_change__"?Xe.find(we=>we.id===$e):void 0,[Xe,$e]),[Ct,Ot]=i.useState(!1);i.useEffect(()=>{if(ee.size===0)return;let we=!1;return(async()=>{xt(!0);try{const oe=await sl();we||wt(oe)}catch(oe){console.error("Failed to fetch nodes for bulk edit",oe),we||wt([])}finally{we||xt(!1)}})(),()=>{we=!0}},[ee.size]);const zt=i.useCallback(async()=>{if(ee.size===0)return;const we=Array.from(ee).filter(oe=>{const Pe=e.find(Ce=>Ce.id===oe);return Pe&&Pe.column!=="archived"});if(we.length===0){d("No valid tasks to update (archived tasks cannot be modified)","error");return}const De={taskIds:we};if(Le!=="__no_change__")if(Le==="")De.modelProvider=null,De.modelId=null;else{const oe=Le.indexOf("/");oe!==-1&&(De.modelProvider=Le.slice(0,oe),De.modelId=Le.slice(oe+1))}if(it!=="__no_change__")if(it==="")De.validatorModelProvider=null,De.validatorModelId=null;else{const oe=it.indexOf("/");oe!==-1&&(De.validatorModelProvider=it.slice(0,oe),De.validatorModelId=it.slice(oe+1))}if($e!=="__no_change__"&&($e===""?De.nodeId=null:De.nodeId=$e),Object.keys(De).length===1){d("No changes to apply","info");return}Ot(!0);try{const oe=await tw(De.taskIds,De.modelProvider,De.modelId,De.validatorModelProvider,De.validatorModelId,void 0,void 0,De.nodeId,C);j&&j(oe.updated),d(`Updated ${we.length} task${we.length===1?"":"s"}`,"success"),ae(),st("__no_change__"),lt("__no_change__"),Ue("__no_change__")}catch(oe){d(_e(oe)||"Failed to update models","error")}finally{Ot(!1)}},[ee,e,Le,it,$e,C,d,ae,j]),Nt=i.useCallback(we=>{if(I){c(we,{origin:"list-mobile"});return}se(we.id),xe(we)},[I,c]),jt=i.useRef(null),Yt=i.useRef(null);i.useEffect(()=>()=>{jt.current&&clearTimeout(jt.current)},[]);const Bt=i.useCallback(we=>{if(se(we.id),xe(we),"prompt"in we){Yt.current=null,jt.current&&(clearTimeout(jt.current),jt.current=null);return}Yt.current=we.id,jt.current&&clearTimeout(jt.current),jt.current=setTimeout(()=>{jt.current=null,Yt.current===we.id&&Ia(we.id,C).then(oe=>{Yt.current===oe.id&&xe(Pe=>!Pe||Pe.id!==oe.id?Pe:{...Pe,...oe})}).catch(()=>{})},200)},[C]),qt=i.useCallback((we,De)=>{if(De.paused){we.preventDefault();return}we.dataTransfer.setData("text/plain",De.id),we.dataTransfer.effectAllowed="move",P(De.id)},[]),wn=i.useCallback(()=>{P(null),q(null)},[]),mn=i.useCallback(we=>{if(I)return;we.preventDefault();const De=We.current;if(!De)return;const oe=De.getBoundingClientRect(),Pe=J=>{const Ie=J.clientX-oe.left;qe(Ro(Ie,oe.width))},Ce=()=>{window.removeEventListener("mousemove",Pe),window.removeEventListener("mouseup",Ce)};window.addEventListener("mousemove",Pe),window.addEventListener("mouseup",Ce)},[I]),Xt=i.useCallback(we=>{if(I)return;const De=We.current?.clientWidth??0,oe=Se/Pd+Po,Pe=Math.max(De,oe),Ce=Rd(Pe);if(we.key==="ArrowLeft"||we.key==="ArrowRight"){we.preventDefault();const J=we.key==="ArrowLeft"?-Po:Po;qe(Ie=>Ro(Ie+J,Pe));return}if(we.key==="Home"){we.preventDefault(),qe(ul);return}we.key==="End"&&(we.preventDefault(),qe(Ce))},[I,Se]),Vt=i.useCallback((we,De)=>{we.preventDefault(),we.dataTransfer.dropEffect="move",q(De)},[]),Ft=i.useCallback(()=>{q(null)},[]),Zt=i.useCallback(async(we,De)=>{we.preventDefault(),q(null);const oe=we.dataTransfer.getData("text/plain");if(oe){if(De==="archived"){d("Tasks can only be archived via the archive button","error");return}try{const Ce=e.find(de=>de.id===oe)?.steps.some(de=>de.status!=="pending")??!1,J=(De==="todo"||De==="triage")&&Ce;let Ie;if(J){if(await $({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))Ie={preserveProgress:!0};else if(!await $({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await n(oe,De,Ie)}catch(Pe){d(_e(Pe),"error")}}},[n,d,e,$]),en=we=>M!==we?t.jsx(Gp,{size:14,className:"sort-icon"}):L==="asc"?t.jsx(Zi,{size:14,className:"sort-icon active"}):t.jsx(Hr,{size:14,className:"sort-icon active"}),cn=we=>t.jsxs("div",{id:we,className:"list-view-options-panel",children:[t.jsx("div",{className:"list-view-options-columns",children:Xg.map(De=>{const oe=w.has(De),Pe=oe&&w.size===1;return t.jsxs("label",{className:`list-column-dropdown-item${Pe?" disabled":""}`,title:Pe?"At least one column must be visible":"",children:[t.jsx("input",{type:"checkbox",checked:oe,onChange:()=>re(De),disabled:Pe}),t.jsx("span",{children:je[De]})]},De)})}),t.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>pe(De=>!De),"aria-pressed":K,title:K?"Show done tasks":"Hide done tasks",children:[K?t.jsx(Va,{size:14}):t.jsx(Ud,{size:14}),K?"Show Done":"Hide Done"]}),t.jsx("div",{className:"list-drop-zones list-drop-zones--sidebar",children:ea.map(De=>{const oe=e.filter(Ie=>Ie.column===De).length,Pe=De==="done"||De==="archived",Ce=K&&Pe?0:oe,J=K&&Pe&&oe>0;return t.jsxs("div",{className:`list-drop-zone${O===De?" drag-over":""}${Z===De?" active":""}`,onClick:()=>Fe(De),onDragOver:Ie=>Vt(Ie,De),onDragLeave:Ft,onDrop:Ie=>Zt(Ie,De),"data-column":De,children:[t.jsx("span",{className:`list-section-dot dot-${De}`}),t.jsx("span",{className:"drop-zone-label",children:Qn[De]}),t.jsx("span",{className:"drop-zone-count",children:J?`${Ce} of ${oe}`:oe})]},De)})})]});return t.jsxs("div",{className:"list-view",children:[I&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"list-toolbar",children:[t.jsx("button",{className:"btn btn-sm",onClick:ve,"aria-pressed":te,children:te?"Done Editing":"Bulk Edit"}),m?t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:m,children:"+ New Task"}):null,t.jsxs("button",{className:"btn btn-sm list-view-options-toggle",onClick:()=>U(we=>!we),"aria-expanded":ye,"aria-controls":"list-view-options-panel-mobile",children:[t.jsx(wu,{size:14}),"View options"]}),t.jsx("div",{className:"list-stats",children:Z?`${tt} of ${e.length} tasks in ${Qn[Z]}`:`${tt} of ${e.length} tasks`})]}),ye?t.jsx("div",{className:"list-toolbar-mobile-options",children:cn("list-view-options-panel-mobile")}):null]}),t.jsx("div",{className:"list-table-container",children:t.jsxs("div",{className:I?"":"list-split-layout","data-testid":I?void 0:"list-split-layout",ref:We,children:[t.jsxs("div",{className:I?"":"list-split-sidebar","data-testid":I?void 0:"list-split-sidebar",ref:Qe,style:I?void 0:{width:`${Se}px`},children:[!I&&t.jsxs("aside",{className:"list-sidebar-controls","aria-label":"List controls",children:[t.jsxs("div",{className:"list-sidebar-controls__header",children:[t.jsxs("p",{className:"list-stats",children:[Z?`${tt} of ${e.length} tasks in ${Qn[Z]}`:`${tt} of ${e.length} tasks`,ke>0&&!Z&&t.jsxs("span",{className:"list-stats-hidden",children:[" (",ke," hidden)"]})]}),t.jsxs("div",{className:"list-sidebar-controls__actions",children:[m?t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:m,children:"+ New Task"}):null,t.jsx("button",{className:"btn btn-sm",onClick:ve,"aria-pressed":te,children:te?"Done Editing":"Bulk Edit"})]}),t.jsxs("div",{className:"list-sidebar-summary-chips",children:[Z?t.jsx("button",{className:"btn btn-sm",onClick:be,"aria-label":"Clear column filter",children:`Filter: ${Qn[Z]}`}):null,K?t.jsx("span",{className:"list-sidebar-chip",children:"Done hidden"}):null,te?t.jsx("span",{className:"list-sidebar-chip",children:"Bulk edit"}):null,te&&ee.size>0?t.jsx("button",{className:"btn btn-sm",onClick:ae,children:`${ee.size} selected`}):null]})]}),t.jsxs("button",{className:"btn btn-sm list-view-options-toggle",onClick:()=>U(we=>!we),"aria-expanded":ye,"aria-controls":"list-view-options-panel",children:[t.jsx(wu,{size:14}),"View options"]}),ye&&cn("list-view-options-panel"),te&&ee.size>0&&f&&f.length>0&&t.jsxs("div",{className:"bulk-edit-toolbar",children:[t.jsx("span",{className:"bulk-edit-label",children:"Bulk Edit Models & Node:"}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx(hs,{models:f,value:Le,onChange:st,label:"Executor Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:p,onToggleFavorite:x,favoriteModels:g,onToggleModelFavorite:v})}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx(hs,{models:f,value:it,onChange:lt,label:"Reviewer Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:p,onToggleFavorite:x,favoriteModels:g,onToggleModelFavorite:v})}),t.jsxs("div",{className:"bulk-edit-dropdown bulk-edit-node-wrap",children:[t.jsxs("select",{className:"select bulk-node-select",value:$e,onChange:we=>Ue(we.target.value),"aria-label":"Node Override",disabled:Re,children:[t.jsx("option",{value:"__no_change__",children:"No change"}),t.jsx("option",{value:"",children:"Use project default"}),Xe.map(we=>t.jsx("option",{value:we.id,children:`${$P(we.status)} ${we.name||we.id} (${IP(we.status)})`},we.id))]}),Pt?t.jsx(ia,{status:Pt.status,showLabel:!0}):null]}),t.jsx("button",{className:"btn btn-primary btn-sm bulk-edit-apply-btn",onClick:zt,disabled:Ct||Le==="__no_change__"&&it==="__no_change__"&&$e==="__no_change__",children:Ct?"Applying...":"Apply"})]})]}),t.jsx("div",{className:"list-quick-entry-above-table",children:t.jsx($f,{onCreate:h??(async()=>d("Task creation not available","error")),addToast:d,tasks:e,availableModels:f,onPlanningMode:b,onSubtaskBreakdown:y,projectId:C,autoExpand:!1,favoriteProviders:p,favoriteModels:g,onToggleFavorite:x,onToggleModelFavorite:v})}),tt===0?t.jsx("div",{className:"list-empty",children:S?"No tasks match your filter":"No tasks yet"}):I?t.jsx("div",{className:"list-cards",children:ea.map(we=>{if(Z&&we!==Z||K&&(we==="done"||we==="archived")&&!Z)return null;const De=ze[we],oe=De.length===0;if(S&&oe)return null;const Pe=le.has(we);return t.jsxs(i.Fragment,{children:[t.jsxs("div",{className:`list-card-section-header${Pe?" list-section-header--collapsed":""}`,onClick:()=>Je(we),"aria-expanded":!Pe,role:"button",tabIndex:0,onKeyDown:Ce=>{(Ce.key==="Enter"||Ce.key===" ")&&(Ce.preventDefault(),Je(we))},children:[t.jsx(Tn,{size:14,className:`list-section-chevron${Pe?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${we}`}),t.jsx("span",{className:"list-section-title",children:Qn[we]}),t.jsx("span",{className:"list-section-count",children:De.length})]}),!Pe&&t.jsx(t.Fragment,{children:oe?t.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):De.map(Ce=>{const J=Ce.status==="failed",Ie=Ce.paused===!0,de=rl(Ce,N,_),Ne=!u&&!J&&!Ie&&!de&&(Ce.column==="in-progress"||Eh.has(Ce.status)),Ye=typeof Ce.status=="string"&&Ce.status.trim().length>0,ft=!!(Ce.dependencies&&Ce.dependencies.length>0),tn=Ih(Ce),$t=tn.hasProgress,Rt=te;return t.jsxs("div",{className:`list-card${Ne?" agent-active":""}${Rt?" list-card--selectable":""}`,onClick:()=>Nt(Ce),"data-id":Ce.id,children:[Rt&&t.jsx("label",{className:"list-card-checkbox",onClick:Dt=>Dt.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:ee.has(Ce.id),onChange:Dt=>{Dt.stopPropagation(),Oe(Ce.id)},onClick:Dt=>Dt.stopPropagation(),disabled:Ce.column==="archived","aria-label":`Select ${Ce.id}`})}),t.jsxs("div",{className:"list-card-row",children:[t.jsx("span",{className:"list-card-id",children:Ce.id}),Ce.executionMode==="fast"&&t.jsxs("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",title:"Fast mode","aria-label":"Fast mode",children:[t.jsx(Xn,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),t.jsx("span",{className:"list-card-spacer"}),de?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):Ye?t.jsx("span",{className:`list-status-badge list-status-badge--${Ce.column}${J?" failed":""}${Ne?" pulsing":""}`,children:Ce.status}):null]}),t.jsx("div",{className:"list-card-row",children:t.jsx("div",{className:"list-card-title",children:Ce.title||Ce.description})}),(ft||$t)&&t.jsxs("div",{className:"list-card-row list-card-meta",children:[ft&&t.jsxs("span",{className:"list-dep-badge",title:Ce.dependencies.join(", "),children:[t.jsx(Pa,{size:12})," ",Ce.dependencies.length]}),$t&&t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${tn.percent}%`,backgroundColor:Ao[Ce.column]}})}),t.jsx("span",{className:"list-progress-label",children:tn.label})]})]})]},Ce.id)})})]},we)})}):t.jsxs("table",{className:"list-table",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[te&&t.jsx("th",{className:"list-header-cell list-header-checkbox",children:t.jsx("input",{type:"checkbox",checked:Te,ref:we=>{we&&(we.indeterminate=he)},onChange:ce,"aria-label":"Select all visible tasks"})}),w.has("title")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Q("title"),children:["Title ",en("title")]}),w.has("status")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Q("status"),children:["Status ",en("status")]}),w.has("column")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Q("column"),children:["Column ",en("column")]}),w.has("dependencies")&&t.jsx("th",{className:"list-header-cell",children:"Dependencies"}),w.has("progress")&&t.jsx("th",{className:"list-header-cell",children:"Progress"})]})}),t.jsx("tbody",{children:ea.map(we=>{if(Z&&we!==Z||K&&(we==="done"||we==="archived")&&!Z)return null;const De=ze[we],oe=De.length===0;if(S&&oe)return null;const Pe=le.has(we);return t.jsxs(i.Fragment,{children:[t.jsx("tr",{className:`list-section-header${Pe?" list-section-header--collapsed":""}`,onClick:()=>Je(we),"aria-expanded":!Pe,children:t.jsxs("th",{colSpan:w.size+(te?1:0),className:"list-section-cell",children:[t.jsx(Tn,{size:14,className:`list-section-chevron${Pe?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${we}`}),t.jsx("span",{className:"list-section-title",children:Qn[we]}),t.jsx("span",{className:"list-section-count",children:De.length})]})}),!Pe&&t.jsx(t.Fragment,{children:oe?t.jsx("tr",{className:"list-section-empty",children:t.jsx("td",{colSpan:w.size+(te?1:0),className:"list-empty-cell",children:"No tasks"})}):De.map(Ce=>{const J=Ce.status==="failed",Ie=Ce.paused===!0,de=rl(Ce,N,_),Ne=!u&&!J&&!Ie&&!de&&(Ce.column==="in-progress"||Eh.has(Ce.status)),Ye=R===Ce.id;return t.jsxs("tr",{className:`list-row${J?" failed":""}${Ie?" paused":""}${de?" stuck":""}${Ne?" agent-active":""}${Ye?" dragging":""}${ge===Ce.id?" list-row--selected":""}`,onClick:()=>Nt(Ce),draggable:!Ie,onDragStart:ft=>qt(ft,Ce),onDragEnd:wn,"data-id":Ce.id,children:[te&&t.jsx("td",{className:"list-cell list-cell-checkbox",children:t.jsx("input",{type:"checkbox",checked:ee.has(Ce.id),onChange:ft=>{ft.stopPropagation(),Oe(Ce.id)},onClick:ft=>ft.stopPropagation(),disabled:Ce.column==="archived","aria-label":`Select ${Ce.id}`})}),w.has("title")&&t.jsx("td",{className:"list-cell list-cell-title",children:t.jsxs("div",{className:"list-title-content",children:[t.jsx("span",{className:"list-title-id",children:Ce.id}),t.jsxs("div",{className:"list-title-row",children:[Ce.executionMode==="fast"&&t.jsxs("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",title:"Fast mode","aria-label":"Fast mode",children:[t.jsx(Xn,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),t.jsx("span",{className:"list-title-text",children:Ce.title||Ce.description})]})]})}),w.has("status")&&t.jsx("td",{className:"list-cell",children:de?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):Ce.status?t.jsx("span",{className:`list-status-badge list-status-badge--${Ce.column}${J?" failed":""}${Ne?" pulsing":""}`,children:Ce.status}):t.jsx("span",{className:"list-status-badge",children:"-"})}),w.has("column")&&t.jsx("td",{className:"list-cell",children:t.jsx("span",{className:"list-column-badge",style:{background:`${Ao[Ce.column]}20`,color:Ao[Ce.column]},children:Qn[Ce.column]})}),w.has("dependencies")&&t.jsx("td",{className:"list-cell list-cell-deps",children:Ce.dependencies&&Ce.dependencies.length>0?t.jsxs("span",{className:"list-dep-badge",title:Ce.dependencies.join(", "),children:[t.jsx(Pa,{size:12})," ",Ce.dependencies.length]}):"-"}),w.has("progress")&&t.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const ft=Ih(Ce);return ft.hasProgress?t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${ft.percent}%`,backgroundColor:Ao[Ce.column]}})}),t.jsx("span",{className:"list-progress-label",children:ft.label})]}):"-"})()})]},Ce.id)})})]},we)})})]})]}),!I&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"list-split-resize-handle","data-testid":"list-split-resize-handle",onMouseDown:mn,onKeyDown:Xt,role:"separator",tabIndex:0,"aria-orientation":"vertical","aria-label":"Resize task list sidebar","aria-valuemin":ul,"aria-valuemax":Math.round(Rd(We.current?.clientWidth??Se/Pd+Po)),"aria-valuenow":Math.round(Se)}),t.jsx("div",{className:"list-split-detail","data-testid":"list-split-detail",children:Ae?t.jsx("div",{className:"list-split-detail-content","data-testid":"list-split-detail-content",children:t.jsx(Qg,{task:Ae,projectId:C,tasks:e,embedded:!0,onOpenDetail:Bt,onMoveTask:n,onDeleteTask:a,onMergeTask:r,onRetryTask:s,onResetTask:o,onDuplicateTask:l,onTaskUpdated:we=>{xe(De=>!De||De.id!==we.id?De:{...De,...we})},addToast:d,prAuthAvailable:T})}):t.jsx("div",{className:"list-split-detail-empty",children:t.jsx("p",{children:"Select a task to view details"})})})]})]})})]})}const OP={active:{label:"Active",color:"var(--success)",icon:Hn},paused:{label:"Paused",color:"var(--warning)",icon:ii},errored:{label:"Error",color:"var(--color-error)",icon:Rs},initializing:{label:"Initializing",color:"var(--info)",icon:gt}};function zP(e){if(!e)return"Never";const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4),o=Math.floor(a/36e5),l=Math.floor(a/864e5);return r<1?"Just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString()}function FP(e,n=40){if(e.length<=n)return e;const s=e.slice(0,Math.floor(n/2)-2),a=e.slice(-Math.floor(n/2)+2);return`${s}...${a}`}function UP(e,n){if(e.project.id!==n.project.id||e.project.status!==n.project.status||e.project.name!==n.project.name||e.project.path!==n.project.path||e.project.lastActivityAt!==n.project.lastActivityAt||e.isLoading!==n.isLoading)return!1;const s=e.health,a=n.health;if(!s&&!a)return!0;if(!s||!a||s.activeTaskCount!==a.activeTaskCount||s.inFlightAgentCount!==a.inFlightAgentCount||s.totalTasksCompleted!==a.totalTasksCompleted||s.totalTasksFailed!==a.totalTasksFailed||s.status!==a.status)return!1;const r=e.node,o=n.node;return!r&&!o?e.nodeNameFallback===n.nodeNameFallback:!r||!o?!1:r.id===o.id&&r.name===o.name&&r.status===o.status&&r.type===o.type}function BP({project:e,health:n,onSelect:s,onPause:a,onResume:r,onRemove:o,node:l,nodeNameFallback:c,isLoading:d=!1}){const[u,m]=i.useState(!1),h=OP[e.status],f=h.icon,p=i.useCallback(()=>{s(e)},[s,e]),g=i.useCallback(C=>{C.stopPropagation(),a(e)},[a,e]),x=i.useCallback(C=>{C.stopPropagation(),r(e)},[r,e]),v=i.useCallback(C=>{if(C.stopPropagation(),!u){m(!0);return}o(e),m(!1)},[u,o,e]),b=e.status==="paused",y=e.status==="errored",j=e.status==="initializing";return t.jsxs("div",{className:`project-card ${d?"project-card-loading":""} ${y?"project-card-errored":""}`,onClick:p,"data-project-id":e.id,role:"button",tabIndex:0,onKeyDown:C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),p())},children:[t.jsxs("div",{className:"project-card-header",children:[t.jsx("div",{className:"project-card-icon",children:t.jsx(os,{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:FP(e.path)})]}),t.jsxs("div",{className:"project-card-status-badge",style:{color:h.color,borderColor:h.color},children:[t.jsx(f,{size:12,className:j?"animate-spin":""}),t.jsx("span",{children:h.label})]})]}),t.jsxs("div",{className:"project-card-health",children:[n&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.activeTaskCount}),t.jsx("span",{className:"project-card-metric-label",children:"Active Tasks"})]}),t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.inFlightAgentCount}),t.jsx("span",{className:"project-card-metric-label",children:"Agents"})]}),t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.totalTasksCompleted}),t.jsx("span",{className:"project-card-metric-label",children:"Completed"})]})]}),!n&&t.jsx("div",{className:"project-card-metric project-card-metric-empty",children:t.jsx("span",{className:"project-card-metric-label",children:"No health data available"})})]}),t.jsxs("div",{className:"project-card-footer",children:[t.jsxs("div",{className:"project-card-activity",children:[t.jsx("span",{className:"project-card-activity-label",children:"Last activity:"}),t.jsx("span",{className:"project-card-activity-time",children:zP(e.lastActivityAt||n?.lastActivityAt)})]}),t.jsxs("div",{className:"project-card-actions",children:[b?t.jsxs("button",{className:"project-card-action project-card-action-resume",onClick:x,disabled:d,title:"Resume project","aria-label":"Resume project",children:[t.jsx(Hn,{size:14}),t.jsx("span",{children:"Resume"})]}):t.jsxs("button",{className:"project-card-action project-card-action-pause",onClick:g,disabled:d||j,title:j?"Cannot pause while initializing":"Pause project","aria-label":"Pause project",children:[t.jsx(ii,{size:14}),t.jsx("span",{children:"Pause"})]}),t.jsxs("button",{className:"project-card-action project-card-action-open",onClick:p,disabled:d,title:"Open project","aria-label":"Open project",children:[t.jsx(qr,{size:14}),t.jsx("span",{children:"Open"})]}),t.jsxs("button",{className:`project-card-action project-card-action-remove ${u?"is-armed":""}`,onClick:v,disabled:d,title:u?"Confirm remove":"Remove project","aria-label":u?"Confirm remove project":"Remove project",children:[t.jsx(Cn,{size:14}),t.jsx("span",{children:u?"Confirm":""})]})]})]})]})}const HP=i.memo(BP,UP);function qP(){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(os,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(Fs,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(Ln,{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(Rs,{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 VP=1e4,$h=5;function WP(e){const[n,s]=i.useState({}),[a,r]=i.useState(!0),[o,l]=i.useState(null),c=i.useRef(null),d=i.useRef(null),u=i.useRef(!1),m=i.useCallback(async()=>{if(e.length===0){s({}),u.current||(u.current=!0),r(!1);return}d.current&&d.current.abort(),d.current=new AbortController,!u.current&&r(!0),l(null);try{const p={};for(let g=0;g<e.length;g+=$h){const x=e.slice(g,g+$h),v=await Promise.allSettled(x.map(async b=>{try{return await Vu(b)}catch{return null}}));if(x.forEach((b,y)=>{const j=v[y];p[b]=j.status==="fulfilled"?j.value:null}),d.current?.signal.aborted)return}s(p),u.current=!0}catch(p){if(p instanceof Error&&p.name==="AbortError")return;l(p instanceof Error?p.message:"Failed to fetch health data"),u.current=!0}finally{r(!1)}},[e]),h=i.useCallback(async f=>{try{const p=await Vu(f);s(g=>({...g,[f]:p}))}catch(p){console.error(`Failed to fetch health for project ${f}:`,p)}},[]);return i.useEffect(()=>(u.current=!1,m(),()=>{d.current&&d.current.abort()}),[m]),i.useEffect(()=>{if(e.length!==0)return c.current&&clearInterval(c.current),c.current=setInterval(()=>{m()},VP),()=>{c.current&&(clearInterval(c.current),c.current=null)}},[m,e.length]),{healthMap:n,loading:a,error:o,refresh:m,refreshProject:h}}function KP({projects:e,loading:n=!1,onSelectProject:s,onAddProject:a,onPauseProject:r,onResumeProject:o,onRemoveProject:l,nodes:c=[]}){const[d,u]=i.useState("all"),[m,h]=i.useState(null),[f,p]=i.useState("activity"),[g,x]=i.useState("desc");i.useEffect(()=>{if(typeof window>"u")return;const F=localStorage.getItem("kb-dashboard-recent-projects");if(F)try{const R=JSON.parse(F);b(R)}catch{}},[]);const[v,b]=i.useState([]),y=i.useMemo(()=>e.map(F=>F.id),[e]),{healthMap:j,loading:C}=WP(y),A=i.useMemo(()=>e.map(F=>({project:F,health:j[F.id]||null})),[e,j]),N=i.useMemo(()=>{let F=[...A];return d!=="all"&&(F=F.filter(({project:R})=>R.status===d)),m!==null&&(F=F.filter(({project:R})=>R.nodeId===m)),F},[A,d,m]),S=i.useMemo(()=>{const F=[...N];return F.sort((R,P)=>{let O=0;switch(f){case"name":O=R.project.name.localeCompare(P.project.name);break;case"activity":{const q=R.project.lastActivityAt||R.health?.lastActivityAt||R.project.updatedAt,Z=P.project.lastActivityAt||P.health?.lastActivityAt||P.project.updatedAt;O=new Date(Z).getTime()-new Date(q).getTime();break}case"status":{const q={errored:0,initializing:1,paused:2,active:3};O=q[R.project.status]-q[P.project.status];break}}return g==="asc"?O:-O}),F},[N,f,g]),_=i.useMemo(()=>{const F=e.length,R=e.filter(I=>I.status==="active").length,P=e.filter(I=>I.status==="errored").length,O=new Set;e.forEach(I=>{I.nodeId&&O.add(I.nodeId)});const q=O.size||(F>0?1:0);let Z=0,z=0,k=0;return Object.values(j).forEach(I=>{I&&(Z+=I.activeTaskCount,z+=I.totalTasksCompleted,k+=I.inFlightAgentCount)}),{totalProjects:F,activeProjects:R,erroredProjects:P,totalNodes:q,totalActiveTasks:Z,totalCompletedTasks:z,totalInFlightAgents:k}},[e,j]),T=i.useMemo(()=>({all:e.length,active:e.filter(F=>F.status==="active").length,paused:e.filter(F=>F.status==="paused").length,errored:e.filter(F=>F.status==="errored").length}),[e]),M=i.useMemo(()=>{const F=new Map;return e.forEach(R=>{const P=R.nodeId,O=F.get(P);if(O)O.count++;else{const Z=c.find(z=>z.id===P)?.name??R._sourceNodeName??"Local";F.set(P,{name:Z,count:1})}}),Array.from(F.entries()).map(([R,{name:P,count:O}])=>({nodeId:R??null,name:P,count:O}))},[e,c]),E=i.useCallback(F=>{const R=[F.id,...v.filter(P=>P!==F.id)].slice(0,3);b(R),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify(R)),s(F)},[s,v]);return n||C&&e.length>0&&Object.keys(j).length===0?t.jsx(qP,{}):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(vr,{size:48})}),t.jsx("h2",{className:"project-empty-state__title",children:"No Projects Found"}),t.jsx("p",{className:"project-empty-state__description",children:"Get started by adding your first project. Projects allow you to organize and track tasks across multiple repositories."}),t.jsxs("button",{className:"btn btn-primary project-empty-state__cta",onClick:a,children:[t.jsx(Sn,{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(Ui,{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(os,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:_.totalProjects}),t.jsx("span",{className:"project-stat__label",children:"Total"})]})]}),t.jsxs("div",{className:"project-stat project-stat--active",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Fs,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:_.totalActiveTasks}),t.jsx("span",{className:"project-stat__label",children:"Active Tasks"})]})]}),t.jsxs("div",{className:"project-stat project-stat--completed",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Ln,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:_.totalCompletedTasks}),t.jsx("span",{className:"project-stat__label",children:"Completed"})]})]}),_.erroredProjects>0&&t.jsxs("div",{className:"project-stat project-stat--error",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Rs,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:_.erroredProjects}),t.jsx("span",{className:"project-stat__label",children:"Errored"})]})]}),_.totalNodes>1&&t.jsxs("div",{className:"project-stat project-stat--nodes",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Ir,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:_.totalNodes}),t.jsx("span",{className:"project-stat__label",children:"Nodes"})]})]})]}),t.jsxs("button",{className:"btn btn-primary project-overview__add-btn",onClick:a,children:[t.jsx(Sn,{size:16}),"Add Project"]})]}),t.jsxs("div",{className:"project-overview__filters",children:[t.jsxs("div",{className:"project-filter-tabs",children:[t.jsxs("button",{className:`project-filter-tab ${d==="all"?"active":""}`,onClick:()=>u("all"),children:["All",t.jsx("span",{className:"project-filter-count",children:T.all})]}),t.jsxs("button",{className:`project-filter-tab ${d==="active"?"active":""}`,onClick:()=>u("active"),children:["Active",t.jsx("span",{className:"project-filter-count",children:T.active})]}),t.jsxs("button",{className:`project-filter-tab ${d==="paused"?"active":""}`,onClick:()=>u("paused"),children:["Paused",t.jsx("span",{className:"project-filter-count",children:T.paused})]}),t.jsxs("button",{className:`project-filter-tab ${d==="errored"?"active":""} ${T.errored>0?"has-errors":""}`,onClick:()=>u("errored"),children:["Errored",t.jsx("span",{className:"project-filter-count",children:T.errored})]})]}),M.length>1&&t.jsxs("div",{className:"project-node-filter",children:[t.jsx(Ir,{size:14}),t.jsxs("select",{value:m??"",onChange:F=>{h(F.target.value||null)},className:"project-node-filter-select","aria-label":"Filter by node",children:[t.jsx("option",{value:"",children:"All Nodes"}),M.map(({nodeId:F,name:R,count:P})=>t.jsxs("option",{value:F??"",children:[R," (",P,")"]},F??"local"))]})]}),t.jsxs("div",{className:"project-sort",children:[t.jsx(Yo,{size:14}),t.jsxs("select",{value:`${f}-${g}`,onChange:F=>{const[R,P]=F.target.value.split("-");p(R),x(P)},className:"project-sort-select","aria-label":"Sort projects",children:[t.jsx("option",{value:"activity-desc",children:"Last Activity (Newest)"}),t.jsx("option",{value:"activity-asc",children:"Last Activity (Oldest)"}),t.jsx("option",{value:"name-asc",children:"Name (A-Z)"}),t.jsx("option",{value:"name-desc",children:"Name (Z-A)"}),t.jsx("option",{value:"status-asc",children:"Status (Error → Active)"}),t.jsx("option",{value:"status-desc",children:"Status (Active → Error)"})]}),t.jsx(Gp,{size:14})]})]}),t.jsx("div",{className:"project-grid",children:S.map(({project:F,health:R})=>{const P=c.find(q=>q.id===F.nodeId),O=P?void 0:F._sourceNodeName;return t.jsx(HP,{project:F,health:R,node:P,nodeNameFallback:O,onSelect:E,onPause:r,onResume:o,onRemove:l},F.id)})}),S.length===0&&t.jsxs("div",{className:"project-overview__no-results",children:[t.jsx(Yo,{size:32}),t.jsx("p",{children:"No projects match the current filter"}),t.jsx("button",{className:"btn btn-secondary",onClick:()=>u("all"),children:"Show All Projects"})]})]})}const bu="kb-planning-last-description",xu="kb-subtask-last-description",vu="kb-mission-last-goal";function GP(e,n){us(bu,e,n)}function JP(e){return Zn(bu,e)||""}function ja(e){La(bu,e)}function YP(e,n){us(xu,e,n)}function QP(e){return Zn(xu,e)||""}function Tc(e){La(xu,e)}function XP(e,n){us(vu,e,n)}function ZP(e){return Zn(vu,e)||""}function Di(e){La(vu,e)}function eR(e){const{question:n,response:s}=e;if(!n)return s;if(s&&typeof s=="object"&&!Array.isArray(s)){const a=s;if(n.id in a)return a[n.id]}return s}function tR(e,n){switch(e.type){case"text":return typeof n=="string"?n:n==null?"":String(n);case"single_select":return typeof n=="string"?e.options?.find(a=>a.id===n)?.label??n:n==null?"":String(n);case"multi_select":return Array.isArray(n)?n.map(s=>typeof s!="string"?String(s):e.options?.find(r=>r.id===s)?.label??s).join(", "):n==null?"":String(n);case"confirm":return n===!0?"Yes":n===!1?"No":n==null?"":String(n);default:return n==null?"":JSON.stringify(n)}}function nR(e){let n=0;const s=[];for(const a of e){if(a.question){n+=1,s.push({...a,questionNumber:n});continue}a.thinkingOutput&&s.push({...a,questionNumber:null})}return s}function Qs({entries:e,defaultShowThinking:n=!1}){const[s,a]=i.useState({}),r=nR(e);return r.length===0?null:t.jsx("div",{className:"conversation-history","data-testid":"conversation-history",children:r.map((o,l)=>{const c=!!o.question,d=!!o.thinkingOutput,u=s[l]??n,m=c?eR(o):void 0,h=o.question&&m!==void 0?tR(o.question,m):"",f=o.response&&typeof o.response=="object"&&!Array.isArray(o.response)?o.response:void 0,p=typeof f?._comment=="string"?f._comment.trim():"";return t.jsxs("div",{className:"conversation-entry",children:[c?t.jsxs("div",{className:"conversation-entry-question",children:[t.jsxs("span",{className:"conversation-entry-question-label",children:["Q",o.questionNumber]}),t.jsx("p",{children:o.question?.question})]}):t.jsx("div",{className:"conversation-entry-question",children:t.jsx("span",{className:"conversation-entry-question-label",children:"AI Reasoning"})}),c&&t.jsxs("div",{className:"conversation-entry-response",children:[t.jsx("strong",{children:"Your response"}),t.jsx("p",{children:h||"—"}),p&&t.jsxs("p",{className:"conversation-comment",children:["💬 ",p]})]}),d&&t.jsxs("div",{className:"conversation-entry-thinking",children:[t.jsxs("button",{type:"button",className:"conversation-thinking-toggle",onClick:()=>{a(g=>({...g,[l]:!u}))},"aria-expanded":u,children:[t.jsx("span",{"aria-hidden":"true",children:u?"▾":"▸"}),u?`Hide ${c?"AI thinking":"AI reasoning"}`:`Show ${c?"AI thinking":"AI reasoning"}`]}),u&&t.jsx("pre",{children:o.thinkingOutput})]})]},`${o.question?.id??"thinking"}-${l}`)})})}const Dh="fusion-tab-id";function sR(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function ma(){if(typeof window>"u")return"server-tab";const e=window.sessionStorage.getItem(Dh);if(e)return e;const n=sR();return window.sessionStorage.setItem(Dh,n),n}function Ll(e){const n=i.useMemo(()=>ma(),[]),[s,a]=i.useState(!1),[r,o]=i.useState(null),[l,c]=i.useState(!1);i.useEffect(()=>{if(!e){a(!1),o(null),c(!1);return}let u=!0;return c(!0),Promise.resolve(PN(e,n)).then(m=>{if(u){if(m.acquired){a(!1),o(null);return}a(!0),o(m.currentHolder)}}).catch(()=>{u&&(a(!1),o(null))}).finally(()=>{u&&c(!1)}),()=>{u=!1;try{const m=RN(e,n);m&&typeof m.catch=="function"&&m.catch(()=>{})}catch{}}},[e,n]),i.useEffect(()=>{if(!e||typeof window>"u")return;const u=()=>{if(typeof navigator.sendBeacon!="function")return;const m=xi(`/api/ai-sessions/${encodeURIComponent(e)}/lock/beacon?tabId=${encodeURIComponent(n)}`);navigator.sendBeacon(m)};return window.addEventListener("beforeunload",u),()=>{window.removeEventListener("beforeunload",u)}},[e,n]),i.useEffect(()=>!e||typeof EventSource>"u"?void 0:li("/api/events",{events:{"ai_session:updated":m=>{try{const h=JSON.parse(m.data);if(h.id!==e)return;const f=h.lockedByTab??null;o(f),a(!!(f&&f!==n))}catch{}}}}),[e,n]);const d=i.useCallback(async()=>{if(e){c(!0);try{await Promise.resolve(TN(e,n)),a(!1),o(null)}finally{c(!1)}}},[e,n]);return{isLockedByOther:s,currentHolder:r,takeControl:d,isLoading:l}}const iR="fusion:ai-session-sync",Lh="fusion:ai-session-sync",aR=3e4,rR=6e4;function pi(){return Date.now()}function oR(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Oh(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 lR{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=oR(),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:pi()})}broadcastUpdate(n){const s=n.timestamp??pi();this.applySessionUpdate({sessionId:n.sessionId,status:n.status,needsInput:n.needsInput??n.status==="awaiting_input",owningTabId:n.owningTabId,type:n.type,title:n.title,projectId:n.projectId,updatedAt:n.updatedAt},s),this.publish({type:"session:updated",sessionId:n.sessionId,status:n.status,needsInput:n.needsInput,owningTabId:n.owningTabId,sessionType:n.type,title:n.title,projectId:n.projectId,updatedAt:n.updatedAt,timestamp:s})}broadcastCompleted(n){const s=n.status??"complete",a=n.timestamp??pi();this.applySessionUpdate({sessionId:n.sessionId,status:s,needsInput:!1,owningTabId:null},a),this.ownershipBySession.delete(n.sessionId),this.ownedSessions.delete(n.sessionId),this.emit(),this.publish({type:"session:completed",sessionId:n.sessionId,status:s,timestamp:a})}broadcastLock(n,s){const a=pi();this.applyTabOwnership(n,s,a),this.ownedSessions.set(n,s),this.publish({type:"tab:active",tabId:s,sessionId:n,timestamp:a})}broadcastUnlock(n,s){const a=pi();this.releaseTabOwnership(n,s,a),this.ownedSessions.delete(n),this.publish({type:"tab:inactive",tabId:s,sessionId:n,timestamp:a})}broadcastHeartbeat(n){const s=pi();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(iR),this.channel.onmessage=s=>{const a=Oh(s.data);a&&this.handleIncomingMessage(a)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==Lh||!s.newValue))try{const a=JSON.parse(s.newValue),r=Oh(a.message);r&&this.handleIncomingMessage(r)}catch{}};window.addEventListener("storage",n),this.cleanupStorageListener=()=>{window.removeEventListener("storage",n)}}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{const n=pi();this.updateHeartbeat(this.tabId,n),this.publish({type:"tab:heartbeat",tabId:this.tabId,timestamp:n})},aR)}startStaleSweep(){this.staleSweepInterval=setInterval(()=>{this.emit()},1e4)}setupBeforeUnloadCleanup(){const n=()=>{for(const[s,a]of this.ownedSessions.entries()){const r=pi();this.publish({type:"tab:inactive",tabId:a,sessionId:s,timestamp:r})}};window.addEventListener("beforeunload",n),this.cleanupBeforeUnload=()=>{window.removeEventListener("beforeunload",n)}}publish(n){const s={...n,senderTabId:this.tabId};if(this.channel){this.channel.postMessage(s);return}if(this.usingStorageFallback)try{const a={id:`${s.type}-${s.timestamp}-${Math.random().toString(36).slice(2,8)}`,message:s};window.localStorage.setItem(Lh,JSON.stringify(a))}catch{}}handleIncomingMessage(n){switch(n.type){case"session:updated":{this.applySessionUpdate({sessionId:n.sessionId,status:n.status,needsInput:n.needsInput,owningTabId:n.owningTabId,type:n.sessionType,title:n.title,projectId:n.projectId,updatedAt:n.updatedAt},n.timestamp);return}case"session:completed":{this.applySessionUpdate({sessionId:n.sessionId,status:n.status??"complete",needsInput:!1,owningTabId:null},n.timestamp),this.ownershipBySession.delete(n.sessionId),this.emit();return}case"tab:active":{this.applyTabOwnership(n.sessionId,n.tabId,n.timestamp);return}case"tab:inactive":{this.releaseTabOwnership(n.sessionId,n.tabId,n.timestamp);return}case"tab:heartbeat":{this.updateHeartbeat(n.tabId,n.timestamp);return}case"sync:request":{if(n.tabId===this.tabId)return;const s=[...this.sessionStates.values()].map(o=>{const l=this.ownershipBySession.get(o.sessionId);return{...o,owningTabId:l?.tabId??o.owningTabId??null}}),a=[...this.ownershipBySession.entries()].map(([o,l])=>({sessionId:o,tabId:l.tabId,timestamp:l.timestamp})),r=[...this.heartbeatByTab.entries()].map(([o,l])=>({tabId:o,timestamp:l}));this.publish({type:"sync:response",tabId:n.tabId,sessions:s,locks:a,heartbeats:r,timestamp:pi()});return}case"sync:response":{if(n.tabId!==this.tabId)return;for(const s of n.sessions)this.applySessionUpdate({sessionId:s.sessionId,status:s.status,needsInput:s.needsInput,owningTabId:s.owningTabId,type:s.type,title:s.title,projectId:s.projectId,updatedAt:s.updatedAt},s.lastEventTimestamp,!1);for(const s of n.locks??[])this.applyTabOwnership(s.sessionId,s.tabId,s.timestamp,!1);for(const s of n.heartbeats??[])this.updateHeartbeat(s.tabId,s.timestamp,!1);this.emit();return}default:return}}applySessionUpdate(n,s,a=!0){const r=this.sessionStates.get(n.sessionId);if(r&&s<r.lastEventTimestamp)return;const o=this.ownershipBySession.get(n.sessionId),l={sessionId:n.sessionId,status:n.status,needsInput:n.needsInput??n.status==="awaiting_input",lastEventTimestamp:s,owningTabId:n.owningTabId??o?.tabId??r?.owningTabId??null,type:n.type??r?.type,title:n.title??r?.title,projectId:n.projectId??r?.projectId,updatedAt:n.updatedAt??new Date(s).toISOString()};this.sessionStates.set(n.sessionId,l),n.owningTabId!==void 0&&(n.owningTabId?this.applyTabOwnership(n.sessionId,n.owningTabId,s,!1):this.ownershipBySession.delete(n.sessionId)),a&&this.emit()}applyTabOwnership(n,s,a,r=!0){const o=this.ownershipBySession.get(n);if(o&&a<o.timestamp)return;this.ownershipBySession.set(n,{tabId:s,timestamp:a}),this.updateHeartbeat(s,a,!1);const l=this.sessionStates.get(n);l&&a>=l.lastEventTimestamp&&this.sessionStates.set(n,{...l,owningTabId:s,lastEventTimestamp:a}),r&&this.emit()}releaseTabOwnership(n,s,a,r=!0){const o=this.ownershipBySession.get(n);if(!o||o.tabId!==s||a<o.timestamp)return;this.ownershipBySession.delete(n);const l=this.sessionStates.get(n);l&&a>=l.lastEventTimestamp&&this.sessionStates.set(n,{...l,owningTabId:null,lastEventTimestamp:a}),r&&this.emit()}updateHeartbeat(n,s,a=!0){const r=this.heartbeatByTab.get(n);r!==void 0&&s<r||(this.heartbeatByTab.set(n,s),a&&this.emit())}emit(){const n=pi(),s=new Map;for(const[r,o]of this.sessionStates.entries()){const l=this.ownershipBySession.get(r);s.set(r,{...o,owningTabId:l?.tabId??o.owningTabId??null})}const a=new Map;for(const[r,o]of this.ownershipBySession.entries()){const l=this.heartbeatByTab.get(o.tabId)??o.timestamp,c=n-l>rR;a.set(r,{sessionId:r,tabId:o.tabId,lastHeartbeatTimestamp:l,lastLockTimestamp:o.timestamp,stale:c})}this.snapshot={tabId:this.tabId,sessions:s,activeTabMap:a};for(const r of this.listeners)r()}}const fi=new lR;function Ya(){const e=i.useSyncExternalStore(c=>fi.subscribe(c),()=>fi.getSnapshot(),()=>fi.getSnapshot());i.useEffect(()=>{fi.requestSync()},[]);const n=i.useCallback(c=>{fi.broadcastUpdate(c)},[]),s=i.useCallback(c=>{fi.broadcastCompleted(c)},[]),a=i.useCallback((c,d)=>{fi.broadcastLock(c,d)},[]),r=i.useCallback((c,d)=>{fi.broadcastUnlock(c,d)},[]),o=i.useCallback(c=>{fi.broadcastHeartbeat(c)},[]),l=i.useCallback(()=>{fi.requestSync()},[]);return{tabId:e.tabId,sessions:e.sessions,activeTabMap:e.activeTabMap,broadcastUpdate:n,broadcastCompleted:s,broadcastLock:a,broadcastUnlock:r,broadcastHeartbeat:o,requestSync:l}}function cR(e,n){return e&&n?`${e}/${n}`:""}function dR(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 uR=["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 mR({isOpen:e,onClose:n,onMissionCreated:s,projectId:a,initialGoal:r,resumeSessionId:o}){const[l,c]=i.useState(""),[d,u]=i.useState({type:"initial"}),[m,h]=i.useState(null),[f,p]=i.useState([]),[g,x]=i.useState([]),[v,b]=i.useState(null),[y,j]=i.useState(!1),C=i.useRef(!1),[A,N]=i.useState(""),[S,_]=i.useState(!0),[T,M]=i.useState(!1),[E,L]=i.useState(!1),[F,R]=i.useState(!1),P=i.useRef(null),O=i.useRef(null),q=i.useRef(null),Z=i.useRef(null),[z,k]=i.useState(o??null),I=i.useMemo(()=>ma(),[]),{isLockedByOther:$,takeControl:w,isLoading:H}=Ll(e?z:null),{activeTabMap:K,broadcastUpdate:pe,broadcastCompleted:le,broadcastLock:B,broadcastUnlock:ye,broadcastHeartbeat:U}=Ya(),{confirm:te}=qs(),[ne,ee]=i.useState(void 0),[ie,ge]=i.useState(void 0),[se,Ae]=i.useState([]),[xe,Se]=i.useState(!0),[qe,We]=i.useState(null),[Qe,ve]=i.useState([]),[Oe,ae]=i.useState([]),re=cR(ne,ie);i.useEffect(()=>{(async()=>{try{Se(!0);const Ue=await Ms();Ae(Ue.models),ve(Ue.favoriteProviders),ae(Ue.favoriteModels)}catch(Ue){We(_e(Ue)||"Failed to load models")}finally{Se(!1)}})()},[]);const je=i.useCallback($e=>{ve(Ue=>{const Xe=Ue,Re=Xe.includes($e)?Xe.filter(xt=>xt!==$e):[$e,...Xe];return _n({favoriteProviders:Re,favoriteModels:Oe}).catch(()=>{ve(Xe)}),Re})},[Oe]),Q=i.useCallback($e=>{ae(Ue=>{const Xe=Ue,Re=Xe.includes($e)?Xe.filter(xt=>xt!==$e):[$e,...Xe];return _n({favoriteProviders:Qe,favoriteModels:Re}).catch(()=>{ae(Xe)}),Re})},[Qe]),Fe=i.useCallback(($e,Ue)=>{if(!$e||!Ue)return"Using default";const Xe=se.find(wt=>wt.provider===$e&&wt.id===Ue);return Xe?`${Xe.provider}/${Xe.id}`:`${$e}/${Ue}`},[se]),Je=i.useCallback($e=>{O.current?.close();const Ue=cN($e,a,{onThinking:Xe=>{N(wt=>wt+Xe),pe({sessionId:$e,status:"generating",needsInput:!1,owningTabId:I,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onQuestion:Xe=>{M(!1),L(!1),Di(a),u({type:"question",sessionId:$e,question:Xe}),N(""),j(!0),pe({sessionId:$e,status:"awaiting_input",needsInput:!0,owningTabId:I,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onSummary:Xe=>{M(!1),L(!1),Di(a),u({type:"summary",sessionId:$e,summary:Xe}),b(Xe),N(""),j(!0),pe({sessionId:$e,status:"complete",needsInput:!1,owningTabId:I,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onError:Xe=>{const wt=Xe||"Session failed while contacting the AI.";M(!1),L(!1),h(null),u({type:"error",sessionId:$e,errorMessage:wt}),N(""),j(!0),q.current=$e,pe({sessionId:$e,status:"error",needsInput:!1,owningTabId:I,type:"mission_interview",title:l.trim()||void 0,projectId:a??null}),le({sessionId:$e,status:"error"})},onComplete:()=>{M(!1),L(!1),q.current=null,le({sessionId:$e,status:"complete"})},onConnectionStateChange:Xe=>{M(Xe==="reconnecting")}});O.current=Ue},[le,pe,l,a,I]),be=i.useCallback(async $e=>{const Ue=$e??l;if(Ue.trim()){h(null),N(""),p([]),x([]),M(!1),u({type:"loading"});try{const{sessionId:Xe}=await aN(Ue.trim(),a,ne&&ie?{modelProvider:ne,modelId:ie}:void 0);q.current=Xe,k(Xe),Di(a),Je(Xe),p([])}catch(Xe){M(!1),h(_e(Xe)||"Failed to start interview session"),u({type:"initial"}),q.current=null,k(null)}}},[Je,l,ne,ie,a]);i.useEffect(()=>{e&&d.type==="initial"&&P.current?.focus()},[e,d.type]),i.useEffect(()=>{if(e&&r&&!C.current&&d.type==="initial"){c(r);const $e=setTimeout(()=>{C.current=!0,be(r)},0);return()=>clearTimeout($e)}else if(e&&!r&&!C.current&&d.type==="initial"){const $e=ZP(a);$e&&c($e)}},[e,r,d.type,be]),i.useEffect(()=>{e||(C.current=!1,M(!1),L(!1),k(null))},[e]),i.useEffect(()=>{if(!e||!o||d.type!=="initial")return;let $e=!1;return bi(o).then(Ue=>{if($e||!Ue)return;const Xe=Da(Ue.conversationHistory);if(x(Xe),k(Ue.id),p(Xe.map(wt=>wt.response).filter(wt=>!!(wt&&typeof wt=="object"&&!Array.isArray(wt)))),Ue.status==="awaiting_input"&&Ue.currentQuestion)try{Di(a);const wt=JSON.parse(Ue.currentQuestion);q.current=Ue.id,j(!0),u({type:"question",sessionId:Ue.id,question:wt})}catch{h("Failed to restore session question.")}else if(Ue.status==="complete"&&Ue.result)try{Di(a);const wt=JSON.parse(Ue.result);q.current=Ue.id,j(!0),b(wt),u({type:"summary",sessionId:Ue.id,summary:wt})}catch{h("Failed to restore session result.")}else Ue.status==="generating"?(q.current=Ue.id,j(!0),Ue.thinkingOutput&&N(Ue.thinkingOutput),u({type:"loading"}),Je(Ue.id)):Ue.status==="error"&&(q.current=Ue.id,j(!0),h(null),u({type:"error",sessionId:Ue.id,errorMessage:Ue.error??"The session encountered an error."}))}).catch(()=>{$e||h("Failed to resume session.")}),()=>{$e=!0}},[Je,e,o,d.type,a]),i.useEffect(()=>{if(!e){Z.current&&(ye(Z.current,I),Z.current=null);return}if(z&&Z.current!==z){Z.current&&ye(Z.current,I),B(z,I),Z.current=z;return}!z&&Z.current&&(ye(Z.current,I),Z.current=null)},[B,ye,e,z,I]),i.useEffect(()=>{if(!e||!z||Z.current!==z)return;U(I);const $e=setInterval(()=>{U(I)},3e4);return()=>{clearInterval($e)}},[U,e,z,I]),i.useEffect(()=>()=>{O.current?.close(),O.current=null,Z.current&&(ye(Z.current,I),Z.current=null)},[ye,I]),i.useEffect(()=>{if(!e)return;const $e=Ue=>{(d.type==="question"||d.type==="summary")&&(Ue.preventDefault(),Ue.returnValue=""),O.current?.close()};return window.addEventListener("beforeunload",$e),()=>window.removeEventListener("beforeunload",$e)},[e,d]);const ze=i.useCallback(()=>{O.current?.close(),O.current=null,n()},[n]),tt=i.useCallback(async()=>{if(l&&XP(l,a),!(y&&!await te({title:"Close Interview",message:"Are you sure you want to close? Your interview progress will be lost.",danger:!0}))){if(O.current?.close(),O.current=null,d.type==="question"||d.type==="summary"||d.type==="error")try{await bf(d.sessionId,a,I)}catch{}c(""),u({type:"initial"}),h(null),p([]),x([]),b(null),N(""),M(!1),L(!1),j(!1),R(!1),ee(void 0),ge(void 0),q.current=null,k(null),n()}},[l,y,d,n,a,I,te]);i.useEffect(()=>{if(!e)return;const $e=Ue=>{Ue.key==="Escape"&&tt()};return document.addEventListener("keydown",$e),()=>document.removeEventListener("keydown",$e)},[e,tt]);const kt=i.useCallback(async $e=>{if(d.type!=="question")return;const{sessionId:Ue}=d;h(null),p(Xe=>[...Xe,$e]),x(Xe=>[...Xe,{question:d.question,response:$e}]),u({type:"loading"}),N("");try{Je(Ue),await rN(Ue,$e,a,I),j(!0)}catch(Xe){O.current?.close(),O.current=null,h(_e(Xe)||"Failed to submit response"),u({type:"question",sessionId:Ue,question:d.question})}},[d,a,I,Je]),ke=i.useCallback(async()=>{if(d.type!=="error")return;const $e=d.sessionId;h(null),L(!0),N(""),u({type:"loading"}),Je($e);try{q.current=$e,k($e),await oN($e,a,I)}catch(Ue){let Xe=Ue;if((_e(Ue)||"").includes("not in an error state"))try{const Re=await bi($e);if(!Re)throw new Error("Failed to refresh interview session.");const xt=Da(Re.conversationHistory);if(x(xt),p(xt.map(Pt=>Pt.response).filter(Pt=>!!(Pt&&typeof Pt=="object"&&!Array.isArray(Pt)))),q.current=Re.id,k(Re.id),j(!0),Re.status==="generating")N(Re.thinkingOutput??""),u({type:"loading"}),O.current?.isConnected()||Je(Re.id);else if(Re.status==="awaiting_input"){if(!Re.currentQuestion)throw new Error("Interview session is awaiting input but has no current question.");Di(a);const Pt=JSON.parse(Re.currentQuestion);u({type:"question",sessionId:Re.id,question:Pt}),O.current?.isConnected()||Je(Re.id)}else if(Re.status==="complete"){if(!Re.result)throw new Error("Interview session is complete but has no result.");Di(a);const Pt=JSON.parse(Re.result);b(Pt),u({type:"summary",sessionId:Re.id,summary:Pt})}else Re.status==="error"&&u({type:"error",sessionId:Re.id,errorMessage:Re.error??"Retry failed. Please try again."});M(!1);return}catch(Re){Xe=Re}O.current?.close(),O.current=null,u({type:"error",sessionId:$e,errorMessage:_e(Xe)||"Retry failed. Please try again."}),M(!1)}finally{L(!1)}},[Je,a,I,d]),ce=i.useCallback(async()=>{if(d.type==="summary"){h(null),R(!0);try{const $e=await lN(d.sessionId,v||void 0,a);s($e),Di(a),O.current?.close(),O.current=null,c(""),u({type:"initial"}),h(null),p([]),x([]),b(null),N(""),M(!1),L(!1),j(!1),R(!1),q.current=null,k(null),n()}catch($e){h(_e($e)||"Failed to create mission"),R(!1)}}},[d,v,s,n,a]),Te=()=>d.type==="question"?Math.min(f.length+1,6):6,he=d.type==="loading"||d.type==="question"||d.type==="summary"||d.type==="error",Le=z?K.get(z):null,st=Le&&Le.tabId!==I,it=!!(st&&!Le.stale),lt=$&&(!st||Le.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:$e=>$e.target===$e.currentTarget&&tt(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(ws,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Plan Mission with AI"})]}),t.jsxs("div",{className:"modal-header-actions",children:[he&&t.jsx("button",{className:"modal-send-to-background",onClick:ze,title:"Send to background","aria-label":"Send to background",children:t.jsx(Kr,{size:16})}),t.jsx("button",{className:"modal-close",onClick:tt,"aria-label":"Close",children:t.jsx(Jt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[m&&t.jsx("div",{className:"form-error planning-error",children:m}),T&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),it&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),d.type==="initial"&&t.jsxs("div",{className:"planning-initial",children:[t.jsxs("div",{className:"planning-view-scroll",children:[t.jsxs("div",{className:"planning-intro",children:[t.jsx(ms,{size:32,className:"icon-triage-lg"}),t.jsx("h4",{children:"Transform your vision into a structured mission"}),t.jsx("p",{className:"text-muted",children:"Describe what you want to build. The AI will interview you to understand scope, constraints, and requirements, then produce a structured plan with milestones, slices, and features."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"mission-goal",children:"What do you want to build?"}),t.jsx("textarea",{ref:P,id:"mission-goal",rows:4,className:"planning-textarea",placeholder:"e.g., Build a real-time collaborative document editor with presence, comments, and version history...",value:l,onChange:$e=>c($e.target.value),onKeyDown:$e=>{$e.key==="Enter"&&!$e.shiftKey&&l.trim()&&($e.preventDefault(),be())}})]}),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:uR.map(($e,Ue)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>c($e),children:$e.length>45?$e.slice(0,45)+"...":$e},Ue))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"mission-interview-modal-model",className:"form-label",children:["Planning Model",xe&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(hs,{id:"mission-interview-modal-model",label:"Planning Model",value:re,onChange:$e=>{const{provider:Ue,modelId:Xe}=dR($e);ee(Ue),ge(Xe)},models:se,disabled:xe,favoriteProviders:Qe,onToggleFavorite:je,favoriteModels:Oe,onToggleModelFavorite:Q}),qe&&t.jsxs("div",{className:"form-hint form-hint-error",children:[qe," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{Se(!0);const $e=await Ms();Ae($e.models),ve($e.favoriteProviders),ae($e.favoriteModels),We(null)}catch($e){We(_e($e)||"Failed to load models")}finally{Se(!1)}})()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${ne&&ie?"model-badge-custom":"model-badge-default"}`,children:Fe(ne,ie)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>be(),disabled:!l.trim(),children:[t.jsx(ws,{size:16,className:"icon-mr-8"}),"Start Interview"]})})]}),d.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(gt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:A?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>_(!S),type:"button",children:S?"Hide thinking":"Show thinking"}),S&&A&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:A})})]})]}),d.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[g.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Qs,{entries:g}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:d.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void ke(),disabled:E,children:[E?t.jsx(gt,{size:14,className:"spin"}):t.jsx(ns,{size:14}),t.jsx("span",{className:"icon-ml-6",children:E?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:tt,disabled:E,children:"Cancel"})]})]})]})}),d.type==="question"&&t.jsx(hR,{question:d.question,progress:Te(),historyEntries:g,onSubmit:kt}),d.type==="summary"&&v&&t.jsx(pR,{summary:v,historyEntries:g,onSummaryChange:b,onApprove:ce,onStartOver:()=>{u({type:"initial"}),j(!1),b(null),p([]),x([]),k(null),O.current?.close(),O.current=null},isCreating:F}),$&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(jl,{size:16}),t.jsx("span",{children:lt?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),lt&&t.jsx("button",{type:"button",onClick:()=>{w()},disabled:H,className:"btn btn-primary session-lock-take-control",children:H?"Taking control...":"Take Control"})]})})]})]})}):null}function hR({question:e,progress:n,historyEntries:s,onSubmit:a}){const[r,o]=i.useState({}),[l,c]=i.useState(""),[d,u]=i.useState(""),m=i.useCallback(()=>{let f;e.type==="text"?f={[e.id]:l}:e.type==="confirm"?f={[e.id]:r[e.id]===!0}:f=r;const p=d.trim();p.length>0&&(f={...f,_comment:p}),a(f)},[d,e,r,l,a]);i.useEffect(()=>{o({}),c(""),u("")},[e.id]);const h=()=>{switch(e.type){case"text":return l.trim().length>0;case"single_select":return r[e.id]!==void 0;case"multi_select":return Array.isArray(r[e.id])&&r[e.id].length>0;case"confirm":return r[e.id]!==void 0;default:return!0}};return t.jsxs("div",{className:"planning-question-form",children:[t.jsxs("div",{className:"planning-view-scroll planning-question-scroll",children:[s.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Qs,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3,4,5,6].map(f=>t.jsx("div",{className:`planning-progress-step ${f<=n?"active":""}`},f))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~6"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:l,onChange:f=>c(f.target.value),onKeyDown:f=>{f.key==="Enter"&&!f.shiftKey&&l.trim()&&(f.preventDefault(),m())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(f=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:f.id,checked:r[e.id]===f.id,onChange:()=>o({[e.id]:f.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:f.label}),f.description&&t.jsx("span",{className:"planning-option-desc",children:f.description})]})]},f.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(f=>{const p=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:f.id,checked:p.includes(f.id),onChange:g=>{const x=g.target.checked?[...p,f.id]:p.filter(v=>v!==f.id);o({[e.id]:x})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:f.label}),f.description&&t.jsx("span",{className:"planning-option-desc",children:f.description})]})]},f.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!0?"selected":""}`,onClick:()=>o({[e.id]:!0}),children:[t.jsx(Ln,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(Jt,{size:18}),"No"]})]})]}),e.type!=="text"&&t.jsxs("div",{className:"planning-comment-section",children:[t.jsx("label",{className:"planning-comment-label",htmlFor:`planning-comment-${e.id}`,children:"Additional comments (optional)"}),t.jsx("textarea",{id:`planning-comment-${e.id}`,className:"planning-textarea",rows:2,placeholder:"Add any extra context or direction...",value:d,onChange:f=>u(f.target.value)})]})]})]})]}),t.jsx("div",{className:"planning-actions",children:t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:m,disabled:!h(),children:["Continue",t.jsx(qr,{size:16,className:"icon-ml-4"})]})})]})}function pR({summary:e,historyEntries:n,onSummaryChange:s,onApprove:a,onStartOver:r,isCreating:o}){const[l,c]=i.useState(()=>new Set(e.milestones.map((C,A)=>A))),[d,u]=i.useState(()=>{const C=new Set;return e.milestones.forEach((A,N)=>{A.slices.forEach((S,_)=>C.add(`${N}-${_}`))}),C}),m=C=>{c(A=>{const N=new Set(A);return N.has(C)?N.delete(C):N.add(C),N})},h=C=>{u(A=>{const N=new Set(A);return N.has(C)?N.delete(C):N.add(C),N})},f=(C,A)=>{const N=[...e.milestones];N[C]={...N[C],...A},s({...e,milestones:N})},p=(C,A,N)=>{const S=[...e.milestones],_=[...S[C].slices];_[A]={..._[A],...N},S[C]={...S[C],slices:_},s({...e,milestones:S})},g=(C,A,N,S)=>{const _=[...e.milestones],T=[..._[C].slices],M=[...T[A].features];M[N]={...M[N],...S},T[A]={...T[A],features:M},_[C]={..._[C],slices:T},s({...e,milestones:_})},x=C=>{const A=e.milestones.filter((N,S)=>S!==C);s({...e,milestones:A})},v=(C,A)=>{const N=[...e.milestones];N[C]={...N[C],slices:N[C].slices.filter((S,_)=>_!==A)},s({...e,milestones:N})},b=(C,A,N)=>{const S=[...e.milestones],_=[...S[C].slices];_[A]={..._[A],features:_[A].features.filter((T,M)=>M!==N)},S[C]={...S[C],slices:_},s({...e,milestones:S})},y=(C,A)=>{const N=[...e.milestones],S=[...N[C].slices];S[A]={...S[A],features:[...S[A].features,{title:"New feature",description:""}]},N[C]={...N[C],slices:S},s({...e,milestones:N})},j=e.milestones.reduce((C,A)=>C+A.slices.reduce((N,S)=>N+S.features.length,0),0);return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Qs,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Ln,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Mission Plan Ready"}),t.jsxs("p",{className:"text-muted",children:[e.milestones.length," milestones, ",j," features. Review and edit before approving."]})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Mission Title"}),t.jsx("input",{type:"text",className:"form-input",value:e.missionTitle||"",onChange:C=>s({...e,missionTitle:C.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Mission Description"}),t.jsx("textarea",{className:"planning-textarea",rows:3,value:e.missionDescription||"",onChange:C=>s({...e,missionDescription:C.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Roadmap"}),t.jsx("div",{className:"roadmap-list",children:e.milestones.map((C,A)=>t.jsxs("div",{className:"roadmap-card",children:[t.jsxs("div",{className:"roadmap-card-header",onClick:()=>m(A),children:[l.has(A)?t.jsx(un,{size:16,className:"icon-text-secondary"}):t.jsx(Tn,{size:16,className:"icon-text-secondary"}),t.jsx(na,{size:16,className:"icon-milestone"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-title",value:C.title,onChange:N=>f(A,{title:N.target.value}),onClick:N=>N.stopPropagation()}),e.milestones.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:N=>{N.stopPropagation(),x(A)},title:"Remove milestone",children:t.jsx(Cn,{size:14,className:"icon-text-secondary"})})]}),l.has(A)&&t.jsxs("div",{className:"roadmap-card-body",children:[t.jsx("textarea",{className:"planning-textarea roadmap-textarea-md",rows:2,placeholder:"Milestone description...",value:C.description||"",onChange:N=>f(A,{description:N.target.value})}),t.jsxs("div",{className:"roadmap-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Verification Criteria"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-sm",rows:2,placeholder:"How to confirm this milestone is complete...",value:C.verification||"",onChange:N=>f(A,{verification:N.target.value})})]}),C.slices.map((N,S)=>{const _=`${A}-${S}`;return t.jsxs("div",{className:"roadmap-slice-card",children:[t.jsxs("div",{className:"roadmap-slice-header",onClick:()=>h(_),children:[d.has(_)?t.jsx(un,{size:14,className:"icon-text-secondary"}):t.jsx(Tn,{size:14,className:"icon-text-secondary"}),t.jsx(cd,{size:14,className:"icon-slice"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:N.title,onChange:T=>p(A,S,{title:T.target.value}),onClick:T=>T.stopPropagation()}),C.slices.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:T=>{T.stopPropagation(),v(A,S)},title:"Remove slice",children:t.jsx(Cn,{size:12,className:"icon-text-secondary"})})]}),d.has(_)&&t.jsxs("div",{className:"roadmap-slice-body",children:[t.jsxs("div",{className:"roadmap-slice-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Slice Verification"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-xs",rows:1,placeholder:"How to confirm this slice is done...",value:N.verification||"",onChange:T=>p(A,S,{verification:T.target.value})})]}),N.features.map((T,M)=>t.jsxs("div",{className:"roadmap-feature-row",children:[t.jsx(td,{size:12,className:"icon-feature"}),t.jsxs("div",{className:"roadmap-feature-content",children:[t.jsx("input",{type:"text",className:"form-input roadmap-input-feature",value:T.title,onChange:E=>g(A,S,M,{title:E.target.value})}),T.description&&t.jsx("p",{className:"roadmap-feature-text",children:T.description}),T.acceptanceCriteria&&t.jsxs("p",{className:"roadmap-feature-text--italic",children:["AC: ",T.acceptanceCriteria]})]}),t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:()=>b(A,S,M),title:"Remove feature",children:t.jsx(Cn,{size:12,className:"icon-text-secondary"})})]},M)),t.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>y(A,S),children:[t.jsx(Sn,{size:12}),"Add Feature"]})]})]},S)})]})]},A))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:r,disabled:o,children:[t.jsx(la,{size:16,className:"icon-mr-4"}),"Start Over"]}),t.jsx("button",{className:"btn btn-primary",onClick:a,disabled:o||e.milestones.length===0,children:o?t.jsxs(t.Fragment,{children:[t.jsx(gt,{size:16,className:"spin icon-mr-8"}),"Creating Mission..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Ln,{size:16,className:"icon-mr-8"}),"Approve Plan"]})})]})]})}function fR({isOpen:e,onClose:n,onApplied:s,targetType:a,targetId:r,targetTitle:o,missionContext:l,projectId:c,resumeSessionId:d}){const[u,m]=i.useState({type:"initial"}),[h,f]=i.useState(null),[p,g]=i.useState([]),[x,v]=i.useState([]),[b,y]=i.useState(null),[j,C]=i.useState(""),[A,N]=i.useState(!0),[S,_]=i.useState(!1),[T,M]=i.useState(!1),E=i.useRef(null),L=i.useRef(null),F=i.useRef(null),R=i.useRef(null),[P,O]=i.useState(null),q=i.useMemo(()=>ma(),[]);Ll(e?P:null);const{activeTabMap:Z,broadcastUpdate:z,broadcastCompleted:k,broadcastLock:I,broadcastUnlock:$,broadcastHeartbeat:w}=Ya(),H=a==="milestone"?dN:fN,K=a==="milestone"?uN:gN,pe=a==="milestone"?mN:bN,le=a==="milestone"?hN:xN,B=a==="milestone"?pN:vN,ye=a==="milestone"?"Milestone":"Slice",U=a==="milestone"?"milestone_interview":"slice_interview",te=i.useCallback(Oe=>{L.current?.close();const ae=pe(Oe,c,{onThinking:re=>{C(je=>je+re),z({sessionId:Oe,status:"generating",needsInput:!1,owningTabId:q,type:U,title:o,projectId:c??null})},onQuestion:re=>{_(!1),ne(),m({type:"question",sessionId:Oe,question:re}),C(""),z({sessionId:Oe,status:"awaiting_input",needsInput:!0,owningTabId:q,type:U,title:o,projectId:c??null})},onSummary:re=>{_(!1),ne(),m({type:"summary",sessionId:Oe,summary:re}),y(re),C(""),z({sessionId:Oe,status:"complete",needsInput:!1,owningTabId:q,type:U,title:o,projectId:c??null})},onError:re=>{const je=re||"Session failed while contacting the AI.";_(!1),f(null),m({type:"error",sessionId:Oe,errorMessage:je}),C(""),F.current=Oe,z({sessionId:Oe,status:"error",needsInput:!1,owningTabId:q,type:U,title:o,projectId:c??null}),k({sessionId:Oe,status:"error"})},onComplete:()=>{_(!1),F.current=null,k({sessionId:Oe,status:"complete"})},onConnectionStateChange:re=>{_(re==="reconnecting")}});L.current=ae},[k,z,pe,U,c,q,o]),ne=()=>{y(null),g([]),v([]),C("")},ee=i.useCallback(async()=>{f(null),ne(),_(!1),m({type:"loading"});try{const{sessionId:Oe}=await H(r,c);F.current=Oe,O(Oe),te(Oe)}catch(Oe){_(!1),f(_e(Oe)||`Failed to start ${ye.toLowerCase()} interview`),m({type:"initial"}),F.current=null,O(null)}},[te,c,H,r,ye]),ie=i.useCallback(async()=>{f(null),M(!0);try{await B(r,c),s(),m({type:"applied"})}catch(Oe){f(_e(Oe)||`Failed to skip ${ye.toLowerCase()} interview`),M(!1)}},[s,c,B,r,ye]);i.useEffect(()=>{e&&u.type==="initial"&&E.current?.focus()},[e,u.type]),i.useEffect(()=>{if(!e||!d||u.type!=="initial")return;let Oe=!1;return bi(d).then(ae=>{if(Oe||!ae)return;const re=Da(ae.conversationHistory);if(v(re),O(ae.id),g(re.map(je=>je.response).filter(je=>!!(je&&typeof je=="object"&&!Array.isArray(je)))),ae.status==="awaiting_input"&&ae.currentQuestion)try{const je=JSON.parse(ae.currentQuestion);F.current=ae.id,m({type:"question",sessionId:ae.id,question:je})}catch{f("Failed to restore session question.")}else if(ae.status==="complete"&&ae.result)try{const je=JSON.parse(ae.result);F.current=ae.id,y(je),m({type:"summary",sessionId:ae.id,summary:je})}catch{f("Failed to restore session result.")}else ae.status==="generating"?(F.current=ae.id,ae.thinkingOutput&&C(ae.thinkingOutput),m({type:"loading"}),te(ae.id)):ae.status==="error"&&(F.current=ae.id,f(null),m({type:"error",sessionId:ae.id,errorMessage:ae.error??"The session encountered an error."}))}).catch(()=>{Oe||f("Failed to resume session.")}),()=>{Oe=!0}},[te,e,d,u.type]),i.useEffect(()=>{e||(_(!1),O(null))},[e]),i.useEffect(()=>{if(!(!e||!P)){if(R.current!==P){R.current&&$(R.current,q),I(P,q),R.current=P;return}!P&&R.current&&($(R.current,q),R.current=null)}},[I,$,e,P,q]),i.useEffect(()=>{if(!e||!P||R.current!==P)return;w(q);const Oe=setInterval(()=>{w(q)},3e4);return()=>{clearInterval(Oe)}},[w,e,P,q]),i.useEffect(()=>()=>{L.current?.close(),L.current=null,R.current&&($(R.current,q),R.current=null)},[$,q]);const ge=i.useCallback(()=>{L.current?.close(),L.current=null,n()},[n]),se=i.useCallback(async()=>{L.current?.close(),L.current=null,ne(),m({type:"initial"}),f(null),F.current=null,O(null),n()},[n]),Ae=i.useCallback(async Oe=>{if(u.type!=="question")return;const{sessionId:ae}=u;f(null),g(re=>[...re,Oe]),v(re=>[...re,{question:u.question,response:Oe}]),m({type:"loading"}),C("");try{te(ae),await K(ae,Oe,c,q)}catch(re){L.current?.close(),L.current=null,f(_e(re)||"Failed to submit response"),m({type:"question",sessionId:ae,question:u.question})}},[te,c,K,q,u]),xe=i.useCallback(async()=>{if(u.type==="summary"){f(null),M(!0);try{await le(u.sessionId,b||void 0,c),s(),m({type:"applied"})}catch(Oe){f(_e(Oe)||"Failed to apply interview results"),M(!1)}}},[le,b,s,c,u]),Se=()=>u.type==="question"?Math.min(p.length+1,6):6,qe=u.type==="loading"||u.type==="question"||u.type==="summary"||u.type==="error",We=P?Z.get(P):null,ve=!!(We&&We.tabId!==q&&!We.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Oe=>Oe.target===Oe.currentTarget&&se(),role:"dialog","aria-modal":"true","data-testid":"milestone-slice-interview-modal",children:t.jsxs("div",{className:"modal modal-lg planning-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(ms,{size:20,className:"icon-triage"}),t.jsxs("h3",{children:["Plan ",ye,": ",o]})]}),t.jsxs("div",{className:"modal-header-actions",children:[qe&&t.jsx("button",{className:"modal-send-to-background",onClick:ge,title:"Send to background","aria-label":"Send to background",children:t.jsx(Kr,{size:16})}),t.jsx("button",{className:"modal-close",onClick:se,"aria-label":"Close",children:t.jsx(Jt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[h&&t.jsx("div",{className:"form-error planning-error",children:h}),S&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),ve&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),u.type==="initial"&&t.jsxs("div",{className:"planning-initial",children:[t.jsx("div",{className:"planning-view-scroll",children:t.jsxs("div",{className:"planning-intro",children:[t.jsx(ms,{size:32,className:"icon-triage-lg"}),t.jsxs("h4",{children:["Refine ",ye," scope with AI"]}),t.jsxs("p",{className:"text-muted",children:["The AI will interview you to refine the ",a,"'s scope, acceptance criteria, and verification methods. Each ",a," can have its own refined plan or inherit context from the mission level."]}),l&&t.jsxs("div",{className:"planning-context-info",children:[t.jsx("span",{className:"planning-context-label",children:"Mission context:"}),t.jsx("span",{className:"planning-context-text",children:l})]})]})}),t.jsxs("div",{className:"planning-view-footer",children:[t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>void ee(),children:[t.jsx(ms,{size:16,className:"icon-mr-8"}),"Start Interview"]}),t.jsxs("button",{className:"btn planning-use-context-btn",onClick:()=>void ie(),disabled:T,children:[T?t.jsx(gt,{size:16,className:"spin"}):null,"Use Mission Context"]}),t.jsx("button",{className:"btn",onClick:se,children:"Cancel"})]})]}),u.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(gt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:j?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>N(!A),type:"button",children:A?"Hide thinking":"Show thinking"}),A&&j&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:j})})]})]}),u.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[x.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Qs,{entries:x}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:u.errorMessage}),t.jsx("div",{className:"ai-error-actions",children:t.jsx("button",{className:"btn",onClick:se,children:"Cancel"})})]})]})}),u.type==="question"&&t.jsx(gR,{question:u.question,progress:Se(),historyEntries:x,onSubmit:Ae}),u.type==="summary"&&b&&t.jsx(bR,{summary:b,historyEntries:x,onSummaryChange:y,onApply:xe,onCancel:se,isApplying:T}),u.type==="applied"&&t.jsxs("div",{className:"planning-summary planning-applied",children:[t.jsx("div",{className:"planning-view-scroll",children:t.jsxs("div",{className:"planning-applied-content",children:[t.jsx(Ln,{size:48,className:"icon-success"}),t.jsxs("h4",{children:[ye," Updated"]}),t.jsxs("p",{className:"text-muted",children:["The ",a,"'s scope and verification have been ",u.type==="applied"?"applied":"updated","."]})]})}),t.jsx("div",{className:"planning-view-footer",children:t.jsx("button",{className:"btn btn-primary",onClick:s,children:"Done"})})]})]})]})}):null}function gR({question:e,progress:n,historyEntries:s,onSubmit:a}){const[r,o]=i.useState({}),[l,c]=i.useState(""),[d,u]=i.useState(""),m=i.useCallback(()=>{let f;e.type==="text"?f={[e.id]:l}:e.type==="confirm"?f={[e.id]:r[e.id]===!0}:f=r;const p=d.trim();p.length>0&&(f={...f,_comment:p}),a(f)},[d,e,r,l,a]);i.useEffect(()=>{o({}),c(""),u("")},[e.id]);const h=()=>{switch(e.type){case"text":return l.trim().length>0;case"single_select":return r[e.id]!==void 0;case"multi_select":return Array.isArray(r[e.id])&&r[e.id].length>0;case"confirm":return r[e.id]!==void 0;default:return!0}};return t.jsxs("div",{className:"planning-question-form",children:[t.jsxs("div",{className:"planning-view-scroll planning-question-scroll",children:[s.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Qs,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3,4,5,6].map(f=>t.jsx("div",{className:`planning-progress-step ${f<=n?"active":""}`},f))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~6"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:l,onChange:f=>c(f.target.value),onKeyDown:f=>{f.key==="Enter"&&!f.shiftKey&&l.trim()&&(f.preventDefault(),m())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(f=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:f.id,checked:r[e.id]===f.id,onChange:()=>o({[e.id]:f.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:f.label}),f.description&&t.jsx("span",{className:"planning-option-desc",children:f.description})]})]},f.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(f=>{const p=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:f.id,checked:p.includes(f.id),onChange:g=>{const x=g.target.checked?[...p,f.id]:p.filter(v=>v!==f.id);o({[e.id]:x})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:f.label}),f.description&&t.jsx("span",{className:"planning-option-desc",children:f.description})]})]},f.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!0?"selected":""}`,onClick:()=>o({[e.id]:!0}),children:[t.jsx(Ln,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(Jt,{size:18}),"No"]})]})]}),e.type!=="text"&&t.jsxs("div",{className:"planning-comment-section",children:[t.jsx("label",{className:"planning-comment-label",htmlFor:`planning-comment-${e.id}`,children:"Additional comments (optional)"}),t.jsx("textarea",{id:`planning-comment-${e.id}`,className:"planning-textarea",rows:2,placeholder:"Add any extra context or direction...",value:d,onChange:f=>u(f.target.value)})]})]})]})]}),t.jsx("div",{className:"planning-actions",children:t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:m,disabled:!h(),children:["Continue",t.jsx(qr,{size:16,className:"icon-ml-4"})]})})]})}function bR({summary:e,historyEntries:n,onSummaryChange:s,onApply:a,onCancel:r,isApplying:o}){const[l,c]=i.useState(e),[d,u]=i.useState(!0),m=(h,f)=>{const p={...l,[h]:f};c(p),s(p)};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Qs,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-panel",children:[t.jsx("div",{className:"planning-summary-header",children:t.jsxs("button",{className:"planning-summary-toggle",onClick:()=>u(!d),"aria-expanded":d,children:[d?t.jsx(un,{size:16}):t.jsx(Tn,{size:16}),t.jsx("span",{children:"Refined Scope"})]})}),d&&t.jsxs("div",{className:"planning-summary-content",children:[l.description&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:l.description,onChange:h=>m("description",h.target.value)})]}),l.planningNotes&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Planning Notes"}),t.jsx("textarea",{rows:3,value:l.planningNotes,onChange:h=>m("planningNotes",h.target.value)})]}),l.verification&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Verification Criteria"}),t.jsx("textarea",{rows:2,value:l.verification,onChange:h=>m("verification",h.target.value)})]}),!l.description&&!l.planningNotes&&!l.verification&&t.jsx("p",{className:"text-muted planning-summary-empty",children:"No additional details were generated for this item."})]})]})]}),t.jsxs("div",{className:"planning-view-footer",children:[t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:a,disabled:o,children:[o?t.jsx(gt,{size:16,className:"spin"}):null,"Apply"]}),t.jsx("button",{className:"btn",onClick:r,disabled:o,children:"Cancel"})]})]})}const ur={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)"}},zh={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)"}},Fh={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)"}},To={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)"}},Io={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)"}},$o={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)"}},Uh={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)"}},xR=3;function vR(e){return e==="completed"?"planned":e==="needs_update"?"needs_update":"not_started"}function Bh({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 Hh(e){return e?e.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const Ic={title:"",description:"",status:"planning",autopilotEnabled:!1},$c={title:"",description:"",status:"planning",dependencies:[]},Dc={title:"",description:"",status:"pending"},Lc={title:"",description:"",acceptanceCriteria:"",status:"defined"},yR=3600*1e3;function ml(e){if(!e)return"—";const n=new Date(e).getTime();if(Number.isNaN(n))return"—";const s=Date.now()-n;if(s<0)return"just now";const a=Math.floor(s/(60*1e3));if(a<1)return"just now";if(a<60)return`${a}m ago`;const r=Math.floor(a/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function wR(e){if(!e)return"healthy";const n=typeof e.lastErrorAt=="string"&&Date.now()-new Date(e.lastErrorAt).getTime()<=yR,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 kR(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 jR(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 Oc(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 Zg=["feature_triaged","feature_completed"],eb=["slice_activated","slice_completed","milestone_completed"],tb=["mission_started","mission_paused","mission_resumed","mission_completed"],nb=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function qh(e,n){switch(n){case"errors":return e==="error"||e==="warning";case"state_changes":return tb.includes(e);case"tasks":return Zg.includes(e);case"slices":return eb.includes(e);case"autopilot":return nb.includes(e);default:return!0}}function NR(e){return e==="error"||e==="warning"?"mission-event__type--error":tb.includes(e)?"mission-event__type--state":Zg.includes(e)?"mission-event__type--task":eb.includes(e)?"mission-event__type--slice":nb.includes(e)?"mission-event__type--autopilot":"mission-event__type--default"}function SR(e){return e.replace(/_/g," ")}function CR(e,n){return n?e==="watching"?`Watching since ${ml(n)}`:`Last activation ${ml(n)}`:null}function ER({isOpen:e,isInline:n=!1,onClose:s,addToast:a,projectId:r,onSelectTask:o,availableTasks:l=[],resumeSessionId:c,targetMissionId:d,milestoneSliceResumeSessionId:u,onMilestoneSliceResumeFetchError:m}){const h=n||e,[f,p]=i.useState([]),[g,x]=i.useState(null),[v,b]=i.useState(!0),[y,j]=i.useState(!1),C=Pi()==="mobile",[A,N]=i.useState(!1),[S,_]=i.useState(null),[T,M]=i.useState(Ic),[E,L]=i.useState(!1),[F,R]=i.useState(new Set),[P,O]=i.useState(new Set),[q,Z]=i.useState(null),[z,k]=i.useState($c),[I,$]=i.useState(!1),[w,H]=i.useState(null),[K,pe]=i.useState(Dc),[le,B]=i.useState(!1),[ye,U]=i.useState(null),[te,ne]=i.useState(null),[ee,ie]=i.useState(Lc),[ge,se]=i.useState(!1),[Ae,xe]=i.useState(null),[Se,qe]=i.useState(null),[We,Qe]=i.useState(""),[ve,Oe]=i.useState(!1),[ae,re]=i.useState([]),[je,Q]=i.useState(void 0),Fe=je??c,[Je,be]=i.useState(null),[ze,tt]=i.useState(null),[kt,ke]=i.useState(null);i.useEffect(()=>{h&&Fe&&Oe(!0)},[h,Fe]),i.useEffect(()=>{if(!h||Fe)return;let W=!1;return Wd(r).then(Ee=>{if(W)return;const Ge=Ee.filter(At=>At.type==="mission_interview"&&(At.status==="awaiting_input"||At.status==="error"));re(Ge)}).catch(Ee=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",Ee)}),()=>{W=!0}},[h,r,Fe]),i.useEffect(()=>{if(!h||!u)return;let W=!1;return bi(u).then(Ee=>{if(!(W||!Ee))try{const Ge=JSON.parse(Ee.inputPayload||"{}");Ge.targetId&&Ge.targetType&&be({type:Ge.targetType,id:Ge.targetId,title:Ge.targetTitle||Ee.title,resumeSessionId:u})}catch{be({type:"milestone",id:"",title:Ee.title,resumeSessionId:u})}}).catch(Ee=>{W||(console.warn("[MissionManager] Failed to fetch session for milestone/slice resume:",Ee),m?.())}),()=>{W=!0}},[h,u,m]);const[ce,Te]=i.useState(null),[he,Le]=i.useState(new Map),[st,it]=i.useState(null),[lt,$e]=i.useState({title:"",assertion:"",status:"pending"}),[Ue,Xe]=i.useState(!1),[wt,Re]=i.useState(null),[xt,Pt]=i.useState(new Map),[Ct,Ot]=i.useState(new Set),[zt,Nt]=i.useState(new Set),[jt,Yt]=i.useState(null),[Bt,qt]=i.useState(new Map),[wn,mn]=i.useState(null),[Xt,Vt]=i.useState(null),[Ft,Zt]=i.useState(!0),[en,cn]=i.useState(new Set),[we,De]=i.useState(new Map),[oe,Pe]=i.useState(null),[Ce,J]=i.useState(new Map),[Ie,de]=i.useState(null),[Ne,Ye]=i.useState(new Map),[ft,tn]=i.useState(new Map),[$t,Rt]=i.useState("structure"),[Dt,En]=i.useState([]),bn=i.useRef([]),Nn=i.useRef([]),dn=i.useRef(null),xn=i.useRef(null),rn=i.useRef("structure"),On=i.useRef("all"),[fe,ct]=i.useState(!1),[hn,zn]=i.useState(0),[ue,ut]=i.useState("all"),[yt,dt]=i.useState(new Set),at=i.useRef(null),vt=i.useRef(null);Nn.current=f,dn.current=g,xn.current=wn,rn.current=$t,On.current=ue;const Ht=i.useCallback((W="auto")=>{const Ee=vt.current;if(Ee&&typeof Ee.scrollIntoView=="function"){Ee.scrollIntoView({block:"end",behavior:W});return}const Ge=at.current;Ge&&(Ge.scrollTop=Ge.scrollHeight)},[]),Ut=i.useCallback(()=>{const W=at.current;return W?W.scrollHeight-W.scrollTop-W.clientHeight<=100:!0},[]),An=i.useCallback(async W=>{if(W.length===0){tn(new Map);return}const Ee=await Rj(r);tn(Ge=>{const At=new Map(Ge);for(const[yn,Qt]of Object.entries(Ee))kR(Qt)&&At.set(yn,Qt);return At})},[r]),Wt=i.useCallback(async()=>{try{b(!0);const W=await Ej(r);p(W),An(W)}catch(W){a(_e(W)||"Failed to load missions","error")}finally{b(!1)}},[a,r,An]),Tt=i.useCallback(async W=>{try{j(!0);const Ee=await gf(W,r);if(x(Ee),Ee.milestones.length>0){const Ge=Ee.milestones[0].id;mn(Ge),Zt(!0),R(new Set([Ge])),Jl(Ge,r).then(At=>{Le(yn=>{const Qt=new Map(yn);return Qt.set(Ge,At),Qt})}).catch(()=>{}),Yl(Ge,r).then(At=>{qt(yn=>{const Qt=new Map(yn);return Qt.set(Ge,At),Qt})}).catch(()=>{}),Ee.milestones[0].slices.length>0&&O(new Set([Ee.milestones[0].slices[0].id]))}else mn(null),Vt(null)}catch(Ee){a(_e(Ee)||"Failed to load mission details","error")}finally{j(!1)}},[a,r]);i.useEffect(()=>{if(!h||!wn){Vt(null);return}let W=!1;return Vt(null),Ku(wn,r).then(Ee=>{if(!W){if(!Oc(Ee)){Vt(null);return}Vt(Ee),qt(Ge=>{const At=new Map(Ge);return At.set(wn,Ee.rollup),At})}}).catch(()=>{W||Vt(null)}),()=>{W=!0}},[h,wn,r]),i.useEffect(()=>{Zt(!0)},[wn]);const G=i.useCallback(W=>{!W||W!==xn.current||Ku(W,r).then(Ee=>{xn.current!==W||!Oc(Ee)||(Vt(Ee),qt(Ge=>{const At=new Map(Ge);return At.set(W,Ee.rollup),At}))}).catch(()=>{})},[r]),He=i.useCallback(async(W,Ee)=>{const Ge=Ee?.append??!1,At=Ge?bn.current.length:0;Ge||(ct(!0),dt(new Set));try{const yn=await Pj(W,{limit:50,offset:At,eventType:void 0},r),Qt=yn.events.filter($n=>qh($n.eventType,ue));En($n=>{if(!Ge)return Qt;const Ze=new Set($n.map(_t=>_t.id)),nt=[...$n];for(const _t of Qt)Ze.has(_t.id)||nt.push(_t);return nt}),zn(yn.total),Ge||requestAnimationFrame(()=>{Ht("auto")})}catch(yn){a(_e(yn)||"Failed to load mission activity","error")}finally{Ge||ct(!1)}},[a,ue,r,Ht]);i.useEffect(()=>{bn.current=Dt},[Dt]),i.useEffect(()=>{h&&(Wt(),x(null),mn(null),Vt(null),En([]),zn(0),Rt("structure"),ut("all"),dt(new Set))},[h,Wt]);const mt=i.useRef(null);i.useEffect(()=>{h&&d&&mt.current!==d&&f.length>0&&(mt.current=d,Tt(d))},[h,d,f,Tt]),i.useEffect(()=>{h||(mt.current=null)},[h]),i.useEffect(()=>{!h||!g||$t!=="activity"||He(g.id)},[$t,h,He,g,ue]),i.useEffect(()=>{if(!h||typeof EventSource>"u")return;const W=new URLSearchParams;r&&W.set("projectId",r);const Ee=`/api/events${W.size>0?`?${W.toString()}`:""}`,Ge=()=>{An(Nn.current)},At=cs=>{Ge();const Bn=cs;if(Bn.data)try{const kn=JSON.parse(Bn.data);kn?.id&&p(Wi=>Wi.map(Ws=>Ws.id===kn.id?{...Ws,...kn}:Ws))}catch{}dn.current&&Tt(dn.current.id)},yn=cs=>{Ge(),dn.current&&Tt(dn.current.id)},Qt=()=>{Ge(),dn.current&&Tt(dn.current.id)},$n=cs=>{Ge(),dn.current&&Tt(dn.current.id)},Ze=cs=>{const Bn=cs;if(Bn.data)try{const kn=JSON.parse(Bn.data);kn&&kn.featureId&&(di(kn.featureId),Ii(kn.featureId),kn.milestoneId&&G(kn.milestoneId))}catch{}},nt=cs=>{const Bn=cs;if(Bn.data)try{const kn=JSON.parse(Bn.data);kn&&kn.featureId&&(di(kn.featureId),Ii(kn.featureId),kn.milestoneId&&G(kn.milestoneId),dn.current&&Tt(dn.current.id))}catch{}},_t=cs=>{const Bn=cs;if(Bn.data)try{const kn=JSON.parse(Bn.data);kn&&kn.milestoneId&&(Pn(kn.milestoneId),G(kn.milestoneId))}catch{}},fn=cs=>{const Bn=cs;if(Bn.data)try{const kn=JSON.parse(Bn.data);kn&&kn.milestoneId&&(Vn(kn.milestoneId),Pn(kn.milestoneId),G(kn.milestoneId))}catch{}};return li(Ee,{events:{"mission:updated":At,"slice:updated":yn,"feature:updated":Qt,"milestone:updated":$n,"mission:event":cs=>{Ge();const Bn=dn.current;if(!Bn||rn.current!=="activity")return;const kn=Ut(),Wi=cs;if(Wi.data)try{const Ws=JSON.parse(Wi.data);if(!jR(Ws)||Ws.missionId!==Bn.id||!qh(Ws.eventType,On.current))return;En(ji=>{const Hl=ji.filter(ql=>ql.id!==Ws.id);return[Ws,...Hl].slice(0,100)}),zn(ji=>ji+1),kn&&requestAnimationFrame(()=>{const ji=at.current;ji&&(ji.scrollTop=0)})}catch{}},"validator-run:started":Ze,"validator-run:completed":nt,"milestone:validation:updated":_t,"assertion:created":fn,"assertion:updated":fn,"assertion:deleted":fn,"assertion:linked":fn,"assertion:unlinked":fn,"fix-feature:created":cs=>{const Bn=cs;if(Bn.data)try{const kn=JSON.parse(Bn.data);if(kn&&kn.sourceFeatureId){di(kn.sourceFeatureId);const Wi=kn?.feature?.sliceId,Ws=dn.current;if(Wi&&Ws){const ji=Ws.milestones.find(Hl=>Hl.slices.some(ql=>ql.id===Wi));ji&&G(ji.id)}dn.current&&Tt(dn.current.id)}}catch{}}}})},[h,Ut,Tt,An,r,G]);const ht=i.useCallback(()=>{N(!0),_(null),M(Ic)},[]),Et=i.useCallback(W=>{_(W.id),N(!1),M({title:W.title,description:W.description||"",status:W.status,autopilotEnabled:W.autopilotEnabled??!1})},[]),St=i.useCallback(()=>{_(null),N(!1),M(Ic)},[]),sn=i.useCallback(async()=>{if(!T.title.trim()){a("Mission title is required","error");return}try{if(L(!0),A)await Mj({title:T.title.trim(),description:T.description.trim()||void 0,autopilotEnabled:T.autopilotEnabled},r),a("Mission created","success");else if(S){const W={title:T.title.trim(),description:T.description.trim()||void 0,status:T.status,autopilotEnabled:T.autopilotEnabled};T.autopilotEnabled&&(W.autoAdvance=!0),await _j(S,W,r),a("Mission updated","success"),g?.id===S&&await Tt(S)}await Wt(),St()}catch(W){a(_e(W)||"Failed to save mission","error")}finally{L(!1)}},[T,A,S,a,Wt,Tt,g,St,r]),nn=i.useCallback(async W=>{try{await Aj(W,r),a("Mission deleted","success"),g?.id===W&&x(null),await Wt(),Te(null)}catch(Ee){a(_e(Ee)||"Failed to delete mission","error")}},[a,Wt,g,r]),as=i.useCallback(()=>{$(!0),Z(null),k($c)},[]),Is=i.useCallback(W=>{Z(W.id),$(!1),k({title:W.title,description:W.description||"",status:W.status,dependencies:W.dependencies})},[]),_s=i.useCallback(()=>{Z(null),$(!1),k($c)},[]),ls=i.useCallback(async()=>{if(!z.title.trim()){a("Milestone title is required","error");return}try{L(!0),I&&g?(await Tj(g.id,{title:z.title.trim(),description:z.description.trim()||void 0,dependencies:z.dependencies},r),a("Milestone created","success")):q&&(await Ij(q,{title:z.title.trim(),description:z.description.trim()||void 0,status:z.status,dependencies:z.dependencies},r),a("Milestone updated","success")),await Tt(g.id),_s()}catch(W){a(_e(W)||"Failed to save milestone","error")}finally{L(!1)}},[z,I,q,g,a,Tt,_s,T.title,r]),Xs=i.useCallback(async W=>{try{await $j(W,r),a("Milestone deleted","success"),await Tt(g.id),Te(null)}catch(Ee){a(_e(Ee)||"Failed to delete milestone","error")}},[a,Tt,g,r]),ci=i.useCallback(W=>{mn(W),Zt(!0),R(Ee=>{const Ge=new Set(Ee);return!Ge.has(W)?(Ge.add(W),Jl(W,r).then(yn=>{Le(Qt=>{const $n=new Map(Qt);return $n.set(W,yn),$n})}).catch(()=>{}),Yl(W,r).then(yn=>{qt(Qt=>{const $n=new Map(Qt);return $n.set(W,yn),$n})}).catch(()=>{})):Ge.delete(W),Ge})},[r]),pn=i.useCallback(W=>{U(W),B(!0),H(null),pe(Dc)},[]),me=i.useCallback(W=>{H(W.id),B(!1),pe({title:W.title,description:W.description||"",status:W.status})},[]),Ve=i.useCallback(()=>{H(null),B(!1),U(null),pe(Dc)},[]),ot=i.useCallback(async()=>{if(!K.title.trim()){a("Slice title is required","error");return}try{L(!0),le&&ye?(await Dj(ye,{title:K.title.trim(),description:K.description.trim()||void 0},r),a("Slice created","success")):w&&(await Lj(w,{title:K.title.trim(),description:K.description.trim()||void 0,status:K.status},r),a("Slice updated","success")),await Tt(g.id),Ve()}catch(W){a(_e(W)||"Failed to save slice","error")}finally{L(!1)}},[K,le,w,ye,g,a,Tt,Ve,r]),on=i.useCallback(async W=>{try{await Oj(W,r),a("Slice deleted","success"),await Tt(g.id),Te(null)}catch(Ee){a(_e(Ee)||"Failed to delete slice","error")}},[a,Tt,g,r]),Un=i.useCallback(async W=>{try{await zj(W,r),a("Slice activated","success"),await Tt(g.id)}catch(Ee){a(_e(Ee)||"Failed to activate slice","error")}},[a,Tt,g,r]),X=i.useCallback(W=>{O(Ee=>{const Ge=new Set(Ee);return Ge.has(W)?Ge.delete(W):Ge.add(W),Ge})},[]),Me=i.useCallback(W=>{xe(W),se(!0),ne(null),ie(Lc)},[]),rt=i.useCallback(W=>{ne(W.id),se(!1),ie({title:W.title,description:W.description||"",acceptanceCriteria:W.acceptanceCriteria||"",status:W.status})},[]),Mt=i.useCallback(()=>{ne(null),se(!1),xe(null),ie(Lc)},[]),Be=i.useCallback(async()=>{if(!ee.title.trim()){a("Feature title is required","error");return}try{L(!0),ge&&Ae?(await Fj(Ae,{title:ee.title.trim(),description:ee.description.trim()||void 0,acceptanceCriteria:ee.acceptanceCriteria.trim()||void 0},r),a("Feature created","success")):te&&(await Uj(te,{title:ee.title.trim(),description:ee.description.trim()||void 0,acceptanceCriteria:ee.acceptanceCriteria.trim()||void 0,status:ee.status},r),a("Feature updated","success")),await Tt(g.id),Mt()}catch(W){a(_e(W)||"Failed to save feature","error")}finally{L(!1)}},[ee,ge,te,Ae,g,a,Tt,Mt,r]),It=i.useCallback(async W=>{try{await Bj(W,r),a("Feature deleted","success"),await Tt(g.id),Te(null)}catch(Ee){a(_e(Ee)||"Failed to delete feature","error")}},[a,Tt,g,r]),Gt=i.useCallback(async()=>{if(!Se||!We.trim()){a("Task ID is required","error");return}try{await Hj(Se,We.trim(),r),a("Feature linked to task","success"),await Tt(g.id),qe(null),Qe("")}catch(W){a(_e(W)||"Failed to link feature to task","error")}},[Se,We,a,Tt,g,r]),vn=i.useCallback(async W=>{try{await qj(W,r),a("Feature unlinked from task","success"),await Tt(g.id)}catch(Ee){a(_e(Ee)||"Failed to unlink feature","error")}},[a,Tt,g,r]),ln=i.useCallback(async W=>{try{L(!0),await Vj(W,void 0,void 0,r),a("Feature triaged — task created","success"),await Tt(g.id)}catch(Ee){a(_e(Ee)||"Failed to triage feature","error")}finally{L(!1)}},[a,Tt,g,r]),Kn=i.useCallback(async W=>{ke(W);try{const Ee=await yN(W,r);tt({featureId:W,enrichedDescription:Ee.description})}catch{await ln(W)}finally{ke(null)}},[ln,r]),Gn=i.useCallback(async()=>{ze&&(tt(null),await ln(ze.featureId))},[ln,ze]),ps=i.useCallback(()=>{tt(null)},[]),Fn=i.useCallback(async W=>{try{L(!0);const Ee=await Wj(W,r);a(`Triaged ${Ee.count} feature${Ee.count!==1?"s":""}`,"success"),await Tt(g.id)}catch(Ee){a(_e(Ee)||"Failed to triage slice features","error")}finally{L(!1)}},[a,Tt,g,r]),Vn=i.useCallback(async W=>{try{const Ee=await Jl(W,r);Le(Ge=>{const At=new Map(Ge);return At.set(W,Ee),At})}catch{}},[r]),Pn=i.useCallback(async W=>{try{const Ee=await Yl(W,r);qt(Ge=>{const At=new Map(Ge);return At.set(W,Ee),At})}catch{}},[r]),fs=i.useCallback(async W=>{if(!lt.title.trim()||!lt.assertion.trim()){a("Title and assertion text are required","error");return}try{L(!0),await Kj(W,{title:lt.title.trim(),assertion:lt.assertion.trim(),status:lt.status},r),a("Assertion created","success"),await Vn(W),await Pn(W),Xe(!1),$e({title:"",assertion:"",status:"pending"})}catch(Ee){a(_e(Ee)||"Failed to create assertion","error")}finally{L(!1)}},[lt,a,Vn,Pn,r]),es=i.useCallback(W=>{it(W.id),$e({title:W.title,assertion:W.assertion,status:W.status})},[]),Wn=i.useCallback(()=>{it(null),Xe(!1),$e({title:"",assertion:"",status:"pending"})},[]),gs=i.useCallback(async(W,Ee)=>{if(!lt.title.trim()||!lt.assertion.trim()){a("Title and assertion text are required","error");return}try{L(!0),await Gj(W,{title:lt.title.trim(),assertion:lt.assertion.trim(),status:lt.status},r),a("Assertion updated","success"),await Vn(Ee),await Pn(Ee),Wn()}catch(Ge){a(_e(Ge)||"Failed to update assertion","error")}finally{L(!1)}},[lt,a,Vn,Pn,Wn,r]),Jn=i.useCallback(async W=>{try{const Ee=await Qj(W,r);Pt(Ge=>{const At=new Map(Ge);return At.set(W,Ee),At})}catch{}},[r]),bs=i.useCallback(async W=>{const Ee=wt!==W;Re(Ge=>Ge===W?null:W),Ee&&await Jn(W)},[wt,Jn]),ts=i.useCallback(W=>{Re(W),Jn(W),requestAnimationFrame(()=>{const Ee=document.querySelector(`[data-mission-assertion-id="${W}"]`);Ee instanceof HTMLElement&&typeof Ee.scrollIntoView=="function"&&Ee.scrollIntoView({behavior:"smooth",block:"center"})})},[Jn]),$s=i.useCallback(async(W,Ee)=>{try{Ot(Ge=>new Set(Ge).add(Ee)),await Jj(W,Ee,r),a("Feature linked to assertion","success"),await Jn(Ee),Yt(null)}catch(Ge){a(_e(Ge)||"Failed to link feature","error")}finally{Ot(Ge=>{const At=new Set(Ge);return At.delete(Ee),At})}},[a,Jn,r]),Ds=i.useCallback(async(W,Ee)=>{const Ge=`${W}-${Ee}`;try{Nt(At=>new Set(At).add(Ge)),await Yj(W,Ee,r),a("Feature unlinked from assertion","success"),await Jn(Ee)}catch(At){a(_e(At)||"Failed to unlink feature","error")}finally{Nt(At=>{const yn=new Set(At);return yn.delete(Ge),yn})}},[a,Jn,r]),ha=i.useCallback(async W=>{try{cn(Ge=>new Set(Ge).add(W)),await Xj(W,r),a("Validation triggered","success");const Ee=await Gu(W,r);De(Ge=>{const At=new Map(Ge);return At.set(W,Ee),At})}catch(Ee){a(_e(Ee)||"Failed to trigger validation","error")}finally{cn(Ee=>{const Ge=new Set(Ee);return Ge.delete(W),Ge})}},[a,r]),di=i.useCallback(async W=>{try{const Ee=await Gu(W,r);De(Ge=>{const At=new Map(Ge);return At.set(W,Ee),At})}catch{}},[r]),Ii=i.useCallback(async W=>{try{const Ee=await Zj(W,{limit:10},r);J(Ge=>{const At=new Map(Ge);return At.set(W,Ee),At})}catch{}},[r]),ui=i.useCallback(W=>{const Ee=dn.current;if(Ee){for(const Ge of Ee.milestones)for(const At of Ge.slices)if(At.features.find(Qt=>Qt.id===W)){R(Qt=>{const $n=new Set(Qt);return $n.add(Ge.id),$n}),O(Qt=>{const $n=new Set(Qt);return $n.add(At.id),$n}),Pe(W),mn(Ge.id),di(W),Ii(W),requestAnimationFrame(()=>{const Qt=document.querySelector(`[data-mission-feature-id="${W}"]`);Qt instanceof HTMLElement&&typeof Qt.scrollIntoView=="function"&&Qt.scrollIntoView({behavior:"smooth",block:"center"})});return}}},[di,Ii]),pa=i.useCallback(async W=>{try{const Ee=await eN(W,r);Ye(Ge=>{const At=new Map(Ge);return At.set(W,Ee),At})}catch{}},[r]),zl=i.useCallback(async W=>{oe===W?Pe(null):(Pe(W),await di(W),await Ii(W))},[oe,di,Ii]),Fl=i.useCallback(async W=>{Ie===W?de(null):(de(W),await pa(W))},[Ie,pa]),Qa=i.useCallback(async W=>{try{await tN(W,r),a("Mission resumed","success"),await Tt(W),Wt()}catch(Ee){a(_e(Ee)||"Failed to resume mission","error")}},[a,Tt,Wt,r]),Xa=i.useCallback(async W=>{try{const Ge=(await nN(W,r)).pausedTaskIds?.length??0;a(`Mission stopped (${Ge} task${Ge!==1?"s":""} paused)`,"success"),await Tt(W),Wt()}catch(Ee){a(_e(Ee)||"Failed to stop mission","error")}},[a,Tt,Wt,r]),Za=i.useCallback(async W=>{try{await sN(W,r),a("Mission started — first slice activated","success"),await Tt(W),Wt()}catch(Ee){a(_e(Ee)||"Failed to start mission","error")}},[a,Tt,Wt,r]),Ul=i.useCallback(async(W,Ee)=>{try{await iN(W,{enabled:Ee},r),a(Ee?"Autopilot enabled":"Autopilot disabled","success"),await Tt(W),Wt()}catch(Ge){a(_e(Ge)||"Failed to update autopilot","error")}},[a,Tt,Wt,r]),so=i.useCallback(W=>{Rt("structure"),mn(null),Vt(null),En([]),zn(0),ut("all"),dt(new Set),Tt(W.id)},[Tt]),io=i.useCallback(()=>{x(null),mn(null),Vt(null),Rt("structure"),En([]),zn(0),ut("all"),dt(new Set),Wt()},[Wt]),rs=Dt.length<hn,mi=g?.autopilotState??"inactive",Ss=mi==="watching"||mi==="activating",er=CR(mi,g?.lastAutopilotActivityAt),qi=i.useMemo(()=>!Xt||!wn||!Oc(Xt)?null:Xt.rollup.milestoneId===wn?Xt:null,[wn,Xt]),ao=i.useMemo(()=>{const W=new Map;for(const Ee of qi?.validationTelemetry.validationRounds??[]){const Ge=W.get(Ee.featureId);(!Ge||Ee.startedAt>Ge.startedAt)&&W.set(Ee.featureId,Ee)}return W},[qi]),fa=i.useCallback(()=>{!g||fe||!rs||He(g.id,{append:!0})},[fe,rs,He,g]),Bl=i.useCallback(W=>{dt(Ee=>{const Ge=new Set(Ee);return Ge.has(W)?Ge.delete(W):Ge.add(W),Ge})},[]),ga=i.useCallback(W=>{W.key==="Enter"&&!W.shiftKey&&(W.preventDefault(),sn())},[sn]),Y=i.useCallback(W=>{W.key==="Enter"&&!W.shiftKey&&(W.preventDefault(),ls())},[ls]),Ke=i.useCallback(W=>{W.key==="Enter"&&!W.shiftKey&&(W.preventDefault(),ot())},[ot]),bt=i.useCallback(W=>{W.key==="Enter"&&!W.shiftKey&&(W.preventDefault(),Be())},[Be]),Kt=i.useRef(null);if(i.useEffect(()=>{if(!h)return;const W=Ee=>{Ee.key==="Escape"&&s()};return document.addEventListener("keydown",W),()=>document.removeEventListener("keydown",W)},[h,s]),!h)return null;const ss=()=>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:[Ss&&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:(ur[g.status]||ur.planning).bg,color:(ur[g.status]||ur.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:W=>Ul(g.id,W.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(Xn,{size:14,className:"mission-detail__autopilot-icon"}),"Autopilot"]})]}),t.jsxs("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(Io[mi]||Io.inactive).bg,color:(Io[mi]||Io.inactive).text},"data-testid":"autopilot-state-badge",children:[Ss&&t.jsx("span",{className:"mission-detail__autopilot-pulse"}),mi]})]}),er&&t.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:er})]}),t.jsxs("div",{className:"mission-detail__actions",children:[g.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Xa(g.id),title:"Stop mission","aria-label":"Stop mission",children:t.jsx(Os,{size:14})}),g.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Qa(g.id),title:"Resume mission","aria-label":"Resume mission",children:t.jsx(Hn,{size:14})}),g.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Za(g.id),title:"Start mission","aria-label":"Start mission",children:t.jsx(Hn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Et(g),title:"Edit mission","aria-label":"Edit mission",children:t.jsx(xs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Te({type:"mission",id:g.id}),title:"Delete mission","aria-label":"Delete mission",children:t.jsx(Cn,{size:14})})]})]}),S===g.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:T.title,onChange:W=>M({...T,title:W.target.value}),onKeyDown:ga,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:T.description,onChange:W=>M({...T,description:W.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:T.status,onChange:W=>M({...T,status:W.target.value}),children:[t.jsx("option",{value:"planning",children:"Planning"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"blocked",children:"Blocked"}),t.jsx("option",{value:"complete",children:"Complete"}),t.jsx("option",{value:"archived",children:"Archived"})]}),t.jsxs("label",{className:"mission-checkbox",children:[t.jsx("input",{type:"checkbox",checked:T.autopilotEnabled,onChange:W=>M({...T,autopilotEnabled:W.target.checked})}),t.jsx(Xn,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:sn,disabled:E,children:[E?t.jsx(gt,{size:14,className:"spinner"}):t.jsx(Yn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:St,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-detail__tabs",role:"tablist","aria-label":"Mission detail tabs",children:[t.jsx("button",{className:`mission-btn ${$t==="structure"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Rt("structure"),role:"tab","aria-selected":$t==="structure","data-testid":"mission-tab-structure",children:"Structure"}),t.jsxs("button",{className:`mission-btn ${$t==="activity"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Rt("activity"),role:"tab","aria-selected":$t==="activity","data-testid":"mission-tab-activity",children:["Activity (",hn,")"]})]}),$t==="structure"?t.jsxs("div",{className:"mission-detail__milestones",children:[g.milestones.map(W=>{const Ee=qi?.rollup.milestoneId===W.id?qi:null,Ge=Ee?.rollup??Bt.get(W.id),At=Ee?.validationTelemetry.validationRounds??[],yn=Ee?.fixFeatures??[],Qt=Uh[Ge?.state??"not_started"]??Uh.not_started,$n=Ge&&(Ge.state==="blocked"||Ge.state==="failed")?Ee?.validationTelemetry.validationRounds.find(Ze=>Ze.blockedReason)?.blockedReason:void 0;return t.jsxs("div",{className:"mission-milestone",children:[t.jsxs("div",{className:"mission-milestone__header",onClick:()=>ci(W.id),children:[t.jsx("button",{className:"mission-milestone__expand",children:F.has(W.id)?t.jsx(un,{size:16}):t.jsx(Tn,{size:16})}),t.jsx(na,{size:16,className:"mission-milestone__icon"}),t.jsx("span",{className:"mission-milestone__title",children:W.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:zh[W.status].bg,color:zh[W.status].text},children:W.status}),t.jsxs("span",{className:"mission-milestone__count",children:[W.slices.length," slices"]}),t.jsx(Bh,{state:vR(W.interviewState)}),Ge&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Qt.bg,color:Qt.text},title:"Validation state",children:Hh(Ge.state)}),Ge.totalAssertions>0&&t.jsx("div",{className:"mission-milestone__coverage-bar",title:`${Ge.passedAssertions??0} of ${Ge.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-milestone__coverage-bar-fill",style:{width:`${(Ge.passedAssertions??0)/Ge.totalAssertions*100}%`,backgroundColor:(Ge.passedAssertions??0)===Ge.totalAssertions?"var(--color-success)":"var(--color-warning)"}})})]}),W.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>be({type:"milestone",id:W.id,title:W.title}),title:"Plan milestone","aria-label":"Plan milestone",children:t.jsx(Fi,{size:14})}),t.jsxs("div",{className:"mission-milestone__actions",onClick:Ze=>Ze.stopPropagation(),children:[t.jsx("button",{className:"mission-icon-btn",onClick:()=>pn(W.id),title:"Add slice",children:t.jsx(Sn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Is(W),title:"Edit milestone",children:t.jsx(xs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Te({type:"milestone",id:W.id}),title:"Delete milestone",children:t.jsx(Cn,{size:14})})]})]}),F.has(W.id)&&t.jsxs("div",{className:"mission-milestone__body",children:[(I||q===W.id)&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:z.title,onChange:Ze=>k({...z,title:Ze.target.value}),onKeyDown:Y,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:z.description,onChange:Ze=>k({...z,description:Ze.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:ls,disabled:E,children:[E?t.jsx(gt,{size:14,className:"spinner"}):t.jsx(Yn,{size:14}),q?"Update":"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:_s,children:"Cancel"})]})]}),Ee&&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:[Ee.validationTelemetry.totalRuns," rounds",Ee.validationTelemetry.lastValidatorStatus?` · Last ${Ee.validationTelemetry.lastValidatorStatus}`:""]})]}),$n&&t.jsxs("div",{className:"mission-blocked-reason",children:[t.jsx("strong",{children:"Blocked reason:"})," ",$n]}),At.length>0&&t.jsxs("div",{className:"mission-validation-rounds",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm mission-validation-rounds__toggle",onClick:()=>Zt(Ze=>!Ze),title:Ft?"Hide validation rounds":"Show validation rounds",children:[Ft?t.jsx(un,{size:12}):t.jsx(Tn,{size:12}),"Validation rounds (",At.length,")"]}),Ft&&t.jsx("div",{className:"mission-validation-rounds__list",children:At.map(Ze=>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--${Ze.validatorStatus}`,children:Ze.validatorStatus}),t.jsx("span",{className:"mission-validation-round__feature",children:Ze.featureTitle}),t.jsxs("span",{className:"mission-validation-round__attempts",children:["impl #",Ze.implementationAttempt," · reviewer #",Ze.validatorAttempt]})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),Ze.failedAssertionIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Ze.failedAssertionIds.map(nt=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>ts(nt),title:`Jump to assertion ${nt}`,children:nt},`${Ze.roundId}-${nt}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Generated fix features:"}),Ze.generatedFixFeatureIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Ze.generatedFixFeatureIds.map(nt=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>ui(nt),title:`Jump to fix feature ${nt}`,children:nt},`${Ze.roundId}-${nt}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),Ze.blockedReason&&t.jsx("div",{className:"mission-validation-round__blocked-reason",children:Ze.blockedReason})]},Ze.roundId))})]}),yn.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:yn.map(Ze=>t.jsxs("div",{className:"mission-fix-feature",children:[t.jsxs("div",{className:"mission-fix-feature__header",children:[t.jsx("button",{className:"mission-fix-feature__title",onClick:()=>ui(Ze.id),title:`Jump to feature ${Ze.id}`,children:Ze.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:To[Ze.status].bg,color:To[Ze.status].text},children:Ze.status}),Ze.loopState&&t.jsx("span",{className:`mission-loop-state mission-loop-state--${Ze.loopState}`,children:Ze.loopState})]}),t.jsxs("div",{className:"mission-fix-feature__meta",children:[t.jsx("span",{children:"Source:"}),t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>ui(Ze.sourceFeatureId),title:`Jump to source feature ${Ze.sourceFeatureId}`,children:Ze.sourceFeatureId}),t.jsx("span",{children:"Run:"}),t.jsx("span",{className:"mission-fix-feature__run",children:Ze.runId})]}),Ze.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:Ze.failedAssertionIds.map(nt=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>ts(nt),title:`Jump to assertion ${nt}`,children:nt},`${Ze.id}-${nt}`))})]})]},Ze.id))})]})]}),t.jsxs("div",{className:"mission-slices",children:[W.slices.map(Ze=>t.jsxs("div",{className:"mission-slice",children:[t.jsxs("div",{className:"mission-slice__header",onClick:()=>X(Ze.id),children:[t.jsx("button",{className:"mission-slice__expand",children:P.has(Ze.id)?t.jsx(un,{size:16}):t.jsx(Tn,{size:16})}),t.jsx(cd,{size:16,className:"mission-slice__icon"}),t.jsx("span",{className:"mission-slice__title",children:Ze.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Fh[Ze.status].bg,color:Fh[Ze.status].text},children:Ze.status}),t.jsxs("span",{className:"mission-slice__count",children:[Ze.features?.length||0," features"]}),t.jsx(Bh,{state:Ze.planState??"not_started"}),Ze.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>be({type:"slice",id:Ze.id,title:Ze.title}),title:"Plan slice","aria-label":"Plan slice",children:t.jsx(Fi,{size:14})}),t.jsxs("div",{className:"mission-slice__actions",onClick:nt=>nt.stopPropagation(),children:[Ze.status==="pending"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Un(Ze.id),title:"Activate slice",children:t.jsx(Hn,{size:14})}),Ze.status==="active"&&Ze.features?.some(nt=>nt.status==="defined")&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Fn(Ze.id),title:"Triage all features",disabled:E,children:E?t.jsx(gt,{size:14,className:"spinner"}):t.jsx(Xn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Me(Ze.id),title:"Add feature",children:t.jsx(Sn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>me(Ze),title:"Edit slice",children:t.jsx(xs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Te({type:"slice",id:Ze.id}),title:"Delete slice",children:t.jsx(Cn,{size:14})})]})]}),P.has(Ze.id)&&t.jsxs("div",{className:"mission-slice__body",children:[le&&ye===W.id&&!w&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:K.title,onChange:nt=>pe({...K,title:nt.target.value}),onKeyDown:Ke,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:K.description,onChange:nt=>pe({...K,description:nt.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:ot,disabled:E,children:[E?t.jsx(gt,{size:14,className:"spinner"}):t.jsx(Yn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Ve,children:"Cancel"})]})]}),w===Ze.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:K.title,onChange:nt=>pe({...K,title:nt.target.value}),onKeyDown:Ke,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:K.description,onChange:nt=>pe({...K,description:nt.target.value}),rows:2}),t.jsxs("select",{value:K.status,onChange:nt=>pe({...K,status:nt.target.value}),children:[t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"complete",children:"Complete"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:ot,disabled:E,children:[E?t.jsx(gt,{size:14,className:"spinner"}):t.jsx(Yn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Ve,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-features",children:[Ze.features?.map(nt=>t.jsxs("div",{className:"mission-feature","data-mission-feature-id":nt.id,children:[t.jsxs("div",{className:"mission-feature__header",children:[t.jsx("button",{className:"mission-feature__expand",onClick:()=>zl(nt.id),title:oe===nt.id?"Collapse details":"Expand to show run history",children:oe===nt.id?t.jsx(un,{size:14}):t.jsx(Tn,{size:14})}),t.jsx(td,{size:14,className:"mission-feature__icon"}),t.jsx("span",{className:"mission-feature__title",children:nt.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:To[nt.status].bg,color:To[nt.status].text},children:nt.status}),nt.loopState&&nt.loopState!=="idle"&&t.jsxs("span",{className:`mission-loop-state mission-loop-state--${nt.loopState}`,title:`Loop state: ${nt.loopState}`,children:[nt.loopState==="implementing"&&"⏳",nt.loopState==="validating"&&"🔄",nt.loopState==="needs_fix"&&"🔧",nt.loopState==="passed"&&"✅",nt.loopState==="blocked"&&"🚫"]}),nt.generatedFromFeatureId&&t.jsx("button",{className:"mission-feature__lineage",onClick:()=>ui(nt.generatedFromFeatureId),title:`Generated from feature: ${nt.generatedFromFeatureId}`,children:"🔗 Fix"}),(nt.loopState==="validating"||nt.loopState==="needs_fix")&&(()=>{const _t=we.get(nt.id),fn=ao.get(nt.id),Zs=_t?.implementationAttemptCount??fn?.implementationAttempt??nt.implementationAttemptCount??0,Vi=_t?.retryBudgetRemaining??Math.max(0,xR-Zs);return t.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",Zs," · ",Vi," ",Vi===1?"retry":"retries"," left"]})})(),nt.loopState==="implementing"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>ha(nt.id),title:"Validate feature",disabled:en.has(nt.id),children:en.has(nt.id)?t.jsx(gt,{size:14,className:"spinner"}):t.jsx(ms,{size:14})}),nt.taskId&&t.jsx("span",{className:"mission-feature__task-link",onClick:()=>o?.(nt.taskId),title:"Click to view task",children:nt.taskId}),t.jsxs("div",{className:"mission-feature__actions",children:[nt.status==="defined"&&!nt.taskId&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Kn(nt.id),title:"Triage — create task",disabled:E||kt===nt.id,children:kt===nt.id?t.jsx(gt,{size:14,className:"spinner"}):t.jsx(Xn,{size:14})}),nt.taskId?t.jsx("button",{className:"mission-icon-btn",onClick:()=>vn(nt.id),title:"Unlink task",children:t.jsx(Nu,{size:14})}):nt.status!=="defined"?t.jsx("button",{className:"mission-icon-btn",onClick:()=>qe(nt.id),title:"Link to task",children:t.jsx(Pa,{size:14})}):null,t.jsx("button",{className:"mission-icon-btn",onClick:()=>rt(nt),title:"Edit feature",children:t.jsx(xs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Te({type:"feature",id:nt.id}),title:"Delete feature",children:t.jsx(Cn,{size:14})})]})]}),nt.description&&t.jsx("p",{className:"mission-feature__description",children:nt.description}),nt.acceptanceCriteria&&t.jsxs("p",{className:"mission-feature__criteria",children:[t.jsx("strong",{children:"Acceptance:"})," ",nt.acceptanceCriteria]}),ze?.featureId===nt.id&&t.jsxs("div",{className:"mission-triage-preview",children:[t.jsx("div",{className:"mission-triage-preview__header",children:"Enriched Description Preview"}),t.jsx("div",{className:"mission-triage-preview__content",children:ze.enrichedDescription}),t.jsxs("div",{className:"mission-triage-preview__actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:Gn,disabled:E,children:[E?t.jsx(gt,{size:14,className:"spinner"}):null,"Create Task"]}),t.jsx("button",{className:"btn",onClick:ps,disabled:E,children:"Cancel"})]})]}),te===nt.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:ee.title,onChange:_t=>ie({...ee,title:_t.target.value}),onKeyDown:bt,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:ee.description,onChange:_t=>ie({...ee,description:_t.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:ee.acceptanceCriteria,onChange:_t=>ie({...ee,acceptanceCriteria:_t.target.value}),rows:2}),t.jsxs("select",{value:ee.status,onChange:_t=>ie({...ee,status:_t.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:Be,disabled:E,children:[E?t.jsx(gt,{size:14,className:"spinner"}):t.jsx(Yn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Mt,children:"Cancel"})]})]}),oe===nt.id&&t.jsxs("div",{className:"mission-feature__run-history",children:[t.jsx("div",{className:"mission-feature__run-history-header",children:t.jsx("span",{className:"mission-feature__run-history-title",children:"Validation Runs"})}),(Ce.get(nt.id)??[]).map(_t=>t.jsxs("div",{className:"mission-run",children:[t.jsxs("div",{className:"mission-run__header",onClick:()=>Fl(_t.id),children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-run__status mission-run__status--${_t.status}`,title:_t.status,children:_t.status}),t.jsx("span",{className:"mission-run__time",children:new Date(_t.startedAt).toLocaleString()}),_t.completedAt&&t.jsxs("span",{className:"mission-run__duration",children:[Math.round((new Date(_t.completedAt).getTime()-new Date(_t.startedAt).getTime())/1e3),"s"]}),_t.triggerType&&t.jsx("span",{className:"mission-run__trigger",children:_t.triggerType}),t.jsx("button",{className:"mission-icon-btn",title:Ie===_t.id?"Hide details":"Show details",children:Ie===_t.id?t.jsx(un,{size:12}):t.jsx(Tn,{size:12})})]}),Ie===_t.id&&Ne.get(_t.id)&&t.jsxs("div",{className:"mission-run__details",children:[_t.summary&&t.jsx("p",{className:"mission-run__summary",children:_t.summary}),_t.blockedReason&&t.jsxs("p",{className:"mission-run__blocked-reason",children:[t.jsx("strong",{children:"Blocked:"})," ",_t.blockedReason]}),Ne.get(_t.id)?.failures&&Ne.get(_t.id).failures.length>0&&t.jsxs("div",{className:"mission-run__failures",children:[t.jsx("span",{className:"mission-run__failures-title",children:"Failed Assertions:"}),Ne.get(_t.id).failures.map(fn=>t.jsxs("div",{className:"mission-run__failure",children:[t.jsx("span",{className:"mission-run__failure-message",children:fn.message}),fn.expected&&t.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",fn.expected]}),fn.actual&&t.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",fn.actual]})]},fn.id))]}),(!Ne.get(_t.id)?.failures||Ne.get(_t.id).failures.length===0)&&t.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},_t.id)),(!Ce.get(nt.id)||Ce.get(nt.id).length===0)&&t.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},nt.id)),ge&&Ae===Ze.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:ee.title,onChange:nt=>ie({...ee,title:nt.target.value}),onKeyDown:bt,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:ee.description,onChange:nt=>ie({...ee,description:nt.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:ee.acceptanceCriteria,onChange:nt=>ie({...ee,acceptanceCriteria:nt.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Be,disabled:E,children:[E?t.jsx(gt,{size:14,className:"spinner"}):t.jsx(Yn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Mt,children:"Cancel"})]})]}),!ge&&(!Ze.features||Ze.features.length===0)&&t.jsxs("div",{className:"mission-manager__empty mission-features__empty",children:[t.jsx(td,{size:16}),t.jsx("span",{children:"No fix features generated."})]})]})]})]},Ze.id)),W.slices.length===0&&!le&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(cd,{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"}),Ge&&t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Qt.bg,color:Qt.text},children:Hh(Ge.state)}),Ge&&Ge.totalAssertions>0&&t.jsx("div",{className:"mission-assertions__coverage-bar",title:`${Ge.passedAssertions??0} of ${Ge.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-assertions__coverage-bar-fill",style:{width:`${(Ge.passedAssertions??0)/Ge.totalAssertions*100}%`,backgroundColor:(Ge.passedAssertions??0)===Ge.totalAssertions?"var(--color-success)":"var(--color-warning)"}})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>{Xe(!0),it(null),$e({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:t.jsx(Sn,{size:14})})]}),Ue&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:lt.title,onChange:Ze=>$e({...lt,title:Ze.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:lt.assertion,onChange:Ze=>$e({...lt,assertion:Ze.target.value}),rows:2}),t.jsxs("select",{value:lt.status,onChange:Ze=>$e({...lt,status:Ze.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(W.id),disabled:E,children:[E?t.jsx(gt,{size:14,className:"spinner"}):t.jsx(Yn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Wn,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-assertions__list",children:[(Array.isArray(he.get(W.id))?he.get(W.id):[]).map(Ze=>t.jsxs("div",{className:"mission-assertion","data-mission-assertion-id":Ze.id,children:[t.jsx("div",{className:"mission-assertion__header",children:st===Ze.id?t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:lt.title,onChange:nt=>$e({...lt,title:nt.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text",value:lt.assertion,onChange:nt=>$e({...lt,assertion:nt.target.value}),rows:2}),t.jsxs("select",{value:lt.status,onChange:nt=>$e({...lt,status:nt.target.value}),children:[t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"passed",children:"Passed"}),t.jsx("option",{value:"failed",children:"Failed"}),t.jsx("option",{value:"blocked",children:"Blocked"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:()=>gs(Ze.id,W.id),disabled:E,children:[E?t.jsx(gt,{size:14,className:"spinner"}):t.jsx(Yn,{size:14}),"Save"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Wn,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:($o[Ze.status]??$o.pending).bg,color:($o[Ze.status]??$o.pending).text},children:Ze.status}),t.jsx("span",{className:"mission-assertion__title",children:Ze.title}),(()=>{const _t=xt.get(Ze.id)?.length??0;return _t>0?t.jsxs("span",{className:"mission-assertion__linked-count",title:`${_t} linked feature${_t!==1?"s":""}`,children:["(",_t," linked)"]}):null})(),t.jsx("button",{className:"mission-icon-btn",onClick:()=>bs(Ze.id),title:"Toggle details",children:wt===Ze.id?t.jsx(un,{size:14}):t.jsx(Tn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>es(Ze),title:"Edit assertion",children:t.jsx(xs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Te({type:"assertion",id:Ze.id}),title:"Delete assertion",children:t.jsx(Cn,{size:14})})]})}),wt===Ze.id&&t.jsxs("div",{className:"mission-assertion__body",children:[t.jsx("p",{className:"mission-assertion__text",children:Ze.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()=>{wt!==Ze.id&&await bs(Ze.id),Yt(jt===Ze.id?null:Ze.id)},title:"Link a feature",children:[t.jsx(Pa,{size:12}),"Link Feature"]})]}),jt===Ze.id&&t.jsx("div",{className:"mission-assertion__feature-picker",children:t.jsx("div",{className:"mission-assertion__feature-picker-dropdown",children:(()=>{const nt=new Set((xt.get(Ze.id)??[]).map(fn=>fn.id)),_t=[];return g?.milestones.forEach(fn=>fn.slices.forEach(Zs=>_t.push(...Zs.features.filter(Vi=>!nt.has(Vi.id))))),_t.length===0?t.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):_t.map(fn=>t.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>$s(fn.id,Ze.id),disabled:Ct.has(Ze.id),children:[t.jsx("span",{className:"mission-assertion__feature-picker-title",children:fn.title}),Ct.has(Ze.id)&&t.jsx(gt,{size:12,className:"spinner"})]},fn.id))})()})}),(()=>{const nt=xt.get(Ze.id)??[];return nt.length===0?t.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):nt.map(_t=>{const fn=`${_t.id}-${Ze.id}`,Zs=zt.has(fn);return t.jsxs("div",{className:"mission-assertion__linked-feature",children:[t.jsx("span",{className:"mission-assertion__linked-feature-title",children:_t.title}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ds(_t.id,Ze.id),disabled:Zs,title:"Unlink feature",children:Zs?t.jsx(gt,{size:12,className:"spinner"}):t.jsx(Nu,{size:12})})]},_t.id)})})()]})]})]},Ze.id)),(!he.get(W.id)||he.get(W.id)?.length===0)&&!Ue&&t.jsx("div",{className:"mission-manager__empty mission-assertions__empty",children:t.jsx("span",{children:"No assertions defined. Add one to define completion criteria."})})]})]})]})]})]},W.id)}),g&&!I&&q===null&&t.jsxs("button",{className:"mission-add-btn",onClick:as,children:[t.jsx(Sn,{size:16}),"Add Milestone"]}),I&&q===null&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:z.title,onChange:W=>k({...z,title:W.target.value}),onKeyDown:Y,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:z.description,onChange:W=>k({...z,description:W.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:ls,disabled:E,children:[E?t.jsx(gt,{size:14,className:"spinner"}):t.jsx(Yn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:_s,children:"Cancel"})]})]}),g.milestones.length===0&&!I&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(na,{size:24}),t.jsx("span",{children:"No milestones yet. Add one to get started."})]})]}):t.jsxs("div",{className:"mission-detail__activity","data-testid":"mission-activity-tab",children:[t.jsxs("div",{className:"mission-detail__activity-controls",children:[t.jsxs("label",{className:"mission-detail__activity-filter",children:[t.jsx("span",{children:"Filter"}),t.jsxs("select",{value:ue,onChange:W=>ut(W.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:[Dt.length," of ",hn]})]}),!fe&&rs&&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:fa,"data-testid":"mission-activity-load-more",children:"Load more"})}),fe?t.jsxs("div",{className:"mission-manager__loading mission-detail__activity-loading",children:[t.jsx(gt,{size:18,className:"spinner"}),t.jsx("span",{children:"Loading mission activity..."})]}):Dt.length===0?t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Fs,{size:18}),t.jsx("span",{children:"No events yet."})]}):t.jsxs("div",{ref:at,className:"mission-events","data-testid":"mission-activity-events",children:[Dt.map(W=>{const Ee=!!(W.metadata&&Object.keys(W.metadata).length>0),Ge=yt.has(W.id);return t.jsxs("div",{className:"mission-event",children:[t.jsxs("div",{className:"mission-event__header",children:[t.jsx("span",{className:`mission-event__type ${NR(W.eventType)}`,children:SR(W.eventType)}),t.jsx("span",{className:"mission-event__time",children:ml(W.timestamp)})]}),t.jsx("p",{className:"mission-event__description",children:W.description}),t.jsx("span",{className:"mission-event__timestamp",children:new Date(W.timestamp).toLocaleString()}),Ee&&t.jsxs("div",{className:"mission-event__metadata",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>Bl(W.id),"data-testid":`mission-event-metadata-${W.id}`,children:[Ge?"Hide":"Show"," metadata"]}),Ge&&t.jsx("pre",{className:"mission-event__metadata-content",children:JSON.stringify(W.metadata,null,2)})]})]},W.id)}),t.jsx("div",{ref:vt})]})]})]}):null,Vs=()=>f.map(W=>{const Ee=W,Ge=g?.id===Ee.id,At=ur[Ee.status]||{bg:"",text:""},yn=Ee.summary,Qt=ft.get(Ee.id),$n=wR(Qt),Ze=!!(yn&&(yn.totalMilestones>0||yn.totalFeatures>0)),nt=Qt?.totalTasks??0,_t=Qt?.tasksCompleted??0,fn=Qt?.tasksFailed??0,Zs=Qt?.estimatedCompletionPercent??yn?.progressPercent??0,Vi=Ze||nt>0||fn>0||!!Qt?.lastActivityAt,cs=Ee.status==="active"&&(Qt?.currentMilestoneId||Qt?.currentSliceId)?"Current milestone/slice in progress":null;return t.jsxs("div",{className:`mission-list__item ${Ge?"mission-list__item--selected":""}`,onClick:()=>so(W),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:Ee.title}),W.autopilotEnabled&&t.jsx("span",{title:"Autopilot enabled",children:t.jsx(Xn,{size:12,className:"mission-list__item-autopilot-icon"})}),t.jsx("span",{className:`mission-health-badge mission-health-badge--${$n}`,"data-testid":`mission-health-badge-${Ee.id}`,"aria-label":`Mission health: ${$n}`}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:At.bg,color:At.text},children:Ee.status})]}),Ee.description&&t.jsx("p",{className:"mission-list__item-description",children:Ee.description}),cs&&t.jsxs("p",{className:"mission-list__item-active-slice",children:["Active: ",cs]}),Vi&&t.jsxs("div",{className:"mission-list__item-summary",children:[Ze&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"mission-list__item-stat",children:[yn.completedMilestones,"/",yn.totalMilestones," milestones"]}),t.jsxs("span",{className:"mission-list__item-stat",children:[yn.completedFeatures,"/",yn.totalFeatures," features"]})]}),t.jsxs("span",{className:"mission-list__item-stat","data-testid":`mission-task-stats-${Ee.id}`,children:[_t,"/",nt," tasks"]}),fn>0&&t.jsxs("button",{className:"mission-list__item-failed",onClick:Bn=>{Bn.stopPropagation(),so(W)},"data-testid":`mission-failed-${Ee.id}`,title:"View mission failures",children:[fn," failed"]}),t.jsxs("span",{className:"mission-relative-time","data-testid":`mission-last-activity-${Ee.id}`,children:["Activity ",ml(Qt?.lastActivityAt)]}),t.jsx("div",{className:`mission-list__item-progress mission-list__item-progress--${$n}`,children:t.jsx("div",{className:"mission-list__item-progress-bar",style:{width:`${Zs}%`}})})]})]}),t.jsxs("div",{className:"mission-list__item-actions",onClick:Bn=>Bn.stopPropagation(),children:[Ee.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Xa(Ee.id),title:"Stop mission",children:t.jsx(Os,{size:14})}),Ee.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Qa(Ee.id),title:"Resume mission",children:t.jsx(Hn,{size:14})}),Ee.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Za(Ee.id),title:"Start mission",children:t.jsx(Hn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Et(W),title:"Edit mission",children:t.jsx(xs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Te({type:"mission",id:Ee.id}),title:"Delete mission",children:t.jsx(Cn,{size:14})})]})]},Ee.id)}),ro=({hideBottomButtons:W=!1}={})=>t.jsxs("div",{className:"mission-list",children:[A&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:T.title,onChange:Ee=>M({...T,title:Ee.target.value}),onKeyDown:ga,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:T.description,onChange:Ee=>M({...T,description:Ee.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:sn,disabled:E,children:[E?t.jsx(gt,{size:14,className:"spinner"}):t.jsx(Yn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:St,children:"Cancel"})]})]}),Vs(),S&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:T.title,onChange:Ee=>M({...T,title:Ee.target.value}),onKeyDown:ga,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:T.description,onChange:Ee=>M({...T,description:Ee.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:T.status,onChange:Ee=>M({...T,status:Ee.target.value}),children:[t.jsx("option",{value:"planning",children:"Planning"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"blocked",children:"Blocked"}),t.jsx("option",{value:"complete",children:"Complete"}),t.jsx("option",{value:"archived",children:"Archived"})]}),t.jsxs("label",{className:"mission-checkbox",children:[t.jsx("input",{type:"checkbox",checked:T.autopilotEnabled,onChange:Ee=>M({...T,autopilotEnabled:Ee.target.checked})}),t.jsx(Xn,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:sn,disabled:E,children:[E?t.jsx(gt,{size:14,className:"spinner"}):t.jsx(Yn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:St,children:"Cancel"})]})]}),f.length===0&&!A&&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."})]}),!A&&t.jsxs("div",{className:"mission-list__footer",children:[ae.length>0&&t.jsxs("div",{className:"mission-resume-prompt",children:[t.jsx(Rs,{size:16}),t.jsx("span",{children:ae.length===1?`Resume "${ae[0].title}"?`:`${ae.length} interview sessions pending`}),t.jsx("div",{className:"mission-list__resume-actions",children:ae.map(Ee=>t.jsxs("button",{className:"mission-add-btn",onClick:()=>{Q(Ee.id),Oe(!0),re([])},children:[Ee.status==="error"?t.jsx(ns,{size:14}):t.jsx(ms,{size:14}),Ee.status==="error"?"Retry":"Resume"]},Ee.id))})]}),!W&&t.jsxs("div",{className:"mission-list__footer-actions",children:[t.jsxs("button",{className:"mission-add-btn",onClick:()=>Oe(!0),children:[t.jsx(ms,{size:16}),"Plan with AI"]}),t.jsxs("button",{className:"mission-add-btn",onClick:ht,children:[t.jsx(Sn,{size:16}),"New Mission"]})]})]})]}),tr=()=>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 ",ce?.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()=>{ce&&(ce.type==="mission"?await nn(ce.id):ce.type==="milestone"?await Xs(ce.id):ce.type==="slice"?await on(ce.id):ce.type==="feature"&&await It(ce.id))},children:"Delete"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>Te(null),children:"Cancel"})]})]})}),oo=()=>t.jsx("div",{className:"mission-confirm-panel mission-confirm-panel--link",children:t.jsxs("div",{className:"mission-confirm-panel__content",children:[t.jsx("p",{children:"Link feature to task:"}),t.jsx("input",{type:"text",placeholder:"Task ID (e.g., FN-001)",value:We,onChange:W=>Qe(W.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(W=>t.jsxs("button",{className:"mission-task-suggestions__item",onClick:()=>Qe(W.id),children:[W.id,": ",W.title||"Untitled"]},W.id))})]}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--primary",onClick:Gt,children:"Link"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>{qe(null),Qe("")},children:"Cancel"})]})]})}),lo=t.jsxs("div",{ref:Kt,className:`mission-manager mission-manager--desktop${n?" mission-manager--inline":""}`,role:n?void 0:"dialog","aria-modal":n?void 0:!0,"aria-label":n?void 0:"Mission Manager","data-testid":"mission-manager-dialog",children:[t.jsxs("div",{className:`mission-manager__header${n?" mission-manager__header--inline":""}`,children:[t.jsxs("div",{className:"mission-manager__header-title",children:[g&&t.jsx("button",{className:"mission-manager__back-btn",onClick:io,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:t.jsx(bl,{size:18})}),t.jsx(ws,{size:18,className:"mission-manager__header-icon"}),t.jsxs("h2",{className:"mission-manager__title","data-testid":"mission-header-title",children:[t.jsx("span",{className:"mission-manager__title-text mission-manager__title-text--desktop",children:"Missions"}),t.jsx("span",{className:"mission-manager__title-text mission-manager__title-text--mobile",children:g?g.title:"Missions"})]})]}),!n&&t.jsx("button",{className:"modal-close",onClick:s,title:"Close","aria-label":"Close Mission Manager","data-testid":"mission-close-btn",children:t.jsx(Jt,{size:18})})]}),C?t.jsxs("div",{className:"mission-manager__body mission-manager__body--stacked",children:[v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(gt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(gt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):g?ss():ro(),ce&&tr(),Se&&oo()]}):t.jsxs("div",{className:"mission-manager__split",children:[t.jsxs("aside",{className:"mission-manager__sidebar","data-testid":"mission-sidebar","aria-label":"Mission list",children:[t.jsxs("div",{className:"mission-manager__sidebar-header",children:[t.jsx("span",{className:"mission-manager__sidebar-title",children:"Missions"}),t.jsxs("div",{className:"mission-manager__sidebar-actions",children:[t.jsx("button",{className:"mission-add-btn mission-add-btn--sm",onClick:()=>Oe(!0),title:"Plan with AI","aria-label":"Plan with AI",children:t.jsx(ms,{size:14})}),t.jsx("button",{className:"mission-add-btn mission-add-btn--sm",onClick:ht,title:"New Mission","aria-label":"New Mission",children:t.jsx(Sn,{size:14})})]})]}),t.jsx("div",{className:"mission-manager__sidebar-list",children:v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(gt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):ro({hideBottomButtons:!0})})]}),t.jsxs("div",{className:"mission-manager__detail-pane",children:[y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(gt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):g?ss():t.jsxs("div",{className:"mission-manager__detail-pane-empty","data-testid":"mission-empty-detail",children:[t.jsx(ws,{size:32}),t.jsx("span",{children:"Select a mission to view details"})]}),ce&&tr(),Se&&oo()]})]})]}),co=t.jsx(mR,{isOpen:ve,onClose:()=>Oe(!1),onMissionCreated:()=>{Wt(),a("Mission created from AI interview","success")},projectId:r,resumeSessionId:Fe}),uo=Je?t.jsx(fR,{isOpen:!0,onClose:()=>be(null),onApplied:()=>{be(null),g&&Tt(g.id)},targetType:Je.type,targetId:Je.id,targetTitle:Je.title,missionContext:g?.title,projectId:r,resumeSessionId:Je.resumeSessionId}):null;return n?t.jsxs(t.Fragment,{children:[lo,co,uo]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mission-manager-overlay open",onClick:W=>W.target===W.currentTarget&&s(),"data-testid":"mission-manager-overlay",role:"dialog","aria-modal":"true",children:lo}),co,uo]})}const Do=2e3;function Vh({recipient:e,replyContext:n,agents:s=[],projectId:a,onSend:r,onCancel:o,addToast:l,isLoadingAgents:c=!1}){const[d,u]=i.useState(e?.id??""),[m,h]=i.useState(e?.type??"agent"),[f,p]=i.useState(""),[g,x]=i.useState(!1),[v,b]=i.useState(null),y=d.trim()!==""&&f.trim().length>0&&f.length<=Do,j=i.useCallback(async()=>{if(!(!y||g)){x(!0),b(null);try{const A=m==="agent"?"user-to-agent":"system";await zN({toId:d.trim(),toType:m,content:f.trim(),type:A,...n?{metadata:{replyTo:{messageId:n.messageId}}}:{}},a),r()}catch(A){const N=_e(A)||"Failed to send message";b(N),l?.(N,"error")}finally{x(!1)}}},[y,g,d,m,f,n,a,r,l]),C=i.useCallback(A=>{u(A),h("agent")},[]);return t.jsxs("div",{className:"message-composer","data-testid":"message-composer",children:[t.jsxs("div",{className:"message-composer-header",children:[t.jsx("span",{children:n?"Reply":"New Message"}),t.jsx("button",{className:"btn-icon",onClick:o,"aria-label":"Cancel","data-testid":"message-composer-cancel",children:t.jsx(Jt,{size:16})})]}),t.jsxs("div",{className:"message-composer-body",children:[!e&&t.jsxs("div",{className:"message-composer-field",children:[t.jsx("label",{className:"message-composer-label",htmlFor:"message-recipient",children:"To:"}),t.jsxs("select",{id:"message-recipient",className:"message-composer-select",value:d,onChange:A=>C(A.target.value),disabled:c||s.length===0,"data-testid":"message-composer-recipient",children:[t.jsx("option",{value:"",children:c?"Loading agents…":s.length===0?"No agents available":"Select agent…"}),s.map(A=>t.jsx("option",{value:A.id,children:A.name||A.id},A.id))]})]}),e&&t.jsxs("div",{className:"message-composer-field",children:[t.jsx("span",{className:"message-composer-label",children:"To:"}),t.jsxs("span",{className:"message-composer-recipient-fixed",children:[t.jsx(Rn,{size:14}),e.id]})]}),n&&t.jsxs("div",{className:"message-composer-field","data-testid":"message-composer-reply-context",children:[t.jsx("span",{className:"message-composer-label",children:"Replying to:"}),t.jsx("span",{className:"message-composer-recipient-fixed",children:n.preview?.trim()?n.preview:`Message ${n.messageId}`})]}),t.jsxs("div",{className:"message-composer-field message-composer-field--content",children:[t.jsx("label",{className:"message-composer-label",htmlFor:"message-content",children:"Message:"}),t.jsx("textarea",{id:"message-content",className:"message-composer-textarea",placeholder:"Type your message…",value:f,onChange:A=>p(A.target.value),maxLength:Do,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>Do?"over-limit":"",children:[f.length,"/",Do]})})]}),v&&t.jsxs("div",{className:"message-composer-error","data-testid":"message-composer-error",children:[t.jsx(Rs,{size:14}),t.jsx("span",{children:v})]})]}),t.jsxs("div",{className:"message-composer-footer",children:[t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:o,"data-testid":"message-composer-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:j,disabled:!y||g,"data-testid":"message-composer-send",children:g?t.jsxs(t.Fragment,{children:[t.jsx(gt,{size:14,className:"spin"}),t.jsx("span",{children:"Sending…"})]}):t.jsxs(t.Fragment,{children:[t.jsx(Xi,{size:14}),t.jsx("span",{children:"Send"})]})})]})]})}function Na(e){const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4),o=Math.floor(a/36e5),l=Math.floor(a/864e5);return r<1?"Just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function MR(e,n,s){if(n==="user")return e==="dashboard"?"You":`User: ${e}`;if(n==="agent"){const a=s?.get(e)?.trim();return a?a===e?`Agent: ${e}`:`Agent: ${a} (${e})`:`Agent: ${e}`}return"System"}function _R(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 Wh(e,n=80){return e.length<=n?e:`${e.slice(0,n)}…`}function AR(e){const n=new Map;for(const s of e){const a=`${s.fromType}:${s.fromId}`,r=n.get(a);r?(r.messages.push(s),new Date(s.createdAt)>new Date(r.latestMessage.createdAt)&&(r.latestMessage=s),s.read||r.unreadCount++):n.set(a,{key:a,fromId:s.fromId,fromType:s.fromType,latestMessage:s,messages:[s],unreadCount:s.read?0:1})}return Array.from(n.values()).sort((s,a)=>new Date(a.latestMessage.createdAt).getTime()-new Date(s.latestMessage.createdAt).getTime())}function PR({projectId:e,addToast:n,onUnreadCountChange:s}){const[a,r]=i.useState("inbox"),[o,l]=i.useState(null),[c,d]=i.useState(null),[u,m]=i.useState(0),[h,f]=i.useState(!1),[p,g]=i.useState(null),[x,v]=i.useState([]),[b,y]=i.useState(!1),[j,C]=i.useState(null),[A,N]=i.useState(null),[S,_]=i.useState(null),[T,M]=i.useState("inbox"),[E,L]=i.useState(null),[F,R]=i.useState([]),P=i.useMemo(()=>new Map(F.map(se=>[se.id,se.name??""])),[F]),O=i.useCallback((se,Ae)=>MR(se,Ae,P),[P]),Z=Pi()==="mobile",z=!Z,k=i.useCallback(async()=>{f(!0);try{const se=await LN({limit:50},e);l(se),m(se.unreadCount),s?.(se.unreadCount)}catch{}finally{f(!1)}},[e,s]),I=i.useCallback(async()=>{f(!0);try{const se=await ON({limit:50},e);d(se)}catch{}finally{f(!1)}},[e]),$=i.useCallback(async se=>{f(!0);try{const Ae=await qN(se,e);L(Ae)}catch{}finally{f(!1)}},[e]),w=i.useCallback(async()=>{try{const se=await da(void 0,e);R(se)}catch{}},[e]),H=i.useCallback(async()=>{try{const se=await vf(e);m(se.unreadCount),s?.(se.unreadCount)}catch{}},[e,s]);i.useEffect(()=>{a==="inbox"?k():a==="outbox"?I():a==="agents"&&w()},[a,k,I,w]),i.useEffect(()=>{S&&$(S)},[S,$]),i.useEffect(()=>{H()},[H]),i.useEffect(()=>{w()},[w]),i.useEffect(()=>{if(typeof EventSource>"u")return;const se=e?`?projectId=${encodeURIComponent(e)}`:"",Ae=()=>{H(),a==="inbox"?k():a==="outbox"&&I(),S&&$(S)};return li(`/api/events${se}`,{events:{"message:sent":Ae,"message:received":Ae,"message:read":Ae,"message:deleted":Ae}})},[e,a,S,H,k,I,$]);const K=i.useCallback(async se=>{if(g(se),!se.read)try{const Ae=await FN(se.id,e);Ae&&l(Se=>Se&&{...Se,messages:Se.messages.map(qe=>qe.id===Ae.id?Ae:qe),unreadCount:Math.max(0,Se.unreadCount-1)});const xe=Math.max(0,u-1);m(xe),s?.(xe)}catch{}try{const Ae=await HN(se.fromId,se.fromType,e);v(Ae)}catch{v([se])}},[e,u,s]),pe=i.useCallback(()=>{g(null),v([])},[]),le=i.useCallback(async()=>{try{const se=await UN(e);m(0),s?.(0),l(Ae=>Ae&&{...Ae,messages:Ae.messages.map(xe=>({...xe,read:!0})),unreadCount:0}),n?.(`Marked ${se.markedAsRead} messages as read`,"success")}catch{n?.("Failed to mark messages as read","error")}},[e,n,s]),B=i.useCallback(async se=>{try{await BN(se,e),g(null),v([]),a==="inbox"?k():a==="outbox"?I():S&&$(S),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[e,a,S,k,I,$,n]),ye=i.useCallback(se=>{C({id:se.fromId,type:se.fromType}),N({messageId:se.id,preview:Wh(se.content,120)}),y(!0)},[]),U=i.useCallback(()=>{y(!1),C(null),N(null),n?.("Message sent","success"),a==="outbox"?I():a==="agents"&&S&&$(S),H()},[a,I,S,$,n,H]),te=i.useCallback(()=>{C(a==="agents"&&S?{id:S,type:"agent"}:null),N(null),y(!0)},[a,S]),ne=i.useCallback(()=>{y(!1),C(null),N(null)},[]),ee=()=>!p||b?null:t.jsxs("div",{className:"mailbox-message-detail","data-testid":"mailbox-message-detail",children:[t.jsxs("div",{className:"mailbox-message-detail-header",children:[Z&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:pe,"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:_R(p.type)}),t.jsx("span",{className:"mailbox-message-time",children:Na(p.createdAt)})]}),t.jsxs("div",{className:"mailbox-message-detail-actions",children:[p.fromType==="agent"&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>ye(p),"data-testid":"mailbox-reply",children:[t.jsx(Ei,{size:14}),t.jsx("span",{children:"Reply"})]}),t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>B(p.id),"data-testid":"mailbox-delete",children:[t.jsx(Cn,{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(Rn,{size:14}):t.jsx(ba,{size:14}),O(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(Rn,{size:14}):t.jsx(ba,{size:14}),O(p.toId,p.toType)]})]})]}),x.length>1&&t.jsxs("div",{className:"mailbox-conversation","data-testid":"mailbox-conversation",children:[t.jsx("div",{className:"mailbox-conversation-label",children:"Conversation"}),x.map(se=>{const Ae=se.metadata?.replyTo?.messageId,xe=Ae?x.find(Se=>Se.id===Ae):void 0;return t.jsxs("div",{className:`mailbox-conversation-msg ${se.id===p.id?"current":""}`,children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:O(se.fromId,se.fromType)}),t.jsx("span",{className:"mailbox-message-time",children:Na(se.createdAt)})]}),Ae&&t.jsxs("div",{className:"mailbox-reply-context","data-testid":`mailbox-reply-context-${se.id}`,children:["↪ Replying to ",xe?Wh(xe.content,60):`message ${Ae}`]}),t.jsx("div",{className:"mailbox-conversation-msg-body",children:se.content})]},se.id)})]}),x.length<=1&&t.jsxs(t.Fragment,{children:[p.metadata?.replyTo?.messageId&&t.jsxs("div",{className:"mailbox-reply-context","data-testid":"mailbox-selected-reply-context",children:["↪ Replying to message ",p.metadata.replyTo.messageId]}),t.jsx("div",{className:"mailbox-message-body","data-testid":"mailbox-message-body",children:p.content})]})]}),ie=()=>t.jsxs(t.Fragment,{children:[a==="inbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[h&&!o&&t.jsx(zc,{}),o&&o.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-inbox-empty",children:[t.jsx(vr,{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:AR(o.messages).map(se=>t.jsxs("div",{className:`mailbox-conversation-group ${se.unreadCount>0?"unread":""}`,onClick:()=>K(se.latestMessage),"data-testid":`mailbox-conversation-${se.key}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:se.fromType==="agent"?t.jsx(Rn,{size:16}):t.jsx(ba,{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:O(se.fromId,se.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:Na(se.latestMessage.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[se.latestMessage.content.slice(0,80),se.latestMessage.content.length>80?"…":""]})]}),se.unreadCount>0&&t.jsx("div",{className:"mailbox-group-unread-badge","data-testid":`mailbox-unread-badge-${se.key}`,children:se.unreadCount>9?"9+":se.unreadCount})]},se.key))})]}),a==="outbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-outbox-list",children:[h&&!c&&t.jsx(zc,{}),c&&c.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-outbox-empty",children:[t.jsx(Xi,{size:32}),t.jsx("p",{children:"No sent messages"})]}),c?.messages.map(se=>t.jsxs("div",{className:"mailbox-item",onClick:()=>K(se),"data-testid":`mailbox-item-${se.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:se.toType==="agent"?t.jsx(Rn,{size:16}):t.jsx(ba,{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: ",O(se.toId,se.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:Na(se.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[se.content.slice(0,80),se.content.length>80?"…":""]})]})]},se.id))]}),a==="agents"&&t.jsx("div",{className:"mailbox-agents","data-testid":"mailbox-agents",children:F.length===0?t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Rn,{size:32}),t.jsx("p",{children:"No agents found"})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"mailbox-agents-header",children:[t.jsx("div",{className:"mailbox-agents-dropdown",children:t.jsxs("select",{className:"message-composer-select mailbox-agent-select",value:S??"",onChange:se=>{_(se.target.value||null),M("inbox")},"data-testid":"mailbox-agent-select",children:[t.jsx("option",{value:"",children:"Select an agent…"}),F.map(se=>t.jsx("option",{value:se.id,children:se.name||se.id},se.id))]})}),t.jsxs("button",{className:"btn btn-sm btn-secondary mailbox-compose-btn",onClick:te,"data-testid":"mailbox-compose-btn",children:[t.jsx(Ei,{size:14}),t.jsx("span",{children:"Compose"})]})]}),S&&t.jsxs("div",{className:"mailbox-agent-subtabs","data-testid":"mailbox-agent-subtabs",children:[t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${T==="inbox"?"active":""}`,onClick:()=>M("inbox"),"data-testid":"mailbox-agent-subtab-inbox",children:[t.jsx(vr,{size:12}),t.jsx("span",{children:"Inbox"}),E&&E.unreadCount>0&&t.jsx("span",{className:"mailbox-tab-badge",children:E.unreadCount})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${T==="outbox"?"active":""}`,onClick:()=>M("outbox"),"data-testid":"mailbox-agent-subtab-outbox",children:[t.jsx(Xi,{size:12}),t.jsx("span",{children:"Outbox"})]})]}),t.jsxs("div",{className:"mailbox-agents-content",children:[!S&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Rn,{size:32}),t.jsx("p",{children:"Select an agent to view their mailbox"})]}),S&&h&&!E&&t.jsx(zc,{}),S&&E&&T==="inbox"&&E.inbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(vr,{size:32}),t.jsx("p",{children:"No received messages for this agent"})]}),S&&E&&T==="outbox"&&E.outbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Xi,{size:32}),t.jsx("p",{children:"No sent messages for this agent"})]}),S&&E&&T==="inbox"&&E.inbox.map(se=>t.jsxs("div",{className:`mailbox-item ${se.read?"":"unread"}`,onClick:()=>K(se),"data-testid":`mailbox-item-${se.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:se.fromType==="agent"?t.jsx(Rn,{size:16}):t.jsx(ba,{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:O(se.fromId,se.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:Na(se.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[se.content.slice(0,80),se.content.length>80?"…":""]})]})]},se.id)),S&&E&&T==="outbox"&&E.outbox.map(se=>t.jsxs("div",{className:"mailbox-item",onClick:()=>K(se),"data-testid":`mailbox-item-${se.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:se.toType==="agent"?t.jsx(Rn,{size:16}):t.jsx(ba,{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: ",O(se.toId,se.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:Na(se.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[se.content.slice(0,80),se.content.length>80?"…":""]})]})]},se.id))]})]})})]}),ge=()=>b?t.jsx(Vh,{recipient:j,replyContext:A,agents:F,projectId:e,onSend:U,onCancel:ne,addToast:n}):p?ee():t.jsxs("div",{className:"mailbox-split-empty","data-testid":"mailbox-split-empty",children:[t.jsx(sa,{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(sa,{size:18}),t.jsx("span",{children:"Mailbox"}),u>0&&t.jsx("span",{className:"mailbox-unread-badge","data-testid":"mailbox-unread-badge",children:u})]}),t.jsxs("div",{className:"mailbox-header-actions",children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:te,title:"Compose message","data-testid":"mailbox-header-compose",children:[t.jsx(Ei,{size:14}),t.jsx("span",{children:"Compose"})]}),a==="inbox"&&u>0&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:le,title:"Mark all as read","data-testid":"mailbox-mark-all-read",children:[t.jsx(ax,{size:14}),t.jsx("span",{children:"Mark all read"})]}),t.jsx("button",{className:"btn-icon",onClick:()=>{a==="inbox"?k():a==="outbox"?I():S&&$(S)},disabled:h,title:"Refresh","data-testid":"mailbox-refresh",children:h?t.jsx(gt,{size:14,className:"spin"}):t.jsx(ns,{size:14})})]})]}),t.jsxs("div",{className:"mailbox-tabs","data-testid":"mailbox-tabs",children:[t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${a==="inbox"?"active":""}`,onClick:()=>{r("inbox"),g(null)},"data-testid":"mailbox-tab-inbox",children:[t.jsx(vr,{size:14}),t.jsx("span",{children:"Inbox"}),u>0&&t.jsx("span",{className:"mailbox-tab-badge",children:u})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${a==="outbox"?"active":""}`,onClick:()=>{r("outbox"),g(null)},"data-testid":"mailbox-tab-outbox",children:[t.jsx(Xi,{size:14}),t.jsx("span",{children:"Outbox"})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${a==="agents"?"active":""}`,onClick:()=>{r("agents"),g(null)},"data-testid":"mailbox-tab-agents",children:[t.jsx(Rn,{size:14}),t.jsx("span",{children:"Agents"})]})]}),t.jsx("div",{className:"mailbox-content","data-testid":"mailbox-content",children:z?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:ie()}),t.jsx("div",{className:"mailbox-split-detail-pane","data-testid":"mailbox-split-detail-pane",children:ge()})]}):t.jsxs(t.Fragment,{children:[ee(),b&&t.jsx(Vh,{recipient:j,replyContext:A,agents:F,projectId:e,onSend:U,onCancel:ne,addToast:n}),!p&&!b&&ie()]})})]})}function zc(){return t.jsx("div",{className:"mailbox-skeleton","data-testid":"mailbox-skeleton",children:Array.from({length:5}).map((e,n)=>t.jsxs("div",{className:"mailbox-skeleton-item",children:[t.jsx("div",{className:"mailbox-skeleton-avatar"}),t.jsxs("div",{className:"mailbox-skeleton-content",children:[t.jsx("div",{className:"mailbox-skeleton-line mailbox-skeleton-line--short"}),t.jsx("div",{className:"mailbox-skeleton-line mailbox-skeleton-line--long"})]})]},n))})}const RR=640;function TR({isOpen:e,onClose:n,onImport:s,tasks:a,projectId:r}){const[o,l]=i.useState(""),[c,d]=i.useState(""),[u,m]=i.useState(""),[h,f]=i.useState(!1),[p,g]=i.useState("issues"),[x,v]=i.useState([]),[b,y]=i.useState(null),[j,C]=i.useState([]),[A,N]=i.useState(null),[S,_]=i.useState(null),[T,M]=i.useState(!1),[E,L]=i.useState([]),[F,R]=i.useState(!1),[P,O]=i.useState(""),q=i.useRef(!1),Z=i.useRef(null);wi(Z,e,"fusion:github-modal-size");const z=Ri(n),[k,I]=i.useState(!1),[$,w]=i.useState("list"),H=i.useRef(null),K=new Set;for(const be of a){const ze=be.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);ze&&K.add(ze[1]);const tt=be.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);tt&&K.add(tt[1])}i.useEffect(()=>{if(e)return l(""),d(""),m(""),v([]),y(null),C([]),N(null),g("issues"),_(null),M(!1),L([]),R(!0),O(""),H.current=null,q.current=!0,Vw().then(be=>{if(q.current)if(L(be),R(!1),be.length===1){const ze=be[0];l(ze.owner),d(ze.repo),O(ze.name)}else be.length>1&&(l(""),d(""),O(""))}).catch(()=>{q.current&&R(!1)}),()=>{q.current=!1}},[e]);const pe=i.useCallback(be=>{if(O(be),be==="")l(""),d("");else{const ze=E.find(tt=>tt.name===be);ze&&(l(ze.owner),d(ze.repo))}},[E]),le=i.useCallback(async()=>{if(!o.trim()||!c.trim()){_("Repository must be selected");return}f(!0),_(null),v([]),y(null);try{const be=u.split(",").map(tt=>tt.trim()).filter(Boolean),ze=await Uw(o.trim(),c.trim(),30,be.length>0?be:void 0);v(ze),ze.length===0&&_("No open issues found")}catch(be){_(_e(be)||"Failed to fetch issues")}finally{f(!1)}},[o,c,u]),B=i.useCallback(async()=>{if(!o.trim()||!c.trim()){_("Repository must be selected");return}f(!0),_(null),C([]),N(null);try{const be=await Hw(o.trim(),c.trim(),30);C(be),be.length===0&&_("No open pull requests found")}catch(be){_(_e(be)||"Failed to fetch pull requests")}finally{f(!1)}},[o,c]);i.useEffect(()=>{if(!e||!o.trim()||!c.trim()||h||T)return;const be={owner:o.trim(),repo:c.trim(),labels:u.trim(),tab:p};H.current?.owner===be.owner&&H.current?.repo===be.repo&&H.current?.labels===be.labels&&H.current?.tab===be.tab||(H.current=be,p==="issues"?le():B())},[o,c,u,p,e,h,T,le,B]),i.useEffect(()=>{if(!e)return;const be=ze=>{ze.key==="Escape"&&n()};return document.addEventListener("keydown",be),()=>document.removeEventListener("keydown",be)},[e,n]),i.useEffect(()=>{if(!e)return;const be=()=>{I(window.innerWidth<=RR)};return be(),window.addEventListener("resize",be),()=>window.removeEventListener("resize",be)},[e]);const ye=i.useCallback(be=>{y(be),k&&w("preview")},[k]),U=i.useCallback(be=>{N(be),k&&w("preview")},[k]),te=i.useCallback(()=>{w("list")},[]),ne=i.useCallback(async()=>{if(p==="issues"){if(b===null)return;M(!0),_(null);try{const be=await Bw(o.trim(),c.trim(),b,r);s(be),y(null),k&&$==="preview"&&w("list")}catch(be){const ze=_e(be);ze?.includes("already imported")?_(ze):_(ze||"Failed to import issue")}finally{M(!1)}}else{if(A===null)return;M(!0),_(null);try{const be=await qw(o.trim(),c.trim(),A,r);s(be),N(null),k&&$==="preview"&&w("list")}catch(be){const ze=_e(be);ze?.includes("already imported")?_(ze):_(ze||"Failed to import pull request")}finally{M(!1)}}},[p,b,A,o,c,s,k,$]),ee=x.find(be=>be.number===b),ie=j.find(be=>be.number===A);if(!e)return null;const ge=E.length>0,se=E.length===1,Ae=x.filter(be=>K.has(be.html_url)).length,xe=j.filter(be=>K.has(be.html_url)).length,Se=S==="No open issues found",qe=S==="No open pull requests found",We=p==="issues"?Se:qe,Qe=!!S&&!Se&&x.length===0&&!h,ve=!!S&&!qe&&j.length===0&&!h,Oe=p==="issues"?Qe:ve,ae=h||x.length>0||Se||Qe,re=h||j.length>0||qe||ve,je=p==="issues"?ae:re,Q=!!S&&x.length>0&&!Se,Fe=!!S&&j.length>0&&!qe,Je=p==="issues"?Q:Fe;return t.jsx("div",{className:"modal-overlay open",...z,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg github-import-modal",ref:Z,children:[t.jsxs("div",{className:"modal-header github-import-modal__header",children:[t.jsxs("div",{children:[t.jsx("h3",{children:"Import from GitHub"}),t.jsx("p",{className:"github-import-modal__subtitle",children:"Choose a detected remote, load open issues or pull requests, and import one into the board."})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close import modal",children:"×"})]}),t.jsxs("div",{className:"modal-body github-import-modal__body",children:[t.jsxs("div",{className:"github-import-tabs",role:"tablist","aria-label":"Import type",children:[t.jsxs("button",{role:"tab","aria-selected":p==="issues","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="issues"?"active":""}`,onClick:()=>{g("issues"),N(null)},disabled:h||T,children:[t.jsx(xl,{size:16}),t.jsx("span",{children:"Issues"})]}),t.jsxs("button",{role:"tab","aria-selected":p==="pulls","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="pulls"?"active":""}`,onClick:()=>{g("pulls"),y(null)},disabled:h||T,children:[t.jsx(zs,{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:F?t.jsxs("div",{className:"github-import-toolbar__loading",role:"status","aria-live":"polite",children:[t.jsx(gt,{size:16,className:"spin"}),t.jsx("span",{children:"Detecting…"})]}):ge?se?t.jsxs("div",{className:"github-import-remote-pill","data-testid":"github-import-single-remote",children:[t.jsx("span",{className:"github-import-remote-pill__name",children:E[0].name}),t.jsxs("span",{className:"github-import-remote-pill__repo",children:[E[0].owner,"/",E[0].repo]})]}):t.jsxs("div",{className:"github-import-remote-select",children:[t.jsx("label",{htmlFor:"gh-remote",className:"visually-hidden",children:"Repository"}),t.jsxs("select",{id:"gh-remote",value:P,onChange:be=>pe(be.target.value),disabled:h||T,"aria-label":"Select Git remote",children:[t.jsx("option",{value:"",children:"Select remote…"}),E.map(be=>t.jsxs("option",{value:be.name,children:[be.name," (",be.owner,"/",be.repo,")"]},be.name))]})]}):t.jsx("span",{className:"github-import-toolbar__no-remote",children:"No remotes"})}),t.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--filter",children:p==="issues"?t.jsxs(t.Fragment,{children:[t.jsx("label",{htmlFor:"gh-labels",className:"visually-hidden",children:"Filter by labels"}),t.jsx("input",{id:"gh-labels",type:"text",placeholder:"Filter: bug,enhancement…",value:u,onChange:be=>m(be.target.value),onKeyDown:be=>be.key==="Enter"&&le(),disabled:h||T||!ge,"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"?le:B,disabled:h||T||!o.trim()||!c.trim(),"aria-label":h?`Loading ${p}`:`Load ${p} from repository`,title:h?"Loading…":`Load ${p}`,children:[h?t.jsx(gt,{size:14,className:"spin"}):t.jsx(ns,{size:14}),t.jsx("span",{children:h?"Loading…":"Load"})]})})]}),!F&&!ge&&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"})]}),Je&&t.jsx("div",{className:"form-error github-import-banner",role:"alert",children:S}),t.jsxs("div",{className:"github-import-workspace",children:[t.jsxs("section",{className:`github-import-list-pane ${k?"mobile":""} ${$==="list"?"active":""}`,"data-testid":"github-import-list-pane","aria-labelledby":"github-import-results-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[t.jsx("h4",{id:"github-import-results-heading",children:p==="issues"?"Issues":"Pull Requests"}),p==="issues"&&x.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[x.length," issue",x.length===1?"":"s"]}),t.jsxs("span",{children:[Ae," imported"]})]}),p==="pulls"&&j.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[j.length," pull request",j.length===1?"":"s"]}),t.jsxs("span",{children:[xe," imported"]})]})]}),t.jsxs("div",{className:"github-import-pane-content",children:[!je&&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(gt,{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."})]})]}),Oe&&t.jsx("div",{className:"github-import-state github-import-state--error",role:"alert",children:t.jsxs("div",{children:[t.jsxs("strong",{children:["Could not load ",p==="issues"?"issues":"pull requests"]}),t.jsx("span",{children:S})]})}),We&&t.jsx("div",{className:"github-import-state github-import-state--empty",role:"status",children:t.jsxs("div",{children:[t.jsxs("strong",{children:["No open ",p==="issues"?"issues":"pull requests"," found"]}),t.jsx("span",{children:p==="issues"?"Try a different label filter or choose another repository.":"Choose another repository."})]})}),p==="issues"&&x.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:x.map(be=>{const ze=K.has(be.html_url);return t.jsxs("div",{className:`issue-item ${b===be.number?"selected":""} ${ze?"imported":""}`,onClick:()=>!ze&&ye(be.number),children:[t.jsx("input",{type:"radio",name:"issue",checked:b===be.number,onChange:()=>ye(be.number),disabled:ze,"aria-label":`Select issue #${be.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",be.number]}),t.jsx("span",{className:"issue-title",children:be.title})]}),be.labels.length>0&&t.jsx("span",{className:"issue-labels",children:be.labels.map(tt=>t.jsx("span",{className:"label-chip",children:tt.name},tt.name))})]}),ze&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},be.number)})}),p==="pulls"&&j.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:j.map(be=>{const ze=K.has(be.html_url);return t.jsxs("div",{className:`issue-item ${A===be.number?"selected":""} ${ze?"imported":""}`,onClick:()=>!ze&&U(be.number),children:[t.jsx("input",{type:"radio",name:"pull",checked:A===be.number,onChange:()=>U(be.number),disabled:ze,"aria-label":`Select pull request #${be.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",be.number]}),t.jsx("span",{className:"issue-title",children:be.title})]}),t.jsxs("span",{className:"pull-branch-info",children:[be.headBranch," → ",be.baseBranch]})]}),ze&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},be.number)})})]})]}),t.jsxs("section",{className:`github-import-preview-pane ${k?"mobile":""} ${$==="preview"?"active":""}`,"data-testid":"github-import-preview-pane","aria-labelledby":"github-import-preview-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[k&&t.jsxs("button",{className:"github-import-back-button",onClick:te,"data-testid":"github-import-back-button","aria-label":`Back to ${p==="issues"?"issues":"pull requests"} list`,children:[t.jsx(la,{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"&&ee?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Issue #",ee.number]}),t.jsx("div",{className:"preview-title",children:ee.title}),t.jsx("div",{className:"preview-body",children:ee.body?ee.body.slice(0,200)+(ee.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"&&ie?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Pull Request #",ie.number]}),t.jsx("div",{className:"preview-title",children:ie.title}),t.jsxs("div",{className:"preview-branch",children:[t.jsx("strong",{children:"Branch:"})," ",ie.headBranch," → ",ie.baseBranch]}),t.jsx("div",{className:"preview-body",children:ie.body?ie.body.slice(0,200)+(ie.body.length>200?"…":""):"(no description)"})]}):p==="pulls"?t.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-preview-empty",children:t.jsxs("div",{children:[t.jsx("strong",{children:"No pull request selected"}),t.jsx("span",{children:"Choose a pull request from the list to inspect its details."})]})}):null]})]})]})]}),t.jsxs("div",{className:"modal-actions github-import-modal__actions",children:[t.jsx("button",{className:"btn",onClick:n,disabled:T,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:ne,disabled:(p==="issues"?b===null:A===null)||T,children:T?t.jsx(gt,{size:14,className:"spin"}):"Import"})]})]})})}function Js({summary:e,children:n,className:s="",onToggle:a,defaultOpen:r=!1}){const[o,l]=i.useState(r);return t.jsxs("div",{className:`onboarding-disclosure ${s}`.trim(),children:[t.jsxs("button",{className:"onboarding-disclosure-trigger",onClick:()=>{const c=!o;l(c),a?.(c)},"aria-expanded":o,type:"button",children:[t.jsx(Tn,{size:14,className:"onboarding-disclosure-chevron","aria-hidden":"true"}),t.jsx("span",{children:e})]}),o?t.jsx("div",{className:"onboarding-disclosure-content",children:n}):null]})}const IR=30,$R=16,DR=16;function LR(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let Ko=null;function sb(){return Ko===null&&(Ko=window.visualViewport?.height??window.innerHeight),Ko}function OR(e){const n=sb();e>n&&(Ko=e)}function zR(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 FR(){if(typeof window>"u"||!window.visualViewport)return{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0};const e=window.visualViewport,n=zR(document.activeElement),s=e.offsetTop;n||OR(e.height);const a=Math.max(0,window.innerHeight-e.offsetTop-e.height);if(a>0)return{overlap:a,open:!0,vvHeight:e.height,vvOffsetTop:s};const r=sb(),o=Math.max(0,r-e.offsetTop-e.height);if(o>=IR)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};if(o>=$R&&n)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};const l=Math.max(0,r-e.height);return n&&l>=DR?{overlap:0,open:!0,vvHeight:e.height,vvOffsetTop:s}:{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0}}function Ol({enabled:e=!0}={}){const[n,s]=i.useState(0),[a,r]=i.useState(null),[o,l]=i.useState(0),[c,d]=i.useState(!1);return i.useEffect(()=>{if(!e||!LR()){s(0),r(null),l(0),d(!1);return}const u=window.visualViewport;if(!u){s(0),r(null),l(0),d(!1);return}const m=()=>{const h=FR();s(h.overlap),r(h.vvHeight),l(h.vvOffsetTop),d(h.open)};return m(),u.addEventListener("resize",m),u.addEventListener("scroll",m),document.addEventListener("focusin",m),document.addEventListener("focusout",m),()=>{u.removeEventListener("resize",m),u.removeEventListener("scroll",m),document.removeEventListener("focusin",m),document.removeEventListener("focusout",m),s(0),r(null),l(0),d(!1)}},[e]),{keyboardOverlap:n,viewportHeight:a,viewportOffsetTop:o,keyboardOpen:c}}const UR=["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 BR(e,n){return e&&n?`${e}/${n}`:""}function HR(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 qR({isOpen:e,onClose:n,onTaskCreated:s,onTasksCreated:a,tasks:r,initialPlan:o,projectId:l,resumeSessionId:c}){const[d,u]=i.useState(""),[m,h]=i.useState({type:"initial"}),[f,p]=i.useState(null),[g,x]=i.useState([]),[v,b]=i.useState([]),[y,j]=i.useState(null),C=i.useRef(!1),A=i.useRef(!1),[N,S]=i.useState(""),[_,T]=i.useState(!0),[M,E]=i.useState(!1),[L,F]=i.useState(!1),[R,P]=i.useState(null),[O,q]=i.useState(0),Z=i.useRef(null),z=i.useRef(null),k=i.useRef(null),I=i.useRef(null),$=i.useRef(null),w=i.useRef(null),H=i.useRef(null),[K,pe]=i.useState(c??null),le=i.useMemo(()=>ma(),[]),{isLockedByOther:B,takeControl:ye,isLoading:U}=Ll(e?K:null),{activeTabMap:te,broadcastUpdate:ne,broadcastCompleted:ee,broadcastLock:ie,broadcastUnlock:ge,broadcastHeartbeat:se}=Ya(),[Ae,xe]=i.useState(void 0),[Se,qe]=i.useState(void 0),[We,Qe]=i.useState("medium"),[ve,Oe]=i.useState(""),[ae,re]=i.useState([]),[je,Q]=i.useState(!1),[Fe,Je]=i.useState(null),[be,ze]=i.useState([]),[tt,kt]=i.useState([]),[ke,ce]=i.useState({}),Te=i.useRef(null),[he,Le]=i.useState([]),[st,it]=i.useState(!1),[lt,$e]=i.useState(c??null),[Ue,Xe]=i.useState(!!c),[wt,Re]=i.useState(null),[xt,Pt]=i.useState(!1),Ct=i.useRef(!1),Ot=i.useRef(null),zt=i.useRef(""),Nt=i.useRef(null),jt=i.useRef(null);wi(z,e,"fusion:planning-modal-size");const Yt=Pi(),{keyboardOverlap:Bt,viewportHeight:qt,viewportOffsetTop:wn,keyboardOpen:mn}=Ol({enabled:Yt==="mobile"}),Xt=mn?{"--keyboard-overlap":`${Bt}px`,"--vv-offset-top":`${wn}px`,...qt!==null?{"--vv-height":`${qt}px`}:{}}:{};i.useEffect(()=>{zt.current=N},[N]),i.useEffect(()=>{const ue=Ot.current;if(!ue)return;ue.scrollHeight-ue.scrollTop-ue.clientHeight<32&&(ue.scrollTop=ue.scrollHeight)},[N]),i.useEffect(()=>{if(m.type!=="loading"){P(null),q(0);return}const ue=Date.now();P(ue),q(0);const ut=setInterval(()=>{q(Math.max(0,Math.floor((Date.now()-ue)/1e3)))},1e3);return()=>clearInterval(ut)},[m.type]),i.useEffect(()=>{if(m.type!=="loading")return;const ue=I.current;if(!ue)return;let ut=!1;const dt=setInterval(async()=>{try{const at=await bi(ue);if(ut||!at||I.current!==ue)return;if(at.status==="awaiting_input"&&at.currentQuestion){const vt=JSON.parse(at.currentQuestion);h({type:"question",session:{sessionId:ue,currentQuestion:vt,summary:null}}),S("")}else if(at.status==="complete"&&at.result){const vt=JSON.parse(at.result);h({type:"summary",session:{sessionId:ue,currentQuestion:null,summary:vt},summary:vt}),j(vt),S("")}}catch{}},8e3);return()=>{ut=!0,clearInterval(dt)}},[m.type]);const Vt=i.useCallback(()=>{u(""),h({type:"initial"}),p(null),x([]),b([]),j(null),S(""),E(!1),F(!1),xe(void 0),qe(void 0),Qe("medium"),Oe(""),I.current=null,pe(null)},[]),Ft=BR(Ae,Se),Zt=i.useCallback((ue,ut)=>{if(!ue||!ut)return ke.provider&&ke.modelId?`${ke.provider}/${ke.modelId}`:"Using default";const yt=ae.find(dt=>dt.provider===ue&&dt.id===ut);return yt?`${yt.provider}/${yt.id}`:`${ue}/${ut}`},[ae,ke.modelId,ke.provider]),en=i.useCallback(async()=>{Q(!0),Je(null);try{const ue=await Ms();re(ue.models),ze(ue.favoriteProviders),kt(ue.favoriteModels),ce({provider:ue.resolvedPlanningProvider,modelId:ue.resolvedPlanningModelId})}catch(ue){Je(_e(ue)||"Failed to load models")}finally{Q(!1)}},[]),cn=i.useCallback(ue=>{ze(ut=>{const yt=ut,at=yt.includes(ue)?yt.filter(vt=>vt!==ue):[ue,...yt];return _n({favoriteProviders:at,favoriteModels:tt}).catch(()=>{ze(yt)}),at})},[tt]),we=i.useCallback(ue=>{kt(ut=>{const yt=ut,at=yt.includes(ue)?yt.filter(vt=>vt!==ue):[ue,...yt];return _n({favoriteProviders:be,favoriteModels:at}).catch(()=>{kt(yt)}),at})},[be]),De=i.useCallback(ue=>{k.current?.close();const ut=()=>I.current!==ue,yt=Wk(ue,l,{onThinking:dt=>{ut()||(S(at=>at+dt),ne({sessionId:ue,status:"generating",needsInput:!1,owningTabId:le,type:"planning",title:d.trim()||void 0,projectId:l??null}))},onQuestion:dt=>{if(ut())return;E(!1),F(!1),ja(l);const at=zt.current.trim();at&&b(vt=>vt[vt.length-1]?.thinkingOutput===at?vt:[...vt,{thinkingOutput:at}]),h({type:"question",session:{sessionId:ue,currentQuestion:dt,summary:null}}),S(""),ne({sessionId:ue,status:"awaiting_input",needsInput:!0,owningTabId:le,type:"planning",title:d.trim()||void 0,projectId:l??null})},onSummary:dt=>{if(ut())return;E(!1),F(!1),ja(l);const at=zt.current.trim();at&&b(vt=>vt[vt.length-1]?.thinkingOutput===at?vt:[...vt,{thinkingOutput:at}]),h({type:"summary",session:{sessionId:ue,currentQuestion:null,summary:dt},summary:dt}),j(dt),S(""),ne({sessionId:ue,status:"complete",needsInput:!1,owningTabId:le,type:"planning",title:d.trim()||void 0,projectId:l??null})},onError:dt=>{const at=dt||"Session failed while contacting the AI.";E(!0),(async()=>{try{const vt=await bi(ue);if(vt&&(vt.status==="generating"||vt.status==="awaiting_input")){De(ue);return}}catch{}E(!1),F(!1),p(null),h(vt=>vt.type==="question"||vt.type==="summary"||vt.type==="error"?{type:"error",session:vt.session,errorMessage:at}:{type:"error",session:{sessionId:ue,currentQuestion:null,summary:null},errorMessage:at}),S(""),I.current=ue,ne({sessionId:ue,status:"error",needsInput:!1,owningTabId:le,type:"planning",title:d.trim()||void 0,projectId:l??null}),ee({sessionId:ue,status:"error"})})()},onComplete:()=>{E(!1),F(!1),I.current=null,ee({sessionId:ue,status:"complete"})},onConnectionStateChange:dt=>{E(dt==="reconnecting")}});k.current=yt},[ee,ne,d,l,le]),oe=i.useCallback(async ue=>{const ut=ue??d;if(ut.trim()){p(null),S(""),b([]),x([]),E(!1),h({type:"loading"});try{const yt=Ae&&Se?{planningModelProvider:Ae,planningModelId:Se}:void 0,dt=ve.trim()?Number.parseInt(ve,10):void 0,at=$.current,{sessionId:vt}=await Mk(ut.trim(),l,yt,{planningDepth:We,customQuestionCount:Number.isInteger(dt)?dt:void 0},at??void 0);$.current=null,I.current=vt,pe(vt),$e(vt),De(vt),x([])}catch(yt){E(!1),p(_e(yt)||"Failed to start planning session"),h({type:"initial"}),I.current=null,pe(null)}}},[De,ve,d,We,Se,Ae,l]);i.useEffect(()=>{e&&m.type==="initial"&&Z.current?.focus()},[e,m.type]),i.useEffect(()=>{e&&en()},[e,en]),i.useEffect(()=>{if(e&&o&&!C.current&&m.type==="initial"){u(o);const ue=setTimeout(()=>{C.current=!0,oe(o)},0);return()=>clearTimeout(ue)}else if(e&&!o&&!C.current&&!A.current&&m.type==="initial"){A.current=!0;const ue=JP(l);ue&&u(ue)}},[e,o,m.type,oe,l]);const Pe=i.useCallback(async ue=>{k.current?.close(),k.current=null,p(null),S(""),x([]),b([]),j(null),F(!1),h({type:"loading"});try{const ut=await bi(ue);if(!ut){$e(null),Xe(!1),h({type:"initial"});return}I.current=ue,pe(ue);const yt=Da(ut.conversationHistory);if(b(yt),x(yt.map(dt=>dt.response).filter(dt=>!!(dt&&typeof dt=="object"&&!Array.isArray(dt)))),ut.status==="draft"){let dt="",at,vt;try{const Ht=ut.inputPayload?JSON.parse(ut.inputPayload):null;Ht&&typeof Ht.initialPlan=="string"&&(dt=Ht.initialPlan),Ht&&typeof Ht.modelProvider=="string"&&typeof Ht.modelId=="string"&&(at=Ht.modelProvider,vt=Ht.modelId)}catch{}u(dt),xe(at),qe(vt),$.current=ue,jt.current=dt?{sessionId:ue,initialPlan:dt.trim(),modelProvider:at,modelId:vt}:null,h({type:"initial"})}else if(ut.status==="awaiting_input"&&ut.currentQuestion){ja(l);const dt=JSON.parse(ut.currentQuestion);if(h({type:"question",session:{sessionId:ue,currentQuestion:dt,summary:null}}),ut.thinkingOutput){const at=ut.thinkingOutput.trim();at&&b(vt=>vt[vt.length-1]?.thinkingOutput===at?vt:[...vt,{thinkingOutput:at}])}De(ue)}else if(ut.status==="complete"&&ut.result){ja(l);const dt=JSON.parse(ut.result);h({type:"summary",session:{sessionId:ue,currentQuestion:null,summary:dt},summary:dt}),j(dt)}else ut.status==="generating"?(h({type:"loading"}),ut.thinkingOutput&&S(ut.thinkingOutput),De(ue)):ut.status==="error"&&h({type:"error",session:{sessionId:ue,currentQuestion:null,summary:null},errorMessage:ut.error||"Session failed"})}catch{p("Failed to load session"),h({type:"initial"})}},[De,l]);i.useEffect(()=>{!e||!c||I.current!==c&&H.current!==c&&($e(c),Xe(!0),Pe(c))},[e,c]),i.useEffect(()=>{e&&lt&&(c&&c===lt||Pe(lt))},[e]);const Ce=i.useCallback(async()=>{it(!0);try{const ut=(await Wd(l,{includeCompleted:!0,includeArchived:xt})).filter(yt=>yt.type==="planning").sort((yt,dt)=>Date.parse(dt.updatedAt)-Date.parse(yt.updatedAt));Le(ut)}catch{}finally{it(!1)}},[l,xt]);i.useEffect(()=>{e&&Ce()},[e,Ce]);const J=i.useRef(!1);i.useEffect(()=>{const ue=J.current&&!st;J.current=st,ue&&Yt==="mobile"&&(Ue||c||lt||he.length>0||Xe(!0))},[Yt,Ue,c,lt,st,he.length]),i.useEffect(()=>{if(!e)return;const ue=l?`?projectId=${encodeURIComponent(l)}`:"",ut=dt=>{try{const at=JSON.parse(dt.data);if(at.type!=="planning")return;Le(vt=>{const Ht=vt.findIndex(An=>An.id===at.id);return(Ht>=0?[...vt.slice(0,Ht),at,...vt.slice(Ht+1)]:[at,...vt]).sort((An,Wt)=>Date.parse(Wt.updatedAt)-Date.parse(An.updatedAt))})}catch{}},yt=dt=>{try{const at=JSON.parse(dt.data);Le(vt=>vt.filter(Ht=>Ht.id!==at))}catch{}};return li(`/api/events${ue}`,{events:{"ai_session:updated":ut,"ai_session:deleted":yt},onReconnect:()=>{Ce()}})},[e,l,Ce]);const Ie=i.useCallback(ue=>{if(lt===ue){Xe(!0);return}$e(ue),Xe(!0),Pe(ue)},[Pe,lt]),de=i.useCallback(()=>{k.current?.close(),k.current=null,$.current=null,w.current&&(clearTimeout(w.current),w.current=null),c&&(H.current=c),Vt(),$e(null),Xe(!0)},[Vt,c]),Ne=i.useCallback(()=>{Xe(!1)},[]),Ye=i.useCallback(async(ue,ut)=>{const yt=ut.trim();if(!(!yt||jt.current?.sessionId===ue&&jt.current.initialPlan===yt&&jt.current.modelProvider===Ae&&jt.current.modelId===Se))try{await $N(ue,{initialPlan:yt,modelProvider:Ae&&Se?Ae:void 0,modelId:Ae&&Se?Se:void 0},l),jt.current={sessionId:ue,initialPlan:yt,modelProvider:Ae,modelId:Se}}catch{}},[Se,Ae,l]);i.useEffect(()=>{if(Nt.current&&(clearTimeout(Nt.current),Nt.current=null),!(!e||m.type!=="initial"||!lt))return Nt.current=setTimeout(()=>{Ye(lt,d)},500),()=>{Nt.current&&(clearTimeout(Nt.current),Nt.current=null)}},[d,e,lt,Ye,m.type]),i.useEffect(()=>{jt.current=null},[lt]),i.useEffect(()=>()=>{Nt.current&&(clearTimeout(Nt.current),Nt.current=null)},[]);const ft=i.useCallback(async ue=>{const ut=dt=>dt==="generating"||dt==="awaiting_input",yt=he.find(dt=>dt.id===ue);if(yt&&ut(yt.status))try{await df(ue,l,le)}catch{}try{await xf(ue)}catch{}ee({sessionId:ue,status:"complete",timestamp:Date.now()}),Le(dt=>dt.filter(at=>at.id!==ue)),lt===ue&&(k.current?.close(),k.current=null,Vt(),$e(null),Xe(!1)),Re(null)},[ee,he,l,Vt,lt,le]),tn=i.useCallback(async ue=>{const yt=he.find(dt=>dt.id===ue)?.archived===!0;try{yt?await AN(ue):await _N(ue)}catch{return}Le(dt=>!yt&&!xt?dt.filter(at=>at.id!==ue):dt.map(at=>at.id===ue?{...at,archived:!yt}:at)),!yt&&lt===ue&&!xt&&(k.current?.close(),k.current=null,Vt(),$e(null),Xe(!1))},[he,Vt,lt,Xe,xt]);i.useEffect(()=>{e||(C.current=!1,A.current=!1,E(!1),F(!1),pe(null))},[e]),i.useEffect(()=>{if(!e){Te.current&&(ge(Te.current,le),Te.current=null);return}if(K&&Te.current!==K){Te.current&&ge(Te.current,le),ie(K,le),Te.current=K;return}!K&&Te.current&&(ge(Te.current,le),Te.current=null)},[ie,ge,e,K,le]),i.useEffect(()=>{if(!e||!K||Te.current!==K)return;se(le);const ue=setInterval(()=>{se(le)},3e4);return()=>{clearInterval(ue)}},[se,e,K,le]),i.useEffect(()=>()=>{w.current&&(clearTimeout(w.current),w.current=null),k.current?.close(),k.current=null,Te.current&&(ge(Te.current,le),Te.current=null)},[ge,le]),i.useEffect(()=>{if(!e)return;const ue=()=>{k.current?.close(),k.current=null};return window.addEventListener("beforeunload",ue),()=>window.removeEventListener("beforeunload",ue)},[e]);const $t=i.useCallback((ue,ut)=>{Nt.current&&(clearTimeout(Nt.current),Nt.current=null),(async()=>{try{await Ye(ue,ut),await DN(ue,l)}catch{}})()},[l,Ye]),Rt=i.useCallback(()=>{d&&m.type==="initial"&&GP(d,l);const ue=$.current;ue&&d.trim()&&$t(ue,d),$.current=null,w.current&&(clearTimeout(w.current),w.current=null),k.current?.close(),k.current=null,E(!1),F(!1),n()},[$t,d,n,l,m.type]);i.useEffect(()=>{if(!e)return;const ue=ut=>{ut.key==="Escape"&&Rt()};return document.addEventListener("keydown",ue),()=>document.removeEventListener("keydown",ue)},[e,Rt]);const Dt=i.useCallback(async ue=>{if(m.type!=="question")return;const{session:ut}=m,yt=ut.sessionId,dt=ut.currentQuestion;if(!dt){p("No active question in session");return}p(null),x(at=>[...at,ue]),b(at=>{const vt=zt.current.trim();let Ht=at;return vt&&Ht[Ht.length-1]?.thinkingOutput!==vt&&(Ht=[...Ht,{thinkingOutput:vt}]),[...Ht,{question:dt,response:ue}]}),h({type:"loading"}),S("");try{await _k(yt,ue,l,le)}catch(at){p(_e(at)||"Failed to submit response"),h({type:"question",session:ut})}},[l,le,m]),En=i.useCallback(async()=>{const ue=I.current;if(ue){try{await Pk(ue,l,le)}catch{}k.current?.close(),k.current=null,E(!1),F(!1),h({type:"error",session:{sessionId:ue,currentQuestion:null,summary:null},errorMessage:"Generation stopped by user. You can retry or start a new session."}),S("")}},[l,le]),bn=i.useCallback(async()=>{if(m.type!=="error")return;const ue=m.session;p(null),F(!0),S(""),h({type:"loading"}),De(ue.sessionId);try{I.current=ue.sessionId,pe(ue.sessionId),await Ak(ue.sessionId,l,le)}catch(ut){let yt=ut;if((_e(ut)||"").includes("not in an error state"))try{const at=await bi(ue.sessionId);if(!at)throw new Error("Failed to refresh planning session.");if(I.current=at.id,pe(at.id),at.status==="generating")S(at.thinkingOutput??""),h({type:"loading"});else if(at.status==="awaiting_input"){if(!at.currentQuestion)throw new Error("Planning session is awaiting input but has no current question.");const vt=JSON.parse(at.currentQuestion);if(ja(l),h({type:"question",session:{sessionId:at.id,currentQuestion:vt,summary:null}}),at.thinkingOutput){const Ht=at.thinkingOutput.trim();Ht&&b(Ut=>Ut[Ut.length-1]?.thinkingOutput===Ht?Ut:[...Ut,{thinkingOutput:Ht}])}k.current?.isConnected()||De(at.id)}else if(at.status==="complete"){if(!at.result)throw new Error("Planning session is complete but has no result.");const vt=JSON.parse(at.result);ja(l),h({type:"summary",session:{sessionId:at.id,currentQuestion:null,summary:vt},summary:vt}),j(vt)}else at.status==="error"&&h({type:"error",session:{sessionId:at.id,currentQuestion:null,summary:null},errorMessage:at.error||"Retry failed. Please try again."});E(!1);return}catch(at){yt=at}k.current?.close(),k.current=null,h({type:"error",session:ue,errorMessage:_e(yt)||"Retry failed. Please try again."}),E(!1)}finally{F(!1)}},[De,l,le,m]),Nn=i.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const ue=m.session.sessionId,ut=await Rk(ue,y??void 0,l);s(ut),$e(null),Le(yt=>yt.filter(dt=>dt.id!==ue)),ee({sessionId:ue,status:"complete",timestamp:Date.now()}),Rt()}catch(ue){p(_e(ue)||"Failed to create task"),h({type:"summary",session:m.session,summary:m.summary})}}},[ee,y,m,l,s,Rt]),dn=i.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const ue=await Tk(m.session.sessionId,y??void 0,l);pe(ue.sessionId),h({type:"breakdown",sessionId:ue.sessionId,subtasks:ue.subtasks,dirty:!1})}catch(ue){p(_e(ue)||"Failed to start breakdown"),h({type:"summary",session:m.session,summary:m.summary})}}},[y,m,l]),xn=i.useCallback(async()=>{if(m.type==="breakdown"){p(null),h({type:"creating"});try{const ue=m.sessionId,ut=await Ik(ue,m.subtasks,l);a(ut.tasks),Le(yt=>yt.filter(dt=>dt.id!==ue)),ee({sessionId:ue,status:"complete",timestamp:Date.now()}),u(""),h({type:"initial"}),p(null),x([]),b([]),j(null),S(""),xe(void 0),qe(void 0),Qe("medium"),Oe(""),I.current=null,pe(null),$e(null),n()}catch(ue){p(_e(ue)||"Failed to create tasks"),h({type:"breakdown",sessionId:m.sessionId,subtasks:m.subtasks,dirty:m.dirty})}}},[ee,m,a,n,l]),rn=i.useCallback(()=>{if(m.type==="question"&&g.length>0){const ue=g.slice(0,-1);x(ue),h({type:"question",session:m.session})}},[m,g]),On=()=>m.type==="question"?Math.min(g.length+1,3):3,fe=K?te.get(K):null,ct=fe&&fe.tabId!==le,hn=!!(ct&&!fe.stale),zn=B&&(!ct||fe.stale);return e?t.jsx("div",{className:"modal-overlay open",onMouseDown:ue=>{Ct.current=ue.target===ue.currentTarget},onClick:ue=>{ue.target===ue.currentTarget&&Ct.current&&Rt(),Ct.current=!1},role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",ref:z,style:Xt,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[Ue&&t.jsx("button",{className:"modal-back planning-mobile-back",onClick:Ne,"aria-label":"Back to sessions",title:"Back to sessions",children:t.jsx(bl,{size:18})}),t.jsx(oi,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Planning Mode"})]}),t.jsx("div",{className:"modal-header-actions",children:t.jsx("button",{className:"modal-close",onClick:Rt,"aria-label":"Close",children:t.jsx(Jt,{size:20})})})]}),t.jsxs("div",{className:`planning-modal-body planning-modal-body--split ${Ue?"planning-modal-body--show-detail":"planning-modal-body--show-list"}`,children:[t.jsx(JR,{sessions:he,loading:st,selectedSessionId:lt,pendingDeleteId:wt,showArchived:xt,onToggleShowArchived:()=>Pt(ue=>!ue),onArchive:ue=>void tn(ue),onSelectSession:Ie,onNewSession:de,onRequestDelete:Re,onConfirmDelete:ue=>void ft(ue),onCancelDelete:()=>Re(null)}),t.jsxs("div",{className:"planning-detail",children:[f&&t.jsx("div",{className:"form-error planning-error",children:f}),M&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),hn&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),m.type==="initial"&&t.jsxs("div",{className:"planning-initial",children:[t.jsxs("div",{className:"planning-view-scroll",children:[t.jsxs("div",{className:"planning-intro",children:[t.jsx(ms,{size:32,className:"icon-triage-lg"}),t.jsx("h4",{children:"Transform your idea into a detailed task"}),t.jsx("p",{className:"text-muted",children:"Describe what you want to build in plain language. The AI will ask clarifying questions and help you structure a well-defined task."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"initial-plan",children:"What do you want to build?"}),t.jsx("textarea",{ref:Z,id:"initial-plan",rows:4,className:"planning-textarea",placeholder:"e.g., Build a user authentication system with login, signup, and password reset...",value:d,onChange:ue=>{const ut=ue.target.value;u(ut),!($.current||ut.trim().length===0)&&(w.current&&clearTimeout(w.current),w.current=setTimeout(()=>{if($.current)return;const yt=ut.trim();if(!yt)return;Ek(yt,l,Ae&&Se?{planningModelProvider:Ae,planningModelId:Se}:void 0).then(at=>{$.current=at.sessionId,Le(vt=>vt.some(Ut=>Ut.id===at.sessionId)?vt:[{id:at.sessionId,type:"planning",status:"draft",title:at.title,preview:yt.length>80?`${yt.slice(0,79).trimEnd()}…`:yt,projectId:l??null,lockedByTab:null,updatedAt:new Date().toISOString(),archived:!1},...vt].sort((Ut,An)=>Date.parse(An.updatedAt)-Date.parse(Ut.updatedAt))),$e(at.sessionId)}).catch(()=>{})},300))},onKeyDown:ue=>{ue.key==="Enter"&&!ue.shiftKey&&d.trim()&&(ue.preventDefault(),oe())},onBlur:()=>{const ue=$.current;ue&&d.trim()&&$t(ue,d)}})]}),t.jsxs("div",{className:"planning-examples",children:[t.jsx("span",{className:"planning-examples-label",children:"Try an example:"}),t.jsx("div",{className:"planning-example-chips",children:UR.map((ue,ut)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>u(ue),children:ue.length>40?ue.slice(0,40)+"...":ue},ut))})]}),t.jsx(Js,{summary:"Advanced planning settings",className:"planning-advanced-disclosure",children:t.jsxs("div",{className:"planning-advanced-content",children:[t.jsxs("div",{className:"planning-advanced-section planning-model-select-group",children:[t.jsxs("label",{htmlFor:"planning-modal-model",className:"form-label",children:["Planning Model",je&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx("p",{className:"planning-advanced-blurb",children:"Selects which model runs the planning interview and writes the final draft."}),t.jsx(hs,{id:"planning-modal-model",label:"Planning Model",value:Ft,onChange:ue=>{const{provider:ut,modelId:yt}=HR(ue);xe(ut),qe(yt)},models:ae,disabled:je,favoriteProviders:be,onToggleFavorite:cn,favoriteModels:tt,onToggleModelFavorite:we}),Fe&&t.jsxs("div",{className:"form-hint form-hint-error",children:[Fe," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{en()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${Ae&&Se?"model-badge-custom":"model-badge-default"}`,children:Zt(Ae,Se)})})]}),t.jsxs("div",{className:"planning-advanced-section planning-depth-selector",children:[t.jsx("p",{className:"planning-advanced-blurb",children:"Plan size sets default interview depth. Questions lets you override with an exact count."}),t.jsxs("div",{className:"planning-depth-controls-row",children:[t.jsx("div",{className:"planning-depth-chip-group",role:"group","aria-label":"Planning depth",children:[{value:"small",label:"Small"},{value:"medium",label:"Medium"},{value:"large",label:"Large"}].map(ue=>t.jsx("button",{type:"button",className:`planning-depth-chip btn ${We===ue.value?"btn-primary planning-depth-chip-active":""}`,onClick:()=>Qe(ue.value),"aria-pressed":We===ue.value,children:ue.label},ue.value))}),t.jsxs("label",{className:"planning-depth-question-count",htmlFor:"planning-depth-questions",children:[t.jsx("span",{children:"Questions"}),t.jsx("input",{id:"planning-depth-questions",className:"input planning-depth-question-input",type:"number",min:1,max:20,value:ve,onChange:ue=>Oe(ue.target.value),placeholder:"Auto"})]})]})]})]})})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>oe(),disabled:!d.trim(),children:[t.jsx(oi,{size:16,className:"icon-mr-8"}),"Start Planning"]})})]}),m.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(gt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:N?"AI is thinking...":"Generating next question..."}),R&&t.jsxs("div",{className:"planning-elapsed",children:["Thinking… (",O,"s)"]}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>T(!_),type:"button",children:_?"Hide thinking":"Show thinking"}),t.jsx("div",{className:"planning-loading-actions",children:t.jsxs("button",{className:"btn planning-stop-btn",type:"button",onClick:()=>void En(),children:[t.jsx(xx,{size:14}),t.jsx("span",{className:"icon-ml-6",children:"Stop"})]})}),_&&N&&t.jsx("div",{className:"planning-thinking-output",ref:Ot,children:t.jsx("pre",{children:N})})]})]}),m.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[v.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Qs,{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 bn(),disabled:L,children:[L?t.jsx(gt,{size:14,className:"spin"}):t.jsx(ns,{size:14}),t.jsx("span",{className:"icon-ml-6",children:L?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Rt,disabled:L,children:"Dismiss"})]})]})]})}),m.type==="creating"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(gt,{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(VR,{question:m.session.currentQuestion,progress:On(),historyEntries:v,onSubmit:Dt,onBack:g.length>0?rn:void 0})}),m.type==="summary"&&y&&t.jsx(WR,{summary:y,historyEntries:v,onSummaryChange:j,tasks:r,onCreateTask:Nn,onBreakIntoTasks:dn,onRefine:()=>{h({type:"question",session:m.session})},isLoading:!1}),m.type==="breakdown"&&t.jsx(GR,{subtasks:m.subtasks,dirty:m.dirty,isLoading:!1,onUpdateSubtasks:ue=>h({...m,subtasks:ue,dirty:!0}),onCreateTasks:xn,onBack:()=>{const ut={sessionId:m.sessionId,currentQuestion:null,summary:y??null};y&&h({type:"summary",session:ut,summary:y})}})]}),B&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(jl,{size:16}),t.jsx("span",{children:zn?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),zn&&t.jsx("button",{type:"button",onClick:()=>{ye()},disabled:U,className:"btn btn-primary session-lock-take-control",children:U?"Taking control...":"Take Control"})]})})]})]})}):null}function VR({question:e,progress:n,historyEntries:s,onSubmit:a,onBack:r}){const[o,l]=i.useState({}),[c,d]=i.useState(""),[u,m]=i.useState(""),h=i.useCallback(()=>{let p;e.type==="text"?p={[e.id]:c}:e.type==="confirm"?p={[e.id]:o[e.id]===!0}:p=o;const g=u.trim();g.length>0&&(p={...p,_comment:g}),a(p)},[u,e,o,c,a]);i.useEffect(()=>{l({}),d(""),m("")},[e.id]);const f=()=>{switch(e.type){case"text":return c.trim().length>0;case"single_select":return o[e.id]!==void 0;case"multi_select":return Array.isArray(o[e.id])&&o[e.id].length>0;case"confirm":return o[e.id]!==void 0;default:return!0}};return t.jsxs("div",{className:"planning-question-form",children:[t.jsxs("div",{className:"planning-view-scroll planning-question-scroll",children:[s.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Qs,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3].map(p=>t.jsx("div",{className:`planning-progress-step ${p<=n?"active":""}`},p))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~3"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:c,onChange:p=>d(p.target.value),onKeyDown:p=>{p.key==="Enter"&&!p.shiftKey&&c.trim()&&(p.preventDefault(),h())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(p=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:p.id,checked:o[e.id]===p.id,onChange:()=>l({[e.id]:p.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:p.label}),p.description&&t.jsx("span",{className:"planning-option-desc",children:p.description})]})]},p.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(p=>{const g=o[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:p.id,checked:g.includes(p.id),onChange:x=>{const v=x.target.checked?[...g,p.id]:g.filter(b=>b!==p.id);l({[e.id]:v})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:p.label}),p.description&&t.jsx("span",{className:"planning-option-desc",children:p.description})]})]},p.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!0?"selected":""}`,onClick:()=>l({[e.id]:!0}),children:[t.jsx(Ln,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!1?"selected":""}`,onClick:()=>l({[e.id]:!1}),children:[t.jsx(Jt,{size:18}),"No"]})]})]}),e.type!=="text"&&t.jsxs("div",{className:"planning-comment-section",children:[t.jsx("label",{className:"planning-comment-label",htmlFor:`planning-comment-${e.id}`,children:"Additional comments (optional)"}),t.jsx("textarea",{id:`planning-comment-${e.id}`,className:"planning-textarea",rows:2,placeholder:"Add any extra context or direction...",value:u,onChange:p=>m(p.target.value)})]})]})]})]}),t.jsxs("div",{className:"planning-actions",children:[r&&t.jsxs("button",{className:"btn",onClick:r,children:[t.jsx(la,{size:16,className:"icon-mr-4"}),"Back"]}),t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:h,disabled:!f(),children:["Continue",t.jsx(qr,{size:16,className:"icon-ml-4"})]})]})]})}function WR({summary:e,historyEntries:n,onSummaryChange:s,tasks:a,onCreateTask:r,onBreakIntoTasks:o,onRefine:l,isLoading:c}){const[d,u]=i.useState(!1),[m,h]=i.useState(e.suggestedDependencies),f=p=>{const g=m.includes(p)?m.filter(x=>x!==p):[...m,p];h(g),s({...e,suggestedDependencies:g})};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(Js,{summary:"Show user Q&A",className:"planning-summary-qa-disclosure",children:[t.jsx(Qs,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Ln,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Planning Complete!"}),t.jsx("p",{className:"text-muted",children:"Review and refine your task before creating it."})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{children:["Description",t.jsx("button",{type:"button",className:"planning-expand-btn",onClick:()=>u(!d),children:d?"Collapse":"Expand"})]}),t.jsx("textarea",{className:`planning-textarea ${d?"expanded":""}`,rows:d?10:4,value:e.description,onChange:p=>s({...e,description:p.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Suggested Size"}),t.jsxs("select",{className:"planning-size-select",value:e.suggestedSize,onChange:p=>s({...e,suggestedSize:p.target.value}),disabled:c,children:[t.jsx("option",{value:"S",children:"S (Small)"}),t.jsx("option",{value:"M",children:"M (Medium)"}),t.jsx("option",{value:"L",children:"L (Large)"})]})]}),a.length>0&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Suggested Dependencies"}),t.jsx("div",{className:"planning-deps-list",children:a.map(p=>t.jsxs("label",{className:`planning-dep-chip ${m.includes(p.id)?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:m.includes(p.id),onChange:()=>f(p.id)}),t.jsx("span",{className:"planning-dep-id",children:p.id}),t.jsx("span",{className:"planning-dep-title",children:p.title||p.description.slice(0,30)})]},p.id))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Key Deliverables"}),t.jsx("ul",{className:"planning-deliverables",children:e.keyDeliverables.map((p,g)=>t.jsx("li",{children:p},g))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:l,disabled:c,children:[t.jsx(la,{size:16,className:"icon-mr-4"}),"Refine Further"]}),t.jsxs("div",{className:"planning-summary-actions-right",children:[t.jsx("button",{className:"btn",onClick:r,disabled:c,children:c?t.jsxs(t.Fragment,{children:[t.jsx(gt,{size:16,className:"spin icon-mr-8"}),"Creating..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Ln,{size:16,className:"icon-mr-8"}),"Create Single Task"]})}),t.jsx("button",{className:"btn btn-primary",onClick:o,disabled:c,title:"Break the plan into multiple tasks with dependencies",children:c?t.jsxs(t.Fragment,{children:[t.jsx(gt,{size:16,className:"spin icon-mr-8"}),"Breaking down..."]}):t.jsxs(t.Fragment,{children:[t.jsx(kl,{size:16,className:"icon-mr-8"}),"Break into Tasks"]})})]})]})]})}function Kh(e){const n=new Map(e.map(o=>[o.id,o.dependsOn])),s=new Set,a=new Set,r=o=>{if(s.has(o))return!0;if(a.has(o))return!1;s.add(o);for(const l of n.get(o)??[])if(n.has(l)&&r(l))return!0;return s.delete(o),a.add(o),!1};return e.some(o=>r(o.id))}function KR(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function GR({subtasks:e,dirty:n,isLoading:s,onUpdateSubtasks:a,onCreateTasks:r,onBack:o}){const[l,c]=i.useState(null),[d,u]=i.useState(null),[m,h]=i.useState(null),f=i.useRef([]),p=i.useMemo(()=>e.length===0||e.some(S=>!S.title.trim())?!0:Kh(e),[e]),g=i.useCallback((S,_)=>{a(e.map(T=>T.id===S?{...T,..._}:T))},[e,a]),x=i.useCallback(()=>{a([...e,KR(e.length+1)])},[e,a]),v=i.useCallback(S=>{a(e.filter(_=>_.id!==S).map(_=>({..._,dependsOn:_.dependsOn.filter(T=>T!==S)})))},[e,a]),b=i.useCallback((S,_)=>{if(_<0||_>=e.length)return;const T=[...e],[M]=T.splice(S,1);T.splice(_,0,M),a(T)},[e,a]),y=i.useCallback(S=>_=>{c(S),_.dataTransfer.setData("text/plain",S),_.dataTransfer.effectAllowed="move"},[]),j=i.useCallback(()=>{c(null),u(null),h(null)},[]),C=i.useCallback(S=>_=>{if(_.preventDefault(),S===l)return;const T=_.currentTarget.getBoundingClientRect(),M=T.top+T.height/2,E=_.clientY<M?"before":"after";u(S),h(E)},[l]),A=i.useCallback(S=>_=>{_.preventDefault();const T=_.dataTransfer.getData("text/plain");if(!T||T===S){j();return}const M=e.findIndex(P=>P.id===T),E=e.findIndex(P=>P.id===S);if(M===-1||E===-1){j();return}const L=[...e],[F]=L.splice(M,1);let R=E;m==="after"&&M<E&&R--,m==="after"&&R++,L.splice(R,0,F),a(L),j()},[e,m,a,j]),N=i.useCallback(S=>{const _=S.currentTarget.getBoundingClientRect(),T=S.clientX,M=S.clientY;(T<_.left||T>_.right||M<_.top||M>_.bottom)&&(u(null),h(null))},[]);return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(kl,{size:24,className:"icon-triage"}),t.jsx("h4",{children:"Break into Tasks"}),t.jsx("p",{className:"text-muted",children:"Review and edit the subtasks generated from your plan. Adjust titles, descriptions, sizes, and dependencies before creating."})]}),t.jsxs("div",{className:"planning-summary-form",children:[e.map((S,_)=>{const T=l===S.id,M=d===S.id,E=["task-detail-section","subtask-item",T?"subtask-item-dragging":"",M?"subtask-item-drop-target":"",M&&m==="before"?"subtask-item-drop-before":"",M&&m==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:E,"data-testid":`subtask-item-${_}`,draggable:!s,onDragStart:y(S.id),onDragEnd:j,onDragOver:C(S.id),onDrop:A(S.id),onDragLeave:N,children:[t.jsxs("div",{className:"detail-title-row subtask-item-header subtask-item-header--between",children:[t.jsxs("div",{className:"subtask-drag-handle",title:"Drag to reorder",children:[t.jsx(wl,{size:16}),t.jsx("strong",{children:S.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>b(_,_-1),disabled:s||_===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(Zi,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>b(_,_+1),disabled:s||_===e.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(Hr,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>v(S.id),disabled:s,children:[t.jsx(Cn,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:L=>{f.current[_]=L},value:S.title,onChange:L=>g(S.id,{title:L.target.value}),onKeyDown:L=>{L.key==="Enter"&&(L.preventDefault(),_<e.length-1&&f.current[_+1]?.focus())},disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:S.description,onChange:L=>g(S.id,{description:L.target.value}),disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Size"}),t.jsxs("select",{className:"planning-size-select",value:S.suggestedSize,onChange:L=>g(S.id,{suggestedSize:L.target.value}),disabled:s,children:[t.jsx("option",{value:"S",children:"S"}),t.jsx("option",{value:"M",children:"M"}),t.jsx("option",{value:"L",children:"L"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"planning-deps-list",children:[e.slice(0,_).filter(L=>L.id!==S.id).map(L=>{const F=S.dependsOn.includes(L.id);return t.jsxs("label",{className:`planning-dep-chip ${F?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:F,onChange:()=>{const R=F?S.dependsOn.filter(P=>P!==L.id):[...S.dependsOn,L.id];g(S.id,{dependsOn:R})},disabled:s}),t.jsx("span",{className:"planning-dep-id",children:L.id}),t.jsx("span",{className:"planning-dep-title",children:L.title||"Untitled"})]},L.id)}),_===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),_>0&&e.slice(0,_).filter(L=>L.id!==S.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},S.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:x,disabled:s,children:[t.jsx(Sn,{size:16,className:"icon-mr-6"})," Add subtask"]}),Kh(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(la,{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(gt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]})}function JR({sessions:e,loading:n,selectedSessionId:s,pendingDeleteId:a,showArchived:r,onToggleShowArchived:o,onArchive:l,onSelectSession:c,onNewSession:d,onRequestDelete:u,onConfirmDelete:m,onCancelDelete:h}){return t.jsxs("aside",{className:"planning-sidebar","aria-label":"Planning sessions",children:[t.jsx("div",{className:"planning-sidebar-header",children:t.jsxs("button",{className:`planning-sidebar-new ${s===null?"active":""}`,onClick:d,type:"button",children:[t.jsx(Tv,{size:16}),t.jsx("span",{children:"New session"})]})}),t.jsxs("div",{className:"planning-sidebar-list",children:[e.length===0&&!n&&t.jsx("div",{className:"planning-sidebar-empty text-muted",children:"No saved sessions yet. Start one on the right to see it here."}),e.map(f=>{const p=f.id===s,g=a===f.id,x=f.archived===!0,v=f.status==="complete"||f.status==="error";return t.jsxs("div",{className:`planning-sidebar-item ${p?"selected":""} ${g?"pending-delete":""} ${x?"archived":""}`,children:[t.jsxs("button",{type:"button",className:"planning-sidebar-item-button",onClick:()=>c(f.id),children:[t.jsx(YR,{status:f.status}),t.jsxs("span",{className:"planning-sidebar-item-body",children:[t.jsx("span",{className:"planning-sidebar-item-title",children:f.status==="draft"&&(!f.title||f.title==="New planning session")?f.preview??"New planning session":f.title||"Untitled session"}),t.jsxs("span",{className:"planning-sidebar-item-meta",children:[t.jsx(QR,{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:b=>{b.stopPropagation(),l(f.id)},"aria-label":x?"Unarchive session":"Archive session",title:x?"Unarchive session":"Archive session",children:x?t.jsx(Vb,{size:14}):t.jsx(Br,{size:14})}),t.jsx("button",{type:"button",className:"planning-sidebar-item-delete",onClick:b=>{b.stopPropagation(),u(f.id)},"aria-label":"Delete session",title:"Delete session",children:t.jsx(Cn,{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 YR({status:e}){switch(e){case"generating":return t.jsx(gt,{size:14,className:"spin planning-sidebar-status-icon planning-sidebar-status-generating"});case"awaiting_input":return t.jsx(nd,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-awaiting"});case"complete":return t.jsx(Ln,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-complete"});case"error":return t.jsx(Rs,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-error"});default:return t.jsx(_i,{size:14,className:"planning-sidebar-status-icon"})}}function QR({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 a=Math.floor(s/60);if(a<60)return`${a}m ago`;const r=Math.floor(a/60);if(r<24)return`${r}h ago`;const o=Math.floor(r/24);if(o<7)return`${o}d ago`;const l=Math.floor(o/7);return l<4?`${l}w ago`:new Date(e).toLocaleDateString()}function ZR(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function Gh(e){const n=new Map(e.map(o=>[o.id,o.dependsOn])),s=new Set,a=new Set,r=o=>{if(s.has(o))return!0;if(a.has(o))return!1;s.add(o);for(const l of n.get(o)??[])if(n.has(l)&&r(l))return!0;return s.delete(o),a.add(o),!1};return e.some(o=>r(o.id))}function eT({isOpen:e,onClose:n,initialDescription:s,onTasksCreated:a,parentTaskId:r,projectId:o,resumeSessionId:l}){const[c,d]=i.useState({type:"initial"}),[u,m]=i.useState([]),[h,f]=i.useState([]),[p,g]=i.useState(""),[x,v]=i.useState(!0),[b,y]=i.useState(!1),[j,C]=i.useState(!1),[A,N]=i.useState(s),[S,_]=i.useState(null),[T,M]=i.useState(!1),[E,L]=i.useState(null),[F,R]=i.useState(null),[P,O]=i.useState(null),q=i.useRef(null),Z=i.useRef([]),z=i.useRef(!1),k=i.useRef(null),I=c.type==="generating"||c.type==="editing"||c.type==="creating"||c.type==="error"?c.sessionId:null,$=i.useMemo(()=>ma(),[]),{isLockedByOther:w,takeControl:H,isLoading:K}=Ll(e?I:null),{activeTabMap:pe,broadcastUpdate:le,broadcastCompleted:B,broadcastLock:ye,broadcastUnlock:U,broadcastHeartbeat:te}=Ya(),ne=i.useMemo(()=>u.length===0||u.some(ce=>!ce.title.trim())?!0:Gh(u),[u]),ee=c.type==="generating"||c.type==="editing"||c.type==="error",ie=I?pe.get(I):null,{confirm:ge}=qs(),se=ie&&ie.tabId!==$,Ae=!!(se&&!ie.stale),xe=w&&(!se||ie.stale),Se=i.useCallback(()=>{A&&YP(A,o),q.current?.close(),q.current=null,d({type:"initial"}),m([]),f([]),g(""),v(!0),y(!1),C(!1),_(null),M(!1),z.current=!1},[A,o]),qe=i.useCallback(()=>{q.current?.close(),q.current=null,n()},[n]),We=i.useCallback(async()=>{if(!((T||c.type==="editing"||c.type==="creating")&&!await ge({title:"Discard Changes",message:"Close subtask breakdown? Unsaved changes will be lost.",danger:!0}))){if(I)try{await hf(I,o,$)}catch{}Se(),n()}},[T,n,Se,I,$,c.type,o,ge]),Qe=i.useCallback(ce=>{q.current?.close(),q.current=lj(ce,o,{onThinking:Te=>{g(he=>he+Te),le({sessionId:ce,status:"generating",needsInput:!1,owningTabId:$,type:"subtask",title:A.trim()||void 0,projectId:o??null})},onSubtasks:Te=>{y(!1),C(!1),Tc(o),m(Te),d({type:"editing",sessionId:ce}),M(!1),le({sessionId:ce,status:"awaiting_input",needsInput:!0,owningTabId:$,type:"subtask",title:A.trim()||void 0,projectId:o??null})},onError:Te=>{const he=Te||"Session failed while contacting the AI.";y(!1),C(!1),_(null),d({type:"error",sessionId:ce,errorMessage:he}),le({sessionId:ce,status:"error",needsInput:!1,owningTabId:$,type:"subtask",title:A.trim()||void 0,projectId:o??null}),B({sessionId:ce,status:"error"})},onComplete:()=>{B({sessionId:ce,status:"complete"})},onConnectionStateChange:Te=>{y(Te==="reconnecting")}})},[B,le,A,o,$]),ve=i.useCallback(async()=>{if(A.trim()){_(null),f([]),g(""),y(!1);try{const{sessionId:ce}=await aj(A.trim(),o);d({type:"generating",sessionId:ce}),Qe(ce)}catch(ce){_(_e(ce)||"Failed to start subtask breakdown"),d({type:"initial"})}}},[Qe,A,o]);i.useEffect(()=>{if(!e){Se();return}if(e&&s&&!z.current)N(s),z.current=!0,ve();else if(e&&!s&&!z.current){const ce=QP(o);ce&&N(ce)}},[e,s,ve,Se]),i.useEffect(()=>{!e||!l||c.type!=="initial"||(async()=>{try{const ce=await bi(l);if(!ce)return;const Te=Da(ce.conversationHistory);if(f(Te),ce.status==="generating"||ce.status==="awaiting_input")g(ce.thinkingOutput??""),d({type:"generating",sessionId:l}),Qe(l);else if(ce.status==="complete"&&ce.result){Tc(o);const he=JSON.parse(ce.result);m(he),d({type:"editing",sessionId:l})}else ce.status==="error"&&(_(null),d({type:"error",sessionId:l,errorMessage:ce.error??"Session encountered an error"}))}catch(ce){_(_e(ce)||"Failed to resume session")}})()},[Qe,e,l,c.type,o]),i.useEffect(()=>{if(!e){k.current&&(U(k.current,$),k.current=null);return}if(I&&k.current!==I){k.current&&U(k.current,$),ye(I,$),k.current=I;return}!I&&k.current&&(U(k.current,$),k.current=null)},[ye,U,e,I,$]),i.useEffect(()=>{if(!e||!I||k.current!==I)return;te($);const ce=setInterval(()=>{te($)},3e4);return()=>{clearInterval(ce)}},[te,e,I,$]),i.useEffect(()=>()=>{q.current?.close(),k.current&&(U(k.current,$),k.current=null)},[U,$]),i.useEffect(()=>{if(!e)return;const ce=Te=>{Te.key==="Escape"&&(Te.preventDefault(),We())};return document.addEventListener("keydown",ce),()=>document.removeEventListener("keydown",ce)},[e,We]);const Oe=i.useCallback((ce,Te)=>{m(he=>he.map(Le=>Le.id===ce?{...Le,...Te}:Le)),M(!0)},[]),ae=i.useCallback(()=>{m(ce=>[...ce,ZR(ce.length+1)]),M(!0)},[]),re=i.useCallback(ce=>{m(Te=>Te.filter(he=>he.id!==ce).map(he=>({...he,dependsOn:he.dependsOn.filter(Le=>Le!==ce)}))),M(!0)},[]),je=i.useCallback(ce=>Te=>{L(ce),Te.dataTransfer.setData("text/plain",ce),Te.dataTransfer.effectAllowed="move"},[]),Q=i.useCallback(()=>{L(null),R(null),O(null)},[]),Fe=i.useCallback(ce=>Te=>{if(Te.preventDefault(),ce===E)return;const he=Te.currentTarget.getBoundingClientRect(),Le=he.top+he.height/2,st=Te.clientY<Le?"before":"after";R(ce),O(st)},[E]),Je=i.useCallback(ce=>Te=>{Te.preventDefault();const he=Te.dataTransfer.getData("text/plain");if(!he||he===ce){L(null),R(null),O(null);return}m(Le=>{const st=Le.findIndex(Xe=>Xe.id===he),it=Le.findIndex(Xe=>Xe.id===ce);if(st===-1||it===-1)return Le;const lt=[...Le],[$e]=lt.splice(st,1);let Ue=it;return P==="after"&&st<it&&Ue--,P==="after"&&Ue++,lt.splice(Ue,0,$e),lt}),M(!0),L(null),R(null),O(null)},[P]),be=i.useCallback(ce=>{const Te=ce.currentTarget.getBoundingClientRect(),he=ce.clientX,Le=ce.clientY;(he<Te.left||he>Te.right||Le<Te.top||Le>Te.bottom)&&(R(null),O(null))},[]),ze=i.useCallback((ce,Te)=>{Te<0||Te>=u.length||(m(he=>{const Le=[...he],[st]=Le.splice(ce,1);return Le.splice(Te,0,st),Le}),M(!0))},[u.length]),tt=i.useCallback(ce=>{Z.current[ce+1]?.focus()},[]),kt=i.useCallback(async()=>{if(!(!I||ne)){_(null),d({type:"creating",sessionId:I});try{const ce=await cj(I,u,r,o);a(ce.tasks),Se(),n()}catch(ce){_(_e(ce)||"Failed to create tasks"),d({type:"editing",sessionId:I})}}},[ne,n,a,r,o,Se,I,u]),ke=i.useCallback(async()=>{if(c.type!=="error")return;const ce=c.sessionId;_(null),C(!0),g(""),d({type:"generating",sessionId:ce}),Qe(ce);try{await rj(ce,o,$)}catch(Te){let he=Te;if((_e(Te)||"").includes("not in an error state"))try{const st=await bi(ce);if(!st)throw new Error("Failed to refresh subtask session.");if(f(Da(st.conversationHistory)),st.status==="generating"||st.status==="awaiting_input")g(st.thinkingOutput??""),d({type:"generating",sessionId:st.id}),q.current?.isConnected()||Qe(st.id);else if(st.status==="complete"){if(!st.result)throw new Error("Subtask session is complete but has no result.");Tc(o);const it=JSON.parse(st.result);m(it),d({type:"editing",sessionId:st.id}),M(!1)}else st.status==="error"&&d({type:"error",sessionId:st.id,errorMessage:st.error??"Retry failed. Please try again."});y(!1);return}catch(st){he=st}q.current?.close(),q.current=null,d({type:"error",sessionId:ce,errorMessage:_e(he)||"Retry failed. Please try again."}),y(!1)}finally{C(!1)}},[Qe,o,$,c]);return e?t.jsx("div",{className:"modal-overlay open",onClick:ce=>ce.target===ce.currentTarget&&void We(),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(kl,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Subtask Breakdown"})]}),t.jsxs("div",{className:"modal-header-actions",children:[ee&&t.jsx("button",{className:"modal-send-to-background",onClick:qe,title:"Send to background","aria-label":"Send to background",children:t.jsx(Kr,{size:16})}),t.jsx("button",{className:"modal-close",onClick:()=>void We(),"aria-label":"Close",children:t.jsx(Jt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[S&&t.jsx("div",{className:"form-error planning-error",children:S}),b&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Ae&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),c.type==="initial"&&t.jsx("div",{className:"planning-initial",children:t.jsxs("div",{className:"planning-view-scroll",children:[t.jsx("p",{className:"text-muted",children:"Preparing to break this task into subtasks."}),t.jsx("pre",{className:"planning-thinking-output",children:A})]})}),c.type==="generating"&&t.jsxs("div",{className:"planning-loading",children:[h.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Qs,{entries:h,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsx(gt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:"AI is generating subtasks..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>v(!x),type:"button",children:x?"Hide thinking":"Show thinking"}),x&&p&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:p})})]})]}),c.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[h.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Qs,{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 ke(),disabled:j,children:[j?t.jsx(gt,{size:14,className:"spin"}):t.jsx(ns,{size:14}),t.jsx("span",{className:"icon-ml-6",children:j?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:()=>void We(),disabled:j,children:"Cancel"})]})]})]})}),(c.type==="editing"||c.type==="creating")&&t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[h.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Qs,{entries:h}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Ln,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Review your subtasks"}),t.jsx("p",{className:"text-muted",children:"Edit titles, descriptions, sizes, and dependencies before creating all tasks at once."})]}),t.jsxs("div",{className:"planning-summary-form",children:[u.map((ce,Te)=>{const he=E===ce.id,Le=F===ce.id,st=["task-detail-section","subtask-item",he?"subtask-item-dragging":"",Le?"subtask-item-drop-target":"",Le&&P==="before"?"subtask-item-drop-before":"",Le&&P==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:st,"data-testid":`subtask-item-${Te}`,draggable:c.type!=="creating",onDragStart:je(ce.id),onDragEnd:Q,onDragOver:Fe(ce.id),onDrop:Je(ce.id),onDragLeave:be,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(wl,{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:()=>ze(Te,Te-1),disabled:c.type==="creating"||Te===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(Zi,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>ze(Te,Te+1),disabled:c.type==="creating"||Te===u.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(Hr,{})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>re(ce.id),disabled:c.type==="creating",children:[t.jsx(Cn,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:it=>{Z.current[Te]=it},value:ce.title,onChange:it=>Oe(ce.id,{title:it.target.value}),onKeyDown:it=>{it.key==="Enter"&&(it.preventDefault(),tt(Te))},disabled:c.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:8,value:ce.description,onChange:it=>Oe(ce.id,{description:it.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:it=>Oe(ce.id,{suggestedSize:it.target.value}),disabled:c.type==="creating",children:[t.jsx("option",{value:"S",children:"S"}),t.jsx("option",{value:"M",children:"M"}),t.jsx("option",{value:"L",children:"L"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"planning-deps-list",children:[u.slice(0,Te).filter(it=>it.id!==ce.id).map(it=>{const lt=ce.dependsOn.includes(it.id);return t.jsxs("label",{className:`planning-dep-chip ${lt?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:lt,onChange:()=>{const $e=lt?ce.dependsOn.filter(Ue=>Ue!==it.id):[...ce.dependsOn,it.id];Oe(ce.id,{dependsOn:$e})},disabled:c.type==="creating"}),t.jsx("span",{className:"planning-dep-id",children:it.id}),t.jsx("span",{className:"planning-dep-title",children:it.title||"Untitled"})]},it.id)}),Te===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),Te>0&&u.slice(0,Te).filter(it=>it.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:ae,disabled:c.type==="creating",children:[t.jsx(Sn,{size:16,className:"icon-mr-6"})," Add subtask"]}),Gh(u)&&t.jsx("div",{className:"form-error planning-error",children:"Dependencies contain a cycle. Remove circular references before creating tasks."})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsx("button",{className:"btn",onClick:()=>void We(),disabled:c.type==="creating",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:()=>void kt(),disabled:c.type==="creating"||ne,children:c.type==="creating"?t.jsxs(t.Fragment,{children:[t.jsx(gt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]}),w&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(jl,{size:16}),t.jsx("span",{children:xe?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),xe&&t.jsx("button",{type:"button",onClick:()=>{H()},disabled:K,className:"btn btn-primary session-lock-take-control",children:K?"Taking control...":"Take Control"})]})})]})]})}):null}const tT=5,nT=1e3,sT=45e3;function Lo(){return{scrollback:null,connected:null,data:[]}}function iT(e,n){const[s,a]=i.useState("disconnected"),r=i.useRef(0),o=i.useRef(e),l=i.useRef(n),c=o.current!==e||l.current!==n;c&&(o.current=e,l.current=n,r.current++);const d=i.useRef(null),u=i.useRef(0),m=i.useRef(null),h=i.useRef(null),f=i.useRef(!1),p=i.useRef(new Set),g=i.useRef(new Set),x=i.useRef(new Set),v=i.useRef(new Set),b=i.useRef(new Set),y=i.useRef(Lo()),j=i.useCallback(R=>{p.current.add(R);const P=y.current;return P.data.length>0&&(P.data.forEach(O=>R(O)),P.data=[]),()=>p.current.delete(R)},[]),C=i.useCallback(R=>(g.current.add(R),()=>g.current.delete(R)),[]),A=i.useCallback(R=>{x.current.add(R);const P=y.current;return P.connected&&(R(P.connected),P.connected=null),()=>x.current.delete(R)},[]),N=i.useCallback(R=>{v.current.add(R);const P=y.current;return P.scrollback&&(R(P.scrollback),P.scrollback=null),()=>v.current.delete(R)},[]),S=i.useCallback(R=>(b.current.add(R),()=>b.current.delete(R)),[]),_=i.useCallback(R=>{const P=d.current;P?.readyState===WebSocket.OPEN&&P.send(JSON.stringify({type:"input",data:R}))},[]),T=i.useCallback((R,P)=>{const O=d.current;O?.readyState===WebSocket.OPEN&&O.send(JSON.stringify({type:"resize",cols:R,rows:P}))},[]),M=i.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.current=null),d.current&&(d.current.onopen=null,d.current.onmessage=null,d.current.onclose=null,d.current.onerror=null,d.current.close(),d.current=null),y.current=Lo()},[]),E=i.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.current=null),d.current&&(f.current=!0,d.current.close(),d.current=null),y.current=Lo()},[]),L=i.useCallback(()=>{if(!e){a("disconnected");return}if(d.current?.readyState===WebSocket.OPEN)return;d.current&&(f.current=!0,d.current.close()),f.current=!1,a("connecting");const R=r.current;let O=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/terminal/ws?sessionId=${encodeURIComponent(e)}`;n&&(O+=`&projectId=${encodeURIComponent(n)}`);const q=new WebSocket(xi(O));d.current=q,q.onopen=()=>{if(r.current!==R){q.close();return}y.current=Lo(),a("connected"),u.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{r.current===R&&q.readyState===WebSocket.OPEN&&q.send(JSON.stringify({type:"ping"}))},sT)},q.onmessage=Z=>{if(r.current===R)try{const z=JSON.parse(Z.data),k=y.current;switch(z.type){case"data":z.data&&(p.current.size===0&&k.data.push(z.data),p.current.forEach(I=>I(z.data)));break;case"scrollback":z.data&&(k.scrollback=z.data,v.current.forEach(I=>I(z.data)));break;case"connected":z.shell&&z.cwd&&(k.connected={shell:z.shell,cwd:z.cwd},x.current.forEach(I=>I({shell:z.shell,cwd:z.cwd})));break;case"exit":z.exitCode!==void 0&&g.current.forEach(I=>I(z.exitCode));break;case"ping":q.readyState===WebSocket.OPEN&&q.send(JSON.stringify({type:"pong"}));break;case"pong":break}}catch{}},q.onclose=Z=>{if(r.current!==R)return;if(d.current=null,h.current&&(clearInterval(h.current),h.current=null),f.current){a("disconnected");return}if(Z.code===4e3||Z.code===4004){a("disconnected"),Z.code===4004&&b.current.forEach(I=>I());return}if(u.current++,u.current>tT){a("disconnected");return}const z=nT*Math.pow(2,u.current-1);a("reconnecting");const k=r.current;m.current=setTimeout(()=>{r.current===k&&(f.current||L())},Math.min(z,16e3))},q.onerror=()=>{}},[e,n]),F=i.useCallback(()=>{u.current=0,E(),L()},[E,L]);return i.useEffect(()=>(c&&(M(),u.current=0,a("disconnected")),e?L():a("disconnected"),E),[e,n,c,L,E,M]),{connectionStatus:s,sendInput:_,resize:T,onData:j,onExit:C,onConnect:A,onScrollback:N,reconnect:F,onSessionInvalid:S}}const ib="kb-terminal-tabs",aT=15e3,rT=15e3;function Jh(){return`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function Yh(e){if(typeof window>"u")return[];try{const n=Zn(ib,e);if(n)return JSON.parse(n)}catch{}return[]}function Fc(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return n.includes("Failed to parse URL")||n.includes("Invalid URL")}function Qh(e,n,s){let a;const r=new Promise((o,l)=>{a=setTimeout(()=>l(new Error(`${s} timed out after ${n}ms`)),n)});return Promise.race([e,r]).finally(()=>clearTimeout(a))}function oT(e){const[n,s]=i.useState(()=>Yh(e)),[a,r]=i.useState(!1),[o,l]=i.useState(!0),[c,d]=i.useState(null),[u,m]=i.useState(0),h=i.useRef(0);i.useEffect(()=>{h.current+=1,s(Yh(e)),r(!1),l(!0),d(null)},[e]),i.useEffect(()=>{try{us(ib,JSON.stringify(n),e)}catch{}},[e,n]),i.useEffect(()=>{let A=!1;const N=h.current;return(async()=>{if(!A)try{const _=await Qh(ek(e),aT,"listTerminalSessions");if(A||N!==h.current)return;const T=new Set(_.map(M=>M.id));l(!0),s(M=>{if(A||N!==h.current)return M;const L=M.map(P=>({...P,_verified:T.has(P.sessionId)})).filter(P=>P._verified);if(L.length===0)return[];const F=L.map(({_verified:P,...O})=>O);return F.find(P=>P.isActive)?F:F.map((P,O)=>({...P,isActive:O===0}))}),r(!0)}catch(_){if(A||N!==h.current)return;const T=Fc(_);T||console.warn("Failed to validate terminal sessions with server:",_),l(!T),r(!0)}})(),()=>{A=!0}},[e]),i.useEffect(()=>{if(n.length===0&&a&&o){const A=h.current,N=setTimeout(()=>{Qh(ho(void 0,void 0,void 0,e),rT,"createTerminalSession").then(S=>{if(A!==h.current)return;const _={id:Jh(),sessionId:S.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};s(T=>T.length>0?T:[...T.map(E=>({...E,isActive:!1})),_]),d(null)}).catch(S=>{if(A!==h.current)return;Fc(S)||console.error(S);const _=S instanceof Error?S.message:typeof S=="string"?S:"Failed to create terminal session";d(_)})},0);return()=>clearTimeout(N)}},[a,o,n.length,u]);const f=i.useCallback(async()=>{const A=await ho(void 0,void 0,void 0,e),N={id:Jh(),sessionId:A.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};return s(S=>[...S.map(T=>({...T,isActive:!1})),N]),N},[n.length]),p=i.useCallback(async()=>f(),[f]),g=i.useCallback(A=>{s(N=>{const S=N.find(E=>E.id===A);if(!S)return N;Tu(S.sessionId,e).catch(E=>{console.warn(`Failed to kill terminal session ${S.sessionId}:`,E)});const _=N.findIndex(E=>E.id===A),T=S.isActive,M=N.filter(E=>E.id!==A);if(M.length===0)return[];if(T){const E=Math.min(_,M.length-1);return M.map((L,F)=>({...L,isActive:F===E}))}return M})},[]),x=i.useCallback(A=>{s(N=>{let S=!1;const _=N.map(T=>T.id===A?(S=!0,{...T,isActive:!0}):{...T,isActive:!1});return S?_:N})},[]),v=i.useCallback((A,N)=>{s(S=>S.map(_=>_.id===A?{..._,title:N}:_))},[]),b=i.useCallback(async()=>{s(S=>{const _=S.find(T=>T.isActive);return _&&Tu(_.sessionId,e).catch(T=>{console.warn(`Failed to kill old session ${_.sessionId}:`,T)}),S});const A=n.find(S=>S.isActive);if(!A)return;const N=await ho(void 0,void 0,void 0,e);s(S=>S.map(_=>_.id===A.id?{..._,sessionId:N.sessionId}:_))},[n]),y=i.useCallback(async()=>{const A=n.find(N=>N.isActive);if(A)try{const N=await ho(void 0,void 0,void 0,e);s(S=>S.map(_=>_.id===A.id?{..._,sessionId:N.sessionId}:_)),d(null)}catch(N){Fc(N)||console.error(N);const S=N instanceof Error?N.message:typeof N=="string"?N:"Failed to create terminal session";d(S)}},[n]),j=n.find(A=>A.isActive)??null,C=i.useCallback(()=>{d(null),h.current+=1,m(A=>A+1)},[]);return{tabs:n,activeTab:j,isReady:a,bootstrapError:c,createTab:p,closeTab:g,setActiveTab:x,updateTabTitle:v,restartActiveTab:b,retryBootstrap:C,replaceActiveTabSession:y}}const lT=1e4,cT=[500,1500,3e3],ab="kb-terminal-font-size",jr=14,dT=8,uT=32,mT='"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 hT(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 pT(e){return`\x1B${e}`}const fT=[{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 Nr(e){return Math.min(uT,Math.max(dT,e))}function gT(){if(typeof window>"u")return jr;try{const e=window.localStorage.getItem(ab);if(!e)return jr;const n=Number.parseInt(e,10);return Number.isFinite(n)?Nr(n):jr}catch{return jr}}function bT(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 xT(e){return new Promise(n=>setTimeout(n,e))}async function vT(e,n=cT){let s;for(let a=0;a<=n.length;a+=1)try{return await e()}catch(r){if(!bT(r))throw r;s===void 0&&(s=r);const o=n[a];if(o===void 0)throw s??r;const l=r instanceof Error?r.message:String(r);console.warn(`[TerminalModal] Dynamic xterm import failed (attempt ${a+1}/${n.length+1}). Retrying in ${o}ms...`,l),await xT(o)}throw s??new Error("Dynamic import failed")}function Xh(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}function yT(){if(typeof window>"u"||!window.visualViewport)return 0;const e=window.visualViewport,n=Math.max(0,window.innerHeight-e.offsetTop-e.height);if(n>0)return n;const a=wT()-e.offsetTop-e.height;return a>=30&&a>80?a:0}let Uc=null;function wT(){return Uc===null&&(Uc=window.innerHeight),Uc}function kT({isOpen:e,onClose:n,initialCommand:s,projectId:a}){const[r,o]=i.useState(null),[l,c]=i.useState(null),[d,u]=i.useState(!1),[m,h]=i.useState(null),[f,p]=i.useState(0),[g,x]=i.useState(0),[v,b]=i.useState(null),[y,j]=i.useState(()=>gT()),[C,A]=i.useState(!1),[N,S]=i.useState(null),_=i.useRef(null),T=i.useRef(null),M=i.useRef(!1);wi(T,e,"fusion:terminal-modal-size");const E=i.useRef(null),L=i.useRef(null),F=i.useRef(!1),R=i.useRef(!1),P=i.useRef(null),O=i.useRef(()=>{}),q=i.useRef(null),Z=i.useRef(0),z=i.useRef(y),k=i.useRef(null),I=i.useRef(a);Z.current=g,z.current=y;const $=i.useCallback(he=>{if(he&&R.current!==he)return;const Le=L.current,st=E.current,it=P.current;if(!(!Le||!st)&&!(he&&R.current!==he))try{Le.fit(),it&&it(st.cols,st.rows)}catch{}},[]);i.useEffect(()=>{e&&p(he=>he+1)},[e]),i.useEffect(()=>{if(!e||!Xh())return;const he=window.visualViewport;if(!he)return;const Le=()=>{const st=yT();x(st),b(he.height),st>0&&T.current?.scrollIntoView&&T.current.scrollIntoView({block:"end",behavior:"smooth"}),k.current!==null&&(cancelAnimationFrame(k.current),k.current=null);const it=typeof R.current=="string"?R.current:void 0;k.current=requestAnimationFrame(()=>{k.current=null,$(it)})};return Le(),he.addEventListener("resize",Le),he.addEventListener("scroll",Le),()=>{he.removeEventListener("resize",Le),he.removeEventListener("scroll",Le),k.current!==null&&(cancelAnimationFrame(k.current),k.current=null),x(0),b(null)}},[$,e]),i.useEffect(()=>{if(!e)return;const he=T.current;if(!he||typeof ResizeObserver>"u")return;let Le=null;const st=new ResizeObserver(()=>{Le!==null&&cancelAnimationFrame(Le),Le=requestAnimationFrame(()=>{Le=null;const it=typeof R.current=="string"?R.current:void 0;$(it)})});return st.observe(he),()=>{st.disconnect(),Le!==null&&cancelAnimationFrame(Le)}},[$,e]);const{tabs:w,activeTab:H,isReady:K,bootstrapError:pe,createTab:le,closeTab:B,setActiveTab:ye,updateTabTitle:U,restartActiveTab:te,retryBootstrap:ne,replaceActiveTabSession:ee}=oT(a),{connectionStatus:ie,sendInput:ge,resize:se,onData:Ae,onConnect:xe,onExit:Se,onScrollback:qe,reconnect:We,onSessionInvalid:Qe}=iT(H?.sessionId??null,a);P.current=se,O.current=ge,i.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(ab,String(y))}catch{}},[y]);const ve=i.useCallback(()=>{const he=E.current;if(he)try{L.current?.fit(),se(he.cols,he.rows)}catch{}},[se]);i.useEffect(()=>{if(!e||!K)return;const he=H?.sessionId;if(!he)return;const Le=I.current!==a;if(Le&&(I.current=a),R.current===he&&E.current&&!Le)return;E.current&&(R.current!==he||Le)&&(E.current.dispose(),E.current=null,L.current=null,R.current=!1,q.current&&(window.removeEventListener("resize",q.current),q.current=null),u(!1),h(null));let st=!0,it;return(async()=>{const $e=vT(()=>Promise.all([Mn(()=>import("./vendor-xterm-DzcZoU0P.js").then(Re=>Re.x),__vite__mapDeps([4,1,5])),Mn(()=>import("./addon-fit-C7jRorKK.js").then(Re=>Re.a),__vite__mapDeps([6,1])),Mn(()=>import("./addon-web-links-CkJwd4cQ.js").then(Re=>Re.a),__vite__mapDeps([7,1]))])),Ue=new Promise((Re,xt)=>{it=setTimeout(()=>{xt(new Error("xterm initialization timed out"))},lT)});let Xe,wt;try{const[{Terminal:Re},{FitAddon:xt},{WebLinksAddon:Pt}]=await Promise.race([$e,Ue]);if(!st||!_.current||E.current)return;Xe=new Re({cursorBlink:!0,cursorStyle:"block",fontSize:z.current,fontFamily:mT,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}),wt=new xt,Xe.loadAddon(wt);const Ct=new Pt;if(Xe.loadAddon(Ct),!Xh())try{const{WebglAddon:Nt}=await Mn(async()=>{const{WebglAddon:Yt}=await import("./addon-webgl-BjvOw43o.js").then(Bt=>Bt.a);return{WebglAddon:Yt}},__vite__mapDeps([8,1])),jt=new Nt;jt.onContextLoss(()=>{jt.dispose()}),Xe.loadAddon(jt)}catch{}Xe.open(_.current),it&&clearTimeout(it);const Ot=_.current?.querySelector(".xterm-helper-textarea");if(Ot&&Ot.focus(),_.current)try{_.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}setTimeout(()=>{wt.fit();const Nt=_.current?.querySelector(".xterm-helper-textarea");Nt&&Nt.focus()},50),E.current=Xe,L.current=wt,R.current=he,Z.current>0&&(k.current!==null&&(cancelAnimationFrame(k.current),k.current=null),k.current=requestAnimationFrame(()=>{k.current=null,$(he)})),Xe.onData(Nt=>{R.current===he&&O.current(Nt)});const zt=()=>{if(R.current===he&&L.current&&E.current)try{L.current.fit();const{cols:Nt,rows:jt}=E.current;P.current?.(Nt,jt)}catch{}};window.addEventListener("resize",zt),q.current&&window.removeEventListener("resize",q.current),q.current=zt,u(!0),h(null)}catch(Re){if(it&&clearTimeout(it),!st)return;const xt=Re instanceof Error?Re.message:"xterm initialization failed";h(xt)}})(),()=>{st=!1,it&&clearTimeout(it)}},[$,e,K,H?.sessionId,a]),i.useEffect(()=>{e||(E.current&&(E.current.dispose(),E.current=null),L.current=null,R.current=!1,q.current&&(window.removeEventListener("resize",q.current),q.current=null),u(!1),h(null),F.current=!1,o(null),c(null),A(!1),S(null))},[e]),i.useEffect(()=>{if(!d||!E.current||!H)return;const he=H.sessionId,Le=Ue=>{R.current===he&&E.current?.write(Ue)},st=Ae(Ue=>{Le(Ue)}),it=qe(Ue=>{Le(Ue)}),lt=xe(Ue=>{U(H.id,Jd(Ue.shell)||Ue.shell)}),$e=Se(Ue=>{R.current===he&&(c(Ue),E.current?.write(`\r
679
+ \x1B[33m[Process exited with code ${Ue}]\x1B[0m\r
680
+ `))});return()=>{st(),it(),lt(),$e()}},[d,H?.sessionId,H?.id,H,ie,Ae,qe,xe,Se,U]),i.useEffect(()=>{ie==="connected"&&s&&F.current!==s&&H&&(F.current=s,setTimeout(()=>{ge(s+`
681
+ `)},500))},[ie,s,ge,H,f]),i.useEffect(()=>{if(!d||!E.current)return;E.current.options.fontSize=y,k.current!==null&&(cancelAnimationFrame(k.current),k.current=null);const he=requestAnimationFrame(()=>{k.current=null,ve()});return k.current=he,()=>{k.current===he&&(cancelAnimationFrame(he),k.current=null)}},[y,d,ve]),i.useEffect(()=>{if(!e)return;const he=Le=>{if(!(!Le.ctrlKey&&!Le.metaKey)){if(Le.code==="Equal"||Le.code==="NumpadAdd"){Le.preventDefault(),j(st=>Nr(st+1));return}if(Le.code==="Minus"||Le.code==="NumpadSubtract"){Le.preventDefault(),j(st=>Nr(st-1));return}if(Le.code==="Digit0"||Le.code==="Numpad0"){Le.preventDefault(),j(jr);return}}};return window.addEventListener("keydown",he),()=>window.removeEventListener("keydown",he)},[e,ve]),i.useEffect(()=>{if(!e)return;const he=Le=>{Le.key==="Escape"&&n()};return document.addEventListener("keydown",he),()=>document.removeEventListener("keydown",he)},[e,n]),i.useEffect(()=>{ie==="connected"&&E.current&&setTimeout(()=>{if(!E.current||!_.current)return;const he=_.current.querySelector(".xterm-helper-textarea");he&&he.focus();try{_.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[ie]);const Oe=i.useCallback(()=>{if(!_.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;E.current?.focus();const Le=_.current.querySelector(".xterm-helper-textarea");if(!Le)return;Le.autocapitalize="off",Le.autocomplete="off",Le.autocorrect="off",Le.spellcheck=!1,Le.setAttribute("inputmode","text");try{Le.focus({preventScroll:!0})}catch{Le.focus()}const st=Le.value.length;Le.setSelectionRange(st,st)},[]);i.useEffect(()=>Qe(()=>{E.current?.clear(),c(null),F.current=!1,E.current&&(E.current.dispose(),E.current=null),L.current=null,R.current=!1,q.current&&(window.removeEventListener("resize",q.current),q.current=null),u(!1),h(null),ee().catch(Le=>{console.error("Failed to replace invalid terminal session:",Le)})}),[Qe,ee]);const ae=i.useCallback(he=>{he.target===he.currentTarget&&(M.current=!0)},[]),re=i.useCallback(he=>{M.current&&he.target===he.currentTarget&&n(),M.current=!1},[n]),je=i.useCallback(()=>{E.current?.clear()},[]),Q=i.useCallback(async()=>{E.current?.clear(),c(null),F.current=!1;try{await te()}catch(he){o(_e(he)||"Failed to restart terminal session")}},[te]),Fe=i.useCallback(()=>{E.current&&(E.current.dispose(),E.current=null),L.current=null,R.current=!1,q.current&&(window.removeEventListener("resize",q.current),q.current=null),h(null),u(!1)},[]),Je=i.useCallback(()=>{window.location.reload()},[]),be=i.useCallback(()=>{j(he=>Nr(he+1))},[]),ze=i.useCallback(()=>{j(he=>Nr(he-1))},[]),tt=i.useCallback(he=>{S(Le=>Le===he?null:he)},[]),kt=i.useCallback(he=>{if(N==="ctrl"){ge(hT(he)),S(null);return}if(N==="alt"){ge(pT(he)),S(null);return}ge(he)},[ge,N]),ke=i.useCallback(he=>{ge(he),S(null)},[ge]);if(!e)return null;const ce=()=>{switch(ie){case"connected":return t.jsx("span",{className:"terminal-status connected",title:"Connected"});case"connecting":case"reconnecting":return t.jsx("span",{className:"terminal-status connecting",title:"Connecting..."});case"disconnected":return t.jsx("span",{className:"terminal-status disconnected",title:"Disconnected"});default:return null}},Te=!K||!H&&!pe;return t.jsx("div",{className:"modal-overlay open",onMouseDown:ae,onMouseUp:re,role:"dialog","aria-modal":"true","data-testid":"terminal-modal-overlay",style:g>0?{"--overlay-padding-top":"0px"}:void 0,children:t.jsxs("div",{ref:T,className:"modal terminal-modal","data-testid":"terminal-modal",style:g>0?{"--keyboard-overlap":`${g}px`,"--vv-height":v?`${v}px`:void 0}:void 0,children:[t.jsxs("div",{className:"terminal-header",children:[t.jsxs("div",{className:"terminal-tabs","data-testid":"terminal-tabs",children:[w.map(he=>t.jsxs("div",{className:`terminal-tab ${he.isActive?"terminal-tab--active":""}`,onClick:()=>ye(he.id),title:he.title,role:"tab","aria-selected":he.isActive,children:[t.jsx("span",{className:"terminal-tab-label",children:he.title}),w.length>1&&t.jsx("button",{className:"terminal-tab-close",onClick:Le=>{Le.stopPropagation(),B(he.id)},title:"Close tab",children:"×"})]},he.id)),t.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:le,title:"New terminal",children:"+"})]}),t.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[t.jsx(Mi,{size:16}),ce()]}),t.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[ie==="disconnected"&&H&&t.jsxs("button",{className:"terminal-reconnect-btn",onClick:We,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[t.jsx(ns,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),l!==null&&t.jsxs("button",{className:"terminal-restart-btn",onClick:Q,title:"New Session","data-testid":"terminal-restart-btn",children:[t.jsx(ns,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:je,"data-testid":"terminal-clear-btn",title:"Clear terminal",children:[t.jsx(Cn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Clear"})]}),t.jsxs("button",{className:"terminal-clear-btn terminal-clear-btn--shortcut",onClick:()=>A(he=>!he),"data-testid":"terminal-shortcut-toggle",title:"Shortcuts","aria-pressed":C,children:[t.jsx(bv,{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(Jt,{size:20})})]})]}),r&&t.jsx("div",{className:"terminal-error","data-testid":"terminal-error",children:r}),t.jsxs("div",{className:"terminal-container","data-testid":"terminal-container",children:[Te&&!pe&&t.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[t.jsx("div",{className:"terminal-spinner"}),t.jsx("span",{children:"Starting terminal..."})]}),pe&&!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: ",pe]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:ne,"data-testid":"terminal-retry-btn",children:[t.jsx(ns,{size:14}),"Retry"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Je,"data-testid":"terminal-bootstrap-refresh-btn",children:[t.jsx(ns,{size:14}),"Refresh page"]})]})]})}),m&&H&&t.jsx("div",{className:"terminal-loading","data-testid":"terminal-xterm-init-error",children:t.jsxs("div",{className:"terminal-error-content",children:[t.jsxs("span",{children:["Terminal UI failed to initialize: ",m]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:Fe,"data-testid":"terminal-reinit-btn",children:[t.jsx(ns,{size:14}),"Reinitialize"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Je,"data-testid":"terminal-xterm-refresh-btn",children:[t.jsx(ns,{size:14}),"Refresh page"]})]})]})}),t.jsx("div",{ref:_,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:Oe,onTouchStart:Oe},H?.sessionId)]}),C&&t.jsxs("div",{className:"terminal-shortcut-panel","data-testid":"terminal-shortcut-panel",children:[t.jsxs("div",{className:"terminal-shortcut-modifier-row",children:[t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${N==="ctrl"?"is-active":""}`,"data-testid":"terminal-modifier-ctrl",onClick:()=>tt("ctrl"),"aria-pressed":N==="ctrl",children:"Ctrl"}),t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${N==="alt"?"is-active":""}`,"data-testid":"terminal-modifier-alt",onClick:()=>tt("alt"),"aria-pressed":N==="alt",children:"Alt"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>ke("\x1B"),children:"ESC"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>ke(" "),children:"Tab"})]}),fT.map(he=>t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>kt(he.key),title:he.description,children:he.label},he.label))]}),t.jsxs("div",{className:"terminal-status-bar","data-testid":"terminal-status-bar",children:[t.jsxs("span",{className:`terminal-connection-status ${ie}`,children:[ie==="connected"&&"Connected",ie==="connecting"&&"Connecting...",ie==="reconnecting"&&"Reconnecting...",ie==="disconnected"&&"Disconnected"]}),l!==null&&t.jsxs("span",{className:"terminal-exit-code","data-testid":"terminal-exit-code",children:["Exit: ",l]}),t.jsxs("span",{className:"terminal-font-size-controls",children:[t.jsx("button",{type:"button",className:"terminal-font-size-btn",onClick:ze,"data-testid":"terminal-font-size-decrease","aria-label":"Decrease terminal font size",children:t.jsx(Lv,{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:be,"data-testid":"terminal-font-size-increase","aria-label":"Increase terminal font size",children:t.jsx(Sn,{size:14})})]}),t.jsx("span",{className:"terminal-shortcuts",children:"Ctrl++/- zoom • ⌨ Shortcuts panel • Esc close"})]})]})})}const mr={name:"",command:""};function Zh(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function jT(e,n=60){return e.length<=n?e:e.slice(0,n-3)+"..."}function NT({isOpen:e,onClose:n,addToast:s,projectId:a,onRunScript:r}){const[o,l]=i.useState({}),[c,d]=i.useState(!0),[u,m]=i.useState(!1),[h,f]=i.useState(null),[p,g]=i.useState(mr),[x,v]=i.useState(!1),[b,y]=i.useState(null),[j,C]=i.useState(null),A=Ri(n),N=i.useCallback(async()=>{try{d(!0);const O=await Lr(a);l(O)}catch(O){s(_e(O)||"Failed to load scripts","error")}finally{d(!1)}},[s,a]);i.useEffect(()=>{e&&N()},[e,N]);const S=i.useCallback(()=>{m(!0),f(null),g(mr),C(null)},[]),_=i.useCallback((O,q)=>{f(O),m(!1),g({name:O,command:q}),C(null)},[]),T=i.useCallback(()=>{f(null),m(!1),g(mr),C(null)},[]),M=i.useCallback(O=>{g(q=>({...q,name:O})),O&&!Zh(O)?C("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):C(null)},[]),E=i.useCallback(async()=>{const O=p.name.trim(),q=p.command.trim();if(!O){s("Script name is required","error");return}if(!Zh(O)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!q){s("Script command is required","error");return}v(!0);try{await sj(O,q,a),s(h?"Script updated":"Script created","success"),f(null),m(!1),g(mr),C(null),await N()}catch(Z){const z=_e(Z);z?.includes("already exists")?s("A script with this name already exists","error"):s(z||"Failed to save script","error")}finally{v(!1)}},[p,h,s,N,a]),L=i.useCallback(async O=>{try{await ij(O,a),s("Script deleted","success"),y(null),h===O&&(f(null),g(mr)),await N()}catch(q){s(_e(q)||"Failed to delete script","error")}},[h,s,N,a]),F=i.useCallback((O,q)=>{r&&r(O,q)},[r]);if(!e)return null;const R=u||h!==null,P=Object.entries(o).map(([O,q])=>({name:O,command:q}));return t.jsx("div",{className:"modal-overlay open",...A,"data-testid":"scripts-modal",children:t.jsxs("div",{className:"modal scripts-modal",role:"dialog","aria-modal":"true","aria-label":"Scripts",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{children:[t.jsx(Mi,{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(gt,{size:24,className:"spin",style:{margin:"0 auto 8px",display:"block"}}),"Loading scripts..."]}):R?t.jsxs("div",{className:"scripts-modal-form",style:{display:"flex",flexDirection:"column",gap:"16px"},children:[t.jsxs("div",{children:[t.jsx("label",{htmlFor:"script-name",style:{display:"block",marginBottom:"4px",fontSize:"13px",fontWeight:500,color:"var(--text)"},children:"Script Name"}),t.jsx("input",{id:"script-name",type:"text",className:"input",value:p.name,onChange:O=>M(O.target.value),placeholder:"e.g., build, test, lint",disabled:x||h!==null,"data-testid":"script-name-input",style:{width:"100%",borderColor:j?"var(--color-error)":void 0}}),j&&t.jsx("div",{style:{fontSize:"12px",color:"var(--color-error)",marginTop:"4px"},"data-testid":"script-name-error",children:j}),t.jsx("div",{style:{fontSize:"11px",color:"var(--text-muted)",marginTop:"4px"},children:"Letters, numbers, hyphens, and underscores only"})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"script-command",style:{display:"block",marginBottom:"4px",fontSize:"13px",fontWeight:500,color:"var(--text)"},children:"Command"}),t.jsx("textarea",{id:"script-command",className:"input",value:p.command,onChange:O=>g(q=>({...q,command:O.target.value})),placeholder:"e.g., npm run build",rows:3,disabled:x,"data-testid":"script-command-input",style:{width:"100%",resize:"vertical",fontFamily:"monospace"}})]}),t.jsxs("div",{className:"scripts-modal-form-actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end"},children:[t.jsx("button",{className:"btn btn-secondary",onClick:T,disabled:x,"data-testid":"script-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:E,disabled:x||!!j,"data-testid":"script-save-btn",children:x?t.jsxs(t.Fragment,{children:[t.jsx(gt,{size:14,className:"spin",style:{marginRight:"6px"}}),"Saving..."]}):h?"Update":"Create"})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"scripts-modal-list-header",style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[t.jsx("div",{style:{fontSize:"13px",color:"var(--text-muted)"},children:P.length===0?"No scripts defined":`${P.length} script${P.length===1?"":"s"}`}),t.jsxs("button",{className:"btn btn-primary",onClick:S,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx(Sn,{size:14}),"Add Script"]})]}),P.length===0?t.jsxs("div",{style:{textAlign:"center",padding:"32px",color:"var(--text-muted)",fontSize:"14px",border:"1px dashed var(--border)",borderRadius:"8px"},"data-testid":"empty-state",children:[t.jsx(Mi,{size:32,style:{margin:"0 auto 12px",opacity:.5}}),t.jsx("div",{children:"No scripts defined yet."}),t.jsx("div",{style:{marginTop:"4px",fontSize:"12px"},children:"Add scripts to quickly run common commands from the dashboard."})]}):t.jsx("div",{className:"scripts-modal-list",style:{display:"flex",flexDirection:"column",gap:"8px"},children:P.map(O=>t.jsx("div",{className:"script-card","data-testid":`script-${O.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:O.name})}),t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:O.command,children:jT(O.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:()=>F(O.name,O.command),title:"Run script","aria-label":`Run ${O.name}`,"data-testid":`run-script-${O.name}`,style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 10px",fontSize:"12px"},children:[t.jsx(Hn,{size:12}),"Run"]}),t.jsx("button",{className:"btn-icon",onClick:()=>_(O.name,O.command),title:"Edit","aria-label":`Edit ${O.name}`,"data-testid":`edit-script-${O.name}`,children:t.jsx(Sn,{size:14,style:{transform:"rotate(45deg)"}})}),b===O.name?t.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[t.jsx("button",{className:"btn-icon",onClick:()=>L(O.name),title:"Confirm delete","aria-label":`Confirm delete ${O.name}`,"data-testid":`confirm-delete-script-${O.name}`,style:{color:"var(--color-error)"},children:t.jsx(Cn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>y(null),title:"Cancel delete","aria-label":"Cancel delete","data-testid":`cancel-delete-script-${O.name}`,children:t.jsx(Jt,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>y(O.name),title:"Delete","aria-label":`Delete ${O.name}`,"data-testid":`delete-script-${O.name}`,children:t.jsx(Cn,{size:14})})]})]})},O.name))})]})})]})})}function ST(e,n,s){const[a,r]=i.useState([]),[o,l]=i.useState("."),[c,d]=i.useState(!1),[u,m]=i.useState(null),[h,f]=i.useState(0),p=i.useCallback(()=>{f(x=>x+1)},[]),g=i.useCallback(x=>{l(x),m(null)},[]);return i.useEffect(()=>{l("."),m(null),r([])},[e]),i.useEffect(()=>{if(!n||!e)return;let x=!1;async function v(){d(!0),m(null);try{const b=await xk(e,o==="."?void 0:o,s);x||r(b.entries)}catch(b){x||(m(_e(b)||"Failed to load files"),r([]))}finally{x||d(!1)}}return v(),()=>{x=!0}},[e,o,n,h,s]),{entries:a,currentPath:o,setPath:g,loading:c,error:u,refresh:p}}function CT(e,n,s,a){const[r,o]=i.useState(""),[l,c]=i.useState(""),[d,u]=i.useState(null),[m,h]=i.useState(!1),[f,p]=i.useState(!1),[g,x]=i.useState(null),v=i.useCallback(j=>{o(j),x(null)},[]);i.useEffect(()=>{if(!e||!n){o(""),c(""),u(null),x(null);return}let j=!1;async function C(){h(!0),x(null);try{const A=await vk(e,n,a);j||(o(A.content),c(A.content),u(A.mtime))}catch(A){j||(x(_e(A)||"Failed to load file"),o(""),c(""),u(null))}finally{j||h(!1)}}return C(),()=>{j=!0}},[e,n,s,a]);const b=r!==l,y=i.useCallback(async()=>{if(!(!e||!n||!b)){p(!0),x(null);try{const j=await yk(e,n,r,a);c(r),u(j.mtime)}catch(j){throw x(_e(j)||"Failed to save file"),j}finally{p(!1)}}},[e,n,r,b,a]);return{content:r,setContent:v,originalContent:l,loading:m,saving:f,error:g,save:y,hasChanges:b,mtime:d}}const ET=1e4;function MT(e){const s=e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||e||"Project Root"}function _T(e){return{id:e.id,label:e.id,title:e.title,worktree:e.worktree,kind:"task"}}function AT(e){const[n,s]=i.useState("Project Root"),[a,r]=i.useState([]),[o,l]=i.useState(!0),[c,d]=i.useState(null);return i.useEffect(()=>{let u=!1;async function m(){try{const f=await bk(e);if(u)return;s(MT(f.project)),r(f.tasks.map(_T)),d(null)}catch(f){u||d(_e(f)||"Failed to load workspaces")}finally{u||l(!1)}}m();const h=window.setInterval(()=>{m()},ET);return()=>{u=!0,window.clearInterval(h)}},[e]),{projectName:n,workspaces:a,loading:o,error:c}}function PT(e){return e===void 0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function RT(e){return e?new Date(e).toLocaleDateString():""}function ep(e,n){return a1(e,n)}const hr={visible:!1,x:0,y:0,entry:null,entryFullPath:""},Bc={type:null,entry:null,entryFullPath:""},TT=200,IT=500,tp=10;function $T({x:e,y:n,entry:s,onAction:a,onClose:r}){const o=i.useRef(null),[l,c]=i.useState({x:e,y:n});i.useEffect(()=>{const m=o.current;if(!m)return;const h=m.getBoundingClientRect(),f=window.visualViewport,p=f?.width&&f.width>0?f.width:window.innerWidth,g=f?.height&&f.height>0?f.height:window.innerHeight,x=f?.offsetLeft??0,v=f?.offsetTop??0,b=8;let y=e-x,j=n-v;y+h.width>p-b&&(y=p-b-h.width),j+h.height>g-b&&(j=g-b-h.height),y<b&&(y=b),j<b&&(j=b),c({x:y+x,y:j+v})},[e,n]),i.useEffect(()=>{const m=h=>{h.key==="Escape"&&r()};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[r]);const d=s.type==="directory",u=[{id:"copy",label:"Copy",icon:ta,disabled:!1},{id:"move",label:"Move",icon:Fv,disabled:!1},{id:"rename",label:"Rename",icon:xs,disabled:!1},...d?[{id:"download-zip",label:"Download as ZIP",icon:Br,disabled:!1}]:[{id:"download",label:"Download",icon:_x,disabled:!1}],{id:"divider",label:"",icon:ta,disabled:!0},{id:"delete",label:"Delete",icon:Cn,disabled:!1}];return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsx("div",{ref:o,className:"file-browser-context-menu",role:"menu","aria-label":"File operations",style:{left:l.x,top:l.y},onClick:m=>m.stopPropagation(),children:u.map(m=>m.id==="divider"?t.jsx("div",{className:"file-browser-context-menu__divider",role:"separator"},"divider"):t.jsxs("button",{role:"menuitem",className:`file-browser-context-menu__item ${m.disabled?"file-browser-context-menu__disabled":""} ${m.id==="delete"?"file-browser-context-menu__item--danger":""}`,disabled:m.disabled,onClick:()=>a(m.id),children:[t.jsx(m.icon,{size:14,className:"file-browser-context-menu__item-icon"}),t.jsx("span",{children:m.label})]},m.id))})})}function DT({type:e,entry:n,entryFullPath:s,onConfirm:a,onCancel:r,loading:o,error:l}){const c=i.useRef(null),d=e==="rename"?n.name:"",[u,m]=i.useState(d);i.useEffect(()=>{setTimeout(()=>c.current?.focus(),50)},[]),i.useEffect(()=>{if(e==="rename"&&c.current){const g=n.name.lastIndexOf(".");g>0?c.current.setSelectionRange(0,g):c.current.select()}},[e,n.name]);const h=g=>{g.key==="Enter"&&u.trim()&&a(u.trim()),g.key==="Escape"&&r()};if(e==="delete")return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsxs("div",{className:"file-browser-dialog",onClick:g=>g.stopPropagation(),children:[t.jsxs("div",{className:"file-browser-dialog-title",children:["Delete ",n.type==="directory"?"Folder":"File"]}),t.jsxs("div",{className:"file-browser-dialog-message",children:["Are you sure you want to delete ",t.jsx("strong",{children:n.name}),"?",n.type==="directory"&&" This will delete all contents recursively."]}),l&&t.jsx("div",{className:"file-browser-dialog-error",children:l}),t.jsxs("div",{className:"file-browser-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:r,disabled:o,children:"Cancel"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>a(""),disabled:o,children:o?"Deleting...":"Delete"})]})]})});const p={copy:{title:"Copy",placeholder:"Destination path",confirm:"Copy"},move:{title:"Move",placeholder:"Destination path",confirm:"Move"},rename:{title:"Rename",placeholder:"New name",confirm:"Rename"}}[e];return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsxs("div",{className:"file-browser-dialog",onClick:g=>g.stopPropagation(),children:[t.jsx("div",{className:"file-browser-dialog-title",children:p.title}),t.jsx("div",{className:"file-browser-dialog-info",children:e==="rename"?n.name:s}),t.jsx("input",{ref:c,className:"file-browser-dialog-input",type:"text",value:u,onChange:g=>m(g.target.value),placeholder:p.placeholder,onKeyDown:h,disabled:o}),l&&t.jsx("div",{className:"file-browser-dialog-error",children:l}),t.jsxs("div",{className:"file-browser-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:r,disabled:o,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>a(u.trim()),disabled:o||!u.trim(),children:o?`${p.confirm}ing...`:p.confirm})]})]})})}function LT({entries:e,currentPath:n,onSelectFile:s,onNavigate:a,loading:r,error:o,onRetry:l,workspace:c,onRefresh:d,projectId:u}){const[m,h]=i.useState(hr),[f,p]=i.useState(Bc),[g,x]=i.useState(!1),[v,b]=i.useState(null),[y,j]=i.useState(!1),[C,A]=i.useState(null),N=i.useRef(null),S=i.useRef(null),_=i.useRef(null),T=i.useRef(!1),M=i.useCallback(()=>{N.current!==null&&(window.clearTimeout(N.current),N.current=null),S.current!==null&&(window.clearTimeout(S.current),S.current=null)},[]),E=i.useCallback(()=>{M(),_.current=null,j(!1),A(null)},[M]);i.useEffect(()=>()=>{M()},[M]);const L=i.useCallback((I,$,w,H)=>{h({visible:!0,x:I,y:$,entry:w,entryFullPath:H})},[]),F=i.useCallback((I,$,w)=>{if(I.touches.length!==1)return;const H=I.touches[0];H&&(E(),_.current={x:H.clientX,y:H.clientY},S.current=window.setTimeout(()=>{j(!0),A(w)},TT),N.current=window.setTimeout(()=>{const K=_.current;K&&(T.current=!0,j(!1),A(null),M(),L(K.x,K.y,$,w))},IT))},[E,M,L]),R=i.useCallback(I=>{const $=_.current,w=I.touches[0];!$||!w||(Math.abs(w.clientX-$.x)>tp||Math.abs(w.clientY-$.y)>tp)&&E()},[E]),P=i.useCallback(()=>{E()},[E]);i.useEffect(()=>{if(!m.visible)return;const I=document.querySelector(".file-browser-list"),$=()=>{T.current=!1,E(),h(hr)};return I?.addEventListener("scroll",$),()=>I?.removeEventListener("scroll",$)},[E,m.visible]),i.useEffect(()=>{if(!m.visible)return;const I=$=>{$.key==="Escape"&&(T.current=!1,h(hr))};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[m.visible]);const O=i.useCallback((I,$)=>{I.preventDefault(),I.stopPropagation(),E(),T.current=!1,L(I.clientX,I.clientY,$,ep(n,$.name))},[E,n,L]),q=i.useCallback(I=>{if(!m.entry)return;T.current=!1;const $=m.entry,w=m.entryFullPath;if(h(hr),I==="download"){if(!c)return;const H=cf(c,w,u);window.open(xi(H),"_blank");return}if(I==="download-zip"){if(!c)return;const H=Ck(c,w,u);window.open(xi(H),"_blank");return}p({type:I,entry:$,entryFullPath:w}),b(null)},[m,c,u]),Z=i.useCallback(async I=>{if(!(!f.type||!f.entry||!c)){x(!0),b(null);try{switch(f.type){case"copy":await kk(c,f.entryFullPath,I,u);break;case"move":await jk(c,f.entryFullPath,I,u);break;case"rename":await Sk(c,f.entryFullPath,I,u);break;case"delete":await Nk(c,f.entryFullPath,u);break}p(Bc),d?.()}catch($){b(_e($)||"Operation failed")}finally{x(!1)}}},[f,c,d,u]),z=i.useCallback(()=>{p(Bc),b(null)},[]),k=i.useCallback((I,$)=>{if(T.current){T.current=!1;return}m.visible||(I.type==="directory"?a($):s($))},[m.visible,a,s]);return r?t.jsxs("div",{className:"file-browser-loading",children:[t.jsx(gt,{className:"spin",size:24}),t.jsx("span",{children:"Loading files..."})]}):o?t.jsxs("div",{className:"file-browser-error",children:[t.jsxs("p",{children:["Error: ",o]}),l&&t.jsx("button",{className:"btn btn-sm",onClick:l,children:"Retry"})]}):t.jsxs("div",{className:"file-browser",children:[t.jsxs("div",{className:"file-browser-header",children:[n!=="."&&t.jsxs("button",{className:"file-browser-up",onClick:()=>{a(r1(n))},children:[t.jsx(Tn,{size:16,style:{transform:"rotate(-90deg)"}}),"Up one level"]}),t.jsx("span",{className:"file-browser-path",children:n==="."?"Root":Ka(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 $=ep(n,I.name),w=y&&C===$;return t.jsxs("div",{className:`file-node file-node--${I.type} ${w?"file-node--long-pressing":""}`,onClick:()=>k(I,$),onContextMenu:H=>O(H,I),onTouchStart:H=>F(H,I,$),onTouchMove:R,onTouchEnd:P,onTouchCancel:P,children:[t.jsx("div",{className:"file-node-icon",children:I.type==="directory"?t.jsx(os,{size:16}):t.jsx(Xp,{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:PT(I.size)}),I.mtime&&t.jsx("div",{className:"file-node-time",children:RT(I.mtime)})]},I.name)})}),m.visible&&m.entry&&t.jsx($T,{x:m.x,y:m.y,entry:m.entry,onAction:q,onClose:()=>{T.current=!1,h(hr)}}),f.type&&f.entry&&t.jsx(DT,{type:f.type,entry:f.entry,entryFullPath:f.entryFullPath,onConfirm:Z,onCancel:z,loading:g,error:v})]})}function OT(e){if(!e)return!1;const n=e.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function zT({content:e,onChange:n,readOnly:s,filePath:a}){const[r,o]=i.useState(!1),[l,c]=i.useState(!0),d=OT(a),u=d&&(s?!0:r),m=i.useCallback(()=>{o(!1)},[]),h=i.useCallback(()=>{o(!0)},[]),f=i.useCallback(()=>{c(p=>!p)},[]);return t.jsxs("div",{className:"file-editor-container",children:[d?t.jsxs("div",{className:"file-editor-toolbar",children:[t.jsxs("div",{className:"file-editor-mode-toggle",children:[!s&&t.jsxs("button",{className:`btn btn-sm ${u?"":"btn-primary"}`,onClick:m,disabled:!u,"aria-label":"Edit mode",children:[t.jsx(Qp,{size:14}),"Edit"]}),t.jsxs("button",{className:`btn btn-sm ${u?"btn-primary":""}`,onClick:h,disabled:u,"aria-label":"Preview mode",children:[t.jsx(Va,{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(Xo,{size:14})})]}):!s&&t.jsxs("div",{className:"file-editor-toolbar",children:[t.jsx("div",{className:"file-editor-mode-toggle"}),t.jsx("button",{className:`btn btn-sm ${l?"btn-primary":""}`,onClick:f,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(Xo,{size:14})})]}),u?t.jsx("div",{className:"file-editor-preview markdown-body",children:t.jsx(vi,{remarkPlugins:[yi],children:e})}):t.jsx("textarea",{className:`file-editor-textarea ${l?"file-editor-textarea--wrap":""}`,value:e,onChange:p=>n(p.target.value),readOnly:s,spellCheck:!1,"aria-label":a?`Editor for ${a}`:"File editor"})]})}function FT(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function UT({currentWorkspace:e,projectName:n,workspaces:s,onSelect:a}){const[r,o]=i.useState(!1),l=i.useMemo(()=>e==="project"?n||"Project Root":s.find(d=>d.id===e)?.label??e,[e,n,s]);return t.jsxs("div",{className:"workspace-selector",children:[t.jsxs("button",{type:"button",className:"workspace-selector-trigger",onClick:()=>o(c=>!c),"aria-haspopup":"listbox","aria-expanded":r,children:[e==="project"?t.jsx(ku,{size:14}):t.jsx(ad,{size:14}),t.jsx("span",{className:"workspace-selector-trigger-label",children:l}),t.jsx(un,{size:14,className:`workspace-selector-trigger-icon${r?" open":""}`})]}),r&&t.jsxs("div",{className:"workspace-selector-menu",role:"listbox","aria-label":"Select workspace",children:[t.jsxs("button",{type:"button",className:`workspace-selector-option${e==="project"?" active":""}`,onClick:()=>{a("project"),o(!1)},children:[t.jsxs("div",{className:"workspace-selector-option-main",children:[t.jsx(ku,{size:14}),t.jsx("span",{children:"Project Root"})]}),t.jsx("span",{className:"workspace-selector-option-meta",children:n})]}),s.length>0&&t.jsxs("div",{className:"workspace-selector-group",children:[t.jsx("div",{className:"workspace-selector-group-label",children:"Task Worktrees"}),s.map(c=>t.jsxs("button",{type:"button",className:`workspace-selector-option${e===c.id?" active":""}`,onClick:()=>{a(c.id),o(!1)},children:[t.jsxs("div",{className:"workspace-selector-option-main",children:[t.jsx(ad,{size:14}),t.jsx("span",{children:c.id})]}),c.title&&t.jsx("span",{className:"workspace-selector-option-meta",title:c.title,children:FT(c.title)})]},c.id))]})]})]})}const BT=768,HT=280,Oo=180,zo=500,np="fusion:file-browser-sidebar-width",rb=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),qT=new Set([...rb,".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 sp(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return qT.has(n)}function VT(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return rb.has(n)}function WT({initialWorkspace:e="project",onClose:n,onWorkspaceChange:s,projectId:a}){const{projectName:r,workspaces:o}=AT(a),l=i.useRef(null);wi(l,!0,"fusion:files-modal-size");const c=Ri(n),[d,u]=i.useState(e),[m,h]=i.useState(null),[f,p]=i.useState(!1),[g,x]=i.useState("list"),[v,b]=i.useState(HT),{entries:y,currentPath:j,setPath:C,loading:A,error:N,refresh:S}=ST(d,!0,a),{content:_,setContent:T,originalContent:M,loading:E,saving:L,error:F,save:R,hasChanges:P,mtime:O}=CT(d,m,!0,a);i.useEffect(()=>{u(e)},[e]),i.useEffect(()=>{const B=()=>{p(window.innerWidth<=BT)};return B(),window.addEventListener("resize",B),()=>window.removeEventListener("resize",B)},[]),i.useEffect(()=>{m||x("list")},[m]),i.useEffect(()=>{try{const B=localStorage.getItem(np);if(!B)return;const ye=Number.parseInt(B,10);if(!Number.isNaN(ye)){const U=Math.max(Oo,Math.min(zo,ye));b(U)}}catch{}},[]),i.useEffect(()=>{const B=ye=>{ye.key==="Escape"&&n(),(ye.metaKey||ye.ctrlKey)&&ye.key==="s"&&(ye.preventDefault(),P&&!L&&R())};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[n,P,L,R]);const q=i.useCallback(B=>{h(B),f&&x("editor")},[f]),Z=i.useCallback(()=>{x("list")},[]),z=i.useCallback(()=>{T(M)},[M,T]),k=i.useCallback(B=>{u(B),h(null),x("list"),s?.(B)},[s]),I=i.useCallback(B=>{try{localStorage.setItem(np,String(B))}catch{}},[]),$=i.useCallback(B=>{if(f)return;B.preventDefault(),B.stopPropagation();const ye=B.currentTarget;typeof ye.setPointerCapture=="function"&&ye.setPointerCapture(B.pointerId);const U=B.clientX,te=v;let ne=te;document.body.style.userSelect="none";const ee=ge=>{const se=ge.clientX-U,Ae=Math.max(Oo,Math.min(zo,te+se));ne=Ae,b(Ae)},ie=ge=>{typeof ye.releasePointerCapture=="function"&&ye.releasePointerCapture(ge.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",ee),document.removeEventListener("pointerup",ie),I(ne)};document.addEventListener("pointermove",ee),document.addEventListener("pointerup",ie)},[f,I,v]),w=i.useCallback(B=>{if(f)return;const ye=20;if(B.key!=="ArrowLeft"&&B.key!=="ArrowRight")return;B.preventDefault();const U=B.key==="ArrowLeft"?-ye:ye,te=Math.max(Oo,Math.min(zo,v+U));b(te),I(te)},[f,I,v]),K=`Files — ${i.useMemo(()=>d==="project"?"Project":o.find(B=>B.id===d)?.id??d,[d,o])}`,pe=i.useMemo(()=>!m||!VT(m)?null:cf(d,m,a),[m,d,a]),le=B=>{const ye=new Blob([B]).size;return ye<1024?`${ye} B`:`${(ye/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(os,{size:18}),t.jsx("span",{children:K}),m&&t.jsx("span",{className:"file-browser-header-path",children:m})]}),t.jsxs("div",{className:"file-browser-header-actions",children:[t.jsx(UT,{currentWorkspace:d,projectName:r,workspaces:o,onSelect:k}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Jt,{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(LT,{entries:y,currentPath:j,onSelectFile:q,onNavigate:C,loading:A,error:N,onRetry:S,workspace:d,onRefresh:S,projectId:a})}),!f&&t.jsx("div",{className:"file-browser-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":Oo,"aria-valuemax":zo,"aria-valuenow":v,"aria-label":"Resize sidebar",tabIndex:0,onPointerDown:$,onKeyDown:w}),t.jsx("div",{className:`file-browser-content ${f?"mobile":""} ${g==="editor"?"active":""}`,children:m?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"file-browser-toolbar",children:[t.jsxs("div",{className:"file-browser-file-info",children:[f&&g==="editor"&&t.jsxs("button",{className:"file-browser-back-button",onClick:Z,"aria-label":"Back to file list",children:[t.jsx(la,{size:16}),t.jsx("span",{children:"Back"})]}),m,sp(m)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(Gx,{size:12}),"Binary file — read only"]}),O&&t.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date(O).toLocaleString()]}),E&&t.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),t.jsx("div",{className:"file-browser-actions",children:!pe&&P&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:z,disabled:L,children:[t.jsx(Zv,{size:14}),"Discard"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void R(),disabled:L,children:[t.jsx(sf,{size:14}),L?"Saving...":"Save"]})]})})]}),F&&!pe&&t.jsx("div",{className:"file-browser-error-banner",children:F}),pe?t.jsx("div",{className:"file-browser-image-preview",children:t.jsx("img",{src:pe,alt:m??"",className:"file-browser-image"})}):t.jsx("div",{className:"file-editor-wrapper",children:t.jsx(zT,{content:_,onChange:T,filePath:m,readOnly:sp(m)})}),!pe&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:le(_)}),P&&t.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):t.jsxs("div",{className:"file-browser-placeholder",children:[t.jsx(os,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to edit"})]})})]})]})})}function KT(e){const{items:n,...s}=e;return s}function ip(e){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`${e}-${crypto.randomUUID()}`:`${e}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function GT(e={}){const{projectId:n,addToast:s}=e,[a,r]=i.useState([]),[o,l]=i.useState([]),[c,d]=i.useState(!0),[u,m]=i.useState(null),[h,f]=i.useState(null),[p,g]=i.useState([]),x=i.useRef(h);x.current=h,i.useEffect(()=>{let _=!1;async function T(){d(!0),m(null);try{const M=await wN(n);if(_)return;g(M),r(M.map(KT));const E=x.current&&M.some(L=>L.id===x.current)?x.current:M[0]?.id??null;f(E),l(E?M.find(L=>L.id===E)?.items??[]:[])}catch(M){if(_)return;g([]),r([]),l([]),f(null),m(M instanceof Error?M.message:"Failed to load todo lists")}finally{_||d(!1)}}return T(),()=>{_=!0}},[n]),i.useEffect(()=>{if(!h){l([]);return}const _=p.find(T=>T.id===h);l(_?.items??[])},[p,h]);const v=i.useCallback(async _=>{const T=a,M=p,E=new Date().toISOString(),L={id:ip("temp-list"),projectId:n??"",title:_,createdAt:E,updatedAt:E};m(null),r(F=>[...F,L]),g(F=>[...F,{...L,items:[]}]);try{const F=await kN(_,n);r(R=>R.map(P=>P.id===L.id?F:P)),g(R=>R.map(P=>P.id===L.id?{...F,items:[]}:P)),x.current||f(F.id)}catch(F){r(T),g(M),m(F instanceof Error?F.message:"Failed to create list"),s?.("Failed to create todo list","error")}},[s,p,a,n]),b=i.useCallback(async(_,T)=>{const M=a,E=p;m(null),r(L=>L.map(F=>F.id===_?{...F,title:T}:F)),g(L=>L.map(F=>F.id===_?{...F,title:T}:F));try{const L=await jN(_,T,n);r(F=>F.map(R=>R.id===_?L:R)),g(F=>F.map(R=>R.id===_?{...L,items:R.items}:R))}catch(L){r(M),g(E),m(L instanceof Error?L.message:"Failed to rename list"),s?.("Failed to rename todo list","error")}},[s,p,a,n]),y=i.useCallback(async _=>{const T=a,M=p,E=x.current,L=E===_?a.find(F=>F.id!==_)?.id??null:E;m(null),r(F=>F.filter(R=>R.id!==_)),g(F=>F.filter(R=>R.id!==_)),E===_&&f(L);try{await NN(_,n)}catch(F){r(T),g(M),f(E),m(F instanceof Error?F.message:"Failed to delete list"),s?.("Failed to delete todo list","error")}},[s,p,a,n]),j=i.useCallback(async _=>{const T=x.current;if(!T)return;const M=o,E=p,L=new Date().toISOString(),F=o.reduce((P,O)=>Math.max(P,O.sortOrder),-1),R={id:ip("temp-item"),listId:T,text:_,completed:!1,completedAt:null,createdAt:L,updatedAt:L,sortOrder:F+1};m(null),l(P=>[...P,R]),g(P=>P.map(O=>O.id===T?{...O,items:[...O.items,R]}:O));try{const P=await SN(T,_,n);l(O=>O.map(q=>q.id===R.id?P:q)),g(O=>O.map(q=>q.id===T?{...q,items:q.items.map(Z=>Z.id===R.id?P:Z)}:q))}catch(P){l(M),g(E),m(P instanceof Error?P.message:"Failed to create item"),s?.("Failed to create todo item","error")}},[s,o,p,n]),C=i.useCallback(async(_,T)=>{const M=o.find(P=>P.id===_);if(!M)return;const E=o,L=p,F=T.completed??M.completed,R={...M,...T,completed:F,completedAt:F?M.completedAt??new Date().toISOString():null,updatedAt:new Date().toISOString()};m(null),l(P=>P.map(O=>O.id===_?R:O)),g(P=>P.map(O=>O.id===R.listId?{...O,items:O.items.map(q=>q.id===_?R:q)}:O));try{const P=await CN(_,T,n);l(O=>O.map(q=>q.id===_?P:q)),g(O=>O.map(q=>q.id===P.listId?{...q,items:q.items.map(Z=>Z.id===_?P:Z)}:q))}catch(P){l(E),g(L),m(P instanceof Error?P.message:"Failed to update item"),s?.("Failed to update todo item","error")}},[s,o,p,n]),A=i.useCallback(async _=>{const T=o.find(M=>M.id===_);T&&await C(_,{completed:!T.completed})},[o,C]),N=i.useCallback(async _=>{const T=o,M=p;m(null),l(E=>E.filter(L=>L.id!==_)),g(E=>E.map(L=>({...L,items:L.items.filter(F=>F.id!==_)})));try{await EN(_,n)}catch(E){l(T),g(M),m(E instanceof Error?E.message:"Failed to delete item"),s?.("Failed to delete todo item","error")}},[s,o,p,n]),S=i.useCallback(async _=>{const T=x.current;if(!T)return;const M=o,E=p,L=new Map(o.map(R=>[R.id,R])),F=_.map((R,P)=>{const O=L.get(R);return O?{...O,sortOrder:P}:null}).filter(R=>R!==null);m(null),l(F),g(R=>R.map(P=>P.id===T?{...P,items:F}:P));try{await MN(T,_,n)}catch(R){l(M),g(E),m(R instanceof Error?R.message:"Failed to reorder items"),s?.("Failed to reorder todo items","error")}},[s,o,p,n]);return{lists:a,items:o,loading:c,error:u,selectedListId:h,setSelectedListId:f,createList:v,renameList:b,deleteList:y,createItem:j,updateItem:C,toggleItem:A,deleteItem:N,reorderItems:S}}function JT(e){return[...e].sort((n,s)=>n.sortOrder-s.sortOrder)}function ob({projectId:e,addToast:n,onPlanningMode:s,onTaskCreated:a}){const{lists:r,items:o,loading:l,error:c,selectedListId:d,setSelectedListId:u,createList:m,renameList:h,deleteList:f,createItem:p,updateItem:g,toggleItem:x,deleteItem:v,reorderItems:b}=GT({projectId:e,addToast:(ae,re)=>{if(re==="success"||re==="error"||re==="info"||re===void 0){n(ae,re);return}n(ae,"info")}}),[y,j]=i.useState(null),[C,A]=i.useState(""),[N,S]=i.useState(null),[_,T]=i.useState(""),[M,E]=i.useState(""),[L,F]=i.useState(!1),[R,P]=i.useState(""),[O,q]=i.useState([]),[Z,z]=i.useState(!1),[k,I]=i.useState(!1),[$,w]=i.useState(null),H=i.useRef(null),{confirm:K}=qs(),pe=i.useMemo(()=>r.find(ae=>ae.id===d)??null,[r,d]),le=i.useMemo(()=>JT(o.filter(ae=>ae.listId===d)),[o,d]);function B(){j(null),A(""),E(""),F(!1)}function ye(){S(null),T(""),P("")}function U(ae){B(),ye(),u(ae)}const te=i.useCallback(async()=>{z(!0);try{const ae=await da(void 0,e);q(ae),I(!0)}catch(ae){n(`Failed to load agents: ${_e(ae)}`,"error"),I(!1),w(null)}finally{z(!1)}},[e,n]);i.useEffect(()=>{j(null),A(""),E(""),F(!1),S(null),T(""),P(""),I(!1),w(null)},[d]),i.useEffect(()=>{if(!k)return;const ae=re=>{H.current&&!H.current.contains(re.target)&&(I(!1),w(null))};return document.addEventListener("mousedown",ae),()=>{document.removeEventListener("mousedown",ae)}},[k]);function ne(ae){ye(),j(ae.id),A(ae.title),F(!1)}async function ee(){if(!y)return;const ae=C.trim();if(!ae){j(null),A("");return}await h(y,ae),j(null),A("")}function ie(){j(null),A("")}function ge(ae){B(),S(ae.id),T(ae.text)}async function se(){if(!N)return;const ae=_.trim();if(!ae){S(null),T("");return}await g(N,{text:ae}),S(null),T("")}function Ae(){S(null),T("")}async function xe(){const ae=M.trim();ae&&(await m(ae),E(""),F(!1))}async function Se(){if(!d)return;const ae=R.trim();ae&&(await p(ae),P(""))}async function qe(ae){await K({title:"Delete List",message:"Delete this list and all its items?",danger:!0})&&await f(ae)}async function We(ae){await v(ae)}async function Qe(ae,re){const je=le.map(Je=>Je.id),Q=je.findIndex(Je=>Je===ae);if(Q<0)return;const Fe=re==="up"?Q-1:Q+1;Fe<0||Fe>=je.length||([je[Q],je[Fe]]=[je[Fe],je[Q]],await b(je))}const ve=i.useCallback(async ae=>{try{const re={description:ae.text,column:"triage",source:{sourceType:"dashboard_ui"}},je=await tl(re,e);a?.(je),n(`Created ${je.id} from todo`,"success")}catch(re){n(`Failed to create task: ${_e(re)}`,"error")}},[e,n,a]),Oe=i.useCallback(async(ae,re)=>{try{const je={description:ae.text,column:"triage",assignedAgentId:re,source:{sourceType:"dashboard_ui"}},Q=await tl(je,e);a?.(Q);const Je=O.find(be=>be.id===re)?.name??re;n(`Created ${Q.id} and assigned to ${Je}`,"success"),I(!1),w(null)}catch(je){n(`Failed to create and assign task: ${_e(je)}`,"error")}},[e,n,O,a]);return l?t.jsx("div",{className:"todo-view",children:t.jsxs("div",{className:"todo-loading",children:[t.jsx(gt,{className:"todo-loading-icon","aria-hidden":"true"}),t.jsx("p",{children:"Loading todos..."})]})}):t.jsx("div",{className:"todo-view",children:t.jsxs("div",{className:"todo-view-layout",children:[t.jsxs("aside",{className:"todo-view-sidebar","aria-label":"Todo lists sidebar",children:[t.jsxs("div",{className:"todo-sidebar-header",children:[t.jsx("h3",{className:"todo-sidebar-title",children:"Lists"}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-add-list-btn",onClick:()=>{ye(),F(!0),j(null)},"aria-label":"Add list","data-testid":"add-list-button",children:t.jsx(Sn,{})})]}),L&&t.jsxs("div",{className:"todo-list-item",children:[t.jsx("input",{className:"input todo-inline-edit-input",placeholder:"New list title",value:M,onChange:ae=>E(ae.target.value),onKeyDown:ae=>{ae.key==="Enter"&&xe(),ae.key==="Escape"&&(E(""),F(!1))},autoFocus:!0,"data-testid":"new-list-input"}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{xe()},"aria-label":"Save list",children:t.jsx(Yn,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{E(""),F(!1)},"aria-label":"Cancel list",children:t.jsx(Jt,{})})]}),r.length===0&&!L?t.jsxs("div",{className:"todo-empty-state",children:[t.jsx(rd,{"aria-hidden":"true"}),t.jsx("p",{children:"No todo lists yet. Create one to get started."}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{ye(),F(!0)},children:"Create List"})]}):t.jsx("div",{className:"todo-list-items",role:"list","aria-label":"Todo lists",children:r.map(ae=>{const re=ae.id===d,je=ae.id===y;return t.jsx("div",{className:`todo-list-item${re?" todo-list-item--active":""}`,role:"listitem",children:je?t.jsxs(t.Fragment,{children:[t.jsx("input",{className:"input todo-inline-edit-input",value:C,onChange:Q=>A(Q.target.value),onKeyDown:Q=>{Q.key==="Enter"&&ee(),Q.key==="Escape"&&ie()},autoFocus:!0,"data-testid":`rename-list-input-${ae.id}`}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{ee()},"aria-label":"Save list rename",children:t.jsx(Yn,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:ie,"aria-label":"Cancel list rename",children:t.jsx(Jt,{})})]}):t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"todo-list-select-btn",onClick:()=>U(ae.id),"aria-label":`Select list ${ae.title}`,"aria-current":re?"true":void 0,"data-testid":`todo-list-${ae.id}`,children:t.jsx("span",{className:"todo-list-item-name",children:ae.title})}),t.jsxs("div",{className:"todo-list-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{ne(ae)},"aria-label":`Rename ${ae.title}`,"data-testid":`rename-list-button-${ae.id}`,children:t.jsx(xs,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon btn-danger todo-icon-btn",onClick:()=>{qe(ae.id)},"aria-label":`Delete ${ae.title}`,"data-testid":`delete-list-button-${ae.id}`,children:t.jsx(Cn,{})})]})]})},ae.id)})})]}),t.jsxs("section",{className:"todo-view-main","aria-label":"Todo items",children:[c&&t.jsxs("div",{className:"todo-error-banner",role:"alert",children:[t.jsx("span",{className:"todo-error-message",children:c}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>window.location.reload(),children:"Retry"})]}),pe?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"todo-items-header",children:t.jsx("h3",{children:pe.title})}),t.jsxs("div",{className:"todo-add-item-row",children:[t.jsx("input",{className:"input",placeholder:"Add a todo item",value:R,onChange:ae=>P(ae.target.value),onKeyDown:ae=>{ae.key==="Enter"&&Se(),ae.key==="Escape"&&P("")},"data-testid":"new-item-input"}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>{Se()},children:"Add"})]}),le.length===0?t.jsx("div",{className:"todo-empty-state",children:t.jsx("p",{children:"No items in this list. Add one above."})}):t.jsx("div",{className:"todo-items-list",children:le.map((ae,re)=>{const je=ae.id===N;return t.jsxs("div",{className:"todo-item","data-testid":`todo-item-${ae.id}`,children:[t.jsxs("div",{className:"todo-item-main-row",children:[t.jsx("input",{type:"checkbox",checked:ae.completed,onChange:()=>{x(ae.id)},className:"todo-item-checkbox","aria-label":`Toggle ${ae.text}`,"data-testid":`toggle-item-${ae.id}`}),je?t.jsx("input",{className:"input todo-inline-edit-input",value:_,onChange:Q=>T(Q.target.value),onKeyDown:Q=>{Q.key==="Enter"&&se(),Q.key==="Escape"&&Ae()},autoFocus:!0,"data-testid":`edit-item-input-${ae.id}`}):t.jsx("button",{type:"button",className:`todo-item-text${ae.completed?" todo-item-text--completed":""}`,onClick:()=>ge(ae),children:ae.text})]}),t.jsx("div",{className:"todo-item-actions","data-testid":`todo-item-actions-${ae.id}`,children:je?t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{se()},"aria-label":"Save item edit",children:t.jsx(Yn,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:Ae,"aria-label":"Cancel item edit",children:t.jsx(Jt,{})})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"todo-item-reorder-btns",children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-item-reorder-btn",onClick:()=>{Qe(ae.id,"up")},disabled:re===0,"aria-label":`Move ${ae.text} up`,"data-testid":`move-up-${ae.id}`,children:t.jsx(ri,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-item-reorder-btn",onClick:()=>{Qe(ae.id,"down")},disabled:re===le.length-1,"aria-label":`Move ${ae.text} down`,"data-testid":`move-down-${ae.id}`,children:t.jsx(un,{})})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{s?.(ae.text)},"aria-label":`Start planning from ${ae.text}`,"data-testid":`planning-from-${ae.id}`,children:t.jsx(oi,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{ve(ae)},"aria-label":`Create task from ${ae.text}`,"data-testid":`create-task-from-${ae.id}`,children:t.jsx(fx,{})}),t.jsxs("div",{className:"todo-agent-picker-trigger",ref:$===ae.id?H:void 0,children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{w(ae.id),te()},"aria-label":`Assign ${ae.text} to agent`,"data-testid":`assign-agent-for-${ae.id}`,children:t.jsx(Rn,{})}),k&&$===ae.id&&t.jsx("div",{className:"todo-agent-picker-dropdown",onMouseDown:Q=>{Q.preventDefault()},children:Z?t.jsx("div",{className:"todo-agent-picker-loading",children:"Loading agents..."}):O.filter(Q=>Q.state!=="terminated").length>0?O.filter(Q=>Q.state!=="terminated").map(Q=>t.jsxs("button",{type:"button",className:"todo-agent-picker-item",onClick:()=>{Oe(ae,Q.id)},children:[t.jsx(Rn,{}),t.jsx("span",{children:Q.name}),t.jsx("span",{className:"todo-agent-picker-role",children:Q.role})]},Q.id)):t.jsx("div",{className:"todo-agent-picker-empty",children:"No agents available"})})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>ge(ae),"aria-label":`Edit ${ae.text}`,"data-testid":`edit-item-${ae.id}`,children:t.jsx(xs,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon btn-danger todo-icon-btn",onClick:()=>{We(ae.id)},"aria-label":`Delete ${ae.text}`,"data-testid":`delete-item-${ae.id}`,children:t.jsx(Cn,{})})]})})]},ae.id)})})]}):t.jsxs("div",{className:"todo-empty-state",children:[t.jsx(rd,{"aria-hidden":"true"}),t.jsx("p",{children:"Select a list from the sidebar"})]})]})]})})}const lb=Object.freeze(Object.defineProperty({__proto__:null,TodoView:ob},Symbol.toStringTag,{value:"Module"}));function YT({onClose:e,projectId:n,addToast:s,onPlanningMode:a}){const r=Ri(e),l=Pi()==="mobile",{keyboardOverlap:c,viewportHeight:d,viewportOffsetTop:u,keyboardOpen:m}=Ol({enabled:l}),h=m?{"--keyboard-overlap":`${c}px`,"--vv-offset-top":`${u}px`,...d!==null?{"--vv-height":`${d}px`}:{}}:{};return i.useEffect(()=>{const f=p=>{p.key==="Escape"&&e()};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[e]),t.jsx("div",{className:"modal-overlay open",...r,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal todo-modal",style:h,children:[t.jsxs("div",{className:"modal-header todo-modal-header",children:[t.jsxs("div",{className:"todo-modal-header-title",children:[t.jsx(rd,{size:18}),t.jsxs("div",{children:[t.jsx("h2",{children:"Todos"}),t.jsx("p",{children:"Manage reusable todo lists for your project."})]})]}),t.jsx("button",{className:"modal-close",onClick:e,"aria-label":"Close",children:t.jsx(Jt,{size:20})})]}),t.jsx("div",{className:"todo-modal-body",children:t.jsx(ob,{projectId:n,addToast:s,onPlanningMode:a,onClose:e})})]})})}function QT(e={}){const{pollInterval:n=3e4,autoRefresh:s=!0}=e,[a,r]=i.useState({providers:[],loading:!0,error:null,lastUpdated:null}),o=i.useRef(null),l=i.useRef(null),c=i.useCallback(async(u=!1)=>{l.current&&l.current.abort(),l.current=new AbortController,u&&r(m=>({...m,loading:!0,error:null}));try{const{providers:m}=await Cw();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:_e(m)||"Failed to fetch usage data"}))}},[]);i.useEffect(()=>{c()},[c]),i.useEffect(()=>{if(s)return o.current=setInterval(()=>{c(!1)},n),()=>{o.current&&(clearInterval(o.current),o.current=null)}},[s,n,c]),i.useEffect(()=>()=>{l.current&&l.current.abort(),o.current&&clearInterval(o.current)},[]);const d=i.useCallback(()=>c(!0),[c]);return{providers:a.providers,loading:a.loading,error:a.error,lastUpdated:a.lastUpdated,refresh:d}}function XT(e){const n=new Date(e),s=new Date,a=n.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit",hour12:!0});if(n.toDateString()===s.toDateString())return a;const o=new Date(s.getFullYear(),s.getMonth(),s.getDate()),l=new Date(n.getFullYear(),n.getMonth(),n.getDate()),c=Math.round((l.getTime()-o.getTime())/(1440*60*1e3));return c>=1&&c<=7?`${n.toLocaleDateString(void 0,{weekday:"short"})} ${a}`:`${n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}, ${a}`}function ZT(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}const cb="kb-usage-hidden-windows",db="kb-usage-modal-size",ub="kb-usage-provider-order";function ap(e){const n=Zn(db,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 rp(e){const n=Zn(cb,e);if(!n)return{};try{const s=JSON.parse(n);return!s||typeof s!="object"?{}:Object.entries(s).reduce((a,[r,o])=>{if(Array.isArray(o)){const l=o.filter(c=>typeof c=="string");l.length>0&&(a[r]=l)}return a},{})}catch{return{}}}function eI(e,n){us(cb,JSON.stringify(e),n)}function op(e){const n=Zn(ub,e);if(!n)return[];try{const s=JSON.parse(n);return Array.isArray(s)?s.filter(a=>typeof a=="string"):[]}catch{return[]}}function lp(e,n){us(ub,JSON.stringify(e),n)}function mb(e,n,s){return s[e]?.includes(n)??!1}function tI({window:e,viewMode:n,isHidden:s,onToggleHidden:a}){const r=ZT(e.percentUsed),o=n==="remaining",l=Math.round(o?e.percentLeft:e.percentUsed),c=o?`${Math.round(e.percentLeft)}% remaining`:`${Math.round(e.percentUsed)}% used`,d=o?`${Math.round(e.percentUsed)}% used`:`${Math.round(e.percentLeft)}% left`;let u=e.resetText;if(!u&&e.resetAt){const v=new Date(e.resetAt).getTime()-Date.now();if(v>0){const b=Math.floor(v/36e5),y=Math.floor(b/24),j=b%24;y>0&&j>0?u=`resets in ${y}d ${j}h`:y>0?u=`resets in ${y}d`:b>0?u=`resets in ${b}h`:u=`resets in ${Math.floor(v/6e4)}m`}}const m=e.pace,h=m!==void 0;let f=0;h&&(f=o?100-m.percentElapsed:m.percentElapsed);const p=m?.status==="ahead",g=m?.status==="behind",x=m?.status==="on-track";return t.jsxs("div",{className:`usage-window ${s?"usage-window--hidden":""}`,children:[t.jsxs("div",{className:"usage-window-header",children:[t.jsx("span",{className:"usage-window-label",children:e.label}),t.jsxs("div",{className:"usage-window-header-controls",children:[!s&&t.jsx("span",{className:"usage-window-percentage",children:c}),!s&&t.jsx("button",{className:"btn-icon usage-window-hide-btn",onClick:a,"aria-label":`Hide ${e.label}`,"data-testid":"usage-window-hide-btn",children:t.jsx(Va,{size:14})})]})]}),t.jsxs("div",{className:"usage-progress-wrapper",children:[t.jsx("div",{className:"usage-progress-bar",children:t.jsx("div",{className:`usage-progress-fill ${r}`,style:{width:`${l}%`},role:"progressbar","aria-valuenow":l,"aria-valuemin":0,"aria-valuemax":100,"aria-label":`${e.label}: ${c}`})}),h&&t.jsx("div",{className:"usage-pace-marker",style:{left:`${f}%`},"aria-hidden":"true","data-testid":"pace-marker"})]}),t.jsxs("div",{className:"usage-window-footer",children:[t.jsx("span",{className:"usage-window-left",children:d}),t.jsxs("span",{className:"usage-window-reset-group",children:[u&&t.jsx("span",{className:"usage-window-reset",children:u}),e.resetAt&&t.jsx("span",{className:"usage-window-reset-at",children:XT(e.resetAt)})]})]}),h&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[p&&t.jsxs(t.Fragment,{children:[t.jsx(Sl,{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(wy,{size:14,className:"pace-icon pace-behind"}),t.jsx("span",{className:"pace-text pace-behind",children:m.message})]}),x&&t.jsxs(t.Fragment,{children:[t.jsx(Ln,{size:14,className:"pace-icon pace-ontrack"}),t.jsx("span",{className:"pace-text pace-ontrack",children:m.message})]})]})]})}function nI(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 sI({provider:e,viewMode:n,hiddenWindows:s,onToggleWindow:a,onShowAllHidden:r,isDragging:o,isDragOver:l,dragOverPosition:c,onDragStart:d,onDragOver:u,onDragLeave:m,onDrop:h,onDragEnd:f,isTouchReorderMode:p,canMoveUp:g,canMoveDown:x,onMoveUp:v,onMoveDown:b}){const y=s[e.name]?.length??0,j=()=>{switch(e.status){case"ok":return null;case"error":return t.jsx("span",{className:"usage-status-badge usage-status-badge--error",children:"Error"});case"no-auth":default:return t.jsx("span",{className:"usage-status-badge usage-status-badge--not-configured",children:"Not configured"})}};return t.jsxs("div",{className:`usage-provider${o?" usage-provider--dragging":""}${l&&c==="before"?" usage-provider--drag-over-before":""}${l&&c==="after"?" usage-provider--drag-over-after":""}`,"data-provider":e.name,"data-status":e.status,draggable:!p,onDragStart:p?void 0:d,onDragOver:p?void 0:u,onDragLeave:p?void 0:m,onDrop:p?void 0:h,onDragEnd:p?void 0:f,children:[t.jsxs("div",{className:"usage-provider-header",children:[t.jsxs("div",{className:"usage-provider-info",children:[t.jsx(qn,{provider:nI(e.name),size:"md"}),t.jsx("span",{className:"usage-provider-name",children:e.name}),y>0&&t.jsxs("button",{className:"btn btn-sm usage-show-hidden-btn",onClick:()=>r(e.name),"data-testid":"usage-show-hidden-btn",children:["Show hidden (",y,")"]})]}),t.jsxs("div",{className:"usage-provider-actions",children:[p&&t.jsxs("div",{className:"usage-provider-reorder-controls",role:"group","aria-label":`Reorder ${e.name}`,children:[t.jsx("button",{className:"btn-icon usage-provider-reorder-btn",type:"button",onClick:v,disabled:!g,"aria-label":`Move ${e.name} up`,children:t.jsx(ri,{size:14})}),t.jsx("button",{className:"btn-icon usage-provider-reorder-btn",type:"button",onClick:b,disabled:!x,"aria-label":`Move ${e.name} down`,children:t.jsx(un,{size:14})})]}),j(),t.jsx("div",{className:"usage-provider-drag-handle","aria-hidden":"true",children:t.jsx(wl,{size:16})})]})]}),e.error&&t.jsx("div",{className:"usage-provider-error",children:e.error}),e.plan&&t.jsx("div",{className:"usage-provider-meta",children:t.jsx("span",{className:"usage-provider-plan",children:e.plan})}),e.windows.length>0?t.jsx("div",{className:"usage-provider-windows",children:e.windows.map((C,A)=>{const N=mb(e.name,C.label,s);return t.jsx(tI,{window:C,viewMode:n,isHidden:N,onToggleHidden:()=>a(e.name,C.label)},`${e.name}-${C.label}-${A}`)})}):e.status==="ok"?t.jsx("div",{className:"usage-provider-empty",children:"No usage data available"}):null]})}function iI(){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 aI({isOpen:e,onClose:n,projectId:s,anchorRect:a}){const{providers:r,loading:o,error:l,lastUpdated:c,refresh:d}=QT({autoRefresh:e}),[u,m]=i.useState(!1),[h,f]=i.useState(()=>typeof window<"u"?window.innerWidth>=769:!1),[p,g]=i.useState(()=>typeof window>"u"?!1:window.matchMedia?.("(pointer: coarse)").matches??!1),[x,v]=i.useState("used"),[b,y]=i.useState(()=>rp(s)),[j,C]=i.useState(()=>op(s)),[A,N]=i.useState(null),[S,_]=i.useState(null),[T,M]=i.useState(null),E=i.useRef(null),L=i.useRef(null),F=i.useRef(e),R=i.useRef(!1),[P,O]=i.useState(()=>ap(s));i.useEffect(()=>{O(ap(s))},[s]),i.useEffect(()=>{if(!e||!h)return;const xe=L.current;if(!xe||typeof ResizeObserver>"u")return;let Se=null;const qe=new ResizeObserver(We=>{const Qe=We[0];if(!Qe)return;const{width:ve,height:Oe}=Qe.contentRect;ve<=0||Oe<=0||(Se&&clearTimeout(Se),Se=setTimeout(()=>{us(db,JSON.stringify({width:Math.round(ve),height:Math.round(Oe)}),s)},250))});return qe.observe(xe),()=>{Se&&clearTimeout(Se),qe.disconnect()}},[e,h,s]),i.useEffect(()=>{e||(R.current=!1)},[e]),i.useEffect(()=>{r.length>0&&(R.current=!0)},[r.length]),i.useEffect(()=>{if(typeof window>"u")return;const xe=window.matchMedia?.("(pointer: coarse)"),Se=()=>{f(window.innerWidth>=769),g(xe?.matches??!1)};return Se(),window.addEventListener("resize",Se),xe?.addEventListener?.("change",Se),()=>{window.removeEventListener("resize",Se),xe?.removeEventListener?.("change",Se)}},[]),i.useEffect(()=>{!F.current&&e&&(!c||Date.now()-c.getTime()>5e3)&&d(),F.current=e},[e,c,d]),i.useEffect(()=>{const xe=Zn("kb-usage-view-mode",s);if(xe==="used"||xe==="remaining"){v(xe);return}v("used")},[s]);const q=i.useCallback(xe=>{v(xe),us("kb-usage-view-mode",xe,s)},[s]);i.useEffect(()=>{y(rp(s)),C(op(s))},[s]),i.useEffect(()=>{eI(b,s)},[b,s]);const Z=i.useCallback((xe,Se)=>{y(qe=>{if(mb(xe,Se,qe)){const We=(qe[xe]??[]).filter(Qe=>Qe!==Se);if(We.length===0){const{[xe]:Qe,...ve}=qe;return ve}return{...qe,[xe]:We}}return{...qe,[xe]:[...qe[xe]??[],Se]}})},[]),z=i.useCallback(xe=>{y(Se=>{if(!Se[xe])return Se;const{[xe]:qe,...We}=Se;return We})},[]),k=i.useCallback(xe=>{if(j.length===0)return xe;const Se=new Map(xe.map(We=>[We.name,We])),qe=[];for(const We of j){const Qe=Se.get(We);Qe&&(qe.push(Qe),Se.delete(We))}return[...qe,...Se.values()]},[j]),I=i.useCallback((xe,Se)=>{xe.dataTransfer.effectAllowed="move",xe.dataTransfer.setData("text/plain",Se),N(Se)},[]),$=i.useCallback((xe,Se)=>{if(!A||A===Se)return;xe.preventDefault(),xe.dataTransfer.dropEffect="move";const{top:qe,height:We}=xe.currentTarget.getBoundingClientRect(),Qe=qe+We/2,ve=xe.clientY<Qe?"before":"after";_(Se),M(ve)},[A]),w=i.useCallback((xe,Se)=>{xe.preventDefault();const qe=A??xe.dataTransfer.getData("text/plain");if(!qe||qe===Se){_(null),M(null);return}const Qe=k(r).map(ae=>ae.name).filter(ae=>ae!==qe),ve=Qe.indexOf(Se);if(ve<0){_(null),M(null);return}const Oe=T==="after"?ve+1:ve;Qe.splice(Oe,0,qe),lp(Qe,s),C(Qe),_(null),M(null)},[A,T,s,r,k]),H=i.useCallback(()=>{N(null),_(null),M(null)},[]),K=i.useCallback((xe,Se)=>{const qe=k(r).map(ae=>ae.name),We=qe.indexOf(xe),Qe=We+Se;if(We<0||Qe<0||Qe>=qe.length)return;const ve=[...qe],[Oe]=ve.splice(We,1);ve.splice(Qe,0,Oe),lp(ve,s),C(ve)},[s,r,k]),pe=i.useCallback(async()=>{m(!0),await d(),m(!1)},[d]);i.useEffect(()=>{if(!e)return;const xe=Se=>{Se.key==="Escape"&&n()};return document.addEventListener("keydown",xe),()=>document.removeEventListener("keydown",xe)},[e,n]);const le=i.useCallback(xe=>{xe.target===xe.currentTarget&&n()},[n]);if(!e)return null;const B=!!(a&&h),ye=8,U=12,ne=P?.width??420,ee=B?Math.min((a?.bottom??0)+ye,window.innerHeight-U):void 0,ie=B?Math.max(8,(a?.right??0)-ne):void 0,ge=h&&P?{width:P.width,height:P.height}:{},se=k(r),Ae=t.jsxs("div",{ref:L,className:`usage-modal${B?" usage-modal--popover":" modal"}`,"data-testid":"usage-modal",style:B?{position:"fixed",top:ee,left:ie,...ge}:ge,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"usage-header",children:[t.jsx(Fs,{size:18,className:"usage-header-icon"}),t.jsx("h3",{children:"Usage"})]}),t.jsxs("div",{className:"usage-header-actions",children:[t.jsxs("div",{className:"usage-view-toggle",role:"group","aria-label":"Usage view mode",children:[t.jsx("button",{className:`usage-view-toggle-btn ${x==="used"?"active":""}`,onClick:()=>q("used"),"aria-pressed":x==="used","data-testid":"usage-view-toggle-used",children:"Used"}),t.jsx("button",{className:`usage-view-toggle-btn ${x==="remaining"?"active":""}`,onClick:()=>q("remaining"),"aria-pressed":x==="remaining","data-testid":"usage-view-toggle-remaining",children:"Remaining"})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close usage modal","data-testid":"usage-modal-close",children:t.jsx(Jt,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:E,children:(o||!R.current&&!l)&&r.length===0?t.jsx(iI,{}):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:pe,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:se.map((xe,Se)=>t.jsx(sI,{provider:xe,viewMode:x,hiddenWindows:b,onToggleWindow:Z,onShowAllHidden:z,isDragging:A===xe.name,isDragOver:S===xe.name,dragOverPosition:S===xe.name?T:null,onDragStart:qe=>I(qe,xe.name),onDragOver:qe=>$(qe,xe.name),onDragLeave:()=>{S===xe.name&&(_(null),M(null))},onDrop:qe=>w(qe,xe.name),onDragEnd:H,isTouchReorderMode:p,canMoveUp:Se>0,canMoveDown:Se<se.length-1,onMoveUp:()=>K(xe.name,-1),onMoveDown:()=>K(xe.name,1)},xe.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:pe,disabled:o||u,"data-testid":"usage-refresh-btn",children:[t.jsx(ns,{size:14,className:u?"spin":"",style:{marginRight:6}}),"Refresh"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]});return B?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"usage-popover-backdrop",onClick:n,"data-testid":"usage-modal-overlay"}),Ae]}):t.jsx("div",{className:"modal-overlay open",onClick:le,"data-testid":"usage-modal-overlay",children:Ae})}function hb(e){if(e<1e3)return`${e}ms`;const n=Math.floor(e/1e3);if(n<60)return`${n}s`;const s=Math.floor(n/60),a=n%60;if(s<60)return a>0?`${s}m ${a}s`:`${s}m`;const r=Math.floor(s/60),o=s%60;return o>0?`${r}h ${o}m`:`${r}h`}function hl(e){const n=Date.now(),s=new Date(e).getTime(),a=n-s;if(a<0){const r=Math.abs(a);return r<6e4?"in a moment":r<36e5?`in ${Math.floor(r/6e4)}m`:r<864e5?`in ${Math.floor(r/36e5)}h`:`in ${Math.floor(r/864e5)}d`}return a<6e4?"just now":a<36e5?`${Math.floor(a/6e4)}m ago`:a<864e5?`${Math.floor(a/36e5)}h ago`:`${Math.floor(a/864e5)}d ago`}const rI={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},pb={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},oI={cron:Jp,webhook:af,api:Yp,manual:Xn},lI={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},cI={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function dI({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(Ln,{size:12}):t.jsx(Vr,{size:12}),t.jsx("span",{children:e.success?"Success":"Failed"}),n>0&&t.jsx("span",{className:"schedule-run-duration",children:hb(n)})]})}function uI({result:e,index:n}){const[s,a]=i.useState(!1),r=e.completedAt&&e.startedAt?new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime():0;return t.jsxs("div",{className:"schedule-history-item",children:[t.jsxs("button",{className:"schedule-history-header",onClick:()=>a(!s),"aria-expanded":s,"aria-label":`Run #${n+1}: ${e.success?"succeeded":"failed"} ${hl(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx(Ln,{size:12}):t.jsx(Vr,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:hl(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:pb[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:hb(r)}),s?t.jsx(ri,{size:12}):t.jsx(un,{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 mI({routine:e,onEdit:n,onDelete:s,onRun:a,onToggle:r,running:o,lastRunOutput:l}){const[c,d]=i.useState(!1),{confirm:u}=qs(),m=i.useCallback(async()=>{await u({title:"Delete Routine",message:`Delete routine "${e.name}"? This cannot be undone.`,danger:!0})&&s(e)},[e,s,u]),h=rI[e.trigger.type],f=oI[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}),pb[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(vl,{size:10}):t.jsx(os,{size:10}),e.scope]})]}),e.description&&t.jsx("p",{className:"routine-card-description",children:e.description})]}),t.jsxs("div",{className:"routine-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>a(e),disabled:o,title:o?"Running…":"Run now","aria-label":o?"Running…":`Run ${e.name} now`,children:o?t.jsx(gt,{className:"spinner"}):t.jsx(Hn,{})}),t.jsx("button",{className:"btn-icon",onClick:()=>r(e),title:e.enabled?"Disable":"Enable","aria-label":e.enabled?`Disable ${e.name}`:`Enable ${e.name}`,"aria-pressed":e.enabled,children:e.enabled?t.jsx(ii,{}):t.jsx(Hn,{})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:"Edit","aria-label":`Edit ${e.name}`,children:t.jsx(xs,{})}),t.jsx("button",{className:"btn-icon",onClick:m,title:"Delete","aria-label":`Delete ${e.name}`,children:t.jsx(Cn,{})})]})]}),t.jsxs("div",{className:"routine-card-meta",children:[e.steps&&e.steps.length>0?t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(na,{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(_i,{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:lI[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:cI[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:hl(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:hl(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(dI,{result:e.lastRunResult}),t.jsxs("div",{className:"routine-meta-item",children:[t.jsx("span",{className:"routine-meta-label",children:"Runs:"}),t.jsx("span",{children:e.runCount})]})]}),l&&t.jsxs("div",{className:`routine-run-output ${l.success?"success":"failure"}`,children:[l.output&&t.jsx("pre",{className:"routine-run-output-text",children:l.output}),l.error&&t.jsx("div",{className:"routine-run-output-error",children:l.error})]}),e.runHistory.length>0&&t.jsxs("div",{className:"routine-card-history",children:[t.jsxs("button",{className:"schedule-history-toggle",onClick:()=>d(g=>!g),"aria-expanded":c,children:[c?t.jsx(ri,{size:12}):t.jsx(un,{size:12}),t.jsxs("span",{children:["Run History (",e.runHistory.length,")"]})]}),c&&t.jsxs("div",{className:"schedule-history-list",children:[e.runHistory.slice(0,10).map((g,x)=>t.jsx(uI,{result:g,index:x},`${g.startedAt}-${x}`)),e.runHistory.length>10&&t.jsxs("div",{className:"schedule-history-more",children:["…and ",e.runHistory.length-10," more"]})]})]})]})}function hI({type:e,size:n=12}){return e==="command"?t.jsxs("span",{className:"step-type-badge step-type-command",title:"Command step",children:[t.jsx(Mi,{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(Nv,{size:n}),t.jsx("span",{children:"Create Task"})]}):t.jsxs("span",{className:"step-type-badge step-type-ai-prompt",title:"AI Prompt step",children:[t.jsx(ms,{size:n}),t.jsx("span",{children:"AI Prompt"})]})}function Hc(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function pI(e){return e==="command"?{id:Hc(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:Hc(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:Hc(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function fI({step:e,onSave:n,onCancel:s}){const[a,r]=i.useState(e.name),[o,l]=i.useState(e.type),[c,d]=i.useState(e.command??""),[u,m]=i.useState(e.prompt??""),[h,f]=i.useState(e.modelProvider??""),[p,g]=i.useState(e.modelId??""),[x,v]=i.useState(e.taskTitle??""),[b,y]=i.useState(e.taskDescription??""),[j,C]=i.useState(e.taskColumn??"triage"),[A,N]=i.useState(e.timeoutMs),[S,_]=i.useState(e.continueOnFailure??!1),[T,M]=i.useState({}),[E,L]=i.useState([]),[F,R]=i.useState(!1),[P,O]=i.useState(null);i.useEffect(()=>{let I=!1;return R(!0),O(null),Ms().then($=>{I||L($.models)}).catch($=>{I||O($ instanceof Error?$.message:"Failed to load models")}).finally(()=>{I||R(!1)}),()=>{I=!0}},[]);const q=i.useCallback(()=>{const I={};return a.trim()||(I.name="Step name is required"),o==="command"&&!c.trim()&&(I.command="Command is required"),o==="ai-prompt"&&!u.trim()&&(I.prompt="Prompt is required"),o==="create-task"&&!b.trim()&&(I.taskDescription="Task description is required"),(o==="ai-prompt"||o==="create-task")&&(h||p)&&(!h||!p)&&(I.modelProvider="Both model provider and model ID must be set together"),A!==void 0&&A<1e3&&(I.timeoutMs="Timeout must be at least 1 second (1000ms)"),M(I),Object.keys(I).length===0},[a,o,c,u,b,h,p,A]),Z=h&&p?`${h}/${p}`:"",z=i.useCallback(I=>{if(!I)f(""),g("");else{const $=I.indexOf("/");$!==-1&&(f(I.slice(0,$)),g(I.slice($+1)))}},[]),k=i.useCallback(()=>{if(!q())return;const I={...e,name:a.trim(),type:o,command:o==="command"?c.trim():void 0,prompt:o==="ai-prompt"?u.trim():void 0,taskTitle:o==="create-task"&&x.trim()?x.trim():void 0,taskDescription:o==="create-task"&&b.trim()?b.trim():void 0,taskColumn:o==="create-task"?j:void 0,modelProvider:(o==="ai-prompt"||o==="create-task")&&h.trim()?h.trim():void 0,modelId:(o==="ai-prompt"||o==="create-task")&&p.trim()?p.trim():void 0,timeoutMs:A||void 0,continueOnFailure:S};o!=="ai-prompt"&&delete I.prompt,o!=="create-task"&&(delete I.taskTitle,delete I.taskDescription,delete I.taskColumn),n(I)},[q,n,e,a,o,c,u,x,b,j,h,p,A,S]);return t.jsxs("div",{className:"step-editor",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-name-${e.id}`,children:"Step Name"}),t.jsx("input",{id:`step-name-${e.id}`,type:"text",placeholder:"e.g. Run tests",value:a,onChange:I=>r(I.target.value),"aria-invalid":!!T.name}),T.name&&t.jsx("small",{className:"field-error",children:T.name})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-type-${e.id}`,children:"Step Type"}),t.jsxs("select",{id:`step-type-${e.id}`,value:o,onChange:I=>l(I.target.value),children:[t.jsx("option",{value:"command",children:"Command"}),t.jsx("option",{value:"ai-prompt",children:"AI Prompt"}),t.jsx("option",{value:"create-task",children:"Create Task"})]})]}),o==="command"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-command-${e.id}`,children:"Command"}),t.jsx("textarea",{id:`step-command-${e.id}`,placeholder:"e.g. npm test",value:c,onChange:I=>d(I.target.value),rows:2,"aria-invalid":!!T.command}),T.command&&t.jsx("small",{className:"field-error",children:T.command})]}),o==="ai-prompt"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-prompt-${e.id}`,children:"Prompt"}),t.jsx("textarea",{id:`step-prompt-${e.id}`,placeholder:"e.g. Summarize the test results and highlight any failures",value:u,onChange:I=>m(I.target.value),rows:3,"aria-invalid":!!T.prompt}),T.prompt&&t.jsx("small",{className:"field-error",children:T.prompt})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-model-${e.id}`,children:"Model (optional)"}),t.jsx(hs,{id:`step-model-${e.id}`,label:"Model",models:E,value:Z,onChange:z,placeholder:"Use default",disabled:F}),P&&t.jsx("small",{className:"field-error",children:P}),t.jsx("small",{children:"AI model for this step. Uses default if not selected."})]})]}),o==="create-task"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-title-${e.id}`,children:"Task Title (optional)"}),t.jsx("input",{id:`step-task-title-${e.id}`,type:"text",placeholder:"e.g. Review weekly dependencies",value:x,onChange:I=>v(I.target.value)}),t.jsx("small",{children:"Leave blank to auto-summarize from description"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-description-${e.id}`,children:"Task Description *"}),t.jsx("textarea",{id:`step-task-description-${e.id}`,placeholder:"e.g. Check all npm dependencies for security vulnerabilities and update outdated packages",value:b,onChange:I=>y(I.target.value),rows:4,"aria-invalid":!!T.taskDescription}),T.taskDescription&&t.jsx("small",{className:"field-error",children:T.taskDescription})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-column-${e.id}`,children:"Target Column"}),t.jsxs("select",{id:`step-task-column-${e.id}`,value:j,onChange:I=>C(I.target.value),children:[t.jsx("option",{value:"triage",children:"Triage"}),t.jsx("option",{value:"todo",children:"To Do"})]}),t.jsx("small",{children:"Column where the new task will be created"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-model-${e.id}`,children:"Executor Model (optional)"}),t.jsx(hs,{id:`step-task-model-${e.id}`,label:"Model",models:E,value:Z,onChange:z,placeholder:"Use default",disabled:F}),P&&t.jsx("small",{className:"field-error",children:P}),T.modelProvider&&t.jsx("small",{className:"field-error",children:T.modelProvider}),t.jsx("small",{children:"AI model for executing the created task. Uses default if not selected."})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-timeout-${e.id}`,children:"Timeout (ms, optional)"}),t.jsx("input",{id:`step-timeout-${e.id}`,type:"number",min:1e3,step:1e3,placeholder:"Override schedule timeout",value:A??"",onChange:I=>N(I.target.value?Number(I.target.value):void 0),"aria-invalid":!!T.timeoutMs}),T.timeoutMs&&t.jsx("small",{className:"field-error",children:T.timeoutMs})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:`step-continue-${e.id}`,className:"checkbox-label",children:[t.jsx("input",{id:`step-continue-${e.id}`,type:"checkbox",checked:S,onChange:I=>_(I.target.checked)}),"Continue on failure"]}),t.jsx("small",{children:"If checked, the next step will run even if this one fails"})]}),t.jsxs("div",{className:"step-editor-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:k,children:"Save Step"})]})]})}function gI({steps:e,onChange:n,onEditingChange:s}){const[a,r]=i.useState(null);i.useEffect(()=>{s?.(a!==null)},[a,s]);const o=i.useCallback(u=>{const m=pI(u);n([...e,m]),r(m.id)},[e,n]),l=i.useCallback(u=>{n(e.filter(m=>m.id!==u)),a===u&&r(null)},[e,n,a]),c=i.useCallback((u,m)=>{const h=e.findIndex(g=>g.id===u);if(h<0)return;const f=m==="up"?h-1:h+1;if(f<0||f>=e.length)return;const p=[...e];[p[h],p[f]]=[p[f],p[h]],n(p)},[e,n]),d=i.useCallback(u=>{n(e.map(m=>m.id===u.id?u:m)),r(null)},[e,n]);return t.jsxs("div",{className:"steps-editor",children:[t.jsx("div",{className:"steps-editor-header",children:t.jsxs("span",{className:"steps-editor-title",children:["Steps (",e.length,")"]})}),e.length===0&&t.jsx("div",{className:"steps-empty-state",children:t.jsx("p",{children:"No steps added yet. Add a command or AI prompt step to get started."})}),t.jsx("div",{className:"steps-list",children:e.map((u,m)=>t.jsx("div",{className:"step-card",children:a===u.id?t.jsx(fI,{step:u,onSave:d,onCancel:()=>r(null)}):t.jsxs("div",{className:"step-card-row",children:[t.jsx("div",{className:"step-card-drag",children:t.jsx(wl,{size:14})}),t.jsx("span",{className:"step-card-index",children:m+1}),t.jsx(hI,{type:u.type}),t.jsx("span",{className:"step-card-name",children:u.name}),u.continueOnFailure&&t.jsx("span",{className:"step-card-flag",title:"Continues on failure",children:"⚡"}),t.jsxs("div",{className:"step-card-actions",children:[t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>c(u.id,"up"),disabled:m===0,title:"Move up","aria-label":`Move ${u.name} up`,children:t.jsx(ri,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>c(u.id,"down"),disabled:m===e.length-1,title:"Move down","aria-label":`Move ${u.name} down`,children:t.jsx(un,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(u.id),title:"Edit","aria-label":`Edit ${u.name}`,children:t.jsx(xs,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>l(u.id),title:"Delete","aria-label":`Delete ${u.name}`,children:t.jsx(Cn,{})})]})]})},u.id))}),t.jsxs("div",{className:"steps-add-buttons",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("command"),children:[t.jsx(Sn,{size:14}),"Add Command Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ai-prompt"),children:[t.jsx(Sn,{size:14}),"Add AI Prompt Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("create-task"),children:[t.jsx(Sn,{size:14}),"Add Create Task Step"]})]})]})}const fb={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},bI={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function xI(e){const n=e.trim();for(const[s,a]of Object.entries(fb))if(a===n)return s;return"custom"}function vI(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function yI(e,n,s,a,r){switch(e){case"cron":return{type:"cron",cronExpression:n};case"webhook":return{type:"webhook",webhookPath:s||"/trigger/"+Math.random().toString(36).slice(2,10),secret:a||void 0};case"api":return{type:"api",endpoint:r||"/api/routine/"+Math.random().toString(36).slice(2,10)};case"manual":return{type:"manual"}}}function wI(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 kI=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],jI=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function cp(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function dp({routine:e,onSubmit:n,onCancel:s,scope:a,projectId:r,onScopeChange:o}){const l=!!e,c=e?wI(e):{triggerType:"cron",cronExpression:"0 * * * *",webhookPath:"",webhookSecret:"",endpoint:""},[d,u]=i.useState(e?.name??""),[m,h]=i.useState(e?.description??""),[f,p]=i.useState(c.triggerType),[g,x]=i.useState(c.cronExpression),[v,b]=i.useState(()=>c.triggerType!=="cron"?"custom":xI(c.cronExpression)),[y,j]=i.useState(c.webhookPath),[C,A]=i.useState(c.webhookSecret),[N,S]=i.useState(c.endpoint),[_,T]=i.useState(e?.executionPolicy??"queue"),[M,E]=i.useState(e?.catchUpPolicy??"run_one"),[L,F]=i.useState(e?.enabled??!0),R=e?.steps&&e.steps.length===1&&e.steps[0].type==="ai-prompt"&&!e.command,P=e?.steps&&e.steps.length===1&&e.steps[0].type==="create-task"&&!e.command,[O,q]=i.useState(e?.steps&&e.steps.length>0&&!R&&!P?"advanced":"simple"),[Z,z]=i.useState(()=>R?"ai-prompt":P?"create-task":"command"),[k,I]=i.useState(e?.command??""),[$,w]=i.useState(e?.steps??[]),[H,K]=i.useState(!1),[pe,le]=i.useState(e?.timeoutMs??3e5),[B,ye]=i.useState(R?e.steps?.[0]?.prompt??"":""),[U,te]=i.useState(P?e.steps?.[0]?.taskTitle??"":""),[ne,ee]=i.useState(P?e.steps?.[0]?.taskDescription??"":""),[ie,ge]=i.useState(P?e.steps?.[0]?.taskColumn??"triage":"triage"),[se,Ae]=i.useState(R||P?e.steps?.[0]?.modelProvider??"":""),[xe,Se]=i.useState(R||P?e.steps?.[0]?.modelId??"":""),[qe,We]=i.useState([]),[Qe,ve]=i.useState(!1),[Oe,ae]=i.useState(null),[re,je]=i.useState(a??"global"),[Q,Fe]=i.useState({}),[Je,be]=i.useState(!1),ze=i.useRef(!0);i.useEffect(()=>()=>{ze.current=!1},[]),i.useEffect(()=>{a&&je(a)},[a]),i.useEffect(()=>{let Re=!1;return ve(!0),ae(null),Ms().then(xt=>{Re||We(xt.models)}).catch(xt=>{Re||ae(xt instanceof Error?xt.message:"Failed to load models")}).finally(()=>{Re||ve(!1)}),()=>{Re=!0}},[]);const tt=se&&xe?`${se}/${xe}`:"",kt=i.useCallback(Re=>{if(!Re){Ae(""),Se("");return}const xt=Re.indexOf("/");xt!==-1&&(Ae(Re.slice(0,xt)),Se(Re.slice(xt+1)))},[]),ke=i.useCallback(()=>{const Re={};if(d.trim()||(Re.name="Name is required"),re==="project"&&!r&&(Re.scope="Project-specific entries require an active project."),f==="cron"&&v==="custom"&&(g.trim()?vI(g)||(Re.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):Re.cronExpression="Cron expression is required"),f==="webhook"&&!y.trim()&&(Re.webhookPath="Webhook path is required"),f==="api"&&!N.trim()&&(Re.endpoint="API endpoint is required"),O==="simple")Z==="command"&&!k.trim()&&(Re.command="Command is required"),Z==="ai-prompt"&&!B.trim()&&(Re.prompt="Prompt is required"),Z==="create-task"&&!ne.trim()&&(Re.taskDescription="Task description is required"),(se.trim()&&!xe.trim()||!se.trim()&&xe.trim())&&(Re.model="Both model provider and model ID must be set, or both must be empty");else{$.length===0&&(Re.steps="At least one step is required"),H&&(Re.stepsEditing="Please save or cancel all step edits before saving the routine");const xt=[];$.forEach((Pt,Ct)=>{Pt.name?.trim()||xt.push(`Step ${Ct+1}: Name is required`),Pt.type==="command"&&!Pt.command?.trim()&&xt.push(`Step ${Ct+1}: Command is required`),Pt.type==="ai-prompt"&&!Pt.prompt?.trim()&&xt.push(`Step ${Ct+1}: Prompt is required`),Pt.type==="create-task"&&!Pt.taskDescription?.trim()&&xt.push(`Step ${Ct+1}: Task description is required`)}),xt.length>0&&(Re.steps=xt.join("; "))}return pe<1e3&&(Re.timeoutMs="Timeout must be at least 1 second (1000ms)"),Fe(Re),Object.keys(Re).length===0},[d,f,g,v,y,N,re,r,O,Z,k,B,ne,se,xe,$,H,pe]),ce=i.useCallback(async Re=>{if(Re.preventDefault(),!!ke()){be(!0);try{let xt=e?.scope??re??(r?"project":"global");xt==="project"&&!r&&(xt="global");const Pt=yI(f,g,y,C,N);let Ct,Ot;O==="simple"?Z==="command"?Ct=k.trim()||void 0:Z==="ai-prompt"?Ot=[{id:cp(),type:"ai-prompt",name:d.trim(),prompt:B.trim(),modelProvider:se.trim()||void 0,modelId:xe.trim()||void 0}]:Ot=[{id:cp(),type:"create-task",name:d.trim(),taskTitle:U.trim()||void 0,taskDescription:ne.trim(),taskColumn:ie,modelProvider:se.trim()||void 0,modelId:xe.trim()||void 0}]:Ot=$;const zt={name:d.trim(),agentId:e?.agentId??"",description:m.trim()||void 0,trigger:Pt,command:Ct,steps:Ot,timeoutMs:pe,executionPolicy:_,catchUpPolicy:M,enabled:L,scope:xt};await n(zt)}finally{ze.current&&be(!1)}}},[ke,n,d,m,f,g,y,C,N,O,Z,k,B,se,xe,U,ne,ie,$,pe,_,M,L,re,r,e?.scope,e?.agentId]),Te="routine-name-error",he="routine-cron-error",Le="routine-webhook-error",st="routine-endpoint-error",it="routine-command-error",lt="routine-prompt-error",$e="routine-task-description-error",Ue="routine-model-error",Xe="routine-timeout-error",wt=i.useCallback(Re=>{b(Re),Re!=="custom"&&x(fb[Re])},[]);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:d,onChange:Re=>u(Re.target.value),"aria-invalid":!!Q.name,"aria-describedby":Q.name?Te:void 0}),Q.name&&t.jsx("small",{id:Te,className:"field-error",children:Q.name})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-description",children:"Description (optional)"}),t.jsx("textarea",{id:"routine-description",placeholder:"What does this routine do?",value:m,onChange:Re=>h(Re.target.value),rows:2})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Scope"}),t.jsxs("div",{className:"routine-scope-toggle",role:"radiogroup","aria-label":"Routine scope",children:[t.jsxs("button",{type:"button",className:`routine-scope-btn${re==="global"?" active":""}`,onClick:()=>{je("global"),o?.("global")},role:"radio","aria-checked":re==="global"?"true":"false",disabled:!!e?.scope,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:"Global scope",children:[t.jsx(vl,{size:12}),"Global"]}),t.jsxs("button",{type:"button",className:`routine-scope-btn${re==="project"?" active":""}`,onClick:()=>{je("project"),o?.("project")},role:"radio","aria-checked":re==="project"?"true":"false",disabled:!!e?.scope||!r,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:r?"Project scope":"Select a project to enable project scope",children:[t.jsx(os,{size:12}),"Project"]})]}),t.jsx("small",{children:!r&&!e?.scope?"No active project. Routines will be created at global scope.":re==="project"&&r?"This routine will be scoped to the current project.":"This routine will be created at global scope."}),Q.scope&&t.jsx("small",{className:"field-error",children:Q.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(Jp,{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(af,{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(Yp,{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(Xn,{size:14}),"Manual"]})]})]}),f==="cron"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-frequency",children:"Frequency"}),t.jsx("select",{id:"routine-frequency",value:v,onChange:Re=>wt(Re.target.value),children:Object.entries(bI).map(([Re,xt])=>t.jsx("option",{value:Re,children:xt},Re))}),t.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),t.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:g,onChange:Re=>x(Re.target.value),disabled:v!=="custom","aria-invalid":!!Q.cronExpression,"aria-describedby":Q.cronExpression?he:void 0}),Q.cronExpression?t.jsx("small",{id:he,className:"field-error",children:Q.cronExpression}):t.jsx("small",{children:v==="custom"?t.jsxs(t.Fragment,{children:["min hour day month weekday — ",t.jsx("a",{href:"https://crontab.guru",target:"_blank",rel:"noopener noreferrer",children:"crontab.guru"})]}):`Auto-filled from preset: ${g}`})]}),f==="webhook"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-path",children:"Webhook Path"}),t.jsx("input",{id:"routine-webhook-path",type:"text",placeholder:"/trigger/my-routine",value:y,onChange:Re=>j(Re.target.value),"aria-invalid":!!Q.webhookPath,"aria-describedby":Q.webhookPath?Le:void 0}),Q.webhookPath?t.jsx("small",{id:Le,className:"field-error",children:Q.webhookPath}):t.jsx("small",{children:"URL path for the webhook endpoint"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-secret",children:"Webhook Secret (optional)"}),t.jsx("input",{id:"routine-webhook-secret",type:"password",placeholder:"Optional — leave empty for unauthenticated webhooks",value:C,onChange:Re=>A(Re.target.value)}),t.jsx("small",{children:"HMAC secret for signature verification. Leave empty for unauthenticated webhooks."})]})]}),f==="api"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-endpoint",children:"API Endpoint"}),t.jsx("input",{id:"routine-endpoint",type:"text",placeholder:"/api/routine/my-routine",value:N,onChange:Re=>S(Re.target.value),"aria-invalid":!!Q.endpoint,"aria-describedby":Q.endpoint?st:void 0}),Q.endpoint?t.jsx("small",{id:st,className:"field-error",children:Q.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${O==="simple"?" active":""}`,onClick:()=>q("simple"),role:"radio","aria-checked":O==="simple",children:"Simple"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${O==="advanced"?" active":""}`,onClick:()=>q("advanced"),role:"radio","aria-checked":O==="advanced",children:"Multi-Step"})]}),t.jsx("small",{children:O==="simple"?"Run one command, prompt, or task creation action":"Run multiple actions sequentially"})]}),O==="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${Z==="command"?" active":""}`,onClick:()=>z("command"),role:"radio","aria-checked":Z==="command",children:"Command"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${Z==="ai-prompt"?" active":""}`,onClick:()=>z("ai-prompt"),role:"radio","aria-checked":Z==="ai-prompt",children:"AI Prompt"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${Z==="create-task"?" active":""}`,onClick:()=>z("create-task"),role:"radio","aria-checked":Z==="create-task",children:"Create Task"})]})]}),Z==="command"?t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-command",children:"Command"}),t.jsx("input",{id:"routine-command",type:"text",placeholder:"e.g. npx runfusion.ai backup --create",value:k,onChange:Re=>I(Re.target.value),"aria-invalid":!!Q.command,"aria-describedby":Q.command?it:void 0}),Q.command?t.jsx("small",{id:it,className:"field-error",children:Q.command}):t.jsx("small",{children:"Shell command to execute."})]}):Z==="ai-prompt"?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-prompt",children:"Prompt"}),t.jsx("textarea",{id:"routine-prompt",placeholder:"e.g. Summarize recent activity and create action items",value:B,onChange:Re=>ye(Re.target.value),rows:3,"aria-invalid":!!Q.prompt,"aria-describedby":Q.prompt?lt:void 0}),Q.prompt?t.jsx("small",{id:lt,className:"field-error",children:Q.prompt}):t.jsx("small",{children:"AI prompt to execute."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-model",children:"Model (optional)"}),t.jsx(hs,{id:"routine-model",label:"Model",models:qe,value:tt,onChange:kt,placeholder:"Use default",disabled:Qe}),Oe&&t.jsx("small",{className:"field-error",children:Oe}),Q.model&&t.jsx("small",{id:Ue,className:"field-error",children:Q.model})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-title",children:"Task Title (optional)"}),t.jsx("input",{id:"routine-task-title",type:"text",placeholder:"e.g. Review weekly dependencies",value:U,onChange:Re=>te(Re.target.value)})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-description",children:"Task Description"}),t.jsx("textarea",{id:"routine-task-description",placeholder:"e.g. Check npm dependencies for security vulnerabilities",value:ne,onChange:Re=>ee(Re.target.value),rows:4,"aria-invalid":!!Q.taskDescription,"aria-describedby":Q.taskDescription?$e:void 0}),Q.taskDescription?t.jsx("small",{id:$e,className:"field-error",children:Q.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:ie,onChange:Re=>ge(Re.target.value),children:[t.jsx("option",{value:"triage",children:"Triage"}),t.jsx("option",{value:"todo",children:"To Do"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-model",children:"Executor Model (optional)"}),t.jsx(hs,{id:"routine-task-model",label:"Executor Model",models:qe,value:tt,onChange:kt,placeholder:"Use default",disabled:Qe}),Oe&&t.jsx("small",{className:"field-error",children:Oe}),Q.model&&t.jsx("small",{id:Ue,className:"field-error",children:Q.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(gI,{steps:$,onChange:w,onEditingChange:K}),Q.steps&&t.jsx("small",{className:"field-error",children:Q.steps}),Q.stepsEditing&&t.jsx("small",{className:"field-error",children:Q.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:pe,onChange:Re=>le(Number(Re.target.value)),"aria-invalid":!!Q.timeoutMs,"aria-describedby":Q.timeoutMs?Xe:void 0}),Q.timeoutMs?t.jsx("small",{id:Xe,className:"field-error",children:Q.timeoutMs}):t.jsx("small",{children:"Maximum execution time in milliseconds."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-execution-policy",children:"Execution Policy"}),t.jsx("select",{id:"routine-execution-policy",value:_,onChange:Re=>T(Re.target.value),children:kI.map(Re=>t.jsx("option",{value:Re.value,children:Re.label},Re.value))}),t.jsx("small",{children:"How to handle concurrent executions of this routine"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-catchup-policy",children:"Catch-up Policy"}),t.jsx("select",{id:"routine-catchup-policy",value:M,onChange:Re=>E(Re.target.value),children:jI.map(Re=>t.jsx("option",{value:Re.value,children:Re.label},Re.value))}),t.jsx("small",{children:"What to do when a scheduled run is missed"})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:"routine-enabled",className:"checkbox-label",children:[t.jsx("input",{id:"routine-enabled",type:"checkbox",checked:L,onChange:Re=>F(Re.target.checked)}),"Enabled"]}),t.jsx("small",{children:"When disabled, the routine will not run automatically"})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,disabled:Je,children:"Cancel"}),t.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:Je,children:Je?"Saving…":l?"Save Changes":"Create Routine"})]})]})}const NI=3e4;function SI({onClose:e,addToast:n,projectId:s}){const[a,r]=i.useState(()=>s?"project":"global"),[o,l]=i.useState([]),[c,d]=i.useState("list"),[u,m]=i.useState(),[h,f]=i.useState(null),[p,g]=i.useState({}),x=i.useRef(null);wi(x,!0,"fusion:automation-modal-size");const v=i.useMemo(()=>({scope:a,projectId:a==="project"?s:void 0}),[a,s]),b=i.useCallback(async()=>{try{const R=await Kk(v);l(R),g(P=>{const O={...P};for(const q of R){const Z=O[q.id];if(!Z||!q.lastRunResult)continue;const z=q.lastRunResult;z.success===Z.success&&(z.output||"")===Z.output&&(z.error||"")===(Z.error||"")&&delete O[q.id]}return O})}catch(R){n(_e(R)||"Failed to load routines","error")}},[n,v]);i.useEffect(()=>{b()},[b]),i.useEffect(()=>{const R=setInterval(()=>{b()},NI);return()=>clearInterval(R)},[b]),i.useEffect(()=>{const R=P=>{P.key==="Escape"&&(c!=="list"?(d("list"),m(void 0)):e())};return document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)},[e,c]);const y=Ri(e),j=i.useCallback(async R=>{try{await Gk(R,v),n("Routine created","success"),d("list"),await b()}catch(P){n(_e(P)||"Failed to create routine","error")}},[n,b,v]),C=i.useCallback(R=>{m(R),d("edit")},[]),A=i.useCallback(async R=>{if(u)try{await zu(u.id,R,v),n("Routine updated","success"),d("list"),m(void 0),await b()}catch(P){n(_e(P)||"Failed to update routine","error")}},[u,n,b,v]),N=i.useCallback(async R=>{try{await Jk(R.id,v),n(`Deleted "${R.name}"`,"success"),await b()}catch(P){n(_e(P)||"Failed to delete routine","error")}},[n,b,v]),S=i.useCallback(async R=>{f(R.id);try{const{result:P}=await Yk(R.id,v);g(O=>({...O,[R.id]:{output:P.output||"",error:P.error,success:P.success}})),P.success?n(`"${R.name}" completed successfully`,"success"):n(`"${R.name}" failed: ${P.error||"Unknown error"}`,"error"),await b()}catch(P){n(_e(P)||"Failed to run routine","error")}finally{f(null)}},[n,b,v]),_=i.useCallback(async R=>{try{await zu(R.id,{enabled:!R.enabled},v),n(`"${R.name}" ${R.enabled?"disabled":"enabled"}`,"success"),await b()}catch(P){n(_e(P)||"Failed to toggle routine","error")}},[n,b,v]),T=i.useCallback(()=>{d("list"),m(void 0)},[]);i.useEffect(()=>{c!=="list"&&g({})},[c]);const M=i.useCallback(R=>{r(R),d("list"),m(void 0),g({})},[]),E=()=>c==="create"?t.jsx(dp,{onSubmit:j,onCancel:T,scope:a,projectId:s}):c==="edit"&&u?t.jsx(dp,{routine:u,onSubmit:A,onCancel:T,scope:a,projectId:s}):o.length===0?t.jsxs("div",{className:"routine-empty-state",children:[t.jsx(Xn,{size:48,strokeWidth:1}),t.jsx("h4",{children:"No automations yet"}),t.jsx("p",{children:"Create an automation with a schedule, webhook, API, or manual trigger."}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>d("create"),children:[t.jsx(Sn,{size:14}),"Create your first automation"]})]}):t.jsx("div",{className:"routine-list",children:o.map(R=>t.jsx(mI,{routine:R,onEdit:C,onDelete:N,onRun:S,onToggle:_,running:h===R.id,lastRunOutput:p[R.id]??null},R.id))}),L=()=>E(),F=c==="list"&&o.length>0;return t.jsx("div",{className:"modal-overlay open",...y,children:t.jsxs("div",{ref:x,className:"modal modal-lg automation-modal",role:"dialog","aria-modal":"true","aria-labelledby":"schedules-modal-title",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(Xn,{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(Jt,{size:20})})]}),t.jsxs("div",{className:"scheduling-toolbar","aria-live":"polite",children:[t.jsxs("div",{className:"scheduling-toolbar-left",role:"group","aria-label":"Scheduling scope",children:[t.jsxs("div",{className:"scheduling-scope-selector",children:[t.jsxs("button",{type:"button",className:`scope-btn${a==="global"?" active":""}`,onClick:()=>M("global"),"aria-pressed":a==="global",title:"Global (user-level) automations",children:[t.jsx(vl,{size:14}),"Global"]}),t.jsxs("button",{type:"button",className:`scope-btn${a==="project"?" active":""}`,onClick:()=>M("project"),"aria-pressed":a==="project",title:"Project-scoped automations",children:[t.jsx(os,{size:14}),"Project"]})]}),t.jsxs("span",{className:"scheduling-count",children:[t.jsx(Xn,{size:14}),o.length," automation",o.length===1?"":"s"]})]}),t.jsx("div",{className:"scheduling-toolbar-right",children:F&&t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>d("create"),"aria-label":"Create new automation",children:[t.jsx(Sn,{size:14}),"New Automation"]})})]}),t.jsx("div",{className:"schedule-modal-content",id:"scheduled-tasks-content",children:L()})]})})}const CI=3e4,Td=new Map,qc=new Map;function up(e){return e??"default"}function mp(e){const n=Td.get(e);return n?Date.now()>=n.expiresAt?(Td.delete(e),null):n:null}function EI(e,n){const s=e.some(r=>r.id!=="github"&&r.authenticated),a=e.some(r=>r.id==="github"&&r.authenticated)||(n?.authenticated??!1);return{hasAiProvider:s,hasGithub:a}}async function MI(e){const n=qc.get(e);if(n)return n;const s=Dr().then(({providers:a,ghCli:r})=>{const l={...EI(a,r),ghCli:r,expiresAt:Date.now()+CI};return Td.set(e,l),l}).finally(()=>{qc.delete(e)});return qc.set(e,s),s}function gb(e){const n=up(e),s=mp(n),[a,r]=i.useState(s?.hasAiProvider??!1),[o,l]=i.useState(s?.hasGithub??!1),[,c]=i.useState(s?.ghCli),[d,u]=i.useState(s==null),m=i.useRef(!!s);return i.useEffect(()=>{let h=!1;const f=up(e),p=mp(f);if(p)return r(p.hasAiProvider),l(p.hasGithub),c(p.ghCli),u(!1),m.current=!0,()=>{h=!0};m.current=!1;async function g(){!m.current&&u(!0);try{const v=await MI(f);if(h)return;r(v.hasAiProvider),l(v.hasGithub),c(v.ghCli)}catch{}finally{h||(m.current=!0,u(!1))}}return g(),()=>{h=!0}},[e]),i.useMemo(()=>({hasAiProvider:a,hasGithub:o,loading:d,hasWarnings:!a||!o}),[a,o,d])}function bb({hasAiProvider:e,hasGithub:n,compact:s=!1,onDismiss:a}){if(e&&n)return null;const r=a?t.jsx("button",{type:"button",className:"setup-warning-banner__dismiss touch-target","aria-label":"Dismiss setup warning",onClick:a,children:t.jsx(Jt,{size:16,"aria-hidden":"true"})}):null;if(s)return t.jsxs("div",{className:`setup-warning-banner setup-warning-banner--compact${a?" setup-warning-banner--dismissible":""}`,role:"status","aria-live":"polite",children:[t.jsx("p",{className:"setup-warning-banner__compact-text",children:"⚠ Setup incomplete — AI and/or GitHub features will be limited."}),r]});const o=[];return e||o.push({key:"ai",title:"No AI provider connected",description:"AI agents won't be able to work on tasks until you connect a provider. Set one up in Settings → AI Setup."}),n||o.push({key:"github",title:"GitHub not connected",description:"You won't be able to import issues from GitHub, but you can still create tasks manually."}),t.jsxs("div",{className:`setup-warning-banner${a?" setup-warning-banner--dismissible":""}`,role:"status","aria-live":"polite",children:[r,o.map(l=>t.jsxs("div",{className:"setup-warning-banner__item",children:[t.jsx("strong",{className:"setup-warning-banner__title",children:l.title}),t.jsx("p",{className:"setup-warning-banner__description",children:l.description})]},l.key))]})}function _I({isOpen:e,onClose:n,projectId:s,tasks:a,onCreateTask:r,addToast:o,onPlanningMode:l,onSubtaskBreakdown:c}){const{confirm:d}=qs(),[u,m]=i.useState(""),[h,f]=i.useState([]),[p,g]=i.useState([]),[x,v]=i.useState(!1),[b,y]=i.useState(""),[j,C]=i.useState(""),[A,N]=i.useState(""),[S,_]=i.useState(""),[T,M]=i.useState(""),[E,L]=i.useState("default"),[F,R]=i.useState(!1),[P,O]=i.useState([]),[q,Z]=i.useState(!1),[z,k]=i.useState(void 0),[I,$]=i.useState(Cs),[w,H]=i.useState(void 0),[K,pe]=i.useState(null),[le,B]=i.useState([]),[ye,U]=i.useState(!1),[te,ne]=i.useState(!1),ee=i.useRef(null),[ie,ge]=i.useState(!1),[se,Ae]=i.useState(""),xe=i.useRef(null),{hasAiProvider:Se,hasGithub:qe,loading:We}=gb(s),{nodes:Qe}=Al(),ve=i.useCallback(ke=>{Z(!0),O(ke)},[]),Oe=i.useCallback(()=>{Z(!1)},[]),ae=i.useCallback(async()=>{if(le.length>0){U(!0);return}ne(!0);try{const ke=await da(void 0,s);B(ke),U(!0)}catch(ke){const ce=_e(ke);o(ce?`Failed to load agents: ${ce}`:"Failed to load agents","error"),U(!1)}finally{ne(!1)}},[le.length,s,o]);i.useEffect(()=>{if(!ye)return;const ke=ce=>{ee.current&&!ee.current.contains(ce.target)&&U(!1)};return document.addEventListener("mousedown",ke),()=>document.removeEventListener("mousedown",ke)},[ye]),i.useEffect(()=>{if(!ie)return;const ke=ce=>{xe.current&&!xe.current.contains(ce.target)&&(ge(!1),Ae(""))};return document.addEventListener("mousedown",ke),()=>document.removeEventListener("mousedown",ke)},[ie]);const re=a.filter(ke=>!h.includes(ke.id)).sort((ke,ce)=>{const Te=ce.createdAt.localeCompare(ke.createdAt);if(Te!==0)return Te;const he=parseInt(ke.id.slice(ke.id.lastIndexOf("-")+1),10)||0;return(parseInt(ce.id.slice(ce.id.lastIndexOf("-")+1),10)||0)-he}),je=se?re.filter(ke=>ke.id.toLowerCase().includes(se.toLowerCase())||ke.title&&ke.title.toLowerCase().includes(se.toLowerCase())||ke.description&&ke.description.toLowerCase().includes(se.toLowerCase())):re,Q=(ke,ce)=>ke.length>ce?ke.slice(0,ce)+"…":ke;i.useEffect(()=>{const ke=u.trim()!==""||h.length>0||p.length>0||b!==""||j!==""||A!==""||S!==""||P.length>0||K!==null||z!==void 0||I!==Cs||w!==void 0;R(ke)},[u,h,p,b,j,A,S,P,K,z,I,w]);const Fe=i.useCallback(async()=>{F&&!await d({title:"Discard Changes",message:"You have unsaved changes. Discard them?",danger:!0})||(p.forEach(ke=>URL.revokeObjectURL(ke.previewUrl)),g([]),m(""),f([]),y(""),C(""),N(""),_(""),M(""),L("default"),O([]),Z(!1),pe(null),U(!1),k(void 0),$(Cs),H(void 0),R(!1),n())},[F,n,p,d]),Je=i.useCallback(async()=>{const ke=u.trim();if(!(!ke||x)){v(!0);try{const ce=b.indexOf("/"),Te=j.indexOf("/"),he=A.indexOf("/"),Le=await r({title:void 0,description:ke,column:"triage",dependencies:h.length?h:void 0,enabledWorkflowSteps:q?P.length>0?P:[]:void 0,...K?{assignedAgentId:K}:{},modelPresetId:E==="preset"&&T||void 0,modelProvider:b&&ce!==-1?b.slice(0,ce):void 0,modelId:b&&ce!==-1?b.slice(ce+1):void 0,validatorModelProvider:j&&Te!==-1?j.slice(0,Te):void 0,validatorModelId:j&&Te!==-1?j.slice(Te+1):void 0,planningModelProvider:A&&he!==-1?A.slice(0,he):void 0,planningModelId:A&&he!==-1?A.slice(he+1):void 0,thinkingLevel:S!==""?S:void 0,reviewLevel:z,priority:I,nodeId:w});if(p.length>0){const st=[];for(const it of p)try{await $r(Le.id,it.file,s)}catch{st.push(it.file.name)}st.length>0&&o(`Failed to upload: ${st.join(", ")}`,"error")}p.forEach(st=>URL.revokeObjectURL(st.previewUrl)),g([]),m(""),f([]),y(""),C(""),N(""),_(""),M(""),L("default"),O([]),Z(!1),pe(null),U(!1),k(void 0),$(Cs),H(void 0),o(`Created ${Le.id}`,"success"),n()}catch(ce){o(_e(ce)||"Failed to create task","error")}finally{v(!1)}}},[u,h,p,b,j,A,S,x,r,o,n,s,E,T,P,q,K,z,I,w]),be=i.useCallback(ke=>{ke.key==="Escape"&&(ke.preventDefault(),Fe())},[Fe]),tt=(K?le.find(ke=>ke.id===K):void 0)?.name??K,kt=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:xe,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>ge(ke=>!ke),disabled:x,"data-testid":"dep-trigger",children:h.length>0?`${h.length} selected`:"Add dependencies"}),ie&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:se,onChange:ke=>Ae(ke.target.value),onClick:ke=>ke.stopPropagation()}),je.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):je.map(ke=>t.jsxs("div",{className:`dep-dropdown-item${h.includes(ke.id)?" selected":""}`,onClick:()=>{f(h.includes(ke.id)?h.filter(ce=>ce!==ke.id):[...h,ke.id]),ge(!1),Ae("")},onMouseDown:ce=>ce.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:ke.id}),t.jsx("span",{className:"dep-dropdown-title",children:Q(ke.title||ke.description||ke.id,30)})]},ke.id))]})]}),h.length>0&&t.jsx("div",{className:"selected-deps",children:h.map(ke=>t.jsxs("span",{className:"dep-chip",children:[ke,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>f(h.filter(ce=>ce!==ke)),disabled:x,children:"×"})]},ke))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Assign Agent"}),t.jsxs("div",{className:"agent-trigger-wrap",ref:ee,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{ye?U(!1):ae()},disabled:x,"data-testid":"new-task-agent-button",children:[t.jsx(Rn,{size:12,style:{verticalAlign:"middle"}}),tt?` ${tt}`:" Assign agent"]}),ye&&t.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:ke=>ke.preventDefault(),children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),te&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!te&&le.filter(ke=>ke.state!=="terminated").map(ke=>t.jsxs("div",{className:`dep-dropdown-item${K===ke.id?" selected":""}`,onMouseDown:ce=>ce.preventDefault(),onClick:()=>{pe(ke.id===K?null:ke.id),U(!1)},"data-testid":`agent-option-${ke.id}`,children:[t.jsx(Rn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:ke.role}),t.jsx("span",{className:"dep-dropdown-title",children:ke.name})]},ke.id)),!te&&le.filter(ke=>ke.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),K&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:ke=>ke.preventDefault(),onClick:()=>{pe(null),U(!1)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return e?t.jsx("div",{className:"modal-overlay open",onClick:Fe,onKeyDown:be,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:ke=>ke.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:"New Task"}),t.jsx("button",{className:"modal-close",onClick:Fe,disabled:x,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!We&&t.jsx(bb,{hasAiProvider:Se,hasGithub:qe}),t.jsx(Yg,{mode:"create",description:u,onDescriptionChange:m,dependencies:h,onDependenciesChange:f,executorModel:b,onExecutorModelChange:y,validatorModel:j,onValidatorModelChange:C,presetMode:E,onPresetModeChange:L,selectedPresetId:T,onSelectedPresetIdChange:M,selectedWorkflowSteps:P,onWorkflowStepsChange:ve,onDefaultOnApplied:Oe,pendingImages:p,onImagesChange:g,tasks:a,projectId:s,disabled:x,addToast:o,isActive:e,onPlanningMode:l,onSubtaskBreakdown:c,onClose:Fe,planningModel:A,onPlanningModelChange:N,thinkingLevel:S,onThinkingLevelChange:_,reviewLevel:z,onReviewLevelChange:k,priority:I,onPriorityChange:$,nodeId:w,onNodeIdChange:H,nodeOptions:Qe,renderBelowPrimary:kt,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:Fe,disabled:x,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Je,disabled:!u.trim()||x,children:x?"Creating...":"Create Task"})]})]})}):null}function ti(e){if(!Number.isFinite(e)||e<0)return"—";const n=e/(1024*1024);return n<1024?`${n.toFixed(0)} MB`:`${(n/1024).toFixed(2)} GB`}function hp(e,n){return!Number.isFinite(e)||!Number.isFinite(n)||n<=0?"—":`${(e/n*100).toFixed(1)}%`}function AI(e,n){if(n<=0)return"normal";const s=e/n;return s>=.85?"critical":s>=.65?"warning":"normal"}function PI(e,n){if(n<=0)return"normal";const s=e/n;return s>=.5?"critical":s>=.25?"warning":"normal"}function RI(e,n){if(n<=0)return"normal";const s=e/n;return s>=.9?"critical":s>=.75?"warning":"normal"}function Vc(e){return e==="critical"?"system-stats-modal__value--critical":e==="warning"?"system-stats-modal__value--warning":""}function TI(e){if(!e)return"Not yet";const n=new Date(e);return Number.isNaN(n.getTime())?"Not yet":n.toLocaleString()}function II({isOpen:e,onClose:n,projectId:s}){const[a,r]=i.useState(null),[o,l]=i.useState(!1),[c,d]=i.useState(null),[u,m]=i.useState(!0),[h,f]=i.useState(90),[p,g]=i.useState(!1),[x,v]=i.useState(!1),[b,y]=i.useState(null),[j,C]=i.useState(null),[A,N]=i.useState(null),S=i.useCallback(async H=>{l(!0);try{const K=await kj(s);r(K),d(null),N(Date.now()),H?.preserveKillResult||y(null)}catch(K){d(K instanceof Error?K.message:"Failed to load system stats")}finally{l(!1)}},[s]);i.useEffect(()=>{if(!e)return;S();const H=window.setInterval(()=>{S()},5e3);return()=>{window.clearInterval(H)}},[e,S]),i.useEffect(()=>{if(!e)return;(async()=>{try{const K=await ca();m(K.vitestAutoKillEnabled??!0),f(K.vitestKillThresholdPct??90),C(null)}catch(K){C(K instanceof Error?K.message:"Failed to load vitest settings")}})()},[e]),i.useEffect(()=>{if(!e)return;const H=K=>{K.key==="Escape"&&n()};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[e,n]);const _=i.useMemo(()=>{if(!a)return[];const H=a.systemStats,K=Vc(AI(H.heapUsed,H.heapLimit)),pe=Vc(PI(H.rss,H.systemTotalMem));return[{label:"RSS",value:ti(H.rss),detail:hp(H.rss,H.systemTotalMem),className:pe},{label:"Heap Used",value:ti(H.heapUsed),detail:`of ${ti(H.heapTotal)}`,className:K},{label:"Heap Limit",value:ti(H.heapLimit),detail:"V8 limit"},{label:"External",value:ti(H.external)},{label:"Array Buffers",value:ti(H.arrayBuffers)}]},[a]),T=i.useCallback(async H=>{m(H);try{await _n({vitestAutoKillEnabled:H}),C(null)}catch(K){C(K instanceof Error?K.message:"Failed to save vitest settings")}},[]),M=i.useCallback(async H=>{const K=Math.min(99,Math.max(50,Number.isFinite(H)?Math.round(H):90));f(K);try{await _n({vitestKillThresholdPct:K}),C(null)}catch(pe){C(pe instanceof Error?pe.message:"Failed to save vitest settings")}},[]),E=i.useCallback(async()=>{if(!p){if(!x){v(!0);return}g(!0);try{const H=await jj(s);y(H),v(!1),await S({preserveKillResult:!0})}catch(H){d(H instanceof Error?H.message:"Failed to kill vitest processes")}finally{g(!1)}}},[x,p,S,s]);if(!e)return null;const L=a?.systemStats,F=o&&!!a,R=A?`Updated ${new Date(A).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`:"Waiting for first update",P=a?.taskStats,O=L?L.systemTotalMem-L.systemFreeMem:0,q=L?RI(O,L.systemTotalMem):"normal",Z=L?Vc(q):"",z=L&&Number.isFinite(L.systemTotalMem)&&L.systemTotalMem>0?Math.max(0,Math.min(100,O/L.systemTotalMem*100)):0,k=L?`System memory used: ${z.toFixed(1)}% (${ti(O)} of ${ti(L.systemTotalMem)})`:"System memory usage unavailable",I=a?.vitestProcessCount,$=b?b.killed>0?"system-stats-modal__kill-result system-stats-modal__kill-result--success":"system-stats-modal__kill-result system-stats-modal__kill-result--error":"",w=TI(a?.vitestLastAutoKillAt);return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"system-stats-modal-title",onClick:H=>{H.target===H.currentTarget&&n()},"data-testid":"system-stats-modal-overlay",children:t.jsxs("div",{className:"modal modal-lg system-stats-modal","data-testid":"system-stats-modal",children:[t.jsxs("div",{className:"modal-header system-stats-modal__header",children:[t.jsxs("h2",{id:"system-stats-modal-title",className:"system-stats-modal__title",children:[t.jsx(Ra,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("div",{className:"system-stats-modal__header-actions",children:[t.jsxs("span",{className:"system-stats-modal__auto-refresh","aria-live":"polite",children:[t.jsx("span",{children:"Auto-refresh · 5s"}),t.jsx("span",{className:"system-stats-modal__auto-refresh-time",children:R})]}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>void S(),title:"Refresh","aria-label":"Refresh system stats",children:t.jsx(ns,{size:16,className:F?"system-stats-modal__refresh--spinning":void 0})}),t.jsx("button",{type:"button",className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Jt,{})})]})]}),o&&!a&&t.jsx("div",{className:"system-stats-modal__state",children:"Loading system stats…"}),c&&!a&&t.jsx("div",{className:"system-stats-modal__state system-stats-modal__state--error",role:"alert",children:c}),a&&t.jsxs("div",{className:"system-stats-modal__content",children:[t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Process stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Process"}),t.jsx("dl",{className:"system-stats-modal__grid",children:_.map(H=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:H.label}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${H.className}`.trim(),children:H.value}),H.detail?t.jsx("span",{className:"system-stats-modal__detail",children:H.detail}):null]})]},H.label))})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"CPU and load stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"CPU & Load"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Load Avg"}),t.jsx("dd",{children:L?.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:L?.cpuCount??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Platform"}),t.jsx("dd",{children:L?.platform??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Node"}),t.jsx("dd",{children:L?.nodeVersion??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"PID"}),t.jsx("dd",{children:L?.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 ${Z}`.trim(),children:L?ti(O):"—"}),t.jsx("span",{className:"system-stats-modal__detail",children:L?`${hp(O,L.systemTotalMem)} of ${ti(L.systemTotalMem)}`:""})]}),t.jsx("div",{className:"system-stats-modal__memory-progress-wrapper",children:t.jsx("div",{className:`system-stats-modal__memory-progress-track system-stats-modal__memory-progress-track--${q}`,role:"progressbar","aria-valuenow":Math.round(z),"aria-valuemin":0,"aria-valuemax":100,"aria-label":k,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${q}`,style:{width:`${z}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Memory Free"}),t.jsx("dd",{children:L?ti(L.systemFreeMem):"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Task stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Tasks"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Total"}),t.jsx("dd",{children:P?.total??0})]}),Object.entries(P?.byColumn??{}).map(([H,K])=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:H}),t.jsx("dd",{children:K})]},H))]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Agent stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Agents"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"idle"}),t.jsx("dd",{children:P?.agents.idle??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"active"}),t.jsx("dd",{children:P?.agents.active??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"running"}),t.jsx("dd",{children:P?.agents.running??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"error"}),t.jsx("dd",{children:P?.agents.error??0})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Vitest controls",children:[t.jsxs("h3",{className:"system-stats-modal__section-title system-stats-modal__section-title--with-icon",children:[t.jsx(ly,{}),t.jsx("span",{children:"Vitest Controls"})]}),t.jsx("dl",{className:"system-stats-modal__grid system-stats-modal__vitest-controls",children:t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Vitest Processes"}),t.jsx("dd",{children:I??"—"})]})}),t.jsxs("div",{className:"system-stats-modal__vitest-controls",children:[t.jsx("div",{className:"system-stats-modal__kill-row",children:t.jsxs("button",{type:"button",className:"btn btn-danger",onClick:()=>void E(),disabled:p||I===0,children:[t.jsx(my,{}),t.jsx("span",{children:x?"Confirm Kill?":"Kill Vitest Processes"})]})}),t.jsxs("label",{className:"system-stats-modal__toggle-row",children:[t.jsx("input",{type:"checkbox",checked:u,onChange:H=>{T(H.target.checked)}}),t.jsx("span",{children:"Auto-kill vitest on memory pressure"})]}),t.jsxs("div",{className:"system-stats-modal__threshold-row",children:[t.jsx("label",{htmlFor:"vitest-threshold-number",children:"Kill threshold (%)"}),t.jsxs("div",{className:"system-stats-modal__threshold-controls",children:[t.jsx("input",{id:"vitest-threshold-range",type:"range",min:50,max:99,value:h,"aria-label":"Kill threshold slider (%)",onChange:H=>{const K=Number.parseInt(H.target.value,10);M(Number.isNaN(K)?90:K)}}),t.jsx("input",{id:"vitest-threshold-number",type:"number",className:"input",min:50,max:99,value:h,"aria-label":"Kill threshold (%)",onChange:H=>{const K=Number.parseInt(H.target.value,10);M(Number.isNaN(K)?90:K)},onBlur:()=>{M(h)}})]})]}),b&&t.jsxs("p",{className:$,children:["Killed ",b.killed," processes"]}),t.jsxs("p",{className:"system-stats-modal__last-kill",children:["Last auto-kill: ",w]}),j&&t.jsx("p",{className:"system-stats-modal__kill-result system-stats-modal__kill-result--error",children:j})]})]})]}),c&&a&&t.jsxs("div",{className:"system-stats-modal__footer-error",children:["Latest refresh failed: ",c]})]})})}const $I=5e3;function DI(e={}){const{projectId:n,type:s,limit:a=50,autoRefresh:r=!0,useCentralFeed:o=!1}=e,[l,c]=i.useState([]),[d,u]=i.useState(!1),[m,h]=i.useState(null),[f,p]=i.useState(!1),g=i.useRef(null),x=i.useRef(void 0),v=i.useCallback(async()=>{try{u(!0),h(null);let j;o?j=await Wu({limit:a,projectId:n,type:s}):j=(await Fu({limit:a,type:s,projectId:n})).map(A=>({...A,projectId:n??"",projectName:""})),c(j),p(j.length===a),j.length>0&&(x.current=j[j.length-1].timestamp)}catch(j){h(j instanceof Error?j.message:"Failed to load activity log")}finally{u(!1)}},[a,n,s,o]),b=i.useCallback(async()=>{if(x.current)try{u(!0);let j;o?j=await Wu({limit:a,projectId:n,type:s,since:x.current}):j=(await Fu({limit:a,type:s,since:x.current,projectId:n})).map(A=>({...A,projectId:n??"",projectName:""})),c(C=>[...C,...j]),p(j.length===a),j.length>0&&(x.current=j[j.length-1].timestamp)}catch(j){h(j instanceof Error?j.message:"Failed to load more entries")}finally{u(!1)}},[a,n,s,o]),y=i.useCallback(()=>{c([]),p(!1),x.current=void 0},[]);return i.useEffect(()=>{v()},[v]),i.useEffect(()=>{if(r)return g.current=setInterval(()=>{v()},$I),()=>{g.current&&(clearInterval(g.current),g.current=null)}},[r,v]),{entries:l,loading:d,error:m,refresh:v,clear:y,hasMore:f,loadMore:b}}const Wc={"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"},LI={"task:created":t.jsx(Sn,{size:14,className:"activity-icon created"}),"task:moved":t.jsx(qr,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx(ns,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(Jt,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx(Ln,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(Vr,{size:14,className:"activity-icon failed"}),"settings:updated":t.jsx(Cr,{size:14,className:"activity-icon settings"})};function OI(e){const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4),o=Math.floor(a/36e5),l=Math.floor(a/864e5);return r<1?"Just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function zI({isOpen:e,onClose:n,tasks:s,onOpenTaskDetail:a,projectId:r,projects:o=[],onProjectFilterChange:l,currentProject:c}){const[d,u]=i.useState("all"),[m,h]=i.useState(r||"all"),[f,p]=i.useState(!1);i.useEffect(()=>{h(r||"all")},[r]);const g=d==="all"?void 0:d,x=m==="all"?void 0:m,v=!c&&o.length>0,{entries:b,loading:y,error:j,refresh:C,hasMore:A}=DI({projectId:x,type:g,limit:100,autoRefresh:e,useCentralFeed:v}),N=b.map(E=>({id:E.id,timestamp:E.timestamp,type:E.type,taskId:E.taskId,taskTitle:E.taskTitle,details:E.details,metadata:E.metadata,projectId:E.projectId,projectName:E.projectName})),S=async()=>{try{await Qk(),C(),p(!1)}catch{p(!1)}},_=E=>{a&&a(E)},T=E=>{h(E),l?.(E==="all"?void 0:E)};i.useEffect(()=>{if(!e)return;const E=L=>{L.key==="Escape"&&(f?p(!1):n())};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[e,n,f]);const M=d!=="all"||m!=="all";return e?t.jsx("div",{className:"modal-overlay open",onClick:E=>{E.target===E.currentTarget&&n()},role:"dialog","aria-modal":"true","data-testid":"activity-log-modal-overlay",children:t.jsxs("div",{className:"modal modal-lg activity-log-modal","data-testid":"activity-log-modal",children:[t.jsxs("div",{className:"modal-header activity-log-header",children:[t.jsxs("div",{className:"activity-log-title",children:[t.jsx(Tr,{size:18}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("div",{className:"activity-log-actions",children:[o.length>0&&t.jsxs("div",{className:"activity-log-filter activity-log-filter--project",children:[t.jsx(os,{size:14}),t.jsxs("select",{value:m,onChange:E=>T(E.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[t.jsx("option",{value:"all",children:"All Projects"}),o.map(E=>t.jsx("option",{value:E.id,children:E.name},E.id))]})]}),t.jsxs("div",{className:"activity-log-filter",children:[t.jsx(Yo,{size:14}),t.jsxs("select",{value:d,onChange:E=>u(E.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:"All Events"}),Object.entries(Wc).map(([E,L])=>t.jsx("option",{value:E,children:L},E))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>C(),title:"Refresh","data-testid":"activity-refresh",children:y?t.jsx(gt,{size:14,className:"spin"}):t.jsx(ns,{size:14})}),N.length>0&&t.jsx("button",{className:"activity-log-clear",onClick:()=>p(!0),title:"Clear Log","data-testid":"activity-clear",children:t.jsx(Cn,{size:14})})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",title:"Close","data-testid":"activity-close",children:"×"})]}),M&&t.jsxs("div",{className:"activity-log-active-filters",children:[t.jsx("span",{className:"activity-log-filter-label",children:"Active filters:"}),m!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Project: ",o.find(E=>E.id===m)?.name||m]}),d!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",Wc[d]]}),t.jsx("button",{className:"activity-log-clear-filters",onClick:()=>{u("all"),h("all"),l?.(void 0)},children:"Clear all"})]}),t.jsxs("div",{className:"activity-log-content","data-testid":"activity-log-content",children:[j&&t.jsxs("div",{className:"activity-log-error","data-testid":"activity-error",children:[t.jsx(Rs,{size:16}),t.jsx("span",{children:j})]}),N.length===0&&!y&&!j&&t.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[t.jsx(Tr,{size:48,className:"activity-log-empty-icon"}),t.jsx("p",{children:M?"No activity matches the current filters":"No activity recorded yet"}),M&&t.jsx("button",{className:"btn btn-secondary",onClick:()=>{u("all"),h("all"),l?.(void 0)},children:"Clear Filters"})]}),t.jsx("div",{className:"activity-log-list",children:N.map(E=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:LI[E.type]}),t.jsxs("div",{className:"activity-log-entry-content",children:[t.jsxs("div",{className:"activity-log-entry-header",children:[t.jsx("span",{className:"activity-log-entry-type",children:Wc[E.type]}),t.jsx("span",{className:"activity-log-entry-time",children:OI(E.timestamp)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[E.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>_(E.taskId),"data-testid":"activity-task-link",children:E.taskId}),E.taskTitle&&t.jsx("span",{className:"activity-log-task-title",children:E.taskTitle}),t.jsx("span",{className:"activity-log-entry-text",children:E.details})]}),E.metadata&&Object.keys(E.metadata).length>0&&t.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof E.metadata.from=="string"&&typeof E.metadata.to=="string"&&t.jsxs("span",{className:"activity-log-metadata-item",children:[E.metadata.from," → ",E.metadata.to]}),typeof E.metadata.merged=="boolean"&&t.jsx("span",{className:`activity-log-metadata-item ${E.metadata.merged?"success":"error"}`,children:E.metadata.merged?"Merged":"Not merged"})]})]})]},E.id))}),A&&!y&&t.jsx("button",{className:"activity-log-load-more",onClick:C,"data-testid":"activity-load-more",children:"Load More"}),y&&N.length>0&&t.jsx("div",{className:"activity-log-loading",children:t.jsx(gt,{size:20,className:"spin"})})]}),f&&t.jsx("div",{className:"activity-log-confirm-overlay",children:t.jsxs("div",{className:"activity-log-confirm-dialog",children:[t.jsx("h3",{children:"Clear Activity Log?"}),t.jsx("p",{children:"This will permanently delete all activity log entries. This action cannot be undone."}),t.jsxs("div",{className:"activity-log-confirm-actions",children:[t.jsx("button",{className:"activity-log-confirm-cancel",onClick:()=>p(!1),children:"Cancel"}),t.jsx("button",{className:"activity-log-confirm-clear",onClick:S,children:"Clear Log"})]})]})})]})}):null}const pr=[{id:"status",label:"Status",icon:nf},{id:"changes",label:"Changes",icon:id},{id:"commits",label:"Commits",icon:Wr},{id:"branches",label:"Branches",icon:Hs},{id:"worktrees",label:"Worktrees",icon:dv},{id:"stashes",label:"Stashes",icon:Br},{id:"remotes",label:"Remotes",icon:Zp}];function pp({status:e}){switch(e){case"added":case"untracked":return t.jsx(Hx,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(Qp,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(Fx,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return t.jsx(Fi,{size:14,className:"gm-file-icon gm-file-renamed"});default:return t.jsx(Vx,{size:14,className:"gm-file-icon"})}}function fp({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 FI(e){return i.useCallback(async(n,s)=>{try{await navigator.clipboard.writeText(n),e(`Copied ${s||"to clipboard"}`,"success")}catch{e("Failed to copy","error")}},[e])}function Fa(e){if(!e)return"—";const n=new Date(e);if(isNaN(n.getTime()))return"—";const a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4);if(r<1)return"just now";if(r<60)return`${r}m ago`;const o=Math.floor(r/60);if(o<24)return`${o}h ago`;const l=Math.floor(o/24);return l<30?`${l}d ago`:n.toLocaleDateString()}function UI({isOpen:e,onClose:n,tasks:s,addToast:a,projectId:r}){const o=qs(),[l,c]=i.useState("status"),[d,u]=i.useState(!1),[m,h]=i.useState(null),f=i.useRef(null);wi(f,e,"fusion:git-modal-size");const p=Ri(n),g=FI(a),[x,v]=i.useState(null),[b,y]=i.useState([]),[j,C]=i.useState(new Set),[A,N]=i.useState(""),[S,_]=i.useState(!1),[T,M]=i.useState(null),[E,L]=i.useState(!1),[F,R]=i.useState(null),[P,O]=i.useState(null),q=i.useRef(0),[Z,z]=i.useState([]),[k,I]=i.useState(null),[$,w]=i.useState(null),[H,K]=i.useState(!1),[pe,le]=i.useState(20),[B,ye]=i.useState(""),[U,te]=i.useState([]),[ne,ee]=i.useState(""),[ie,ge]=i.useState(""),[se,Ae]=i.useState(""),[xe,Se]=i.useState(null),[qe,We]=i.useState([]),[Qe,ve]=i.useState(!1),[Oe,ae]=i.useState(null),[re,je]=i.useState(null),[Q,Fe]=i.useState(!1),[Je,be]=i.useState([]),[ze,tt]=i.useState([]),[kt,ke]=i.useState(""),[ce,Te]=i.useState(null),[he,Le]=i.useState(null),[st,it]=i.useState(null),lt=i.useCallback(async()=>{if(e){u(!0),h(null);try{switch(l){case"status":{const oe=await ei(r);v(oe);break}case"changes":{const[oe,Pe]=await Promise.all([ei(r),xa(r)]);v(oe),y(Pe),C(new Set),O(null),M(null),R(null);break}case"commits":{const oe=await tk(pe,r);z(oe);break}case"branches":{const[oe,Pe]=await Promise.all([nr(r),ei(r)]);te(oe),v(Pe);break}case"worktrees":{const oe=await ak(r);be(oe);break}case"stashes":{const oe=await po(r);tt(oe);break}case"remotes":{const oe=await ei(r);v(oe);break}}}catch(oe){h(_e(oe)||"Failed to fetch git data"),a(_e(oe)||"Failed to fetch git data","error")}finally{u(!1)}}},[l,e,pe,a,r]);i.useEffect(()=>{e&&lt()},[lt,e]),i.useEffect(()=>{if(!e)return;const oe=Pe=>{if(Pe.key==="Escape"){n();return}if((Pe.key==="ArrowUp"||Pe.key==="ArrowDown")&&Pe.altKey){Pe.preventDefault();const Ce=pr.findIndex(J=>J.id===l);Pe.key==="ArrowUp"&&Ce>0?c(pr[Ce-1].id):Pe.key==="ArrowDown"&&Ce<pr.length-1&&c(pr[Ce+1].id)}};return document.addEventListener("keydown",oe),()=>document.removeEventListener("keydown",oe)},[e,n,l]);const $e=i.useCallback(async oe=>{try{await $u(oe,r),a(`Staged ${oe.length} file(s)`,"success");const Pe=await xa(r);y(Pe),C(new Set),O(null),M(null),R(null)}catch(Pe){a(_e(Pe)||"Failed to stage files","error")}},[a,r]),Ue=i.useCallback(async oe=>{try{await fk(oe,r),a(`Unstaged ${oe.length} file(s)`,"success");const Pe=await xa(r);y(Pe),C(new Set),O(null),M(null),R(null)}catch(Pe){a(_e(Pe)||"Failed to unstage files","error")}},[a,r]),Xe=i.useCallback(async oe=>{if(await o.confirm({title:"Discard Changes",message:`Discard changes to ${oe.length} file(s)? This cannot be undone.`,danger:!0}))try{await gk(oe,r),a(`Discarded changes to ${oe.length} file(s)`,"success");const[Ce,J]=await Promise.all([xa(r),ei(r)]);y(Ce),v(J),C(new Set),O(null),M(null),R(null)}catch(Ce){a(_e(Ce)||"Failed to discard changes","error")}},[a,r,o]),wt=i.useCallback(async oe=>{if(oe.preventDefault(),!!A.trim()){_(!0);try{const Pe=await Du(A.trim(),r);a(`Committed: ${Pe.hash}`,"success"),N("");const[Ce,J]=await Promise.all([xa(r),ei(r)]);y(Ce),v(J),O(null),M(null),R(null)}catch(Pe){a(_e(Pe)||"Failed to commit","error")}finally{_(!1)}}},[A,a,r]),Re=i.useCallback(async()=>{if(A.trim()){_(!0);try{const oe=b.filter(Ie=>!Ie.staged).map(Ie=>Ie.file);oe.length>0&&await $u(oe,r);const Pe=await Du(A.trim(),r);a(`Committed: ${Pe.hash}`,"success"),N("");const[Ce,J]=await Promise.all([xa(r),ei(r)]);y(Ce),v(J),O(null),M(null),R(null)}catch(oe){a(_e(oe)||"Failed to commit","error")}finally{_(!1)}}},[A,b,a,r]),xt=i.useCallback(async(oe,Pe)=>{O({file:oe,staged:Pe}),L(!0),R(null);const Ce=q.current+1;q.current=Ce;try{const J=await pk(oe,Pe,r);if(q.current!==Ce)return;M(J)}catch(J){if(q.current!==Ce)return;const Ie=_e(J)||"Failed to load file diff";M(null),R(Ie),a(Ie,"error")}finally{q.current===Ce&&L(!1)}},[a,r]),Pt=i.useCallback(oe=>{C(Pe=>{const Ce=new Set(Pe);return Ce.has(oe)?Ce.delete(oe):Ce.add(oe),Ce})},[]),Ct=i.useCallback(async oe=>{if(k===oe){I(null),w(null);return}I(oe),K(!0);try{const Pe=await nl(oe,r);w(Pe)}catch(Pe){a(_e(Pe)||"Failed to load diff","error"),w(null)}finally{K(!1)}},[k,a,r]),Ot=i.useCallback(()=>{le(oe=>Math.min(oe+20,100))},[]),zt=i.useMemo(()=>{if(!B.trim())return Z;const oe=B.toLowerCase();return Z.filter(Pe=>Pe.message.toLowerCase().includes(oe)||Pe.author.toLowerCase().includes(oe)||Pe.shortHash.toLowerCase().includes(oe))},[Z,B]),Nt=i.useCallback(async oe=>{if(oe.preventDefault(),!!ne.trim()){u(!0);try{await rk(ne.trim(),ie.trim()||void 0,r),a(`Created branch ${ne}`,"success"),ee(""),ge("");const Pe=await nr(r);te(Pe)}catch(Pe){a(_e(Pe)||"Failed to create branch","error")}finally{u(!1)}}},[ne,ie,a,r]),jt=i.useCallback(async oe=>{u(!0);try{await ok(oe,r),a(`Switched to ${oe}`,"success");const[Pe,Ce]=await Promise.all([ei(r),nr(r)]);v(Pe),te(Ce)}catch(Pe){a(_e(Pe)||"Failed to checkout branch","error")}finally{u(!1)}},[a,r]),Yt=i.useCallback(async oe=>{if(await o.confirm({title:"Delete Branch",message:`Delete branch "${oe}"?`,danger:!0})){u(!0);try{await Iu(oe,void 0,r),a(`Deleted branch ${oe}`,"success");const Ce=await nr(r);te(Ce)}catch(Ce){if(_e(Ce).includes("not fully merged")){if(await o.confirm({title:"Force Delete Branch",message:"Branch has unmerged commits. Force delete?",danger:!0}))try{await Iu(oe,!0,r),a(`Force deleted branch ${oe}`,"success");const Ie=await nr(r);te(Ie)}catch(Ie){a(_e(Ie)||"Failed to delete branch","error")}}else a(_e(Ce)||"Failed to delete branch","error")}finally{u(!1)}}},[a,r,o]),Bt=i.useMemo(()=>{if(!se.trim())return U;const oe=se.toLowerCase();return U.filter(Pe=>Pe.name.toLowerCase().includes(oe))},[U,se]),qt=i.useCallback(async oe=>{if(xe===oe){Se(null),We([]),ae(null),je(null);return}Se(oe),We([]),ae(null),je(null),ve(!0);try{const Pe=await ik(oe,10,r);We(Pe)}catch{We([])}finally{ve(!1)}},[xe,r]),wn=i.useCallback(async oe=>{if(Oe===oe){ae(null),je(null);return}ae(oe),je(null),Fe(!0);try{const Pe=await nl(oe,r);je(Pe)}catch{je(null)}finally{Fe(!1)}},[Oe,r]),mn=i.useCallback(()=>{Se(null),We([]),ae(null),je(null)},[]),Xt=i.useCallback(async oe=>{oe.preventDefault(),Te("create");try{await uk(kt.trim()||void 0,r),a("Changes stashed","success"),ke("");const Pe=await po(r);tt(Pe)}catch(Pe){a(_e(Pe)||"Failed to stash changes","error")}finally{Te(null)}},[kt,a,r]),Vt=i.useCallback(async(oe,Pe=!1)=>{Te(`apply-${oe}`);try{await mk(oe,Pe,r),a(Pe?"Stash popped":"Stash applied","success");const Ce=await po(r);tt(Ce)}catch(Ce){a(_e(Ce)||"Failed to apply stash","error")}finally{Te(null)}},[a,r]),Ft=i.useCallback(async oe=>{if(await o.confirm({title:"Drop Stash",message:`Drop stash@{${oe}}? This cannot be undone.`,danger:!0})){Te(`drop-${oe}`);try{await hk(oe,r),a("Stash dropped","success");const Ce=await po(r);tt(Ce)}catch(Ce){a(_e(Ce)||"Failed to drop stash","error")}finally{Te(null)}}},[a,r,o]),Zt=i.useCallback(async()=>{Le("fetch");try{const oe=await lk(void 0,r);it(oe),a(oe.message||"Fetch completed",oe.fetched?"success":"info");const Pe=await ei(r);v(Pe)}catch(oe){a(_e(oe)||"Fetch failed","error")}finally{Le(null)}},[a,r]),en=i.useCallback(async()=>{Le("pull");try{const oe=await ck(r);it(oe),oe.conflict?a("Merge conflict detected. Resolve manually.","error"):a(oe.message||"Pull completed","success");const Pe=await ei(r);v(Pe)}catch(oe){a(_e(oe)||"Pull failed","error")}finally{Le(null)}},[a,r]),cn=i.useCallback(async()=>{Le("push");try{const oe=await dk(r);it(oe),a(oe.message||"Push completed","success");const Pe=await ei(r);v(Pe)}catch(oe){a(_e(oe)||"Push failed","error")}finally{Le(null)}},[a,r]),we=i.useMemo(()=>b.filter(oe=>oe.staged),[b]),De=i.useMemo(()=>b.filter(oe=>!oe.staged),[b]);return e?t.jsx("div",{className:"modal-overlay open",...p,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal gm-modal",ref:f,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h3",{children:[t.jsx(ad,{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:lt,disabled:d,title:"Refresh",children:t.jsx(ns,{size:14,className:d?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Jt,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:pr.map(oe=>{const Pe=oe.icon;return t.jsxs("button",{role:"tab","aria-selected":l===oe.id,className:`gm-nav-item${l===oe.id?" active":""}`,onClick:()=>c(oe.id),children:[t.jsx(Pe,{size:16}),t.jsx("span",{className:"gm-nav-label",children:oe.label})]},oe.id)})}),t.jsxs("div",{className:"gm-content",role:"tabpanel",children:[d&&t.jsxs("div",{className:"gm-loading",children:[t.jsx(gt,{size:24,className:"spin"}),t.jsx("span",{children:"Loading..."})]}),m&&!d&&t.jsxs("div",{className:"gm-error",children:[t.jsx(Rs,{size:18}),t.jsx("span",{children:m}),t.jsx("button",{className:"btn btn-sm",onClick:lt,children:"Retry"})]}),l==="status"&&!d&&x&&t.jsx(BI,{status:x,copyToClipboard:g}),l==="changes"&&!d&&t.jsx(HI,{status:x,stagedFiles:we,unstagedFiles:De,selectedFiles:j,toggleFileSelection:Pt,onStageFiles:$e,onUnstageFiles:Ue,onDiscardChanges:Xe,onSelectDiffFile:xt,selectedDiffTarget:P,changeDiff:T,loadingChangeDiff:E,changeDiffError:F,commitMessage:A,setCommitMessage:N,onCommit:wt,onStageAllAndCommit:Re,committing:S}),l==="commits"&&!d&&t.jsx(qI,{commits:zt,commitSearch:B,setCommitSearch:ye,selectedCommit:k,commitDiff:$,loadingDiff:H,onCommitClick:Ct,onLoadMore:Ot,canLoadMore:Z.length>=pe&&pe<100,copyToClipboard:g}),l==="branches"&&!d&&t.jsx(VI,{branches:Bt,branchSearch:se,setBranchSearch:Ae,newBranchName:ne,setNewBranchName:ee,branchBase:ie,setBranchBase:ge,onCreateBranch:Nt,onCheckoutBranch:jt,onDeleteBranch:Yt,loading:d,allBranches:U,selectedBranch:xe,branchCommits:qe,loadingBranchCommits:Qe,expandedBranchCommit:Oe,branchCommitDiff:re,loadingBranchCommitDiff:Q,onSelectBranch:qt,onBranchCommitClick:wn,onCloseBranchDetails:mn}),l==="worktrees"&&!d&&t.jsx(WI,{worktrees:Je}),l==="stashes"&&!d&&t.jsx(KI,{stashes:ze,stashMessage:kt,setStashMessage:ke,onCreateStash:Xt,onApplyStash:Vt,onDropStash:Ft,stashLoading:ce}),l==="remotes"&&!d&&t.jsx(GI,{status:x,remoteLoading:he,lastRemoteResult:st,onFetch:Zt,onPull:en,onPush:cn,addToast:a,projectId:r,copyToClipboard:g})]})]})]})}):null}function BI({status:e,copyToClipboard:n}){return t.jsxs("div",{className:"gm-panel","data-testid":"status-panel",children:[t.jsx("div",{className:"gm-panel-header",children:t.jsx("h4",{children:"Repository Status"})}),t.jsxs("div",{className:"gm-status-grid",children:[t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Branch"}),t.jsxs("span",{className:"gm-status-value",children:[t.jsx(Hs,{size:14}),t.jsx("span",{children:e.branch})]})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Commit"}),t.jsxs("span",{className:"gm-status-value",children:[t.jsx("code",{className:"gm-hash",children:e.commit}),t.jsx("button",{className:"gm-icon-btn",onClick:()=>n(e.commit,"commit hash"),title:"Copy commit hash",children:t.jsx(ta,{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(Rs,{size:12}),"Modified"]}):t.jsxs(t.Fragment,{children:[t.jsx(Ln,{size:12}),"Clean"]})})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Remote Sync"}),t.jsxs("span",{className:"gm-status-value",children:[e.ahead>0&&t.jsxs("span",{className:"gm-ahead",title:`${e.ahead} commit(s) ahead`,children:[t.jsx(Zi,{size:12}),e.ahead]}),e.behind>0&&t.jsxs("span",{className:"gm-behind",title:`${e.behind} commit(s) behind`,children:[t.jsx(Hr,{size:12}),e.behind]}),e.ahead===0&&e.behind===0&&t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(Ln,{size:12}),"Up to date"]})]})]})]})]})}function HI({status:e,stagedFiles:n,unstagedFiles:s,selectedFiles:a,toggleFileSelection:r,onStageFiles:o,onUnstageFiles:l,onDiscardChanges:c,onSelectDiffFile:d,selectedDiffTarget:u,changeDiff:m,loadingChangeDiff:h,changeDiffError:f,commitMessage:p,setCommitMessage:g,onCommit:x,onStageAllAndCommit:v,committing:b}){const y=s.filter(C=>a.has(`unstaged:${C.file}`)),j=n.filter(C=>a.has(`staged:${C.file}`));return t.jsxs("div",{className:"gm-panel","data-testid":"changes-panel",children:[e&&t.jsxs("div",{className:"gm-changes-header",children:[t.jsxs("span",{className:"gm-branch-indicator",children:[t.jsx(Hs,{size:14}),e.branch]}),e.isDirty&&t.jsx("span",{className:"gm-dirty-badge",children:"Modified"})]}),t.jsxs("div",{className:"gm-changes-split",children:[t.jsxs("div",{className:"gm-changes-lists",children:[t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Unstaged Changes (",s.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[y.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>o(y.map(C=>C.file)),title:"Stage selected",children:[t.jsx(Sn,{size:12})," Stage (",y.length,")"]}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>c(y.map(C=>C.file)),title:"Discard selected",children:t.jsx(Vr,{size:12})})]}),s.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>o(s.map(C=>C.file)),title:"Stage all",children:"Stage All"})]})]}),t.jsx("div",{className:"gm-file-list",children:s.length===0?t.jsx("div",{className:"gm-empty",children:"No unstaged changes"}):s.map(C=>{const A=u?.file===C.file&&u.staged===!1;return t.jsxs("div",{className:`gm-file-item${A?" active":""}`,onClick:()=>d(C.file,!1),role:"button",tabIndex:0,onKeyDown:N=>{(N.key==="Enter"||N.key===" ")&&(N.preventDefault(),d(C.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:N=>N.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:a.has(`unstaged:${C.file}`),onChange:()=>r(`unstaged:${C.file}`)})}),t.jsx(pp,{status:C.status}),t.jsx("span",{className:"gm-file-name",title:C.file,children:t.jsx("bdo",{dir:"ltr",children:C.file})}),t.jsx(fp,{status:C.status}),t.jsx("button",{className:"gm-icon-btn",onClick:N=>{N.stopPropagation(),o([C.file])},title:"Stage file",children:t.jsx(Sn,{size:12})})]},`unstaged:${C.file}`)})})]}),t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Staged Changes (",n.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[j.length>0&&t.jsxs("button",{className:"btn btn-sm",onClick:()=>l(j.map(C=>C.file)),title:"Unstage selected",children:["Unstage (",j.length,")"]}),n.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(n.map(C=>C.file)),title:"Unstage all",children:"Unstage All"})]})]}),t.jsx("div",{className:"gm-file-list",children:n.length===0?t.jsx("div",{className:"gm-empty",children:"No staged changes"}):n.map(C=>{const A=u?.file===C.file&&u.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${A?" active":""}`,onClick:()=>d(C.file,!0),role:"button",tabIndex:0,onKeyDown:N=>{(N.key==="Enter"||N.key===" ")&&(N.preventDefault(),d(C.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:N=>N.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:a.has(`staged:${C.file}`),onChange:()=>r(`staged:${C.file}`)})}),t.jsx(pp,{status:C.status}),t.jsx("span",{className:"gm-file-name",title:C.file,children:t.jsx("bdo",{dir:"ltr",children:C.file})}),t.jsx(fp,{status:C.status}),t.jsx("button",{className:"gm-icon-btn",onClick:N=>{N.stopPropagation(),l([C.file])},title:"Unstage file",children:t.jsx(Jt,{size:12})})]},`staged:${C.file}`)})})]})]}),t.jsx("div",{className:"gm-changes-diff",children:u||h||m||f?t.jsxs("div",{className:"gm-diff-section",children:[u&&t.jsxs("div",{className:"gm-diff-target",children:[t.jsx(id,{size:14}),t.jsxs("span",{children:[u.staged?"Staged":"Unstaged"," diff: "]}),t.jsx("code",{children:u.file})]}),h&&t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(gt,{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(id,{size:20}),t.jsx("span",{children:"Select a file to view its diff"})]})})]}),t.jsxs("form",{className:"gm-commit-form",onSubmit:x,children:[t.jsx("textarea",{className:"gm-commit-input",placeholder:"Commit message...",value:p,onChange:C=>g(C.target.value),rows:3,disabled:b}),t.jsxs("div",{className:"gm-commit-actions",children:[t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:b||!p.trim()||n.length===0,title:n.length===0?"No staged changes to commit":"Commit staged changes",children:[b?t.jsx(gt,{size:14,className:"spin"}):t.jsx(Xi,{size:14}),"Commit"]}),s.length>0&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:v,disabled:b||!p.trim(),title:"Stage all and commit",children:"Stage All & Commit"})]})]})]})}function qI({commits:e,commitSearch:n,setCommitSearch:s,selectedCommit:a,commitDiff:r,loadingDiff:o,onCommitClick:l,onLoadMore:c,canLoadMore:d,copyToClipboard:u}){return t.jsxs("div",{className:"gm-panel","data-testid":"commits-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Commits"}),t.jsxs("div",{className:"gm-search-box",children:[t.jsx(Ci,{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:Fa(m.date)}),m.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),t.jsx("div",{className:"gm-commit-actions-row",children:t.jsx("button",{className:"gm-icon-btn",onClick:()=>u(m.hash,"commit hash"),title:"Copy full hash",children:t.jsx(ta,{size:12})})}),a===m.hash&&t.jsx("div",{className:"gm-commit-diff",children:o?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(gt,{size:16,className:"spin"}),"Loading diff..."]}):r?t.jsxs(t.Fragment,{children:[r.stat&&t.jsx("pre",{className:"gm-diff-stat",children:r.stat}),t.jsx("pre",{className:"gm-diff-patch",children:r.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]})]},m.hash))}),d&&t.jsx("button",{className:"gm-load-more",onClick:c,children:"Load more commits"})]})}function VI({branches:e,branchSearch:n,setBranchSearch:s,newBranchName:a,setNewBranchName:r,branchBase:o,setBranchBase:l,onCreateBranch:c,onCheckoutBranch:d,onDeleteBranch:u,loading:m,allBranches:h,selectedBranch:f,branchCommits:p,loadingBranchCommits:g,expandedBranchCommit:x,branchCommitDiff:v,loadingBranchCommitDiff:b,onSelectBranch:y,onBranchCommitClick:j,onCloseBranchDetails:C}){return t.jsxs("div",{className:"gm-panel","data-testid":"branches-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Branches"}),t.jsxs("div",{className:"gm-search-box",children:[t.jsx(Ci,{size:14}),t.jsx("input",{type:"text",placeholder:"Filter branches...",value:n,onChange:A=>s(A.target.value)})]})]}),t.jsxs("form",{className:"gm-create-form",onSubmit:c,children:[t.jsx("input",{type:"text",placeholder:"New branch name",value:a,onChange:A=>r(A.target.value),disabled:m}),t.jsxs("select",{value:o,onChange:A=>l(A.target.value),disabled:m,className:"gm-branch-select",children:[t.jsx("option",{value:"",children:"Base: HEAD"}),h.map(A=>t.jsx("option",{value:A.name,children:A.name},A.name))]}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:m||!a.trim(),children:[t.jsx(Sn,{size:14}),"Create"]})]}),t.jsx("div",{className:"gm-branches-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:n?"No matching branches":"No branches found"}):e.map(A=>t.jsxs("div",{children:[t.jsxs("div",{className:`gm-branch-item${A.isCurrent?" current":""}${f===A.name?" selected":""}`,onClick:()=>y(A.name),children:[t.jsxs("div",{className:"gm-branch-info",children:[t.jsxs("span",{className:"gm-branch-name",children:[A.isCurrent&&t.jsx(Yn,{size:14,className:"gm-current-icon"}),A.name]}),A.remote&&t.jsxs("span",{className:"gm-branch-remote",children:["→ ",A.remote]}),A.lastCommitDate&&t.jsx("span",{className:"gm-branch-date",children:Fa(A.lastCommitDate)})]}),t.jsx("div",{className:"gm-branch-actions",children:!A.isCurrent&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:N=>{N.stopPropagation(),d(A.name)},disabled:m,title:"Checkout",children:t.jsx(Hs,{size:14})}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:N=>{N.stopPropagation(),u(A.name)},disabled:m,title:"Delete",children:t.jsx(Cn,{size:14})})]})})]}),f===A.name&&t.jsxs("div",{className:"gm-branch-details",children:[t.jsxs("div",{className:"gm-branch-details-header",children:[t.jsxs("span",{className:"gm-branch-details-title",children:[t.jsx(Wr,{size:14}),"Commits on ",A.name]}),t.jsx("button",{className:"gm-icon-btn",onClick:C,title:"Close","data-testid":"close-branch-details",children:t.jsx(Jt,{size:14})})]}),g?t.jsxs("div",{className:"gm-branch-details-loading",children:[t.jsx(gt,{size:16,className:"spin"}),"Loading commits..."]}):p.length===0?t.jsx("div",{className:"gm-empty",children:"No commits found"}):t.jsx("div",{className:"gm-branch-commits-list",children:p.map(N=>t.jsxs("div",{className:"gm-branch-commit",children:[t.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>j(N.hash),"data-testid":`branch-commit-${N.shortHash}`,children:[t.jsx("span",{className:"gm-commit-hash",children:N.shortHash}),t.jsx("span",{className:"gm-commit-message",title:N.message,children:N.message}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:N.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Fa(N.date)}),N.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),x===N.hash&&t.jsx("div",{className:"gm-commit-diff",children:b?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(gt,{size:16,className:"spin"}),"Loading diff..."]}):v?t.jsxs(t.Fragment,{children:[v.stat&&t.jsx("pre",{className:"gm-diff-stat",children:v.stat}),t.jsx("pre",{className:"gm-diff-patch",children:v.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},N.hash))})]})]},A.name))})]})}function WI({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(Hs,{size:12}),n.branch]}),n.taskId&&t.jsx("span",{className:"gm-worktree-task",children:n.taskId})]})]})},n.path))})]})}function KI({stashes:e,stashMessage:n,setStashMessage:s,onCreateStash:a,onApplyStash:r,onDropStash:o,stashLoading:l}){return t.jsxs("div",{className:"gm-panel","data-testid":"stashes-panel",children:[t.jsx("div",{className:"gm-panel-header",children:t.jsx("h4",{children:"Stashes"})}),t.jsxs("form",{className:"gm-create-form",onSubmit:a,children:[t.jsx("input",{type:"text",placeholder:"Stash message (optional)",value:n,onChange:c=>s(c.target.value),disabled:l!==null}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:l!==null,children:[l==="create"?t.jsx(gt,{size:14,className:"spin"}):t.jsx(Br,{size:14}),"Stash"]})]}),t.jsx("div",{className:"gm-stash-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:"No stashes"}):e.map(c=>t.jsxs("div",{className:"gm-stash-item",children:[t.jsxs("div",{className:"gm-stash-info",children:[t.jsxs("span",{className:"gm-stash-ref",children:["stash@",`{${c.index}}`]}),t.jsx("span",{className:"gm-stash-message",children:c.message}),t.jsxs("div",{className:"gm-stash-meta",children:[c.branch&&t.jsxs("span",{className:"gm-stash-branch",children:[t.jsx(Hs,{size:12}),c.branch]}),t.jsx("span",{children:Fa(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(gt,{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(gt,{size:14,className:"spin"}):t.jsx(Cn,{size:14})})]})]},c.index))})]})}function GI({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:a,onPull:r,onPush:o,addToast:l,projectId:c,copyToClipboard:d}){const u=Q=>{try{return new URL(Q).hostname}catch{return Q.replace(/^git@/,"").split(":")[0]||Q}},[m,h]=i.useState([]),[f,p]=i.useState(!1),[g,x]=i.useState(null),[v,b]=i.useState(""),[y,j]=i.useState(""),[C,A]=i.useState(null),[N,S]=i.useState(""),[_,T]=i.useState(""),[M,E]=i.useState(!1),[L,F]=i.useState([]),[R,P]=i.useState(!1),[O,q]=i.useState(null),[Z,z]=i.useState([]),[k,I]=i.useState(!1),[$,w]=i.useState(null),H=m.find(Q=>Q.name===O),[K,pe]=i.useState(null),[le,B]=i.useState(null),[ye,U]=i.useState(!1),[te,ne]=i.useState(null),[ee,ie]=i.useState(null),[ge,se]=i.useState(!1);i.useEffect(()=>{Ae()},[]),i.useEffect(()=>{e&&e.ahead>0?xe():e&&e.ahead===0&&F([])},[e?.ahead]),i.useEffect(()=>{m.length>0&&!O&&q(m[0].name)},[m]),i.useEffect(()=>{O?Se(O):(z([]),w(null))},[O]),i.useEffect(()=>{O&&!m.find(Q=>Q.name===O)&&q(m.length>0?m[0].name:null)},[m,O]);const Ae=async()=>{p(!0);try{const Q=await Ww(c);h(Q)}catch(Q){l(_e(Q)||"Failed to load remotes","error")}finally{p(!1)}},xe=async()=>{P(!0);try{const Q=await nk(c);F(Q)}catch{F([])}finally{P(!1)}},Se=async Q=>{I(!0),w(null);try{const Fe=await sk(Q,void 0,10,c);z(Fe)}catch(Fe){w(_e(Fe)||"Failed to load remote commits"),z([])}finally{I(!1)}},qe=qs(),We=async Q=>{if(Q.preventDefault(),!(!v.trim()||!y.trim())){x("add");try{await Kw(v.trim(),y.trim(),c),l(`Remote '${v}' added successfully`,"success"),b(""),j(""),E(!1),await Ae()}catch(Fe){l(_e(Fe)||"Failed to add remote","error")}finally{x(null)}}},Qe=async Q=>{if(await qe.confirm({title:"Remove Remote",message:`Are you sure you want to remove remote '${Q}'?`,danger:!0})){x(`remove-${Q}`);try{await Gw(Q,c),l(`Remote '${Q}' removed`,"success"),await Ae()}catch(Je){l(_e(Je)||"Failed to remove remote","error")}finally{x(null)}}},ve=async Q=>{if(_.trim()){x(`rename-${Q}`);try{await Jw(Q,_.trim(),c),l(`Remote renamed to '${_.trim()}'`,"success"),A(null),T(""),await Ae()}catch(Fe){l(_e(Fe)||"Failed to rename remote","error")}finally{x(null)}}},Oe=async Q=>{if(N.trim()){x(`url-${Q}`);try{await Yw(Q,N.trim(),c),l("Remote URL updated","success"),A(null),S(""),await Ae()}catch(Fe){l(_e(Fe)||"Failed to update remote URL","error")}finally{x(null)}}},ae=i.useCallback(async(Q,Fe)=>{if(Fe==="ahead"){if(K===Q){pe(null),B(null);return}pe(Q),B(null),U(!0);try{const Je=await nl(Q);B(Je)}catch{B(null)}finally{U(!1)}}else{if(te===Q){ne(null),ie(null);return}ne(Q),ie(null),se(!0);try{const Je=await nl(Q);ie(Je)}catch{ie(null)}finally{se(!1)}}},[K,te]),re=Q=>{A(`url-${Q.name}`),S(Q.pushUrl||Q.fetchUrl)},je=Q=>{A(`name-${Q.name}`),T(Q.name)};return t.jsx("div",{className:"gm-panel gm-remotes-panel","data-testid":"remotes-panel",children:t.jsxs("div",{className:"gm-remotes-layout",children:[t.jsxs("div",{className:"gm-remote-selector","data-testid":"remote-selector",children:[t.jsxs("div",{className:"gm-remote-selector-header",children:[t.jsx("span",{className:"gm-remote-selector-title",children:"Remotes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>E(!M),disabled:g!==null,title:M?"Cancel":"Add Remote",children:M?t.jsx(Jt,{size:14}):t.jsx(Sn,{size:14})})]}),M&&t.jsxs("form",{className:"gm-remote-form",onSubmit:We,children:[t.jsx("input",{type:"text",placeholder:"Remote name",value:v,onChange:Q=>b(Q.target.value),disabled:g==="add",className:"input gm-input"}),t.jsx("input",{type:"text",placeholder:"Repository URL",value:y,onChange:Q=>j(Q.target.value),disabled:g==="add",className:"input gm-input gm-input-url"}),t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:!v.trim()||!y.trim()||g==="add",children:[g==="add"?t.jsx(gt,{size:12,className:"spin"}):t.jsx(Sn,{size:12}),"Add"]})]}),f?t.jsxs("div",{className:"gm-loading",children:[t.jsx(gt,{size:16,className:"spin"}),"Loading..."]}):m.length===0?t.jsx("div",{className:"gm-empty",children:"No remotes"}):m.map(Q=>t.jsxs("div",{className:`gm-remote-selector-item${O===Q.name?" selected":""}`,onClick:()=>q(Q.name),role:"button",tabIndex:0,onKeyDown:Fe=>{(Fe.key==="Enter"||Fe.key===" ")&&(Fe.preventDefault(),q(Q.name))},children:[t.jsxs("div",{className:"gm-remote-selector-info",children:[t.jsxs("span",{className:"gm-remote-selector-name",children:[t.jsx("span",{className:"gm-remote-selector-name-text",children:Q.name}),Q.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),t.jsx("span",{className:"gm-remote-selector-host",title:Q.fetchUrl,children:u(Q.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm gm-remote-remove-btn",onClick:Fe=>{Fe.stopPropagation(),Qe(Q.name)},disabled:g!==null,title:"Remove remote",children:t.jsx(Cn,{size:14})})]},Q.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[O&&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:O}),e&&(e.ahead>0||e.behind>0)&&t.jsxs("div",{className:"gm-remote-status",children:[e.ahead>0&&t.jsxs("div",{className:"gm-remote-indicator ahead",children:[t.jsx("span",{className:"status-dot status-dot--online","aria-hidden":"true"}),t.jsx(Zi,{size:14}),e.ahead," to push"]}),e.behind>0&&t.jsxs("div",{className:"gm-remote-indicator behind",children:[t.jsx("span",{className:"status-dot status-dot--pending","aria-hidden":"true"}),t.jsx(Hr,{size:14}),e.behind," to pull"]})]})]}),t.jsxs("div",{className:"gm-remote-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:a,disabled:n!==null||f,children:[n==="fetch"?t.jsx(gt,{size:14,className:"spin"}):t.jsx(ns,{size:14}),"Fetch"]}),t.jsxs("button",{className:"btn btn-primary",onClick:r,disabled:n!==null||f,children:[n==="pull"?t.jsx(gt,{size:14,className:"spin"}):t.jsx(zs,{size:14}),"Pull"]}),t.jsxs("button",{className:"btn btn-primary",onClick:o,disabled:n!==null||f,children:[n==="push"?t.jsx(gt,{size:14,className:"spin"}):t.jsx(Zi,{size:14}),"Push"]})]})]}),t.jsxs("div",{className:"gm-remote-detail-card","data-testid":"remote-detail-card",children:[t.jsxs("div",{className:"gm-remote-detail-urls",children:[t.jsxs("div",{className:"gm-remote-detail-url-row",children:[t.jsx("span",{className:"gm-url-label",children:"Fetch:"}),C===`url-${O}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:N,onChange:Q=>S(Q.target.value),className:"input gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Oe(O),disabled:g===`url-${O}`,children:g===`url-${O}`?t.jsx(gt,{size:12,className:"spin"}):t.jsx(Yn,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{A(null),S("")},title:"Cancel",children:t.jsx(Jt,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:H.fetchUrl,children:t.jsx("bdo",{dir:"ltr",children:H.fetchUrl})}),t.jsxs("div",{className:"gm-remote-inline-actions",children:[t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>d(H.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:t.jsx(ta,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>re(H),disabled:g!==null,title:"Edit remote URL",children:t.jsx(xs,{size:14})})]})]})]}),H.pushUrl&&H.pushUrl!==H.fetchUrl&&t.jsxs("div",{className:"gm-remote-detail-url-row",children:[t.jsx("span",{className:"gm-url-label",children:"Push:"}),t.jsx("span",{className:"gm-url-value",title:H.pushUrl,children:t.jsx("bdo",{dir:"ltr",children:H.pushUrl})}),t.jsx("div",{className:"gm-remote-inline-actions",children:t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>d(H.pushUrl,"push URL"),title:"Copy push URL",children:t.jsx(ta,{size:14})})})]})]}),t.jsx("div",{className:"gm-remote-detail-name-row",children:C===`name-${O}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:_,onChange:Q=>T(Q.target.value),className:"input gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>ve(O),disabled:g===`rename-${O}`,children:g===`rename-${O}`?t.jsx(gt,{size:12,className:"spin"}):t.jsx(Yn,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{A(null),T("")},title:"Cancel",children:t.jsx(Jt,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>je(H),disabled:g!==null,title:"Edit remote name",children:t.jsx(xs,{size:14})})})]}),e&&e.ahead>0&&t.jsxs("div",{className:"gm-remote-section","data-testid":"commits-to-push",children:[t.jsx("div",{className:"gm-section-subheader",children:t.jsxs("h5",{children:[t.jsx(Zi,{size:14}),"Commits to Push (",e.ahead,")"]})}),R?t.jsxs("div",{className:"gm-loading",children:[t.jsx(gt,{size:14,className:"spin"}),"Loading..."]}):L.length>0?t.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:L.map(Q=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>ae(Q.hash,"ahead"),role:"button",tabIndex:0,onKeyDown:Fe=>{(Fe.key==="Enter"||Fe.key===" ")&&(Fe.preventDefault(),ae(Q.hash,"ahead"))},title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:Q.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:Q.message,children:Q.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:Q.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Fa(Q.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:K===Q.hash?t.jsx(un,{size:14}):t.jsx(Tn,{size:14})})]}),K===Q.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:ye?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(gt,{size:16,className:"spin"}),"Loading diff..."]}):le?t.jsxs(t.Fragment,{children:[Q.message&&t.jsx("div",{className:"gm-commit-message-full",children:Q.message}),le.stat&&t.jsx("pre",{className:"gm-diff-stat",children:le.stat}),t.jsx("pre",{className:"gm-diff-patch",children:le.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},Q.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(nf,{size:14}),"Recent commits on ",O]})}),k?t.jsxs("div",{className:"gm-loading",children:[t.jsx(gt,{size:14,className:"spin"}),"Loading commits..."]}):$?t.jsxs("div",{className:"gm-error",children:[t.jsx(Rs,{size:14}),$]}):Z.length===0?t.jsxs("div",{className:"gm-empty",children:["No commits found on ",O,". Try fetching first."]}):t.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:Z.map(Q=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>ae(Q.hash,"remote"),role:"button",tabIndex:0,onKeyDown:Fe=>{(Fe.key==="Enter"||Fe.key===" ")&&(Fe.preventDefault(),ae(Q.hash,"remote"))},title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:Q.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:Q.message,children:Q.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:Q.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Fa(Q.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:te===Q.hash?t.jsx(un,{size:14}):t.jsx(Tn,{size:14})})]}),te===Q.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:ge?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(gt,{size:16,className:"spin"}),"Loading diff..."]}):ee?t.jsxs(t.Fragment,{children:[Q.message&&t.jsx("div",{className:"gm-commit-message-full",children:Q.message}),ee.stat&&t.jsx("pre",{className:"gm-diff-stat",children:ee.stat}),t.jsx("pre",{className:"gm-diff-patch",children:ee.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},Q.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 fr={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function JI(e,n){return e&&n?`${e}/${n}`:""}function YI(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 QI(e){switch(e){case"file-text":return Fi;case"check-circle":return Ln;case"shield":return dy;case"zap":return Xn;case"eye":return Va;case"globe":return vl;case"layout-grid":return Ui;default:return Ln}}function XI(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 ZI({isOpen:e,onClose:n,addToast:s,projectId:a}){const[r,o]=i.useState([]),[l,c]=i.useState([]),[d,u]=i.useState(!0),[m,h]=i.useState(!0),[f,p]=i.useState("my-steps"),[g,x]=i.useState(null),[v,b]=i.useState(!1),[y,j]=i.useState(fr),[C,A]=i.useState(!1),[N,S]=i.useState(!1),[_,T]=i.useState(null),[M,E]=i.useState(null),[L,F]=i.useState({}),[R,P]=i.useState([]),O=i.useRef(null);wi(O,e,"fusion:workflow-steps-modal-size");const q=i.useCallback(async()=>{try{u(!0);const U=await Yr(a);o(U)}catch(U){s(_e(U)||"Failed to load workflow steps","error")}finally{u(!1)}},[s,a]),Z=i.useCallback(async()=>{try{const U=await Lr(a);F(U||{})}catch{}},[a]),z=i.useCallback(async()=>{try{const U=await Ms();P(U.models||[])}catch{}},[]),k=i.useCallback(async()=>{try{h(!0);const U=await tj();c(U.templates)}catch(U){s(_e(U)||"Failed to load templates","error")}finally{h(!1)}},[s]);i.useEffect(()=>{e&&(q(),k(),Z(),z())},[e,q,k,Z,z]);const I=i.useCallback(()=>{b(!0),x(null),j(fr)},[]),$=i.useCallback(U=>{x(U.id),b(!1),j({name:U.name,description:U.description,mode:U.mode||"prompt",phase:U.phase||"pre-merge",prompt:U.prompt,scriptName:U.scriptName||"",enabled:U.enabled,defaultOn:U.defaultOn||!1,modelProvider:U.modelProvider||"",modelId:U.modelId||""})},[]),w=i.useCallback(()=>{x(null),b(!1),j(fr)},[]),H=i.useCallback(async()=>{if(!y.name.trim()||!y.description.trim()){s("Name and description are required","error");return}A(!0);try{const U=y.mode==="prompt"&&y.modelProvider&&y.modelId?{modelProvider:y.modelProvider,modelId:y.modelId}:y.mode==="prompt"?{modelProvider:void 0,modelId:void 0}:{};if(v){const te={name:y.name.trim(),description:y.description.trim(),mode:y.mode,phase:y.phase,prompt:y.mode==="prompt"&&y.prompt.trim()||void 0,scriptName:y.mode==="script"?y.scriptName.trim():void 0,enabled:y.enabled,defaultOn:y.defaultOn||void 0,...U};await Uu(te,a),s("Workflow step created","success")}else g&&(await Xk(g,{name:y.name.trim(),description:y.description.trim(),mode:y.mode,phase:y.phase,prompt:y.mode==="prompt"?y.prompt:"",scriptName:y.mode==="script"?y.scriptName.trim():void 0,enabled:y.enabled,defaultOn:y.defaultOn,...U},a),s("Workflow step updated","success"));b(!1),x(null),j(fr),await q()}catch(U){s(_e(U)||"Failed to save workflow step","error")}finally{A(!1)}},[y,v,g,s,q]),K=i.useCallback(async U=>{try{await Zk(U,a),s("Workflow step deleted","success"),T(null),g===U&&(x(null),j(fr)),await q()}catch(te){s(_e(te)||"Failed to delete workflow step","error")}},[g,s,q]),pe=i.useCallback(async()=>{if(!(!g&&!v)&&y.mode==="prompt"){if(v){if(!y.name.trim()||!y.description.trim()){s("Name and description are required before refining","error");return}A(!0);try{const U=y.modelProvider&&y.modelId?{modelProvider:y.modelProvider,modelId:y.modelId}:{},te={name:y.name.trim(),description:y.description.trim(),mode:"prompt",prompt:y.prompt.trim()||void 0,enabled:y.enabled,defaultOn:y.defaultOn||void 0,...U},ne=await Uu(te,a);b(!1),x(ne.id),S(!0);const ee=await Bu(ne.id,a);j(ie=>({...ie,prompt:ee.prompt})),s("Prompt refined with AI","success"),await q()}catch(U){s(_e(U)||"Failed to refine prompt","error")}finally{A(!1),S(!1)}return}if(g){S(!0);try{const U=await Bu(g,a);j(te=>({...te,prompt:U.prompt})),s("Prompt refined with AI","success"),await q()}catch(U){s(_e(U)||"Failed to refine prompt","error")}finally{S(!1)}}}},[g,v,y,s,q]),le=i.useCallback(async U=>{E(U.id);try{await nj(U.id,a),s(`Added ${U.name} workflow step`,"success"),await q(),p("my-steps")}catch(te){const ne=_e(te);ne?.includes("already exists")?s(`A workflow step named '${U.name}' already exists`,"error"):s(ne||"Failed to add workflow step from template","error")}finally{E(null)}},[s,q]),B=Ri(n);if(!e)return null;const ye=v||g!==null;return t.jsx("div",{className:"modal-overlay open",...B,"data-testid":"workflow-step-manager",children:t.jsxs("div",{ref:O,className:"modal workflow-step-manager-modal",role:"dialog","aria-modal":"true","aria-label":"Workflow Steps",children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h2",{children:"Workflow Steps"}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]}),t.jsx("div",{className:"wfm-body",children:d?t.jsx("div",{className:"wfm-loading",children:"Loading..."}):t.jsxs(t.Fragment,{children:[!ye&&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(Zb,{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(Ui,{size:14}),"Templates (",l.length,")"]})]}),f==="my-steps"&&!ye&&t.jsxs(t.Fragment,{children:[r.length===0&&t.jsx("div",{className:"wfm-empty","data-testid":"empty-state",children:"No workflow steps defined. Create one to get started, or add one from the Templates tab."}),r.length>0&&t.jsx("div",{className:"wfm-step-list",children:r.map(U=>t.jsx("div",{className:"wfm-step-card","data-testid":`workflow-step-${U.id}`,children:t.jsxs("div",{className:"wfm-step-card-top",children:[t.jsxs("div",{className:"wfm-step-card-info",children:[t.jsxs("div",{className:"wfm-step-card-title-row",children:[t.jsx("span",{className:"wfm-step-card-name",children:U.name}),t.jsx("span",{className:`wfm-badge ${U.enabled?"wfm-badge-enabled":"wfm-badge-disabled"}`,children:U.enabled?"Enabled":"Disabled"}),t.jsx("span",{className:`wfm-badge ${(U.mode||"prompt")==="script"?"wfm-badge-script":"wfm-badge-prompt"}`,children:(U.mode||"prompt")==="script"?"Script":"AI Prompt"}),t.jsx("span",{className:`wfm-badge ${(U.phase||"pre-merge")==="post-merge"?"wfm-badge-post-merge":"wfm-badge-pre-merge"}`,children:(U.phase||"pre-merge")==="post-merge"?"Post-merge":"Pre-merge"}),U.defaultOn&&t.jsx("span",{className:"wfm-badge wfm-badge-default-on",children:"Default on"})]}),t.jsx("div",{className:"wfm-step-card-desc",children:U.description})]}),t.jsxs("div",{className:"wfm-step-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>$(U),title:"Edit","aria-label":`Edit ${U.name}`,children:t.jsx(xs,{size:14})}),_===U.id?t.jsxs("div",{className:"wfm-delete-confirm",children:[t.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>K(U.id),title:"Confirm delete","aria-label":`Confirm delete ${U.name}`,children:t.jsx(Yn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>T(null),title:"Cancel delete","aria-label":"Cancel delete",children:t.jsx(Jt,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>T(U.id),title:"Delete","aria-label":`Delete ${U.name}`,children:t.jsx(Cn,{size:14})})]})]})},U.id))})]}),f==="templates"&&!ye&&t.jsx(t.Fragment,{children:m?t.jsxs("div",{className:"wfm-loading",children:[t.jsx(gt,{size:24,className:"spin wfm-spinner"}),"Loading templates..."]}):l.length===0?t.jsx("div",{className:"wfm-empty","data-testid":"no-templates-state",children:"No templates available."}):t.jsx("div",{className:"wfm-template-list",children:l.map(U=>{const te=QI(U.icon),ne=XI(U.category),ee=M===U.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`template-${U.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(te,{size:20})}),t.jsxs("div",{className:"wfm-template-content",children:[t.jsxs("div",{className:"wfm-template-title-row",children:[t.jsx("span",{className:"wfm-template-name",children:U.name}),t.jsx("span",{className:ne,children:U.category})]}),t.jsx("div",{className:"wfm-template-desc",children:U.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>le(U),disabled:ee,"data-testid":`add-template-${U.id}`,children:ee?t.jsxs(t.Fragment,{children:[t.jsx(gt,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Sn,{size:12}),"Add"]})})]})]})},U.id)})})}),ye&&t.jsxs("div",{className:"wfm-form","data-testid":"workflow-step-form",children:[t.jsx("h3",{className:"wfm-form-title",children:v?"New Workflow Step":"Edit Workflow Step"}),t.jsxs("div",{className:"wfm-form-fields",children:[t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Name"}),t.jsx("input",{type:"text",value:y.name,onChange:U=>j(te=>({...te,name:U.target.value})),placeholder:"e.g. Documentation Review","data-testid":"workflow-step-name"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{value:y.description,onChange:U=>j(te=>({...te,description:U.target.value})),placeholder:"Brief description of what this step does",rows:2,"data-testid":"workflow-step-description"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Execution Mode"}),t.jsxs("div",{className:"wfm-mode-selector","data-testid":"workflow-step-mode-selector",children:[t.jsxs("button",{className:`btn ${y.mode==="prompt"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>j(U=>({...U,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[t.jsx(Ei,{size:14}),"AI Prompt"]}),t.jsxs("button",{className:`btn ${y.mode==="script"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>j(U=>({...U,mode:"script",prompt:"",modelProvider:"",modelId:""})),"data-testid":"mode-script",children:[t.jsx(Mi,{size:14}),"Run Script"]})]})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Execution Phase"}),t.jsxs("div",{className:"wfm-mode-selector","data-testid":"workflow-step-phase-selector",children:[t.jsx("button",{className:`btn ${y.phase==="pre-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>j(U=>({...U,phase:"pre-merge"})),"data-testid":"phase-pre-merge",children:"Pre-merge"}),t.jsx("button",{className:`btn ${y.phase==="post-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>j(U=>({...U,phase:"post-merge"})),"data-testid":"phase-post-merge",children:"Post-merge"})]}),t.jsx("div",{className:"wfm-field-hint",children:y.phase==="pre-merge"?"Runs before merge — can block merge on failure":"Runs after merge success — failures are logged but do not block"})]}),y.mode==="prompt"&&t.jsxs("div",{className:"wfm-field",children:[t.jsxs("div",{className:"wfm-prompt-header",children:[t.jsx("label",{children:"Agent Prompt"}),t.jsxs("button",{className:"btn-icon wfm-refine-btn",onClick:pe,disabled:!y.description.trim()||N,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[N?t.jsx(gt,{size:12,className:"spin"}):t.jsx(ms,{size:12}),t.jsx("span",{children:"Refine with AI"})]})]}),t.jsx("textarea",{value:y.prompt,onChange:U=>j(te=>({...te,prompt:U.target.value})),placeholder:"Leave empty to use AI refinement",rows:6,className:"wfm-prompt-textarea","data-testid":"workflow-step-prompt"})]}),y.mode==="prompt"&&t.jsxs("div",{className:"wfm-field","data-testid":"workflow-step-model-field",children:[t.jsxs("div",{className:"wfm-model-header",children:[t.jsx("label",{children:"Model Override"}),y.modelProvider&&y.modelId&&t.jsxs("button",{type:"button",className:"btn-icon wfm-model-clear-btn",onClick:()=>j(U=>({...U,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[t.jsx(Jt,{size:12}),t.jsx("span",{children:"Use default"})]})]}),t.jsx("span",{className:"wfm-model-hint",children:y.modelProvider&&y.modelId?`Using ${y.modelProvider}/${y.modelId}`:"Using global default model"}),t.jsx("div",{"data-testid":"workflow-step-model-select",children:t.jsx(hs,{models:R,value:JI(y.modelProvider,y.modelId),onChange:U=>{const te=YI(U);j(ne=>({...ne,modelProvider:te.provider,modelId:te.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(L).length===0?t.jsx("div",{className:"wfm-no-scripts","data-testid":"no-scripts-message",children:"No scripts configured. Add scripts in Settings → Scripts first."}):t.jsxs("select",{value:y.scriptName,onChange:U=>j(te=>({...te,scriptName:U.target.value})),"data-testid":"workflow-step-script-select",children:[t.jsx("option",{value:"",children:"Select a script…"}),Object.entries(L).map(([U,te])=>t.jsxs("option",{value:U,children:[U," (",te,")"]},U))]})]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:y.enabled,onChange:U=>j(te=>({...te,enabled:U.target.checked})),"data-testid":"workflow-step-enabled"}),"Enabled (available for selection on new tasks)"]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:y.defaultOn,onChange:U=>j(te=>({...te,defaultOn:U.target.checked})),"data-testid":"workflow-step-default-on"}),"Default on for new tasks"]}),t.jsxs("div",{className:"wfm-form-actions",children:[t.jsx("button",{className:"btn btn-secondary",onClick:w,disabled:C,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:H,disabled:C||!y.name.trim()||!y.description.trim()||y.mode==="script"&&!y.scriptName.trim(),"data-testid":"save-workflow-step",children:C?"Saving...":v?"Create":"Save"})]})]})]})]})}),!ye&&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(Sn,{size:14}),"Add Workflow Step"]})})]})})}const e4=36e5,t4=3e5,Kc=[{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 n4(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 s4(e){return typeof e!="number"||!Number.isFinite(e)?e4:Math.max(t4,Math.round(e))}function Kz(e){if(Kc.some(s=>s.value===e))return[...Kc];const n={value:e,label:`${n4(e)} (custom)`};return[...Kc,n].sort((s,a)=>s.value-a.value)}const i4=4,a4=5*6e4;function r4(e){const n=s4(e?.heartbeatIntervalMs);return Math.max(n*i4,a4)}function gp(e){const n=Math.floor(e/6e4);if(n<1)return"<1m";const s=Math.floor(n/60),a=n%60;return s>0&&a>0?`${s}h ${a}m`:s>0?`${s}h`:`${a}m`}function o4(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 l4(e){const{state:n,lastHeartbeatAt:s,lastError:a,pauseReason:r,runtimeConfig:o}=e,l=o4(e),c=l||o?.enabled!==!1;if(n==="terminated")return{label:"Terminated",icon:t.jsx(Os,{size:14}),color:"var(--state-error-text)",stateDerived:!0};if(n==="error")return{label:a??"Error",icon:t.jsx(Fs,{size:14}),color:"var(--state-error-text)",stateDerived:!a};if(n==="paused")return{label:r?`Paused: ${r}`:"Paused",icon:t.jsx(ii,{size:14}),color:"var(--state-paused-text)",stateDerived:!r};if(n==="running"||l&&n==="active")return{label:"Running",icon:t.jsx(Fs,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!c)return{label:"Heartbeat Disabled",icon:t.jsx(ii,{size:14}),color:"var(--state-paused-text)",stateDerived:!1};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:t.jsx(Rn,{size:14}),color:"var(--text-secondary)",stateDerived:!1};const d=new Date(s).getTime(),u=Date.now()-d,m=r4(o);if(u>m){const h=`No heartbeat for ${gp(u)} (threshold: ${gp(m)})`;return{label:"Unresponsive",icon:t.jsx(Fs,{size:14}),color:"var(--state-error-text)",stateDerived:!1,reason:h}}return{label:"Healthy",icon:t.jsx(mv,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}const gr=[{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 c4({isOpen:e,onClose:n,addToast:s,projectId:a}){const[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState(!1),[m,h]=i.useState(""),[f,p]=i.useState("custom"),[g,x]=i.useState("all"),[v,b]=i.useState(()=>{if(typeof window>"u")return"list";const $=Zn("fn-agent-view",a);return $==="board"||$==="list"?$:"list"});i.useEffect(()=>{const $=Zn("fn-agent-view",a);if($==="board"||$==="list"){b($);return}b("list")},[a]),i.useEffect(()=>{us("fn-agent-view",v,a)},[a,v]);const[y,j]=i.useState(null),C=i.useRef(null),[A,N]=i.useState(new Set),[S,_]=i.useState(new Map),{confirm:T}=qs(),M=i.useMemo(()=>S.size===0?r:r.map($=>{const w=S.get($.id);return w?{...$,state:w}:$}),[r,S]),E=i.useMemo(()=>g==="all"?M.filter($=>$.state!=="terminated"):M,[M,g]),L=i.useCallback(async()=>{c(!0);try{const w=await da(g!=="all"?{state:g}:void 0,a);o(w)}catch($){s(`Failed to load agents: ${_e($)}`,"error")}finally{c(!1)}},[g,s,a]);i.useEffect(()=>{e&&L()},[e,L]),i.useEffect(()=>{if(!e)return;const $=setInterval(()=>{L()},3e4);return()=>{clearInterval($)}},[e,L]);const F=async()=>{if(m.trim())try{await uj({name:m.trim(),role:f},a),s(`Agent "${m}" created`,"success"),h(""),u(!1),L()}catch($){s(`Failed to create agent: ${_e($)}`,"error")}},R=async($,w)=>{if(!A.has($)){N(H=>new Set(H).add($)),_(H=>{const K=new Map(H);return K.set($,w),K});try{await hj($,w,a),s(`Agent state updated to ${w}`,"success"),await L(),_(H=>{const K=new Map(H);return K.delete($),K})}catch(H){_(K=>{const pe=new Map(K);return pe.delete($),pe}),s(`Failed to update state: ${_e(H)}`,"error")}finally{N(H=>{const K=new Set(H);return K.delete($),K})}}},P=async($,w)=>{if(await T({title:"Delete Agent",message:`Delete agent "${w}"? This cannot be undone.`,danger:!0}))try{await pj($,a),s(`Agent "${w}" deleted`,"success"),L()}catch(K){s(`Failed to delete agent: ${_e(K)}`,"error")}},O=async($,w)=>{const H=r.find(K=>K.id===$);if(H){if(H.role===w){j(null);return}try{await mj($,{role:w},a),s(`Agent role updated to ${gr.find(K=>K.value===w)?.label??w}`,"success"),j(null),L()}catch(K){s(`Failed to update role: ${_e(K)}`,"error")}}},q=($,w)=>{$.key==="Escape"&&j(null)},Z=$=>gr.find(w=>w.value===$)?.label??$,z=$=>gr.find(w=>w.value===$)?.icon??"◆",k=$=>l4($),I=$=>$.color==="var(--state-active-text)"?"active":$.color==="var(--state-paused-text)"?"paused":$.color==="var(--state-error-text)"?"error":"muted";return e?t.jsx("div",{className:"modal-overlay open",onClick:$=>$.target===$.currentTarget&&n(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal--wide agent-list-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{className:"modal-title",children:[t.jsx(Rn,{size:20}),"Agents"]}),t.jsxs("div",{className:"modal-actions",children:[t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${v==="board"?" active":""}`,onClick:()=>b("board"),title:"Board view","aria-label":"Board view","aria-pressed":v==="board",children:t.jsx(Ui,{size:16})}),t.jsx("button",{className:`view-toggle-btn${v==="list"?" active":""}`,onClick:()=>b("list"),title:"List view","aria-label":"List view","aria-pressed":v==="list",children:t.jsx(od,{size:16})})]}),t.jsx("button",{className:"btn-icon",onClick:()=>void L(),title:"Refresh",disabled:l,children:t.jsx(ns,{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(Yo,{size:14}),t.jsxs("select",{className:"agent-state-filter-select",value:g,onChange:$=>x($.target.value),"aria-label":"Filter agents by state",children:[t.jsx("option",{value:"all",children:"All States"}),t.jsx("option",{value:"idle",children:"Idle"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"running",children:"Running"}),t.jsx("option",{value:"paused",children:"Paused"}),t.jsx("option",{value:"error",children:"Error"}),t.jsx("option",{value:"terminated",children:"Terminated"})]})]}),t.jsxs("button",{className:"btn btn-task-create btn-sm",onClick:()=>u(!d),children:[t.jsx(Sn,{size:16}),d?"Cancel":"New Agent"]})]}),d&&t.jsxs("div",{className:"agent-create-form",children:[t.jsx("input",{type:"text",placeholder:"Agent name...",value:m,onChange:$=>h($.target.value),onKeyDown:$=>$.key==="Enter"&&F(),className:"input",autoFocus:!0}),t.jsx("select",{className:"select",value:f,onChange:$=>p($.target.value),children:gr.map($=>t.jsxs("option",{value:$.value,children:[$.icon," ",$.label]},$.value))}),t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:()=>void F(),children:"Create"})]}),t.jsx("div",{className:v==="board"?"agent-board":"agent-list",children:E.length===0?t.jsxs("div",{className:"agent-empty",children:[t.jsx(Rn,{size:48,opacity:.3}),t.jsx("p",{children:"No agents found"}),t.jsx("p",{className:"text-secondary",children:"Create an agent to get started"})]}):v==="board"?E.map($=>{const w=k($),H=I(w);return t.jsxs("div",{className:"agent-board-card","data-state":$.state,children:[t.jsxs("div",{className:"agent-board-header",children:[t.jsx("span",{className:"agent-board-icon",children:z($.role)}),t.jsx("span",{className:"agent-board-badge","data-state":$.state,children:$.state}),t.jsx("span",{className:"agent-board-health","data-health":H,title:w.reason??w.label,children:w.icon})]}),t.jsx("div",{className:"agent-board-name",title:$.name,children:$.name}),t.jsx("div",{className:"agent-board-id",children:$.id}),t.jsxs("div",{className:"agent-board-actions",children:[$.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void R($.id,"active"),disabled:A.has($.id),title:"Activate",children:t.jsx(Hn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void P($.id,$.name),title:"Delete",children:t.jsx(Cn,{size:14})})]}),$.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void R($.id,"paused"),disabled:A.has($.id),title:"Pause",children:t.jsx(ii,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void R($.id,"terminated"),disabled:A.has($.id),title:"Stop",children:t.jsx(Os,{size:14})})]}),$.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void R($.id,"active"),disabled:A.has($.id),title:"Resume",children:t.jsx(Hn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void R($.id,"terminated"),disabled:A.has($.id),title:"Stop",children:t.jsx(Os,{size:14})})]}),$.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void R($.id,"paused"),disabled:A.has($.id),title:"Pause",children:t.jsx(ii,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void R($.id,"terminated"),disabled:A.has($.id),title:"Stop",children:t.jsx(Os,{size:14})})]}),$.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void R($.id,"active"),disabled:A.has($.id),title:"Retry",children:t.jsx(Hn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void R($.id,"terminated"),disabled:A.has($.id),title:"Stop",children:t.jsx(Os,{size:14})})]}),$.state==="terminated"&&t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void P($.id,$.name),title:"Delete",children:t.jsx(Cn,{size:14})})]})]},$.id)}):E.map($=>{const w=k($),H=I(w);return t.jsxs("div",{className:"agent-card","data-state":$.state,children:[t.jsxs("div",{className:"agent-card-header",children:[t.jsxs("div",{className:"agent-info",children:[y===$.id?t.jsx("select",{ref:C,className:"select agent-role-select",value:$.role,onChange:K=>void O($.id,K.target.value),onKeyDown:K=>q(K,$.id),onBlur:()=>j(null),autoFocus:!0,children:gr.map(K=>t.jsxs("option",{value:K.value,children:[K.icon," ",K.label]},K.value))}):t.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>j($.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&j($.id)},children:z($.role)}),t.jsxs("div",{className:"agent-meta",children:[t.jsx("span",{className:"agent-name",children:$.name}),t.jsx("span",{className:"agent-id text-secondary",children:$.id})]})]}),t.jsxs("div",{className:"agent-badges",children:[t.jsx("span",{className:"badge agent-list-state-badge","data-state":$.state,children:$.state}),t.jsxs("span",{className:"badge agent-list-health-badge","data-health":H,title:w.reason??w.label,children:[w.icon,!w.stateDerived&&` ${w.label}`]}),t.jsx("span",{className:"badge text-secondary",children:Z($.role)})]})]}),t.jsxs("div",{className:"agent-card-body",children:[$.taskId&&t.jsxs("div",{className:"agent-task",children:[t.jsx("span",{className:"text-secondary",children:"Working on:"}),t.jsx("span",{className:"badge",children:$.taskId})]}),$.lastHeartbeatAt&&t.jsxs("div",{className:"agent-heartbeat",children:[t.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),t.jsx("span",{children:new Date($.lastHeartbeatAt).toLocaleString()})]})]}),t.jsxs("div",{className:"agent-card-actions",children:[$.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void R($.id,"active"),disabled:A.has($.id),title:"Activate",children:[t.jsx(Hn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void P($.id,$.name),title:"Delete",children:[t.jsx(Cn,{size:14})," Delete"]})]}),$.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void R($.id,"paused"),disabled:A.has($.id),title:"Pause",children:[t.jsx(ii,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void R($.id,"terminated"),disabled:A.has($.id),title:"Stop",children:[t.jsx(Os,{size:14})," Stop"]})]}),$.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void R($.id,"active"),disabled:A.has($.id),title:"Resume",children:[t.jsx(Hn,{size:14})," Resume"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void R($.id,"terminated"),disabled:A.has($.id),title:"Stop",children:[t.jsx(Os,{size:14})," Stop"]})]}),$.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void R($.id,"paused"),disabled:A.has($.id),title:"Pause",children:[t.jsx(ii,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void R($.id,"terminated"),disabled:A.has($.id),title:"Stop",children:[t.jsx(Os,{size:14})," Stop"]})]}),$.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void R($.id,"active"),disabled:A.has($.id),title:"Retry",children:[t.jsx(Hn,{size:14})," Retry"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void R($.id,"terminated"),disabled:A.has($.id),title:"Stop",children:[t.jsx(Os,{size:14})," Stop"]})]}),$.state==="terminated"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm btn-task-create",onClick:()=>void R($.id,"active"),disabled:A.has($.id),title:"Start",children:[t.jsx(Hn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void P($.id,$.name),title:"Delete",children:[t.jsx(Cn,{size:14})," Delete"]})]})]})]},$.id)})})]})]})}):null}function d4({authenticated:e,onToggled:n,compact:s=!1}){const[a,r]=i.useState(null),[o,l]=i.useState(null),[c,d]=i.useState(null),u=i.useRef(!0);i.useEffect(()=>(u.current=!0,()=>{u.current=!1}),[]);const m=i.useCallback(async()=>{try{const b=await Ew();return u.current&&r(b),b}catch(b){return u.current&&d({kind:"error",message:b instanceof Error?b.message:String(b)}),null}},[]);i.useEffect(()=>{m()},[m]);const h=i.useCallback(async()=>{l("testing"),d(null),await m(),u.current&&l(null)},[m]),f=i.useCallback(async b=>{l(b?"enabling":"disabling"),d(null);try{const y=await Pw(b);u.current&&d({kind:y.enabled?"enabled":"disabled",restartRequired:y.restartRequired}),n?.(y.enabled),await m()}catch(y){u.current&&d({kind:"error",message:y instanceof Error?y.message:String(y)})}finally{u.current&&l(null)}},[n,m]),p=a?.binary.available??!1,g=a?.enabled??e,x=t.jsxs("span",{className:"onboarding-provider-card__description",children:["Route AI calls through your locally-installed ",t.jsx("code",{children:"claude"})," CLI. Uses your existing Claude subscription / quota instead of an API key."]}),v=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(gt,{size:12,className:"animate-spin"}),"Testing…"]}):"Test"}),g?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void f(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void f(!0),disabled:o!==null||!p,title:p?void 0:"`claude` binary not detected on PATH — install Claude CLI first.",children:o==="enabling"?"Enabling…":"Enable"})]});return s?t.jsxs("div",{className:`auth-provider-card auth-provider-card--cli${e?" auth-provider-card--authenticated":""}`,"data-testid":"claude-cli-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(qn,{provider:"claude-cli",size:"sm"}),t.jsx("strong",{children:"Anthropic — via Claude CLI"}),t.jsx(u4,{status:a,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:v})]}),t.jsxs("details",{className:"auth-provider-cli-details",children:[t.jsx("summary",{children:"Details"}),t.jsxs("div",{className:"auth-provider-cli-details-body",children:[x,t.jsx(bp,{status:a,authenticated:e}),c&&t.jsx(xp,{action:c})]})]})]}):t.jsxs("div",{className:`onboarding-provider-card${e?" onboarding-provider-card--connected":""}`,"data-testid":"claude-cli-provider-card",children:[t.jsx("div",{className:"onboarding-provider-card__icon",children:t.jsx(qn,{provider:"claude-cli",size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:"Anthropic — via Claude CLI"}),x,t.jsx(bp,{status:a,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(xp,{action:c})]})}function u4({status:e,authenticated:n}){const s=e?.enabled??n,a=e?.binary.available??!1;return s?t.jsx("span",{className:"auth-status-badge authenticated",children:"✓ Active"}):!a&&e?t.jsx("span",{className:"auth-status-badge not-authenticated",children:"✗ Not installed"}):t.jsx("span",{className:"auth-status-badge not-authenticated",children:"✗ Not connected"})}function bp({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(gt,{size:10,className:"animate-spin"})," Probing local CLI…"]});const{binary:s,enabled:a,extension:r,ready:o}=e;return s.available?a?r&&r.status!=="ok"?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--warning",children:["⚠ Extension load failed: ",r.reason??r.status]}):o||n?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--connected",children:["✓ Connected",s.version?` — ${s.version}`:""]}):t.jsx("small",{className:"settings-muted",children:"Enabled. Validating…"}):t.jsxs("small",{className:"settings-muted",children:[t.jsx("code",{children:"claude"})," ",s.version?`(${s.version})`:""," detected",s.binaryPath?` at ${s.binaryPath}`:"",". Click Enable to route AI calls through it."]}):t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--error",children:["✗ ",s.reason??"`claude` not found on PATH"]})}function xp({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 m4({authenticated:e,onToggled:n,compact:s=!1}){const[a,r]=i.useState(null),[o,l]=i.useState(null),[c,d]=i.useState(null),u=i.useRef(!0);i.useEffect(()=>(u.current=!0,()=>{u.current=!1}),[]);const m=i.useCallback(async()=>{try{const b=await Aw();return u.current&&r(b),b}catch(b){return u.current&&d({kind:"error",message:b instanceof Error?b.message:String(b)}),null}},[]);i.useEffect(()=>{m()},[m]);const h=i.useCallback(async()=>{l("testing"),d(null),await m(),u.current&&l(null)},[m]),f=i.useCallback(async b=>{l(b?"enabling":"disabling"),d(null);try{const y=await Rw(b);u.current&&d({kind:y.enabled?"enabled":"disabled",restartRequired:y.restartRequired}),n?.(y.enabled),await m()}catch(y){u.current&&d({kind:"error",message:y instanceof Error?y.message:String(y)})}finally{u.current&&l(null)}},[n,m]),p=a?.binary.available??!1,g=a?.enabled??e,x=t.jsxs("span",{className:"onboarding-provider-card__description",children:["Route AI calls through your locally-installed ",t.jsx("code",{children:"droid"})," CLI. Uses your existing Factory AI subscription / quota instead of an API key."]}),v=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(gt,{size:12,className:"animate-spin"}),"Testing…"]}):"Test"}),g?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void f(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void f(!0),disabled:o!==null||!p,title:p?void 0:"`droid` binary not detected on PATH — install Droid CLI first.",children:o==="enabling"?"Enabling…":"Enable"})]});return s?t.jsxs("div",{className:`auth-provider-card auth-provider-card--cli${e?" auth-provider-card--authenticated":""}`,"data-testid":"droid-cli-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(qn,{provider:"droid-cli",size:"sm"}),t.jsx("strong",{children:"Factory AI — via Droid CLI"}),t.jsx(h4,{status:a,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:v})]}),t.jsxs("details",{className:"auth-provider-cli-details",children:[t.jsx("summary",{children:"Details"}),t.jsxs("div",{className:"auth-provider-cli-details-body",children:[x,t.jsx(vp,{status:a,authenticated:e}),c&&t.jsx(yp,{action:c})]})]})]}):t.jsxs("div",{className:`onboarding-provider-card${e?" onboarding-provider-card--connected":""}`,"data-testid":"droid-cli-provider-card",children:[t.jsx("div",{className:"onboarding-provider-card__icon",children:t.jsx(qn,{provider:"droid-cli",size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:"Factory AI — via Droid CLI"}),x,t.jsx(vp,{status:a,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(yp,{action:c})]})}function h4({status:e,authenticated:n}){const s=e?.enabled??n,a=e?.binary.available??!1;return s?t.jsx("span",{className:"auth-status-badge authenticated",children:"✓ Active"}):!a&&e?t.jsx("span",{className:"auth-status-badge not-authenticated",children:"✗ Not installed"}):t.jsx("span",{className:"auth-status-badge not-authenticated",children:"✗ Not connected"})}function vp({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(gt,{size:10,className:"animate-spin"})," Probing local CLI…"]});const{binary:s,enabled:a,extension:r,ready:o}=e;return s.available?a?r&&r.status!=="ok"?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--warning",children:["⚠ Extension load failed: ",r.reason??r.status]}):o||n?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--connected",children:["✓ Connected",s.version?` — ${s.version}`:""]}):t.jsx("small",{className:"settings-muted",children:"Enabled. Validating…"}):t.jsxs("small",{className:"settings-muted",children:[t.jsx("code",{children:"droid"})," ",s.version?`(${s.version})`:""," detected",s.binaryPath?` at ${s.binaryPath}`:"",". Click Enable to route AI calls through it."]}):t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--error",children:["✗ ",s.reason??"`droid` not found on PATH"]})}function yp({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 p4(e){const n="([A-Z0-9]{2,}(?:-[A-Z0-9]{2,})+|[A-Z0-9]{6,9})",s=new RegExp(`\\b(?:device\\s+code|your\\s+code|code)\\s*(?:is|:)?\\s*${n}\\b`,"i"),a=new RegExp(`\\b(?:enter|use)\\s+${n}\\b`,"i"),r=/\b([A-Z0-9]{2,}(?:-[A-Z0-9]{2,})+)\b/,o=e.match(s);if(o?.[1])return o[1];const l=e.match(a);if(l?.[1])return l[1];const c=e.match(r);return c?.[1]?c[1]:null}function Gc({instructions:e,"data-testid":n}){const[s,a]=i.useState(!1),r=p4(e),o=i.useRef(null),l=i.useCallback(()=>{a(!0),setTimeout(()=>a(!1),2e3)},[]),c=i.useCallback(async()=>{const d=r??e;try{await navigator.clipboard.writeText(d),l()}catch{}},[r,e,l]);return i.useEffect(()=>{const d=o.current===null&&r!==null;if(o.current=r,!d)return;(async()=>{try{await navigator.clipboard.writeText(r),l()}catch{}})()},[r,l]),t.jsx("p",{className:"auth-login-instructions","data-testid":n,children:r?t.jsx(t.Fragment,{children:e.split(r).map((d,u,m)=>t.jsxs("span",{children:[d,u<m.length-1&&t.jsxs("span",{className:"device-code-wrapper",children:[t.jsx("code",{className:"device-code",children:r}),t.jsx("button",{className:"device-code-copy-btn",onClick:c,title:s?"Copied!":"Copy code","aria-label":s?"Copied to clipboard":"Copy device code",type:"button",children:s?t.jsx(Yn,{size:12}):t.jsx(ta,{size:12})})]})]},u))}):e})}const f4=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"]),g4=/^[a-z][a-z0-9-]*$/,wp=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function kp(){return{id:"",name:"",reasoning:!1}}function b4({initialConfig:e,onSave:n,onCancel:s,saving:a=!1,error:r}){const o=!!e,[l,c]=i.useState(e?.id??""),[d,u]=i.useState(e?.name??""),[m,h]=i.useState(e?.baseUrl??""),[f,p]=i.useState(e?.api??"openai-completions"),[g,x]=i.useState(e?.apiKey??""),[v,b]=i.useState(e?.models?.length?e.models:[kp()]),[y,j]=i.useState(null),C=v.length>1,A=i.useMemo(()=>y??r??null,[y,r]);function N(M,E){b(L=>L.map((F,R)=>R===M?{...F,...E}:F))}function S(M){b(E=>E.length<=1?E:E.filter((L,F)=>F!==M))}function _(){if(!l.trim())return"Provider ID is required.";if(!g4.test(l.trim()))return"Provider ID must be kebab-case.";if(!o&&f4.has(l.trim()))return"Provider ID conflicts with a built-in provider.";if(!m.trim())return"Base URL is required.";try{const M=new URL(m.trim());if(M.protocol!=="http:"&&M.protocol!=="https:")return"Base URL must use http or https."}catch{return"Base URL must be a valid URL."}return wp.includes(f)?v.length===0?"At least one model is required.":v.some(M=>!M.id?.trim())?"Each model must have a model ID.":null:"API type is required."}async function T(M){M.preventDefault();const E=_();j(E),!E&&await n({id:l.trim(),name:d.trim()||void 0,baseUrl:m.trim(),api:f,apiKey:g.trim()||void 0,models:v.map(L=>({id:L.id.trim(),name:L.name?.trim()||void 0,reasoning:!!L.reasoning,contextWindow:L.contextWindow,maxTokens:L.maxTokens}))})}return t.jsxs("form",{onSubmit:T,className:"custom-provider-form","aria-label":"custom-provider-form",children:[t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-id",children:"Provider ID"}),t.jsx("input",{id:"custom-provider-id",className:"input",value:l,onChange:M=>c(M.target.value),disabled:o||a})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-name",children:"Display Name"}),t.jsx("input",{id:"custom-provider-name",className:"input",value:d,onChange:M=>u(M.target.value),disabled:a})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-base-url",children:"Base URL"}),t.jsx("input",{id:"custom-provider-base-url",className:"input",value:m,onChange:M=>h(M.target.value),disabled:a})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-api",children:"API Type"}),t.jsx("select",{id:"custom-provider-api",className:"select",value:f,onChange:M=>p(M.target.value),disabled:a,children:wp.map(M=>t.jsx("option",{value:M,children:M},M))})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-api-key",children:"API Key"}),t.jsx("input",{id:"custom-provider-api-key",className:"input",placeholder:"sk-..., MY_API_KEY, or !command",value:g,onChange:M=>x(M.target.value),disabled:a})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{children:"Models"}),t.jsx("div",{className:"custom-provider-form__models",children:v.map((M,E)=>t.jsxs("div",{className:"custom-provider-form__model-row",children:[t.jsx("input",{className:"input","aria-label":`Model ID ${E+1}`,placeholder:"Model ID",value:M.id,onChange:L=>N(E,{id:L.target.value}),disabled:a}),t.jsx("input",{className:"input","aria-label":`Model name ${E+1}`,placeholder:"Display name",value:M.name??"",onChange:L=>N(E,{name:L.target.value}),disabled:a}),t.jsxs("label",{className:"checkbox-label custom-provider-form__toggle",children:[t.jsx("input",{type:"checkbox",checked:!!M.reasoning,onChange:L=>N(E,{reasoning:L.target.checked}),disabled:a}),"Reasoning"]}),t.jsx("input",{className:"input","aria-label":`Context window ${E+1}`,placeholder:"Context window",type:"number",value:M.contextWindow??"",onChange:L=>N(E,{contextWindow:L.target.value?Number(L.target.value):void 0}),disabled:a}),t.jsx("input",{className:"input","aria-label":`Max tokens ${E+1}`,placeholder:"Max tokens",type:"number",value:M.maxTokens??"",onChange:L=>N(E,{maxTokens:L.target.value?Number(L.target.value):void 0}),disabled:a}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>S(E),disabled:a||!C,"aria-label":`Remove model ${E+1}`,children:"×"})]},`${E}-model`))}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>b(M=>[...M,kp()]),disabled:a,children:"+ Add model"})]}),A?t.jsx("div",{className:"form-error",children:A}):null,t.jsxs("div",{className:"custom-provider-form__actions",children:[s?t.jsx("button",{type:"button",className:"btn",onClick:s,disabled:a,children:"Cancel"}):null,t.jsx("button",{type:"submit",className:"btn btn-primary",disabled:a,children:a?"Saving...":"Save Provider"})]})]})}const x4=new Set(["google-antigravity","antigravity","google-gemini-cli"]);function v4(e){return!x4.has(e)}function jp(e){return e.filter(n=>v4(n.id))}const oa="fusion_model_onboarding_state",Ua=[],Ba=[],pl=!1,fl=!1,Ha={},y4=void 0,Li=["ai-setup","github","project-setup","first-task"],w4={"ai-setup":"AI Setup",github:"GitHub","project-setup":"Project","first-task":"First Task",complete:"Complete"};function Bs(){if(typeof window>"u")return null;try{const e=localStorage.getItem(oa);if(!e)return null;const n=JSON.parse(e);return n&&typeof n=="object"&&"currentStep"in n&&typeof n.currentStep=="string"?k4(n):null}catch{return null}}function k4(e){const n=e.postOnboardingDismissedAt??y4;return{...e,completedSteps:e.completedSteps??Ua,skippedSteps:e.skippedSteps??Ba,dismissed:e.dismissed??pl,completed:e.completed??fl,stepData:e.stepData??Ha,...n?{postOnboardingDismissedAt:n}:{}}}function Fo(e,n){if(!(typeof window>"u")){if(!n){const s={currentStep:e,updatedAt:new Date().toISOString(),completedSteps:Ua,skippedSteps:Ba,dismissed:pl,completed:fl,stepData:Ha};try{localStorage.setItem(oa,JSON.stringify(s))}catch{}return}try{const s=Bs(),a=new Date().toISOString(),r=n.completed??fl;let o=n.dismissed??pl;r&&(o=!1);const l=n.completedSteps??s?.completedSteps??Ua,c=n.skippedSteps??s?.skippedSteps??Ba,d={...s?.stepData??Ha};if(n.stepData)for(const[m,h]of Object.entries(n.stepData))h!==void 0&&(d[m]={...d[m]??{},...h});const u={currentStep:e,updatedAt:a,completedSteps:l,skippedSteps:c,dismissed:o,completed:r,stepData:d};localStorage.setItem(oa,JSON.stringify(u))}catch{}}}function j4(e){if(!(typeof window>"u"))try{const n=Bs(),s=new Date().toISOString();if(!n){const o={currentStep:e,updatedAt:s,completedSteps:Ua,skippedSteps:[e],dismissed:pl,completed:fl,stepData:Ha};localStorage.setItem(oa,JSON.stringify(o));return}const a=n.skippedSteps.includes(e)?n.skippedSteps:[...n.skippedSteps,e],r={...n,skippedSteps:a,completedSteps:n.completedSteps.filter(o=>o!==e),updatedAt:s};localStorage.setItem(oa,JSON.stringify(r))}catch{}}function Np(){if(!(typeof window>"u"))try{const e=Bs(),n=new Date().toISOString(),s=e?{...e,completedAt:n,completed:!0,dismissed:!1,updatedAt:n}:{currentStep:"complete",updatedAt:n,completedAt:n,completedSteps:Ua,skippedSteps:Ba,dismissed:!1,completed:!0,stepData:Ha};localStorage.setItem(oa,JSON.stringify(s))}catch{}}function qa(){const e=Bs();return e?e.completed===!0?!0:typeof e.completedAt=="string"&&e.completedAt.length>0:!1}function N4(){if(!(typeof window>"u"))try{const e=Bs(),n=new Date().toISOString(),s=e?{...e,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:Ua,skippedSteps:Ba,dismissed:!1,completed:!1,stepData:Ha,postOnboardingDismissedAt:n};localStorage.setItem(oa,JSON.stringify(s))}catch{}}function xb(){const e=Bs();return e?typeof e.postOnboardingDismissedAt=="string"&&e.postOnboardingDismissedAt.length>0:!1}function S4(){const e=Bs();return!e||qa()?!1:e.currentStep!=="complete"}function C4(){const e=Bs();if(!e||qa()||e.currentStep==="complete")return null;const n=e.currentStep,s=w4[n]??_4(e.currentStep);return{currentStep:e.currentStep,label:s,completedSteps:e.completedSteps}}function E4(){const e=Bs();return e?e.skippedSteps:Ba}function M4(e){const n=Bs();return!n||!n.stepData?null:n.stepData[e]??null}function _4(e){return e.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const vb="fusion_onboarding_events",Sp="fusion_onboarding_session_id",A4=200,P4=50;function Gs(e,n={}){if(!(typeof window>"u"))try{const s=T4(),a=D4(n.step),r={type:e,timestamp:new Date().toISOString(),...a?{step:a}:{},metadata:n,sessionId:R4()},o=$4([...s,r]);I4(o)}catch{}}function R4(){if(typeof window>"u")return"server-session";try{const e=sessionStorage.getItem(Sp);if(e)return e;const n=Cp();return sessionStorage.setItem(Sp,n),n}catch{return Cp()}}function Cp(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function T4(){try{const e=localStorage.getItem(vb);if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(L4):[]}catch{return[]}}function I4(e){try{localStorage.setItem(vb,JSON.stringify(e))}catch{}}function $4(e){const n=[...e];for(;n.length>A4;)n.splice(0,P4);return n}function D4(e){if(e==="ai-setup"||e==="github"||e==="first-task"||e==="complete")return e}function L4(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 O4=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}))??[]}),z4={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"}}},yb={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:"..."}},F4={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},Ep={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 Id(e){if(Ep[e])return Ep[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 Jc=["anthropic","openai","google","gemini","ollama"],U4=["anthropic","claude-cli","droid-cli","openai-codex","gemini","minimax","kimi","zai"],B4={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"},H4={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function $d(e){return B4[e]??e}function Mp(e){const n=$d(e),s=U4.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function _p(e,n){if(e.authenticated!==n.authenticated)return e.authenticated?-1:1;const s=Mp(e.id),a=Mp(n.id);if(s!==a)return s-a;const r=$d(e.id),o=$d(n.id);if(r!==o)return r.localeCompare(o);const l=H4[r];if(l){const d=l.indexOf(e.id),u=l.indexOf(n.id);if(d!==u)return(d===-1?Number.POSITIVE_INFINITY:d)-(u===-1?Number.POSITIVE_INFINITY:u)}const c=e.name.localeCompare(n.name);return c!==0?c:e.id.localeCompare(n.id)}function q4(e,n){const s=n.trim();if(!s)return"API key is required";const a=yb[e]??F4;return a.pattern.test(s)?null:`${Id(e)} keys should follow this format: ${a.hint} (e.g. ${a.example})`}const wb={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"},V4={description:"AI provider — connect to start using AI models",apiKeyInfo:wb};function Dd(e){return z4[e]??V4}function W4(e){return Dd(e.id).apiKeyInfo??wb}function K4({items:e}){return e.some(s=>s.status!=="connected")?t.jsxs("div",{className:"onboarding-readiness-summary","data-testid":"readiness-summary",role:"status",children:[t.jsx("p",{className:"onboarding-readiness-header",children:"Setup Summary"}),e.map(s=>{const a=s.status==="connected"?"✓":s.status==="missing"?"⚠":"○";return t.jsxs("div",{className:`onboarding-readiness-item onboarding-readiness-item--${s.status}`,"data-status":s.status,children:[t.jsx("span",{className:"onboarding-readiness-icon","aria-hidden":"true",children:a}),t.jsxs("span",{className:"onboarding-readiness-content",children:[t.jsx("span",{className:"onboarding-readiness-label",children:s.label}),s.detail&&t.jsx("span",{className:"onboarding-readiness-detail",children:s.detail})]})]},s.label)})]}):t.jsx("div",{className:"onboarding-readiness-summary","data-testid":"readiness-summary",role:"status",children:t.jsx("p",{className:"onboarding-readiness-all-connected",children:"✓ All integrations connected"})})}function G4({provider:e,apiKeyInfo:n,inputValue:s,isSaving:a,error:r,success:o,isConnected:l,onInputChange:c,onSave:d,onClear:u}){const m=`onboarding-apikey-input-${e.id}`,h=a||!s.trim(),f=yb[e.id],p=`input onboarding-apikey-input${r?" onboarding-apikey-input--error":""}${o?" onboarding-apikey-input--success":""}`,g=t.jsxs(t.Fragment,{children:[f&&t.jsxs("small",{className:"onboarding-apikey-hint",children:["Format: ",f.hint]}),t.jsx("p",{className:"onboarding-apikey-instructions",children:n.setupInstructions}),n.dashboardUrl&&t.jsx("a",{href:n.dashboardUrl,target:"_blank",rel:"noreferrer",className:"onboarding-apikey-dashboard-link",children:"Get your API key →"}),t.jsx("p",{className:"onboarding-apikey-usage",children:n.usageDescription})]});return l?t.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${e.id}`,children:[t.jsxs("div",{className:"onboarding-apikey-connected-header",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:n.fieldLabel}),t.jsx("span",{className:"auth-status-badge connected",children:"✓ API key saved"})]}),t.jsx("button",{className:"btn btn-sm",onClick:()=>u(e.id),disabled:a,children:a?"Removing…":"Remove Key"}),t.jsx(Js,{summary:"Advanced setup details",children:g}),r&&t.jsx("small",{className:"field-error",children:r})]}):t.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${e.id}`,children:[t.jsx("label",{htmlFor:m,className:"onboarding-apikey-field-label",children:n.fieldLabel}),t.jsxs("div",{className:"onboarding-apikey-input-row",children:[t.jsx("input",{id:m,type:"password",className:p,placeholder:n.inputPlaceholder??"Enter API key",value:s,onChange:x=>c(e.id,x.target.value),onKeyDown:x=>{x.key==="Enter"&&d(e.id,s)},"data-testid":m}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>d(e.id,s),disabled:h,"data-testid":`onboarding-apikey-save-${e.id}`,children:a?"Saving…":"Save"})]}),r&&t.jsx("small",{className:"field-error",children:r}),o&&!r&&t.jsx("small",{className:"onboarding-apikey-success","data-testid":`onboarding-apikey-success-${e.id}`,children:o}),t.jsx(Js,{summary:"Advanced setup details",children:g})]})}const J4=150;function Y4({onComplete:e,addToast:n,projectId:s,onOpenSetupWizard:a,onOpenNewTask:r,onOpenGitHubImport:o,firstCreatedTask:l,onViewTask:c}){const d=Bs(),u=d?.currentStep,m=u==="complete"?"ai-setup":Li.includes(u)?u:"ai-setup",h=d?.completedSteps??[],f=d?.skippedSteps??E4(),[p,g]=i.useState(!0),[x,v]=i.useState(m),[b,y]=i.useState(h),[j,C]=i.useState(f),[A,N]=i.useState(!1),[S,_]=i.useState(""),[T,M]=i.useState(!1),[E,L]=i.useState(null),[F,R]=i.useState(null),[P,O]=i.useState([]),[q,Z]=i.useState(void 0),[z,k]=i.useState(!0),[I,$]=i.useState(null),[w,H]=i.useState({}),[K,pe]=i.useState([]),[le,B]=i.useState(""),[ye,U]=i.useState(!1),[te,ne]=i.useState({}),[ee,ie]=i.useState({}),[ge,se]=i.useState({}),[Ae,xe]=i.useState([]),[Se,qe]=i.useState(!1),[We,Qe]=i.useState(!1),[ve,Oe]=i.useState(),ae=i.useRef({}),re=i.useRef(null),je=i.useRef(null),Q=i.useRef(null),[Fe,Je]=i.useState({}),[be,ze]=i.useState(()=>Bs()?.stepData?.github?.skipped===!0),tt=i.useRef(0),kt=i.useRef(l),ke=i.useRef(!1),ce=d?.currentStep,Te=!!d&&d.currentStep!=="complete";wi(je,p,"fusion:model-onboarding-modal-size"),i.useEffect(()=>{const G=re.current;G&&(G.scrollTop=0)},[x]);const[he,Le]=i.useState(()=>Bs()?.stepData?.["ai-setup"]?.skippedProviders??{}),st=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"project-setup",label:"Project"},{key:"first-task",label:"First Task"}],it=st.findIndex(G=>G.key===x),lt=x==="complete"?st.length:it;i.useEffect(()=>{x!=="complete"&&Fo(x,{completedSteps:b,skippedSteps:j})},[x,b,j]),i.useEffect(()=>{ke.current||(ke.current=!0,Gs("onboarding:wizard-opened",{source:Te?"resume":"initial",resumedFromStep:ce}))},[Te,ce]),i.useEffect(()=>{const G=kt.current!=null,He=l!=null;!G&&He&&N(!0),He||N(!1),kt.current=l},[l]);const $e=i.useRef(m);i.useEffect(()=>{if($e.current==="ai-setup"&&x!=="ai-setup"&&!P.some(He=>He.id!=="github"&&He.authenticated)){const He={};for(const mt of P)mt.id!=="github"&&!mt.authenticated&&!he[mt.id]&&(He[mt.id]=!0);if(Object.keys(He).length>0){const mt={...he,...He};Le(mt),Fo(x,{stepData:{"ai-setup":{skippedProviders:mt}}})}}$e.current=x},[x,P,he]);const Ue=i.useCallback(async()=>{try{const{providers:G,ghCli:He}=await Dr(),mt=jp(G);O(mt),Z(He),H(ht=>{const Et={};for(const[St,sn]of Object.entries(ht)){const nn=mt.find(as=>as.id===St);nn&&!nn.authenticated&&nn.loginInProgress&&(Et[St]=sn)}return Object.keys(Et).length===Object.keys(ht).length?ht:Et}),Je(ht=>{let Et=!1;const St={...ht};for(const[sn,nn]of Object.entries(ht)){if(nn!=="pending")continue;mt.find(Is=>Is.id===sn)?.loginInProgress||(delete St[sn],Et=!0)}return Et?St:ht}),Le(ht=>{const Et={...ht};for(const St of mt)St.authenticated&&Et[St.id]&&delete Et[St.id];return Object.keys(Et).length===Object.keys(ht).length?ht:Et})}catch{}},[]),Xe=i.useCallback(async()=>{try{const G=await Tw();xe((G.providers??[]).map(O4))}catch{}},[]),wt=i.useCallback(async G=>{Qe(!0),Oe(void 0);try{await $w(G),await Xe(),await Ms().then(He=>pe(He.models??[])),qe(!1)}catch(He){Oe(_e(He)||"Failed to create custom provider")}finally{Qe(!1)}},[Xe]),Re=i.useRef(!1);i.useEffect(()=>{x==="ai-setup"&&Xe(),Re.current&&Ue(),Re.current=x!=="ai-setup"},[x,Ue,Xe]),i.useEffect(()=>{if(!P.some(mt=>mt.loginInProgress))return;const He=setInterval(()=>{Ue()},2e3);return()=>clearInterval(He)},[P,Ue]);const xt=P.find(G=>G.id==="github"),Pt=!!xt,Ct=xt?.authenticated??!1,Ot=xt?.loginInProgress??!1,zt=q?.authenticated??!1,Nt=Ct||zt,jt=!Ct&&zt,Yt=i.useCallback(G=>{if(G.authenticated)return"connected";const He=Fe?.[G.id];return He==="timeout"||He==="failed"?"retry":he[G.id]?"skipped":"not-connected"},[Fe,he]);function Bt({status:G}){const He={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:mt,className:ht}=He[G];return t.jsx("span",{"data-testid":"provider-status-badge",className:ht,"data-status":G,children:mt})}const qt=i.useCallback(()=>{if(Nt)return"connected";const G=Fe.github;return G==="pending"?"pending":G==="failed"||G==="timeout"?"failed":be?"skipped":"not-connected"},[Nt,Fe,be]);function wn({status:G}){const He={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:mt,className:ht}=He[G];return t.jsx("span",{"data-testid":"github-status-badge",className:ht,"data-status":G,children:mt})}const mn=i.useCallback(async()=>{try{const G=await Ms();pe(G.models)}catch{}},[]),Xt=i.useCallback(async()=>{try{const G=await ca();if(G.defaultProvider&&G.defaultModelId){const He=`${G.defaultProvider}/${G.defaultModelId}`;B(He)}}catch{}},[]);i.useEffect(()=>{Promise.all([Ue(),mn(),Xt()]).finally(()=>k(!1))},[Ue,mn,Xt]),i.useEffect(()=>{const G=M4("ai-setup");if(G?.loginOutcomes){const He=G.loginOutcomes,mt={};for(const[ht,Et]of Object.entries(He))Et!=="pending"&&(mt[ht]=Et);Object.keys(mt).length>0&&Je(mt)}},[]);const Vt=i.useCallback((G,He)=>{Fo(x,{completedSteps:b,stepData:{"ai-setup":{loginOutcomes:{[G]:He}}}})},[x,b]);i.useEffect(()=>{const G=Object.entries(Fe).filter(([He,mt])=>mt!=="pending");for(const[He,mt]of G)Vt(He,mt)},[Fe,Vt]),i.useEffect(()=>()=>{Q.current&&clearInterval(Q.current),Object.values(ae.current).forEach(clearTimeout),ae.current={}},[]);const Ft=i.useCallback(G=>{ze(G),Fo(x,{completedSteps:b,stepData:{github:{skipped:G}}})},[x,b]),Zt=i.useCallback(G=>G==="complete"?-1:Li.indexOf(G),[]),en=i.useCallback(()=>{y(He=>[...new Set([...He,x])]),C(He=>He.filter(mt=>mt!==x)),Gs("onboarding:step-completed",{step:x}),x==="github"&&!Ct&&Ft(!1);const G=Zt(x);G>=0&&G<Li.length-1&&v(Li[G+1])},[x,Ct,Ft,Zt]),cn=i.useCallback(()=>{C(He=>[...new Set([...He,x])]),j4(x),Gs("onboarding:step-skipped",{step:x}),x==="github"&&!Ct&&Ft(!0);const G=Zt(x);G>=0&&G<Li.length-1&&v(Li[G+1])},[x,Ct,Ft,Zt]),we=i.useCallback(()=>{const G=x;y(mt=>mt.filter(ht=>ht!==G)),C(mt=>mt.filter(ht=>ht!==G)),G==="github"&&!Ct&&Ft(!1);const He=Zt(x);He>0&&v(Li[He-1])},[x,Ct,Ft,Zt]),De=i.useCallback(()=>{cn()},[cn]),oe=i.useCallback(async G=>{Je(He=>{const mt=He[G];if(mt&&mt!=="pending"){const{[G]:ht,...Et}=He;return Et}return He}),H(He=>{if(!(G in He))return He;const mt={...He};return delete mt[G],mt}),Je(He=>({...He,[G]:"pending"})),$(G),tt.current=0;try{const{url:He,instructions:mt}=await Dw(G);mt?.trim()&&H(ht=>({...ht,[G]:mt})),window.open(xi(He),"_blank"),Q.current=setInterval(async()=>{if(tt.current++,tt.current>=J4){Q.current&&(clearInterval(Q.current),Q.current=null),$(null),Je(ht=>({...ht,[G]:"timeout"})),H(ht=>{if(!(G in ht))return ht;const Et={...ht};return delete Et[G],Et}),n("Login timed out. Please try again.","warning");return}try{const{providers:ht,ghCli:Et}=await Dr(),St=jp(ht);O(St),Z(Et),St.find(nn=>nn.id===G)?.authenticated&&(Q.current&&(clearInterval(Q.current),Q.current=null),$(null),Je(nn=>({...nn,[G]:"success"})),H(nn=>{if(!(G in nn))return nn;const as={...nn};return delete as[G],as}),G==="github"&&Ft(!1),n("Login successful","success"))}catch{}},2e3)}catch(He){He instanceof Error&&He.message.includes("already in progress")||He&&typeof He=="object"&&"status"in He&&He.status===409?(n("Login already in progress. Cancel it to retry.","warning"),Je(ht=>({...ht,[G]:"pending"})),Ue()):(n(He instanceof Error?He.message:"Login failed","error"),Je(ht=>({...ht,[G]:"failed"}))),$(null),H(ht=>{if(!(G in ht))return ht;const Et={...ht};return delete Et[G],Et})}},[n,Ue,Ft]),Pe=i.useCallback(async G=>{Q.current&&(clearInterval(Q.current),Q.current=null),$(G),tt.current=0;try{await Ow(G),await Ue(),Je(He=>({...He,[G]:"cancelled"})),n("Login cancelled","success")}catch(He){n(_e(He)||"Failed to cancel login","error")}finally{$(null),H(He=>{if(!(G in He))return He;const mt={...He};return delete mt[G],mt})}},[n,Ue]),Ce=i.useCallback((G,He)=>{ne(ht=>({...ht,[G]:He}));const mt=ae.current[G];mt&&(clearTimeout(mt),delete ae.current[G]),ie(ht=>{if(!ht[G])return ht;const Et={...ht};return delete Et[G],Et}),se(ht=>{if(!ht[G])return ht;const Et={...ht};return delete Et[G],Et})},[]),J=i.useCallback(()=>{const G=re.current;if(!G)return;const He=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof G.scrollTo=="function"){G.scrollTo({top:0,behavior:He?"auto":"smooth"});return}}catch{}G.scrollTop=0},[]),Ie=i.useCallback(async(G,He)=>{const mt=(He??te[G]??"").trim(),ht=q4(G,mt);if(ht){ie(St=>({...St,[G]:ht}));return}const Et=ae.current[G];Et&&(clearTimeout(Et),delete ae.current[G]),$(G),ie(St=>{const sn={...St};return delete sn[G],sn}),se(St=>{if(!St[G])return St;const sn={...St};return delete sn[G],sn});try{await zw(G,mt),await Ue(),J(),ne(St=>{const sn={...St};return delete sn[G],sn}),ie(St=>{if(!St[G])return St;const sn={...St};return delete sn[G],sn}),se(St=>({...St,[G]:"✓ Key saved"})),ae.current[G]=setTimeout(()=>{se(St=>{if(!St[G])return St;const sn={...St};return delete sn[G],sn}),delete ae.current[G]},3e3),n("API key saved","success")}catch(St){const sn=St instanceof TypeError&&St.message.includes("Failed to fetch")?"Could not reach the server. Check your connection and try again.":St instanceof Error?St.message:"Failed to save API key";ie(nn=>({...nn,[G]:sn})),se(nn=>{if(!nn[G])return nn;const as={...nn};return delete as[G],as}),n(sn,"error")}finally{$(null)}},[te,n,Ue,J]),de=i.useCallback(async G=>{$(G);try{await Fw(G),await Ue(),n("API key removed","success")}catch(He){n(He instanceof Error?He.message:"Failed to clear API key","error")}finally{$(null)}},[n,Ue]),Ne=i.useCallback(async G=>{$(G);try{await Lw(G),await Ue(),n("Logged out","success")}catch(He){n(He instanceof Error?He.message:"Logout failed","error")}finally{$(null)}},[n,Ue]),Ye=i.useCallback(G=>{B(G)},[]),ft=i.useCallback(async()=>{try{const G={modelOnboardingComplete:!0};if(le){const He=le.indexOf("/"),mt=He!==-1?le.slice(0,He):void 0,ht=He!==-1?le.slice(He+1):le,Et=K.find(St=>St.id===ht);Et?(G.defaultProvider=Et.provider,G.defaultModelId=Et.id):mt&&ht&&(G.defaultProvider=mt,G.defaultModelId=ht)}await _n(G),Np()}catch{}},[le,K,_n,Np]),tn=i.useCallback(async()=>{const G=[...new Set([...b,"first-task"])];U(!0);try{await ft(),Gs("onboarding:completed",{completedSteps:G,skippedSteps:j}),y(G),C(He=>He.filter(mt=>mt!=="first-task")),v("complete")}finally{U(!1)}},[ft,b,j]),$t=i.useCallback(async()=>{if(!s)return;const G=S.trim();if(!G){L("Please enter a task description.");return}L(null),M(!0);let He=!1;try{const mt=await tl({description:G,source:{sourceType:"dashboard_ui"}},s);R(mt),N(!0),Gs("onboarding:first-task-created",{taskId:mt?.id}),n("Task created","success"),He=!0}catch(mt){const ht=mt instanceof Error?mt.message:"Something went wrong creating your task. Please try again.";L(ht),n(ht,"error")}finally{M(!1)}He&&ft()},[s,S,n,ft]),Rt=i.useCallback(async()=>{U(!0);try{await ft()}finally{U(!1)}Gs("onboarding:open-new-task",{}),r?.()},[ft,r]),Dt=i.useCallback(async()=>{if(Nt){U(!0);try{await ft()}finally{U(!1)}g(!1),e(),Gs("onboarding:open-github-import",{}),o?.()}},[ft,Nt,e,o]),En=i.useCallback(async()=>{Gs("onboarding:dismissed",{currentStep:x,completedSteps:b,skippedSteps:j}),U(!0);try{await _n({modelOnboardingComplete:!0})}catch{}g(!1),e()},[x,b,j,e]),bn=i.useCallback(()=>{Gs("onboarding:finished",{}),g(!1),e()},[e]),Nn=i.useCallback(()=>{const G=l??F;G&&(ft(),c?.(G),e())},[l,F,ft,c,e]),dn=i.useCallback(()=>{ft(),e()},[ft,e]);if(!p)return null;const xn=qt(),rn=P.filter(G=>G.id!=="github"),On=[...rn].sort(_p),fe=On.some(G=>!G.type||G.type==="oauth"),ct=On.some(G=>G.type==="api_key"),hn=rn.filter(G=>G.authenticated),zn=hn.length>0,ue=!!s,ut=x==="github"&&!zn,yt=(()=>{if(!le)return"";const G=le.indexOf("/"),He=G===-1?void 0:le.slice(0,G),mt=G===-1?le:le.slice(G+1),ht=K.find(Et=>Et.id===mt&&(!He||Et.provider===He));return ht?.name?ht.name:He?`${Id(He)} ${mt}`:le})(),dt=[];if(ue?dt.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):dt.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),zn){const G=Id(hn[0]?.id??"");dt.push({label:"AI Provider",status:"connected",detail:`${G} connected — AI agents can work on tasks`})}else rn.length>0&&rn.some(G=>he[G.id])?dt.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):dt.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});Nt?dt.push({label:"GitHub",status:"connected",detail:jt?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!Pt||be?dt.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):dt.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),yt&&dt.push({label:"Default Model",status:"connected",detail:yt});const at=l??F,vt=at?.description?.split(`
682
+ `)[0]?.trim()||at?.title||"",Ht=new Set(Jc),Ut=On.filter(G=>Ht.has(G.id)).sort((G,He)=>{const mt=Jc.indexOf(G.id),ht=Jc.indexOf(He.id);return mt!==ht?mt-ht:_p(G,He)}),An=On.filter(G=>G.authenticated&&!Ht.has(G.id)),Wt=On.filter(G=>!G.authenticated&&!Ht.has(G.id)),Tt=G=>{if(G.id==="droid-cli"&&G.type==="cli")return t.jsx(m4,{authenticated:G.authenticated,onToggled:()=>{Ue()}},G.id);if(G.id==="claude-cli"&&G.type==="cli")return t.jsx(d4,{authenticated:G.authenticated,onToggled:()=>{Ue()}},G.id);if(G.type==="api_key"){const He=Dd(G.id),mt=W4(G);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${G.id}`,className:`onboarding-provider-card${G.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${G.id}`,"aria-hidden":"true",children:t.jsx(qn,{provider:G.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(ef,{size:14,className:"onboarding-provider-key-icon"}),G.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:He.description}),t.jsx(Bt,{status:Yt(G)}),G.authenticated&&G.keyHint&&t.jsxs("span",{className:"auth-key-hint",children:["Key: ",G.keyHint]})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx(G4,{provider:G,apiKeyInfo:mt,inputValue:te[G.id]??"",isSaving:I===G.id,error:ee[G.id],success:ge[G.id],isConnected:G.authenticated,onInputChange:Ce,onSave:Ie,onClear:de})})]},G.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${G.id}`,className:`onboarding-provider-card${G.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${G.id}`,"aria-hidden":"true",children:t.jsx(qn,{provider:G.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:G.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:Dd(G.id).description}),t.jsx(Bt,{status:Yt(G)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:I===G.id?G.authenticated?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void Pe(G.id),children:"Cancel"})]}):G.loginInProgress?t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void Pe(G.id),children:"Cancel"})]}):G.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>Ne(G.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>oe(G.id),children:"Login"})}),(I===G.id||G.loginInProgress)&&w[G.id]&&t.jsx(Gc,{instructions:w[G.id],"data-testid":`onboarding-login-instructions-${G.id}`}),Fe[G.id]==="timeout"&&I!==G.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),Fe[G.id]==="failed"&&I!==G.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},G.id)};return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"onboarding-title",children:t.jsxs("div",{className:"modal model-onboarding-modal",ref:je,children:[t.jsxs("div",{className:"model-onboarding-header",children:[t.jsxs("h2",{id:"onboarding-title",className:"model-onboarding-title",children:[x==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(Xn,{size:24})," Set Up AI ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(zs,{size:24})," Connect GitHub ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(ju,{size:24})," Set Up Your Project"]}),x==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(ju,{size:24})," Create Your First Task"]}),x==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx(Ln,{size:24})," All Set!"]})]}),x!=="complete"&&t.jsx("button",{className:"modal-close",onClick:En,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(Jt,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:st.map((G,He)=>{const mt=lt>He,ht=b.includes(G.key)&&mt,Et=j.includes(G.key)&&!b.includes(G.key)&&mt,St=ht||Et;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[He>0&&t.jsx("div",{className:`model-onboarding-step-connector ${He<=lt?"done":""}`}),St?t.jsxs("button",{className:`model-onboarding-step-indicator ${x===G.key?"active":""} ${ht?"done":""} ${Et?"skipped":""}`,onClick:()=>v(G.key),"aria-label":`Go back to ${G.label}`,title:`Review ${G.label}`,children:[t.jsx("span",{className:"step-number",children:ht?t.jsx(Ln,{size:14}):Et?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):He+1}),t.jsx("span",{className:"step-label",children:G.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${x===G.key?"active":""} ${ht?"done":""} ${Et?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:ht?t.jsx(Ln,{size:14}):Et?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):He+1}),t.jsx("span",{className:"step-label",children:G.label})]})]},G.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:re,children:[x==="ai-setup"&&t.jsxs("div",{className:"model-onboarding-ai-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Fusion uses AI models to plan, write, and review code for you. Connect an AI provider below to get started — you can use a hosted service or enter an API key."}),t.jsx("p",{className:"onboarding-helper-text model-onboarding-primary-helper",children:"You only need one provider to get started."}),!z&&P.length>0&&(()=>{const G=P.filter(St=>St.id!=="github"&&St.authenticated).length,He=P.filter(St=>St.id!=="github").length,mt=Object.keys(he).filter(St=>!P.find(sn=>sn.id===St)?.authenticated).length;if(He===0)return null;let ht="onboarding-provider-summary",Et="";return G>0?(ht+=" onboarding-provider-summary--connected",Et=`✓ ${G} of ${He} provider${He!==1?"s":""} connected`):mt>0?(ht+=" onboarding-provider-summary--skipped",Et=`${mt} provider${mt!==1?"s":""} skipped`):(ht+=" onboarding-provider-summary--none",Et="No providers connected yet"),t.jsx("div",{className:ht,"data-testid":"provider-summary",children:Et})})(),t.jsx(Oi,{slotId:"onboarding-recommendation-card",projectId:s}),t.jsx(Js,{summary:"What are AI providers?",children:t.jsx("p",{className:"onboarding-helper-text",children:"AI providers like OpenAI and Anthropic power the AI capabilities in Fusion. Connecting a provider lets Fusion's agents use AI models to help with your tasks."})}),P.length>0&&!P.some(G=>G.authenticated)&&t.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),z?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(gt,{size:24,className:"animate-spin"}),t.jsx("span",{children:"Loading providers…"})]}):P.length===0?t.jsx("div",{className:"model-onboarding-empty",children:"No AI providers are configured. Please check your Fusion configuration."}):t.jsxs(t.Fragment,{children:[t.jsx(Oi,{slotId:"onboarding-provider-card",projectId:s}),t.jsxs("section",{className:"onboarding-provider-section","data-testid":"onboarding-quick-start-providers",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Quick start providers"}),Ut.length>0?t.jsx("div",{className:"model-onboarding-providers",children:Ut.map(G=>Tt(G))}):t.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),An.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:An.map(G=>Tt(G))})]}),t.jsxs("div",{className:"onboarding-model-section",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Default Model (Optional)"}),t.jsx("p",{className:"model-onboarding-description",children:"Pick a default model for AI tasks, or leave this blank to choose later. Models vary in speed, capability, and cost."}),t.jsx(Js,{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."})}),K.length===0?t.jsx("div",{className:"model-onboarding-empty",children:"No models available yet. Connect a provider above to see model options."}):t.jsx("div",{className:"onboarding-model-selector",children:t.jsx(hs,{models:K,value:le,onChange:Ye,placeholder:"Select a default model…",label:"Default model"})}),le&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",K.find(G=>G.id===le)?.name??le]})})]}),t.jsx(Js,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:t.jsxs("div",{"data-testid":"onboarding-advanced-provider-settings",children:[Wt.length>0?t.jsx("div",{className:"model-onboarding-providers",children:Wt.map(G=>Tt(G))}):t.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."}),Ae.length>0?t.jsx("div",{className:"onboarding-custom-provider-list",children:Ae.map(G=>t.jsxs("div",{className:"onboarding-custom-provider-item",children:[t.jsx(qn,{provider:G.id,size:"sm"}),t.jsx("span",{children:G.name||G.id})]},G.id))}):null,Se?t.jsx(b4,{onSave:wt,onCancel:()=>{qe(!1),Oe(void 0)},saving:We,error:ve}):t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>qe(!0),children:"Add custom provider"})]})}),fe&&t.jsx(Js,{summary:"How does login work?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Clicking Login opens the provider's website in a new tab where you sign in. Once you authorize Fusion, this page will automatically detect the connection. Your credentials are never stored in Fusion."})}),ct&&t.jsx(Js,{summary:"What is an API key?",children:t.jsx("p",{className:"onboarding-helper-text",children:"An API key is a secret token that authenticates Fusion with the provider. You can find your key in the provider's dashboard under API settings. Keys are stored securely on your machine."})}),t.jsx(Oi,{slotId:"onboarding-setup-help",projectId:s})]})]}),x==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[Nt?t.jsx("p",{className:"model-onboarding-description",children:jt?"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."}),!Nt&&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"})]})}),ut&&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(Js,{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(zs,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(wn,{status:xn})})]}),Ct&&(I==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>Ne("github"),children:"Disconnect"}))]}),(xn==="not-connected"||xn==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[I==="github"||Ot?t.jsxs("div",{className:"onboarding-github-connect-actions",children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void Pe("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>oe("github"),children:[t.jsx(zs,{size:16}),"Connect"]}),(I==="github"||Ot)&&w.github&&t.jsx(Gc,{instructions:w.github,"data-testid":"onboarding-login-instructions-github"})]}),xn==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:jt?"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."}),xn==="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:()=>oe("github"),children:"Retry"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:De,children:"Skip for now"})]})]}),xn==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),xn==="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:()=>oe("github"),children:"Connect anyway"})})]}),xn==="not-connected"&&t.jsx("p",{className:"onboarding-helper-text",children:"No worries if you're not ready — connect GitHub anytime from Settings → Authentication."})]}):t.jsxs("div",{className:"model-onboarding-github-optional",children:[t.jsx("div",{className:"optional-icon optional-icon--github","aria-hidden":"true",children:t.jsx(qn,{provider:"github",size:"lg"})}),jt?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:jt?"Continue with gh CLI auth →":"Continue without GitHub →"}),jt&&(I==="github"||Ot?t.jsxs("button",{className:"btn btn-sm",disabled:!0,children:[t.jsx(gt,{size:14,className:"onboarding-spinner"}),"Waiting for OAuth login…"]}):t.jsxs("button",{className:"btn btn-sm",onClick:()=>oe("github"),children:[t.jsx(qn,{provider:"github",size:"sm"}),"Connect OAuth (optional)"]}))]}),jt&&(I==="github"||Ot)&&w.github&&t.jsx(Gc,{instructions:w.github,"data-testid":"onboarding-login-instructions-github"})]})]}),x==="project-setup"&&t.jsxs("div",{className:"model-onboarding-project-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Choose your first project before creating or importing tasks. You can register an existing local directory or clone a GitHub repository URL through the setup wizard."}),ue?t.jsx("div",{className:"onboarding-project-ready","data-testid":"onboarding-project-ready",role:"status",children:t.jsx("p",{children:"Project selected — task creation and imports are available."})}):t.jsxs("div",{className:"onboarding-project-prerequisite","data-testid":"onboarding-project-prerequisite",children:[t.jsx("p",{className:"onboarding-helper-text",children:"A project is required before first-task actions are available."}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:a,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"}),t.jsx("p",{className:"onboarding-helper-text",children:"In the setup wizard, pick an existing directory or paste a GitHub clone URL."})]}),t.jsx(Js,{summary:"What does project setup do?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Project setup registers a workspace so Fusion knows where to read files, run commands, and track task changes."})})]}),x==="first-task"&&t.jsxs("div",{className:"model-onboarding-first-task",children:[t.jsx("p",{className:"model-onboarding-description",children:"Create your first task to start the board and launch AI execution."}),A&&at?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx(Ln,{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:at.id}),vt&&t.jsx("p",{className:"onboarding-task-created__description",children:vt}),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:Nn,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:dn,children:"Go to Dashboard"})]})]}):t.jsxs(t.Fragment,{children:[ue?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"onboarding-first-task-form",children:[t.jsx("label",{className:"onboarding-first-task-form__label",htmlFor:"onboarding-first-task-input",children:"Describe your first task"}),t.jsx("textarea",{id:"onboarding-first-task-input",className:"input onboarding-first-task-form__input","data-testid":"onboarding-first-task-input",value:S,onChange:G=>{_(G.target.value),L(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:$t,disabled:T,"data-testid":"onboarding-first-task-submit",children:T?t.jsxs(t.Fragment,{children:[t.jsx(gt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),E&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:E}),t.jsx("p",{className:"onboarding-helper-text",children:"Your text has been preserved — fix the issue and try again."})]})]}):t.jsxs("div",{className:"onboarding-project-prerequisite","data-testid":"onboarding-project-prerequisite",children:[t.jsx("p",{className:"onboarding-helper-text",children:"A project must be selected before you can create tasks or import from GitHub."}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:a,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"})]}),t.jsx(K4,{items:dt}),ue&&t.jsxs(t.Fragment,{children:[t.jsx(Js,{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:Rt,disabled:ye,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(Sn,{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${Nt?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:Dt,disabled:ye||!Nt,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(zs,{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"}),!Nt&&t.jsx("small",{className:"onboarding-cta-note",children:"Requires GitHub connection"})]})]})]}),t.jsxs("p",{className:"onboarding-skip-note",children:["You can create tasks anytime from the board, or use"," ",t.jsx("code",{children:"fn task create"})," in the terminal."]})]})]})]}),x==="complete"&&t.jsxs("div",{className:"model-onboarding-complete",children:[t.jsx(Ln,{size:48,className:"success-icon"}),t.jsx("p",{children:"Setup complete! Head to the board to create your first task, or explore the dashboard to see what's available."})]})]}),t.jsxs("div",{className:"model-onboarding-footer",children:[x==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:En,disabled:ye,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:cn,children:"Skip setup →"}),t.jsx("button",{className:"btn btn-primary",onClick:en,children:"Next →"})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:we,children:"← Back"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:cn,children:"Skip GitHub →"}),t.jsx("button",{className:"btn btn-primary",onClick:en,children:"Next →"})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:we,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:en,disabled:!ue,children:"Next →"})]}),x==="first-task"&&!A&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:we,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:tn,disabled:ye,children:ye?t.jsxs(t.Fragment,{children:[t.jsx(gt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),x==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:bn,children:[t.jsx(Ln,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function kb({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 Q4=i.lazy(()=>Mn(()=>import("./SetupWizardModal-Dw6N4UvY.js"),__vite__mapDeps([9,1,10,11,12,4,5,13])).then(e=>({default:e.SetupWizardModal}))),X4=i.lazy(()=>Mn(()=>import("./SettingsModal-BN00HYJ2.js"),__vite__mapDeps([14,1,15,16,17,2,4,5,18])).then(e=>({default:e.SettingsModal})));function Z4(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{Mn(()=>import("./SettingsModal-BN00HYJ2.js"),__vite__mapDeps([14,1,15,16,17,2,4,5,18]))},{timeout:1500})}function e$({projectId:e,tasks:n,projects:s,currentProject:a,addToast:r,toasts:o,removeToast:l,modalManager:c,projectActions:d,taskHandlers:u,taskOperations:m,deepLink:h,settings:f,onSettingsClose:p,onReopenOnboarding:g}){const[x,v]=i.useState(null),b=c.detailTask?(()=>{const S=n.find(_=>_.id===c.detailTask?.id);return S?"prompt"in c.detailTask?{...c.detailTask,...S,prompt:c.detailTask.prompt,log:c.detailTask.log}:S:c.detailTask})():null,y=p??c.closeSettings,j=i.useCallback(()=>{c.openNewTask()},[c]),C=i.useCallback(()=>{c.openGitHubImport()},[c]),A=i.useCallback(S=>{v(null),c.closeModelOnboarding(),c.openDetailTask(S)},[c]),N=i.useCallback(async S=>{const _=await u.handleModalCreate(S);return c.modelOnboardingOpen&&v(_),_},[u.handleModalCreate,c.modelOnboardingOpen]);return i.useEffect(()=>{!c.modelOnboardingOpen&&x&&v(null)},[c.modelOnboardingOpen,x]),i.useEffect(()=>{Z4()},[]),t.jsxs(t.Fragment,{children:[b&&t.jsx(Ki,{children:t.jsx(RP,{task:b,projectId:e,tasks:n,onClose:h.handleDetailClose,onOpenDetail:c.openDetailTask,mobileHeaderMode:c.detailTaskOrigin==="list-mobile"?"back":"close",onMoveTask:m.moveTask,onDeleteTask:m.deleteTask,onMergeTask:m.mergeTask,onRetryTask:m.retryTask,onResetTask:m.resetTask,onDuplicateTask:m.duplicateTask,onTaskUpdated:c.updateDetailTask,addToast:r,prAuthAvailable:f.prAuthAvailable,initialTab:c.detailTaskInitialTab})}),c.settingsOpen&&t.jsx(Ki,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(X4,{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(TR,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:u.handleGitHubImport,tasks:n,projectId:e}),t.jsx(Ki,{children:t.jsx(qR,{isOpen:c.isPlanningOpen,onClose:c.closePlanning,onTaskCreated:u.handlePlanningTaskCreated,onTasksCreated:u.handlePlanningTasksCreated,tasks:n,initialPlan:c.planningInitialPlan??void 0,projectId:e,resumeSessionId:c.planningResumeSessionId})}),t.jsx(Ki,{children:t.jsx(eT,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:u.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx(kT,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx(NT,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx(WT,{initialWorkspace:c.fileBrowserWorkspace,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),c.todosOpen&&t.jsx(YT,{isOpen:!0,onClose:c.closeTodos,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan}),t.jsx(aI,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e,anchorRect:c.usageAnchorRect}),t.jsx(II,{isOpen:c.systemStatsOpen,onClose:c.closeSystemStats,projectId:e}),c.schedulesOpen&&t.jsx(SI,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx(Ki,{children:t.jsx(_I,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:N,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan,onSubtaskBreakdown:c.openSubtaskBreakdown})}),t.jsx(zI,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:a,onOpenTaskDetail:S=>{const _=n.find(T=>T.id===S);_&&c.openDetailTask(_)}}),t.jsx(Ki,{children:t.jsx(UI,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx(Ki,{children:t.jsx(ZI,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(c4,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(i.Suspense,{fallback:null,children:t.jsx(Q4,{onProjectRegistered:d.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(Y4,{onComplete:d.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:d.handleAddProject,onOpenNewTask:j,onOpenGitHubImport:C,firstCreatedTask:x,onViewTask:A}),t.jsx(kb,{toasts:o,onRemove:l})]})}function t$({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 n$(e,n){if(n==="ready")return"done";const s=Ld.findIndex(r=>r.id===n),a=Ld.findIndex(r=>r.id===e);return a<s?"done":a===s?"active":"pending"}function s$({stage:e}){const[n]=i.useState(()=>Ay());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 a=n$(s.id,e);return t.jsxs("li",{className:`dashboard-loader__step dashboard-loader__step--${a}`,"data-testid":`dashboard-loader-step-${s.id}`,children:[t.jsx("span",{className:"dashboard-loader__step-icon","aria-hidden":"true",children:a==="done"?"✓":a==="active"?t.jsx(gt,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:s.label})]},s.id)})})]})})}const i$=5e3;function a$(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function r$(e,n,s){let a=0,r=0,o=0,l=0,c=0;for(const d of e){switch(d.column){case"in-progress":a++,rl(d,n,s)&&o++;break;case"todo":l++;break;case"in-review":c++;break}d.blockedBy&&d.blockedBy.length>0&&r++}return{runningTaskCount:a,blockedTaskCount:r,stuckTaskCount:o,queuedTaskCount:l,inReviewCount:c}}function o$(e,n,s,a){const[r,o]=i.useState({globalPause:!1,enginePaused:!1,maxConcurrent:2}),[l,c]=i.useState(!0),[d,u]=i.useState(null),m=i.useRef(null),h=i.useRef(null),f=i.useCallback(async()=>{h.current&&h.current.abort(),h.current=new AbortController;try{c(!0),u(null);const v=await wj(n);o(v)}catch(v){if(v instanceof Error&&v.name==="AbortError")return;u(v instanceof Error?v.message:"Failed to fetch executor stats")}finally{c(!1)}},[n]);i.useEffect(()=>(f(),()=>{h.current&&h.current.abort()}),[f]),i.useEffect(()=>(m.current&&clearInterval(m.current),m.current=setInterval(()=>{f()},i$),()=>{m.current&&(clearInterval(m.current),m.current=null)}),[f]);const p=r$(e,s,a),g=a$(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:g,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:d,refresh:f}}const l$={planning:oi,subtask:na,mission_interview:ws,milestone_interview:ws,slice_interview:ws},c$={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function d$({sessions:e,generating:n,needsInput:s,onOpenSession:a,onDismissSession:r}){const{confirm:o}=qs(),[l,c]=i.useState(!1),[d,u]=i.useState(new Set),m=i.useRef(null),h=i.useRef(new Map),f=i.useRef(null),{activeTabMap:p}=Ya(),g=i.useMemo(()=>ma(),[]);if(i.useEffect(()=>{if(!l)return;const b=y=>{m.current&&!m.current.contains(y.target)&&c(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[l]),i.useEffect(()=>{const b=new Set,y=new Map;for(const j of e){const C=p.get(j.id),A=[j.status,j.updatedAt,C?.tabId??j.lockedByTab??"",C?.stale?"stale":"fresh"].join("|"),N=h.current.get(j.id);N&&N!==A&&b.add(j.id),y.set(j.id,A)}if(h.current=y,b.size!==0)return u(b),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{u(new Set),f.current=null},500),()=>{f.current&&(clearTimeout(f.current),f.current=null)}},[p,e]),e.length===0)return null;const x=e.length,v=s>0;return t.jsxs("div",{ref:m,className:"background-tasks-indicator",children:[t.jsxs("button",{className:`background-tasks-indicator__pill${v?" background-tasks-indicator__pill--attention":""}`,onClick:()=>c(b=>!b),title:`${x} background AI task${x!==1?"s":""}${s>0?` (${s} need${s!==1?"":"s"} input)`:""}`,children:[n>0&&t.jsx(gt,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&t.jsx(nd,{size:12}),t.jsxs("span",{children:["AI ",x]})]}),l&&t.jsxs("div",{className:"background-tasks-indicator__popover",children:[t.jsx("div",{className:"background-tasks-indicator__popover-header",children:"Background Tasks"}),t.jsx("div",{className:"background-tasks-indicator__popover-list",children:e.map(b=>{const y=l$[b.type],j=b.status==="generating",C=b.status==="awaiting_input",A=b.status==="error",N=p.get(b.id),S=N?.tabId??b.lockedByTab??null,_=!!(S&&S!==g&&!N?.stale),T=d.has(b.id);return t.jsxs("div",{className:`background-tasks-indicator__item${T?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:T?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:T?"translateY(-1px)":void 0},onClick:async()=>{_&&!await o({title:"Open Active Session",message:"This session is active in another tab. Open anyway?"})||(a(b),c(!1))},children:[A?t.jsx(Rs,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--color-error)"}}):t.jsx(y,{size:14,className:"background-tasks-indicator__session-icon"}),t.jsxs("div",{className:"background-tasks-indicator__session-content",children:[t.jsx("div",{className:"background-tasks-indicator__session-title",children:b.title}),t.jsxs("div",{className:"background-tasks-indicator__session-meta",children:[A?"Failed":c$[b.type],j&&" — generating...",C&&!_&&" — needs input",C&&_&&" — active in another tab"]})]}),j&&t.jsx(gt,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),C&&!_&&t.jsx(nd,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),C&&_&&t.jsx(jl,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),t.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:M=>{M.stopPropagation(),r(b.id)},title:"Dismiss",children:t.jsx(Jt,{size:12})})]},b.id)})})]})]})}function u$(e){if(!e)return"no activity";const n=Date.now(),s=new Date(e).getTime(),a=n-s,r=Math.floor(a/1e3),o=Math.floor(r/60),l=Math.floor(o/60),c=Math.floor(l/24);return c>0?`${c}d ago`:l>0?`${l}h ago`:o>0?`${o}m ago`:r>10?`${r}s ago`:"just now"}function m$(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:Hn};case"paused":return{label:"Paused",color:"var(--triage)",icon:ii};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:Xn}}}function h$({tasks:e,projectId:n,taskStuckTimeoutMs:s,backgroundSessions:a,backgroundGenerating:r,backgroundNeedsInput:o,onOpenBackgroundSession:l,onDismissBackgroundSession:c,lastFetchTimeMs:d,currentProjectPath:u,onOpenProjectDirectory:m}){const{stats:h,loading:f,error:p}=o$(e,n,s,d),[g,x]=i.useState(!1),v=i.useMemo(()=>m$(h.executorState),[h.executorState]),b=i.useMemo(()=>u$(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(Sl,{size:14}),p]})}):f&&h.runningTaskCount===0?t.jsx("div",{className:"executor-status-bar executor-status-bar--loading",role:"status","aria-label":"Executor status",children:t.jsx("span",{className:"executor-status-bar__loading-text",children:"Loading..."})}):t.jsxs("div",{className:`executor-status-bar ${h.executorState==="running"?"executor-status-bar--running":""}`,role:"status","aria-label":"Executor status",children:[a&&a.length>0&&l&&c&&t.jsxs(t.Fragment,{children:[t.jsx(d$,{sessions:a,generating:r??0,needsInput:o??0,onOpenSession:l,onDismissSession:c}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--queued","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Queued"}),t.jsx("span",{className:"executor-status-bar__count",children:h.queuedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--running ${h.runningTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Running"}),t.jsx("span",{className:"executor-status-bar__count",children:h.runningTaskCount}),t.jsx("span",{className:"executor-status-bar__separator","aria-hidden":"true",children:"/"}),t.jsx("span",{className:"executor-status-bar__max",children:h.maxConcurrent})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),h.stuckTaskCount>0&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--stuck",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--stuck executor-status-bar__indicator--active","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Stuck"}),t.jsx("span",{className:"executor-status-bar__count executor-status-bar__count--error",children:h.stuckTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--blocked ${h.blockedTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Blocked"}),t.jsx("span",{className:`executor-status-bar__count ${h.blockedTaskCount>0?"executor-status-bar__count--warning":""}`,children:h.blockedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--review","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"In Review"}),t.jsx("span",{className:"executor-status-bar__count",children:h.inReviewCount})]}),u&&m&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--project-directory",children:[t.jsx("button",{className:`executor-status-bar__folder-toggle${g?" executor-status-bar__folder-toggle--active":""}`,onClick:()=>x(j=>!j),"aria-label":g?"Hide project directory":"Show project directory","aria-expanded":g,"data-testid":"executor-project-path-toggle",title:g?"Hide project directory":"Show project directory",children:t.jsx(os,{size:12,"aria-hidden":"true"})}),g&&t.jsx("button",{className:"executor-status-bar__project-path",onClick:m,title:u,"data-testid":"executor-project-path-link",children:u})]})]}),t.jsx("div",{className:"executor-status-bar__spacer"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--time",children:[t.jsx(_i,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__time",children:b})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx(y,{size:12,style:{color:v.color},"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__state",style:{color:v.color},children:v.label})]})]})}const p$={planning:oi,subtask:na,mission_interview:ws,milestone_interview:ws,slice_interview:ws},f$={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},jb="fusion:session-banner-dismissed";function Sr(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function g$(){if(typeof window>"u")return new Map;try{const e=window.localStorage.getItem(jb);if(!e)return new Map;const n=JSON.parse(e),s=new Map;for(const[a,r]of Object.entries(n)){const o=typeof r=="number"?r:Sr(r);s.set(a,o)}return s}catch{return new Map}}function b$(e){if(!(typeof window>"u"))try{const n={};for(const[s,a]of e)n[s]=a;window.localStorage.setItem(jb,JSON.stringify(n))}catch{}}const Si=g$();function x$({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:a}){const[r,o]=i.useState(0),l=()=>{b$(Si),o(g=>g+1)};i.useEffect(()=>{if(Si.size===0)return;const g=new Map(e.map(v=>[v.id,v]));let x=!1;for(const[v,b]of Si){const y=g.get(v);if(!y)continue;if(!(y.status==="awaiting_input"||y.status==="error")){Si.delete(v),x=!0;continue}Sr(y.updatedAt)>b&&(Si.delete(v),x=!0)}x&&l()},[e]);const c=i.useMemo(()=>e.filter(g=>{if(g.status!=="awaiting_input"&&g.status!=="error")return!1;const x=Si.get(g.id);return x===void 0?!0:Sr(g.updatedAt)>x}),[e,r]);if(c.length===0)return null;const d=c.filter(g=>g.status==="awaiting_input").length,u=c.filter(g=>g.status==="error").length;let m="";d>0&&u>0?m=`${d} AI session${d===1?"":"s"} need${d===1?"s":""} your input, ${u} failed`:d>0?m=`${d} AI session${d===1?"":"s"} need${d===1?"s":""} your input`:u>0&&(m=`${u} AI session${u===1?"":"s"} failed`);const h=g=>{Si.set(g.id,Math.max(Sr(g.updatedAt),Date.now())),l()},f=g=>{Si.delete(g.id),l(),n(g)},p=()=>{const g=Date.now();for(const x of c)Si.set(x.id,Math.max(Sr(x.updatedAt),g));l(),a()};return t.jsxs("section",{className:"session-notification-banner",role:"region","aria-live":"polite","aria-label":"AI sessions needing input or failed",children:[t.jsxs("div",{className:"session-notification-banner__header",children:[t.jsxs("div",{className:"session-notification-banner__headline",children:[t.jsx(Rs,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:m})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[t.jsx(Jt,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Dismiss all"})]})]}),t.jsx("div",{className:"session-notification-banner__list",children:c.map(g=>{const x=p$[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(Rs,{size:16,className:"session-notification-banner__type-icon session-notification-banner__type-icon--error","aria-hidden":"true"}):t.jsx(x,{size:16,className:"session-notification-banner__type-icon","aria-hidden":"true"}),t.jsxs("div",{className:"session-notification-banner__text",children:[t.jsx("p",{className:"session-notification-banner__title",title:g.title,children:g.title}),t.jsx("p",{className:"session-notification-banner__meta",children:v?"Failed":f$[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(Jt,{size:14,"aria-hidden":"true"})})]})]},g.id)})})]})}const Nb="fusion:cli-binary-banner-dismissed";function v$(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Nb)==="1"}catch{return!1}}function y$(){if(!(typeof window>"u"))try{window.localStorage.setItem(Nb,"1")}catch{}}function w$({onOpenSettings:e}){const[n,s]=i.useState(null),[a,r]=i.useState(()=>v$()),[o,l]=i.useState(!1),[c,d]=i.useState(null);i.useEffect(()=>{if(a)return;let h=!1;return Mw().then(f=>{h||s(f)}).catch(()=>{}),()=>{h=!0}},[a]);const u=i.useCallback(async()=>{l(!0),d(null);try{const h=await _w();s({binary:h.binary,expectedVersion:h.expectedVersion,state:h.state,install:h.install}),h.installResult.success||d(h.installResult.permissionsHint||h.installResult.stderr||`Install failed (exit ${h.installResult.exitCode??"n/a"})`)}catch(h){d(h instanceof Error?h.message:String(h))}finally{l(!1)}},[]),m=i.useCallback(()=>{y$(),r(!0)},[]);return a||!n||n.state==="installed"||n.state==="skipped"?null:t.jsxs("div",{className:"cli-binary-banner",role:"status",children:[t.jsxs("div",{className:"cli-binary-banner__body",children:[t.jsx("div",{className:"cli-binary-banner__title",children:"Install the Fusion CLI"}),t.jsxs("div",{className:"cli-binary-banner__text",children:["Get the ",t.jsx("code",{children:"fn"})," and ",t.jsx("code",{children:"fusion"})," commands on your terminal so you can drive Fusion from anywhere. One click below or copy the command into your shell."]}),t.jsxs("div",{className:"cli-binary-banner__actions",children:[t.jsx("button",{type:"button",className:"cli-binary-banner__primary",onClick:()=>void u(),disabled:o,children:o?"Installing…":"Install with npm"}),t.jsx("button",{type:"button",className:"cli-binary-banner__secondary",onClick:e,children:"Open Settings"})]}),c&&t.jsx("div",{className:"cli-binary-banner__error",children:c})]}),t.jsx("button",{type:"button",className:"cli-binary-banner__dismiss","aria-label":"Dismiss",onClick:m,children:t.jsx(Jt,{size:16})})]})}function k$({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(Jt,{size:16,"aria-hidden":"true"})})]})}function j$({onResume:e}){const n=C4();if(!n)return null;const s=n.completedSteps.length,a=Li.length,r=s>0?`${s} of ${a} step${s!==1?"s":""} complete — You're on the `:"You're on the ";return t.jsxs("section",{className:"onboarding-resume-card",role:"region","aria-label":"Resume onboarding",children:[t.jsxs("div",{className:"onboarding-resume-card__main",children:[t.jsx("div",{className:"onboarding-resume-card__icon","aria-hidden":"true",children:t.jsx(ms,{size:20})}),t.jsxs("div",{className:"onboarding-resume-card__content",children:[t.jsx("h2",{className:"onboarding-resume-card__title",children:"Continue Setup"}),t.jsxs("p",{className:"onboarding-resume-card__description",children:[r,t.jsx("strong",{children:n.label})," step. Continue where you left off to complete your dashboard setup."]})]})]}),t.jsx("div",{className:"onboarding-resume-card__actions",children:t.jsxs("button",{className:"onboarding-resume-card__resume-btn btn btn-primary btn-sm",onClick:()=>{Gs("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),e()},children:[t.jsx(Hn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function N$({onOpenSettings:e,onOpenModelOnboarding:n}){const s=qa(),a=xb(),[r,o]=i.useState(!0),[l,c]=i.useState(!1),[d,u]=i.useState(!1),[m,h]=i.useState({needsAiProvider:!1,needsDefaultModel:!1,needsGitHub:!1});i.useEffect(()=>{if(!s||a){o(!1);return}let b=!1;return(async()=>{try{o(!0),c(!1);const[j,C]=await Promise.all([Dr(),ca()]);if(b)return;const A=j.providers??[],N=A.find(E=>E.id==="github"),_=!A.some(E=>E.id!=="github"&&E.authenticated),T=!C.defaultProvider&&!C.defaultModelId,M=N?!N.authenticated:!1;h({needsAiProvider:_,needsDefaultModel:T,needsGitHub:M})}catch{b||c(!0)}finally{b||o(!1)}})(),()=>{b=!0}},[s,a]);const f=i.useCallback(()=>{N4(),u(!0)},[]),p=i.useCallback(()=>{n()},[n]),g=i.useCallback(()=>{e("global-models")},[e]),x=i.useCallback(()=>{e("authentication")},[e]),v=i.useMemo(()=>{const b=[];return m.needsAiProvider&&b.push({id:"ai-provider",title:"Connect AI Provider",description:"Connect an AI provider to enable AI agents for task planning and code generation",actionLabel:"Set Up AI",onAction:p,icon:Xn}),m.needsDefaultModel&&b.push({id:"default-model",title:"Select Default Model",description:"Choose a default AI model for task execution",actionLabel:"Choose Model",onAction:g,icon:ef}),m.needsGitHub&&b.push({id:"github",title:"Connect GitHub",description:"Connect GitHub to import issues and track pull requests",actionLabel:"Connect GitHub",onAction:x,icon:zs}),b},[m.needsAiProvider,m.needsDefaultModel,m.needsGitHub,x,g,p]);return!s||a||d||r||l||v.length===0?null:t.jsxs("section",{className:"post-onboarding-recommendations",role:"region","aria-label":"Setup recommendations",children:[t.jsxs("div",{className:"post-onboarding-recommendations__main",children:[t.jsx("div",{className:"post-onboarding-recommendations__icon","aria-hidden":"true",children:t.jsx(oi,{size:18,"aria-hidden":!0})}),t.jsxs("div",{className:"post-onboarding-recommendations__content",children:[t.jsx("h2",{className:"post-onboarding-recommendations__title",children:"Recommended Next Steps"}),t.jsx("p",{className:"post-onboarding-recommendations__description",children:"Complete these setup items to get the most out of Fusion."}),t.jsx("ul",{className:"post-onboarding-recommendations__list",children:v.map(b=>{const y=b.icon;return t.jsxs("li",{className:"post-onboarding-recommendations__item",children:[t.jsx("span",{className:"post-onboarding-recommendations__item-icon","aria-hidden":"true",children:t.jsx(y,{size:14,"aria-hidden":!0})}),t.jsxs("span",{className:"post-onboarding-recommendations__item-text",children:[t.jsx("strong",{children:b.title}),t.jsx("span",{children:b.description})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-primary",onClick:b.onAction,children:b.actionLabel})]},b.id)})}),t.jsx(Oi,{slotId:"post-onboarding-recommendation"})]})]}),t.jsx("button",{type:"button",className:"post-onboarding-recommendations__dismiss",onClick:f,"aria-label":"Dismiss recommendations",children:t.jsx(Jt,{size:16,"aria-hidden":!0})})]})}function S$({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 Yc(e){return e>99?"99+":String(e)}function C$({view:e,onChangeView:n,footerVisible:s,modalOpen:a=!1,keyboardOpen:r=!1,onOpenSettings:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:d,mailboxUnreadCount:u=0,onOpenGitManager:m,onOpenWorkflowSteps:h,onOpenSchedules:f,onOpenScripts:p,onToggleTerminal:g,onOpenFiles:x,onOpenTodos:v,todosOpen:b=!1,onOpenGitHubImport:y,onOpenPlanning:j,onResumePlanning:C,activePlanningSessionCount:A=0,onOpenUsage:N,onRunScript:S,projectId:_,onViewAllProjects:T,showSkillsTab:M,experimentalFeatures:E,onOpenNodes:L,pluginDashboardViews:F=[]}){const R=Pi(),[P,O]=i.useState(!1),[q,Z]=i.useState(!1),[z,k]=i.useState({}),[I,$]=i.useState(!1),w=i.useMemo(()=>Object.entries(z).sort(([ve],[Oe])=>ve.localeCompare(Oe)),[z]);i.useEffect(()=>{if(!q)return;let ve=!1;return $(!0),Lr(_).then(Oe=>{ve||k(Oe)}).catch(()=>{ve||k({})}).finally(()=>{ve||$(!1)}),()=>{ve=!0}},[q,_]);const H=i.useCallback(()=>O(!1),[]),K=i.useCallback(ve=>{H(),ve?.()},[H]);if(i.useEffect(()=>{if(!P)return;const ve=Oe=>{Oe.key==="Escape"&&O(!1)};return document.addEventListener("keydown",ve),()=>document.removeEventListener("keydown",ve)},[P]),R!=="mobile"||a||r)return null;const pe=A>0&&C?C:j,le=F.some(ve=>ve.pluginId==="fusion-plugin-roadmap"),B=!!E?.roadmap&&!le,ye=!!M,U=!!E?.todoView,te=B&&(!ye||e==="roadmaps"),ne=ye&&(!B||e!=="roadmaps"),ee=ye&&!ne,ie=ve=>ve.pluginId==="fusion-plugin-dependency-graph"&&ve.view.viewId==="graph",ge=F.filter(ve=>ve.view.placement==="primary").sort((ve,Oe)=>(ve.view.order??Number.MAX_SAFE_INTEGER)-(Oe.view.order??Number.MAX_SAFE_INTEGER)),se=F.find(ie)??null,Se=(se?[se,...ge.filter(ve=>!ie(ve))]:ge).slice(0,1),qe=new Set(Se.map(ve=>`${ve.pluginId}:${ve.view.viewId}`)),We=F.filter(ve=>!qe.has(`${ve.pluginId}:${ve.view.viewId}`)).sort((ve,Oe)=>(ve.view.order??Number.MAX_SAFE_INTEGER)-(Oe.view.order??Number.MAX_SAFE_INTEGER)),Qe=e==="documents"||e==="research"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||b&&U||e==="roadmaps"&&!te||e==="skills"&&!ne||e.startsWith("plugin:")&&!Se.some(ve=>Mr(ve.pluginId,ve.view.viewId)===e);return t.jsxs(t.Fragment,{children:[t.jsxs("nav",{className:`mobile-nav-bar${s?" mobile-nav-bar--with-footer":""}`,role:"tablist","aria-label":"Primary navigation",children:[t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="board"||e==="list"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-tasks",role:"tab","aria-selected":e==="board"||e==="list",onClick:()=>{n(e==="board"||e==="list"?e:"board")},children:[t.jsx(Ui,{}),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(Rn,{}),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(Ei,{}),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(sa,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-nav-tab-badge",children:Yc(u)})]}),ne&&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(Xn,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),te&&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(ld,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Roadmaps"})]}),Se.map(ve=>{const Oe=Mr(ve.pluginId,ve.view.viewId),ae=il(ve.view.icon);return t.jsxs("button",{type:"button",className:`mobile-nav-tab${e===Oe?" mobile-nav-tab--active":""}`,"data-testid":`mobile-nav-tab-plugin-${ve.pluginId}-${ve.view.viewId}`,role:"tab","aria-selected":e===Oe,onClick:()=>n(Oe),children:[t.jsx(ae,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:ve.view.label})]},`${ve.pluginId}:${ve.view.viewId}`)}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${Qe?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>O(ve=>!ve),children:[t.jsx(sd,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),P&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mobile-more-sheet-backdrop",onClick:H}),t.jsxs("div",{className:"mobile-more-sheet",children:[t.jsx("div",{className:"mobile-more-sheet-handle"}),t.jsx("div",{className:"mobile-more-sheet-title",children:"Navigate"}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-mailbox",onClick:()=>K(d),children:[t.jsx(sa,{}),t.jsx("span",{children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:Yc(u)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>K(l),children:[t.jsx(Fs,{}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-system-stats",onClick:()=>K(c),children:[t.jsx(Ra,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>K(m),children:[t.jsx(Hs,{}),t.jsx("span",{children:"Git Manager"})]}),t.jsxs("div",{className:"mobile-more-split-row",children:[t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-split-primary","data-testid":"mobile-more-item-terminal",onClick:()=>K(g),children:[t.jsx(Mi,{}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>Z(ve=>!ve),"aria-expanded":q,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(Tn,{size:14,className:`mobile-more-chevron${q?" mobile-more-chevron--open":""}`})})]}),q&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:I?t.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[t.jsx(gt,{className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):w.length>0?t.jsxs(t.Fragment,{children:[w.map(([ve,Oe])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${ve}`,onClick:()=>{S&&S(ve,Oe),H(),Z(!1)},children:[t.jsx(Hn,{}),t.jsx("span",{children:ve})]},ve)),p&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{H(),Z(!1),p()},children:[t.jsx(si,{}),t.jsx("span",{children:"Manage Scripts…"})]})]}):p&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":"mobile-more-scripts-manage",onClick:()=>{H(),Z(!1),p()},children:[t.jsx(si,{}),t.jsx("span",{children:"No scripts — add one…"})]})}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-files",onClick:()=>K(x),children:[t.jsx(os,{}),t.jsx("span",{children:"Files"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>K(pe),children:[t.jsx(oi,{}),t.jsx("span",{children:"Planning"}),A>0&&t.jsx("span",{className:"mobile-more-item-badge",children:Yc(A)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>K(h),children:[t.jsx(Zo,{}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>K(f),children:[t.jsx(_i,{}),t.jsx("span",{children:"Automation"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>K(y),children:[t.jsx(S$,{}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>K(N),children:[t.jsx(Fs,{}),t.jsx("span",{children:"Usage"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>K(T),children:[t.jsx(yl,{}),t.jsx("span",{children:"Projects"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>K(()=>n("documents")),children:[t.jsx(Fi,{}),t.jsx("span",{children:"Documents"})]}),ee&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>K(()=>n("skills")),children:[t.jsx(Xn,{}),t.jsx("span",{children:"Skills"})]}),B&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-roadmaps",onClick:()=>K(()=>n("roadmaps")),children:[t.jsx(ld,{}),t.jsx("span",{children:"Roadmaps"})]}),E?.researchView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-research",onClick:()=>K(()=>n("research")),children:[t.jsx(Ci,{}),t.jsx("span",{children:"Research"})]}),E?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>K(()=>n("insights")),children:[t.jsx(ms,{}),t.jsx("span",{children:"Insights"})]}),E?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>K(()=>n("memory")),children:[t.jsx(Rr,{}),t.jsx("span",{children:"Memory"})]}),E?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{K(()=>n("dev-server"))},children:[t.jsx(Ra,{}),t.jsx("span",{children:"Dev Server"})]}),E?.nodesView&&L&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-nodes",onClick:()=>K(L),children:[t.jsx(Bv,{}),t.jsx("span",{children:"Nodes"})]}),U&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-todos",onClick:()=>K(()=>v?.()),children:[t.jsx(Qo,{}),t.jsx("span",{children:"Todos"})]}),We.map(ve=>{const Oe=Mr(ve.pluginId,ve.view.viewId),ae=il(ve.view.icon);return t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":`mobile-more-item-plugin-${ve.pluginId}-${ve.view.viewId}`,onClick:()=>K(()=>n(Oe)),children:[t.jsx(ae,{}),t.jsx("span",{children:ve.view.label})]},`${ve.pluginId}:${ve.view.viewId}`)}),t.jsx("div",{className:"mobile-more-separator"}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-settings",onClick:()=>K(o),children:[t.jsx(Cr,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function E$({agents:e,filter:n,highlightedIndex:s,visible:a,onSelect:r,position:o="below"}){const l=i.useMemo(()=>{const c=n.trim().toLowerCase();return c?e.filter(d=>d.name.toLowerCase().includes(c)):e},[e,n]);return a?t.jsx("div",{className:`agent-mention-popup agent-mention-popup--${o}`,"data-testid":"agent-mention-popup",role:"listbox","aria-label":"Agent mention suggestions",children:l.length===0?t.jsx("div",{className:"agent-mention-empty",children:"No agents found"}):l.map((c,d)=>t.jsxs("button",{type:"button",className:`agent-mention-item${d===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${c.id}`,onMouseDown:u=>u.preventDefault(),onClick:()=>r(c),role:"option","aria-selected":d===s,children:[t.jsx(Rn,{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 _a="__fn_agent__";function Sb(e,n){const s=typeof e=="string"?e.trim():"",a=typeof n=="string"?n.trim():"";return!s||!a?{}:{modelProvider:s,modelId:a}}function Uo(e,n,s){const a=typeof e=="string"?e.trim():"",r=Sb(n,s),o=a||(r.modelProvider&&r.modelId?_a:"");return o?{agentId:o,...r}:null}function Bo(e,n,s){const a=Sb(n,s),r=a.modelProvider??"",o=a.modelId??"";return`${e}::${r}/${o}`}function M$(e){const n=e?.toolCalls;if(!Array.isArray(n))return;const s=n.map(a=>{if(!a||typeof a!="object")return null;const r=a,o=typeof r.toolName=="string"?r.toolName:"";if(!o)return null;const l=r.args;return{toolName:o,...l&&typeof l=="object"?{args:l}:{},isError:!!r.isError,result:r.result,status:"completed"}}).filter(a=>a!==null);return s.length>0?s:void 0}function Qc(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:M$(e.metadata),createdAt:e.createdAt}}function _$(e,n){const[s,a]=i.useState(null),[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState([]),[m,h]=i.useState(!1),[f,p]=i.useState(!1),[g,x]=i.useState(""),[v,b]=i.useState(""),[y,j]=i.useState([]),[C,A]=i.useState(""),N=i.useRef(null),S=i.useRef(!1),_=i.useRef(null),T=i.useRef(""),M=i.useRef(f);M.current=f;const E=i.useRef(null),L=i.useRef(""),F=i.useRef(null);i.useEffect(()=>{T.current=C},[C]);const R=i.useCallback(async()=>{c(!0);try{const le=await Ju(e);o(le.sessions)}catch(le){console.error("[useQuickChat] Failed to refresh sessions:",le)}finally{c(!1)}},[e]),P=i.useCallback(async le=>{const B={agentId:le.agentId};return le.modelProvider&&le.modelId&&(B.modelProvider=le.modelProvider,B.modelId=le.modelId),(await JN(B,e)).session},[e]),O=i.useCallback(async(le,B,ye)=>{const U=Uo(le,B,ye);if(!U)return;const te=Bo(U.agentId,U.modelProvider,U.modelId);c(!0);try{const{session:ne}=await GN({agentId:U.agentId,modelProvider:U.modelProvider,modelId:U.modelId},e);if(ne)a(ne),L.current=te,ne.isGenerating&&(p(!0),x(""));else{const ee=await P(U);a(ee),L.current=te}}catch(ne){console.error("[useQuickChat] Failed to initialize session:",ne),n?.("Failed to initialize chat","error")}finally{c(!1)}},[e,n,P]),q=i.useCallback(async()=>{if(s){h(!0);try{const le=await Ql(s.id,{limit:50},e);u(le.messages.map(Qc))}catch(le){console.error("[useQuickChat] Failed to load messages:",le)}finally{h(!1)}}},[s,e]);i.useEffect(()=>{s?q():u([])},[s,q]),i.useEffect(()=>{if(!f||N.current||!s)return;const le=setInterval(async()=>{if(!M.current||N.current||!s){clearInterval(le);return}try{if(!(await YN(s.id,e)).session.isGenerating){clearInterval(le);const ye=await Ql(s.id,{limit:50},e);u(ye.messages.map(Qc)),x(""),b(""),j([]),p(!1)}}catch{}},3e3);return()=>clearInterval(le)},[f,s,e]);const Z=i.useCallback(async()=>{if(s){h(!0);try{const le=await Ql(s.id,{limit:50},e);u(le.messages.map(Qc))}catch(le){console.error("[useQuickChat] Failed to reload messages:",le)}finally{h(!1)}}},[s,e]),z=i.useCallback(()=>{_.current?.(),_.current=null,T.current="",A(""),x(""),b(""),j([]),p(!1)},[]),k=i.useCallback(async(le,B,ye)=>{const U=Uo(le,B,ye);if(!U)return;const te=Bo(U.agentId,U.modelProvider,U.modelId);F.current=U;const ne=te===L.current&&s;if(ne||(N.current&&(N.current.close(),N.current=null),z()),ne){await Z();return}a(null),u([]),L.current=te,await O(U.agentId,U.modelProvider,U.modelId)},[s,O,Z,z]),I=i.useCallback(async le=>{const B=Uo(le.agentId,le.modelProvider??void 0,le.modelId??void 0);B&&(F.current=B,L.current=Bo(B.agentId,B.modelProvider,B.modelId),N.current&&(N.current.close(),N.current=null),z(),a(le))},[z]),$=i.useCallback(async(le,B)=>{await k(_a,le,B)},[k]),w=i.useCallback(async(le,B,ye)=>{const te=Uo(le??"",B,ye)??F.current;if(!te)return;F.current=te;const ne=Bo(te.agentId,te.modelProvider,te.modelId);N.current&&(N.current.close(),N.current=null),z(),u([]),a(null),c(!0);try{const ee=await P(te);a(ee),L.current=ne;const ie=await Ju(e);o(ie.sessions)}catch(ee){console.error("[useQuickChat] Failed to start a fresh session:",ee),n?.("Failed to start a new chat","error")}finally{c(!1)}},[n,P,e,z]),H=i.useCallback(()=>{s&&(S.current=!0,_.current?.(),_.current=null,N.current?.close(),N.current=null,QN(s.id,e).catch(()=>{}),p(!1),x(""),b(""),j([]))},[s,e]),K=i.useCallback(()=>{T.current="",A("")},[]),pe=i.useCallback((le,B)=>{if(!s||!le.trim()&&(!B||B.length===0))return Promise.resolve();if(f)return B&&B.length>0?Promise.reject(new Error("Cannot send attachments while a response is streaming")):(T.current=le,A(le),Promise.resolve());const ye=new Promise((U,te)=>{E.current={resolve:U,reject:te},S.current=!1,N.current&&(N.current.close(),N.current=null);const ee={id:`temp-${Date.now()}`,sessionId:s.id,role:"user",content:le,createdAt:new Date().toISOString()};u(ve=>[...ve,ee]),x(""),b(""),j([]),p(!0);let ie="",ge="",se=[],Ae=null,xe=null;const Se=()=>{Ae=null,x(ie)},qe=()=>{xe=null,b(ge)},We=()=>{Ae!==null&&(cancelAnimationFrame(Ae),Ae=null),xe!==null&&(cancelAnimationFrame(xe),xe=null)};_.current=We;const Qe={onThinking:ve=>{ge+=ve,xe===null&&(xe=requestAnimationFrame(qe))},onText:ve=>{ie+=ve,Ae===null&&(Ae=requestAnimationFrame(Se))},onToolStart:ve=>{se=[...se,{toolName:ve.toolName,args:ve.args,isError:!1,status:"running"}],j(se)},onToolEnd:ve=>{const Oe=[...se];for(let ae=Oe.length-1;ae>=0;ae--){const re=Oe[ae];if(re?.toolName===ve.toolName&&re.status==="running"){Oe[ae]={...re,status:"completed",isError:ve.isError,result:ve.result},se=Oe,j(Oe);return}}se=[...Oe,{toolName:ve.toolName,isError:ve.isError,result:ve.result,status:"completed"}],j(se)},onDone:ve=>{We();const Oe={id:ve.messageId||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:ie,thinkingOutput:ge||void 0,toolCalls:se.length>0?se:void 0,createdAt:new Date().toISOString()};u(re=>[...re,Oe]),x(""),b(""),j([]),p(!1),N.current=null,E.current?.resolve(),E.current=null;const ae=T.current.trim();ae&&(T.current="",A(""),pe(ae))},onError:ve=>{if(We(),x(""),b(""),j([]),p(!1),N.current=null,console.error("[useQuickChat] Stream error:",ve),n?.("Failed to get response","error"),E.current?.reject(new Error(typeof ve=="string"?ve:"Failed to get response")),E.current=null,!S.current){const Oe=T.current.trim();Oe&&(T.current="",A(""),pe(Oe))}Z()}};N.current=XN(s.id,le,Qe,B,e)});return ye.catch(()=>{}),ye},[s,f,e,n,Z]);return i.useEffect(()=>()=>{N.current&&(N.current.close(),N.current=null)},[]),i.useMemo(()=>({activeSession:s,sessions:r,sessionsLoading:l,messages:d,messagesLoading:m,isStreaming:f,streamingText:g,streamingThinking:v,streamingToolCalls:y,pendingMessage:C,sendMessage:pe,stopStreaming:H,clearPendingMessage:K,switchSession:k,selectSession:I,startModelChat:$,startFreshSession:w,refreshSessions:R,loadMessages:q,reloadMessages:Z}),[s,r,l,d,m,f,g,v,y,C,pe,H,K,k,I,$,w,R,q,Z])}function A$(e,n){const[s,a]=i.useState([]),[r,o]=i.useState(null),[l,c]=i.useState(!1),d=i.useCallback(async f=>{c(!0);try{const p=n?.filterState,g=p&&p!=="all"?{state:p}:void 0,x=n?.showSystemAgents??!1,v=await da({...g,...f,includeEphemeral:f?.includeEphemeral??x},e),b=Array.from(new Map(v.map(y=>[y.id,y])).values());a(b)}catch(p){console.error("Failed to load agents:",p)}finally{c(!1)}},[e,n?.filterState,n?.showSystemAgents]),u=i.useCallback(async()=>{try{const f=await fj(e);o(f)}catch(f){console.error("Failed to load agent stats:",f)}},[e]);i.useEffect(()=>{d(),u()},[d,u]),i.useEffect(()=>{const f=e?`?projectId=${encodeURIComponent(e)}`:"",p=()=>{d(),u()};return li(`/api/events${f}`,{events:{"agent:created":p,"agent:updated":p,"agent:deleted":p,"agent:stateChanged":p}})},[e,d,u]);const m=n?.showSystemAgents??!1,h=s.filter(f=>f.state!=="active"&&f.state!=="running"?!1:m||!D1(f));return{agents:s,activeAgents:h,stats:r,isLoading:l,loadAgents:d,loadStats:u}}function P$({visible:e,position:n,files:s,selectedIndex:a,onSelect:r,loading:o}){return e?t.jsxs("div",{className:"file-mention-popup",style:{top:n.top,left:n.left},"data-testid":"file-mention-popup",onMouseDown:l=>{l.preventDefault()},children:[o&&t.jsx("div",{className:"file-mention-popup-loading","data-testid":"file-mention-loading",children:t.jsx("span",{className:"spinner"})}),!o&&s.length===0&&t.jsx("div",{className:"file-mention-popup-empty","data-testid":"file-mention-empty",children:"No files found"}),!o&&s.length>0&&t.jsx("ul",{className:"file-mention-popup-list",role:"listbox",children:s.map((l,c)=>{const d=i1(l.path),u=l.name;return t.jsxs("li",{className:`file-mention-popup-item${c===a?" file-mention-popup-item--selected":""}`,onClick:()=>r(l),onMouseEnter:()=>{},role:"option","aria-selected":c===a,"data-testid":`file-mention-item-${c}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(Xp,{size:14})}),t.jsxs("div",{className:"file-mention-popup-info",children:[t.jsx("span",{className:"file-mention-popup-item-name",children:u}),d&&t.jsx("span",{className:"file-mention-popup-item-path",children:d})]})]},l.path)})})]}):null}const R$=200;function T$(e={}){const{projectId:n,workspace:s="project"}=e,[a,r]=i.useState(!1),[o,l]=i.useState(""),[c,d]=i.useState(-1),[u,m]=i.useState([]),[h,f]=i.useState(!1),[p,g]=i.useState(0),x=i.useRef(null),v=i.useRef(null);i.useEffect(()=>()=>{x.current&&clearTimeout(x.current),v.current?.abort()},[]);const b=i.useCallback((N,S)=>{if(S<0||S>N.length){r(!1);return}const _=T=>/[a-zA-Z0-9/_.-]/.test(T);for(let T=S-1;T>=0;T--){if(N[T]==="#")if(T===0){const M=N.slice(T+1,S);d(T),l(M),g(0),r(!0);return}else{const M=N[T-1];if(/[\s,.;:!?'"()[\]{}]/.test(M)){const E=N.slice(T+1,S);d(T),l(E),g(0),r(!0);return}r(!1);return}if(!_(N[T])){r(!1);return}}r(!1)},[]),y=i.useCallback(()=>{r(!1),l(""),d(-1),m([]),g(0),f(!1)},[]),j=i.useCallback(async N=>{if(!N.trim()){m([]),f(!1);return}v.current?.abort(),v.current=new AbortController;try{f(!0);const S=await wk(N,s,n);m(S.files),g(0)}catch(S){S.name!=="AbortError"&&m([])}finally{f(!1)}},[s,n]);i.useEffect(()=>{if(a)return x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{j(o)},R$),()=>{x.current&&clearTimeout(x.current)}},[o,a,j]);const C=i.useCallback((N,S)=>{if(!a||c<0)return S;const _=S.slice(0,c),T=S.slice(c+1),M=T.match(/[\s]|$/),E=M?M.index:T.length,L=T.slice(E);return`${_}#${N.path}${L}`},[a,c]),A=i.useCallback((N,S)=>{if(!a||u.length===0)return!1;switch(N.key){case"ArrowDown":return N.preventDefault(),g(_=>Math.min(_+1,u.length-1)),!0;case"ArrowUp":return N.preventDefault(),g(_=>Math.max(_-1,0)),!0;case"Enter":case"Tab":return u[p]?(N.preventDefault(),!0):!1;case"Escape":return N.preventDefault(),y(),!0;default:return!1}},[a,u,p,y]);return{mentionActive:a,files:u,loading:h,mentionQuery:o,selectedIndex:p,setSelectedIndex:g,detectMention:b,selectFile:C,dismissMention:y,handleKeyDown:A}}function I$(e){return`${e.name?.trim()||e.id} (${e.role})`}function Ho(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 $$(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 Go(e,n){return e.length<=n?e:`${e.slice(0,n)}…`}function D$(e){if(!e)return null;const n=Object.entries(e);return n.length===0?null:n.map(([s,a])=>{const r=typeof a=="string"?a:(()=>{try{return JSON.stringify(a)}catch{return String(a)}})();return`${s}=${Go(r,50)}`}).join(", ")}function L$(e){if(e===void 0)return null;if(typeof e=="string")return Go(e,200);try{return Go(JSON.stringify(e),200)}catch{return Go(String(e),200)}}function Cb(e,n=!1){if(!e||e.length===0)return null;const s=(f,p)=>{const g=f.status==="running",x=f.status==="completed"&&f.isError,v=D$(f.args),b=L$(f.result),y=g?v:b?`result: ${b}`:v?`args: ${v}`:null,j=n?null:y,C=g?"running":x?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${g?" chat-tool-call--running":""}${x?" chat-tool-call--error":""}`,open:g,children:[t.jsxs("summary",{children:[t.jsx("span",{className:"chat-tool-call-status-dot","aria-hidden":"true"}),t.jsx("span",{className:"chat-tool-call-name",title:f.toolName,children:f.toolName}),j&&t.jsx("span",{className:"chat-tool-call-preview",title:j,children:j}),t.jsx("span",{className:"chat-tool-call-status-text",children:C})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[v&&t.jsxs("div",{className:"chat-tool-call-row",children:[t.jsx("span",{className:"chat-tool-call-label",children:"args"}),t.jsx("span",{className:"chat-tool-call-value",children:v})]}),b&&t.jsxs("div",{className:`chat-tool-call-row${x?" chat-tool-call-row--error":""}`,children:[t.jsx("span",{className:"chat-tool-call-label",children:"result"}),t.jsx("span",{className:"chat-tool-call-value",children:b})]})]})]},`${f.toolName}-${p}`)},a=`chat-tool-calls${n?" chat-tool-calls--compact":""}`;if(e.length===1)return t.jsxs("div",{className:a,"data-testid":"chat-tool-calls",children:[t.jsxs("div",{className:"chat-tool-calls-header",children:[t.jsx(Su,{size:12,"aria-hidden":"true"}),t.jsx("span",{children:"Tool calls"})]}),s(e[0],0)]});const r=e.filter(f=>f.status==="running").length,o=e.filter(f=>f.status==="completed"&&f.isError).length,l=r>0,c=Array.from(new Set(e.map(f=>f.toolName))),d=c.slice(0,5),u=Math.max(0,c.length-d.length),m=u>0?`${d.join(", ")}, +${u} more`:d.join(", "),h=l?`(${r} running)`:o>0?`(${o} ${o===1?"error":"errors"})`:null;return t.jsx("div",{className:a,"data-testid":"chat-tool-calls",children:t.jsxs("details",{className:`chat-tool-calls-group${n?" chat-tool-calls-group--compact":""}`,"data-testid":"chat-tool-calls-group",open:l,children:[t.jsxs("summary",{className:"chat-tool-calls-group-summary",children:[t.jsx(Su,{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 Eb={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 Ap(e){const n=/(^|[\s])\/([^\s]*)$/.exec(e);if(!n)return null;const s=n[1]??"",a=n[2]??"",r=n.index+s.length;return{filter:a,start:r,end:e.length}}function O$(e,n){const s=e.slice(0,n),a=/(^|[\s])@([\w-]*)$/.exec(s);if(!a)return null;const r=a[2]??"",o=s.length-r.length-1;return{filter:r,start:o,end:n}}const qo={width:320,height:400},z$=new Set(["image/png","image/jpeg","image/gif","image/webp","text/plain","application/json","text/yaml","text/x-log","text/csv","application/xml","text/markdown"]),F$=[".png",".jpg",".jpeg",".gif",".webp",".txt",".json",".yaml",".yml",".log",".csv",".xml",".md"];function U$(e){return e.type.startsWith("image/")}function B$(e){if(z$.has(e.type))return!0;const n=e.name.toLowerCase();return F$.some(s=>n.endsWith(s))}const Sa={width:280,height:260},ys=768,Ca=8;function H$(e,n){const s=i.useCallback(()=>{if(typeof window>"u")return 0;const x=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return x&&parseFloat(x)||0},[]),a=i.useCallback(()=>typeof window<"u"&&window.innerWidth<=768?{x:4,y:4+s()}:{x:24,y:24+s()},[s]),[r,o]=i.useState(()=>{if(typeof window>"u")return a();const x=`fusion-quick-chat-position-${e||"default"}`;try{const v=localStorage.getItem(x);if(v){const b=JSON.parse(v);if(typeof b.x=="number"&&typeof b.y=="number"&&!isNaN(b.x)&&!isNaN(b.y))return b}}catch{}return a()}),[l,c]=i.useState(!1),d=i.useRef(null),u=n??i.useRef(!1),m=i.useCallback(x=>{if(typeof window>"u")return x;const v=48,b=window.innerWidth<=768?4:8,y=window.innerWidth<=768?44:0,j=window.innerWidth>768?s():0,C=window.innerWidth-v-b,A=window.innerHeight-v-b-y-j;return{x:Math.max(b,Math.min(C,x.x)),y:Math.max(b,Math.min(A,x.y))}},[s]),h=i.useCallback(x=>{if(typeof window>"u")return;const v=`fusion-quick-chat-position-${e||"default"}`;try{localStorage.setItem(v,JSON.stringify(x))}catch{}},[e]),f=i.useCallback(x=>{if(x.button!==0&&x.pointerType==="mouse")return;const b=x.target.closest(".quick-chat-fab");b&&(x.preventDefault(),typeof b.setPointerCapture=="function"&&b.setPointerCapture(x.pointerId),d.current={x:r.x,y:r.y,pointerX:x.clientX,pointerY:x.clientY},u.current=!1,c(!0),document.body.style.userSelect="none")},[r]),p=i.useCallback(x=>{if(!d.current||!l)return;const v=x.clientX-d.current.pointerX,b=x.clientY-d.current.pointerY;if((Math.abs(v)>=5||Math.abs(b)>=5)&&(u.current=!0),u.current){const y=d.current.x-v,j=d.current.y-b,C=m({x:y,y:j});o(C)}},[l,m]),g=i.useCallback(x=>{if(!d.current)return;const v=x.target.closest(".quick-chat-fab");if(v&&typeof v.releasePointerCapture=="function"&&v.releasePointerCapture(x.pointerId),c(!1),document.body.style.userSelect="",!u.current){d.current=null;return}h(r),d.current=null,u.current=!1},[r,h]);return{position:r,isDragging:l,handlePointerDown:f,handlePointerMove:p,handlePointerUp:g}}function q$(e,n,s){const a=`fusion:quick-chat-size-${e||"default"}`,r=i.useCallback(()=>typeof window<"u"&&window.innerWidth>ys,[]),o=i.useCallback((f,p,g)=>{if(typeof window>"u")return f;const x=Math.max(Sa.width,window.innerWidth-p-Ca),v=Math.max(Sa.height,window.innerHeight-g-Ca);return{width:Math.max(Sa.width,Math.min(x,f.width)),height:Math.max(Sa.height,Math.min(v,f.height))}},[]),l=i.useCallback(()=>{if(typeof window>"u"||window.innerWidth<=ys)return qo;try{const f=localStorage.getItem(a);if(!f)return qo;const p=JSON.parse(f);return typeof p.width!="number"||typeof p.height!="number"?qo:{width:p.width,height:p.height}}catch{return qo}},[a]),[c,d]=i.useState(l),[u,m]=i.useState({right:0,bottom:0});i.useEffect(()=>{if(!r())return;const f={right:n+u.right,bottom:s+u.bottom};d(p=>o(p,f.right,f.bottom))},[o,r,n,s,u]),i.useEffect(()=>{if(r())try{localStorage.setItem(a,JSON.stringify(c))}catch{}},[r,c,a]);const h=i.useCallback(f=>{if(!r())return;const p=f.currentTarget.dataset.resizeDirection;if(!p)return;f.preventDefault(),f.stopPropagation();const g=f.currentTarget;typeof g.setPointerCapture=="function"&&g.setPointerCapture(f.pointerId);const x={pointerX:f.clientX,pointerY:f.clientY,width:c.width,height:c.height,anchorRight:u.right,anchorBottom:u.bottom};document.body.style.userSelect="none";const v=y=>{const j=y.clientX-x.pointerX,C=y.clientY-x.pointerY;let A=x.width,N=x.height,S=x.anchorRight,_=x.anchorBottom;if(p.includes("w")&&(A=x.width-j),p.includes("e")){const R=j;A=x.width+R,S=x.anchorRight-R}if(p.includes("n")&&(N=x.height-C),p.includes("s")){const R=C;N=x.height+R,_=x.anchorBottom-R}const T=n+S,M=s+_,E=o({width:A,height:N},T,M),L=Math.max(Ca-n,Math.min(window.innerWidth-n-Sa.width-Ca,S)),F=Math.max(Ca-s,Math.min(window.innerHeight-s-Sa.height-Ca,_));d(E),m({right:L,bottom:F})},b=y=>{typeof g.releasePointerCapture=="function"&&g.releasePointerCapture(y.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",b);try{localStorage.setItem(a,JSON.stringify({width:c.width,height:c.height}))}catch{}};document.addEventListener("pointermove",v),document.addEventListener("pointerup",b)},[u.bottom,u.right,o,s,n,r,c.height,c.width,a]);return{panelSize:c,anchorOffset:u,handleResizeStart:h}}const Pp=i.memo(function({message:n,forcePlain:s,mentionAgentsByName:a,onToggleRender:r}){const o=n.role==="user",l=i.useMemo(()=>{if(!o)return null;const d=n.content,u=/@([\w-]+)/g,m=[];let h=0,f=u.exec(d);for(;f;){const[p,g=""]=f,x=f.index;x>h&&m.push(d.slice(h,x));const v=g.replace(/_/g," ").toLowerCase(),b=a.get(v);b?m.push(t.jsxs("span",{className:"chat-mention-chip",children:["@",b.name.replace(/\s+/g,"_")]},`${b.id}-${x}`)):m.push(p),h=x+p.length,f=u.exec(d)}return h<d.length&&m.push(d.slice(h)),m.length===0?d:m},[o,n.content,a]),c=i.useMemo(()=>o?null:s?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:n.content}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(vi,{remarkPlugins:[yi],components:Eb,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(Ud,{size:14}):t.jsx(Va,{size:14})})]}),Cb(n.toolCalls,!0)]})});function V$({projectId:e,addToast:n,showFAB:s=!0,open:a,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:c,onToggleModelFavorite:d}){const{agents:u}=A$(e),[m,h]=i.useState(!1),f=a!==void 0,p=f?a:m,g=f?me=>{r?.(typeof me=="function"?me(p):me)}:h;Ol({enabled:p});const x=Pi(),[v,b]=i.useState("agent"),[y,j]=i.useState(""),[C,A]=i.useState(!1),[N,S]=i.useState("model"),[_,T]=i.useState(""),[M,E]=i.useState(""),[L,F]=i.useState([]),[R,P]=i.useState(!1),[O,q]=i.useState(""),[Z,z]=i.useState(""),[k,I]=i.useState(""),[$,w]=i.useState([]),[H,K]=i.useState(!1),[pe,le]=i.useState(!1),[B,ye]=i.useState(""),[U,te]=i.useState(0),[ne,ee]=i.useState(""),[ie,ge]=i.useState(!1),[se,Ae]=i.useState(0),[xe,Se]=i.useState(-1),[qe,We]=i.useState(()=>new Set),[Qe,ve]=i.useState(!1),[Oe,ae]=i.useState([]),[re,je]=i.useState(!1),[,Q]=i.useState(!1),[Fe,Je]=i.useState({top:0,left:0}),be=T$({projectId:e}),ze=i.useCallback(me=>{if(!me||!be.mentionActive)return;const Ve=me.getBoundingClientRect();Je({top:Ve.top-260,left:Ve.left+8})},[be.mentionActive]),tt=i.useRef(!1),kt=i.useRef(!1),ke=i.useRef(""),ce=i.useRef(0),Te=i.useRef(null),he=i.useRef(null),Le=i.useRef(0),{position:st,isDragging:it,handlePointerDown:lt,handlePointerMove:$e,handlePointerUp:Ue}=H$(e,tt),Xe=st.y+60,{panelSize:wt,anchorOffset:Re,handleResizeStart:xt}=q$(e,st.x,Xe),Pt=typeof window<"u"&&window.innerWidth>ys,{activeSession:Ct,messages:Ot,isStreaming:zt,streamingText:Nt,streamingThinking:jt,streamingToolCalls:Yt,sessions:Bt,sessionsLoading:qt,messagesLoading:wn,sendMessage:mn,stopStreaming:Xt,pendingMessage:Vt,clearPendingMessage:Ft,switchSession:Zt,selectSession:en,startModelChat:cn,startFreshSession:we,refreshSessions:De}=_$(e,n),oe=i.useRef(null),Pe=i.useRef(null),Ce=i.useRef(null),J=i.useRef(null),Ie=i.useRef(null),de=i.useRef([]),Ne=i.useRef(!1),Ye=i.useRef(!1),ft=i.useRef(!1),tn=i.useRef(null),$t=i.useRef(!1);i.useEffect(()=>{if(!p||typeof window>"u"||typeof document>"u"||window.innerWidth>ys)return;const me=window.scrollY,Ve=document.documentElement,ot=document.body,on={htmlOverflow:Ve.style.overflow,bodyOverflow:ot.style.overflow};return window.scrollTo(0,0),Ve.style.overflow="hidden",ot.style.overflow="hidden",()=>{Ve.style.overflow=on.htmlOverflow,ot.style.overflow=on.bodyOverflow,window.scrollTo(0,me)}},[p]),i.useLayoutEffect(()=>{if(!p||typeof window>"u"||!window.visualViewport)return;const me=oe.current;if(!me)return;const Ve=window.visualViewport,ot=()=>{$t.current||(me.style.setProperty("--vv-height",`${Ve.height}px`),me.style.setProperty("--vv-offset-top",`${Ve.offsetTop||0}px`))};return ot(),Ve.addEventListener("resize",ot),Ve.addEventListener("scroll",ot),()=>{Ve.removeEventListener("resize",ot),Ve.removeEventListener("scroll",ot)}},[p]);const Rt=O||Z,Dt=i.useMemo(()=>Ho(Rt),[Rt]),En=i.useMemo(()=>L.find(me=>`${me.provider}/${me.id}`===Rt)??null,[L,Rt]),bn=i.useMemo(()=>$$(En,Dt),[En,Dt]),Nn=i.useMemo(()=>v==="model"?Dt?`${_a}::${Dt.modelProvider}/${Dt.modelId}`:"":y?`${y}::`:"",[v,Dt,y]),xn=!(v==="agent"?!!y:!!Dt)||!Ct;i.useEffect(()=>{if(u.length===0){j(""),b("model");return}u.some(Ve=>Ve.id===y)||j(u[0]?.id??"")},[u,y]),i.useEffect(()=>{!p||kt.current||(kt.current=!0,P(!0),Ms().then(me=>{const Ve=me.models??[];if(F(Ve),O||Ve.length===0)return;const ot=me.defaultProvider,on=me.defaultModelId;if(ot&&on){const X=`${ot}/${on}`;if(Ve.some(rt=>`${rt.provider}/${rt.id}`===X)){z(X),q(X),b("model");return}}z("");const Un=Ve[0];Un&&q(`${Un.provider}/${Un.id}`)}).catch(me=>{console.error("[QuickChatFAB] Failed to load models:",me),F([]),z("")}).finally(()=>{P(!1)}))},[p,u.length,O]),i.useEffect(()=>{!p||!e||(K(!0),KN(e).then(me=>{w(me)}).catch(()=>{w([])}).finally(()=>{K(!1)}))},[p,e]),i.useEffect(()=>{p&&De()},[p,De]),i.useEffect(()=>{if(!p){ke.current="";return}if(!Nn){ke.current="";return}const me=Nn===ke.current&&!Ct&&!qt;if(!(Nn===ke.current&&!me)){if(ke.current=Nn,v==="model"&&Dt){cn(Dt.modelProvider,Dt.modelId);return}v==="agent"&&y&&Zt(y)}},[p,v,Dt,y,Nn,Ct,qt,cn,Zt]),i.useEffect(()=>{p||(ge(!1),ee(""),Se(-1),le(!1),ye(""),te(0),de.current.forEach(me=>{me.previewUrl&&URL.revokeObjectURL(me.previewUrl)}),ae([]))},[p]),i.useEffect(()=>{de.current=Oe},[Oe]),i.useEffect(()=>{if(!p){Ne.current=!1;return}typeof window>"u"||(Ne.current=window.innerWidth<=ys)},[p]),i.useEffect(()=>{if(!p||xn||!Ne.current)return;const me=J.current;if(!me)return;const Ve=document.activeElement,ot=Ve?oe.current?.contains(Ve):!1,on=Ve===document.body,Un=Ve===tn.current;if(!ot&&!on&&!Un){Ne.current=!1;return}if(Un){me.focus({preventScroll:!0}),Ne.current=!1;return}const X=requestAnimationFrame(()=>{me.focus(),Ne.current=!1});return()=>cancelAnimationFrame(X)},[p,xn]),i.useEffect(()=>()=>{de.current.forEach(me=>{me.previewUrl&&URL.revokeObjectURL(me.previewUrl)})},[]);const rn=i.useCallback(()=>{A(!0),S("model"),T(u[0]?.id??""),E(O||Z||"")},[u,Z,O]),On=i.useMemo(()=>u.find(me=>me.id===y)??null,[u,y]),fe=i.useMemo(()=>{const me=B.trim().toLowerCase();return(me?$.filter(ot=>ot.name.toLowerCase().includes(me)):$).slice(0,10)},[$,B]),ct=i.useMemo(()=>{const me=ne.trim().toLowerCase();return me?u.filter(Ve=>Ve.name.toLowerCase().includes(me)):u},[u,ne]),hn=i.useMemo(()=>{const me=new Map;for(const Ve of u)me.set(Ve.name.toLowerCase(),Ve);return me},[u]);i.useEffect(()=>{te(0)},[fe]),i.useEffect(()=>{Ae(0)},[ne,ie]),i.useEffect(()=>()=>{Te.current!==null&&(window.clearTimeout(Te.current),Te.current=null),he.current!==null&&(window.clearTimeout(he.current),he.current=null)},[]),i.useEffect(()=>{if(!p)return;const me=ot=>{const on=ot.target;oe.current?.contains(on)||Pe.current?.contains(on)||on.closest(".model-combobox-dropdown--portal")||g(!1)},Ve=ot=>{ot.key==="Escape"&&g(!1)};return document.addEventListener("mousedown",me),document.addEventListener("keydown",Ve),()=>{document.removeEventListener("mousedown",me),document.removeEventListener("keydown",Ve)}},[p,g]),i.useEffect(()=>{if(!p)return;const me=Ce.current;me&&(me.scrollTop=me.scrollHeight)},[Ot,Nt,jt,zt,p]);const zn=i.useMemo(()=>{const me=new Map(u.map(ot=>[ot.id,ot.name?.trim()||ot.id])),Ve=new Map(L.map(ot=>[`${ot.provider}/${ot.id}`,ot.name?.trim()||""]));return Bt.map((ot,on)=>{const Un=ot.title?.trim()||`Session ${on+1}`;let X=null;if(ot.agentId&&ot.agentId!==_a)X=me.get(ot.agentId)||ot.agentId;else if(ot.modelProvider&&ot.modelId){const Me=`${ot.modelProvider}/${ot.modelId}`,rt=Ve.get(Me);X=rt?`${rt} [${Me}]`:Me}return{id:ot.id,label:X?`${Un} — ${X}`:Un}})},[u,L,Bt]),ue=i.useMemo(()=>v==="agent"?On?`Message ${On.name||On.id}`:"Select an agent to start chatting":bn?`Message ${bn}`:"Select a model to start chatting",[v,On,bn]),ut=i.useCallback(me=>{const Ve=Bt.find(ot=>ot.id===me);Ve&&(Ve.modelProvider&&Ve.modelId?(b("model"),q(`${Ve.modelProvider}/${Ve.modelId}`)):(b("agent"),j(Ve.agentId)),en(Ve))},[en,Bt]),yt=i.useCallback(async()=>{if(!qt){if(N==="agent"){if(!_)return;b("agent"),j(_),await we(_)}else{const me=Ho(M||O||Z);if(!me)return;b("model"),q(`${me.modelProvider}/${me.modelId}`),await we(_a,me.modelProvider,me.modelId)}await De(),A(!1),S("model")}},[Z,_,N,M,De,O,qt,we]),dt=Vt.length>50?`${Vt.slice(0,50)}…`:Vt,at=i.useCallback(me=>{if(!me||me.length===0)return;const Ve=[];for(let ot=0;ot<me.length;ot+=1){const on=me[ot];B$(on)&&Ve.push({file:on,previewUrl:U$(on)?URL.createObjectURL(on):""})}Ve.length>0&&ae(ot=>[...ot,...Ve])},[]),vt=i.useCallback(me=>{ae(Ve=>{const ot=Ve[me];return ot?.previewUrl&&URL.revokeObjectURL(ot.previewUrl),Ve.filter((on,Un)=>Un!==me)})},[]),Ht=i.useCallback(me=>{at(me.clipboardData?.files)},[at]),Ut=i.useCallback(()=>{if(typeof window>"u"||window.innerWidth>ys)return;const me=J.current;!me||me.disabled||me.focus({preventScroll:!0})},[]),An=i.useCallback(()=>{typeof window>"u"||window.innerWidth>ys||(ft.current=!0)},[]),Wt=i.useCallback(async()=>{const me=k.trim(),Ve=de.current;if(!(!me&&Ve.length===0)&&!xn){if(I(""),ge(!1),ee(""),Se(-1),me==="/help"){ve(!0),Ut(),ft.current=!1;return}if(me==="/clear"){Xt(),Ft(),Ve.forEach(ot=>{ot.previewUrl&&URL.revokeObjectURL(ot.previewUrl)}),ae(ot=>ot.filter(on=>!Ve.includes(on)));try{if(v==="model"){const ot=Ho(Rt);if(!ot)return;await we(_a,ot.modelProvider,ot.modelId)}else y&&await we(y)}catch{n("Failed to clear conversation","error")}finally{Ut(),ft.current=!1}return}try{ve(!1),await mn(me,Ve.map(ot=>ot.file)),Ve.forEach(ot=>{ot.previewUrl&&URL.revokeObjectURL(ot.previewUrl)}),ae(ot=>ot.filter(on=>!Ve.includes(on)))}catch{}finally{Ut(),ft.current=!1}}},[n,v,Ft,Ut,xn,k,Rt,y,mn,we,Xt]),Tt=i.useCallback(me=>{me.preventDefault(),Le.current+=1,je(!0)},[]),G=i.useCallback(me=>{me.preventDefault(),me.dataTransfer.dropEffect="copy",je(!0)},[]),He=i.useCallback(me=>{me.preventDefault(),Le.current=Math.max(0,Le.current-1),Le.current===0&&je(!1)},[]),mt=i.useCallback(me=>{me.preventDefault(),Le.current=0,je(!1),at(me.dataTransfer?.files)},[at]),ht=i.useCallback((me,Ve)=>{const ot=O$(me,Ve);if(ot){ge(!0),ee(ot.filter),Se(ot.start);return}ge(!1),ee(""),Se(-1)},[]),Et=i.useCallback(me=>{I(Ve=>{const ot=Ap(Ve);if(!ot)return Ve;const on=`/skill:${me.name} `,Un=Ve.slice(0,ot.start)+on+Ve.slice(ot.end);return window.requestAnimationFrame(()=>{J.current&&J.current.focus()}),Un}),le(!1),ye(""),te(0)},[]),St=i.useCallback(me=>{const Ve=J.current;if(!Ve||xe<0)return;const ot=Ve.selectionStart??ce.current,on=Ve.selectionEnd??ot,Un=Math.max(ot,on),X=Math.min(xe,Un),rt=`${`@${me.name.replace(/\s+/g,"_")}`} `,Mt=k.slice(0,X)+rt+k.slice(Un),Be=X+rt.length;I(Mt),ge(!1),ee(""),Ae(0),Se(-1),window.requestAnimationFrame(()=>{J.current&&(J.current.focus(),J.current.setSelectionRange(Be,Be))})},[xe,k]),sn=i.useCallback(me=>{const Ve=me.target.value,ot=me.target.selectionStart??Ve.length;ce.current=ot,I(Ve),Qe&&Ve.trim().length>0&&ve(!1),ht(Ve,ot);const on=Ap(Ve);on?(le(!0),ye(on.filter)):(le(!1),ye("")),be.detectMention(Ve,ot),Q(be.mentionActive),be.mentionActive&&ze(me.target)},[Qe,ht,be,ze]),nn=i.useCallback(()=>{if(ft.current){window.requestAnimationFrame(()=>{Ut()});return}typeof window<"u"&&window.innerWidth<=ys&&oe.current&&($t.current=!0,oe.current.style.removeProperty("--vv-height"),oe.current.style.removeProperty("--vv-offset-top"),window.setTimeout(()=>{$t.current=!1},450)),Te.current!==null&&window.clearTimeout(Te.current),Te.current=window.setTimeout(()=>{ge(!1),ee(""),Se(-1),Q(!1),be.dismissMention(),Te.current=null},120),he.current!==null&&window.clearTimeout(he.current),he.current=window.setTimeout(()=>{le(!1),he.current=null},120)},[be,Ut]),as=i.useCallback(()=>{$t.current=!1,Te.current!==null&&(window.clearTimeout(Te.current),Te.current=null),he.current!==null&&(window.clearTimeout(he.current),he.current=null)},[]),Is=i.useCallback(me=>{const Ve=me.currentTarget,ot=Ve.selectionStart??Ve.value.length;ce.current=ot,ht(Ve.value,ot),be.detectMention(Ve.value,ot),Q(be.mentionActive),be.mentionActive&&ze(Ve)},[ht,be,ze]),_s=i.useCallback(me=>{me.key!=="Escape"&&Is(me)},[Is]),ls=i.useCallback(me=>{We(Ve=>{const ot=new Set(Ve);return ot.has(me)?ot.delete(me):ot.add(me),ot})},[]),Xs=i.useCallback((me,Ve=!1)=>Ve?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:me}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(vi,{remarkPlugins:[yi],components:Eb,children:me})}),[]),ci=i.useCallback(me=>{if(ce.current=me.currentTarget.selectionStart??ce.current,be.mentionActive&&be.files.length>0){if(be.handleKeyDown(me,k),me.key==="Enter"||me.key==="Tab"){const Ve=be.files[be.selectedIndex];if(Ve){const ot=be.selectFile(Ve,k);I(ot),be.dismissMention(),Q(!1)}}return}if(ie&&me.key==="ArrowDown"){me.preventDefault(),ct.length>0&&Ae(Ve=>(Ve+1)%ct.length);return}if(ie&&me.key==="ArrowUp"){me.preventDefault(),ct.length>0&&Ae(Ve=>Ve===0?ct.length-1:Ve-1);return}if(ie&&me.key==="Enter"){me.preventDefault();const Ve=ct[se]??ct[0];Ve&&St(Ve);return}if(ie&&me.key==="Escape"){me.preventDefault(),me.stopPropagation(),ge(!1),ee(""),Se(-1);return}if(pe&&fe.length>0&&me.key==="ArrowDown"){me.preventDefault(),te(Ve=>(Ve+1)%fe.length);return}if(pe&&fe.length>0&&me.key==="ArrowUp"){me.preventDefault(),te(Ve=>Ve===0?fe.length-1:Ve-1);return}if(pe&&(me.key==="Enter"||me.key==="Tab")){me.preventDefault();const Ve=fe[U]??fe[0];Ve&&Et(Ve);return}if(pe&&me.key==="Escape"){me.preventDefault(),le(!1),ye("");return}me.key!=="Enter"||me.shiftKey||(me.preventDefault(),Wt())},[ie,ct,se,St,Wt,be,k,pe,fe,U,Et]),pn=i.useCallback(()=>{if(tt.current){tt.current=!1;return}if(p){g(!1);return}typeof window<"u"&&window.innerWidth<=ys&&tn.current?.focus({preventScroll:!0}),g(!0)},[p,g]);return t.jsxs(t.Fragment,{children:[t.jsx("input",{ref:tn,type:"text",className:"quick-chat-stealth-input","aria-hidden":"true",tabIndex:-1}),s&&t.jsx("button",{ref:Pe,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":it?"true":"false",style:{right:st.x,bottom:st.y},onPointerDown:lt,onPointerMove:$e,onPointerUp:Ue,onClick:pn,children:t.jsx(Ei,{size:24})}),p&&t.jsxs("div",{className:"quick-chat-panel",ref:oe,"data-testid":"quick-chat-panel",style:{...Pt?{right:st.x+Re.right,bottom:Xe+Re.bottom,width:wt.width,height:wt.height}:{}},children:[Pt&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"n","data-testid":"quick-chat-resize-n",onPointerDown:xt,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:xt,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:xt,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:xt,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:xt,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:xt,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:xt,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:xt,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"&&bn&&(()=>{const me=En?.provider??Dt?.modelProvider??"";return x==="mobile"&&bn.length>12&&me?t.jsx("span",{className:"quick-chat-model-tag quick-chat-model-tag--icon","data-testid":"quick-chat-model-tag",title:bn,"aria-label":bn,children:t.jsx(qn,{provider:me,size:"sm"})}):t.jsx("span",{className:"quick-chat-model-tag","data-testid":"quick-chat-model-tag",title:bn,children:bn})})()]}),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:rn,disabled:qt,children:t.jsx(Sn,{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(Jt,{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:Ct?.id??"",onChange:me=>ut(me.target.value),"data-testid":"quick-chat-session-dropdown",children:[t.jsx("option",{value:"",disabled:!0,children:qt?"Loading sessions…":"Select a session"}),zn.map(me=>t.jsx("option",{value:me.id,children:me.label},me.id))]})]}),C&&t.jsxs("div",{className:"quick-chat-new-session-chooser","data-testid":"quick-chat-new-session-chooser",children:[t.jsxs("div",{className:"quick-chat-inline-mode-toggle","data-testid":"quick-chat-inline-mode-toggle",children:[t.jsx("button",{type:"button",className:`quick-chat-mode-btn${N==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-model",onClick:()=>S("model"),children:"Model"}),t.jsx("button",{type:"button",className:`quick-chat-mode-btn${N==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-agent",onClick:()=>S("agent"),children:"Agent"})]}),N==="agent"?t.jsxs("div",{className:"quick-chat-panel-agent-select",children:[t.jsx("label",{htmlFor:"quick-chat-new-agent-select",className:"visually-hidden",children:"Select agent for new chat"}),t.jsx("select",{id:"quick-chat-new-agent-select",value:_,onChange:me=>T(me.target.value),"data-testid":"quick-chat-new-agent-select",children:u.map(me=>t.jsx("option",{value:me.id,children:I$(me)},me.id))})]}):t.jsx("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-new-model-select",children:t.jsx(hs,{id:"quick-chat-new-model-select",models:L,value:M,onChange:E,label:"Select model override",placeholder:R?"Loading models…":"Select a model",disabled:R||L.length===0,favoriteProviders:o,favoriteModels:l,onToggleFavorite:c,onToggleModelFavorite:d})}),t.jsxs("div",{className:"quick-chat-new-session-actions",children:[t.jsx("button",{type:"button",className:"btn","data-testid":"quick-chat-new-session-cancel",onClick:()=>{A(!1),S("model")},children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary","data-testid":"quick-chat-new-session-submit",onClick:()=>void yt(),disabled:qt||(N==="agent"?!_:!Ho(M||O||Z)),children:"Create"})]})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:Ce,"data-testid":"quick-chat-messages",children:qt?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):zt?t.jsxs(t.Fragment,{children:[Ot.map(me=>t.jsx(Pp,{message:me,forcePlain:me.role!=="user"&&qe.has(me.id),mentionAgentsByName:hn,onToggleRender:ls},me.id)),Qe&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:Xs("Available commands:\n- `/clear` — Clear conversation and start fresh\n- `/skill:{name}` — Use a specific skill\n- `/help` — Show this help")}),t.jsxs("div",{className:"quick-chat-panel-message quick-chat-panel-message--received quick-chat-panel-message--streaming","data-testid":"quick-chat-streaming-message",children:[Nt?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:Xs(Nt,qe.has("__streaming__"))}),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${qe.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":qe.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>ls("__streaming__"),children:qe.has("__streaming__")?t.jsx(Ud,{size:14}):t.jsx(Va,{size:14})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:jt?"Thinking…":"Connecting…"}),Cb(Yt,!0),jt&&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:jt})]})]})]}):wn?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):Ot.length===0&&!Nt&&!jt&&!zt&&!Qe?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[Ot.map(me=>t.jsx(Pp,{message:me,forcePlain:me.role!=="user"&&qe.has(me.id),mentionAgentsByName:hn,onToggleRender:ls},me.id)),Qe&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:Xs("Available commands:\n- `/clear` — Clear conversation and start fresh\n- `/skill:{name}` — Use a specific skill\n- `/help` — Show this help")})]})}),Oe.length>0&&t.jsx("div",{className:"quick-chat-attachment-previews","data-testid":"quick-chat-attachment-previews",children:Oe.map((me,Ve)=>t.jsxs("div",{className:"quick-chat-attachment-preview","data-testid":`quick-chat-attachment-preview-${Ve}`,children:[me.previewUrl?t.jsx("img",{src:me.previewUrl,alt:me.file.name}):t.jsx("span",{className:"quick-chat-attachment-preview-name",children:me.file.name}),t.jsx("button",{type:"button",className:"quick-chat-attachment-remove","data-testid":`quick-chat-attachment-remove-${Ve}`,"aria-label":`Remove ${me.file.name}`,onClick:()=>vt(Ve),children:"×"})]},`${me.file.name}-${Ve}`))}),t.jsx("div",{className:"quick-chat-panel-input",children:t.jsxs("div",{className:`quick-chat-input-wrapper${re?" quick-chat-input-wrapper--dragover":""}`,onDragEnter:Tt,onDragOver:G,onDragLeave:He,onDrop:mt,children:[t.jsx("input",{ref:Ie,type:"file",accept:"image/*,.txt,.json,.yaml,.yml,.log,.csv,.xml,.md",multiple:!0,tabIndex:-1,"aria-hidden":"true",className:"quick-chat-attachment-input",onChange:me=>{at(me.target.files),me.target.value=""}}),t.jsxs("div",{className:"quick-chat-input-row","data-testid":"quick-chat-input-row",children:[t.jsx("button",{type:"button",className:"btn-icon quick-chat-attach-btn","data-testid":"quick-chat-attach-btn","aria-label":"Attach files",onClick:()=>Ie.current?.click(),children:t.jsx(tf,{size:16})}),t.jsx("input",{ref:J,type:"text",value:k,onChange:sn,onKeyDown:ci,onKeyUp:_s,onClick:Is,onBlur:nn,onFocus:as,onPaste:Ht,onTouchStart:me=>{typeof window>"u"||window.innerWidth>ys||document.activeElement!==me.currentTarget&&(me.preventDefault(),me.currentTarget.focus({preventScroll:!0}))},placeholder:ue,disabled:xn,"data-testid":"quick-chat-input"}),zt?t.jsx("button",{type:"button",className:"chat-input-stop quick-chat-send-btn",onPointerDown:me=>{typeof window>"u"||window.innerWidth>ys||(me.preventDefault(),me.pointerType&&me.pointerType!=="mouse"&&(Ye.current=!0,Xt()))},onTouchStart:me=>{typeof window>"u"||window.innerWidth>ys||(me.preventDefault(),Ye.current=!0,Xt())},onMouseDown:me=>{typeof window>"u"||window.innerWidth>ys||me.preventDefault()},onClick:()=>{if(Ye.current){Ye.current=!1;return}Xt()},"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:t.jsx(Os,{size:14})}):t.jsx("button",{type:"button",className:"quick-chat-send-btn",onPointerDown:me=>{typeof window>"u"||window.innerWidth>ys||(me.preventDefault(),me.pointerType&&me.pointerType!=="mouse"&&(Ye.current=!0,An(),Ut(),Wt()))},onTouchStart:me=>{typeof window>"u"||window.innerWidth>ys||(me.preventDefault(),Ye.current=!0,An(),Ut(),Wt())},onMouseDown:me=>{typeof window>"u"||window.innerWidth>ys||me.preventDefault()},onClick:()=>{if(Ye.current){Ye.current=!1;return}Wt()},disabled:xn||k.trim().length===0&&Oe.length===0,"data-testid":"quick-chat-send",children:t.jsx(Xi,{size:16})})]}),t.jsx(E$,{agents:u,filter:ne,highlightedIndex:se,visible:ie,onSelect:St,position:"above"}),t.jsx(P$,{visible:be.mentionActive&&!ie,position:Fe,files:be.files,selectedIndex:be.selectedIndex,onSelect:me=>{const Ve=be.selectFile(me,k);I(Ve),be.dismissMention(),Q(!1),J.current?.focus()},loading:be.loading}),pe&&t.jsx("div",{className:"chat-skill-menu","data-testid":"quick-chat-skill-menu",role:"listbox","aria-label":"Skill suggestions",children:H?t.jsx("div",{className:"chat-skill-menu-empty",children:"Loading skills…"}):fe.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:B?"No skills found":"No skills available"}):fe.map((me,Ve)=>t.jsxs("button",{type:"button",role:"option","aria-selected":Ve===U,className:`chat-skill-menu-item${Ve===U?" chat-skill-menu-item--highlighted":""}`,onMouseDown:ot=>ot.preventDefault(),onMouseEnter:()=>te(Ve),onClick:()=>Et(me),children:[t.jsx("span",{className:"chat-skill-menu-item-name",children:me.name}),t.jsx("span",{className:"chat-skill-menu-item-description",title:me.relativePath,children:me.relativePath})]},me.id))}),Vt&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${dt}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:Ft,children:"×"})]})]})})]})]})}function br(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function Rp(e){return e.status==="generating"||e.status==="awaiting_input"}function xr(e){return e==="complete"||e==="error"}function W$(e){const[n,s]=i.useState([]),a=i.useRef(new Map),r=i.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:c,requestSync:d}=Ya(),u=i.useCallback(()=>{Wd(e).then(p=>{const g=p.filter(v=>{const b=br(v.updatedAt),y=r.current.get(v.id);return y===void 0?!0:b<=y?!1:(r.current.delete(v.id),!0)}),x=new Map;for(const v of g)x.set(v.id,br(v.updatedAt));a.current=x,s(g)}).catch(p=>{console.warn("[useBackgroundSessions] Failed to fetch AI sessions:",p)})},[e]);i.useEffect(()=>{d(),u()},[u,d]),i.useEffect(()=>{s(p=>{if(o.size===0)return p;let g=!1;const x=new Map(p.map(v=>[v.id,v]));for(const v of o.values()){if(e&&v.projectId&&v.projectId!==e)continue;const b=v.lastEventTimestamp,y=a.current.get(v.sessionId)??0;if(b<y)continue;const j=r.current.get(v.sessionId);if(j!==void 0&&b<=j)continue;if(j!==void 0&&b>j&&!xr(v.status)&&r.current.delete(v.sessionId),xr(v.status)){x.delete(v.sessionId)&&(g=!0),a.current.set(v.sessionId,b);continue}const C=x.get(v.sessionId),A=v.type??C?.type,N=v.title??C?.title;if(!C&&(!A||!N))continue;const S={id:v.sessionId,type:A??"planning",status:v.status,title:N??"AI Session",projectId:v.projectId??C?.projectId??e??null,lockedByTab:v.owningTabId??C?.lockedByTab??null,updatedAt:v.updatedAt??C?.updatedAt??new Date(b).toISOString()},_=x.get(v.sessionId);(!_||_.status!==S.status||_.title!==S.title||_.type!==S.type||_.projectId!==S.projectId||_.lockedByTab!==S.lockedByTab||_.updatedAt!==S.updatedAt)&&(x.set(v.sessionId,S),a.current.set(v.sessionId,b),g=!0)}return g?[...x.values()].sort((v,b)=>br(b.updatedAt)-br(v.updatedAt)):p})},[e,o]),i.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",g=v=>{try{const b=JSON.parse(v.data),y=br(b.updatedAt)||Date.now();s(j=>{const C=a.current.get(b.id)??0;if(y<C)return j;const A=r.current.get(b.id);if(A!==void 0&&y<=A)return j;if(A!==void 0&&y>A&&!xr(b.status)&&r.current.delete(b.id),a.current.set(b.id,y),xr(b.status))return j.filter(S=>S.id!==b.id);const N=j.findIndex(S=>S.id===b.id);if(N>=0){const S=[...j];return S[N]=b,S}return Rp(b)?[b,...j]:j}),l({sessionId:b.id,status:b.status,needsInput:b.status==="awaiting_input",type:b.type,title:b.title,projectId:b.projectId,owningTabId:b.lockedByTab,updatedAt:b.updatedAt,timestamp:y}),xr(b.status)&&c({sessionId:b.id,status:b.status,timestamp:y})}catch{}},x=v=>{try{const b=JSON.parse(v.data),y=Date.now();r.current.set(b,y),a.current.set(b,Math.max(a.current.get(b)??0,y)),c({sessionId:b,status:"complete",timestamp:y}),s(j=>j.filter(C=>C.id!==b))}catch{}};return li(`/api/events${p}`,{events:{"ai_session:updated":g,"ai_session:deleted":x},onReconnect:()=>{u()}})},[c,l,e,u]);const m=i.useCallback(async p=>{const x=n.find(j=>j.id===p)?.type,v=ma();let b=!1;if(x==="planning")try{await df(p,e,v)}catch(j){b=!0,j instanceof Error&&j.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of planning session ${p} despite lock by another tab`)}else if(x==="subtask")try{await hf(p,e,v)}catch(j){b=!0,j instanceof Error&&j.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of subtask session ${p} despite lock by another tab`)}else if(x==="mission_interview")try{await bf(p,e,v)}catch(j){b=!0,j instanceof Error&&j.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of mission interview session ${p} despite lock by another tab`)}b&&console.warn(`[useBackgroundSessions] Cancellation failed for session ${p}, attempting delete anyway`);const y=Date.now();r.current.set(p,y),a.current.set(p,Math.max(a.current.get(p)??0,y)),c({sessionId:p,status:"complete",timestamp:y});try{await xf(p)}catch{}s(j=>j.filter(C=>C.id!==p))},[c,e,n]),h=i.useMemo(()=>n.filter(p=>Rp(p)),[n]),f=i.useMemo(()=>h.filter(p=>p.type==="planning"),[h]);return{sessions:h,generating:h.filter(p=>p.status==="generating").length,needsInput:h.filter(p=>p.status==="awaiting_input").length,planningSessions:f,dismissSession:m,refresh:u}}const gl="fusion:hide-session-banners",Od="fusion:session-banner-pref-changed";function K$(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(gl)==="1"}catch{return!1}}function G$(e){if(typeof window>"u")return()=>{};const n=a=>{a.key===gl&&e()},s=()=>e();return window.addEventListener("storage",n),window.addEventListener(Od,s),()=>{window.removeEventListener("storage",n),window.removeEventListener(Od,s)}}function Gz(e){if(!(typeof window>"u"))try{e?window.localStorage.setItem(gl,"1"):window.localStorage.removeItem(gl),window.dispatchEvent(new Event(Od))}catch{}}function J$(){return i.useSyncExternalStore(G$,K$,()=>!1)}function ds(e){return{...e,dependencies:Array.isArray(e.dependencies)?e.dependencies:[],steps:Array.isArray(e.steps)?e.steps:[],log:Array.isArray(e.log)?e.log:[]}}function Tp(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function Y$(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 Xc(e,n){if(Tp(n.updatedAt,e.updatedAt)<0)return e;if(e.column===n.column)return Y$(e,n);const a=Tp(e.columnMovedAt,n.columnMovedAt);return e.columnMovedAt&&!n.columnMovedAt?{...n,column:e.column,columnMovedAt:e.columnMovedAt}:a>0?{...n,column:e.column,columnMovedAt:e.columnMovedAt}:n}function Q$(e){const n=e?.projectId,s=e?.searchQuery,a=e?.sseEnabled??!0,[r,o]=i.useState([]),[l,c]=i.useState(!1),d=i.useRef(l);d.current=l;const u=i.useRef(r),m=i.useRef(0),h=i.useRef(0),f=i.useRef(s),p=i.useRef(null),g=i.useRef(void 0),x=i.useRef(0),v=i.useRef(n);u.current=r,f.current=s,v.current!==n&&(v.current=n,x.current++);const b=1e3,y=i.useCallback(async Z=>{const z=++m.current,k=n,I=Z?.searchQueryOverride??f.current,$=Z?.includeArchivedOverride??d.current;try{const w=await ew(void 0,void 0,k,I,$);if(m.current!==z||n!==k)return;o(w.map(ds)),g.current=Date.now()}catch{if(m.current!==z||n!==k)return;if(Z?.clearOnError){o([]);return}o(w=>w)}},[n]);p.current=y;const j=i.useCallback(async()=>{d.current||(c(!0),d.current=!0,await p.current({includeArchivedOverride:!0}))},[]),C=i.useRef(s);i.useEffect(()=>{if(s===void 0&&C.current===void 0)return;C.current=s;const Z=setTimeout(()=>{y({searchQueryOverride:s})},300);return()=>clearTimeout(Z)},[s]),i.useEffect(()=>{y({clearOnError:!0});const Z=()=>{if(document.visibilityState!=="visible")return;const z=Date.now();z-h.current<b||(h.current=z,y())};return document.addEventListener("visibilitychange",Z),()=>{document.removeEventListener("visibilitychange",Z)}},[y]),i.useEffect(()=>{if(a===!1)return;const Z=x.current,z=n?`?projectId=${encodeURIComponent(n)}`:"",k=()=>x.current!==Z;let I=!0;const $=B=>{if(k())return;const ye=ds(JSON.parse(B.data));if(f.current){p.current({searchQueryOverride:f.current});return}o(U=>{const te=U.findIndex(ge=>ge.id===ye.id);if(te===-1)return[...U,ye];const ne=U[te],ee=Xc(ne,ye);if(ee===ne)return U;const ie=[...U];return ie[te]=ee,ie}),g.current=Date.now()},w=B=>{if(k())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:ye,to:U}=JSON.parse(B.data),te=ds(ye);o(ne=>ne.map(ee=>ee.id===te.id?{...te,column:U}:ee)),g.current=Date.now()},H=B=>{if(k())return;if(f.current){p.current({searchQueryOverride:f.current});return}const ye=ds(JSON.parse(B.data));o(U=>U.map(te=>te.id!==ye.id?te:Xc(te,ye))),g.current=Date.now()},K=B=>{if(k())return;if(f.current){p.current({searchQueryOverride:f.current});return}const ye=ds(JSON.parse(B.data));o(U=>U.filter(te=>te.id!==ye.id))},pe=B=>{if(k())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:ye}=JSON.parse(B.data),U=ds(ye);o(te=>te.map(ne=>ne.id===U.id?{...U,column:"done"}:ne))},le=li(`/api/events${z}`,{events:{"task:created":$,"task:moved":w,"task:updated":H,"task:deleted":K,"task:merged":pe},onReconnect:()=>{I&&(k()||p.current())}});return()=>{I=!1,le()}},[n,a]);const A=i.useCallback(async Z=>{const z=ds(await tl(Z,n));return o(k=>k.some(I=>I.id===z.id)?k:[...k,z]),z},[n]),N=i.useCallback(async(Z,z,k)=>ds(await nw(Z,z,n,k)),[n]),S=i.useCallback(async Z=>ds(await of(Z,n)),[n]),_=i.useCallback(async Z=>ds(await sw(Z,n)),[n]),T=i.useCallback(async Z=>iw(Z,n),[n]),M=i.useCallback(async Z=>ds(await aw(Z,n)),[n]),E=i.useCallback(async Z=>ds(await rw(Z,n)),[n]),L=i.useCallback(async Z=>{const z=ds(await ow(Z,n));return o(k=>k.some(I=>I.id===z.id)?k:[...k,z]),z},[n]),F=i.useCallback(async(Z,z)=>{const k=u.current.find($=>$.id===Z),I=k?{...k,...z,updatedAt:new Date().toISOString()}:void 0;I&&o($=>$.map(w=>w.id===Z?I:w));try{const $=ds(await ni(Z,z,n));return o(w=>w.map(H=>H.id===Z?$:H)),$}catch($){throw k&&o(w=>w.map(H=>H.id===Z?k:H)),$}},[n]),R=i.useCallback(async Z=>{const z=ds(await cw(Z,n));return o(k=>k.map(I=>I.id===Z?z:I)),z},[n]),P=i.useCallback(async Z=>{const z=ds(await dw(Z,n));return o(k=>k.map(I=>I.id===Z?z:I)),z},[n]),O=i.useCallback(async()=>{const z=(await uw(n)).map(ds);return o(k=>k.map(I=>z.find(w=>w.id===I.id)||I)),z},[n]),q=i.useCallback(Z=>{if(Z.length===0)return;if(f.current){p.current({searchQueryOverride:f.current});return}const z=Z.map(ds);o(k=>{let I=k;for(const $ of z){const w=I.findIndex(pe=>pe.id===$.id);if(w===-1){I===k&&(I=[...k]),I.push($);continue}const H=I[w],K=Xc(H,$);K!==H&&(I===k&&(I=[...k]),I[w]=K)}return I}),g.current=Date.now()},[]);return{tasks:r,createTask:A,moveTask:N,pauseTask:S,deleteTask:_,mergeTask:T,retryTask:M,resetTask:E,duplicateTask:L,updateTask:F,archiveTask:R,unarchiveTask:P,archiveAllDone:O,loadArchivedTasks:j,includeArchived:l,ingestCreatedTasks:q,lastFetchTimeMs:g.current}}const X$=5e3,Z$=1e3;function eD(){const[e,n]=i.useState([]),[s,a]=i.useState(!0),[r,o]=i.useState(null),l=i.useRef(null),c=i.useRef(0),d=i.useCallback(async()=>{try{o(null);const f=await qu();n(f)}catch(f){o(f instanceof Error?f.message:"Failed to fetch projects")}},[]);i.useEffect(()=>{let f=!1;async function p(){a(!0);const x=performance.now();try{const v=await qu(),y=`initial fetchProjectsAcrossNodes took ${Math.round(performance.now()-x)}ms (${v.length} projects)`;console.log(`[useProjects] ${y}`),Er("[useProjects]",y),f||(n(v),o(null))}catch(v){const y=`initial fetch failed after ${Math.round(performance.now()-x)}ms: ${v instanceof Error?v.message:String(v)}`;console.warn(`[useProjects] ${y}`),Er("[useProjects]",y),f||o(v instanceof Error?v.message:"Failed to fetch projects")}finally{f||a(!1)}}p();const g=()=>{if(document.visibilityState!=="visible")return;const x=Date.now();x-c.current<Z$||(c.current=x,d())};return document.addEventListener("visibilitychange",g),()=>{f=!0,document.removeEventListener("visibilitychange",g)}},[d]),i.useEffect(()=>{if(!s)return l.current=setInterval(()=>{d()},X$),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,d]);const u=i.useCallback(async f=>{const p=await yj(f);return n(g=>[...g,p]),p},[]),m=i.useCallback(async(f,p)=>{const g=await Cj(f,p);return n(x=>x.map(v=>v.id===f?g:v)),g},[]),h=i.useCallback(async f=>{await pf(f),n(p=>p.filter(g=>g.id!==f))},[]);return{projects:e,loading:s,error:r,refresh:d,register:u,update:m,unregister:h}}const tD="kb-dashboard-current-project";function nD(e){return e??"local"}function sD(e,n={}){const{nodeId:s=null}=n,[a,r]=i.useState(null),[o,l]=i.useState(!0),c=i.useRef(!1),d=i.useRef(!1),u=i.useRef(null),m=nD(s);i.useEffect(()=>{let p=!1;async function g(){try{const x=await ca();if(p)return;u.current=x.dashboardCurrentProjectIdByNode??{};const v=u.current[m];if(v){const b=e.find(y=>y.id===v);b&&(r(b),c.current=!0)}if(!v)try{const b=localStorage.getItem(tD);if(b){const y=JSON.parse(b);y?.id&&e.some(C=>C.id===y.id)&&(r(y),c.current=!0,u.current={...u.current,[m]:y.id},await _n({dashboardCurrentProjectIdByNode:u.current}).catch(()=>{}))}}catch{}}catch{}finally{p||l(!1)}}return g(),()=>{p=!0}},[m,e]),i.useEffect(()=>{if(!o){if(a){if(!e.some(x=>x.id===a.id)&&e.length>0){const x=e.find(v=>v.status==="active");r(x||e[0]||null);return}const g={...u.current,[m]:a.id};u.current=g,_n({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}else if(e.length>0&&!d.current){const p=e.find(g=>g.status==="active");p&&r(p)}}},[a,e,o,m]);const h=i.useCallback(p=>{if(d.current=!1,r(p),p){const g={...u.current,[m]:p.id};u.current=g,_n({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}},[m]),f=i.useCallback(()=>{d.current=!0,r(null);const p={...u.current};delete p[m],u.current=p,_n({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[m]);return{currentProject:a,setCurrentProject:h,clearCurrentProject:f,loading:o}}const Mb=i.createContext(null);function iD({children:e}){const[n,s]=i.useState([]),a=i.useRef(0),r=i.useRef(new Map),o=i.useCallback(c=>{const d=r.current.get(c);d!==void 0&&(clearTimeout(d),r.current.delete(c)),s(u=>u.filter(m=>m.id!==c))},[]),l=i.useCallback((c,d="info")=>{const u=a.current++;s(h=>[...h,{id:u,message:c,type:d}]);const m=setTimeout(()=>o(u),4e3);r.current.set(u,m)},[o]);return i.useEffect(()=>()=>{r.current.forEach(c=>clearTimeout(c)),r.current.clear()},[]),Jo.createElement(Mb.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function aD(){const e=i.useContext(Mb);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const _b="kb-dashboard-theme-mode",Ab="kb-dashboard-color-theme",Pb="kb-dashboard-font-scale-pct",zd=100,rD=85,oD=125,Rb=[...I1],Fd="theme-data",Zc="theme-data.css";function lD(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.endsWith("/")?e.slice(0,-1)+`/${Zc}`:e.replace(/\/[^/]+$/,`/${Zc}`):`/${Zc}`}const Ps=typeof window<"u",cD=Ps?i.useLayoutEffect:i.useEffect;function Tb(e){return e==="dark"||e==="light"||e==="system"}function Ip(){if(!Ps)return"dark";try{const e=localStorage.getItem(_b);if(Tb(e))return e}catch{}return"dark"}function $p(){if(!Ps)return"default";try{const e=localStorage.getItem(Ab);if(e&&Rb.includes(e))return e}catch{}return"default"}function Dp(e){if(Ps)try{localStorage.setItem(_b,e)}catch{}}function Lp(e){if(Ps)try{localStorage.setItem(Ab,e)}catch{}}function Ur(e){return typeof e!="number"||!Number.isFinite(e)?zd:Math.min(oD,Math.max(rD,Math.round(e)))}function Op(){if(!Ps)return zd;try{const e=Number(localStorage.getItem(Pb));return Ur(e)}catch{return zd}}function zp(e){if(Ps)try{localStorage.setItem(Pb,String(Ur(e)))}catch{}}function dD(e,n){return e==="system"?n?"dark":"light":e}function uD(e,n,s,a){if(!Ps)return;const r=dD(e,a);document.documentElement.setAttribute("data-theme",r),document.documentElement.setAttribute("data-color-theme",n),document.documentElement.style.fontSize=`${Ur(s)}%`}function Fp(){if(!Ps)return;const e=lD(),n=document.getElementById(Fd);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=Fd,document.head.appendChild(s)}function Up(){if(!Ps)return;const e=document.getElementById(Fd);e&&e.remove()}function mD(){const[e,n]=i.useState(()=>Ip()),[s,a]=i.useState(()=>$p()),[r,o]=i.useState(()=>Op()),[l,c]=i.useState(!0),[d,u]=i.useState(()=>Ps?window.matchMedia("(prefers-color-scheme: dark)").matches:!0),m=i.useRef(e),h=i.useRef(s),f=i.useRef(r),p=i.useRef(!1),g=i.useRef(!1),x=i.useRef(!1);i.useEffect(()=>{m.current=e},[e]),i.useEffect(()=>{h.current=s},[s]),i.useEffect(()=>{f.current=r},[r]),i.useEffect(()=>{if(!Ps||!l)return;let j=!1;return ca().then(C=>{if(!j&&(Tb(C.themeMode)&&!p.current&&(m.current!==C.themeMode&&(m.current=C.themeMode,n(C.themeMode)),Ip()!==C.themeMode&&Dp(C.themeMode)),C.colorTheme&&Rb.includes(C.colorTheme)&&!g.current&&(h.current!==C.colorTheme&&(h.current=C.colorTheme,a(C.colorTheme)),$p()!==C.colorTheme&&Lp(C.colorTheme)),!x.current)){const A=Ur(C.dashboardFontScalePct);f.current!==A&&(f.current=A,o(A)),Op()!==A&&zp(A)}}).catch(C=>{console.warn("[useTheme] Failed to hydrate theme from global settings",C)}).finally(()=>{j||c(!1)}),()=>{j=!0}},[l]),i.useEffect(()=>{if(!Ps)return;const j=window.matchMedia("(prefers-color-scheme: dark)"),C=A=>{u(A.matches)};return j.addEventListener("change",C),()=>j.removeEventListener("change",C)},[]),cD(()=>{uD(e,s,r,d)},[e,s,r,d]),i.useEffect(()=>{!Ps||l||(s!=="default"?Fp():Up())},[s,l]);const v=i.useCallback(j=>{p.current=!0,m.current=j,n(j),Dp(j),_n({themeMode:j}).catch(C=>{console.warn("[useTheme] Failed to persist themeMode to global settings",C)})},[]),b=i.useCallback(j=>{g.current=!0,h.current=j,a(j),Lp(j),j!=="default"?Fp():Up(),_n({colorTheme:j}).catch(C=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",C)})},[]),y=i.useCallback(j=>{const C=Ur(j);x.current=!0,f.current=C,o(C),zp(C),_n({dashboardFontScalePct:C}).catch(A=>{console.warn("[useTheme] Failed to persist dashboardFontScalePct to global settings",A)})},[]);return{themeMode:e,colorTheme:s,dashboardFontScalePct:r,setThemeMode:v,setColorTheme:b,setDashboardFontScalePct:y,isSystemDark:d}}function hD(e){const{planningSessions:n}=e,[s,a]=i.useState(!1),[r,o]=i.useState(!1),[l,c]=i.useState(null),[d,u]=i.useState(void 0),[m,h]=i.useState(!1),[f,p]=i.useState(null),[g,x]=i.useState(void 0),[v,b]=i.useState(null),[y,j]=i.useState("definition"),[C,A]=i.useState(null),[N,S]=i.useState(!1),[_,T]=i.useState(void 0),[M,E]=i.useState(!1),[L,F]=i.useState(!1),[R,P]=i.useState(!1),[O,q]=i.useState(null),[Z,z]=i.useState(!1),[k,I]=i.useState(!1),[$,w]=i.useState(void 0),[H,K]=i.useState(!1),[pe,le]=i.useState(!1),[B,ye]=i.useState("project"),[U,te]=i.useState(!1),[ne,ee]=i.useState(!1),[ie,ge]=i.useState(!1),[se,Ae]=i.useState(!1),[xe,Se]=i.useState(!1),[qe,We]=i.useState(!1),[Qe,ve]=i.useState(!1),Oe=!!(v||N||s||r||m||k||H||pe||U||ne||ie||xe||se||R||Z||M||L||qe||Qe),ae=i.useCallback(()=>a(!0),[]),re=i.useCallback(()=>a(!1),[]),je=i.useCallback(()=>o(!0),[]),Q=i.useCallback(Ne=>{c(Ne),o(!0)},[]),Fe=i.useCallback(()=>{const Ne=n[0];Ne&&(u(Ne.id),o(!0))},[n]),Je=i.useCallback(Ne=>{u(Ne),o(!0)},[]),be=i.useCallback(()=>{o(!1),c(null),u(void 0)},[]),ze=i.useCallback(Ne=>{p(Ne),h(!0)},[]),tt=i.useCallback(Ne=>{x(Ne),h(!0)},[]),kt=i.useCallback(()=>{h(!1),p(null),x(void 0)},[]),ke=i.useCallback((Ne,Ye="definition",ft)=>{b(Ne),j(Ye),A(ft?.origin??null)},[]),ce=i.useCallback(Ne=>{b(Ne),j("changes"),A(null)},[]),Te=i.useCallback(Ne=>{b(Ye=>Ye&&{...Ye,...Ne})},[]),he=i.useCallback(()=>{b(null),A(null)},[]),Le=i.useCallback(Ne=>{T(Ne),S(!0)},[]),st=i.useCallback(()=>{S(!1),T(void 0)},[]),it=i.useCallback(()=>E(!0),[]),lt=i.useCallback(()=>E(!1),[]),$e=i.useCallback(()=>F(!0),[]),Ue=i.useCallback(()=>F(!1),[]),Xe=i.useCallback(Ne=>{q(Ne??null),P(!0)},[]),wt=i.useCallback(()=>{P(!1),q(null)},[]),Re=i.useCallback(()=>z(!0),[]),xt=i.useCallback(()=>z(!1),[]),Pt=i.useCallback(()=>{I(Ne=>!Ne)},[]),Ct=i.useCallback(()=>{I(!1),w(void 0)},[]),Ot=i.useCallback(()=>K(!0),[]),zt=i.useCallback(()=>K(!1),[]),Nt=i.useCallback(()=>le(!0),[]),jt=i.useCallback(()=>le(!1),[]),Yt=i.useCallback(Ne=>{ye(Ne)},[]),Bt=i.useCallback(()=>te(!0),[]),qt=i.useCallback(()=>te(!1),[]),wn=i.useCallback(()=>ee(!0),[]),mn=i.useCallback(()=>ee(!1),[]),Xt=i.useCallback(()=>ge(!0),[]),Vt=i.useCallback(()=>ge(!1),[]),Ft=i.useCallback(()=>Ae(!0),[]),Zt=i.useCallback(()=>Ae(!1),[]),en=i.useCallback(()=>Se(!0),[]),cn=i.useCallback(()=>Se(!1),[]),we=i.useCallback(async(Ne,Ye)=>{Se(!1),w(Ye),I(!0)},[]),De=i.useCallback(()=>We(!0),[]),oe=i.useCallback(()=>We(!1),[]),Pe=i.useCallback(()=>ve(!0),[]),Ce=i.useCallback(()=>ve(!1),[]),J=i.useCallback((Ne,Ye)=>{Ye(`Created ${Ne.id} from planning mode`,"success"),o(!1),c(null)},[]),Ie=i.useCallback((Ne,Ye)=>{const ft=Ne.map(tn=>tn.id).join(", ");Ye(`Created ${ft} from planning mode`,"success"),o(!1),c(null)},[]),de=i.useCallback((Ne,Ye)=>{const ft=Ne.map(tn=>tn.id).join(", ");Ye(`Created ${ft} from subtask breakdown`,"success"),h(!1),p(null)},[]);return{newTaskModalOpen:s,isPlanningOpen:r,planningInitialPlan:l,planningResumeSessionId:d,isSubtaskOpen:m,subtaskInitialDescription:f,subtaskResumeSessionId:g,detailTask:v,detailTaskInitialTab:y,detailTaskOrigin:C,settingsOpen:N,settingsInitialSection:_,schedulesOpen:M,githubImportOpen:L,usageOpen:R,usageAnchorRect:O,systemStatsOpen:Z,terminalOpen:k,terminalInitialCommand:$,filesOpen:H,todosOpen:pe,fileBrowserWorkspace:B,activityLogOpen:U,gitManagerOpen:ne,workflowStepsOpen:ie,agentsOpen:se,scriptsOpen:xe,setupWizardOpen:qe,modelOnboardingOpen:Qe,anyModalOpen:Oe,openNewTask:ae,closeNewTask:re,openPlanning:je,openPlanningWithInitialPlan:Q,resumePlanning:Fe,openPlanningWithSession:Je,closePlanning:be,openSubtaskBreakdown:ze,openSubtaskWithSession:tt,closeSubtask:kt,openDetailTask:ke,openDetailWithChangesTab:ce,updateDetailTask:Te,closeDetailTask:he,openSettings:Le,closeSettings:st,openSchedules:it,closeSchedules:lt,openGitHubImport:$e,closeGitHubImport:Ue,openUsage:Xe,closeUsage:wt,openSystemStats:Re,closeSystemStats:xt,toggleTerminal:Pt,closeTerminal:Ct,openFiles:Ot,closeFiles:zt,openTodos:Nt,closeTodos:jt,setFileWorkspace:Yt,openActivityLog:Bt,closeActivityLog:qt,openGitManager:wn,closeGitManager:mn,openWorkflowSteps:Xt,closeWorkflowSteps:Vt,openAgents:Ft,closeAgents:Zt,openScripts:en,closeScripts:cn,runScript:we,openSetupWizard:De,closeSetupWizard:oe,openModelOnboarding:Pe,closeModelOnboarding:Ce,onPlanningTaskCreated:J,onPlanningTasksCreated:Ie,onSubtaskTasksCreated:de}}function pD(e){const[n,s]=i.useState(2),[a,r]=i.useState("."),[o,l]=i.useState(!0),[c,d]=i.useState(!1),[u,m]=i.useState(!1),[h,f]=i.useState(void 0),[p,g]=i.useState(!1),[x,v]=i.useState(!1),[b,y]=i.useState(!1),[j,C]=i.useState({}),[A,N]=i.useState(!1),[S,_]=i.useState(!1),[T,M]=i.useState(!1),[E,L]=i.useState(!1),[F,R]=i.useState(!1),[P,O]=i.useState(!0),q=i.useCallback(async()=>{const[w,H]=await Promise.allSettled([pw(e),El(e)]);if(w.status==="fulfilled"&&(s(w.value.maxConcurrent),r(w.value.rootDir)),H.status==="fulfilled"){const K=H.value;l(!!K.autoMerge),d(!!K.globalPause),m(!!K.enginePaused),v(!!K.prAuthAvailable),f(K.taskStuckTimeoutMs),g(K.showQuickChatFAB===!0),C(K.experimentalFeatures??{});const pe=K.experimentalFeatures??{};N(pe.insights===!0),_(pe.roadmap===!0),M(pe.memoryView===!0),L(pe.devServerView===!0||pe.devServer===!0),R(pe.todoView===!0);const le=K.autoReloadOnVersionChange!==!1;O(le),Wl(le)}y(!0)},[e]);i.useEffect(()=>{y(!1),C({}),N(!1),_(!1),M(!1),L(!1),R(!1),q()},[q]);const Z=i.useCallback(async()=>{const w=!o;l(w);try{await mo({autoMerge:w},e)}catch{l(!w)}},[o,e]),z=i.useCallback(async()=>{const w=!c;d(w);try{await mo({globalPause:w,globalPauseReason:w?"manual":void 0},e)}catch{d(!w)}},[c,e]),k=i.useCallback(async()=>{const w=!u;m(w);try{await mo({enginePaused:w},e)}catch{m(!w)}},[u,e]),I=i.useCallback(async()=>{const w=!p;g(w);try{await mo({showQuickChatFAB:w},e)}catch{g(!w)}},[p,e]),$=i.useCallback(async()=>{const w=!P;O(w),Wl(w);try{await _n({autoReloadOnVersionChange:w})}catch{O(!w),Wl(!w)}},[P]);return{maxConcurrent:n,rootDir:a,autoMerge:o,globalPaused:c,enginePaused:u,taskStuckTimeoutMs:h,showQuickChatFAB:p,prAuthAvailable:x,settingsLoaded:b,experimentalFeatures:j,insightsEnabled:A,roadmapEnabled:S,memoryEnabled:T,devServerEnabled:E,todosEnabled:F,autoReloadOnVersionChange:P,toggleAutoMerge:Z,toggleGlobalPause:z,toggleEnginePause:k,toggleShowQuickChatFAB:I,toggleAutoReloadOnVersionChange:$,refresh:q}}function fD(e){const{projectId:n,projects:s,projectsLoading:a,currentProject:r,setCurrentProject:o,addToast:l,openTaskDetail:c,closeTaskDetail:d}=e,u=i.useRef(!1),m=i.useRef(null);return i.useEffect(()=>{const f=new URLSearchParams(window.location.search),p=f.get("project"),g=f.get("task");if(!g||a)return;if(p){const v=s.find(b=>b.id===p);if(!v){l(`Project '${p}' not found`,"error");return}r?.id!==v.id&&o(v)}if(u.current)return;u.current=!0,Ia(g,p??n).then(v=>{c(v),m.current=g}).catch(()=>{l(`Task ${g} not found`,"error")})},[n,s,a,r,o,l,c]),{handleDetailClose:i.useCallback(()=>{if(m.current){const f=new URLSearchParams(window.location.search);f.delete("task");const p=f.toString();window.history.replaceState(null,"",p?`${window.location.pathname}?${p}`:window.location.pathname),m.current=null}d()},[d])}}function gD(){const[e,n]=i.useState([]),[s,a]=i.useState([]),[r,o]=i.useState([]),l=i.useRef(s),c=i.useRef(r);i.useEffect(()=>{Ms().then(m=>{n(m.models),l.current=m.favoriteProviders,c.current=m.favoriteModels,a(m.favoriteProviders),o(m.favoriteModels)}).catch(()=>{})},[]),i.useEffect(()=>{l.current=s},[s]),i.useEffect(()=>{c.current=r},[r]);const d=i.useCallback(async m=>{const h=l.current,p=h.includes(m)?h.filter(g=>g!==m):[m,...h];l.current=p,a(()=>p);try{await _n({favoriteProviders:p,favoriteModels:c.current})}catch(g){throw l.current=h,a(()=>h),g}},[]),u=i.useCallback(async m=>{const h=c.current,p=h.includes(m)?h.filter(g=>g!==m):[m,...h];c.current=p,o(()=>p);try{await _n({favoriteProviders:l.current,favoriteModels:p})}catch(g){throw c.current=h,o(()=>h),g}},[]);return{availableModels:e,favoriteProviders:s,favoriteModels:r,toggleFavoriteProvider:d,toggleFavoriteModel:u}}function bD({projectId:e,setupWizardOpen:n,openModelOnboarding:s,openSettings:a}){const r=i.useRef(!1),o=i.useRef(n);o.current=n,i.useEffect(()=>{if(n||!e||r.current)return;r.current=!0;let l=!1,c=!1;Dr().then(({providers:d})=>{const u=d.some(h=>h.authenticated);if(d.length>0&&!u||d.length>0&&u)return ca().then(h=>{const f=!!(h.defaultProvider&&h.defaultModelId);(h.modelOnboardingComplete===!1||h.modelOnboardingComplete===void 0)&&(!u||!f)&&!qa()?l=!0:!u&&!qa()&&(c=!0)})}).then(()=>{if(o.current){r.current=!1;return}l?(Gs("onboarding:auto-triggered",{trigger:"first-run"}),s()):c&&(Gs("onboarding:auto-triggered",{trigger:"missing-provider"}),a("authentication"))}).catch(()=>{})},[e,n,s,a])}const Bp="kb-update-banner-dismissed";function xD(){const[e,n]=i.useState(!0),[s,a]=i.useState(!1),[r,o]=i.useState(null),[l,c]=i.useState(null),[d,u]=i.useState(!1);i.useEffect(()=>{const h=sessionStorage.getItem(Bp)==="true";u(h);let f=!1;return fw().then(p=>{f||p.disabled||(a(p.updateAvailable===!0),o(typeof p.latestVersion=="string"?p.latestVersion:null),c(typeof p.currentVersion=="string"?p.currentVersion:null))}).catch(()=>{}).finally(()=>{f||n(!1)}),()=>{f=!0}},[]);const m=i.useCallback(()=>{u(!0),sessionStorage.setItem(Bp,"true")},[]);return{updateAvailable:s,latestVersion:r,currentVersion:l,loading:e,dismissed:d,dismiss:m}}const vD=["board","list","agents","missions","chat","documents","research","roadmaps","skills","mailbox","insights","memory","devserver","dev-server"];function yD(e){return e!==null&&vD.includes(e)}function wD(e){return e!==null&&/^plugin:[^:]+:.+$/u.test(e)}function Hp(e){return yD(e)||wD(e)}function kD(e){return e==="devserver"?"dev-server":e}function jD(e){const{projectsLoading:n,projectsError:s,currentProjectLoading:a,currentProject:r,projectsLength:o,setupWizardOpen:l,openSetupWizard:c,themeMode:d,setThemeMode:u}=e,[m,h]=i.useState(()=>{if(typeof window<"u"){const b=window.localStorage.getItem("kb-dashboard-view-mode");if(b==="overview"||b==="project")return b}return"overview"}),[f,p]=i.useState(()=>{const b=Zn("kb-dashboard-task-view");return Hp(b)?b:"board"}),g=i.useRef(!1);i.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",m)},[m]),i.useEffect(()=>{const b=Zn("kb-dashboard-task-view",r?.id);if(Hp(b)){const y=!g.current&&b==="devserver";p(y?"devserver":kD(b))}else p("board");r?.id&&(g.current=!0)},[r?.id]),i.useEffect(()=>{us("kb-dashboard-task-view",f,r?.id)},[r?.id,f]),i.useEffect(()=>{n||a||r&&m==="overview"&&h("project")},[n,a,r,m]),i.useEffect(()=>{if(n||a||l||s||o>0||r)return;const b=window.setTimeout(()=>{c()},500);return()=>window.clearTimeout(b)},[n,s,o,a,r,l,c]);const x=i.useCallback(b=>{p(b)},[]),v=i.useCallback(()=>{const b=["dark","light","system"],y=b.indexOf(d),j=b[(y+1)%b.length];u(j)},[d,u]);return{viewMode:m,setViewMode:h,taskView:f,setTaskView:p,handleChangeTaskView:x,handleToggleTheme:v}}const qp=new Map,ND=6e4;function SD(e){const[n,s]=i.useState([]),[a,r]=i.useState(!0),[o,l]=i.useState(null),c=i.useRef(!1);return i.useEffect(()=>{const d=e??"default";let u=!1;async function m(){const h=qp.get(d);if(h&&Date.now()<h.expiresAt){if(u)return;s(h.views),r(!1);return}c.current||r(!0),l(null);try{const f=await WN(e);if(u)return;qp.set(d,{views:f,expiresAt:Date.now()+ND}),s(f)}catch(f){if(u)return;l(f instanceof Error?f.message:"Failed to fetch plugin dashboard views")}finally{u||(r(!1),c.current=!0)}}return m(),()=>{u=!0}},[e]),i.useMemo(()=>({views:n,loading:a,error:o}),[n,a,o])}function CD({taskView:e,context:n}){const s=v1(e);if(!s)return null;const a=y1(s.pluginId,s.viewId);return a?t.jsx(a,{context:n}):t.jsx(t.Fragment,{children:w1({pluginId:s.pluginId,viewId:s.viewId})})}function ED(e){const{setCurrentProject:n,clearCurrentProject:s,setViewMode:a,currentProject:r,refreshProjects:o,toggleFavoriteProvider:l,toggleFavoriteModel:c,addToast:d,openSettings:u,openSetupWizard:m,closeSetupWizard:h,closeModelOnboarding:f}=e,p=i.useCallback(_=>{n(_),a("project")},[n,a]),g=i.useCallback(()=>{s(),a("overview")},[s,a]),x=i.useCallback(()=>{u()},[u]),v=i.useCallback(()=>{m()},[m]),b=i.useCallback(_=>{h(),n(_),a("project"),d(`Project ${_.name} registered successfully`,"success"),o()},[h,n,a,d,o]),y=i.useCallback(()=>{f()},[f]),j=i.useCallback(async _=>{try{await Nj(_.id),d(`Project ${_.name} paused`,"success"),await o()}catch{d(`Failed to pause project ${_.name}`,"error")}},[d,o]),C=i.useCallback(async _=>{try{await Sj(_.id),d(`Project ${_.name} resumed`,"success"),await o()}catch{d(`Failed to resume project ${_.name}`,"error")}},[d,o]),A=i.useCallback(async _=>{try{await pf(_.id),d(`Project ${_.name} removed`,"success"),r?.id===_.id&&(s(),a("overview")),await o()}catch{d(`Failed to remove project ${_.name}`,"error")}},[r,s,a,d,o]),N=i.useCallback(async _=>{try{await l(_)}catch{d("Failed to update favorites","error")}},[l,d]),S=i.useCallback(async _=>{try{await c(_)}catch{d("Failed to update model favorites","error")}},[c,d]);return{handleSelectProject:p,handleViewAllProjects:g,handleOpenSettings:x,handleAddProject:v,handleSetupComplete:b,handleModelOnboardingComplete:y,handlePauseProject:j,handleResumeProject:C,handleRemoveProject:A,handleToggleFavorite:N,handleToggleModelFavorite:S}}function MD(e){const{createTask:n,ingestCreatedTasks:s,onPlanningTaskCreated:a,onPlanningTasksCreated:r,onSubtaskTasksCreated:o,addToast:l}=e,c=i.useCallback(async p=>n({...p,column:"triage",source:{sourceType:"dashboard_ui"}}),[n]),d=i.useCallback(async p=>await n({...p,column:"triage",source:{sourceType:"dashboard_ui"}}),[n]),u=i.useCallback(p=>{s([p]),a(p,l)},[l,s,a]),m=i.useCallback(p=>{s(p),r(p,l)},[l,s,r]),h=i.useCallback(p=>{s(p),o(p,l)},[l,s,o]),f=i.useCallback(p=>{l(`Imported ${p.id} from GitHub`,"success")},[l]);return{handleBoardQuickCreate:c,handleModalCreate:d,handlePlanningTaskCreated:u,handlePlanningTasksCreated:m,handleSubtaskTasksCreated:h,handleGitHubImport:f}}async function _D(e){return Ml("/health",{nodeId:e})}async function AD(e){return Ml("/projects",{nodeId:e})}async function PD(e,n,s){const a=new URLSearchParams({projectId:n});return s&&s.trim()&&a.set("q",s.trim()),Ml(`/tasks?${a.toString()}`,{nodeId:e})}async function RD(e,n){return Ml(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:e})}async function Jz(e){return D(`/nodes/${encodeURIComponent(e)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function Yz(e){return D(`/nodes/${encodeURIComponent(e)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function Qz(e){return D(`/nodes/${encodeURIComponent(e)}/settings/sync-status`)}async function Xz(e){return D(`/nodes/${encodeURIComponent(e)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}function TD(e,n){const{projectId:s,searchQuery:a}=n??{},[r,o]=i.useState([]),[l,c]=i.useState([]),[d,u]=i.useState(null),[m,h]=i.useState(!1),[f,p]=i.useState(null),g=i.useRef(null),x=i.useCallback(async()=>{if(!e){o([]),c([]),u(null),h(!1),p(null);return}g.current?.abort();const b=new AbortController;g.current=b,h(!0),p(null);try{const y=[_D(e),AD(e)];s&&(y.push(PD(e,s,a)),y.push(RD(e,s)));const j=await Promise.allSettled(y);if(b.signal.aborted)return;const C=j[0],A=j[1];if(C.status==="rejected"){p(`Failed to fetch node health: ${C.reason}`),h(!1);return}if(u(C.value),A.status==="rejected"){p(`Failed to fetch projects: ${A.reason}`),h(!1);return}if(o(A.value),s&&j[2]){const N=j[2];if(N.status==="rejected"){p(`Failed to fetch tasks: ${N.reason}`),h(!1);return}N.status==="fulfilled"&&c(N.value)}h(!1)}catch(y){b.signal.aborted||(p(y instanceof Error?y.message:"Unknown error"),h(!1))}},[e,s,a]);i.useEffect(()=>(x(),()=>{g.current?.abort()}),[x]);const v=i.useCallback(()=>{x()},[x]);return{projects:r,tasks:l,health:d,loading:m,error:f,refresh:v}}function ID(e){const[n,s]=i.useState(!1),[a,r]=i.useState(null);return i.useEffect(()=>{if(!e){s(!1),r(null);return}const o=`/api/proxy/${encodeURIComponent(e)}/events`;return li(o,{events:{"task:created":l=>{r({type:"task:created",data:l.data})},"task:moved":l=>{r({type:"task:moved",data:l.data})},"task:updated":l=>{r({type:"task:updated",data:l.data})},"task:deleted":l=>{r({type:"task:deleted",data:l.data})},"task:merged":l=>{r({type:"task:merged",data:l.data})}},onOpen:()=>s(!0),onError:()=>s(!1)})},[e]),{isConnected:n,lastEvent:a}}const $D="fusion-dashboard-current-node",Ib=i.createContext(null);function DD({children:e}){const[n,s]=i.useState(null),[a,r]=i.useState(!0),o=i.useRef(!1),l=i.useRef(void 0);i.useEffect(()=>{let m=!1;async function h(){try{const f=await ca();if(m)return;l.current=f.dashboardCurrentNodeId;const p=f.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const g=localStorage.getItem($D);if(g){const x=JSON.parse(g);x?.id&&x?.type==="remote"&&(l.current=x.id,await _n({dashboardCurrentNodeId:x.id}).catch(()=>{}))}}catch{}}catch{}finally{m||r(!1)}}return h(),()=>{m=!0}},[]),i.useEffect(()=>{if(!a)if(n&&n.type==="remote"&&n.id){const m=n.id;l.current!==m&&(l.current=m,_n({dashboardCurrentNodeId:m}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,_n({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,a]);const c=i.useCallback(m=>{s(m)},[]),d=i.useCallback(()=>{s(null),l.current=void 0,_n({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),u={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:d};return t.jsx(Ib.Provider,{value:u,children:e})}function LD(){const e=i.useContext(Ib);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}function OD({open:e}){const[n,s]=i.useState(""),a=i.useRef(null);i.useEffect(()=>{e&&a.current?.focus()},[e]);const r=i.useCallback(()=>{const l=n.trim();l&&(Hy(l),window.location.reload())},[n]),o=i.useCallback(()=>{qy(),window.location.reload()},[]);return e?t.jsx("div",{className:"modal-overlay open auth-token-recovery-overlay",role:"presentation",onKeyDownCapture:l=>{l.key==="Escape"&&(l.preventDefault(),l.stopPropagation())},children:t.jsxs("div",{className:"modal modal-md",role:"dialog","aria-modal":"true","aria-labelledby":"auth-token-recovery-title","aria-describedby":"auth-token-recovery-description",children:[t.jsx("div",{className:"modal-header auth-token-recovery-header",children:t.jsx("h3",{id:"auth-token-recovery-title",children:"Authentication token required"})}),t.jsxs("div",{className:"auth-token-recovery-content",children:[t.jsx("p",{id:"auth-token-recovery-description",children:"This dashboard session can't authenticate with the daemon. Set a replacement token or clear the current token and retry."}),t.jsxs("div",{className:"auth-token-recovery-field",children:[t.jsx("label",{htmlFor:"auth-token-recovery-input",children:"Replacement token"}),t.jsx("input",{ref:a,id:"auth-token-recovery-input",className:"input",type:"password",value:n,onChange:l=>s(l.target.value),placeholder:"Paste token",autoComplete:"off",spellCheck:!1})]})]}),t.jsxs("div",{className:"modal-actions auth-token-recovery-actions",children:[t.jsx("button",{type:"button",className:"btn",onClick:o,children:"Clear token and retry"}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:r,disabled:n.trim().length===0,children:"Set token and reload"})]})]})}):null}const zD=200,FD=i.lazy(()=>Mn(()=>import("./AgentsView-BmemrfrO.js"),__vite__mapDeps([19,1,0,2,3,20,11,4,5,21])).then(e=>({default:e.AgentsView}))),UD=i.lazy(()=>Mn(()=>import("./DocumentsView-DO48ivSq.js"),__vite__mapDeps([22,1,4,5,23])).then(e=>({default:e.DocumentsView}))),BD=i.lazy(()=>Mn(()=>import("./InsightsView-CAngTfMf.js"),__vite__mapDeps([24,1,17,4,5,25])).then(e=>({default:e.InsightsView}))),HD=i.lazy(()=>Mn(()=>import("./ResearchView-Dfdsuc21.js"),__vite__mapDeps([26,1,4,5,27])).then(e=>({default:e.ResearchView}))),qD=i.lazy(()=>Mn(()=>import("./NodesView-BnV1LWa8.js"),__vite__mapDeps([28,1,20,4,5,29])).then(e=>({default:e.NodesView}))),VD=i.lazy(()=>Mn(()=>import("./ChatView-CZQUBFlV.js"),__vite__mapDeps([30,1,4,5])).then(e=>({default:e.ChatView}))),WD=i.lazy(()=>Mn(()=>import("./RoadmapsView-BiIpE-b8.js"),__vite__mapDeps([31,1,4,5,32])).then(e=>({default:e.RoadmapsView}))),KD=i.lazy(()=>Mn(()=>import("./SkillsView-C1196wgA.js"),__vite__mapDeps([33,1,4,5,34])).then(e=>({default:e.SkillsView}))),GD=i.lazy(()=>Mn(()=>import("./MemoryView-B3rNcAOW.js"),__vite__mapDeps([35,1,15,16,4,5,36])).then(e=>({default:e.MemoryView}))),JD=i.lazy(()=>Mn(()=>import("./DevServerView-C3Q0XqDA.js"),__vite__mapDeps([37,1,4,5,38])).then(e=>({default:e.DevServerView})));i.lazy(()=>Mn(()=>Promise.resolve().then(()=>lb),void 0).then(e=>({default:e.TodoView})));function YD(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{Mn(()=>import("./AgentsView-BmemrfrO.js"),__vite__mapDeps([19,1,0,2,3,20,11,4,5,21])),Mn(()=>import("./DocumentsView-DO48ivSq.js"),__vite__mapDeps([22,1,4,5,23])),Mn(()=>import("./InsightsView-CAngTfMf.js"),__vite__mapDeps([24,1,17,4,5,25])),Mn(()=>import("./ResearchView-Dfdsuc21.js"),__vite__mapDeps([26,1,4,5,27])),Mn(()=>import("./NodesView-BnV1LWa8.js"),__vite__mapDeps([28,1,20,4,5,29])),Mn(()=>import("./ChatView-CZQUBFlV.js"),__vite__mapDeps([30,1,4,5])),Mn(()=>import("./RoadmapsView-BiIpE-b8.js"),__vite__mapDeps([31,1,4,5,32])),Mn(()=>import("./SkillsView-C1196wgA.js"),__vite__mapDeps([33,1,4,5,34])),Mn(()=>import("./MemoryView-B3rNcAOW.js"),__vite__mapDeps([35,1,15,16,4,5,36])),Mn(()=>import("./DevServerView-C3Q0XqDA.js"),__vite__mapDeps([37,1,4,5,38])),Mn(()=>Promise.resolve().then(()=>lb),void 0)})}const ed="kb-setup-warning-dismissed";function QD(){const{toasts:e,addToast:n,removeToast:s}=aD(),a=typeof window<"u"&&!!window.electronAPI;i.useEffect(()=>{YD()},[]);const{projects:r,loading:o,error:l,refresh:c}=eD(),{nodes:d}=Al(),{currentNode:u,currentNodeId:m,isRemote:h,setCurrentNode:f,clearCurrentNode:p}=LD(),{currentProject:g,setCurrentProject:x,clearCurrentProject:v,loading:b}=sD(r,{nodeId:m}),{hasAiProvider:y,hasGithub:j,loading:C,hasWarnings:A}=gb(g?.id),{updateAvailable:N,latestVersion:S,currentVersion:_,dismissed:T,dismiss:M}=xD();i.useEffect(()=>{if(m&&!u&&d.length>0){const Be=d.find(It=>It.id===m);if(Be){f(Be);return}}m&&d.length>0&&(d.some(It=>It.id===m)||p())},[m,u,d,f,p]);const[E,L]=i.useState(""),F=TD(m,{projectId:g?.id,searchQuery:E||void 0});ID(m);const R=h&&F.projects.length>0?F.projects:r,{themeMode:P,colorTheme:O,dashboardFontScalePct:q,setThemeMode:Z,setColorTheme:z,setDashboardFontScalePct:k}=mD(),{sessions:I,generating:$,needsInput:w,planningSessions:H,dismissSession:K}=W$(g?.id),pe=I.filter(Be=>Be.status==="awaiting_input"||Be.status==="error"),le=J$(),B=hD({projectId:g?.id,planningSessions:H}),{viewMode:ye,setViewMode:U,taskView:te,handleChangeTaskView:ne}=jD({projectsLoading:o,projectsError:l,currentProjectLoading:b,currentProject:g,projectsLength:r.length,setupWizardOpen:B.setupWizardOpen,openSetupWizard:B.openSetupWizard,themeMode:P,setThemeMode:Z}),{views:ee}=SD(g?.id),ie=i.useCallback(Be=>{Be==="missions"&&(zt(void 0),jt(void 0),Bt(void 0)),ne(Be)},[ne]),ge=te==="board"||te==="list",{tasks:se,createTask:Ae,moveTask:xe,pauseTask:Se,deleteTask:qe,mergeTask:We,retryTask:Qe,resetTask:ve,updateTask:Oe,duplicateTask:ae,archiveTask:re,unarchiveTask:je,archiveAllDone:Q,loadArchivedTasks:Fe,ingestCreatedTasks:Je,lastFetchTimeMs:be}=Q$({...g?{projectId:g.id}:{},searchQuery:E||void 0,sseEnabled:ge}),[ze,tt]=i.useState(!1),[kt,ke]=i.useState(0),ce=i.useRef(performance.now()),Te=i.useRef(!1),he=i.useRef(!1),Le=i.useMemo(()=>o?"projects":b?"project":"tasks",[o,b]);i.useEffect(()=>{if(!o&&!Te.current){Te.current=!0;const Be=`projects loaded at ${Math.round(performance.now()-ce.current)}ms from mount`;console.log(`[App] ${Be}`),Er("[App]",Be)}if(!b&&!he.current){he.current=!0;const Be=`current-project resolved at ${Math.round(performance.now()-ce.current)}ms from mount`;console.log(`[App] ${Be}`),Er("[App]",Be)}},[o,b]),i.useEffect(()=>{if(ze||o||b)return;const Be=performance.now(),It=window.setTimeout(()=>{const Gt=`dashboard ready at ${Math.round(performance.now()-ce.current)}ms from mount (settle delay=${Math.round(performance.now()-Be)}ms)`;console.log(`[App] ${Gt}`),Er("[App]",Gt),tt(!0)},zD);return()=>{window.clearTimeout(It)}},[ze,o,b]);const it=Pi()==="mobile",{keyboardOpen:lt}=Ol({enabled:it}),$e=it&&lt&&!B.anyModalOpen,[Ue,Xe]=i.useState(0),wt=i.useCallback(()=>{vf(g?.id).then(Be=>{Xe(Be.unreadCount)}).catch(Be=>{console.warn("[App] Failed to fetch mailbox unread count:",Be)})},[g?.id]);i.useEffect(()=>{wt();const Be=new URLSearchParams;g?.id&&Be.set("projectId",g.id);const It=Be.size>0?`?${Be.toString()}`:"";return li(`/api/events${It}`,{events:{"message:sent":wt,"message:received":wt,"message:read":wt,"message:deleted":wt}})},[g?.id,wt]);const[Re,xt]=i.useState(!1),[Pt,Ct]=i.useState(!1),[Ot,zt]=i.useState(void 0),[Nt,jt]=i.useState(void 0),[Yt,Bt]=i.useState(void 0),[qt,wn]=i.useState(!1),[mn,Xt]=i.useState(!1),[Vt,Ft]=i.useState(()=>Zn(ed,g?.id)==="true");i.useEffect(()=>{Ft(Zn(ed,g?.id)==="true")},[g?.id]),i.useEffect(()=>{const Be=()=>{Xt(!0)};return window.addEventListener(md,Be),()=>{window.removeEventListener(md,Be)}},[]);const Zt=i.useCallback(()=>{us(ed,"true",g?.id),Ft(!0)},[g?.id]),{maxConcurrent:en,autoMerge:cn,globalPaused:we,enginePaused:De,taskStuckTimeoutMs:oe,showQuickChatFAB:Pe,prAuthAvailable:Ce,settingsLoaded:J,experimentalFeatures:Ie,insightsEnabled:de,roadmapEnabled:Ne,memoryEnabled:Ye,devServerEnabled:ft,todosEnabled:tn,toggleAutoMerge:$t,toggleGlobalPause:Rt,toggleEnginePause:Dt,refresh:En}=pD(g?.id),bn=Ie.skillsView===!0,Nn=Ie.nodesView===!0,dn=Ie.researchView===!0,xn=Ie.agentOnboarding===!0,rn=!0;i.useEffect(()=>{J&&(te==="skills"&&!bn&&ne("board"),te==="insights"&&!de&&ne("board"),te==="roadmaps"&&!Ne&&ne("board"),te==="memory"&&!Ye&&ne("board"),(te==="devserver"||te==="dev-server")&&!ft&&ne("board"),te==="research"&&!dn&&ne("board"))},[te,J,bn,de,Ne,ne,rn,Ye,ft,dn]),i.useEffect(()=>{Re&&!Nn&&xt(!1)},[Re,Nn]);const{availableModels:On,favoriteProviders:fe,favoriteModels:ct,toggleFavoriteProvider:hn,toggleFavoriteModel:zn}=gD();bD({projectId:g?.id,setupWizardOpen:B.setupWizardOpen,openModelOnboarding:B.openModelOnboarding,openSettings:B.openSettings});const{handleSelectProject:ue,handleViewAllProjects:ut,handleOpenSettings:yt,handleAddProject:dt,handleSetupComplete:at,handleModelOnboardingComplete:vt,handlePauseProject:Ht,handleResumeProject:Ut,handleRemoveProject:An,handleToggleFavorite:Wt,handleToggleModelFavorite:Tt}=ED({setCurrentProject:x,clearCurrentProject:v,setViewMode:U,currentProject:g,refreshProjects:c,toggleFavoriteProvider:hn,toggleFavoriteModel:zn,addToast:n,openSettings:B.openSettings,openSetupWizard:B.openSetupWizard,closeSetupWizard:B.closeSetupWizard,closeModelOnboarding:B.closeModelOnboarding}),{handleDetailClose:G}=fD({projectId:g?.id,projects:r,projectsLoading:o,currentProject:g,setCurrentProject:x,addToast:n,openTaskDetail:B.openDetailTask,closeTaskDetail:B.closeDetailTask}),He=i.useCallback(async({insightId:Be,title:It,description:Gt})=>{await Ae({title:It,description:Gt,column:"triage",source:{sourceType:"dashboard_ui",sourceMetadata:{origin:"insights",insightId:Be}}})},[Ae]),{handleBoardQuickCreate:mt,handleModalCreate:ht,handlePlanningTaskCreated:Et,handlePlanningTasksCreated:St,handleSubtaskTasksCreated:sn,handleGitHubImport:nn}=MD({createTask:Ae,ingestCreatedTasks:Je,onPlanningTaskCreated:B.onPlanningTaskCreated,onPlanningTasksCreated:B.onPlanningTasksCreated,onSubtaskTasksCreated:B.onSubtaskTasksCreated,addToast:n}),as=i.useCallback((Be,It)=>{if(It==="changes"){B.openDetailWithChangesTab(Be);return}B.openDetailTask(Be,It)},[B]),Is=i.useCallback(async Be=>{try{const It=await Ia(Be,g?.id);B.openDetailTask(It,"logs")}catch(It){n(`Failed to open task logs: ${It.message}`,"error")}},[B,g?.id,n]),[_s,ls]=i.useState([]);i.useEffect(()=>{let Be=!1;return Yr(g?.id).then(It=>{Be||ls(It)}).catch(()=>{Be||ls([])}),()=>{Be=!0}},[g?.id]);const Xs=i.useMemo(()=>new Map(_s.map(Be=>[Be.id,Be.name])),[_s]),ci=i.useCallback(()=>{Nn&&xt(Be=>!Be)},[Nn]),pn=i.useCallback(()=>{B.setFileWorkspace("project"),B.openFiles()},[B]),me=i.useCallback(async()=>{Ct(!0);try{await c()}finally{Ct(!1)}},[c]),Ve=i.useCallback(Be=>{jt(Be),zt(void 0),ne("missions")},[ne]),ot=i.useCallback(Be=>{Be.type==="planning"?B.openPlanningWithSession(Be.id):Be.type==="subtask"?B.openSubtaskWithSession(Be.id):Be.type==="mission_interview"?(jt(void 0),zt(Be.id),Bt(void 0),ne("missions")):(Be.type==="milestone_interview"||Be.type==="slice_interview")&&(zt(void 0),jt(void 0),Bt(Be.id),ne("missions"))},[ne,B]),on=i.useCallback(()=>{},[]),Un=i.useCallback(()=>{},[]),X=!o&&!b&&r.length===0&&!g&&!!l,Me=()=>X?t.jsx(t$,{errorMessage:l??"Failed to fetch projects",isRetrying:Pt,onRetry:me}):Re?t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(vs,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(qD,{addToast:n,onClose:()=>xt(!1)})})})}):ye==="overview"?t.jsx(vs,{children:t.jsx(KP,{projects:r,loading:o,onSelectProject:ue,onAddProject:dt,onPauseProject:Ht,onResumeProject:Ut,onRemoveProject:An,nodes:d})}):te.startsWith("plugin:")?t.jsx(vs,{children:t.jsx(CD,{taskView:te,context:{projectId:g?.id,tasks:h&&F.tasks.length>0?F.tasks:se,workflowSteps:_s,openTaskDetail:(Be,It)=>B.openDetailTask(Be,It),renderTaskCard:Be=>t.jsx(Or,{task:Be,projectId:g?.id,onOpenDetail:It=>B.openDetailTask(It),addToast:n,workflowStepNameLookup:Xs})}})}):te==="skills"?!J||!bn?null:t.jsx(vs,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(KD,{addToast:n,projectId:g?.id,onClose:()=>ne("board")})})}):te==="chat"?t.jsx(vs,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(VD,{addToast:n,projectId:g?.id})})}):te==="mailbox"?t.jsx(vs,{children:t.jsx(PR,{projectId:g?.id,addToast:n,onUnreadCountChange:Xe})}):te==="roadmaps"?!J||!Ne?null:t.jsx(vs,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(WD,{addToast:n,projectId:g?.id})})}):te==="missions"?t.jsx(vs,{children:t.jsx(ER,{isInline:!0,isOpen:!0,onClose:()=>{jt(void 0),zt(void 0),Bt(void 0),ne("board")},addToast:n,projectId:g?.id,onSelectTask:Be=>{const It=se.find(Gt=>Gt.id===Be);It&&B.openDetailTask(It)},availableTasks:se.map(Be=>({id:Be.id,title:Be.title})),resumeSessionId:Ot,targetMissionId:Nt,milestoneSliceResumeSessionId:Yt,onMilestoneSliceResumeFetchError:()=>Bt(void 0)})}):te==="agents"&&rn?t.jsx(vs,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(FD,{addToast:n,projectId:g?.id,onOpenTaskLogs:Is,agentOnboardingEnabled:xn})})}):te==="documents"?t.jsx(vs,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(UD,{projectId:g?.id,addToast:n,onOpenDetail:B.openDetailTask})})}):te==="insights"?!J||!de?null:t.jsx(vs,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(BD,{projectId:g?.id,addToast:n,onClose:()=>ne("board"),onCreateTask:He})})}):te==="research"?!J||!dn?null:t.jsx(vs,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(HD,{projectId:g?.id,addToast:n,onOpenSettings:Be=>B.openSettings(Be),readinessVersion:kt})})}):te==="memory"?!J||!Ye?null:t.jsx(vs,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(GD,{addToast:n,projectId:g?.id})})}):te==="devserver"||te==="dev-server"?!J||!ft?null:t.jsx(vs,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(JD,{addToast:n,projectId:g?.id})})}):te==="board"?t.jsx(vs,{children:t.jsx(ZS,{tasks:h&&F.tasks.length>0?F.tasks:se,projectId:g?.id,maxConcurrent:en,onMoveTask:xe,onPauseTask:Se,onOpenDetail:B.openDetailTask,addToast:n,onQuickCreate:mt,onNewTask:B.openNewTask,onPlanningMode:B.openPlanningWithInitialPlan,onSubtaskBreakdown:B.openSubtaskBreakdown,autoMerge:cn,onToggleAutoMerge:$t,globalPaused:we,onUpdateTask:Oe,onRetryTask:Qe,onArchiveTask:re,onUnarchiveTask:je,onDeleteTask:qe,onArchiveAllDone:Q,onLoadArchivedTasks:Fe,searchQuery:E,availableModels:On,onOpenDetailWithTab:as,favoriteProviders:fe,favoriteModels:ct,onToggleFavorite:Wt,onToggleModelFavorite:Tt,taskStuckTimeoutMs:oe,onOpenMission:Ve,lastFetchTimeMs:be})}):t.jsx(vs,{children:t.jsx(LP,{tasks:h&&F.tasks.length>0?F.tasks:se,projectId:g?.id,onMoveTask:xe,onRetryTask:Qe,onDeleteTask:qe,onMergeTask:We,onResetTask:ve,onDuplicateTask:ae,onOpenDetail:(Be,It)=>B.openDetailTask(Be,void 0,It),addToast:n,globalPaused:we,onNewTask:B.openNewTask,onQuickCreate:mt,onPlanningMode:B.openPlanningWithInitialPlan,onSubtaskBreakdown:B.openSubtaskBreakdown,availableModels:On,favoriteProviders:fe,favoriteModels:ct,onToggleFavorite:Wt,onToggleModelFavorite:Tt,taskStuckTimeoutMs:oe,searchQuery:E,lastFetchTimeMs:be,prAuthAvailable:Ce})});if(!ze)return t.jsxs(t.Fragment,{children:[t.jsx(s$,{stage:Le}),t.jsx(kb,{toasts:e,onRemove:s})]});const rt=!B.modelOnboardingOpen&&S4(),Mt=!B.modelOnboardingOpen&&!rt&&qa()&&!xb();return t.jsxs(t.Fragment,{children:[t.jsx(S1,{isElectron:a,onOpenSettings:yt,onOpenGitHubImport:B.openGitHubImport,onOpenPlanning:B.openPlanning,onResumePlanning:B.resumePlanning,activePlanningSessionCount:H.length,onOpenUsage:B.openUsage,onOpenActivityLog:B.openActivityLog,onOpenSystemStats:B.openSystemStats,onOpenMailbox:()=>ie("mailbox"),mailboxUnreadCount:Ue,onOpenSchedules:B.openSchedules,onOpenGitManager:B.openGitManager,onOpenNodes:ci,showNodesButton:Nn,onOpenWorkflowSteps:B.openWorkflowSteps,onOpenScripts:B.openScripts,onRunScript:B.runScript,onToggleTerminal:B.toggleTerminal,onOpenFiles:B.openFiles,filesOpen:B.filesOpen,onOpenTodos:B.openTodos,todosOpen:B.todosOpen,todosEnabled:tn,globalPaused:we,enginePaused:De,onToggleGlobalPause:Rt,onToggleEnginePause:Dt,view:te,onChangeView:ye==="project"&&g?ie:void 0,showSkillsTab:bn,showAgentsTab:rn,searchQuery:E,onSearchChange:L,projects:R,currentProject:g,onSelectProject:ue,onViewAllProjects:ut,projectId:g?.id,mobileNavEnabled:it,availableNodes:d,currentNode:u,onSelectNode:Be=>{Be===null?p():f(Be)},isRemote:h,experimentalFeatures:{insights:de,roadmap:Ne,memoryView:Ye,devServer:ft,devServerView:ft,researchView:dn},pluginDashboardViews:ee}),ye==="project"&&g&&!Re&&te!=="missions"&&!B.isPlanningOpen&&!le&&t.jsx(x$,{sessions:pe,onResumeSession:ot,onDismissSession:on,onDismissAll:Un}),ye==="project"&&g&&t.jsx(w$,{onOpenSettings:()=>B.openSettings("general")}),ye==="project"&&g&&rt&&t.jsx(j$,{onResume:B.openModelOnboarding}),ye==="project"&&g&&Mt&&t.jsx(N$,{onOpenModelOnboarding:B.openModelOnboarding,onOpenSettings:Be=>B.openSettings(Be)}),ye==="project"&&g&&N&&S&&_&&!T&&t.jsx(k$,{latestVersion:S,currentVersion:_,onDismiss:M}),ye==="project"&&g&&!C&&A&&!Vt&&t.jsx(bb,{hasAiProvider:y,hasGithub:j,onDismiss:Zt}),t.jsx("div",{className:`project-content${ye==="project"&&g?" project-content--with-footer":""}${it&&!$e?" project-content--with-mobile-nav":""}`,children:Me()}),ye==="project"&&g&&!Re&&t.jsx(h$,{tasks:h&&F.tasks.length>0?F.tasks:se,projectId:g.id,taskStuckTimeoutMs:oe,backgroundSessions:I,backgroundGenerating:$,backgroundNeedsInput:w,onOpenBackgroundSession:ot,onDismissBackgroundSession:K,lastFetchTimeMs:be,currentProjectPath:g.path,onOpenProjectDirectory:pn}),t.jsx(C$,{view:te,onChangeView:ye==="project"&&g?ie:()=>{},footerVisible:ye==="project"&&!!g,modalOpen:B.anyModalOpen,keyboardOpen:$e,onOpenSettings:yt,onOpenActivityLog:B.openActivityLog,onOpenSystemStats:B.openSystemStats,onOpenMailbox:()=>ie("mailbox"),onOpenNodes:ci,mailboxUnreadCount:Ue,onOpenGitManager:B.openGitManager,onOpenWorkflowSteps:B.openWorkflowSteps,onOpenSchedules:B.openSchedules,onOpenScripts:B.openScripts,onToggleTerminal:B.toggleTerminal,onOpenFiles:B.openFiles,onOpenTodos:B.openTodos,todosOpen:B.todosOpen,onOpenGitHubImport:B.openGitHubImport,onOpenPlanning:B.openPlanning,onResumePlanning:B.resumePlanning,activePlanningSessionCount:H.length,onOpenUsage:()=>B.openUsage(null),onViewAllProjects:ut,onRunScript:B.runScript,projectId:g?.id,showSkillsTab:bn,experimentalFeatures:{insights:de,roadmap:Ne,memoryView:Ye,devServer:ft,devServerView:ft,todoView:tn,researchView:dn,nodesView:Nn},pluginDashboardViews:ee}),ye==="project"&&g&&te!=="chat"&&te!=="mailbox"&&te!=="insights"&&te!=="devserver"&&te!=="dev-server"&&!te.startsWith("plugin:")&&t.jsx(V$,{projectId:g.id,addToast:n,showFAB:Pe,open:qt,onOpenChange:wn,favoriteProviders:fe,favoriteModels:ct,onToggleFavorite:Wt,onToggleModelFavorite:Tt}),t.jsx(e$,{projectId:g?.id,tasks:se,projects:r,currentProject:g,addToast:n,toasts:e,removeToast:s,modalManager:B,projectActions:{handleAddProject:dt,handleSetupComplete:at,handleModelOnboardingComplete:vt},taskHandlers:{handleModalCreate:ht,handlePlanningTaskCreated:Et,handlePlanningTasksCreated:St,handleSubtaskTasksCreated:sn,handleGitHubImport:nn},taskOperations:{moveTask:xe,deleteTask:qe,mergeTask:We,retryTask:Qe,resetTask:ve,duplicateTask:ae},deepLink:{handleDetailClose:G},settings:{prAuthAvailable:Ce,themeMode:P,colorTheme:O,dashboardFontScalePct:q,setThemeMode:Z,setColorTheme:z,setDashboardFontScalePct:k},onSettingsClose:()=>{B.closeSettings(),ke(Be=>Be+1),En()},onReopenOnboarding:()=>{B.closeSettings(),B.openModelOnboarding()}}),t.jsx(OD,{open:mn})]})}function XD(){return t.jsx(iD,{children:t.jsx(DD,{children:t.jsx(z1,{children:t.jsx(QD,{})})})})}function $b(e){e.postMessage({type:"SKIP_WAITING"})}function Vp(e){e.addEventListener("statechange",()=>{e.state==="installed"&&navigator.serviceWorker.controller&&$b(e)})}function ZD(){if(!("serviceWorker"in navigator))return;let e=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{e||(e=!0,Hd("service worker activated new version"))}),navigator.serviceWorker.register("/sw.js").then(n=>{console.log("SW registered:",n.scope),n.waiting&&navigator.serviceWorker.controller&&$b(n.waiting),n.installing&&Vp(n.installing),n.addEventListener("updatefound",()=>{const s=n.installing;s&&Vp(s)})}).catch(n=>{console.log("SW registration failed:",n)})}Qy();Dy();Db.createRoot(document.getElementById("root")).render(t.jsx(i.StrictMode,{children:t.jsx(Ly,{children:t.jsx(XD,{})})}));ZD();export{bl as $,Fs as A,Rn as B,Ln as C,El as D,mo as E,Fi as F,vl as G,_e as H,D1 as I,CO as J,od as K,gt as L,Sn as M,Bv as N,Yo as O,qn as P,Kz as Q,ns as R,Ci as S,Sl as T,Kc as U,Hn as V,ii as W,Jt as X,Cn as Y,Xn as Z,n4 as _,un as a,Ol as a$,l4 as a0,mj as a1,t4 as a2,hj as a3,jO as a4,pj as a5,Mn as a6,OL as a7,zL as a8,vk as a9,ew as aA,Dr as aB,Qz as aC,Jz as aD,Yz as aE,Xz as aF,Ir as aG,dy as aH,Cr as aI,Os as aJ,ty as aK,_x as aL,xs as aM,sf as aN,LO as aO,OO as aP,Al as aQ,eD as aR,Ju as aS,Ql as aT,La as aU,JN as aV,Cz as aW,Ez as aX,QN as aY,XN as aZ,T$ as a_,Ud as aa,Va as ab,la as ac,vi as ad,yi as ae,ri as af,Mz as ag,Pz as ah,Az as ai,_z as aj,Rz as ak,ms as al,Rs as am,wy as an,oi as ao,Ix as ap,Br as aq,_i as ar,Tz as as,$z as at,Fz as au,zz as av,Oz as aw,Lz as ax,Dz as ay,Iz as az,Tn as b,Nl as b$,KN as b0,tf as b1,E$ as b2,P$ as b3,Xi as b4,Xp as b5,Su as b6,Ei as b7,BO as b8,qO as b9,_L as bA,SL as bB,kL as bC,jL as bD,NL as bE,wL as bF,yL as bG,fL as bH,CL as bI,zT as bJ,aO as bK,iO as bL,uO as bM,sO as bN,rO as bO,oO as bP,lO as bQ,cO as bR,Hk as bS,dO as bT,Vd as bU,Fk as bV,Uk as bW,Bk as bX,zk as bY,nO as bZ,Kr as b_,HO as ba,VO as bb,WO as bc,KO as bd,GO as be,JO as bf,YO as bg,QO as bh,XO as bi,ZO as bj,ez as bk,tz as bl,sz as bm,iz as bn,nz as bo,Yn as bp,wl as bq,ta as br,Nz as bs,jz as bt,Sz as bu,xL as bv,bL as bw,gL as bx,vL as by,ML as bz,et as c,cL as c$,ly as c0,Ra as c1,Ta as c2,yj as c3,Hy as c4,qy as c5,Mw as c6,_w as c7,vz as c8,UL as c9,iL as cA,rL as cB,pL as cC,hL as cD,Ww as cE,Dw as cF,xi as cG,Ow as cH,Lw as cI,zw as cJ,Fw as cK,TL as cL,IO as cM,$O as cN,DO as cO,Ri as cP,Bz as cQ,Hz as cR,UO as cS,oL as cT,nd as cU,os as cV,LT as cW,d4 as cX,m4 as cY,Oi as cZ,Gc as c_,FL as ca,yz as cb,BL as cc,YL as cd,KL as ce,HL as cf,GL as cg,qL as ch,JL as ci,VL as cj,WL as ck,Zb as cl,Tw as cm,QL as cn,Iw as co,XL as cp,Js as cq,wi as cr,J$ as cs,ST as ct,AL as cu,FO as cv,nL as cw,sL as cx,jp as cy,TO as cz,RO as d,$L as d$,aL as d0,dL as d1,lL as d2,uL as d3,mL as d4,ia as d5,Gz as d6,R1 as d7,_l as d8,qz as d9,xO as dA,bO as dB,e4 as dC,NO as dD,DA as dE,fO as dF,pO as dG,yk as dH,gO as dI,vO as dJ,hz as dK,hO as dL,pz as dM,Zv as dN,cd as dO,wz as dP,bz as dQ,gz as dR,xz as dS,fz as dT,zO as dU,Uz as dV,IL as dW,PL as dX,RL as dY,DL as dZ,LL as d_,wh as da,Vz as db,Wz as dc,EL as dd,az as de,oz as df,dz as dg,lz as dh,rz as di,cz as dj,uz as dk,pd as dl,Pu as dm,yO as dn,kO as dp,rd as dq,Hs as dr,mv as ds,mz as dt,SO as du,Vr as dv,wO as dw,MO as dx,EO as dy,Qp as dz,AO as e,Ia as f,PO as g,Ms as h,da as i,kz as j,hs as k,uj as l,mO as m,Qs as n,tO as o,ZL as p,eO as q,s4 as r,li as s,_O as t,_n as u,Pi as v,A$ as w,Zn as x,qs as y,us as z};