@runfusion/fusion 0.15.0 → 0.16.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.
- package/dist/bin.js +3946 -2118
- package/dist/client/assets/AgentDetailView-BoEpPOjM.css +1 -0
- package/dist/client/assets/AgentDetailView-KQz9dg0n.js +18 -0
- package/dist/client/assets/AgentsView-8Xo-c04o.js +517 -0
- package/dist/client/assets/ChatView-CjgOh8x7.js +1 -0
- package/dist/client/assets/DevServerView-BOPrzi-j.js +1 -0
- package/dist/client/assets/{DirectoryPicker-DPfkGnj5.js → DirectoryPicker-CFj7FOgn.js} +1 -1
- package/dist/client/assets/DocumentsView-CcJNmH06.js +1 -0
- package/dist/client/assets/{InsightsView-BKhvyEyQ.js → InsightsView-B0DKRIYV.js} +1 -1
- package/dist/client/assets/MemoryView-DDbr1DaJ.js +2 -0
- package/dist/client/assets/NodesView-BprfihLf.css +1 -0
- package/dist/client/assets/NodesView-BqtHfXsl.js +14 -0
- package/dist/client/assets/{PiExtensionsManager-C4fTzemh.js → PiExtensionsManager-QgzWFBAT.js} +3 -3
- package/dist/client/assets/{PluginManager-C2-dExUL.js → PluginManager-KHiz9oLY.js} +1 -1
- package/dist/client/assets/ResearchView-CVxPC1vz.css +1 -0
- package/dist/client/assets/ResearchView-s3SrjNBm.js +1 -0
- package/dist/client/assets/RoadmapsView-BlbAZTdi.js +6 -0
- package/dist/client/assets/RoadmapsView-DdGlfuu-.css +1 -0
- package/dist/client/assets/SettingsModal-D0QA2W5K.css +1 -0
- package/dist/client/assets/{SettingsModal-BGnSAeqa.js → SettingsModal-D5EUFR2z.js} +1 -1
- package/dist/client/assets/SettingsModal-c9MG4sxl.js +31 -0
- package/dist/client/assets/{SetupWizardModal-C_d9clJp.js → SetupWizardModal-tTXAm1Wb.js} +1 -1
- package/dist/client/assets/SkillsView-CS4ONN3D.js +1 -0
- package/dist/client/assets/{folder-open-CKivQd8c.js → folder-open-DObdkm5J.js} +1 -1
- package/dist/client/assets/index-BRaIPmpp.js +682 -0
- package/dist/client/assets/index-DeED_ky2.css +1 -0
- package/dist/client/assets/{star-damu_EYz.js → star-BkGA2L-k.js} +1 -1
- package/dist/client/assets/{upload-uH6CHlEw.js → upload-B0NF4J5P.js} +1 -1
- package/dist/client/assets/{users-CUySbfji.js → users-DgomiHTd.js} +1 -1
- package/dist/client/index.html +2 -2
- package/dist/client/version.json +1 -1
- package/dist/extension.js +4126 -3248
- package/dist/pi-claude-cli/package.json +1 -1
- package/dist/plugins/fusion-plugin-dependency-graph/manifest.json +16 -0
- package/dist/plugins/fusion-plugin-dependency-graph/package.json +32 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/DependencyGraphView.css +101 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/DependencyGraphView.tsx +320 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/storage.test.ts +31 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/index.ts +25 -0
- package/dist/plugins/fusion-plugin-dependency-graph/src/storage.ts +23 -0
- package/package.json +8 -4
- package/skill/fusion/references/engine-tools.md +2 -2
- package/dist/client/assets/AgentDetailView-B1zViykq.js +0 -18
- package/dist/client/assets/AgentDetailView-B5tq9ius.css +0 -1
- package/dist/client/assets/AgentsView-Bl9JH5C8.js +0 -522
- package/dist/client/assets/ChatView-liNErE53.js +0 -1
- package/dist/client/assets/DevServerView-CV_PpbnZ.js +0 -1
- package/dist/client/assets/DocumentsView-CESb6RI7.js +0 -1
- package/dist/client/assets/MemoryView-DB-l2miV.js +0 -2
- package/dist/client/assets/NodesView-DCoS6iYh.css +0 -1
- package/dist/client/assets/NodesView-DgTXO8mm.js +0 -14
- package/dist/client/assets/ResearchView-BzRdUzNq.css +0 -1
- package/dist/client/assets/ResearchView-CkVwRDVA.js +0 -1
- package/dist/client/assets/RoadmapsView-BOYnyMCh.css +0 -1
- package/dist/client/assets/RoadmapsView-Cu85_XrQ.js +0 -6
- package/dist/client/assets/SettingsModal-C0DokcId.js +0 -31
- package/dist/client/assets/SettingsModal-DcGFm6NR.css +0 -1
- package/dist/client/assets/SkillMultiselect-DDHJnrkn.css +0 -1
- package/dist/client/assets/SkillMultiselect-DwGWYZi6.js +0 -1
- package/dist/client/assets/SkillsView-C096TB7i.js +0 -1
- package/dist/client/assets/TodoView-CUiAt2mR.js +0 -6
- package/dist/client/assets/TodoView-SeO9o7km.css +0 -1
- package/dist/client/assets/index-B4StE1qN.js +0 -662
- package/dist/client/assets/index-DYJk0WDc.css +0 -1
- package/dist/client/assets/list-checks-B3oufblU.js +0 -6
|
@@ -1,662 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AgentDetailView-B1zViykq.js","assets/vendor-react-K0fH_qHe.js","assets/star-damu_EYz.js","assets/SkillMultiselect-DwGWYZi6.js","assets/SkillMultiselect-DDHJnrkn.css","assets/list-checks-B3oufblU.js","assets/vendor-xterm-DzcZoU0P.js","assets/vendor-xterm-LZoznX6r.css","assets/AgentDetailView-B5tq9ius.css","assets/addon-fit-C7jRorKK.js","assets/addon-web-links-CkJwd4cQ.js","assets/addon-webgl-BjvOw43o.js","assets/SetupWizardModal-C_d9clJp.js","assets/DirectoryPicker-DPfkGnj5.js","assets/folder-open-CKivQd8c.js","assets/DirectoryPicker-DzKVmxOf.css","assets/SetupWizardModal-DRF5fOoR.css","assets/SettingsModal-C0DokcId.js","assets/SettingsModal-BGnSAeqa.js","assets/SettingsModal-DcGFm6NR.css","assets/users-CUySbfji.js","assets/SettingsModal-D_AFkDJa.css","assets/AgentsView-Bl9JH5C8.js","assets/upload-uH6CHlEw.js","assets/AgentsView-V5GhlBYu.css","assets/DocumentsView-CESb6RI7.js","assets/DocumentsView-BrhyOdeE.css","assets/InsightsView-BKhvyEyQ.js","assets/InsightsView-4KiUKzbz.css","assets/ResearchView-CkVwRDVA.js","assets/ResearchView-BzRdUzNq.css","assets/NodesView-DgTXO8mm.js","assets/NodesView-DCoS6iYh.css","assets/ChatView-liNErE53.js","assets/RoadmapsView-Cu85_XrQ.js","assets/RoadmapsView-BOYnyMCh.css","assets/SkillsView-C096TB7i.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-DB-l2miV.js","assets/MemoryView-DiajLXby.css","assets/DevServerView-CV_PpbnZ.js","assets/DevServerView-DlZpuAnj.css","assets/TodoView-CUiAt2mR.js","assets/TodoView-SeO9o7km.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as a,j as t,R as $o,a as pa,g as vp,c as lb}from"./vendor-react-K0fH_qHe.js";import"./vendor-xterm-DzcZoU0P.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&i(l)}).observe(document,{childList:!0,subtree:!0});function s(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function i(r){if(r.ep)return;r.ep=!0;const o=s(r);fetch(r.href,o)}})();/**
|
|
3
|
-
* @license lucide-react v1.7.0 - ISC
|
|
4
|
-
*
|
|
5
|
-
* This source code is licensed under the ISC license.
|
|
6
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
7
|
-
*/const yp=(...e)=>e.filter((n,s,i)=>!!n&&n.trim()!==""&&i.indexOf(n)===s).join(" ").trim();/**
|
|
8
|
-
* @license lucide-react v1.7.0 - ISC
|
|
9
|
-
*
|
|
10
|
-
* This source code is licensed under the ISC license.
|
|
11
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
12
|
-
*/const cb=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 db=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(n,s,i)=>i?i.toUpperCase():s.toLowerCase());/**
|
|
18
|
-
* @license lucide-react v1.7.0 - ISC
|
|
19
|
-
*
|
|
20
|
-
* This source code is licensed under the ISC license.
|
|
21
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
22
|
-
*/const Qd=e=>{const n=db(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 Sl={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 ub=e=>{for(const n in e)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},mb=a.createContext({}),hb=()=>a.useContext(mb),pb=a.forwardRef(({color:e,size:n,strokeWidth:s,absoluteStrokeWidth:i,className:r="",children:o,iconNode:l,...c},u)=>{const{size:d=24,strokeWidth:m=2,absoluteStrokeWidth:h=!1,color:f="currentColor",className:p=""}=hb()??{},g=i??h?Number(s??m)*24/Number(n??d):s??m;return a.createElement("svg",{ref:u,...Sl,width:n??d??Sl.width,height:n??d??Sl.height,stroke:e??f,strokeWidth:g,className:yp("lucide",p,r),...!o&&!ub(c)&&{"aria-hidden":"true"},...c},[...l.map(([b,v])=>a.createElement(b,v)),...Array.isArray(o)?o:[o]])});/**
|
|
33
|
-
* @license lucide-react v1.7.0 - ISC
|
|
34
|
-
*
|
|
35
|
-
* This source code is licensed under the ISC license.
|
|
36
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
37
|
-
*/const Je=(e,n)=>{const s=a.forwardRef(({className:i,...r},o)=>a.createElement(pb,{ref:o,iconNode:n,className:yp(`lucide-${cb(Qd(e))}`,`lucide-${e}`,i),...r}));return s.displayName=Qd(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 fb=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],Ds=Je("activity",fb);/**
|
|
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 gb=[["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"}]],bb=Je("archive-restore",gb);/**
|
|
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 xb=[["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"}]],Ir=Je("archive",xb);/**
|
|
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 vb=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],$r=Je("arrow-down",vb);/**
|
|
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 yb=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],Ra=Je("arrow-left",yb);/**
|
|
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 wb=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],Dr=Je("arrow-right",wb);/**
|
|
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 jb=[["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"}]],wp=Je("arrow-up-down",jb);/**
|
|
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 kb=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Fi=Je("arrow-up",kb);/**
|
|
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 Nb=[["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"}]],Sb=Je("book-open",Nb);/**
|
|
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 Cb=[["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"}]],En=Je("bot",Cb);/**
|
|
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 Eb=[["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"}]],Tc=Je("box",Eb);/**
|
|
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 _b=[["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"}]],Do=Je("brain",_b);/**
|
|
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 Mb=[["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=Je("calendar",Mb);/**
|
|
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 Ab=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],Rb=Je("check-check",Ab);/**
|
|
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 Tb=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Jn=Je("check",Tb);/**
|
|
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 Pb=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Yt=Je("chevron-down",Pb);/**
|
|
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 Ib=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],el=Je("chevron-left",Ib);/**
|
|
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 $b=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],gn=Je("chevron-right",$b);/**
|
|
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 Db=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],bi=Je("chevron-up",Db);/**
|
|
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 Lb=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],gs=Je("circle-alert",Lb);/**
|
|
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 zb=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],Nn=Je("circle-check-big",zb);/**
|
|
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 Ob=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],tl=Je("circle-dot",Ob);/**
|
|
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 Fb=[["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"}]],Pc=Je("circle-question-mark",Fb);/**
|
|
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 Ub=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],Bb=Je("circle-stop",Ub);/**
|
|
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 Hb=[["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"}]],Lr=Je("circle-x",Hb);/**
|
|
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 qb=[["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"}]],Vb=Je("clipboard-list",qb);/**
|
|
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 Wb=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],Ei=Je("clock",Wb);/**
|
|
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 Kb=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],kp=Je("code",Kb);/**
|
|
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 Gb=[["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"}]],Jb=Je("columns-3",Gb);/**
|
|
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 Yb=[["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"}]],Bi=Je("copy",Yb);/**
|
|
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 Qb=[["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"}]],Xb=Je("cpu",Qb);/**
|
|
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 Zb=[["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"}]],ex=Je("download",Zb);/**
|
|
198
|
-
* @license lucide-react v1.7.0 - ISC
|
|
199
|
-
*
|
|
200
|
-
* This source code is licensed under the ISC license.
|
|
201
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
202
|
-
*/const tx=[["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"}]],nx=Je("ellipsis-vertical",tx);/**
|
|
203
|
-
* @license lucide-react v1.7.0 - ISC
|
|
204
|
-
*
|
|
205
|
-
* This source code is licensed under the ISC license.
|
|
206
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
207
|
-
*/const sx=[["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"}]],Ic=Je("ellipsis",sx);/**
|
|
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 ix=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],ax=Je("external-link",ix);/**
|
|
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 rx=[["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"}]],bd=Je("eye-off",rx);/**
|
|
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 ox=[["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"}]],Ta=Je("eye",ox);/**
|
|
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 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"}]],qs=Je("file-code",lx);/**
|
|
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 cx=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M9 10h6",key:"9gxzsh"}],["path",{d:"M12 13V7",key:"h0r20n"}],["path",{d:"M9 17h6",key:"r8uit2"}]],$c=Je("file-diff",cx);/**
|
|
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 dx=[["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"}]],ux=Je("file-minus",dx);/**
|
|
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 mx=[["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"}]],Np=Je("file-pen",mx);/**
|
|
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 hx=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],px=Je("file-plus",hx);/**
|
|
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 fx=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M12 17h.01",key:"p32p05"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}]],gx=Je("file-question-mark",fx);/**
|
|
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 bx=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Hi=Je("file-text",bx);/**
|
|
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 xx=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M11 18h2",key:"12mj7e"}],["path",{d:"M12 12v6",key:"3ahymv"}],["path",{d:"M9 13v-.5a.5.5 0 0 1 .5-.5h5a.5.5 0 0 1 .5.5v.5",key:"qbrxap"}]],vx=Je("file-type",xx);/**
|
|
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 yx=[["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"}]],Sp=Je("file",yx);/**
|
|
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 wx=[["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"}]],Dc=Je("folder-git-2",wx);/**
|
|
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 jx=[["path",{d:"M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z",key:"1fr9dc"}],["circle",{cx:"12",cy:"13",r:"2",key:"1c1ljs"}],["path",{d:"M12 15v5",key:"11xva1"}]],Xd=Je("folder-root",jx);/**
|
|
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 kx=[["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"}]],ts=Je("folder",kx);/**
|
|
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 Nx=[["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"}]],Lo=Je("funnel",Nx);/**
|
|
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 Sx=[["path",{d:"M15 6a9 9 0 0 0-9 9V3",key:"1cii5b"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}]],Ks=Je("git-branch",Sx);/**
|
|
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 Cx=[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["line",{x1:"3",x2:"9",y1:"12",y2:"12",key:"1dyftd"}],["line",{x1:"15",x2:"21",y1:"12",y2:"12",key:"oup4p8"}]],zr=Je("git-commit-horizontal",Cx);/**
|
|
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 Ex=[["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"}]],Cp=Je("git-merge",Ex);/**
|
|
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 _x=[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v7",key:"1yeb86"}],["line",{x1:"6",x2:"6",y1:"9",y2:"21",key:"rroup"}]],Es=Je("git-pull-request",_x);/**
|
|
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 Mx=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],nl=Je("globe",Mx);/**
|
|
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 Ax=[["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"}]],zo=Je("grid-3x3",Ax);/**
|
|
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 Rx=[["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"}]],xd=Je("grip-vertical",Rx);/**
|
|
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 Tx=[["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"}]],Px=Je("hard-drive",Tx);/**
|
|
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 Ix=[["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"}]],$x=Je("heart",Ix);/**
|
|
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 Dx=[["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"}]],jr=Je("history",Dx);/**
|
|
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 Lx=[["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"}]],dr=Je("inbox",Lx);/**
|
|
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 zx=[["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"}]],Ep=Je("key",zx);/**
|
|
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 Ox=[["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"}]],Fx=Je("keyboard",Ox);/**
|
|
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 Ux=[["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"}]],qi=Je("layers",Ux);/**
|
|
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 Bx=[["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"}]],Vi=Je("layout-grid",Bx);/**
|
|
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 Hx=[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]],ri=Je("lightbulb",Hx);/**
|
|
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 qx=[["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"}]],va=Je("link",qx);/**
|
|
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 Vx=[["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"}]],Wx=Je("list-plus",Vx);/**
|
|
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 Kx=[["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"}]],sl=Je("list-tree",Kx);/**
|
|
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 Gx=[["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"}]],Lc=Je("list",Gx);/**
|
|
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 Jx=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],lt=Je("loader-circle",Jx);/**
|
|
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 Yx=[["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"}]],il=Je("lock",Yx);/**
|
|
398
|
-
* @license lucide-react v1.7.0 - ISC
|
|
399
|
-
*
|
|
400
|
-
* This source code is licensed under the ISC license.
|
|
401
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
402
|
-
*/const Qx=[["path",{d:"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"}]],ya=Je("mail",Qx);/**
|
|
403
|
-
* @license lucide-react v1.7.0 - ISC
|
|
404
|
-
*
|
|
405
|
-
* This source code is licensed under the ISC license.
|
|
406
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
407
|
-
*/const Xx=[["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"}]],zc=Je("map",Xx);/**
|
|
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 Zx=[["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"}]],al=Je("maximize-2",Zx);/**
|
|
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 ev=[["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=Je("message-square-plus",ev);/**
|
|
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 nv=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],Si=Je("message-square",nv);/**
|
|
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 sv=[["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"}]],Or=Je("minimize-2",sv);/**
|
|
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 iv=[["path",{d:"M5 12h14",key:"1ays0h"}]],av=Je("minus",iv);/**
|
|
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 rv=[["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"}]],kr=Je("monitor",rv);/**
|
|
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 ov=[["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"}]],lv=Je("move",ov);/**
|
|
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 cv=[["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"}]],Oc=Je("package",cv);/**
|
|
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 dv=[["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"}]],_p=Je("paperclip",dv);/**
|
|
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 uv=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1",key:"kaeet6"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1",key:"1wsw3u"}]],Vs=Je("pause",uv);/**
|
|
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 mv=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],hs=Je("pencil",mv);/**
|
|
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:"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"}]],_n=Je("play",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 pv=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],dn=Je("plus",pv);/**
|
|
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 fv=[["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"}]],Mp=Je("radio",fv);/**
|
|
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 gv=[["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"}]],Fn=Je("refresh-cw",gv);/**
|
|
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 bv=[["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"}]],Zd=Je("rocket",bv);/**
|
|
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 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"}]],vv=Je("rotate-ccw",xv);/**
|
|
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 yv=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]],wv=Je("rotate-cw",yv);/**
|
|
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 jv=[["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"}]],Ap=Je("save",jv);/**
|
|
503
|
-
* @license lucide-react v1.7.0 - ISC
|
|
504
|
-
*
|
|
505
|
-
* This source code is licensed under the ISC license.
|
|
506
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
507
|
-
*/const kv=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Ni=Je("search",kv);/**
|
|
508
|
-
* @license lucide-react v1.7.0 - ISC
|
|
509
|
-
*
|
|
510
|
-
* This source code is licensed under the ISC license.
|
|
511
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
512
|
-
*/const Nv=[["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"}]],Oi=Je("send",Nv);/**
|
|
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 Sv=[["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"}]],Nr=Je("server",Sv);/**
|
|
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 Cv=[["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"}]],br=Je("settings",Cv);/**
|
|
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 Ev=[["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"}]],_v=Je("shield-alert",Ev);/**
|
|
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 Mv=[["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"}]],Av=Je("shield",Mv);/**
|
|
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 Rv=[["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"}]],Tv=Je("skull",Rv);/**
|
|
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 Pv=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],cs=Je("sparkles",Pv);/**
|
|
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 Iv=[["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"}]],Rp=Je("square-check-big",Iv);/**
|
|
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 $v=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],Cs=Je("square",$v);/**
|
|
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 Dv=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]],ks=Je("target",Dv);/**
|
|
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 Lv=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],gi=Je("terminal",Lv);/**
|
|
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 zv=[["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"}]],Oo=Je("text-wrap",zv);/**
|
|
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 Ov=[["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=Je("trash-2",Ov);/**
|
|
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 Fv=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],Uv=Je("trending-up",Fv);/**
|
|
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 Bv=[["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"}]],rl=Je("triangle-alert",Bv);/**
|
|
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 Hv=[["path",{d:"m18.84 12.25 1.72-1.71h-.02a5.004 5.004 0 0 0-.12-7.07 5.006 5.006 0 0 0-6.95 0l-1.72 1.71",key:"yqzxt4"}],["path",{d:"m5.17 11.75-1.71 1.71a5.004 5.004 0 0 0 .12 7.07 5.006 5.006 0 0 0 6.95 0l1.71-1.71",key:"4qinb0"}],["line",{x1:"8",x2:"8",y1:"2",y2:"5",key:"1041cp"}],["line",{x1:"2",x2:"5",y1:"8",y2:"8",key:"14m1p5"}],["line",{x1:"16",x2:"16",y1:"19",y2:"22",key:"rzdirn"}],["line",{x1:"19",x2:"22",y1:"16",y2:"16",key:"ox905f"}]],eu=Je("unlink",Hv);/**
|
|
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 qv=[["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"}]],ia=Je("user",qv);/**
|
|
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 Vv=[["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"}]],Tp=Je("webhook",Vv);/**
|
|
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 Wv=[["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"}]],Fc=Je("workflow",Wv);/**
|
|
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 Kv=[["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"}]],tu=Je("wrench",Kv);/**
|
|
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 Gv=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],qt=Je("x",Gv);/**
|
|
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 Jv=[["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"}]],es=Je("zap",Jv),Uc="fusion:version-reload",Bc="fusion:version-update";function Yv(){try{if(sessionStorage.getItem(Bc))return sessionStorage.removeItem(Bc),!0}catch{}return!1}function vd(e){if(sessionStorage.getItem(Uc)){console.warn("[versionCheck] reload already attempted, suppressing",e);return}sessionStorage.setItem(Uc,"1"),console.info("[versionCheck] reloading:",e),window.location.reload()}function Qv(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 Xv(e){return Qv(e)?(vd(`chunk load error: ${e?.message??e}`),!0):!1}async function Zv(){try{const e=await fetch("/version.json",{cache:"no-store",headers:{Accept:"application/json"}});if(!e.ok||!(e.headers.get("content-type")??"").includes("application/json"))return null;const s=await e.json();return typeof s.version=="string"?s.version:null}catch{return null}}let Cl=!1;async function El(){if(!(Cl||document.visibilityState!=="visible")){Cl=!0;try{const e=await Zv();if(e&&e!=="monyzkz7-8f97cfdc"){try{sessionStorage.setItem(Bc,"1")}catch{}vd(`build version changed: monyzkz7-8f97cfdc -> ${e}`)}}finally{Cl=!1}}}function ey(){window.setTimeout(()=>sessionStorage.removeItem(Uc),5e3),document.addEventListener("visibilitychange",()=>{El()}),window.addEventListener("focus",()=>{El()}),window.setTimeout(()=>void El(),2e3)}class ol extends a.Component{constructor(n){super(n),this.state={hasError:!1,error:null}}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,s){console.error("[ErrorBoundary]",n,s),!Xv(n)&&this.props.onError?.(n,s)}resetErrorBoundary=()=>{this.setState({hasError:!1,error:null})};render(){if(!this.state.hasError)return this.props.children;if(this.props.fallback)return this.props.fallback;const n=this.props.level??"page",i=n==="modal"?"This section encountered an error":"Something went wrong";return t.jsxs("div",{className:`error-boundary error-boundary--${n}`,children:[t.jsx("div",{className:"error-boundary__icon",children:t.jsx(rl,{size:40})}),t.jsx("div",{className:"error-boundary__title",children:i}),this.state.error&&t.jsx("pre",{className:"error-boundary__message",children:this.state.error.message}),t.jsxs("div",{className:"error-boundary__actions",children:[t.jsx("button",{className:"btn btn-primary",onClick:this.resetErrorBoundary,children:"Retry"}),t.jsx("button",{className:"btn",onClick:()=>window.location.reload(),children:"Reload page"})]})]})}}function rs({children:e,onError:n}){return t.jsx(ol,{level:"page",onError:n,children:e})}function $i({children:e,onError:n}){return t.jsx(ol,{level:"modal",onError:n,children:e})}function ty({children:e,onError:n}){return t.jsx(ol,{level:"root",onError:n,children:e})}const ny="modulepreload",sy=function(e){return"/"+e},nu={},hn=function(n,s,i){let r=Promise.resolve();if(s&&s.length>0){let l=function(d){return Promise.all(d.map(m=>Promise.resolve(m).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),u=c?.nonce||c?.getAttribute("nonce");r=l(s.map(d=>{if(d=sy(d),d in nu)return;nu[d]=!0;const m=d.endsWith(".css"),h=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${h}`))return;const f=document.createElement("link");if(f.rel=m?"stylesheet":ny,m||(f.as="script"),f.crossOrigin="",f.href=d,u&&f.setAttribute("nonce",u),document.head.appendChild(f),m)return new Promise((p,g)=>{f.addEventListener("load",p),f.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return r.then(l=>{for(const c of l||[])c.status==="rejected"&&o(c.reason);return n().catch(o)})},yd="fn.authToken",su="token",iy="fn_token";let ga,iu=!1,Fo=!1;const Hc="fn:auth-token-recovery-required";function ay(){try{const e=window.localStorage.getItem(yd);return e&&e.length>0?e:void 0}catch{return}}function Pp(e){try{window.localStorage.setItem(yd,e)}catch{}}function ry(){if(!(iu||typeof window>"u")){iu=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(su);if(!n)return;Pp(n),e.searchParams.delete(su);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function wa(){if(ga!==void 0)return ga;const e=ry();if(e)return ga=e,e;const n=ay();if(n)return ga=n,n}function oy(e){ga=e,Fo=!1,Pp(e)}function ly(){ga=void 0,Fo=!1;try{window.localStorage.removeItem(yd)}catch{}}function au(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function cy(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function dy(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!cy(e.protocol))return!1;const s=e.hostname===n.hostname,i=e.port===n.port,r=au(e.protocol)===au(n.protocol);return s&&i&&r}function uy(e){if(!(typeof window>"u"))try{const n=new URL(e,window.location.origin),s=e.startsWith("/");return{parsed:n,preserveRelativePath:s}}catch{return}}function oi(e){const n=wa();if(!n||typeof window>"u")return e;const s=uy(e);return!s||!dy(s.parsed)?e:(s.parsed.searchParams.set(iy,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function xi(e){const n=wa();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function my(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function hy(){typeof window>"u"||Fo||(Fo=!0,window.dispatchEvent(new CustomEvent(Hc)))}async function py(e){if(e.status===401)try{const n=e.clone();if(!(n.headers.get("content-type")??"").toLowerCase().includes("application/json"))return;const i=await n.json();my(i)&&hy()}catch{}}function fy(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,wa();const e=window.fetch.bind(window);window.fetch=function(s,i){const r=wa(),o=typeof s=="string"?s:s instanceof URL?s.toString():s.url;if(!(()=>{try{const u=new URL(o,window.location.origin);return u.origin!==window.location.origin?!1:u.pathname.startsWith("/api/")||u.pathname==="/api"}catch{return o.startsWith("/api/")||o==="/api"}})())return e(s,i);const c=new Headers(i?.headers??(s instanceof Request?s.headers:void 0));return r&&!c.has("Authorization")&&c.set("Authorization",`Bearer ${r}`),e(s,{...i,headers:c}).then(u=>(py(u),u))}}class gy extends Error{status;details;constructor(n,s,i){super(n),this.name="ApiRequestError",this.status=s,this.details=i}}function by(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function ds(e){return`/api${e}`}async function $(e,n={}){const s=ds(e),i=wa(),r=(()=>{if(i){const f=new Headers(n.headers??{});return f.has("Content-Type")||f.set("Content-Type","application/json"),xi(f)}if(!n.headers)return{"Content-Type":"application/json"};const h=new Headers(n.headers);return h.has("Content-Type")||h.set("Content-Type","application/json"),Object.fromEntries(h.entries())})(),o=await fetch(s,{...n,headers:r});if(o.status===204){if(!o.ok)throw new Error(`Request failed for ${s}: ${o.status} ${o.statusText}`);return}const l=o.headers.get("content-type")??"",c=await o.text(),u=l.includes("application/json");if(l.includes("text/html")||by(c))throw new Error(`API returned HTML instead of JSON for ${s}. The endpoint may not be properly configured. (${o.status} ${o.statusText})`);if(!u){const h=c.length>160?`${c.slice(0,160)}...`:c;throw new Error(`API returned ${l||"an unknown content type"} instead of JSON for ${s}. (${o.status} ${o.statusText})${h?` Response: ${h}`:""}`)}let m;try{m=c?JSON.parse(c):null}catch{throw new Error(`API returned invalid JSON for ${s}. (${o.status} ${o.statusText})`)}if(!o.ok){const h=m;throw new gy(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return m}function Q$(){return $("/health")}function X$(){return $("/updates/check")}function xy(e,n,s,i,r){const o=new URLSearchParams;s&&o.set("projectId",s),i&&o.set("q",i),r&&o.set("includeArchived","1");const l=o.size>0?`?${o.toString()}`:"";return $(`/tasks${l}`)}async function Sr(e,n){const i=ds(W(`/tasks/${e}`,n));for(let r=1;r<=2;r++){const o=await fetch(i,{headers:xi({"Content-Type":"application/json"})}),l=await o.json();if(o.ok)return l;if(r===2)throw new Error(l.error||"Request failed")}throw new Error("Request failed")}function Ip(e,n){const{title:s,description:i,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:u,modelPresetId:d,modelProvider:m,modelId:h,validatorModelProvider:f,validatorModelId:p,planningModelProvider:g,planningModelId:b,thinkingLevel:v,summarize:x,reviewLevel:y,executionMode:j,priority:E,source:C}=e;return $(W("/tasks",n),{method:"POST",body:JSON.stringify({title:s,description:i,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:u,modelPresetId:d,modelProvider:m,modelId:h,validatorModelProvider:f,validatorModelId:p,planningModelProvider:g,planningModelId:b,thinkingLevel:v,summarize:x,reviewLevel:y,executionMode:j,priority:E,source:C})})}function ii(e,n,s){return $(W(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function vy(e,n,s,i,r,o,l,c,u){return $(W("/tasks/batch-update-models",u),{method:"POST",body:JSON.stringify({taskIds:e,modelProvider:n,modelId:s,validatorModelProvider:i,validatorModelId:r,planningModelProvider:o,planningModelId:l,nodeId:c})})}function yy(e,n,s){return $(W(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n})})}function wy(e,n,s){const i=new URLSearchParams,r=i.size>0?`?${i.toString()}`:"";return $(W(`/tasks/${e}${r}`,n),{method:"DELETE"})}function jy(e,n){return $(W(`/tasks/${e}/merge`,n),{method:"POST"})}function ky(e,n){return $(W(`/tasks/${e}/retry`,n),{method:"POST"})}function Ny(e,n){return $(W(`/tasks/${e}/reset`,n),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({confirm:!0})})}function Sy(e,n){return $(W(`/tasks/${e}/duplicate`,n),{method:"POST"})}function $p(e,n){return $(W(`/tasks/${e}/pause`,n),{method:"POST"})}function Cy(e,n){return $(W(`/tasks/${e}/unpause`,n),{method:"POST"})}function Ey(e,n){return $(W(`/tasks/${e}/archive`,n),{method:"POST"})}function _y(e,n){return $(W(`/tasks/${e}/unarchive`,n),{method:"POST"})}function My(e){return $(W("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function Ay(e,n){return $(W(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function Ry(e,n){return $(W(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function Ty(e){return $(W("/config",e))}function ll(e){return $(W("/settings",e))}function so(e,n){return $(W("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function Py(e){return $(W("/update-check",e))}function Z$(e){return $(W("/remote/settings",e))}function eD(e,n){return $(W("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function tD(e){return $(W("/remote/status",e))}function nD(e){return $(W("/remote/install-cloudflared",e),{method:"POST"})}function sD(e){return $(W("/remote/tunnel/start",e),{method:"POST"})}function iD(e){return $(W("/remote/tunnel/stop",e),{method:"POST"})}function aD(e){return $(W("/remote/tunnel/kill-external",e),{method:"POST"})}function rD(e){return $(W("/remote/token/persistent/regenerate",e),{method:"POST"})}function oD(e,n){return $(W("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function Dp(e,n,s){const i=new URLSearchParams;e&&i.set("format",e),i.set("tokenType",n),n==="short-lived"&&typeof s=="number"&&Number.isFinite(s)&&i.set("ttlMs",String(s));const r=i.toString();return r?`?${r}`:""}function lD(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:i}=e,r=Dp(null,s,i);return $(W(`/remote/url${r}`,n))}function cD(e="text",n={}){const{projectId:s,tokenType:i="persistent",ttlMs:r}=n,o=Dp(e,i,r);return $(W(`/remote/qr${o}`,s))}function dD(e){return $(W("/memory",e))}function uD(e,n){return $(W("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function mD(e){return $(W("/memory/files",e))}function hD(e,n){const s=`path=${encodeURIComponent(e)}`;return $(W(`/memory/file?${s}`,n))}function pD(e,n,s){return $(W("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function fD(e,n){let s,i=n;if(n!==void 0)s=e;else if(typeof e=="string"&&e.trim().length>0){const r=e.trim();r.includes("/")||r.endsWith(".md")||r.startsWith(".")?s=r:i=r}return $(W("/memory/compact",i),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function gD(e){return $(W("/memory/dream",e),{method:"POST"})}function bD(e){return $(W("/memory/insights",e))}function xD(e,n){return $(W("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function vD(e){return $(W("/memory/extract",e),{method:"POST"})}function yD(e){return $(W("/memory/audit",e))}function wD(e){return $(W("/memory/stats",e))}function jD(e){return $(W("/memory/backend",e))}function kD(e){return $(W("/memory/install-qmd",e),{method:"POST"})}function ND(e,n){return $(W("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function Yi(){return $("/settings/global")}function bn(e){return $("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function SD(e){return $(W("/settings/scopes",e))}function CD(e){return $(W("/settings/pi-extensions",e))}function ED(e,n){return $(W("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function _D(e,n,s){return $(W("/settings/test-notification",s),{method:"POST",body:JSON.stringify({providerId:e,...n??{}})})}function MD(){return $("/pi-settings")}async function AD(e){return $("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function RD(e){return $("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function TD(e){return $(W("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function Cr(e,n,s){const i=new FormData;i.append("file",n);const r=await fetch(ds(W(`/tasks/${e}/attachments`,s)),{method:"POST",headers:xi(),body:i}),o=await r.json();if(!r.ok)throw new Error(o.error||"Upload failed");return o}async function Iy(e,n,s){return $(W(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function ru(e,n,s){const i=new URLSearchParams;s?.limit!==void 0&&i.set("limit",String(s.limit)),s?.offset!==void 0&&i.set("offset",String(s.offset));const r=i.toString()?`?${i.toString()}`:"",o=W(`/tasks/${e}/logs${r}`,n),l=await fetch(ds(o),{headers:xi()});if(!l.ok){const m=await l.json().catch(()=>({error:"Failed to fetch agent logs"}));throw new Error(m.error||`HTTP ${l.status}`)}const c=await l.json(),u=l.headers.has("X-Total-Count")?parseInt(l.headers.get("X-Total-Count"),10):c.length,d=l.headers.has("X-Has-More")?l.headers.get("X-Has-More")==="true":!1;return{entries:c,total:u,hasMore:d}}function $y(e,n,s,i){return $(W(`/tasks/${e}/comments/${n}`,i),{method:"PATCH",body:JSON.stringify({text:s})})}function Dy(e,n,s){return $(W(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function Ly(e,n){return $(W(`/tasks/${e}/documents`,n))}function zy(e,n,s){return $(W(`/tasks/${e}/documents/${n}/revisions`,s))}async function PD(e,n){const s=new URLSearchParams;e?.q&&s.set("q",e.q),e?.limit!==void 0&&s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset));const i=s.toString(),r=`/documents${i?`?${i}`:""}`;return $(W(r,n))}function ID(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const i=s.toString(),r=`/files/markdown-list${i?`?${i}`:""}`;return $(W(r,e))}function ou(e,n,s,i,r){return $(W(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:i?.author,metadata:i?.metadata})})}function Oy(e,n,s){return $(W(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function Fy(e,n,s){return $(W(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function Uy(e,n,s){return $(W(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function By(e,n){return $(W(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function Hy(e,n,s){return $(W(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function bs(){return $("/models")}function qy(){return $("/usage")}function Vy(){return $("/providers/claude-cli/status")}function Wy(){return $("/system/fn-binary/status")}function Ky(){return $("/system/fn-binary/install",{method:"POST"})}function Gy(){return $("/providers/droid-cli/status")}async function $D(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return $(`/providers/hermes/status${n}`)}async function DD(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return(await $(`/providers/hermes/profiles${n}`)).profiles??[]}async function LD(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return $(`/providers/openclaw/status${n}`)}async function zD(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),$(`/providers/paperclip/status?${n.toString()}`)}async function OD(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),(await $(`/providers/paperclip/companies?${n.toString()}`)).companies??[]}async function FD(e){const n=new URLSearchParams({apiUrl:e.apiUrl,companyId:e.companyId});return e.apiKey&&n.set("apiKey",e.apiKey),(await $(`/providers/paperclip/agents?${n.toString()}`)).agents??[]}async function UD(e){return $("/providers/paperclip/cli-mint-key",{method:"POST",body:JSON.stringify(e)})}async function BD(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return $(`/providers/paperclip/cli-status${s?`?${s}`:""}`)}async function HD(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 $(`/providers/paperclip/cli-companies${s?`?${s}`:""}`)).companies??[]}async function qD(e){const n=new URLSearchParams({companyId:e.companyId});return e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath),(await $(`/providers/paperclip/cli-agents?${n.toString()}`)).agents??[]}async function VD(e={}){const n=new URLSearchParams;e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return $(`/providers/paperclip/cli-discovery${s?`?${s}`:""}`)}function Jy(e){return $("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function Yy(e){return $("/auth/droid-cli",{method:"POST",body:JSON.stringify({enabled:e})})}async function Qy(){const n=(await $("/custom-providers")).map(s=>({id:s.id,name:s.name,baseUrl:s.baseUrl,api:s.apiType==="anthropic-compatible"?"anthropic-messages":"openai-completions",apiKey:s.apiKey,models:(s.models??[]).map(i=>({id:i.id,name:i.name}))}));return Object.assign(n,{providers:n})}function Xy(e){return $("/custom-providers",{method:"POST",body:JSON.stringify(e)})}function WD(e,n){const s=n,i={...typeof s.name=="string"?{name:s.name}:{},...typeof s.baseUrl=="string"?{baseUrl:s.baseUrl}:{},...typeof s.apiKey=="string"?{apiKey:s.apiKey}:{},...Array.isArray(s.models)?{models:s.models.map(r=>({id:r.id,name:r.name??r.id}))}:{},...s.api?{apiType:s.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible"}:{},..."apiType"in n?{apiType:n.apiType}:{}};return $(`/custom-providers/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(i)})}function KD(e){return $(`/custom-providers/${encodeURIComponent(e)}`,{method:"DELETE"})}function Zy(e){const n=e.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible";return Xy({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 Er(){return $("/auth/status")}function ew(e){return $("/auth/login",{method:"POST",body:JSON.stringify({provider:e,origin:window.location.origin})})}function tw(e){return $("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function nw(e){return $("/auth/cancel",{method:"POST",body:JSON.stringify({provider:e})})}function sw(e,n){return $("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function iw(e){return $("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function aw(e,n,s,i){return $("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:i})})}function rw(e,n,s,i){return $(W("/github/issues/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function ow(e,n,s){return $("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function lw(e,n,s,i){return $(W("/github/pulls/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function cw(e){return $(W("/git/remotes",e))}function dw(e){return $(W("/git/remotes/detailed",e))}function uw(e,n,s){return $(W("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function mw(e,n){return $(W(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function hw(e,n,s){return $(W(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function pw(e,n,s){return $(W(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function fw(e,n,s){return $(W(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function gw(e,n){return $(W(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}async function bw(e,n){return(await $(W("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:e})})).results}function io(e,n,s,i){return $(W("/terminal/sessions",i),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function lu(e,n){return $(W(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function xw(e){return $(W("/terminal/sessions",e))}function Bs(e){return $(W("/git/status",e))}function vw(e,n){const s=e?`?limit=${e}`:"";return $(W(`/git/commits${s}`,n))}function Uo(e,n){return $(W(`/git/commits/${e}/diff`,n))}function yw(e){return $(W("/git/commits/ahead",e))}function ww(e,n,s,i){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return $(W(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,i))}function Va(e){return $(W("/git/branches",e))}function jw(e,n,s){const i=`?limit=${n}`;return $(W(`/git/branches/${encodeURIComponent(e)}/commits${i}`,s))}function kw(e){return $(W("/git/worktrees",e))}function Nw(e,n,s){return $(W("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function Sw(e,n){return $(W(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function cu(e,n,s){const i=n?"?force=true":"";return $(W(`/git/branches/${encodeURIComponent(e)}${i}`,s),{method:"DELETE"})}function Cw(e,n){return $(W("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function Ew(e){return $(W("/git/pull",e),{method:"POST"})}function _w(e){return $(W("/git/push",e),{method:"POST"})}function ao(e){return $(W("/git/stashes",e))}function Mw(e,n){return $(W("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function Aw(e,n,s){return $(W(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function Rw(e,n){return $(W(`/git/stashes/${e}`,n),{method:"DELETE"})}function Tw(e,n,s){const i=new URLSearchParams;return i.set("path",e),i.set("staged",String(n)),$(W(`/git/diff/file?${i.toString()}`,s))}function aa(e){return $(W("/git/changes",e))}function du(e,n){return $(W("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function Pw(e,n){return $(W("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function uu(e,n){return $(W("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function Iw(e,n){return $(W("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function $w(e){return $(W("/workspaces",e))}function Dw(e,n,s){const i=new URLSearchParams({workspace:e});return n&&i.set("path",n),s&&i.set("projectId",s),$(`/files?${i.toString()}`)}function Lw(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),$(`/files/${encodeURIComponent(n)}?${i.toString()}`)}function zw(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),$(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function Ow(e,n,s){const i=new URLSearchParams({q:e});return n&&i.set("workspace",n),s&&i.set("projectId",s),$(`/files/search?${i.toString()}`)}function Fw(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),$(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function Uw(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),$(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function Bw(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),$(`/files/${encodeURIComponent(n)}/delete?${i.toString()}`,{method:"POST"})}function Hw(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),$(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function Lp(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${i.toString()}`}function qw(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${i.toString()}`}function Vw(e,n,s){return $(W("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function Ww(e,n,s,i){return $(W("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Kw(e,n,s){return $(W(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Gw(e,n,s){return $(W(`/planning/${encodeURIComponent(e)}/stop`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function zp(e,n,s){return $(W("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function GD(e,n,s,i){return $(W("/agents/onboarding/start-streaming",s),{method:"POST",body:JSON.stringify({intent:e,context:n,planningModelProvider:i?.planningModelProvider,planningModelId:i?.planningModelId})})}function JD(e,n,s){return $(W("/agents/onboarding/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n})})}function YD(e,n){return $(W("/agents/onboarding/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function Jw(e,n,s){return $(W("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Yw(e,n,s){return $(W("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Qw(e,n,s){return $(W("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const qc=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(qc))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function Xw(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function Pa(e,n,s={}){const i=s.maxReconnectAttempts??10;let r=null,o=!1,l=0,c=null,u=null,d=!1;const m=p=>{const g=p.lastEventId;if(!g)return!0;const b=Number.parseInt(g,10);return Number.isFinite(b)?u!==null&&b<=u?!1:(u=b,!0):!0},h=()=>{if(o)return;const p=Xw(e,u),g=new EventSource(oi(p));r=g,g.onopen=()=>{l=0,d=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},g.onmessage=b=>{const v=b;m(v)&&n.onMessage?.(v)};for(const[b,v]of Object.entries(n.events??{}))g.addEventListener(b,x=>{const y=x;m(y)&&v(y)});g.onerror=()=>{if(o||r!==g)return;if(g.readyState===EventSource.CONNECTING){d||(d=!0,s.onConnectionStateChange?.("reconnecting"));return}if(g.close(),l>=i){s.onFatalError?.("Connection lost");return}d=!0,s.onConnectionStateChange?.("reconnecting"),l+=1;const v=Math.min(1e3*2**(l-1),3e4);c=setTimeout(()=>{c=null,h()},v)}};h();const f={close:()=>{o=!0,c&&(clearTimeout(c),c=null),r?.close(),qc.delete(f)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return qc.add(f),f}function mu(e){const n=typeof e.source=="string"&&e.source.trim().length>0?e.source.trim():"root",s=n==="root"?".":n,i=e.name,r=typeof e.packagePath=="string"&&e.packagePath.trim().length>0?e.packagePath.trim():s,o=typeof e.confidence=="number"?e.confidence:1,l=n==="root"?"root":n,c=typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():"project";return{name:e.name,command:e.command,scriptName:i,packagePath:r,confidence:o,cwd:s,source:n,workspaceName:typeof e.packageName=="string"?e.packageName:void 0,label:`${c} · ${i} (${l})`}}function ja(e){const n=e.status,s=n==="starting"||n==="running"||n==="failed"||n==="stopped"?n:"stopped",i=typeof e.previewUrl=="string"?e.previewUrl:e.detectedUrl,r=typeof e.manualPreviewUrl=="string"?e.manualPreviewUrl:e.manualUrl;return{id:typeof e.id=="string"?e.id:"",name:typeof e.name=="string"&&e.name.length>0?e.name:"default",status:s,command:typeof e.command=="string"?e.command:"",scriptName:typeof e.scriptId=="string"?e.scriptId:"",cwd:typeof e.cwd=="string"?e.cwd:"",pid:e.pid,startedAt:e.startedAt,previewUrl:i,detectedUrl:typeof e.detectedUrl=="string"?e.detectedUrl:i,detectedPort:e.detectedPort,manualPreviewUrl:r,manualUrl:typeof e.manualUrl=="string"?e.manualUrl:r,logs:Array.isArray(e.logHistory)?e.logHistory:[],exitCode:e.exitCode}}function Zw(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 ej(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((i,r)=>Zw(i,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function tj(e,n){const s=typeof n.maxLines=="number"&&Number.isFinite(n.maxLines)?Math.max(1,Math.floor(n.maxLines)):100,i=typeof n.offset=="number"&&Number.isFinite(n.offset)?Math.max(0,Math.floor(n.offset)):0,r=typeof n.lastEventId=="number"&&Number.isFinite(n.lastEventId)?Math.max(0,Math.floor(n.lastEventId)):null,o=e.length,l=e.map((d,m)=>({id:m+1,text:d,stream:"stdout",timestamp:""}));if(r!==null)return{lines:l.filter(d=>d.id>r).slice(0,s),totalLines:o};const c=Math.max(o-i,0),u=Math.max(c-s,0);return{lines:l.slice(u,c),totalLines:o}}function hu(e){return Array.isArray(e)?e.map(mu):(e.candidates??[]).map(mu)}async function nj(e){try{const n=await $(W("/dev-server/candidates",e));return hu(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await $(W("/dev-server/detect",e));return hu(s)}throw n}}function wd(e){return $(W("/dev-server/status",e)).then(ja)}async function QD(e={},n){const s=new URLSearchParams;typeof e.maxLines=="number"&&Number.isFinite(e.maxLines)&&s.set("maxLines",String(Math.max(1,Math.floor(e.maxLines)))),typeof e.offset=="number"&&Number.isFinite(e.offset)&&s.set("offset",String(Math.max(0,Math.floor(e.offset)))),typeof e.lastEventId=="number"&&Number.isFinite(e.lastEventId)&&s.set("lastEventId",String(Math.max(0,Math.floor(e.lastEventId))));const i=s.size>0?`?${s.toString()}`:"";try{const r=await $(W(`/dev-server/logs/history${i}`,n));return ej(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await wd(n);return tj(o.logs,e)}throw r}}function sj(e,n){const s=e.cwd??e.packagePath??".",i=e.scriptName;return $(W("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:i,scriptId:i,cwd:s,packagePath:e.packagePath})}).then(ja)}function ij(e){return $(W("/dev-server/stop",e),{method:"POST"}).then(ja)}function aj(e){return $(W("/dev-server/restart",e),{method:"POST"}).then(ja)}async function rj(e,n){const s=typeof e=="string"?{url:e}:e;try{const i=await $(W("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return ja(i)}catch(i){if(i instanceof Error&&/\/dev-server\/preview-url/.test(i.message)){const r=await $(W("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return ja(r)}throw i}}function XD(e){return ds(W("/dev-server/logs/stream",e))}async function ZD(e){try{return(await $(W("/devserver",e))).sessions??[]}catch{try{const n=await wd(e);return[{config:{id:n.id??"default",name:n.name??"Dev Server",command:n.command??"",cwd:n.cwd??"."},status:n.status,runtime:n.pid?{pid:n.pid,startedAt:n.startedAt??new Date().toISOString(),exitCode:n.exitCode??void 0,previewUrl:n.previewUrl}:void 0,previewUrl:n.previewUrl??n.detectedUrl??void 0,logHistory:(n.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}]}catch{return[]}}}async function eL(e,n){try{return await $(W(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await wd(n);return!e||e==="default"||e===s.id?{config:{id:s.id??"default",name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}:null}catch{return null}}}async function tL(e,n){try{return await $(W(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await sj({command:""},n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}}}async function nL(e,n){try{return await $(W(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await ij(n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}}}async function sL(e,n){try{return await $(W(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await aj(n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}}}async function iL(e,n,s){try{const i=await $(W(`/devserver/${encodeURIComponent(e)}/preview`,s),{method:"POST",body:JSON.stringify({url:n})});return{url:i.url??null,source:i.source??null}}catch{const i=await rj({url:n},s);return{url:i.previewUrl??i.manualUrl??null,source:"manual"}}}async function aL(e){try{return(await $(W("/devserver/detect",e))).candidates??[]}catch{try{return(await nj(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function rL(e,n){return ds(W(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function Fr(e,n,s=25e3){const i=setInterval(()=>{Hk(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(i)}}}function oj(e,n){return ds(W(`/planning/${encodeURIComponent(e)}/stream`,n))}function lj(e,n){return ds(W(`/agents/onboarding/${encodeURIComponent(e)}/stream`,n))}function oL(e,n,s,i){const r=lj(e,n),o=Pa(r,{events:{thinking:l=>{try{s.onThinking?.(JSON.parse(l.data))}catch{s.onThinking?.(l.data)}},question:l=>{try{s.onQuestion?.(JSON.parse(l.data))}catch{}},summary:l=>{try{s.onSummary?.(JSON.parse(l.data))}catch{}},error:l=>{try{const c=JSON.parse(l.data);s.onError?.(c.message||c)}catch{s.onError?.(l.data||"Stream error")}},complete:()=>{s.onComplete?.()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:l=>s.onError?.(l)});return{close:o.close,isConnected:o.isConnected}}function cj(e,n,s,i){const r=oj(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Pa(r,{onOpen:()=>{c(),o=Fr(e,n)},onMessage:d=>{d.data.startsWith(":")},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},question:d=>{try{s.onQuestion?.(JSON.parse(d.data))}catch(m){console.error("[planning] Failed to parse question event:",m)}},summary:d=>{try{s.onSummary?.(JSON.parse(d.data))}catch(m){console.error("[planning] Failed to parse summary event:",m)}},error:d=>{try{const m=JSON.parse(d.data);s.onError?.(m.message||m)}catch{s.onError?.(d.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{c(),s.onError?.(d)}});return l={close:()=>{c(),u.close()},isConnected:u.isConnected},l}function Ur(e,n){const s=new URLSearchParams;n?.scope&&s.set("scope",n.scope),n?.projectId&&s.set("projectId",n.projectId);const i=s.toString();return i?`${e}?${i}`:e}function dj(e){return $(Ur("/routines",e))}function uj(e,n){return $(Ur("/routines",n),{method:"POST",body:JSON.stringify(e)})}function pu(e,n,s){return $(Ur(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function mj(e,n){await $(Ur(`/routines/${e}`,n),{method:"DELETE"})}function hj(e,n){return $(Ur(`/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 $(`/activity${s}`)}function pj(e){const n=W("/activity",e);return $(n,{method:"DELETE"})}function Br(e){return $(W("/workflow-steps",e))}function gu(e,n){return $(W("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function fj(e,n,s){return $(W(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function gj(e,n){return $(W(`/workflow-steps/${e}`,n),{method:"DELETE"})}function bu(e,n){return $(W(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function bj(e,n){return $(W(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function xj(){return $("/workflow-step-templates")}function vj(e,n){return $(W(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function _r(e){return $(W("/scripts",e))}function yj(e,n,s){return $(W("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function wj(e,n){return $(W(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function Op(e,n,s){return(await $(W("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const ro={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 Fp(e){if(!(e instanceof Error))return ro.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?ro.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?ro.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:ro.NETWORK}function jj(e,n){return $(W("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function kj(e,n,s){return $(W(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Nj(e,n){return ds(W(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function Sj(e,n,s,i){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=Pa(Nj(e,n),{onOpen:()=>{l(),r=Fr(e,n)},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},subtasks:u=>{try{s.onSubtasks?.(JSON.parse(u.data))}catch(d){console.error("[subtasks] Failed to parse subtasks event:",d)}},error:u=>{try{const d=JSON.parse(u.data),m=typeof d=="string"&&d.length>0?d:null;s.onError?.(m||"Stream error")}catch{s.onError?.("Stream error")}o?.close()},complete:()=>{s.onComplete?.(),o?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{l(),s.onError?.(u)}});return o={close:()=>{l(),c.close()},isConnected:c.isConnected},o}function Cj(e,n,s,i){return $(W("/subtasks/create-tasks",i),{method:"POST",body:JSON.stringify({sessionId:e,parentTaskId:s,subtasks:n.map(r=>({tempId:r.id,title:r.title,description:r.description,size:r.suggestedSize,dependsOn:r.dependsOn}))})})}function Up(e,n,s){return $(W("/subtasks/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function W(e,n){if(!n)return e;const s=e.includes("?")?"&":"?";return`${e}${s}projectId=${encodeURIComponent(n)}`}function Ej(e,n,s){if(!n||n===s)return e;const i="/api",r=e.startsWith(i)?e.slice(i.length):e;return`/proxy/${encodeURIComponent(n)}${r}`}function cl(e,n){const{nodeId:s,localNodeId:i,...r}=n??{},o=Ej(e,s,i);return $(o,r)}function Ia(e,n){const s=new URLSearchParams;e?.state&&s.set("state",e.state),e?.role&&s.set("role",e.role),e?.includeEphemeral===!0&&s.set("includeEphemeral","true"),n&&s.set("projectId",n);const i=s.size>0?`?${s.toString()}`:"";return $(`/agents${i}`)}function Vc(e,n){return $(W(`/agents/${encodeURIComponent(e)}`,n))}function _j(e,n){return $(W("/agents",n),{method:"POST",body:JSON.stringify(e)})}function Mj(e,n,s){return $(W(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function lL(e,n){return $(W(`/agents/${encodeURIComponent(e)}/upgrade-heartbeat-procedure`,n),{method:"POST"})}function cL(e,n,s){return $(W(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function dL(e,n,s){return $(W(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function uL(e,n,s){return $(W(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function mL(e,n){return $(W(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function hL(e,n,s){const i=`path=${encodeURIComponent(n)}`;return $(W(`/agents/${encodeURIComponent(e)}/memory/file?${i}`,s))}function pL(e,n,s,i){return $(W(`/agents/${encodeURIComponent(e)}/memory/file`,i),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function Aj(e,n,s){return $(W(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function Rj(e,n){return $(W(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function fL(e,n,s){const i=new URLSearchParams;n!==void 0&&i.set("limit",String(n)),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return $(`/agents/${encodeURIComponent(e)}/runs${r}`)}function gL(e,n,s){return $(W(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function bL(e,n,s){return $(W(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function xL(e,n,s){const i=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return $(W(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:i,triggerDetail:r})})}function vL(e,n){return $(W(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function Tj(e){return $(W("/agents/stats",e))}function yL(e,n){return $(W(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function wL(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeEphemeral&&s.set("includeEphemeral","true");const i=s.toString();return $(`/agents/org-tree${i?`?${i}`:""}`)}function jL(e,n){return $(W(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function xu(e,n,s){return $(W(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function kL(e,n){return $(W(`/agents/${encodeURIComponent(e)}/tasks`,n))}function NL(){return $("/agents/companies")}function SL(e,n){return $(W("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function CL(e,n){return $(W("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function EL(e,n){return $(W(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function _L(e){return $(W("/backups",e))}function ML(e){return $(W("/backups",e),{method:"POST"})}function AL(e,n){const s=W("/settings/export",n),i=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return $(i)}function RL(e,n,s){return $(W("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}function vu(){return $("/projects/across-nodes")}function xr(e,n){$("/_perf/dashboard-load",{method:"POST",body:JSON.stringify({source:e,message:n})}).catch(()=>{})}function Bo(){return $("/nodes")}function Pj(e){return $("/nodes",{method:"POST",body:JSON.stringify(e)})}function Ij(e,n){return $(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function $j(e){return $(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Dj(e){const n=await $(`/nodes/${encodeURIComponent(e)}/health-check`,{method:"POST"});return{nodeId:n.nodeId??e,status:n.status,responseTimeMs:n.responseTimeMs,error:n.error,checkedAt:n.checkedAt??new Date().toISOString()}}function TL(e,n,s,i){const r=s&&s!==i?s:void 0,o=new URLSearchParams;e&&o.set("path",e),n&&o.set("showHidden","true"),r&&o.set("nodeId",r);const l=wa();l&&o.set("fn_token",l);const c=o.toString(),u=`/browse-directory${c?`?${c}`:""}`;return $(u)}function Lj(e){return $("/projects",{method:"POST",body:JSON.stringify(e)})}function Bp(e){return $(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function yu(e){return $(`/projects/${encodeURIComponent(e)}/health`)}function zj(e){return $(W("/executor/stats",e))}function Oj(e){return $(W("/system-stats",e))}function Fj(e){return $(W("/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 $(`/activity-feed${s}`)}function Uj(e){return $(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function Bj(e){return $(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function PL(){return $("/global-concurrency")}function IL(e){return $("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function Hj(e,n){return $(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function Hp(e,n,s){const i=new URLSearchParams;n&&i.set("worktree",n),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return $(`/tasks/${encodeURIComponent(e)}/diff${r}`)}function qj(e){return $(W("/missions",e))}function Vj(e,n){return $(W("/missions",n),{method:"POST",body:JSON.stringify(e)})}function qp(e,n){return $(W(`/missions/${encodeURIComponent(e)}`,n))}function Wj(e,n,s){return $(W(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Kj(e,n){return $(W(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Gj(e,n,s){const i=new URLSearchParams;i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset));const r=i.size>0?`?${i.toString()}`:"";return $(W(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function Jj(e){return $(W("/missions/health",e))}function Yj(e,n,s){return $(W(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function Qj(e,n,s){return $(W(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Xj(e,n){return $(W(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Zj(e,n,s){return $(W(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function ek(e,n,s){return $(W(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function tk(e,n){return $(W(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function nk(e,n){return $(W(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function sk(e,n,s){return $(W(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function ik(e,n,s){return $(W(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function ak(e,n){return $(W(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function rk(e,n,s){return $(W(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function ok(e,n){return $(W(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function lk(e,n,s,i){return $(W(`/missions/features/${encodeURIComponent(e)}/triage`,i),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s})})}function ck(e,n){return $(W(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST"})}function _l(e,n){return $(W(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function dk(e,n,s){return $(W(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function uk(e,n,s){return $(W(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function mk(e,n,s){return $(W(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function hk(e,n,s){return $(W(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function pk(e,n){return $(W(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function Ml(e,n){return $(W(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function ju(e,n){return $(W(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function fk(e,n){return $(W(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function ku(e,n){return $(W(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function gk(e,n,s){const i=new URLSearchParams;i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset));const r=i.size>0?`?${i.toString()}`:"";return $(W(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function bk(e,n){return $(W(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function xk(e,n){return $(W(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function vk(e,n){return $(W(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function yk(e,n){return $(W(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function wk(e,n,s){return $(W(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function jk(e,n,s){return $(W("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function kk(e,n,s,i){return $(W("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Nk(e,n,s){return $(W(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Vp(e,n,s){return $(W("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function Sk(e,n,s){return $(W("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function Ck(e,n,s,i){const r=ds(W(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Pa(r,{onOpen:()=>{c(),o=Fr(e,n)},onMessage:d=>{d.data.startsWith(":")},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},question:d=>{try{s.onQuestion?.(JSON.parse(d.data))}catch(m){console.error("[mission-interview] Failed to parse question event:",m)}},summary:d=>{try{s.onSummary?.(JSON.parse(d.data))}catch(m){console.error("[mission-interview] Failed to parse summary event:",m)}},error:d=>{try{const m=JSON.parse(d.data);s.onError?.(m.message||m)}catch{s.onError?.(d.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{c(),s.onError?.(d)}});return l={close:()=>{c(),u.close()},isConnected:u.isConnected},l}function Hr(e,n,s){return W(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function qr(e,n,s){return W(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function Ek(e,n){return $(Hr(e,"/start",n),{method:"POST"})}function _k(e,n,s,i){return $(Hr(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Mk(e,n,s,i){const r=ds(Hr(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Pa(r,{onOpen:()=>{c(),o=Fr(e,n)},onMessage:d=>{d.data.startsWith(":")},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},question:d=>{try{s.onQuestion?.(JSON.parse(d.data))}catch(m){console.error("[milestone-interview] Failed to parse question event:",m)}},summary:d=>{try{s.onSummary?.(JSON.parse(d.data))}catch(m){console.error("[milestone-interview] Failed to parse summary event:",m)}},error:d=>{try{const m=JSON.parse(d.data);s.onError?.(m.message||m)}catch{s.onError?.(d.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{c(),s.onError?.(d)}});return l={close:()=>{c(),u.close()},isConnected:u.isConnected},l}function Ak(e,n,s){return $(Hr(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function Rk(e,n){return $(Hr(e,"/skip",n),{method:"POST"})}function Tk(e,n){return $(qr(e,"/start",n),{method:"POST"})}function Pk(e,n,s,i){return $(qr(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Ik(e,n,s,i){const r=ds(qr(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Pa(r,{onOpen:()=>{c(),o=Fr(e,n)},onMessage:d=>{d.data.startsWith(":")},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},question:d=>{try{s.onQuestion?.(JSON.parse(d.data))}catch(m){console.error("[slice-interview] Failed to parse question event:",m)}},summary:d=>{try{s.onSummary?.(JSON.parse(d.data))}catch(m){console.error("[slice-interview] Failed to parse summary event:",m)}},error:d=>{try{const m=JSON.parse(d.data);s.onError?.(m.message||m)}catch{s.onError?.(d.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{c(),s.onError?.(d)}});return l={close:()=>{c(),u.close()},isConnected:u.isConnected},l}function $k(e,n,s){return $(qr(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function Dk(e,n){return $(qr(e,"/skip",n),{method:"POST"})}async function Lk(e,n){try{return await $(W(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function $L(e){return $(W("/roadmaps",e))}function DL(e,n){return $(W("/roadmaps",n),{method:"POST",body:JSON.stringify(e)})}function LL(e,n){return $(W(`/roadmaps/${encodeURIComponent(e)}`,n))}function zL(e,n,s){return $(W(`/roadmaps/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function OL(e,n){return $(W(`/roadmaps/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function FL(e,n,s){return $(W(`/roadmaps/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function UL(e,n,s){return $(W(`/roadmaps/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function BL(e,n){return $(W(`/roadmaps/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function HL(e,n,s){return $(W(`/roadmaps/milestones/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function qL(e,n,s){return $(W(`/roadmaps/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function VL(e,n){return $(W(`/roadmaps/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function WL(e,n,s){return $(W(`/roadmaps/${encodeURIComponent(e)}/milestones/reorder`,s),{method:"POST",body:JSON.stringify({orderedMilestoneIds:n})})}function KL(e,n,s){return $(W(`/roadmaps/milestones/${encodeURIComponent(e)}/features/reorder`,s),{method:"POST",body:JSON.stringify({orderedFeatureIds:n})})}function GL(e,n,s,i){return $(W(`/roadmaps/features/${encodeURIComponent(e)}/move`,i),{method:"POST",body:JSON.stringify({targetMilestoneId:n,targetIndex:s})})}function JL(e,n){return $(W(`/roadmaps/${encodeURIComponent(e)}/handoff`,n))}function YL(e,n,s,i){return $(W(`/roadmaps/${encodeURIComponent(e)}/suggestions/milestones`,i),{method:"POST",body:JSON.stringify({goalPrompt:n.trim(),...s!==void 0?{count:s}:{}})})}function QL(e,n,s){return $(W(`/roadmaps/milestones/${encodeURIComponent(e)}/suggestions/features`,s),{method:"POST",body:JSON.stringify({...n?.prompt!==void 0?{prompt:n.prompt.trim()}:{},...n?.count!==void 0?{count:n.count}:{}})})}function XL(e){return $(W("/todos",e))}function ZL(e,n){const s={title:e};return $(W("/todos",n),{method:"POST",body:JSON.stringify(s)})}function e3(e,n,s){const i={title:n};return $(W(`/todos/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(i)})}function t3(e,n){return $(W(`/todos/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function n3(e,n,s){const i={text:n};return $(W(`/todos/${encodeURIComponent(e)}/items`,s),{method:"POST",body:JSON.stringify(i)})}function s3(e,n,s){const i=n;return $(W(`/todos/items/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(i)})}function i3(e,n){return $(W(`/todos/items/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function a3(e,n,s){return $(W(`/todos/${encodeURIComponent(e)}/items/reorder`,s),{method:"POST",body:JSON.stringify({itemIds:n})})}function ka(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function jd(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeCompleted&&s.set("includeCompleted","1"),n?.includeArchived&&s.set("includeArchived","1");const i=s.toString(),r=await fetch(ds(`/ai-sessions${i?`?${i}`:""}`),{headers:xi()});return r.ok?(await r.json()).sessions??[]:[]}async function zk(e){return $(`/ai-sessions/${encodeURIComponent(e)}/archive`,{method:"POST"})}async function Ok(e){return $(`/ai-sessions/${encodeURIComponent(e)}/unarchive`,{method:"POST"})}async function ai(e){const n=await fetch(ds(`/ai-sessions/${encodeURIComponent(e)}`),{headers:xi()});return n.ok?n.json():null}async function Fk(e,n){const s=await $(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function Uk(e,n){return $(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function Bk(e,n){return $(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function Wp(e){await fetch(ds(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:xi()})}function Hk(e,n){return $(W(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function qk(e,n){const s=new URLSearchParams;s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),e?.unreadOnly&&s.set("unreadOnly","true"),e?.type&&s.set("type",e.type),n&&s.set("projectId",n);const i=s.size>0?`?${s.toString()}`:"";return $(`/messages/inbox${i}`)}function Vk(e,n){const s=new URLSearchParams;s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),e?.type&&s.set("type",e.type),n&&s.set("projectId",n);const i=s.size>0?`?${s.toString()}`:"";return $(`/messages/outbox${i}`)}function Kp(e){return $(W("/messages/unread-count",e))}function Wk(e,n){return $(W("/messages",n),{method:"POST",body:JSON.stringify(e)})}function Kk(e,n){return $(W(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function Gk(e){return $(W("/messages/read-all",e),{method:"POST"})}function Jk(e,n){return $(W(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Yk(e,n,s){const i=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return $(W(i,s))}function Qk(e,n){return $(W(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function r3(e,n,s){const i=new URLSearchParams;i.set("limit",String(n)),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return $(`/agents/${encodeURIComponent(e)}/reflections${r}`)}function o3(e,n){return $(W(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function l3(e,n,s){const i=new URLSearchParams;s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return $(`/agents/${encodeURIComponent(e)}/performance${r}`)}function c3(e,n,s){const i=new URLSearchParams;i.set("limit",String(n.limit)),n?.category&&i.set("category",n.category),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return $(`/agents/${encodeURIComponent(e)}/ratings${r}`)}function d3(e,n,s){return $(W(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function u3(e,n){return $(W(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function m3(e,n,s){return $(W(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function h3(e,n){return $(W(`/agents/${encodeURIComponent(e)}/budget`,n))}function p3(e,n){return $(W(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function f3(e){return $(W("/plugins",e))}async function g3(e,n){return $(W("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function b3(e,n){return $(W(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function x3(e,n){return $(W(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function v3(e,n){return $(W(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function y3(e,n){return $(W(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function w3(e,n,s){return $(W(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function j3(e,n){return $(W(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function Xk(e){return $(W("/plugins/ui-slots",e))}async function Zk(e){return $(W("/plugins/dashboard-views",e))}async function k3(e){return $(W("/plugins/runtimes",e))}async function N3(e){return(await $(W("/skills/discovered",e))).skills}async function S3(e,n,s){return $(W("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function C3(e,n,s){const i=new URLSearchParams;e&&i.set("q",e),i.set("limit",String(n));const r=i.size>0?`?${i.toString()}`:"";return $(W(`/skills/catalog${r}`,s))}async function E3(e,n){return(await $(W(`/skills/${encodeURIComponent(e)}/content`,n))).content}function Nu(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const i=s.toString();return $(`/chat/sessions${i?`?${i}`:""}`)}async function eN(e,n){const s=e.agentId.trim();if(!s)throw new Error("agentId is required");const i=e.modelProvider?.trim(),r=e.modelId?.trim();if(i&&!r||!i&&r)throw new Error("Both modelProvider and modelId must be provided together, or neither should be provided");const o=new URLSearchParams;return o.set("lookup","resume"),o.set("agentId",s),n&&o.set("projectId",n),i&&r&&(o.set("modelProvider",i),o.set("modelId",r)),{session:(await $(`/chat/sessions?${o.toString()}`)).sessions[0]??null}}function tN(e,n){return $(W("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function _3(e,n,s){return $(W(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function M3(e,n){return $(W(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Su(e,n,s){const i=new URLSearchParams;n?.limit!==void 0&&i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset)),n?.before&&i.set("before",n.before);const r=i.toString();return $(W(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function nN(e,n){return $(W(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function sN(e,n,s,i,r,o){const l=ds(W(`/chat/sessions/${encodeURIComponent(e)}/messages`,r)),c=new AbortController;let u=!1;const d=(m,h)=>{if(!(!m||!h))switch(m){case"thinking":try{s.onThinking?.(JSON.parse(h))}catch{s.onThinking?.(h)}break;case"text":try{s.onText?.(JSON.parse(h))}catch{s.onText?.(h)}break;case"tool_start":try{s.onToolStart?.(JSON.parse(h))}catch{}break;case"tool_end":try{s.onToolEnd?.(JSON.parse(h))}catch{}break;case"done":try{s.onDone?.(JSON.parse(h))}catch{s.onDone?.({messageId:""})}break;case"error":try{const f=JSON.parse(h);s.onError?.(f.message||f)}catch{s.onError?.(h||"Stream error")}break}};return(async()=>{try{const m=Array.isArray(i)&&i.length>0,h=m?(()=>{const j=new FormData;return j.append("content",n),i.forEach(E=>j.append("attachments",E)),j})():JSON.stringify({content:n}),f=await fetch(l,{method:"POST",headers:m?xi():xi({"Content-Type":"application/json"}),body:h,signal:c.signal});if(!f.ok){const j=await f.text();let E=`Request failed: ${f.status}`;try{E=JSON.parse(j).error||E}catch{}s.onError?.(E);return}if(!f.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected");const p=f.body.getReader(),g=new TextDecoder;let b="",v="",x=[];const y=(j,E=!1)=>{b+=j;const C=b.split(`
|
|
618
|
-
`);b=C.pop()||"",E&&b.length>0&&(C.push(b),b="");for(const w of C){const R=w.endsWith("\r")?w.slice(0,-1):w;if(R.startsWith("event:"))v=R.slice(6).trim();else if(R.startsWith("data:")){const S=R.slice(5);x.push(S.startsWith(" ")?S.slice(1):S)}else if(R===""){const S=x.join(`
|
|
619
|
-
`);d(v,S),v="",x=[]}}if(E&&v&&x.length>0){const w=x.join(`
|
|
620
|
-
`);d(v,w),v="",x=[]}};for(;;){const{done:j,value:E}=await p.read();if(j){y(g.decode(),!0);break}y(g.decode(E,{stream:!0}))}}catch(m){if(m instanceof DOMException&&m.name==="AbortError"){u||s.onError?.("Connection aborted");return}if(u)return;s.onError?.(m instanceof Error?m.message:"Connection error")}})(),{close:()=>{u=!0,c.abort()},isConnected:()=>!u}}function A3(e={},n){const s=new URLSearchParams;e.category&&s.set("category",e.category),e.status&&s.set("status",e.status),e.runId&&s.set("runId",e.runId),e.limit!==void 0&&s.set("limit",String(e.limit)),e.offset!==void 0&&s.set("offset",String(e.offset));const i=s.size>0?`?${s.toString()}`:"";return $(W(`/insights${i}`,n))}function R3(e,n){return $(W(`/insights/${encodeURIComponent(e)}/dismiss`,n),{method:"POST"})}function T3(e="manual",n,s){return $(W("/insights/run",s),{method:"POST",body:JSON.stringify({trigger:e,inputMetadata:n})})}function P3(e){return $(W("/insights/runs",e))}function I3(e,n){return $(W(`/insights/${encodeURIComponent(e)}/create-task`,n),{method:"POST"})}function $3(e={},n){const s=new URLSearchParams;e.q&&s.set("q",e.q),e.status&&s.set("status",e.status),e.limit!==void 0&&s.set("limit",String(e.limit));const i=s.size>0?`?${s.toString()}`:"";return $(W(`/research/runs${i}`,n))}function D3(e,n){return $(W("/research/runs",n),{method:"POST",body:JSON.stringify(e)})}function L3(e,n){return $(W(`/research/runs/${encodeURIComponent(e)}`,n))}function z3(e,n){return $(W(`/research/runs/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function O3(e,n){return $(W(`/research/runs/${encodeURIComponent(e)}/retry`,n),{method:"POST"})}function F3(e,n,s){return $(W(`/research/runs/${encodeURIComponent(e)}/export?format=${encodeURIComponent(n)}`,s))}function U3(e,n,s){return $(W(`/research/runs/${encodeURIComponent(e)}/create-task`,s),{method:"POST",body:JSON.stringify(n)})}function B3(e,n,s){return $(W(`/research/runs/${encodeURIComponent(e)}/attach-task`,s),{method:"POST",body:JSON.stringify(n)})}function iN(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 aN({node:e,showDetails:n=!1}){if(!e||e.type==="local")return t.jsx("div",{className:"node-status-indicator node-status-indicator--local",children:t.jsx("span",{className:"node-status-indicator__label",children:"Local"})});const{label:s,dotClass:i}=iN(e.status),r=e.status==="connecting";return t.jsxs("div",{className:"node-status-indicator node-status-indicator--remote",children:[t.jsx("span",{className:`node-status-indicator__dot ${i}`,children:r&&t.jsx("span",{className:"node-status-indicator__spinner"})}),t.jsx("span",{className:"node-status-indicator__name",children:e.name}),n&&t.jsxs("span",{className:"node-status-indicator__details",children:[e.type," · ",s]})]})}function rN(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Wi({status:e,showLabel:n=!1,className:s,compact:i=!1}){const r=rN(e);return t.jsxs("span",{className:`node-health-dot${i?" node-health-dot--compact":""}${s?` ${s}`:""}`,title:r,"aria-label":`Node status: ${r}`,children:[t.jsx("span",{className:`status-dot status-dot--${e}`}),n?t.jsx("span",{className:"node-health-dot__label",children:r}):null]})}const Cu=new Map,oN=6e4;function Gp(e){const[n,s]=a.useState([]),[i,r]=a.useState(!0),[o,l]=a.useState(null),c=a.useRef(!1),u=a.useRef(!1),d=a.useCallback(m=>n.filter(h=>h.slot.slotId===m),[n]);return a.useEffect(()=>{const m=e??"default";let h=!1;async function f(){const p=Cu.get(m);if(p&&Date.now()<p.expiresAt){if(h||u.current)return;s(p.slots),r(!1);return}!c.current&&r(!0),l(null);try{const b=await Xk(e);if(h||u.current)return;Cu.set(m,{slots:b,expiresAt:Date.now()+oN}),s(b),c.current=!0}catch(b){if(h||u.current)return;l(b instanceof Error?b.message:"Failed to fetch UI slots"),c.current=!0}finally{!h&&!u.current&&r(!1)}}return f(),()=>{h=!0}},[e]),a.useEffect(()=>{c.current=!1,u.current=!1},[e]),a.useEffect(()=>()=>{u.current=!0},[]),a.useMemo(()=>({slots:n,getSlotsForId:d,loading:i,error:o}),[n,d,i,o])}function dl({slotId:e,projectId:n}){const{getSlotsForId:s,loading:i,error:r}=Gp(n);if(i||r||!e)return null;const o=s(e);return o.length===0?null:t.jsx(ol,{level:"page",children:t.jsx(t.Fragment,{children:o.map(l=>t.jsx("div",{"data-plugin-slot":!0,"data-slot-id":l.slot.slotId,"data-plugin-id":l.pluginId,"data-component-path":l.slot.componentPath,"aria-label":l.slot.label},`${l.pluginId}-${l.slot.slotId}`))})})}function lN(){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 $a(){const[e,n]=a.useState(lN);return a.useEffect(()=>{if(typeof window>"u")return;const s=window.matchMedia("(max-width: 768px)"),i=window.matchMedia("(min-width: 769px) and (max-width: 1024px)"),r=()=>{s.matches?n("mobile"):i.matches?n("tablet"):n("desktop")};return s.addEventListener("change",r),i.addEventListener("change",r),()=>{s.removeEventListener("change",r),i.removeEventListener("change",r)}},[]),e}function Da(e){return e.replace(/\\/g,"/")}function kd(e){return e.replace(/[\\/]+$/g,"")}function Nd(e){const n=Da(kd(e));return n?n.split("/").filter(Boolean):[]}function Sd(e){const n=Da(kd(e));if(!n)return e;const s=n.split("/").filter(Boolean);return s[s.length-1]||n}function Jp(e,n){const s=Nd(e);return s.length===0?Da(e):s.slice(-2).join("/")}function cN(e){const n=Da(kd(e)),s=n.lastIndexOf("/");return s<0?"":n.slice(0,s+1)}function dN(e,n){return!e||e==="."?n:[...Nd(e),n].join("/")}function uN(e){const n=Nd(e);return n.length===0?".":(n.pop(),n.length===0?".":n.join("/"))}function H3(e){const n=Da(e),s=n.match(/^([A-Za-z]:)(?:\/(.*))?$/);if(s){const r=`${s[1]}/`,o=(s[2]??"").split("/").filter(Boolean),l=[{label:s[1],path:r}];for(let c=0;c<o.length;c+=1)l.push({label:o[c],path:`${r}${o.slice(0,c+1).join("/")}`});return l}if(n.startsWith("/")){const r=n.split("/").filter(Boolean),o=[{label:"/",path:"/"}];for(let l=0;l<r.length;l+=1)o.push({label:r[l],path:`/${r.slice(0,l+1).join("/")}`});return o}const i=n.split("/").filter(Boolean);return i.map((r,o)=>({label:r,path:i.slice(0,o+1).join("/")}))}const mN="dependency-graph-positions";function Yp(e){return`kb:${e??"default"}:${mN}`}function hN(e){if(typeof window>"u")return{};try{const n=window.localStorage.getItem(Yp(e));return n?JSON.parse(n)??{}:{}}catch{return{}}}function pN(e,n){typeof window>"u"||window.localStorage.setItem(Yp(e),JSON.stringify(n))}const fN=new Set(["triage","todo","in-progress","in-review"]),ra=18,Di=9,gN=3,bN=4,Eu=.5,oo=2,xN=2,_u=.4,Mu=2;function Au(e,n){const s=e.x-n.x,i=e.y-n.y;return Math.hypot(s,i)}function vN({context:e}){const[n,s]=a.useState(1),[i,r]=a.useState({x:0,y:0}),[o,l]=a.useState({}),[c,u]=a.useState(null),[d,m]=a.useState(null),h=a.useMemo(()=>hN(e.projectId),[e.projectId]),f=a.useRef(null),p=a.useRef(null),g=a.useMemo(()=>e.tasks.filter(M=>fN.has(M.column)),[e.tasks]),b=a.useMemo(()=>g.map((M,T)=>{const D=o[M.id]??h[M.id];return{task:M,x:D?.x??T%4*(ra+gN),y:D?.y??Math.floor(T/4)*(Di+bN)}}),[o,h,g]),v=a.useMemo(()=>new Map(b.map(M=>[M.task.id,M])),[b]),x=a.useMemo(()=>{const M=[];return b.forEach(T=>{(T.task.dependencies??[]).forEach(D=>{const K=v.get(D);K&&M.push({from:D,to:T.task.id,x1:K.x+ra,y1:K.y+Di/2,x2:T.x,y2:T.y+Di/2})})}),M},[v,b]),y=a.useMemo(()=>{if(b.length===0)return{minX:0,minY:0,width:ra*2,height:Di*2};const M=Math.min(...b.map(J=>J.x))-oo,T=Math.min(...b.map(J=>J.y))-oo,D=Math.max(...b.map(J=>J.x+ra))+oo,K=Math.max(...b.map(J=>J.y+Di))+oo;return{minX:M,minY:T,width:Math.max(ra*2,D-M),height:Math.max(Di*2,K-T)}},[b]),j=a.useMemo(()=>b.map(M=>({...M,renderX:M.x-y.minX,renderY:M.y-y.minY})),[y.minX,y.minY,b]),E=a.useMemo(()=>x.map(M=>({...M,renderX1:M.x1-y.minX,renderY1:M.y1-y.minY,renderX2:M.x2-y.minX,renderY2:M.y2-y.minY})),[y.minX,y.minY,x]),C=a.useMemo(()=>{const M=new Map,T=new Map;return x.forEach(D=>{M.set(D.from,(M.get(D.from)??new Set).add(D.to)),T.set(D.to,(T.get(D.to)??new Set).add(D.from))}),{downstream:M,upstream:T}},[x]),w=d??c,R=a.useMemo(()=>{if(!w)return null;const M=new Set([w]),T=(D,K)=>{const J=[D];for(;J.length>0;){const te=J.shift();te&&(K.get(te)??new Set).forEach(N=>{M.has(N)||(M.add(N),J.push(N))})}};return T(w,C.downstream),T(w,C.upstream),M},[C.downstream,C.upstream,w]),S=()=>{const M=f.current;if(!M)return;const T=Number.parseFloat(globalThis.getComputedStyle(document.documentElement).fontSize)||16,D=y.width*T,K=y.height*T,J=xN*T,te=Math.max(1,M.clientWidth-J*2),N=Math.max(1,M.clientHeight-J*2),z=Math.min(Mu,Math.max(_u,Math.min(te/D,N/K))),I=(M.clientWidth-D*z)/(2*T*z),k=(M.clientHeight-K*z)/(2*T*z);s(z),r({x:I,y:k})},O=(M,T)=>{l(D=>({...D,[M]:T})),pN(e.projectId,{...h,...o,[M]:T})},_=(M,T)=>{if(u(K=>K===M?null:M),T.button!==0)return;T.preventDefault(),T.stopPropagation();const D=v.get(M);D&&(p.current={kind:"node",taskId:M,startPointer:{x:T.clientX,y:T.clientY},startNode:{x:D.x,y:D.y},moved:!1},T.currentTarget.setPointerCapture(T.pointerId))},P=M=>{M.button===0&&(p.current={kind:"pan",startPointer:{x:M.clientX,y:M.clientY},startPan:i,moved:!1},M.currentTarget.setPointerCapture(M.pointerId))},U=M=>{const T=p.current;if(!T)return;const D={x:(M.clientX-T.startPointer.x)/16,y:(M.clientY-T.startPointer.y)/16};if(T.kind==="node"){if(Au({x:0,y:0},D)>Eu&&!T.moved&&(T.moved=!0),!T.moved)return;l(te=>({...te,[T.taskId]:{x:T.startNode.x+D.x/n,y:T.startNode.y+D.y/n}}));return}Au({x:0,y:0},D)>Eu&&!T.moved&&(T.moved=!0),T.moved&&r({x:T.startPan.x+D.x,y:T.startPan.y+D.y})},G=M=>{const T=p.current;if(p.current=null,!!T){if(T.kind==="node"){const D=v.get(T.taskId);if(!D)return;if(!T.moved){e.openTaskDetail(D.task);return}O(T.taskId,{x:D.x,y:D.y})}M.currentTarget.releasePointerCapture(M.pointerId)}};return t.jsxs("section",{className:"dependency-graph-view",children:[t.jsxs("div",{className:"dependency-graph-controls",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>s(M=>Math.min(M+.1,Mu)),children:"Zoom In"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>s(M=>Math.max(M-.1,_u)),children:"Zoom Out"}),t.jsx("button",{className:"btn btn-sm",onClick:S,children:"Fit"})]}),t.jsx("div",{className:"dependency-graph-canvas",ref:f,onPointerDown:P,onPointerMove:U,onPointerUp:G,children:t.jsxs("div",{className:"dependency-graph-scene",style:{width:`${y.width}rem`,height:`${y.height}rem`,transform:`translate(${i.x}rem, ${i.y}rem) scale(${n})`,transformOrigin:"top left"},children:[t.jsx("svg",{className:"dependency-graph-edges",viewBox:`0 0 ${y.width} ${y.height}`,children:E.map(M=>t.jsx("line",{x1:M.renderX1,y1:M.renderY1,x2:M.renderX2,y2:M.renderY2,className:`dependency-graph-edge${R?R.has(M.from)&&R.has(M.to)?" is-related":" is-dimmed":""}`},`${M.from}-${M.to}`))}),j.map(M=>t.jsx("div",{className:`dependency-graph-node${c===M.task.id?" is-selected":""}${R?R.has(M.task.id)?" is-related":" is-dimmed":""}`,style:{width:`${ra}rem`,minHeight:`${Di}rem`,transform:`translate(${M.renderX}rem, ${M.renderY}rem)`},onPointerDown:T=>_(M.task.id,T),onPointerEnter:()=>m(M.task.id),onPointerLeave:()=>m(T=>T===M.task.id?null:T),children:e.renderTaskCard(M.task)},M.task.id))]})})]})}const yN=[{pluginId:"fusion-plugin-dependency-graph",viewId:"graph",component:vN}];function Qp(e,n){return`plugin:${e}:${n}`}function wN(e){if(!e.startsWith("plugin:"))return null;const[,n,...s]=e.split(":"),i=s.join(":");return!n||!i?null:{pluginId:n,viewId:i}}function jN(e,n){return yN.find(i=>i.pluginId===e&&i.viewId===n)?.component??null}function kN({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(rl,{}),"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 Xp={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function NN({projects:e,currentProject:n,onViewAll:s,onSelectProject:i}){const[r,o]=a.useState(!1),l=a.useRef(null);a.useEffect(()=>{if(!r)return;const u=d=>{l.current&&!l.current.contains(d.target)&&o(!1)};return document.addEventListener("mousedown",u),()=>document.removeEventListener("mousedown",u)},[r]),a.useEffect(()=>{if(!r)return;const u=d=>{d.key==="Escape"&&o(!1)};return document.addEventListener("keydown",u),()=>document.removeEventListener("keydown",u)},[r]);const c=a.useCallback(u=>{i?.(u),o(!1)},[i]);return t.jsx("div",{className:"project-selector",ref:l,children:e.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:`project-selector-trigger${r?" project-selector-trigger--open":""}`,onClick:()=>o(u=>!u),title:n?.name?`Switch project (current: ${n.name})`:"Switch project","aria-label":"Switch project","aria-expanded":r,"aria-haspopup":"listbox","data-testid":"project-selector-trigger",children:[t.jsx("span",{className:"project-selector-trigger-label",children:n?.name??"Projects"}),t.jsx(Yt,{size:12,className:`project-selector-chevron${r?" project-selector-chevron--open":""}`})]}),r&&t.jsxs("div",{className:"project-selector-dropdown",role:"listbox","aria-label":"Select project","data-testid":"project-selector-dropdown",children:[e.map(u=>{const d=n?.id===u.id,m=Xp[u.status]?.color;return t.jsxs("button",{className:`project-selector-item${d?" project-selector-item--current":""}`,onClick:()=>c(u),role:"option","aria-selected":d,children:[t.jsx("span",{className:"project-selector-dot",style:{backgroundColor:m||"var(--text-muted)"}}),t.jsxs("div",{className:"project-selector-info",children:[t.jsx("span",{className:"project-selector-name",children:u.name}),t.jsx("span",{className:"project-selector-path",children:Jp(u.path)})]}),d&&t.jsx(Jn,{size:14,className:"project-selector-check"})]},u.id)}),t.jsx("div",{className:"project-selector-divider",role:"presentation"}),t.jsx("button",{className:"project-selector-manage",onClick:()=>{s(),o(!1)},"data-testid":"manage-projects-action",children:"Manage Projects"})]})]})})}function Ru({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 SN({onOpenSettings:e,onOpenGitHubImport:n,onOpenPlanning:s,onResumePlanning:i,activePlanningSessionCount:r=0,onOpenUsage:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:u,mailboxUnreadCount:d=0,onOpenSchedules:m,onOpenGitManager:h,onOpenNodes:f,showNodesButton:p,onOpenWorkflowSteps:g,onOpenScripts:b,onRunScript:v,onToggleTerminal:x,onOpenFiles:y,filesOpen:j,globalPaused:E,enginePaused:C,onToggleGlobalPause:w,onToggleEnginePause:R,view:S="board",onChangeView:O,showSkillsTab:_,showAgentsTab:P,searchQuery:U="",onSearchChange:G,projects:M=[],currentProject:T,onSelectProject:D,onViewAllProjects:K,projectId:J,isElectron:te=!1,mobileNavEnabled:N,availableNodes:z=[],currentNode:I,onSelectNode:k,isRemote:H=!1,experimentalFeatures:Q,pluginDashboardViews:ue=[]}){const be=$a(),V=be==="mobile",B=V||be==="tablet",Y=V&&N,[X,he]=a.useState(!1),[de,me]=a.useState(!1),[se,_e]=a.useState(!1),[Fe,Te]=a.useState(!1),[st,nt]=a.useState(!1),[qe,Xe]=a.useState(!1),[$e,Ue]=a.useState(!1),[oe,je]=a.useState(!1),[ie,Ae]=a.useState(!1),[Le,we]=a.useState(!1),[Ee,Ve]=a.useState(!1),[rt,xe]=a.useState({}),[ce,Pe]=a.useState(!1),[pe,Re]=a.useState(-1),[Qe,Ie]=a.useState(null),[bt,ee]=a.useState({}),[re,Se]=a.useState(!1),ot=a.useRef(null),ne=a.useRef(null),Ze=a.useRef(null),ft=a.useRef(null),gt=a.useRef(null),St=a.useRef(null),Nt=a.useRef(!1),pt=a.useRef(null),kt=a.useRef(null),Ht=a.useRef(null),$t=a.useRef(null),Tt=a.useRef(null),Mt=a.useRef(null),Ot=a.useRef(null),zt=a.useRef(null),Ft=a.useRef(!1),Et=a.useMemo(()=>z.filter(Ne=>Ne.type==="remote"),[z]),Pt=Et.length>0,Dt=a.useMemo(()=>Object.entries(rt).sort(([Ne],[et])=>Ne.localeCompare(et)),[rt]),Wt=Dt.length>0,It=Dt.length+(Wt?1:0),Rt=a.useMemo(()=>Object.entries(bt).sort(([Ne],[et])=>Ne.localeCompare(et)),[bt]),fe=a.useMemo(()=>!!(Q?.researchView||Q?.todoView||Q?.insights||Q?.roadmap||_||Q?.memoryView||Q?.devServerView||!Y||ue.some(Ne=>Ne.view.placement!=="primary")),[Q,_,Y,ue]),Oe=a.useCallback(()=>{const Ne=window.visualViewport;return Ne&&Ne.width>0&&Ne.height>0?{width:Ne.width,height:Ne.height,offsetTop:Ne.offsetTop,offsetLeft:Ne.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),ut=a.useCallback(()=>{const Ne=Ot.current;if(!Ne)return;const et=Ne.getBoundingClientRect(),ln=zt.current,{width:wn,height:Gn,offsetTop:Tn,offsetLeft:Un}=Oe(),sn=16,un=16,Bn=6,Sn=ln?.offsetWidth||Math.max(et.width,260),an=Math.min(Sn,Math.max(wn-sn*2,160)),Dn=ln?.offsetHeight||280,Ln=Math.min(Dn,Math.max(Gn-un*2,160)),ss=et.top-Tn,Pn=et.bottom-Tn,nn=et.right-Un,vt=Gn-Pn,rn=ss,A=vt<Ln&&rn>vt,le=Math.min(Math.max(nn-an,sn),wn-sn-an)+Un,ye=A?Math.max(un+Tn,ss-Ln-Bn+Tn):Math.min(Pn+Bn+Tn,Gn+Tn-un-Ln);Ie({top:ye,left:le,width:an})},[Oe]),L=a.useCallback((Ne,et)=>{v?.(Ne,et),Ve(!1),Re(-1)},[v]),F=a.useCallback(()=>{b?.(),Ve(!1),Re(-1)},[b]),ge=a.useCallback(Ne=>{switch(Ne.key){case"ArrowDown":Ne.preventDefault(),It>0&&Re(et=>et<It-1?et+1:0);break;case"ArrowUp":Ne.preventDefault(),It>0&&Re(et=>et>0?et-1:It-1);break;case"Enter":if(Ne.preventDefault(),pe>=0)if(pe<Dt.length){const[et,ln]=Dt[pe];L(et,ln)}else Wt&&pe===Dt.length&&F();break;case"Home":Ne.preventDefault(),It>0&&Re(0);break;case"End":Ne.preventDefault(),It>0&&Re(It-1);break}},[F,L,pe,Dt,Wt,It]);a.useEffect(()=>{Nt.current=st},[st]),a.useEffect(()=>{Ft.current=Ee},[Ee]),a.useEffect(()=>{if(!st||!B)return;let Ne=!1;return Se(!0),_r(J).then(et=>{Ne||ee(et)}).catch(()=>{Ne||ee({})}).finally(()=>{Ne||Se(!1)}),()=>{Ne=!0}},[st,B,J]),a.useEffect(()=>{if(!Ee||B)return;let Ne=!1;return Pe(!0),_r(J).then(et=>{Ne||xe(et)}).catch(()=>{Ne||xe({})}).finally(()=>{Ne||Pe(!1)}),()=>{Ne=!0}},[Ee,B,J]),a.useEffect(()=>{if(!Ee)return;const Ne=et=>{Mt.current&&!Mt.current.contains(et.target)&&Ve(!1)};return document.addEventListener("mousedown",Ne),()=>document.removeEventListener("mousedown",Ne)},[Ee]),a.useEffect(()=>{if(!Ee)return;const Ne=et=>{et.key==="Escape"&&(Ve(!1),Ot.current?.focus())};return document.addEventListener("keydown",Ne),()=>document.removeEventListener("keydown",Ne)},[Ee]),a.useEffect(()=>{if(Ee){Re(-1);const Ne=window.setTimeout(()=>zt.current?.focus(),0);return()=>window.clearTimeout(Ne)}Ie(null)},[Ee]),a.useEffect(()=>{if(!Ee)return;const Ne=requestAnimationFrame(()=>{ut()});return()=>cancelAnimationFrame(Ne)},[Ee,ce,Dt.length,Wt,ut]),a.useEffect(()=>{if(!Ee)return;const Ne=()=>ut();window.addEventListener("resize",Ne),window.addEventListener("scroll",Ne,!0);const et=window.visualViewport;return et&&(et.addEventListener("resize",Ne),et.addEventListener("scroll",Ne)),()=>{window.removeEventListener("resize",Ne),window.removeEventListener("scroll",Ne,!0),et&&(et.removeEventListener("resize",Ne),et.removeEventListener("scroll",Ne))}},[Ee,ut]),a.useEffect(()=>{B&&(Ve(!1),Re(-1))},[B]);const ze=X||U.length>0,Be=(de||U.length>0)&&!se,Ke=(S==="board"||S==="list")&&!V&&G&&!se&&U.length===0,dt=(S==="board"||S==="list")&&!V&&G;a.useEffect(()=>{U===""&&_e(!1)},[U]),a.useEffect(()=>{if(!Fe)return;const Ne=et=>{ne.current&&!ne.current.contains(et.target)&&ot.current&&!ot.current.contains(et.target)&&Te(!1)};return document.addEventListener("mousedown",Ne),()=>document.removeEventListener("mousedown",Ne)},[Fe]),a.useEffect(()=>{if(!ie)return;const Ne=et=>{ft.current&&!ft.current.contains(et.target)&&Ze.current&&!Ze.current.contains(et.target)&&Ae(!1)};return document.addEventListener("mousedown",Ne),()=>document.removeEventListener("mousedown",Ne)},[ie]),a.useEffect(()=>{if(!qe)return;const Ne=et=>{pt.current&&!pt.current.contains(et.target)&&Xe(!1)};return document.addEventListener("mousedown",Ne),()=>document.removeEventListener("mousedown",Ne)},[qe]),a.useEffect(()=>{const Ne=et=>{if(et.key==="Escape"){if(je(!1),Ae(!1),Nt.current){nt(!1);return}if(Ft.current){Ve(!1),Ot.current?.focus();return}Te(!1),he(!1),Xe(!1),Ue(!1)}};return document.addEventListener("keydown",Ne),()=>document.removeEventListener("keydown",Ne)},[]),a.useEffect(()=>{if(!$e)return;const Ne=et=>{kt.current&&!kt.current.contains(et.target)&&Ue(!1)};return document.addEventListener("mousedown",Ne),()=>document.removeEventListener("mousedown",Ne)},[$e]),a.useEffect(()=>{if(!Le)return;const Ne=et=>{Tt.current&&!Tt.current.contains(et.target)&&we(!1)};return document.addEventListener("mousedown",Ne),()=>document.removeEventListener("mousedown",Ne)},[Le]),a.useEffect(()=>{if(!Le)return;const Ne=et=>{et.key==="Escape"&&we(!1)};return document.addEventListener("keydown",Ne),()=>document.removeEventListener("keydown",Ne)},[Le]),a.useEffect(()=>{if(!oe)return;const Ne=et=>{Ht.current&&!Ht.current.contains(et.target)&&$t.current&&!$t.current.contains(et.target)&&je(!1)};return document.addEventListener("mousedown",Ne),()=>document.removeEventListener("mousedown",Ne)},[oe]);const Xt=a.useCallback(()=>{he(Ne=>!Ne)},[]),Cn=a.useCallback(()=>{me(!0),_e(!1)},[]),pn=a.useCallback(()=>{me(!1),_e(!0),G&&G("")},[G]),Kn=a.useCallback(()=>{Te(Ne=>!Ne)},[]),Lt=a.useCallback(Ne=>{Ne&&Ne(),Te(!1),nt(!1)},[]),Zt=a.useCallback(()=>{he(!1),G&&G("")},[G]);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"})]}),V&&M.length>=1&&D&&t.jsxs("div",{className:"mobile-project-switch",ref:kt,children:[t.jsx("button",{className:`mobile-project-switch-trigger${$e?" mobile-project-switch-trigger--open":""}`,onClick:()=>Ue(Ne=>!Ne),title:"Switch project","aria-label":"Switch project","aria-expanded":$e,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:t.jsx(Yt,{size:14,className:`mobile-project-switch-chevron${$e?" mobile-project-switch-chevron--open":""}`})}),$e&&t.jsx("div",{className:"mobile-project-switch-dropdown",role:"listbox","aria-label":"Select project","data-testid":"mobile-project-switch-dropdown",children:M.map(Ne=>{const et=T?.id===Ne.id,ln=Xp[Ne.status]?.color;return t.jsxs("button",{className:`mobile-project-switch-item${et?" mobile-project-switch-item--current":""}`,onClick:()=>{D(Ne),Ue(!1)},role:"option","aria-selected":et,"data-testid":`mobile-project-switch-item-${Ne.id}`,children:[t.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:ln||"var(--text-muted)"}}),t.jsxs("div",{className:"mobile-project-switch-info",children:[t.jsx("span",{className:"mobile-project-switch-name",children:Ne.name}),t.jsx("span",{className:"mobile-project-switch-path",children:Jp(Ne.path)})]}),et&&t.jsx(Jn,{size:14,className:"mobile-project-switch-check"})]},Ne.id)})})]}),!B&&M.length>=1&&K&&t.jsx(NN,{projects:M,currentProject:T??null,onViewAll:K,onSelectProject:D}),Pt&&t.jsxs("div",{className:`header-node-selector${V?" header-node-selector--mobile":""}`,ref:V?void 0:pt,children:[t.jsx(aN,{node:I??null,showDetails:!V}),!V&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:`btn-icon node-selector-trigger${qe?" node-selector-trigger--open":""}`,onClick:()=>Xe(Ne=>!Ne),title:"Switch node","aria-label":"Switch node","aria-expanded":qe,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:t.jsx(gn,{size:12,className:`node-selector-chevron${qe?" node-selector-chevron--open":""}`})}),qe&&t.jsxs("div",{className:"node-selector-dropdown",role:"listbox","aria-label":"Select node",children:[t.jsxs("button",{className:`node-selector-option${H?"":" node-selector-option--active"}`,onClick:()=>{k?.(null),Xe(!1)},role:"option","aria-selected":!H,"data-testid":"node-option-local",children:[t.jsx(Wi,{status:"online",compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:"Local"})]}),Et.map(Ne=>t.jsxs("button",{className:`node-selector-option${I?.id===Ne.id?" node-selector-option--active":""}`,onClick:()=>{k?.(Ne),Xe(!1)},role:"option","aria-selected":I?.id===Ne.id,"data-testid":`node-option-${Ne.id}`,children:[t.jsx(Wi,{status:Ne.status,compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:Ne.name}),t.jsx("span",{className:"node-selector-option-status",children:Ne.status})]},Ne.id))]})]})]})]}),t.jsxs("div",{className:"header-actions",children:[Y&&O&&(S==="board"||S==="list")&&t.jsxs("div",{className:"view-toggle","data-testid":"mobile-view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${S==="board"?" active":""}`,onClick:()=>O("board"),title:"Board view","aria-label":"Board view","aria-pressed":S==="board","data-testid":"mobile-view-toggle-board",children:t.jsx(Vi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${S==="list"?" active":""}`,onClick:()=>O("list"),title:"List view","aria-label":"List view","aria-pressed":S==="list","data-testid":"mobile-view-toggle-list",children:t.jsx(Lc,{size:16})})]}),G&&V&&(Y||S==="board"||S==="list")&&!ze&&t.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:Xt,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:t.jsx(Ni,{size:16})}),Ke&&t.jsx("button",{className:"btn-icon",onClick:Cn,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:t.jsx(Ni,{size:16})}),V&&Y&&o&&t.jsx("button",{className:"btn-icon",onClick:Ne=>o(Ne.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"mobile-header-usage-btn",children:t.jsx(Ds,{size:16})}),!Y&&O&&t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${S==="board"?" active":""}`,onClick:()=>O("board"),title:"Board view","aria-label":"Board view","aria-pressed":S==="board",children:t.jsx(Vi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${S==="list"?" active":""}`,onClick:()=>O("list"),title:"List view","aria-label":"List view","aria-pressed":S==="list",children:t.jsx(Lc,{size:16})}),P&&t.jsx("button",{className:`view-toggle-btn${S==="agents"?" active":""}`,onClick:()=>O("agents"),title:"Agents view","aria-label":"Agents view","aria-pressed":S==="agents",children:t.jsx(En,{size:16})}),t.jsx("button",{className:`view-toggle-btn${S==="missions"?" active":""}`,onClick:()=>O("missions"),title:"Missions view","aria-label":"Missions view","aria-pressed":S==="missions",children:t.jsx(ks,{size:16})}),t.jsx("button",{className:`view-toggle-btn${S==="chat"?" active":""}`,onClick:()=>O("chat"),title:"Chat view","aria-label":"Chat view","aria-pressed":S==="chat",children:t.jsx(Si,{size:16})}),t.jsx("button",{className:`view-toggle-btn${S==="documents"?" active":""}`,onClick:()=>O("documents"),title:"Documents view","aria-label":"Documents view","aria-pressed":S==="documents",children:t.jsx(Hi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${S==="mailbox"?" active":""}`,onClick:()=>O("mailbox"),title:"Mailbox view","aria-label":"Mailbox view","aria-pressed":S==="mailbox",children:t.jsx(ya,{size:16})}),fe&&t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:$t,className:`view-toggle-btn${["research","skills","roadmaps","insights","memory","dev-server","devserver"].includes(S)||Q?.todoView&&S==="todos"||S.startsWith("plugin:")?" active":""}`,onClick:()=>je(Ne=>!Ne),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":oe,"data-testid":"view-toggle-overflow-trigger",children:t.jsx(Yt,{size:12})}),oe&&t.jsxs("div",{ref:Ht,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[Q?.researchView&&t.jsxs("button",{className:`view-toggle-overflow-item${S==="research"?" active":""}`,onClick:()=>{O("research"),je(!1)},role:"menuitem","data-testid":"view-overflow-research",children:[t.jsx(Ni,{size:14}),t.jsx("span",{children:"Research"})]}),Q?.insights&&t.jsxs("button",{className:`view-toggle-overflow-item${S==="insights"?" active":""}`,onClick:()=>{O("insights"),je(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[t.jsx(cs,{size:14}),t.jsx("span",{children:"Insights"})]}),Q?.roadmap&&t.jsxs("button",{className:`view-toggle-overflow-item${S==="roadmaps"?" active":""}`,onClick:()=>{O("roadmaps"),je(!1)},role:"menuitem","data-testid":"view-overflow-roadmaps",children:[t.jsx(zc,{size:14}),t.jsx("span",{children:"Roadmaps"})]}),_&&t.jsxs("button",{className:`view-toggle-overflow-item${S==="skills"?" active":""}`,onClick:()=>{O("skills"),je(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[t.jsx(es,{size:14}),t.jsx("span",{children:"Skills"})]}),Q?.memoryView&&t.jsxs("button",{className:`view-toggle-overflow-item${S==="memory"?" active":""}`,onClick:()=>{O("memory"),je(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[t.jsx(Do,{size:14}),t.jsx("span",{children:"Memory"})]}),Q?.devServerView&&t.jsxs("button",{className:`view-toggle-overflow-item${S==="dev-server"||S==="devserver"?" active":""}`,onClick:()=>{O("devserver"),je(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[t.jsx(kr,{size:14}),t.jsx("span",{children:"Dev Server"}),t.jsx("span",{className:"visually-hidden","data-testid":"view-toggle-dev-server"})]}),Q?.todoView&&t.jsxs("button",{className:`view-toggle-overflow-item${S==="todos"?" active":""}`,onClick:()=>{O("todos"),je(!1)},role:"menuitem","data-testid":"view-overflow-todos",children:[t.jsx(Rp,{size:14}),t.jsx("span",{children:"Todos"})]}),ue.filter(Ne=>Ne.view.placement!=="primary").sort((Ne,et)=>(Ne.view.order??Number.MAX_SAFE_INTEGER)-(et.view.order??Number.MAX_SAFE_INTEGER)).map(Ne=>{const et=Qp(Ne.pluginId,Ne.view.viewId);return t.jsxs("button",{className:`view-toggle-overflow-item${S===et?" active":""}`,onClick:()=>{O(et),je(!1)},role:"menuitem","data-testid":`view-overflow-plugin-${Ne.pluginId}-${Ne.view.viewId}`,children:[t.jsx(zo,{size:14}),t.jsx("span",{children:Ne.view.label})]},`${Ne.pluginId}:${Ne.view.viewId}`)})]})]})]}),!B&&o&&t.jsx("button",{className:"btn-icon",onClick:Ne=>o(Ne.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"desktop-header-usage-btn",children:t.jsx(Ds,{size:16})}),!B&&c&&t.jsx("button",{className:"btn-icon",onClick:c,title:"System Stats","data-testid":"desktop-header-system-stats-btn",children:t.jsx(kr,{size:16})}),!B&&l&&t.jsx("button",{className:"btn-icon",onClick:l,title:"View Activity Log",children:t.jsx(jr,{size:16})}),!B&&!te&&t.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:t.jsx(Ru,{size:16})}),!B&&t.jsxs("button",{className:`btn-icon${r>0?" btn-icon--has-indicator":""}`,onClick:r>0&&i?i:s,title:r>0?"Resume planning session":"Create a task with AI planning","data-testid":"planning-btn",style:{position:"relative"},children:[t.jsx(ri,{size:16}),r>0&&t.jsx("span",{className:"header-badge header-badge--pulse","data-testid":"planning-badge","aria-label":`${r} active planning session${r!==1?"s":""}`,children:r})]}),!B&&t.jsxs("div",{className:"terminal-split-btn",ref:Mt,children:[t.jsx("button",{className:"btn-icon btn-icon--terminal terminal-split-btn__main",onClick:x,title:"Open Terminal","data-testid":"terminal-toggle-btn",children:t.jsx(gi,{size:16})}),b&&v&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"terminal-split-btn__divider"}),t.jsx("button",{ref:Ot,className:`btn-icon terminal-split-btn__chevron${Ee?" btn-icon--active":""}`,onClick:()=>Ve(Ne=>!Ne),title:"Scripts","aria-haspopup":"listbox","aria-expanded":Ee,"aria-label":"Quick scripts","data-testid":"scripts-btn",children:t.jsx(Yt,{size:12,className:`quick-scripts-dropdown__trigger-chevron${Ee?" rotate":""}`})}),Ee&&t.jsx("div",{ref:zt,tabIndex:-1,className:"quick-scripts-dropdown__menu",role:"listbox","aria-label":"Scripts",onKeyDown:ge,"data-testid":"quick-scripts-dropdown",style:Qe?{position:"fixed",top:`${Qe.top}px`,left:`${Qe.left}px`,width:`${Qe.width}px`,right:"auto"}:void 0,children:ce?t.jsxs("div",{className:"quick-scripts-dropdown__loading","data-testid":"quick-scripts-loading",children:[t.jsx(lt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts..."})]}):Dt.length===0?t.jsxs("div",{className:"quick-scripts-dropdown__empty","data-testid":"quick-scripts-empty",children:[t.jsx("div",{className:"quick-scripts-dropdown__empty-icon",children:t.jsx(gi,{size:16})}),t.jsx("p",{children:"No scripts configured"}),t.jsx("button",{className:"quick-scripts-dropdown__empty-action btn",onClick:F,children:"Add your first script"})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-scripts-dropdown__list",children:Dt.map(([Ne,et],ln)=>t.jsxs("button",{className:`quick-scripts-dropdown__item ${pe===ln?"highlighted":""}`,onClick:()=>L(Ne,et),role:"option","aria-selected":pe===ln,"data-testid":`quick-script-item-${Ne}`,children:[t.jsx(_n,{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:Ne}),t.jsx("span",{className:"quick-scripts-dropdown__item-command",title:et,children:et.length>50?`${et.slice(0,50)}...`:et})]})]},Ne))}),t.jsx("div",{className:"quick-scripts-dropdown__footer",children:t.jsxs("button",{className:`quick-scripts-dropdown__manage ${Wt&&pe===Dt.length?"highlighted":""}`,onClick:F,"data-testid":"quick-scripts-manage",children:[t.jsx(br,{size:14}),t.jsx("span",{children:"Manage Scripts..."})]})})]})})]})]}),!B&&y&&t.jsx("button",{className:`btn-icon${j?" btn-icon--active":""}`,onClick:y,title:"Browse files","data-testid":"files-toggle-btn",children:t.jsx(ts,{size:16})}),!B&&h&&t.jsx("button",{className:"btn-icon",onClick:h,title:"Git Manager","data-testid":"git-manager-btn",children:t.jsx(Ks,{size:16})}),!B&&g&&t.jsx("button",{className:"btn-icon",onClick:g,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:t.jsx(Fc,{size:16})}),!B&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{ref:Ze,className:"btn-icon",onClick:()=>Ae(Ne=>!Ne),title:"More actions","aria-label":"More actions","aria-expanded":ie,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:t.jsx(Ic,{size:16})}),ie&&t.jsxs("div",{ref:ft,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[f&&p!==!1&&t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{f(),Ae(!1)},role:"menuitem","data-testid":"desktop-overflow-nodes-btn",children:[t.jsx(Nr,{size:14}),t.jsx("span",{children:"Nodes"})]}),t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{Lt(m),Ae(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[t.jsx(Ei,{size:14}),t.jsx("span",{children:"Automation"})]})]})]}),t.jsxs("div",{className:"engine-control-split-btn",ref:Tt,children:[t.jsx("button",{className:`btn-icon engine-control-split-btn__main${E?" btn-icon--stopped":""}`,onClick:w,title:E?"Start AI engine":"Stop AI engine","data-testid":"engine-control-main-btn",children:E?t.jsx(_n,{size:16}):t.jsx(Cs,{size:16})}),t.jsx("span",{className:"engine-control-split-btn__divider"}),t.jsx("button",{className:`btn-icon engine-control-split-btn__chevron${Le?" btn-icon--active":""}`,onClick:()=>we(Ne=>!Ne),title:"Engine options","aria-haspopup":"menu","aria-expanded":Le,"data-testid":"engine-control-chevron-btn",children:t.jsx(Yt,{size:12})}),Le&&t.jsx("div",{className:"engine-control-split-btn__menu",role:"menu",children:t.jsxs("button",{className:`engine-control-split-btn__menu-item${C?" engine-control-split-btn__menu-item--active":""}`,onClick:()=>{R?.(),we(!1)},role:"menuitem",title:C?"Resume scheduling":"Pause triage",disabled:!!E,"data-testid":"engine-control-pause-triage-btn",children:[C?t.jsx(_n,{size:14}):t.jsx(Vs,{size:14}),t.jsx("span",{children:C?"Resume scheduling":"Pause triage"})]})})]}),!B&&t.jsx("button",{className:"btn-icon",onClick:e,title:"Settings",children:t.jsx(br,{size:16})}),t.jsx(dl,{slotId:"header-action",projectId:J}),B&&!Y&&t.jsx("button",{ref:ot,className:"btn-icon compact-overflow-trigger",onClick:Kn,title:"More header actions","aria-label":"More header actions","aria-expanded":Fe,"aria-haspopup":"menu",children:t.jsx(Ic,{size:16})}),B&&!Y&&Fe&&t.jsxs("div",{ref:ne,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[M.length>=1&&K&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Lt(K),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[t.jsx(zo,{size:16}),t.jsx("span",{children:"Projects"})]}),y&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Lt(y),role:"menuitem","data-testid":"overflow-files-btn",children:[t.jsx(ts,{size:16}),t.jsx("span",{children:"Browse Files"})]}),t.jsxs("button",{className:`mobile-overflow-item${r>0?" mobile-overflow-item--has-indicator":""}`,onClick:()=>Lt(r>0&&i?i:s),role:"menuitem","data-testid":"overflow-planning-btn",children:[t.jsxs("span",{className:"mobile-overflow-icon-wrapper",children:[t.jsx(ri,{size:16}),r>0&&t.jsx("span",{className:"header-badge header-badge--pulse","data-testid":"overflow-planning-badge",children:r})]}),t.jsx("span",{children:r>0?`Resume planning session (${r})`:"Create a task with AI planning"})]}),h&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Lt(h),role:"menuitem","data-testid":"overflow-git-btn",children:[t.jsx(Ks,{size:16}),t.jsx("span",{children:"Git Manager"})]}),f&&p!==!1&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Lt(f),role:"menuitem","data-testid":"overflow-nodes-btn",children:[t.jsx(Nr,{size:16}),t.jsx("span",{children:"Nodes"})]}),!te&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Lt(n),role:"menuitem",children:[t.jsx(Ru,{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:()=>Lt(x),role:"menuitem","data-testid":"overflow-terminal-primary-btn",children:[t.jsx(gi,{size:16}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{className:"mobile-overflow-split-toggle",onClick:()=>nt(Ne=>!Ne),role:"menuitem","aria-expanded":st,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:t.jsx(gn,{size:14,className:`mobile-overflow-chevron${st?" mobile-overflow-chevron--open":""}`})})]}),st&&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(lt,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):Rt.length>0?t.jsxs(t.Fragment,{children:[Rt.map(([Ne,et])=>t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{v&&v(Ne,et),Te(!1),nt(!1)},role:"menuitem","data-testid":`overflow-script-item-${Ne}`,children:[t.jsx(_n,{size:14}),t.jsx("span",{children:Ne})]},Ne)),b&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>Lt(b),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(qs,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):b&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>Lt(b),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(qs,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Lt(m),role:"menuitem","data-testid":"overflow-schedules-btn",children:[t.jsx(Ei,{size:16}),t.jsx("span",{children:"Automation"})]}),l&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Lt(l),role:"menuitem","data-testid":"overflow-activity-log-btn",children:[t.jsx(jr,{size:16}),t.jsx("span",{children:"View Activity Log"})]}),u&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Lt(u),role:"menuitem","data-testid":"overflow-mailbox-btn",children:[t.jsx(ya,{size:16}),t.jsxs("span",{children:["Mailbox",d>0?` (${d})`:""]})]}),o&&t.jsxs("button",{className:"mobile-overflow-item",onClick:Ne=>Lt(()=>o(Ne.currentTarget.getBoundingClientRect())),role:"menuitem","data-testid":"overflow-usage-btn",children:[t.jsx(Ds,{size:16}),t.jsx("span",{children:"View Usage"})]}),g&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Lt(g),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[t.jsx(Fc,{size:16}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Lt(e),role:"menuitem",children:[t.jsx(br,{size:16}),t.jsx("span",{children:"Settings"})]})]})]})]}),dt&&Be&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{className:"header-search",children:[t.jsx(Ni,{size:14,className:"header-search-icon"}),t.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:U,onChange:Ne=>G(Ne.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:pn,"aria-label":"Close search",children:t.jsx(qt,{size:14})})]})}),G&&V&&ze&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{ref:gt,className:"header-search mobile-search-expanded",children:[t.jsx(Ni,{size:14,className:"header-search-icon"}),t.jsx("input",{ref:St,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:U,onChange:Ne=>G(Ne.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:Zt,"aria-label":"Close search",children:t.jsx(qt,{size:14})})]})})]})}const CN={themeMode:"dark",colorTheme:"default",dashboardFontScalePct:100,defaultProvider:void 0,defaultModelId:void 0,fallbackProvider:void 0,fallbackModelId:void 0,defaultThinkingLevel:void 0,ntfyEnabled:!1,ntfyTopic:void 0,ntfyBaseUrl:void 0,ntfyEvents:["in-review","merged","failed","awaiting-approval","awaiting-user-review","planning-awaiting-input","gridlock"],ntfyDashboardHost:void 0,webhookEnabled:!1,webhookUrl:void 0,webhookFormat:"generic",webhookEvents:[],notificationProviders:[],customProviders:[],defaultProjectId:void 0,setupComplete:void 0,favoriteProviders:void 0,favoriteModels:void 0,openrouterModelSync:!0,updateCheckEnabled:!0,fnBinaryCheckEnabled:!0,updateCheckFrequency:"daily",showGitHubStarButton:!0,modelOnboardingComplete:void 0,useClaudeCli:void 0,useDroidCli:void 0,executionGlobalProvider:void 0,executionGlobalModelId:void 0,planningGlobalProvider:void 0,planningGlobalModelId:void 0,validatorGlobalProvider:void 0,validatorGlobalModelId:void 0,titleSummarizerGlobalProvider:void 0,titleSummarizerGlobalModelId:void 0,daemonToken:void 0,daemonPort:4040,daemonHost:"127.0.0.1",settingsSyncEnabled:!1,settingsSyncAuth:!1,settingsSyncInterval:9e5,settingsSyncConflictResolution:"last-write-wins",dashboardCurrentNodeId:void 0,dashboardCurrentProjectIdByNode:void 0,vitestAutoKillEnabled:!0,vitestKillThresholdPct:90,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:{}},EN={globalPause:!1,globalPauseReason:void 0,enginePaused:!1,maxConcurrent:2,maxTriageConcurrent:2,globalMaxConcurrent:4,maxWorktrees:4,pollIntervalMs:15e3,heartbeatMultiplier:1,groupOverlappingFiles:!0,overlapIgnorePaths:[],autoMerge:!0,mergeStrategy:"direct",requirePrApproval:!1,pushAfterMerge:!1,pushRemote:"origin",unavailableNodePolicy:"block",defaultNodeId:void 0,worktreeInitCommand:void 0,testCommand:void 0,buildCommand:void 0,recycleWorktrees:!1,worktreeNaming:"random",taskPrefix:"FN",includeTaskIdInCommit:!0,commitAuthorEnabled:!0,commitAuthorName:"Fusion",commitAuthorEmail:"noreply@runfusion.ai",planningProvider:void 0,planningModelId:void 0,planningFallbackProvider:void 0,planningFallbackModelId:void 0,defaultProviderOverride:void 0,defaultModelIdOverride:void 0,executionProvider:void 0,executionModelId:void 0,validatorProvider:void 0,validatorModelId:void 0,validatorFallbackProvider:void 0,validatorFallbackModelId:void 0,modelPresets:[],autoSelectModelPreset:!1,defaultPresetBySize:{},autoResolveConflicts:!0,smartConflictResolution:!0,worktreeRebaseBeforeMerge:!0,worktreeRebaseRemote:"",worktreeRebaseLocalBase:!0,mergeConflictStrategy:"smart-prefer-main",workflowStepTimeoutMs:36e4,strictScopeEnforcement:!1,buildRetryCount:0,verificationFixRetries:3,buildTimeoutMs:3e5,requirePlanApproval:!1,specStalenessEnabled:!1,specStalenessMaxAgeMs:360*60*1e3,taskStuckTimeoutMs:void 0,aiSessionTtlMs:10080*60*1e3,aiSessionCleanupIntervalMs:3600*1e3,autoUnpauseEnabled:!0,autoUnpauseBaseDelayMs:3e5,autoUnpauseMaxDelayMs:36e5,maxStuckKills:6,maxPostReviewFixes:1,maxSpawnedAgentsPerParent:5,maxSpawnedAgentsGlobal:20,maintenanceIntervalMs: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},_N=Object.freeze(Object.keys(CN)),MN=Object.freeze(Object.keys(EN));function q3(e){return _N.includes(e)}function V3(e){return MN.includes(e)}function ke(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function AN(e){return!!(e?.provider&&e?.modelId)}function _i(...e){for(const n of e)if(AN(n))return{provider:n.provider,modelId:n.modelId};return{}}function ul(e){return _i({provider:e?.defaultProviderOverride,modelId:e?.defaultModelIdOverride},{provider:e?.defaultProvider,modelId:e?.defaultModelId})}function RN(e){return _i({provider:e?.executionProvider,modelId:e?.executionModelId},{provider:e?.executionGlobalProvider,modelId:e?.executionGlobalModelId},ul(e))}function TN(e){return _i({provider:e?.planningProvider,modelId:e?.planningModelId},{provider:e?.planningGlobalProvider,modelId:e?.planningGlobalModelId},ul(e))}function PN(e){return _i({provider:e?.validatorProvider,modelId:e?.validatorModelId},{provider:e?.validatorGlobalProvider,modelId:e?.validatorGlobalModelId},ul(e))}function W3(e){return _i({provider:e?.titleSummarizerProvider,modelId:e?.titleSummarizerModelId},{provider:e?.titleSummarizerGlobalProvider,modelId:e?.titleSummarizerGlobalModelId},{provider:e?.planningProvider,modelId:e?.planningModelId},ul(e))}function Zp(e,n){return _i({provider:e.modelProvider,modelId:e.modelId},RN(n))}function ef(e,n){return _i({provider:e.validatorModelProvider,modelId:e.validatorModelId},PN(n))}function tf(e,n){return _i({provider:e.planningModelProvider,modelId:e.planningModelId},TN(n))}const K3=["off","minimal","low","medium","high"],Ui=["triage","todo","in-progress","in-review","done","archived"],Cd=["low","normal","high","urgent"],_s="normal",IN=["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"],Wn={triage:"Planning",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},$N={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"},Wc={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 DN(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 LN(e,n=1400){const s=a.useRef(null),[i,r]=a.useState(!1),o=a.useRef(null);return a.useEffect(()=>(s.current!==null&&e>s.current&&(r(!0),o.current=setTimeout(()=>r(!1),n)),s.current=e,()=>{o.current!==null&&clearTimeout(o.current)}),[e,n]),i}function zN({isOpen:e,options:n,onConfirm:s,onCancel:i}){const r=a.useRef(null);return a.useEffect(()=>{if(!e)return;r.current?.focus();const o=l=>{l.key==="Escape"&&(l.preventDefault(),i())};return document.addEventListener("keydown",o),()=>document.removeEventListener("keydown",o)},[e,i]),!e||!n?null:t.jsx("div",{className:"modal-overlay open",onClick:i,children:t.jsxs("div",{className:"modal confirm-dialog",onClick:o=>o.stopPropagation(),role:"dialog","aria-modal":"true","aria-label":n.title,children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:n.title}),t.jsx("button",{className:"modal-close",onClick:i,"aria-label":"Close confirmation dialog",children:"×"})]}),t.jsx("div",{className:"confirm-dialog__body",children:n.message}),t.jsxs("div",{className:"modal-actions confirm-dialog__actions",children:[t.jsx("button",{ref:r,className:"btn",onClick:i,children:n.cancelLabel??"Cancel"}),t.jsx("button",{className:`btn ${n.danger?"btn-danger":"btn-primary"}`,onClick:s,children:n.confirmLabel??"Confirm"})]})]})})}const nf=a.createContext(null);function ON({children:e}){const[n,s]=a.useState([]),i=a.useRef([]),r=a.useCallback(d=>{s(m=>{const h=d(m);return i.current=h,h})},[]),o=a.useCallback(d=>new Promise(m=>{r(h=>[...h,{options:d,resolve:m}])}),[r]),l=a.useCallback(d=>{const m=i.current[0];m&&(m.resolve(d),r(h=>h.slice(1)))},[r]),c=n[0]??null,u=a.useMemo(()=>({confirm:o}),[o]);return $o.createElement(nf.Provider,{value:u},e,$o.createElement(zN,{isOpen:c!==null,options:c?.options??null,onConfirm:()=>l(!0),onCancel:()=>l(!1)}))}function Gs(){const e=a.useContext(nf);return e||{confirm:async n=>!1}}function FN(e,n){return e==="open"?"card-github-badge--open":n==="completed"?"card-github-badge--completed":n==="not_planned"?"card-github-badge--not-planned":"card-github-badge--closed"}function sf({prInfo:e,issueInfo:n,onIssueRefresh:s}){const i=()=>{e?.url&&window.open(e.url,"_blank","noopener,noreferrer")},r=()=>{n?.url&&window.open(n.url,"_blank","noopener,noreferrer")};return t.jsxs(t.Fragment,{children:[e&&t.jsxs("span",{className:`card-github-badge card-github-badge--${e.status}`,title:`PR #${e.number}: ${e.title}`,onClick:i,children:[t.jsx(Es,{size:12}),t.jsxs("span",{children:["#",e.number]})]}),n&&t.jsxs("span",{className:`card-github-badge ${FN(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,onClick:r,children:[t.jsx(tl,{size:12}),t.jsxs("span",{children:["#",n.number]})]})]})}function lo(e,n){return`${e??"default"}:${n}`}class UN{ws=null;listeners=new Set;badgeUpdates=new Map;subscriptionsByTask=new Map;reconnectTimeout=null;reconnectDelayMs=1e3;shouldReconnect=!1;isConnected=!1;projectId=null;snapshot={badgeUpdates:new Map,isConnected:!1};previousProjectIdRef=null;projectContextVersionRef=0;contextVersionAtStart=0;subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}getSnapshot(){return this.snapshot}setProjectId(n){if(this.projectId===n)return;this.previousProjectIdRef=this.projectId,this.projectContextVersionRef++,this.contextVersionAtStart=this.projectContextVersionRef;const s=this.subscriptionsByTask.size>0,i=[];for(const[r,o]of this.subscriptionsByTask){const l=r.split(":").slice(1).join(":");for(const c of o)i.push({hookId:c,taskId:l})}if(this.projectId=n,this.reset(),s){for(const{hookId:r,taskId:o}of i){const l=lo(this.projectId,o);this.subscriptionsByTask.set(l,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const i=lo(this.projectId,s),r=this.subscriptionsByTask.get(i)??new Set,o=!r.has(n);r.add(n),this.subscriptionsByTask.set(i,r),this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect(),o&&this.send({type:"subscribe",taskId:s,projectId:this.projectId})}unsubscribeTask(n,s){const i=lo(this.projectId,s),r=this.subscriptionsByTask.get(i);r&&(r.delete(n),r.size===0&&(this.subscriptionsByTask.delete(i),this.badgeUpdates.delete(i),this.send({type:"unsubscribe",taskId:s,projectId:this.projectId}),this.emit()),this.shouldReconnect=this.subscriptionsByTask.size>0,this.shouldReconnect||this.disconnect())}cleanupHook(n){for(const s of[...this.subscriptionsByTask.keys()]){const i=s.split(":").slice(1).join(":");this.unsubscribeTask(n,i)}}reset(){this.disconnect(),this.badgeUpdates.clear(),this.subscriptionsByTask.clear(),this.shouldReconnect=!1,this.emit()}connect(){if(!this.shouldReconnect||typeof window>"u"||this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))return;const n=this.projectContextVersionRef;let i=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/ws`;this.projectId&&(i+=`?projectId=${encodeURIComponent(this.projectId)}`);const r=new WebSocket(oi(i));this.ws=r,r.onopen=()=>{if(this.projectContextVersionRef!==n){r.close();return}this.isConnected=!0,this.reconnectDelayMs=1e3,this.emit();const o=new Set;for(const l of this.subscriptionsByTask.keys()){const c=l.split(":").slice(1).join(":");o.add(c)}for(const l of o)this.send({type:"subscribe",taskId:l,projectId:this.projectId})},r.onmessage=o=>{if(this.projectContextVersionRef===n)try{const l=JSON.parse(o.data);if(l.type!=="badge:updated"||l.projectId!==void 0&&l.projectId!==this.projectId)return;const c=lo(this.projectId,l.taskId),u=this.badgeUpdates.get(c);this.badgeUpdates.set(c,{prInfo:Tu(l,"prInfo")?l.prInfo??null:u?.prInfo,issueInfo:Tu(l,"issueInfo")?l.issueInfo??null:u?.issueInfo,timestamp:l.timestamp}),this.emit()}catch{}},r.onclose=()=>{this.projectContextVersionRef===n&&(this.ws=null,this.isConnected&&(this.isConnected=!1,this.emit()),this.shouldReconnect&&this.scheduleReconnect(n))},r.onerror=()=>{}}disconnect(){if(this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.ws){const n=this.ws;this.ws=null,n.close()}this.isConnected&&(this.isConnected=!1,this.emit())}scheduleReconnect(n){if(this.reconnectTimeout)return;const s=n??this.projectContextVersionRef,i=Math.min(this.reconnectDelayMs,5e3);this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.projectContextVersionRef===s&&this.shouldReconnect&&this.connect()},i),this.reconnectDelayMs=Math.min(this.reconnectDelayMs*2,5e3)}send(n){!this.ws||this.ws.readyState!==WebSocket.OPEN||this.ws.send(JSON.stringify(n))}emit(){this.snapshot={badgeUpdates:new Map(this.badgeUpdates),isConnected:this.isConnected};for(const n of this.listeners)n()}}const Li=new UN;let BN=0;function Tu(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function af(e){const n=a.useRef(null);n.current===null&&(n.current=`badge-hook-${BN++}`);const s=a.useSyncExternalStore(o=>Li.subscribe(o),()=>Li.getSnapshot(),()=>Li.getSnapshot()),i=a.useCallback(o=>{Li.subscribeTask(n.current,o)},[]),r=a.useCallback(o=>{Li.unsubscribeTask(n.current,o)},[]);return a.useEffect(()=>{Li.setProjectId(e??null)},[e]),a.useEffect(()=>()=>{Li.cleanupHook(n.current)},[]),{badgeUpdates:s.badgeUpdates,isConnected:s.isConnected,subscribeToBadge:i,unsubscribeFromBadge:r}}function Ho(e,n,s,i){return e===void 0||!n?s:!i||n>=i?e??void 0:s}function HN({taskId:e,prInfo:n,issueInfo:s,updatedAt:i,isInViewport:r,projectId:o}){const{badgeUpdates:l,subscribeToBadge:c,unsubscribeFromBadge:u}=af(o),d=!!(n||s);a.useEffect(()=>{if(!d||!r){u(e);return}return c(e),()=>{u(e)}},[d,r,o,c,e,u]);const m=l.get(`${o??"default"}:${e}`),h=Ho(m?.prInfo,m?.timestamp,n,n?.lastCheckedAt??i),f=Ho(m?.issueInfo,m?.timestamp,s,s?.lastCheckedAt??i);return!h&&!f?null:t.jsx(sf,{prInfo:h,issueInfo:f})}const qN=a.memo(HN);qN.displayName="TaskCardBadge";const VN={sm:16,md:20,lg:24};function WN({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 Pu({size:e,color:n,label:s="OpenAI"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"openai-icon","aria-label":s,children:t.jsx("path",{d:"M22.282 9.821a6 6 0 0 0-.516-4.91a6.05 6.05 0 0 0-6.51-2.9A6.065 6.065 0 0 0 4.981 4.18a6 6 0 0 0-3.998 2.9a6.05 6.05 0 0 0 .743 7.097a5.98 5.98 0 0 0 .51 4.911a6.05 6.05 0 0 0 6.515 2.9A6 6 0 0 0 13.26 24a6.06 6.06 0 0 0 5.772-4.206a6 6 0 0 0 3.997-2.9a6.06 6.06 0 0 0-.747-7.073M13.26 22.43a4.48 4.48 0 0 1-2.876-1.04l.141-.081l4.779-2.758a.8.8 0 0 0 .392-.681v-6.737l2.02 1.168a.07.07 0 0 1 .038.052v5.583a4.504 4.504 0 0 1-4.494 4.494M3.6 18.304a4.47 4.47 0 0 1-.535-3.014l.142.085l4.783 2.759a.77.77 0 0 0 .78 0l5.843-3.369v2.332a.08.08 0 0 1-.033.062L9.74 19.95a4.5 4.5 0 0 1-6.14-1.646M2.34 7.896a4.5 4.5 0 0 1 2.366-1.973V11.6a.77.77 0 0 0 .388.677l5.815 3.354l-2.02 1.168a.08.08 0 0 1-.071 0l-4.83-2.786A4.504 4.504 0 0 1 2.34 7.872zm16.597 3.855l-5.833-3.387L15.119 7.2a.08.08 0 0 1 .071 0l4.83 2.791a4.494 4.494 0 0 1-.676 8.105v-5.678a.79.79 0 0 0-.407-.667m2.01-3.023l-.141-.085l-4.774-2.782a.78.78 0 0 0-.785 0L9.409 9.23V6.897a.07.07 0 0 1 .028-.061l4.83-2.787a4.5 4.5 0 0 1 6.68 4.66zm-12.64 4.135l-2.02-1.164a.08.08 0 0 1-.038-.057V6.075a4.5 4.5 0 0 1 7.375-3.453l-.142.08L8.704 5.46a.8.8 0 0 0-.393.681zm1.097-2.365l2.602-1.5l2.607 1.5v2.999l-2.597 1.5l-2.607-1.5Z",fill:n})})}function Zs({size:e,color:n,label:s="Google Gemini"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"gemini-icon","aria-label":s,children:t.jsx("path",{d:"M11.04 19.32Q12 21.51 12 24q0-2.49.93-4.68.96-2.19 2.58-3.81t3.81-2.55Q21.51 12 24 12q-2.49 0-4.68-.93a12.3 12.3 0 0 1-3.81-2.58 12.3 12.3 0 0 1-2.58-3.81Q12 2.49 12 0q0 2.49-.96 4.68-.93 2.19-2.55 3.81a12.3 12.3 0 0 1-3.81 2.58Q2.49 12 0 12q2.49 0 4.68.96 2.19.93 3.81 2.55t2.55 3.81",fill:n})})}function KN({size:e,color:n,label:s="Ollama"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"ollama-icon","aria-label":s,children:t.jsx("path",{d:"M16.361 10.26a.894.894 0 0 0-.558.47l-.072.148.001.207c0 .193.004.217.059.353.076.193.152.312.291.448.24.238.51.3.872.205a.86.86 0 0 0 .517-.436.752.752 0 0 0 .08-.498c-.064-.453-.33-.782-.724-.897a1.06 1.06 0 0 0-.466 0zm-9.203.005c-.305.096-.533.32-.65.639a1.187 1.187 0 0 0-.06.52c.057.309.31.59.598.667.362.095.632.033.872-.205.14-.136.215-.255.291-.448.055-.136.059-.16.059-.353l.001-.207-.072-.148a.894.894 0 0 0-.565-.472 1.02 1.02 0 0 0-.474.007Zm4.184 2c-.131.071-.223.25-.195.383.031.143.157.288.353.407.105.063.112.072.117.136.004.038-.01.146-.029.243-.02.094-.036.194-.036.222.002.074.07.195.143.253.064.052.076.054.255.059.164.005.198.001.264-.03.169-.082.212-.234.15-.525-.052-.243-.042-.28.087-.355.137-.08.281-.219.324-.314a.365.365 0 0 0-.175-.48.394.394 0 0 0-.181-.033c-.126 0-.207.03-.355.124l-.085.053-.053-.032c-.219-.13-.259-.145-.391-.143a.396.396 0 0 0-.193.032zm.39-2.195c-.373.036-.475.05-.654.086-.291.06-.68.195-.951.328-.94.46-1.589 1.226-1.787 2.114-.04.176-.045.234-.045.53 0 .294.005.357.043.524.264 1.16 1.332 2.017 2.714 2.173.3.033 1.596.033 1.896 0 1.11-.125 2.064-.727 2.493-1.571.114-.226.169-.372.22-.602.039-.167.044-.23.044-.523 0-.297-.005-.355-.045-.531-.288-1.29-1.539-2.304-3.072-2.497a6.873 6.873 0 0 0-.855-.031zm.645.937a3.283 3.283 0 0 1 1.44.514c.223.148.537.458.671.662.166.251.26.508.303.82.02.143.01.251-.043.482-.08.345-.332.705-.672.957a3.115 3.115 0 0 1-.689.348c-.382.122-.632.144-1.525.138-.582-.006-.686-.01-.853-.042-.57-.107-1.022-.334-1.35-.68-.264-.28-.385-.535-.45-.946-.03-.192.025-.509.137-.776.136-.326.488-.73.836-.963.403-.269.934-.46 1.422-.512.187-.02.586-.02.773-.002zm-5.503-11a1.653 1.653 0 0 0-.683.298C5.617.74 5.173 1.666 4.985 2.819c-.07.436-.119 1.04-.119 1.503 0 .544.064 1.24.155 1.721.02.107.031.202.023.208a8.12 8.12 0 0 1-.187.152 5.324 5.324 0 0 0-.949 1.02 5.49 5.49 0 0 0-.94 2.339 6.625 6.625 0 0 0-.023 1.357c.091.78.325 1.438.727 2.04l.13.195-.037.064c-.269.452-.498 1.105-.605 1.732-.084.496-.095.629-.095 1.294 0 .67.009.803.088 1.266.095.555.288 1.143.503 1.534.071.128.243.393.264.407.007.003-.014.067-.046.141a7.405 7.405 0 0 0-.548 1.873c-.062.417-.071.552-.071.991 0 .56.031.832.148 1.279L3.42 24h1.478l-.05-.091c-.297-.552-.325-1.575-.068-2.597.117-.472.25-.819.498-1.296l.148-.29v-.177c0-.165-.003-.184-.057-.293a.915.915 0 0 0-.194-.25 1.74 1.74 0 0 1-.385-.543c-.424-.92-.506-2.286-.208-3.451.124-.486.329-.918.544-1.154a.787.787 0 0 0 .223-.531c0-.195-.07-.355-.224-.522a3.136 3.136 0 0 1-.817-1.729c-.14-.96.114-2.005.69-2.834.563-.814 1.353-1.336 2.237-1.475.199-.033.57-.028.776.01.226.04.367.028.512-.041.179-.085.268-.19.374-.431.093-.215.165-.333.36-.576.234-.29.46-.489.822-.729.413-.27.884-.467 1.352-.561.17-.035.25-.04.569-.04.319 0 .398.005.569.04a4.07 4.07 0 0 1 1.914.997c.117.109.398.457.488.602.034.057.095.177.132.267.105.241.195.346.374.43.14.068.286.082.503.045.343-.058.607-.053.943.016 1.144.23 2.14 1.173 2.581 2.437.385 1.108.276 2.267-.296 3.153-.097.15-.193.27-.333.419-.301.322-.301.722-.001 1.053.493.539.801 1.866.708 3.036-.062.772-.26 1.463-.533 1.854a2.096 2.096 0 0 1-.224.258.916.916 0 0 0-.194.25c-.054.109-.057.128-.057.293v.178l.148.29c.248.476.38.823.498 1.295.253 1.008.231 2.01-.059 2.581a.845.845 0 0 0-.044.098c0 .006.329.009.732.009h.73l.02-.074.036-.134c.019-.076.057-.3.088-.516.029-.217.029-1.016 0-1.258-.11-.875-.295-1.57-.597-2.226-.032-.074-.053-.138-.046-.141.008-.005.057-.074.108-.152.376-.569.607-1.284.724-2.228.031-.26.031-1.378 0-1.628-.083-.645-.182-1.082-.348-1.525a6.083 6.083 0 0 0-.329-.7l-.038-.064.131-.194c.402-.604.636-1.262.727-2.04a6.625 6.625 0 0 0-.024-1.358 5.512 5.512 0 0 0-.939-2.339 5.325 5.325 0 0 0-.95-1.02 8.097 8.097 0 0 1-.186-.152.692.692 0 0 1 .023-.208c.208-1.087.201-2.443-.017-3.503-.19-.924-.535-1.658-.98-2.082-.354-.338-.716-.482-1.15-.455-.996.059-1.8 1.205-2.116 3.01a6.805 6.805 0 0 0-.097.726c0 .036-.007.066-.015.066a.96.96 0 0 1-.149-.078A4.857 4.857 0 0 0 12 3.03c-.832 0-1.687.243-2.456.698a.958.958 0 0 1-.148.078c-.008 0-.015-.03-.015-.066a6.71 6.71 0 0 0-.097-.725C8.997 1.392 8.337.319 7.46.048a2.096 2.096 0 0 0-.585-.041Zm.293 1.402c.248.197.523.759.682 1.388.03.113.06.244.069.292.007.047.026.152.041.233.067.365.098.76.102 1.24l.002.475-.12.175-.118.178h-.278c-.324 0-.646.041-.954.124l-.238.06c-.033.007-.038-.003-.057-.144a8.438 8.438 0 0 1 .016-2.323c.124-.788.413-1.501.696-1.711.067-.05.079-.049.157.013zm9.825-.012c.17.126.358.46.498.888.28.854.36 2.028.212 3.145-.019.14-.024.151-.057.144l-.238-.06a3.693 3.693 0 0 0-.954-.124h-.278l-.119-.178-.119-.175.002-.474c.004-.669.066-1.19.214-1.772.157-.623.434-1.185.68-1.382.078-.062.09-.063.159-.012z",fill:n})})}function Iu({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 GN({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 Al({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 $u({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 Du({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 Lu({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 Wa({size:e,color:n,label:s="Qwen"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"qwen-icon","aria-label":s,children:[t.jsx("circle",{cx:"11",cy:"12",r:"7.5",stroke:n,strokeWidth:"2",fill:"none"}),t.jsx("path",{d:"M14 15 L21 22",stroke:n,strokeWidth:"2.6",strokeLinecap:"round"})]})}function zu({size:e,color:n,label:s="LM Studio"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"lmstudio-icon","aria-label":s,children:[t.jsx("rect",{x:"2",y:"2",width:"20",height:"20",rx:"4.5",fill:n}),t.jsx("text",{x:"12",y:"16",textAnchor:"middle",fontFamily:"-apple-system, system-ui, sans-serif",fontSize:"9.5",fontWeight:"700",fill:"var(--provider-icon-contrast)",letterSpacing:"-0.4",children:"LM"})]})}function Rl({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 Ou({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 Tl({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 JN({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 YN({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 Fu({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 Pl({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 QN({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 Uu({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 Il({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 Bu({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 $l({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 Hu({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 XN({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 ZN={anthropic:{component:WN,color:"var(--provider-anthropic)"},"claude-cli":{component:Hu,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"pi-claude-cli":{component:Hu,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"droid-cli":{component:XN,color:"var(--provider-openai)",label:"Factory AI — via Droid CLI"},openai:{component:Pu,color:"var(--provider-openai)"},"openai-codex":{component:Pu,color:"var(--provider-openai)",label:"OpenAI Codex"},google:{component:Zs,color:"var(--provider-gemini)"},gemini:{component:Zs,color:"var(--provider-gemini)"},"google-antigravity":{component:Zs,color:"var(--provider-gemini)",label:"Google Gemini"},antigravity:{component:Zs,color:"var(--provider-gemini)",label:"Google Gemini"},"google-vertex":{component:Zs,color:"var(--provider-gemini)",label:"Google Vertex AI"},vertex:{component:Zs,color:"var(--provider-gemini)",label:"Google Vertex AI"},"google-cloud-code":{component:Zs,color:"var(--provider-gemini)",label:"Google Cloud Code"},"cloud-code":{component:Zs,color:"var(--provider-gemini)",label:"Google Cloud Code"},"google-gemini-cli":{component:Zs,color:"var(--provider-gemini)",label:"Google Gemini CLI"},"google-generative-ai":{component:Zs,color:"var(--provider-gemini)",label:"Google Generative AI"},ollama:{component:KN,color:"var(--text)"},github:{component:Uu,color:"var(--text)"},"github-copilot":{component:Uu,color:"var(--text)",label:"GitHub Copilot"},openrouter:{component:QN,color:"var(--provider-openrouter)"},minimax:{component:Iu,color:"var(--provider-minimax)"},"minimax-cn":{component:Iu,color:"var(--provider-minimax)",label:"MiniMax (CN)"},zai:{component:GN,color:"var(--provider-zai)"},kimi:{component:Al,color:"var(--provider-kimi)"},moonshot:{component:Al,color:"var(--provider-kimi)"},"kimi-coding":{component:Al,color:"var(--provider-kimi)",label:"Kimi"},bedrock:{component:$u,color:"var(--provider-bedrock)"},"amazon-bedrock":{component:$u,color:"var(--provider-bedrock)",label:"Amazon Bedrock"},xai:{component:Du,color:"var(--text)"},grok:{component:Du,color:"var(--text)",label:"xAI"},opencode:{component:Lu,color:"var(--provider-opencode)"},"opencode-go":{component:Lu,color:"var(--provider-opencode)",label:"Opencode (Go)"},qwen:{component:Wa,color:"var(--provider-qwen)"},"qwen-ai":{component:Wa,color:"var(--provider-qwen)",label:"Qwen"},"qwen-coder":{component:Wa,color:"var(--provider-qwen)",label:"Qwen Coder"},alibaba:{component:Wa,color:"var(--provider-qwen)",label:"Qwen"},tongyi:{component:Wa,color:"var(--provider-qwen)",label:"Qwen"},lmstudio:{component:zu,color:"var(--provider-lmstudio)",label:"LM Studio"},"lm-studio":{component:zu,color:"var(--provider-lmstudio)",label:"LM Studio"},huggingface:{component:Rl,color:"var(--provider-huggingface)",label:"Hugging Face"},"hugging-face":{component:Rl,color:"var(--provider-huggingface)",label:"Hugging Face"},hf:{component:Rl,color:"var(--provider-huggingface)",label:"Hugging Face"},mistral:{component:Ou,color:"var(--provider-mistral)",label:"Mistral AI"},"mistral-ai":{component:Ou,color:"var(--provider-mistral)",label:"Mistral AI"},azure:{component:Tl,color:"var(--provider-azure)"},"azure-openai":{component:Tl,color:"var(--provider-azure)",label:"Azure OpenAI"},"azure-openai-responses":{component:Tl,color:"var(--provider-azure)",label:"Azure OpenAI"},fireworks:{component:Pl,color:"var(--provider-fireworks)",label:"Fireworks AI"},"fireworks-ai":{component:Pl,color:"var(--provider-fireworks)",label:"Fireworks AI"},fireworksai:{component:Pl,color:"var(--provider-fireworks)",label:"Fireworks AI"},cerebras:{component:JN,color:"var(--provider-cerebras)"},groq:{component:YN,color:"var(--provider-groq)"},vercel:{component:Fu,color:"var(--provider-vercel)"},"vercel-ai-gateway":{component:Fu,color:"var(--provider-vercel)",label:"Vercel AI Gateway"},hermes:{component:Il,color:"var(--provider-hermes)",label:"Hermes"},"hermes-agent":{component:Il,color:"var(--provider-hermes)",label:"Hermes"},hermesagent:{component:Il,color:"var(--provider-hermes)",label:"Hermes"},openclaw:{component:Bu,color:"var(--provider-openclaw)",label:"OpenClaw"},"open-claw":{component:Bu,color:"var(--provider-openclaw)",label:"OpenClaw"},paperclip:{component:$l,color:"var(--provider-paperclip)",label:"Paperclip"},paperclipai:{component:$l,color:"var(--provider-paperclip)",label:"Paperclip"},"paperclip-ai":{component:$l,color:"var(--provider-paperclip)",label:"Paperclip"}};function Rn({provider:e,size:n="sm"}){const s=e.toLowerCase(),i=ZN[s],r=i?.component,o=i?.color??"var(--text-muted)",l=i?.label,c=VN[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(Xb,{size:c})})}const Ps={data:new Map,pendingPromise:null,lastFetchTime:null},e1=5e3;function Ro(e,n){return n?`${n}::${e}`:e}function t1(e,n){const s=Ps.data.get(Ro(e,n));if(!(!s||Date.now()-s.timestamp>e1))return s}function n1(e){const[n,s]=a.useState(!1),i=a.useRef(null),r=a.useCallback(async c=>{let d=null;for(let m=0;m<3;m++)try{return await bw(c,e)}catch(h){d=h instanceof Error?h:new Error(String(h));const f=ke(h);if(f?.includes("429")||f?.toLowerCase().includes("rate limit")){const p=Math.min(1e3*Math.pow(2,m),3e4);await new Promise(g=>setTimeout(g,p));continue}break}if(d)throw d;return{}},[e]),o=a.useCallback(async c=>{if(c.length===0)return;const d=Date.now()-5e3;if(c.every(f=>{const p=Ps.data.get(Ro(f,e));return p&&p.timestamp>d})&&Ps.lastFetchTime&&Ps.lastFetchTime>d)return;if(i.current&&(clearTimeout(i.current),i.current=null),Ps.pendingPromise){s(!0);try{await Ps.pendingPromise}finally{s(!1)}return}s(!0);const h=r(c);Ps.pendingPromise=h;try{const f=await h,p=Date.now();for(const[g,b]of Object.entries(f))Ps.data.set(Ro(g,e),{result:b,timestamp:p});Ps.lastFetchTime=p}catch{}finally{Ps.pendingPromise=null,s(!1)}},[r,e]),l=a.useCallback(c=>Ps.data.get(Ro(c,e)),[e]);return{fetchBatch:o,isLoading:n,lastFetchTime:Ps.lastFetchTime,getBatchData:l}}const Kc=new Map,s1=3e4;function rf(e,n,s,i){return`${e}:${n??""}:${s??""}:${i??""}`}function i1(e,n,s,i){const r=rf(e,n,s,i),o=Kc.get(r);return o?Date.now()>o.expiresAt?(Kc.delete(r),null):o.stats:null}function a1(e,n,s,i,r){const o=rf(e,n,s,i);Kc.set(o,{stats:r,expiresAt:Date.now()+s1})}function r1(e,n,s,i,r={}){const o=r.enabled??!0,l=r.worktree,c=r.stepVersion,u=r.pollIntervalMs,[d,m]=a.useState(null),[h,f]=a.useState(!1);return a.useEffect(()=>{if(!o){m(null),f(!1);return}const p=n==="done"&&!!s,g=(n==="in-progress"||n==="in-review")&&!!l;if(!e||!p&&!g){m(null),f(!1);return}const b=g?l:void 0,v=c!==void 0?String(c):void 0;let x=!1;async function y(E=!1){if(!E){const C=i1(e,i,b,v);if(C){x||(m(C),f(!1));return}}f(!0);try{const C=await Hp(e,b,i);x||(m(C.stats),a1(e,i,b,v,C.stats))}catch{x||m(null)}finally{x||f(!1)}}y();let j;return u&&g&&(j=setInterval(()=>{y(!0)},u)),()=>{x=!0,j&&clearInterval(j)}},[e,n,s,i,o,l,c,u]),{stats:d,loading:h}}const o1=new Set(["failed","stuck-killed"]);function qo(e,n,s){if(e.column!=="in-progress"||e.status&&o1.has(e.status)||!n||n<=0)return!1;const i=new Date(e.updatedAt).getTime();return(s??Date.now())-i>n}function l1(e){switch(e){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function c1(e){return e==="done"||e==="skipped"}function d1(e,n,s){const i=s?.get(e)?.trim();if(i)return i;const r=n?.workflowStepName?.trim();return r||e}function of(e,n){const s=(e.steps??[]).map((u,d)=>({id:`step-${d}`,name:u.name,status:u.status,source:"step",phase:"pre-merge"})),i=new Map((e.workflowStepResults??[]).map(u=>[u.workflowStepId,u])),r=(e.enabledWorkflowSteps??[]).map(u=>{const d=i.get(u);return{id:`workflow-${u}`,name:d1(u,d,n),status:d?l1(d.status):"pending",source:"workflow",phase:d?.phase??"pre-merge"}}),o=[...s,...r],l=o.length,c=o.filter(u=>c1(u.status)).length;return{total:l,completed:c,items:o}}function u1(e){return(e.action||e.outcome||"").replace(/^\[timing\]\s*/i,"").replace(/^\[[^\]]+\]\s*/i,"").replace(/\s+in\s+\d+(?:\.\d+)?ms\b/i,"").replace(/\s+after\s+\d+(?:\.\d+)?ms\b/i,"").trim()||"Timing event"}function lf(e){return e.filter(n=>{const s=typeof n.action=="string"?n.action:"",i=typeof n.outcome=="string"?n.outcome:"";return s.includes("[timing]")||i.includes("[timing]")}).map(n=>{const i=`${n.action??""}
|
|
621
|
-
${n.outcome??""}`.match(/(\d+(?:\.\d+)?)ms\b/i),r=i?Number(i[1]):void 0;return{timestamp:n.timestamp,durationMs:Number.isFinite(r)?r:void 0,summary:u1(n)}})}function m1(e){if(!e||e.length===0)return null;let n=0,s=0;for(const i of lf(e))typeof i.durationMs=="number"&&(n+=i.durationMs,s+=1);return s>0?n:null}const Gc=new Map;async function h1(e,n){const s=Gc.get(e);if(s)return s;try{const i=await qp(e,n);return Gc.set(e,i.title),i.title}catch{return e}}const qu=12;function p1(e){return e.length<=qu?e:e.slice(0,qu-3)+"..."}const Jc=new Map;async function f1(e,n){const s=Jc.get(e);if(s)return s;try{const i=await Vc(e,n);return Jc.set(e,i.name),i.name}catch{return e}}function g1(e){return typeof e=="string"&&Cd.includes(e)?e:_s}function b1(e,n){return e.length<=n?e:e.slice(0,n-3)+"..."}const x1=new Set(["triage","todo"]),Vu=new Set(["planning","researching","executing","finalizing","merging"]),Wu=new Set(["merging","merging-pr"]),v1={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"},y1=new Set(["in-progress","in-review","done"]),w1=3e4;function Ki(e){if(!e)return null;const n=Date.parse(e);return Number.isFinite(n)?n:null}function j1(e){const n=Ki(e.columnMovedAt??e.updatedAt);if(n==null)return null;const s=Date.now();return n>s?null:n}function Ku(e,n){const s=Ki(e.columnMovedAt??e.updatedAt);return s==null?null:Math.max(0,n-s)}function ur(e,n){const s=Ki(e.executionStartedAt);if(s==null)return null;const i=Ki(e.executionCompletedAt),r=i!=null&&i>=s?i:n;return Math.max(0,r-s)}function k1(e){return e.column==="done"?j1(e):null}function cf(e,n){const s=Ki(e.updatedAt);return s==null?null:Math.max(0,n-s)}function N1(e,n){const s=ur(e,n);if(s!=null)return s;const i=cf(e,n),r=mr(e,n);return r!=null?r+(i??0):i}function S1(e,n){const s=e.workflowStepResults;if(!s||s.length===0)return null;let i=0,r=0;for(const o of s){if(!o.startedAt)continue;const l=Ki(o.startedAt);if(l==null)continue;let c;if(o.completedAt){const u=Ki(o.completedAt);if(u==null||u<l)continue;c=u}else c=Math.max(l,n);i+=c-l,r+=1}return r>0?i:null}function mr(e,n){const s=typeof e.timedExecutionMs=="number"?e.timedExecutionMs:m1(e.log),i=S1(e,n);return s==null&&i==null?null:(s??0)+(i??0)}function Gu(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 Ju(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 Yu(e,n){if(!e&&!n)return!0;if(!e||!n)return!1;const s=Object.keys(e),i=Object.keys(n);return s.length!==i.length?!1:s.every(r=>e[r]===n[r])}function C1(e,n){return e.length!==n.length?!1:e.every((s,i)=>s.name===n[i]?.name&&s.status===n[i]?.status)}function E1(e,n){return e.length!==n.length?!1:e.every((s,i)=>s===n[i])}function _1(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>s===n[i])}function M1(e){if(!(e instanceof Error))return null;const n=e.details;if(n?.code==="TASK_HAS_DEPENDENTS"&&Array.isArray(n.dependentIds))return{dependentIds:n.dependentIds.filter(i=>typeof i=="string")};const s=e.message.match(/[A-Z]+-\d+/g)??[];return s.length>1?{dependentIds:[...new Set(s.slice(1))]}:null}function A1(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>{const r=n[i];return r?s.workflowStepId===r.workflowStepId&&s.workflowStepName===r.workflowStepName&&s.phase===r.phase&&s.status===r.status&&s.output===r.output&&s.startedAt===r.startedAt&&s.completedAt===r.completedAt:!1})}function R1(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>{const r=n[i];return r?s.filename===r.filename&&s.mimeType===r.mimeType&&s.size===r.size:!1})}function T1(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>{const r=n[i];return r?s.author===r.author&&s.text===r.text&&s.createdAt===r.createdAt:!1})}function P1(e,n){const s=e.task,i=n.task;return e.queued===n.queued&&e.projectId===n.projectId&&e.globalPaused===n.globalPaused&&e.taskStuckTimeoutMs===n.taskStuckTimeoutMs&&e.onOpenDetail===n.onOpenDetail&&e.addToast===n.addToast&&e.onUpdateTask===n.onUpdateTask&&e.onArchiveTask===n.onArchiveTask&&e.onUnarchiveTask===n.onUnarchiveTask&&e.onDeleteTask===n.onDeleteTask&&e.onRetryTask===n.onRetryTask&&e.onOpenDetailWithTab===n.onOpenDetailWithTab&&e.onOpenMission===n.onOpenMission&&e.onMoveTask===n.onMoveTask&&e.workflowStepNameLookup===n.workflowStepNameLookup&&s.id===i.id&&s.title===i.title&&s.description===i.description&&s.column===i.column&&s.columnMovedAt===i.columnMovedAt&&s.timedExecutionMs===i.timedExecutionMs&&s.updatedAt===i.updatedAt&&s.createdAt===i.createdAt&&s.status===i.status&&s.priority===i.priority&&s.executionMode===i.executionMode&&s.paused===i.paused&&s.error===i.error&&s.size===i.size&&s.blockedBy===i.blockedBy&&s.worktree===i.worktree&&s.baseBranch===i.baseBranch&&s.breakIntoSubtasks===i.breakIntoSubtasks&&s.currentStep===i.currentStep&&s.modelProvider===i.modelProvider&&s.modelId===i.modelId&&s.validatorModelProvider===i.validatorModelProvider&&s.validatorModelId===i.validatorModelId&&s.planningModelProvider===i.planningModelProvider&&s.planningModelId===i.planningModelId&&s.reviewLevel===i.reviewLevel&&s.missionId===i.missionId&&s.assignedAgentId===i.assignedAgentId&&s.mergeRetries===i.mergeRetries&&R1(s.attachments,i.attachments)&&T1(s.comments,i.comments)&&E1(s.dependencies,i.dependencies)&&C1(s.steps,i.steps)&&_1(s.enabledWorkflowSteps,i.enabledWorkflowSteps)&&A1(s.workflowStepResults,i.workflowStepResults)&&Yu(s.prInfo,i.prInfo)&&Yu(s.issueInfo,i.issueInfo)}function I1({task:e,projectId:n,queued:s,onOpenDetail:i,addToast:r,globalPaused:o,onUpdateTask:l,onArchiveTask:c,onUnarchiveTask:u,onDeleteTask:d,onRetryTask:m,onOpenDetailWithTab:h,taskStuckTimeoutMs:f,onOpenMission:p,onMoveTask:g,lastFetchTimeMs:b,workflowStepNameLookup:v}){const[x,y]=a.useState(!1),[j,E]=a.useState(!1),[C,w]=a.useState(!1),[R,S]=a.useState(e.description||""),[O,_]=a.useState(!1),[P,U]=a.useState(e.column==="in-progress"||e.column==="triage"&&e.steps.some(L=>L.status==="done"||L.status==="skipped")),[G,M]=a.useState(null),[T,D]=a.useState(null),[K,J]=a.useState(!1),[te,N]=a.useState(!1),[z,I]=a.useState(()=>Date.now()),k=a.useRef(null),H=a.useRef(!1),Q=a.useRef(null),ue=a.useRef(null),[be,V]=a.useState(!1),{badgeUpdates:ve,subscribeToBadge:B,unsubscribeFromBadge:Y}=af(n),{confirm:X}=Gs(),he=a.useRef(null),de=a.useRef(!1),me=a.useCallback(L=>L instanceof Element?!!L.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);a.useEffect(()=>{S(e.description||"")},[e.id,e.description]),a.useEffect(()=>{if(!K)return;const L=F=>{ue.current&&!ue.current.contains(F.target)&&J(!1)};return document.addEventListener("click",L),()=>document.removeEventListener("click",L)},[K]),a.useEffect(()=>{if(!e.missionId){M(null);return}const L=Gc.get(e.missionId);if(L){M(L);return}let F=!1;return h1(e.missionId,n).then(ge=>{F||M(ge)}),()=>{F=!0}},[e.missionId,n]),a.useEffect(()=>{if(!e.assignedAgentId){D(null);return}const L=Jc.get(e.assignedAgentId);if(L){D(L);return}D(null);let F=!1;return f1(e.assignedAgentId,n).then(ge=>{F||D(ge)}),()=>{F=!0}},[e.assignedAgentId,n]),a.useEffect(()=>{if(C&&k.current){const L=k.current;L.focus(),L.style.height="auto",L.style.height=L.scrollHeight+"px"}},[C]),a.useEffect(()=>{if(typeof IntersectionObserver>"u"){V(!0);return}const L=Q.current;if(!L)return;const F=new IntersectionObserver(([ge])=>{V(ge?.isIntersecting??!0)},{rootMargin:"200px"});return F.observe(L),()=>F.disconnect()},[C,e.id]);const se=a.useCallback(L=>{L.dataTransfer.setData("text/plain",e.id),L.dataTransfer.effectAllowed="move",y(!0)},[e.id]),_e=a.useCallback(()=>{y(!1)},[]),Fe=a.useCallback(L=>L.dataTransfer.types.includes("Files"),[]),Te=a.useCallback(L=>{Fe(L)&&(L.preventDefault(),L.stopPropagation(),L.dataTransfer.dropEffect="copy",E(!0))},[Fe]),st=a.useCallback(L=>{Fe(L)&&(L.preventDefault(),L.stopPropagation(),E(!1))},[Fe]),nt=a.useCallback(async L=>{if(!Fe(L))return;L.preventDefault(),L.stopPropagation(),E(!1);const F=Array.from(L.dataTransfer.files);for(const ge of F)try{await Cr(e.id,ge,n),r(`Attached ${ge.name} to ${e.id}`,"success")}catch(ze){r(`Failed to attach ${ge.name}: ${ke(ze)}`,"error")}},[e.id,Fe,r]),qe=a.useCallback(()=>{C||i(e)},[e,i,C]),Xe=a.useCallback(L=>{if(H.current){H.current=!1;return}me(L.target)||qe()},[qe,me]),$e=a.useCallback(L=>{const F=L.touches[0];F&&(he.current={x:F.clientX,y:F.clientY,time:Date.now()},de.current=!1)},[]),Ue=a.useCallback(L=>{if(!he.current)return;const F=L.touches[0];if(!F)return;const ge=Math.abs(F.clientX-he.current.x),ze=Math.abs(F.clientY-he.current.y);(ge>Qu||ze>Qu)&&(de.current=!0)},[]),oe=a.useCallback(L=>{if(me(L.target)||!he.current)return;const ge=Date.now()-he.current.time<$1,ze=!de.current;ge&&ze&&(H.current=!0,qe()),he.current=null,de.current=!1},[qe,me]),je=a.useCallback(async(L,F)=>{L.stopPropagation();try{const ge=await Sr(F,n);i(ge)}catch{r(`Failed to load dependency ${F}`,"error")}},[i,r]),ie=e.status==="failed",Ae=e.paused===!0,Le=g1(e.priority),we=Le!==_s,Ee=qo(e,f,b),Ve=e.column==="triage"&&e.status==="awaiting-approval",rt=e.column==="archived",xe=!o&&!s&&!ie&&!Ae&&!Ee&&!Ve&&(e.column==="in-progress"||Vu.has(e.status)),ce=!s&&!Ae&&!C&&!rt,Pe=x1.has(e.column)&&!xe&&!Ae&&!s&&l,pe=!!(e.prInfo||e.issueInfo),Re=!!(e.assignedAgentId&&T===null),Qe=a.useMemo(()=>{const L=[];return e.modelProvider&&L.push(e.modelProvider),e.validatorModelProvider&&!L.includes(e.validatorModelProvider)&&L.push(e.validatorModelProvider),e.planningModelProvider&&!L.includes(e.planningModelProvider)&&L.push(e.planningModelProvider),L},[e.modelProvider,e.validatorModelProvider,e.planningModelProvider]),Ie=a.useMemo(()=>of(e,v),[e.steps,e.enabledWorkflowSteps,e.workflowStepResults,v]),bt=Ie.total>0&&(e.status==="executing"||e.column==="in-progress");a.useEffect(()=>{if(e.column!=="in-progress"&&e.column!=="in-review")return;const L=e.status!=null&&Wu.has(e.status);if(e.column==="in-progress"){const ge=ur(e,Date.now()),ze=Ku(e,Date.now()),Be=mr(e,Date.now());if(ge==null&&ze==null&&Be==null)return}if(!L&&e.column==="in-review"){const ge=ur(e,Date.now()),ze=mr(e,Date.now());if(ge==null&&ze==null)return}I(Date.now());const F=window.setInterval(()=>{I(Date.now())},w1);return()=>window.clearInterval(F)},[e.column,e.status,e.columnMovedAt,e.updatedAt,e.workflowStepResults,e.timedExecutionMs,e.executionStartedAt,e.executionCompletedAt]);const ee=a.useMemo(()=>{if(!y1.has(e.column))return null;if(e.status!=null&&Wu.has(e.status)){const Ke=N1(e,z);if(Ke!=null){const dt=Ju(Ke);if(dt){const Xt=cf(e,z),Cn=Xt==null?null:Gu(Xt),pn=Cn?`Execution time ${dt}. Merge phase ${Cn}`:`Execution time ${dt}. Merging`;return{label:dt,title:pn,ariaLabel:pn}}}}if(e.column==="in-progress"){const Ke=ur(e,z)??Ku(e,z)??mr(e,z);if(Ke==null)return null;const dt=Gu(Ke);return dt?{label:dt,title:`In progress ${dt}`,ariaLabel:`In progress ${dt}`}:null}const F=ur(e,z)??mr(e,z);if(F==null)return null;const ge=Ju(F);if(!ge)return null;const ze=k1(e);if(ze==null)return{label:ge,title:`Execution time ${ge}`,ariaLabel:`Execution time ${ge}`};const Be=new Date(ze).toLocaleString();return{label:ge,title:`Execution time ${ge}. Completed ${Be}`,ariaLabel:`Execution time ${ge}. Completed ${Be}`}},[e.column,e.status,e.columnMovedAt,e.timedExecutionMs,e.updatedAt,e.workflowStepResults,e.log,e.executionStartedAt,e.executionCompletedAt,z]);a.useEffect(()=>{if(!pe||!be){Y(e.id);return}return B(e.id),()=>{Y(e.id)}},[pe,be,B,e.id,Y]);const re=ve.get(`${n??"default"}:${e.id}`),Se=e.column==="in-progress"||e.column==="in-review",ot=a.useMemo(()=>e.steps.map(L=>`${L.name}:${L.status}`).join("|"),[e.steps]),{stats:ne}=r1(e.id,e.column,e.mergeDetails?.commitSha,n,{enabled:be,worktree:e.worktree,stepVersion:Se?ot:void 0,pollIntervalMs:Se?3e4:void 0}),Ze=a.useMemo(()=>t1(e.id,n),[e.id,n]),ft=a.useMemo(()=>{const L=re?.prInfo,F=re?.timestamp,ge=Ze?.result?.prInfo,ze=Ze?.timestamp?new Date(Ze.timestamp).toISOString():void 0,Be=e.prInfo,Ke=e.prInfo?.lastCheckedAt??e.updatedAt;let dt=Ho(L,F,Be,Ke);const Xt=F&&F>=Ke?F:Ke;return ge&&ze&&(!Xt||ze>Xt)&&(dt=ge),dt},[re,Ze,e.prInfo,e.updatedAt]),gt=a.useMemo(()=>{const L=re?.issueInfo,F=re?.timestamp,ge=Ze?.result?.issueInfo,ze=Ze?.timestamp?new Date(Ze.timestamp).toISOString():void 0,Be=e.issueInfo,Ke=e.issueInfo?.lastCheckedAt??e.updatedAt;let dt=Ho(L,F,Be,Ke);const Xt=F&&F>=Ke?F:Ke;return ge&&ze&&(!Xt||ze>Xt)&&(dt=ge),dt},[re,Ze,e.issueInfo,e.updatedAt]),St=a.useCallback(L=>{L?.stopPropagation(),!(!Pe||O)&&(w(!0),S(e.description||""))},[Pe,O,e.description]),Nt=a.useCallback(()=>{w(!1),S(e.description||"")},[e.description]),pt=a.useCallback(()=>R!==(e.description||""),[R,e.description]),kt=a.useCallback(async()=>{if(!(!l||O)){if(!pt()){Nt();return}_(!0);try{await l(e.id,{description:R.trim()||void 0}),r(`Updated ${e.id}`,"success"),w(!1)}catch(L){r(`Failed to update ${e.id}: ${ke(L)}`,"error")}finally{_(!1)}}},[l,e.id,R,O,pt,Nt,r]),Ht=a.useCallback(L=>{L.key==="Enter"&&!L.shiftKey?(L.preventDefault(),kt()):L.key==="Escape"&&(L.preventDefault(),Nt())},[kt,Nt]),$t=a.useCallback(()=>{setTimeout(()=>{const L=document.activeElement;L===k.current||L?.closest(".card-editing-content")||(pt()?kt():Nt())},0)},[pt,kt,Nt]),Tt=a.useCallback(L=>{Pe&&(L.stopPropagation(),St(L))},[Pe,St]),Mt=a.useCallback(L=>{L.stopPropagation(),St(L)},[St]),Ot=a.useCallback(L=>{S(L.target.value);const F=L.target;F.style.height="auto",F.style.height=F.scrollHeight+"px"},[]),zt=a.useCallback(L=>{L.stopPropagation(),c&&c(e.id).then(()=>{r(`Archived ${e.id}`,"success")}).catch(F=>{r(`Failed to archive ${e.id}: ${ke(F)}`,"error")})},[r,c,e.id]),Ft=a.useCallback(L=>{L.stopPropagation(),u&&u(e.id).then(()=>{r(`Unarchived ${e.id}`,"success")}).catch(F=>{r(`Failed to unarchive ${e.id}: ${ke(F)}`,"error")})},[r,u,e.id]),Et=a.useCallback(async L=>{if(L.stopPropagation(),!(!d||!await X({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0})))try{await d(e.id),r(`Deleted ${e.id}`,"success")}catch(ge){const ze=M1(ge);if(!ze||ze.dependentIds.length===0){r(`Failed to delete ${e.id}: ${ke(ge)}`,"error");return}const Be=ze.dependentIds.join(", ");if(!await X({title:"Force Delete Task",message:`${e.id} is a dependency of ${Be}.
|
|
622
|
-
|
|
623
|
-
Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await d(e.id,{removeDependencyReferences:!0}),r(`Deleted ${e.id} after removing dependency references`,"success")}catch(dt){r(`Failed to delete ${e.id}: ${ke(dt)}`,"error")}}},[r,X,d,e.id]),Pt=a.useCallback(L=>{L.stopPropagation(),h?.(e,"changes")},[e,h]),Dt=a.useCallback(L=>{L.stopPropagation(),U(F=>!F)},[]),Wt=a.useCallback(L=>{L.stopPropagation(),e.missionId&&p&&p(e.missionId)},[e.missionId,p]),It=a.useCallback(L=>{L.stopPropagation(),J(F=>!F)},[]),Rt=a.useCallback((L,F)=>{L.stopPropagation(),J(!1),g&&g(e.id,F).then(()=>{r(`Moved ${e.id} to ${Wn[F]}`,"success")}).catch(ge=>{r(`Failed to move ${e.id}: ${ke(ge)}`,"error")})},[r,g,e.id]),fe=a.useCallback(async L=>{if(L.stopPropagation(),!(!m||te)){N(!0);try{await m(e.id)}catch(F){r(`Failed to retry ${e.id}: ${ke(F)}`,"error")}finally{N(!1)}}},[r,te,m,e.id]),Oe=`card${x?" dragging":""}${s?" queued":""}${xe?" agent-active":""}${ie?" failed":""}${Ae?" paused":""}${Ee?" stuck":""}${Ve?" awaiting-approval":""}${j?" file-drop-target":""}${C?" card-editing":""}${O?" card-saving":""}`,ut=(()=>{if(e.column==="in-progress"){const L=ne?.filesChanged,F=L==null||L===0?e.modifiedFiles?.length:void 0,ge=L!=null&&L>0?L:F;return ge==null||ge===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:Pt,disabled:!h,children:[t.jsx(ts,{size:12}),t.jsxs("span",{children:[ge," ",ge===1?"file":"files"," changed"]})]})}if(e.column==="in-review"){const L=ne?.filesChanged,F=L==null||L===0?e.modifiedFiles?.length:void 0,ge=L!=null&&L>0?L:F;return ge==null||ge===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:Pt,disabled:!h,children:[t.jsx(ts,{size:12}),t.jsxs("span",{children:[ge," ",ge===1?"file":"files"," changed"]})]})}if(e.column==="done"){const L=ne?.filesChanged,F=e.mergeDetails?.filesChanged,ge=L??F;if(ge!=null&&ge>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:Pt,disabled:!h,children:[t.jsx(ts,{size:12}),t.jsxs("span",{children:[ge," ",ge===1?"file":"files"," changed"]})]});const ze=e.modifiedFiles?.length;if(ze!=null&&ze>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:Pt,disabled:!h,children:[t.jsx(ts,{size:12}),t.jsxs("span",{children:[ze," ",ze===1?"file":"files"," changed"]})]})}return null})();return C?t.jsx("div",{ref:Q,className:Oe,"data-id":e.id,onDoubleClick:Tt,children:t.jsxs("div",{className:"card-editing-content",children:[t.jsx("textarea",{ref:k,className:"card-edit-desc-textarea",placeholder:"Task description",value:R,onChange:Ot,onKeyDown:Ht,onBlur:$t,disabled:O,rows:4}),O&&t.jsxs("div",{className:"card-edit-loading",children:[t.jsx("span",{className:"card-edit-loading-spinner"}),t.jsx("span",{className:"card-edit-loading-text",children:"Saving..."})]})]})}):t.jsxs("div",{ref:Q,className:Oe,"data-id":e.id,draggable:ce,onDragStart:ce?se:void 0,onDragEnd:ce?_e:void 0,onDragOver:Te,onDragLeave:st,onDrop:nt,onClick:Xe,onTouchStart:$e,onTouchMove:Ue,onTouchEnd:oe,onDoubleClick:Tt,children:[t.jsxs("div",{className:"card-header",children:[t.jsx("span",{className:"card-id",children:e.id}),Ae&&t.jsx("span",{className:"card-status-badge paused",children:"paused"}),!Ae&&e.status&&e.status!=="queued"&&t.jsx("span",{className:`card-status-badge card-status-badge--${e.column}${Ve?" awaiting-approval":""}${Vu.has(e.status)?" pulsing":""}${ie?" failed":""}${Ee?" stuck":""}`,children:Ee?"Stuck":Ve?"Awaiting Approval":e.status}),Ee&&(Ae||!e.status||e.status==="queued")&&t.jsx("span",{className:"card-status-badge stuck",children:"Stuck"}),pe&&t.jsx(sf,{prInfo:ft,issueInfo:gt}),we&&t.jsx("span",{className:`card-priority-badge card-priority-badge--${Le}`,children:Le}),e.executionMode==="fast"&&t.jsx("span",{className:"card-execution-mode-badge card-execution-mode-badge--fast",children:"Fast"}),e.missionId&&t.jsxs("span",{className:"card-mission-badge",onClick:Wt,title:`Mission: ${G??e.missionId}`,role:p?"button":void 0,tabIndex:p?0:void 0,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[t.jsx(ks,{size:11}),p1(G??e.missionId)]}),t.jsxs("div",{className:"card-header-actions",children:[Pe&&t.jsx("button",{className:"card-edit-btn",onClick:Mt,title:"Edit task","aria-label":"Edit task",children:t.jsx(hs,{size:12})}),e.column==="triage"&&d&&t.jsx("button",{className:"card-delete-btn",onClick:Et,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:zt,title:"Archive task","aria-label":"Archive task",children:"Archive"}),e.column==="archived"&&u&&t.jsx("button",{className:"card-unarchive-btn",onClick:Ft,title:"Unarchive task","aria-label":"Unarchive task",children:"Unarchive"}),e.column==="in-progress"&&g&&t.jsxs("div",{className:"card-send-back",ref:ue,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:It,title:"Send back","aria-label":"Send back","aria-haspopup":"menu","aria-expanded":K,children:["Send back",t.jsx(Yt,{size:10})]}),K&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:Wc["in-progress"].filter(L=>L!=="in-review").map(L=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:F=>Rt(F,L),children:Wn[L]},L))})]}),e.column==="in-review"&&g&&t.jsxs("div",{className:"card-send-back",ref:ue,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:It,title:"Move task","aria-label":"Move task","aria-haspopup":"menu","aria-expanded":K,children:["Move",t.jsx(Yt,{size:10})]}),K&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:Wc["in-review"].map(L=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:F=>Rt(F,L),children:L==="done"?"Done (no merge)":Wn[L]},L))})]}),e.size&&t.jsx("span",{className:`card-size-badge size-${e.size.toLowerCase()}`,children:e.size})]})]}),ie&&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:fe,disabled:te,children:[t.jsx(wv,{size:12}),te?"Retrying…":"Retry"]})]}),t.jsx("div",{className:"card-title",title:e.title||e.description||void 0,children:Zu(e.title,Xu)||Zu(e.description,Xu)||e.id}),bt&&(()=>{const L=Ie.completed/Ie.total*100;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"card-progress",children:[t.jsx("div",{className:"card-progress-bar",children:t.jsx("div",{className:"card-progress-fill",style:{width:`${L}%`,backgroundColor:v1[e.column]}})}),t.jsxs("span",{className:"card-progress-label",children:[Ie.completed,"/",Ie.total]})]}),t.jsxs("button",{type:"button",className:"card-steps-toggle",onClick:Dt,"aria-expanded":P,"aria-label":P?"Hide steps":"Show steps",children:[t.jsxs("span",{children:[Ie.total," step",Ie.total===1?"":"s"]}),t.jsx(Yt,{size:14,className:`card-steps-toggle-icon${P?" expanded":""}`})]}),P&&t.jsx("div",{className:"card-steps-list",children:Ie.items.map(F=>{const ge=F.source==="workflow"&&F.status==="failed";return t.jsxs("div",{className:"card-step-item",children:[t.jsx("span",{className:`card-step-dot card-step-dot--${F.status}${ge?" card-step-dot--workflow-failed":""}`,"aria-hidden":"true"}),t.jsx("span",{className:`card-step-name${F.status==="done"?" completed":""}`,children:F.name}),F.source==="workflow"&&t.jsx("span",{className:`card-step-workflow-badge card-step-workflow-badge--${F.phase}`,title:"Workflow check",children:"workflow"})]},F.id)})})]})})(),(ut||ee)&&t.jsxs("div",{className:"card-footer-row",children:[ut,ee&&t.jsxs("span",{className:"card-time-indicator",title:ee.title,"aria-label":ee.ariaLabel,children:[t.jsx(Ei,{size:12}),t.jsx("span",{children:ee.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(L=>t.jsxs("span",{className:"card-dep-badge clickable",onClick:F=>void je(F,L),title:`Click to view ${L}`,children:[t.jsx(va,{size:12,style:{verticalAlign:"middle"}})," ",L]},L))}),e.blockedBy&&t.jsxs("span",{className:"card-scope-badge","data-tooltip":`Blocked by ${e.blockedBy} (file overlap)`,children:[t.jsx(qi,{size:12,style:{verticalAlign:"middle"}})," ",e.blockedBy]}),(s||e.status==="queued")&&e.column!=="in-progress"&&t.jsxs("span",{className:"queued-badge",children:[t.jsx(Ei,{size:12,style:{verticalAlign:"middle"}})," Queued"]})]}),(e.assignedAgentId||Qe.length>0)&&t.jsxs("div",{className:"card-agent-row",children:[Qe.length>0&&t.jsx("span",{className:"card-provider-icons","data-testid":"card-provider-icons",children:Qe.map(L=>t.jsx(Rn,{provider:L,size:"sm"},L))}),e.assignedAgentId&&t.jsxs("span",{className:`card-agent-badge${Re?" card-agent-badge--loading":""}`,title:`Assigned to ${T??e.assignedAgentId}`,children:[t.jsx(En,{size:11}),t.jsx("span",{className:"card-agent-badge-text",children:b1(T??e.assignedAgentId,15)})]})]}),t.jsx(dl,{slotId:"task-card-badge",projectId:n})]})}const Qu=10,$1=300,Xu=140;function Zu(e,n){return e?e.length>n?e.slice(0,n)+"…":e:""}const Mr=a.memo(I1,P1);Mr.displayName="TaskCard";function D1({label:e,activeTasks:n,queuedTasks:s,projectId:i,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:u,onOpenDetailWithTab:d,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p}){return t.jsxs("div",{className:"worktree-group",children:[t.jsxs("div",{className:"worktree-group-header",children:[t.jsx("span",{className:"worktree-icon",children:e==="Up Next"||e==="Unassigned"?t.jsx(Vb,{size:14}):t.jsx(Ks,{size:14})}),t.jsx("span",{className:"worktree-label",children:e})]}),n.map(g=>t.jsx(Mr,{task:g,projectId:i,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:u,onOpenDetailWithTab:d,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p},g.id)),s.map(g=>t.jsx(Mr,{task:g,projectId:i,queued:!0,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:u,onOpenDetailWithTab:d,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p},g.id))]})}const df=a.memo(D1);df.displayName="WorktreeGroup";function em(e){return e.toLowerCase().replace(/[-_./]/g,"")}function L1(e,n){let s=0;for(let i=0;i<n.length&&s<e.length;i++)e[s]===n[i]&&s++;return s===e.length}function z1(e,n,s){const i=e.length,r=n.length;if(i===0)return!0;if(r===0)return!1;let o=new Array(r+1).fill(0),l=new Array(r+1).fill(0);for(let c=1;c<=i;c++){const u=new Array(r+1);u[0]=c;for(let d=1;d<=r;d++){const m=e[c-1]===n[d-1]?0:1;u[d]=Math.min(l[d]+1,u[d-1]+1,l[d-1]+m),c>=2&&d>=2&&e[c-1]===n[d-2]&&e[c-2]===n[d-1]&&(u[d]=Math.min(u[d],o[d-2]+1))}o=l,l=u}for(let c=0;c<=r;c++)if(l[c]<=s)return!0;return!1}function O1(e,n){const s=em(e),i=em(n);if(s.length===0||i.includes(s))return!0;const r=i.split(/\s+/).filter(Boolean);for(const o of r)if(s.length>=3&&L1(s,o)||s.length>=4&&z1(s,o,1))return!0;return!1}function F1(e,n){const s=n.toLowerCase().trim().split(/\s+/).filter(Boolean);return s.length===0?e:e.filter(i=>{const r=`${i.provider} ${i.id} ${i.name}`;return s.every(o=>O1(o,r))})}function ns({models:e,value:n,onChange:s,placeholder:i="Select a model…",disabled:r=!1,id:o,label:l,favoriteProviders:c=[],onToggleFavorite:u,favoriteModels:d=[],onToggleModelFavorite:m,noChangeValue:h,noChangeLabel:f="No change"}){const[p,g]=a.useState(!1),[b,v]=a.useState(""),[x,y]=a.useState(0),[j,E]=a.useState(null),[C,w]=a.useState(null),R=a.useRef(null),S=a.useRef(null),O=a.useRef(null),_=a.useRef(null),P=a.useRef(null),U=a.useMemo(()=>F1(e,b),[e,b]),G=a.useMemo(()=>U.reduce((X,he)=>((X[he.provider]??=[]).push(he),X),{}),[U]),M=a.useMemo(()=>{const X=[];for(const he of d){const de=he.indexOf("/");if(de===-1)continue;const me=he.slice(0,de),se=he.slice(de+1),_e=U.find(Fe=>Fe.provider===me&&Fe.id===se);_e&&X.push({model:_e,fullId:he})}return X},[d,U]),T=a.useMemo(()=>{const X=Object.entries(G),he=new Set(c);return X.sort(([de],[me])=>{const se=he.has(de),_e=he.has(me);if(se&&!_e)return-1;if(!se&&_e)return 1;if(se&&_e){const Fe=c.indexOf(de),Te=c.indexOf(me);if(Fe!==Te)return Fe-Te}return de.localeCompare(me)})},[G,c]),D=typeof h=="string"&&h.length>0,K=a.useMemo(()=>{if(!n||D&&n===h)return null;const X=n.indexOf("/");return X===-1?null:n.slice(0,X)},[D,h,n]),J=a.useMemo(()=>{const X=[];return D&&X.push({type:"no-change",value:h,label:f}),X.push({type:"default",value:"",label:"Use default"}),X},[D,f,h]),te=a.useMemo(()=>{const X=[...J];for(const{model:he,fullId:de}of M)X.push({type:"favorite",value:de,label:he.name,provider:he.provider});return T.forEach(([he,de])=>{X.push({type:"provider",value:`__group_${he}`,label:he,provider:he}),de.forEach(me=>{X.push({type:"model",value:`${me.provider}/${me.id}`,label:me.name,provider:me.provider})})}),X},[M,T,J]),N=a.useMemo(()=>{if(D&&n===h)return f;if(!n)return"Use default";const X=n.indexOf("/");if(X===-1)return n;const he=n.slice(0,X),de=n.slice(X+1);return e.find(se=>se.provider===he&&se.id===de)?.name||n},[D,f,h,n,e]),z=a.useMemo(()=>te.findIndex(X=>X.value===n),[te,n]),I=a.useCallback(()=>{const X=window.visualViewport;return X&&X.height>0&&X.width>0?{width:X.width,height:X.height,offsetTop:X.offsetTop,offsetLeft:X.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),k=a.useCallback(()=>{const{height:X}=I(),he=typeof window.matchMedia=="function",de=he?window.matchMedia("(max-width: 640px)").matches:!1,me=he?window.matchMedia("(max-width: 768px)").matches:!1;return X<=0?320:de?Math.min(X*.6,360):me?Math.min(X*.7,420):320},[I]),H=a.useCallback(()=>{const X=S.current;if(!X)return;const he=X.getBoundingClientRect(),{width:de,height:me,offsetTop:se,offsetLeft:_e}=I(),Fe=16,Te=16,st=4,nt=k(),qe=he.bottom-se,Xe=he.top-se,$e=he.left-_e,Ue=me-qe,oe=Xe,je=Math.max(Ue-Te-st,160),ie=Math.max(oe-Te-st,160),Ae=Ue<nt&&oe>Ue,Le=Math.max(Math.min(Ae?ie:je,nt),160),we=Math.min(he.width,de-Fe*2),Ee=Math.min(Math.max($e,Fe),de-Fe-we)+_e,Ve=Ae?Math.max(Te+se,Xe-Le-st+se):Math.min(qe+st+se,me+se-Te-Le);E({top:Ve,left:Ee,width:we,maxHeight:Le})},[I,k]);a.useEffect(()=>{w(document.body)},[]);const Q=a.useRef(!1);a.useEffect(()=>{if(!p){Q.current=!1;return}if(Q.current||te.length===0)return;const X=te.findIndex((he,de)=>de>=(z>=0?z:0)&&he.type!=="provider");y(X>=0?X:0),Q.current=!0},[p,te,z]),a.useEffect(()=>{p&&Q.current&&(y(0),P.current&&(P.current.scrollTop=0))},[b,p]),a.useEffect(()=>{if(!p)return;H();const X=requestAnimationFrame(()=>_.current?.focus());return()=>cancelAnimationFrame(X)},[p,H]),a.useEffect(()=>{if(!p)return;const X=()=>H();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const he=window.visualViewport;return he&&(he.addEventListener("resize",X),he.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),he&&(he.removeEventListener("resize",X),he.removeEventListener("scroll",X))}},[p,H]),a.useEffect(()=>{if(!p)return;const X=he=>{const de=he.target,me=R.current?.contains(de),se=O.current?.contains(de);!me&&!se&&(g(!1),v(""))};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[p]);const ue=a.useCallback(X=>{switch(X.key){case"ArrowDown":if(X.preventDefault(),!p)g(!0);else{let he=x;for(let de=1;de<=te.length;de++){const me=(x+de)%te.length;if(te[me]?.type!=="provider"){he=me;break}}y(he)}break;case"ArrowUp":if(X.preventDefault(),p){let he=x;for(let de=1;de<=te.length;de++){const me=(x-de+te.length)%te.length;if(te[me]?.type!=="provider"){he=me;break}}y(he)}break;case"Enter":if(X.preventDefault(),p){const he=te[x];he&&he.type!=="provider"&&he.type!=="favorite"&&(s(he.value),g(!1),v(""))}else g(!0);break;case"Escape":X.preventDefault(),g(!1),v("");break;case"Tab":p&&(g(!1),v(""));break}},[p,x,te,s]),be=a.useCallback(X=>{s(X),g(!1),v("")},[s]),V=a.useCallback(()=>{v(""),_.current?.focus()},[]),ve=a.useCallback(()=>{r||g(X=>!X)},[r]);a.useEffect(()=>{if(p&&P.current){const X=P.current.querySelector(`[data-index="${x}"]`);X&&typeof X.scrollIntoView=="function"&&X.scrollIntoView({block:"nearest"})}},[x,p]);const B=b.length>0,Y=p&&j?t.jsxs("div",{ref:O,className:"model-combobox-dropdown model-combobox-dropdown--portal",role:"listbox","data-testid":"model-combobox-portal",onKeyDown:ue,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:_,type:"text",className:"model-combobox-search",placeholder:"Filter models…",value:b,onChange:X=>v(X.target.value),onClick:X=>X.stopPropagation()}),B&&t.jsx("button",{type:"button",className:"model-combobox-clear",onClick:V,"aria-label":"Clear filter",children:"×"})]}),t.jsxs("div",{className:"model-combobox-results-count",children:[U.length," model",U.length!==1?"s":""]}),t.jsxs("div",{ref:P,className:"model-combobox-list",children:[J.map((X,he)=>t.jsx("div",{"data-index":he,className:`model-combobox-option ${x===he?"model-combobox-option--highlighted":""} ${n===X.value?"model-combobox-option--selected":""}`,onClick:()=>be(X.value),onMouseEnter:()=>y(he),role:"option","aria-selected":n===X.value,children:t.jsx("span",{className:"model-combobox-option-text model-combobox-option-text--default",children:X.label})},`${X.type}-${X.value}`)),M.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"model-combobox-divider"}),M.map(({model:X,fullId:he},de)=>{const me=de+J.length,se=x===me,_e=n===he;return t.jsxs("div",{"data-index":me,className:`model-combobox-option model-combobox-option--favorite ${se?"model-combobox-option--highlighted":""} ${_e?"model-combobox-option--selected":""}`,onClick:()=>be(he),onMouseEnter:()=>y(me),role:"option","aria-selected":_e,children:[t.jsxs("span",{className:"model-combobox-option-main",children:[t.jsx("span",{className:"model-combobox-option-icon",children:t.jsx(Rn,{provider:X.provider,size:"sm"})}),t.jsx("span",{className:"model-combobox-option-text",children:X.name})]}),t.jsx("span",{className:"model-combobox-option-id",children:X.id}),m&&t.jsx("button",{type:"button",className:"model-combobox-option-favorite model-combobox-option-favorite--active",onClick:Fe=>{Fe.stopPropagation(),m(he)},title:"Remove from favorites","aria-label":`Remove ${X.name} from favorites`,children:"★"})]},he)}),t.jsx("div",{className:"model-combobox-divider"})]}),T.map(([X,he])=>{const de=te.findIndex(_e=>_e.value===`__group_${X}`),me=c.includes(X),se=he.filter(_e=>{const Fe=`${_e.provider}/${_e.id}`;return!d.includes(Fe)});return se.length===0?null:t.jsxs("div",{className:"model-combobox-group",children:[t.jsxs("div",{className:"model-combobox-optgroup","data-index":de,children:[t.jsx(Rn,{provider:X,size:"sm"}),t.jsx("span",{className:"model-combobox-optgroup-text",children:X}),u&&t.jsx("button",{type:"button",className:`model-combobox-optgroup-favorite ${me?"model-combobox-optgroup-favorite--active":""}`,onClick:_e=>{_e.stopPropagation(),u(X)},title:me?"Remove from favorites":"Add to favorites","aria-label":me?`Remove ${X} from favorites`:`Add ${X} to favorites`,children:"★"})]}),se.map(_e=>{const Fe=`${_e.provider}/${_e.id}`,Te=te.findIndex(Xe=>Xe.value===Fe),st=x===Te,nt=n===Fe,qe=d.includes(Fe);return t.jsxs("div",{"data-index":Te,className:`model-combobox-option ${st?"model-combobox-option--highlighted":""} ${nt?"model-combobox-option--selected":""}`,onClick:()=>be(Fe),onMouseEnter:()=>y(Te),role:"option","aria-selected":nt,children:[t.jsx("span",{className:"model-combobox-option-text",children:_e.name}),t.jsx("span",{className:"model-combobox-option-id",children:_e.id}),m&&t.jsx("button",{type:"button",className:`model-combobox-option-favorite ${qe?"model-combobox-option-favorite--active":""}`,onClick:Xe=>{Xe.stopPropagation(),m(Fe)},title:qe?"Remove from favorites":"Add to favorites","aria-label":qe?`Remove ${_e.name} from favorites`:`Add ${_e.name} to favorites`,children:qe?"★":"☆"})]},Fe)})]},X)}),U.length===0&&B&&t.jsxs("div",{className:"model-combobox-no-results",children:["No models match '",b,"'"]})]})]}):null;return t.jsxs(t.Fragment,{children:[t.jsx("div",{ref:R,className:"model-combobox",onKeyDown:ue,children:t.jsxs("button",{ref:S,type:"button",id:o,className:"model-combobox-trigger",onClick:ve,disabled:r,"aria-haspopup":"listbox","aria-expanded":p,"aria-label":l,children:[K&&t.jsx("span",{className:"model-combobox-trigger-icon",children:t.jsx(Rn,{provider:K,size:"sm"})}),t.jsx("span",{className:"model-combobox-trigger-text",children:N||i}),t.jsx("span",{className:"model-combobox-trigger-arrow",children:"▼"})]})}),C&&Y?pa.createPortal(Y,C):null]})}function Ed(e,n){return typeof n!="string"||n.length===0?e:`kb:${n}:${e}`}function Yn(e,n){return typeof window>"u"?null:window.localStorage.getItem(Ed(e,n))}function fs(e,n,s){typeof window>"u"||window.localStorage.setItem(Ed(e,s),n)}function Ar(e,n){typeof window>"u"||window.localStorage.removeItem(Ed(e,n))}const U1=1e4,B1=1e3;function ml(){const[e,n]=a.useState([]),[s,i]=a.useState(!0),[r,o]=a.useState(null),l=a.useRef(null),c=a.useRef(0),u=a.useCallback(async()=>{try{o(null);const p=await Bo();n(p)}catch(p){o(p instanceof Error?p.message:"Failed to fetch nodes")}},[]);a.useEffect(()=>{let p=!1;async function g(){i(!0);try{const v=await Bo();p||(n(v),o(null))}catch(v){p||o(v instanceof Error?v.message:"Failed to fetch nodes")}finally{p||i(!1)}}g();const b=()=>{if(document.visibilityState!=="visible")return;const v=Date.now();v-c.current<B1||(c.current=v,u())};return document.addEventListener("visibilitychange",b),()=>{p=!0,document.removeEventListener("visibilitychange",b)}},[u]),a.useEffect(()=>{if(!s)return l.current=setInterval(()=>{u()},U1),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async p=>{const g=await Pj(p);return n(b=>[...b,g]),g},[]),m=a.useCallback(async(p,g)=>{const b=await Ij(p,g);return n(v=>v.map(x=>x.id===p?b:x)),b},[]),h=a.useCallback(async p=>{await $j(p),n(g=>g.filter(b=>b.id!==p))},[]),f=a.useCallback(async p=>{const g=await Dj(p);n(b=>b.map(v=>v.id===p?{...v,status:g.status,updatedAt:g.checkedAt}:v))},[]);return{nodes:e,loading:s,error:r,refresh:u,register:d,update:m,unregister:h,healthCheck:f}}const Ka="kb-quick-entry-text",H1=["image/png","image/jpeg","image/gif","image/webp"];function q1(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function Dl(e,n){return e&&n?`${e}/${n}`:""}function Ll(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 uf({onCreate:e,addToast:n,tasks:s=[],availableModels:i,onPlanningMode:r,onSubtaskBreakdown:o,projectId:l,autoExpand:c=!0,favoriteProviders:u,favoriteModels:d,onToggleFavorite:m,onToggleModelFavorite:h}){const[f,p]=a.useState(()=>typeof window<"u"&&Yn(Ka,l)||""),[g,b]=a.useState(!1),[v,x]=a.useState(!1),[y,j]=a.useState(!1),E=a.useRef(null),C=a.useRef(null),w=a.useRef(!1),R=a.useRef(l),[S,O]=a.useState([]),_=a.useRef([]),[P,U]=a.useState([]),[G,M]=a.useState(!1),[T,D]=a.useState(""),[K,J]=a.useState(null),[te,N]=a.useState([]),[z,I]=a.useState(void 0),[k,H]=a.useState(!1),[Q,ue]=a.useState(!1),[be,V]=a.useState(!1),[ve,B]=a.useState(!1),[Y,X]=a.useState(null),[he,de]=a.useState(void 0),[me,se]=a.useState(void 0),[_e,Fe]=a.useState(void 0),[Te,st]=a.useState(void 0),[nt,qe]=a.useState(void 0),[Xe,$e]=a.useState(void 0),Ue=a.useRef(null),oe=a.useRef(null),je=a.useRef(null),ie=a.useRef(null),Ae=a.useRef(null),Le=a.useRef(null),[we,Ee]=a.useState(null),[Ve,rt]=a.useState(null),[xe,ce]=a.useState(null),Pe=a.useRef(null),pe=a.useRef(null),[Re,Qe]=a.useState(null),[Ie]=a.useState(()=>typeof document<"u"?document.body:null),[bt,ee]=a.useState(!1),[re,Se]=a.useState(null),[ot,ne]=a.useState(i??[]),[Ze,ft]=a.useState([]),[gt,St]=a.useState([]),[Nt,pt]=a.useState(null),[kt,Ht]=a.useState(void 0),[$t,Tt]=a.useState(!1),[Mt,Ot]=a.useState(void 0),{nodes:zt}=ml(),[Ft,Et]=a.useState(!1),[Pt,Dt]=a.useState(!1),Wt=a.useRef(null),It=a.useRef(null),[Rt,fe]=a.useState(null),Oe=u??Ze,ut=d??gt,L=!e;a.useEffect(()=>{if(i)ne(i),ee(!1),Se(null);else{let ae=!1;return ee(!0),Se(null),bs().then(Me=>{ae||(ne(Me.models),u||ft(Me.favoriteProviders),d||St(Me.favoriteModels))}).catch(Me=>{ae||Se(ke(Me)||"Failed to load models")}).finally(()=>{ae||ee(!1)}),ll(l).then(Me=>{ae||pt(Me)}).catch(()=>{}),()=>{ae=!0}}},[i,u,d,l]);const F=Dl(he,me),ge=Dl(_e,Te),ze=Dl(nt,Xe),Be=!!(he&&me),Ke=!!(_e&&Te),dt=!!(nt&&Xe),Xt=Number(Be)+Number(Ke)+Number(dt),Cn=kt?Nt?.modelPresets?.find(ae=>ae.id===kt)?.name??"Models":Xt>0?`${Xt} model${Xt===1?"":"s"}`:"Models",pn=a.useCallback((ae,Me)=>{if(!ae||!Me)return"Using default";const it=ot.find(wt=>wt.provider===ae&&wt.id===Me);return it?`${it.provider}/${it.id}`:`${ae}/${Me}`},[ot]);a.useEffect(()=>{p(Yn(Ka,l)||"")},[l]),a.useEffect(()=>{typeof window<"u"&&fs(Ka,f,l)},[f,l]),a.useEffect(()=>{R.current!==l&&(R.current=l,N([]),I(void 0),J(null),H(!1),Ee(null))},[l]),a.useEffect(()=>{typeof window<"u"&&localStorage.removeItem("kb-quick-entry-expanded")},[]),a.useEffect(()=>{_.current=S},[S]),a.useEffect(()=>()=>{_.current.forEach(ae=>URL.revokeObjectURL(ae.previewUrl))},[]);const Kn=a.useCallback(()=>{const ae=E.current;if(!ae)return;ae.style.height="auto";const Me=Math.min(ae.scrollHeight,200);ae.style.height=`${Me}px`},[]);a.useEffect(()=>{v&&Kn()},[f,v,Kn]),a.useEffect(()=>{if(!g&&f===""&&E.current){const ae=setTimeout(()=>{E.current?.focus()},0);return()=>clearTimeout(ae)}},[g,f]),a.useEffect(()=>{G||D("")},[G]),a.useEffect(()=>{if(!Ft)return;const ae=Me=>{const it=Me.target,wt=Wt.current?.contains(it),jt=It.current?.contains(it);!wt&&!jt&&Et(!1)};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[Ft]),a.useEffect(()=>{if(!ve)return;const ae=Me=>{const it=Me.target,wt=Ue.current?.contains(it),jt=oe.current?.contains(it),fn=it instanceof Element&&it.closest?.(".model-combobox-dropdown--portal")!=null;!wt&&!jt&&!fn&&(B(!1),X(null))};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[ve]),a.useEffect(()=>{if(!Q)return;const ae=Me=>{const it=Me.target;Ae.current?.contains(it)||Le.current?.contains(it)||(ue(!1),rt(null))};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[Q]),a.useEffect(()=>{if(!k)return;const ae=Me=>{const it=Me.target;je.current?.contains(it)||ie.current?.contains(it)||(H(!1),Ee(null))};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[k]);const Lt=a.useCallback(()=>{S.forEach(ae=>URL.revokeObjectURL(ae.previewUrl)),O([]),C.current&&(C.current.value=""),p(""),U([]),J(null),H(!1),Ee(null),ue(!1),rt(null),de(void 0),se(void 0),Fe(void 0),st(void 0),qe(void 0),$e(void 0),Ht(void 0),Tt(!1),Ot(void 0),M(!1),B(!1),ce(null),X(null),Et(!1),Dt(!1),x(!1),j(!1),w.current=!0,E.current&&(E.current.style.height="auto"),typeof window<"u"&&Ar(Ka,l)},[S,l]),Zt=a.useCallback(ae=>{if(!ae||ae.length===0)return;const Me=[];for(let it=0;it<ae.length;it++){const wt=ae[it];H1.includes(wt.type)&&Me.push({file:wt,previewUrl:URL.createObjectURL(wt)})}Me.length>0&&O(it=>[...it,...Me])},[]),Ne=a.useCallback(ae=>{g||Zt(ae.clipboardData?.files)},[Zt,g]),et=a.useCallback(ae=>{O(Me=>{const it=Me[ae];return it&&URL.revokeObjectURL(it.previewUrl),Me.filter((wt,jt)=>jt!==ae)})},[]),ln=a.useCallback(async()=>{const ae=f.trim();if(!ae||g||!e)return;const Me=f;b(!0),p("");try{const it=await e({description:ae,column:"triage",dependencies:P.length?P:void 0,...K?{assignedAgentId:K}:{},modelPresetId:kt,modelProvider:Be?he:void 0,modelId:Be?me:void 0,validatorModelProvider:Ke?_e:void 0,validatorModelId:Ke?Te:void 0,planningModelProvider:dt?nt:void 0,planningModelId:dt?Xe:void 0,...$t?{executionMode:"fast"}:{},nodeId:Mt});if(it&&S.length>0){const wt=[];for(const jt of S)try{await Cr(it.id,jt.file,l)}catch{wt.push(jt.file.name)}wt.length>0&&n(`Failed to upload: ${wt.join(", ")}`,"error")}Lt()}catch(it){p(Me),n(ke(it)||"Failed to create task","error")}finally{b(!1)}},[f,g,e,P,K,Be,he,me,Ke,_e,Te,dt,nt,Xe,S,l,n,Lt,$t,Mt]),wn=a.useCallback(ae=>{if(ae.key==="Enter"){if(ae.shiftKey&&v)return;ae.preventDefault(),ln()}else if(ae.key==="Escape"){if(ae.preventDefault(),Y){X(null);return}if(ve){B(!1),ce(null);return}if(G){M(!1);return}if(Ft){Et(!1);return}if(Q){ue(!1),rt(null);return}if(k){H(!1),Ee(null);return}f.trim()&&(p(""),E.current&&(E.current.style.height="auto"),typeof window<"u"&&Ar(Ka,l)),x(!1),j(!1),E.current?.blur()}},[ln,f,v,G,k,Q,ve,Y,Ft,l,j]),Gn=a.useCallback(()=>{w.current&&(w.current=!1)},[]),Tn=a.useCallback(()=>{c&&x(!0)},[c]),Un=a.useCallback(ae=>{U(Me=>Me.includes(ae)?Me.filter(it=>it!==ae):[...Me,ae])},[]),sn=a.useCallback(()=>{const ae=window.visualViewport;return ae&&ae.width>0&&ae.height>0?{width:ae.width,height:ae.height,offsetTop:ae.offsetTop,offsetLeft:ae.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),un=a.useCallback(()=>{const ae=Ue.current;if(!ae)return;const Me=ae.getBoundingClientRect(),{width:it,height:wt,offsetTop:jt,offsetLeft:fn}=sn(),mn=16,en=16,on=4,xn=it<=768,qn=Math.min(xn?wt*.6:wt*.5,360),On=Math.max(Me.width*1.35,320),tt=xn?Math.min(it-mn*2,360):On,At=Math.min(tt,Math.max(it-mn*2,240)),Mn=Me.top-jt,xs=Me.bottom-jt,In=Me.left-fn,Qn=wt-xs,vs=Mn,Os=Math.max(Qn-en-on,160),ys=Math.max(vs-en-on,160),$n=Qn<qn&&vs>Qn,Xn=Math.max(Math.min($n?ys:Os,qn),160),Fs=Math.min(Math.max(In,mn),it-mn-At)+fn,Ri=$n?Math.max(en+jt,Mn-Xn-on+jt):Math.min(xs+on+jt,wt+jt-en-Xn);ce({top:Ri,left:Fs,width:At,maxHeight:Xn})},[sn]),Bn=a.useCallback(()=>{const ae=Wt.current?.querySelector(".refine-button");if(!ae)return;const Me=ae.getBoundingClientRect(),{width:it,height:wt,offsetTop:jt,offsetLeft:fn}=sn(),mn=8,en=12,on=4,xn=Math.min(200,Math.max(wt-en*2,160)),qn=Math.min(200,it-mn*2),On=Me.top-jt,tt=Me.bottom-jt,At=Me.left-fn,Mn=wt-tt,xs=On,In=Mn<xn&&xs>Mn,Qn=Math.min(Math.max(At,mn),it-mn-qn)+fn,vs=In?Math.max(en+jt,On-xn-on+jt):Math.min(tt+on+jt,wt+jt-en-xn);fe({top:vs,left:Qn})},[sn]),Sn=a.useCallback(()=>{const ae=Pe.current;if(!ae)return;const Me=ae.getBoundingClientRect(),{width:it,height:wt,offsetTop:jt,offsetLeft:fn}=sn(),mn=16,en=16,on=4,xn=it<=768,qn=Math.min(xn?wt*.6:wt*.5,320),On=xn?Math.min(it-mn*2,360):Math.max(Me.width,280),tt=Math.min(On,Math.max(it-mn*2,240)),At=Me.top-jt,Mn=Me.bottom-jt,xs=Me.left-fn,In=wt-Mn,Qn=At,vs=Math.max(In-en-on,200),Os=Math.max(Qn-en-on,200),ys=In<qn&&Qn>In,$n=Math.max(Math.min(ys?Os:vs,qn),200),Xn=Math.min(Math.max(xs,mn),it-mn-tt)+fn,Fs=ys?Math.max(en+jt,At-$n-on+jt):Math.min(Mn+on+jt,wt+jt-en-$n);Qe({top:Fs,left:Xn,width:tt,maxHeight:$n})},[sn]),an=a.useCallback(()=>{const ae=je.current?.querySelector("button");if(!ae)return;const Me=ae.getBoundingClientRect(),{width:it,height:wt,offsetTop:jt,offsetLeft:fn}=sn(),mn=16,en=16,on=4,xn=it<=768,qn=Math.min(xn?wt*.6:wt*.5,320),On=xn?Math.min(it-mn*2,280):Math.max(Me.width,240),tt=Math.min(On,Math.max(it-mn*2,200)),At=Me.top-jt,Mn=Me.bottom-jt,xs=Me.left-fn,In=wt-Mn,Qn=At,vs=Math.max(In-en-on,160),Os=Math.max(Qn-en-on,160),ys=In<qn&&Qn>In,$n=Math.max(Math.min(ys?Os:vs,qn),160),Xn=Math.min(Math.max(xs,mn),it-mn-tt)+fn,Fs=ys?Math.max(en+jt,At-$n-on+jt):Math.min(Mn+on+jt,wt+jt-en-$n);Ee({top:Fs,left:Xn,width:tt,maxHeight:$n})},[sn]),Dn=a.useCallback(()=>{const ae=Ae.current?.querySelector("button");if(!ae)return;const Me=ae.getBoundingClientRect(),{width:it,height:wt,offsetTop:jt,offsetLeft:fn}=sn(),mn=16,en=16,on=4,xn=it<=768,qn=Math.min(xn?wt*.6:wt*.5,320),On=xn?Math.min(it-mn*2,280):Math.max(Me.width,240),tt=Math.min(On,Math.max(it-mn*2,200)),At=Me.top-jt,Mn=Me.bottom-jt,xs=Me.left-fn,In=wt-Mn,Qn=At,vs=Math.max(In-en-on,160),Os=Math.max(Qn-en-on,160),ys=In<qn&&Qn>In,$n=Math.max(Math.min(ys?Os:vs,qn),160),Xn=Math.min(Math.max(xs,mn),it-mn-tt)+fn,Fs=ys?Math.max(en+jt,At-$n-on+jt):Math.min(Mn+on+jt,wt+jt-en-$n);rt({top:Fs,left:Xn,width:tt,maxHeight:$n})},[sn]);a.useEffect(()=>{if(!ve)return;const ae=()=>un();window.addEventListener("resize",ae),window.addEventListener("scroll",ae,!0);const Me=window.visualViewport;return Me&&(Me.addEventListener("resize",ae),Me.addEventListener("scroll",ae)),()=>{window.removeEventListener("resize",ae),window.removeEventListener("scroll",ae,!0),Me&&(Me.removeEventListener("resize",ae),Me.removeEventListener("scroll",ae))}},[ve,un]),a.useEffect(()=>{if(!Ft)return;const ae=()=>Bn();window.addEventListener("resize",ae),window.addEventListener("scroll",ae,!0);const Me=window.visualViewport;return Me&&(Me.addEventListener("resize",ae),Me.addEventListener("scroll",ae)),()=>{window.removeEventListener("resize",ae),window.removeEventListener("scroll",ae,!0),Me&&(Me.removeEventListener("resize",ae),Me.removeEventListener("scroll",ae))}},[Ft,Bn]),a.useEffect(()=>{if(!G)return;const ae=()=>Sn();window.addEventListener("resize",ae),window.addEventListener("scroll",ae,!0);const Me=window.visualViewport;return Me&&(Me.addEventListener("resize",ae),Me.addEventListener("scroll",ae)),()=>{window.removeEventListener("resize",ae),window.removeEventListener("scroll",ae,!0),Me&&(Me.removeEventListener("resize",ae),Me.removeEventListener("scroll",ae))}},[G,Sn]),a.useEffect(()=>{if(!k)return;const ae=()=>an();window.addEventListener("resize",ae),window.addEventListener("scroll",ae,!0);const Me=window.visualViewport;return Me&&(Me.addEventListener("resize",ae),Me.addEventListener("scroll",ae)),()=>{window.removeEventListener("resize",ae),window.removeEventListener("scroll",ae,!0),Me&&(Me.removeEventListener("resize",ae),Me.removeEventListener("scroll",ae))}},[k,an]),a.useEffect(()=>{if(!Q)return;const ae=()=>Dn();window.addEventListener("resize",ae),window.addEventListener("scroll",ae,!0);const Me=window.visualViewport;return Me&&(Me.addEventListener("resize",ae),Me.addEventListener("scroll",ae)),()=>{window.removeEventListener("resize",ae),window.removeEventListener("scroll",ae,!0),Me&&(Me.removeEventListener("resize",ae),Me.removeEventListener("scroll",ae))}},[Q,Dn]);const Ln=a.useCallback(ae=>{const Me=Ll(ae);qe(Me.provider),$e(Me.modelId)},[]),ss=a.useCallback(ae=>{const Me=Ll(ae);de(Me.provider),se(Me.modelId)},[]),Pn=a.useCallback(ae=>{const Me=Ll(ae);Fe(Me.provider),st(Me.modelId)},[]),nn=a.useCallback(async ae=>{if(m){m(ae);return}const Me=Ze,wt=Me.includes(ae)?Me.filter(jt=>jt!==ae):[ae,...Me];ft(wt);try{await bn({favoriteProviders:wt,favoriteModels:gt})}catch{ft(Me)}},[Ze,gt,m]),vt=a.useCallback(async ae=>{if(h){h(ae);return}const Me=gt,wt=Me.includes(ae)?Me.filter(jt=>jt!==ae):[ae,...Me];St(wt);try{await bn({favoriteProviders:Ze,favoriteModels:wt})}catch{St(Me)}},[gt,Ze,h]),rn=a.useCallback(()=>{const ae=f.trim();if(!ae){n("Enter a description first","error");return}r?.(ae),Lt()},[f,r,n,Lt]),A=a.useCallback(()=>{const ae=f.trim();if(!ae){n("Enter a description first","error");return}o?.(ae),Lt()},[f,o,n,Lt]),le=a.useCallback(()=>{ln()},[ln]),ye=a.useCallback(async ae=>{const Me=f.trim();if(!(!Me||Pt)){Et(!1),Dt(!0);try{const it=await Op(Me,ae,l);p(it),n("Description refined with AI","success"),E.current&&(E.current.style.height="auto",E.current.style.height=`${Math.min(E.current.scrollHeight,200)}px`)}catch(it){const wt=Fp(it);n(wt,"error")}finally{Dt(!1)}}},[f,Pt,n,l]),Ye=(ae,Me)=>ae.length>Me?ae.slice(0,Me)+"…":ae,mt=a.useCallback(async()=>{if(i){ne(i),Se(null),ee(!1);return}ee(!0),Se(null);try{const ae=await bs();ne(ae.models),u||ft(ae.favoriteProviders),d||St(ae.favoriteModels)}catch(ae){Se(ke(ae)||"Failed to load models")}finally{ee(!1)}},[i,u,d]),ht=a.useCallback(async()=>{if(te.length>0&&z===l){H(!0),an();return}V(!0);try{const ae=await Ia(void 0,l);N(ae),I(l),H(!0),an()}catch(ae){const Me=ke(ae);n(Me?`Failed to load agents: ${Me}`:"Failed to load agents","error"),H(!1)}finally{V(!1)}},[te.length,z,l,n,an]),Jt=(K?te.find(ae=>ae.id===K):void 0)?.name??K,zn=Mt?zt.find(ae=>ae.id===Mt):void 0,Hn=y,zs=a.useCallback(()=>{j(ae=>{const Me=!ae;return x(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:E,className:`quick-entry-input ${v?"quick-entry-input--expanded":""}`,placeholder:g?"Creating...":"Add a task...",value:f,onChange:ae=>p(ae.target.value),onKeyDown:wn,onPaste:Ne,onFocus:Tn,onBlur:Gn,disabled:g||L,"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:zs,"aria-expanded":y,"aria-controls":"quick-entry-controls","data-testid":"quick-entry-toggle",title:y?"Collapse":"Expand",children:y?t.jsx(bi,{size:14}):t.jsx(Yt,{size:14})})]})}),t.jsxs("div",{id:"quick-entry-controls",className:"quick-entry-controls",hidden:!Hn,"aria-hidden":!Hn,children:[Hn&&!g&&t.jsxs("div",{className:"quick-entry-actions","data-testid":"quick-entry-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:rn,onMouseDown:ae=>ae.preventDefault(),disabled:!f.trim(),"data-testid":"plan-button",title:"Open planning mode with current description",children:[t.jsx(ri,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Plan"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:A,onMouseDown:ae=>ae.preventDefault(),disabled:!f.trim(),"data-testid":"subtask-button",title:"Break down into AI-generated subtasks",children:[t.jsx(sl,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Subtask"]}),t.jsxs("div",{className:"refine-trigger-wrap",ref:Wt,children:[t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${Pt?"refine-button--loading":""}`,onClick:()=>{Et(ae=>{const Me=!ae;return Me?Bn():fe(null),Me})},disabled:!f.trim()||Pt,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(cs,{size:12,style:{verticalAlign:"middle"}}),Pt?"Refining...":"Refine"]}),Ft&&Ie&&Rt&&pa.createPortal(t.jsxs("div",{ref:It,className:"refine-menu refine-menu--portal",onMouseDown:ae=>ae.preventDefault(),style:{position:"fixed",top:`${Rt.top}px`,left:`${Rt.left}px`},children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>ye("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:()=>ye("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:()=>ye("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:()=>ye("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"})]})]}),Ie)]}),t.jsx("div",{className:"dep-trigger-wrap",children:t.jsxs("button",{ref:Pe,type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-deps",onClick:()=>{M(ae=>{const Me=!ae;return Me?(B(!1),ce(null),X(null),H(!1),Ee(null),ue(!1),rt(null),Sn()):Qe(null),Me})},children:[t.jsx(va,{size:12,style:{verticalAlign:"middle"}}),P.length>0?`${P.length} deps`:"Deps"]})}),G&&Ie&&Re&&(()=>{const ae=T.toLowerCase(),Me=(ae?s.filter(it=>it.id.toLowerCase().includes(ae)||it.title&&it.title.toLowerCase().includes(ae)||it.description&&it.description.toLowerCase().includes(ae)):[...s]).sort((it,wt)=>{const jt=wt.createdAt.localeCompare(it.createdAt);if(jt!==0)return jt;const fn=parseInt(it.id.slice(it.id.lastIndexOf("-")+1),10)||0;return(parseInt(wt.id.slice(wt.id.lastIndexOf("-")+1),10)||0)-fn});return pa.createPortal(t.jsxs("div",{ref:pe,className:"dep-dropdown dep-dropdown--portal",onMouseDown:it=>it.preventDefault(),style:{position:"fixed",top:`${Re.top}px`,left:`${Re.left}px`,width:`${Re.width}px`,maxHeight:Re.maxHeight?`${Re.maxHeight}px`:void 0,overflowY:Re.maxHeight?"auto":void 0},children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:T,onChange:it=>D(it.target.value),onClick:it=>it.stopPropagation()}),Me.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No existing tasks"}):Me.map(it=>t.jsxs("div",{className:`dep-dropdown-item${P.includes(it.id)?" selected":""}`,onMouseDown:wt=>wt.preventDefault(),onClick:()=>Un(it.id),children:[t.jsx("span",{className:"dep-dropdown-id",children:it.id}),t.jsx("span",{className:"dep-dropdown-title",children:Ye(it.title||it.description||it.id,60)})]},it.id))]}),Ie)})(),t.jsxs("button",{type:"button",className:"btn btn-sm","data-testid":"quick-entry-attach",onClick:()=>C.current?.click(),children:[t.jsx(_p,{size:12,style:{verticalAlign:"middle"}}),S.length>0?`Attach (${S.length})`:"Attach"]}),t.jsxs("button",{ref:Ue,type:"button",className:"btn btn-sm","data-testid":"quick-entry-models",onClick:()=>{M(!1),H(!1),Ee(null),ue(!1),rt(null),X(null),B(!0),un()},children:[t.jsx(Do,{size:12,style:{verticalAlign:"middle"}}),Cn]}),t.jsx("div",{className:"node-trigger-wrap",ref:Ae,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-node-button",onClick:()=>{M(!1),H(!1),Ee(null),B(!1),ce(null),X(null),ue(ae=>{const Me=!ae;return Me?Dn():rt(null),Me})},children:[t.jsx(Nr,{size:12,style:{verticalAlign:"middle"}}),` ${zn?.name??"Node"}`,zn&&t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(Wi,{status:zn.status,showLabel:!0})})]})}),Q&&Ie&&Ve&&pa.createPortal(t.jsxs("div",{ref:Le,className:"dep-dropdown node-picker-dropdown node-picker-dropdown--portal",onMouseDown:ae=>ae.preventDefault(),style:{position:"fixed",top:`${Ve.top}px`,left:`${Ve.left}px`,width:`${Ve.width}px`,maxHeight:Ve.maxHeight?`${Ve.maxHeight}px`:void 0,overflowY:Ve.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select execution node"}),t.jsx("div",{className:`dep-dropdown-item node-picker-item${Mt==null?" selected":""}`,onMouseDown:ae=>ae.preventDefault(),onClick:()=>{Ot(void 0),ue(!1),rt(null)},children:t.jsx("span",{className:"node-picker-item-name",children:"Project default / local"})}),zt.map(ae=>t.jsxs("div",{className:`dep-dropdown-item node-picker-item${Mt===ae.id?" selected":""}`,onMouseDown:Me=>Me.preventDefault(),onClick:()=>{Ot(ae.id),ue(!1),rt(null)},children:[t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(Wi,{status:ae.status})}),t.jsx("span",{className:"node-picker-item-name",children:ae.name}),t.jsx("span",{className:"node-picker-item-status",children:q1(ae.status)})]},ae.id))]}),Ie),t.jsx("div",{className:"agent-trigger-wrap",ref:je,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{k?(H(!1),Ee(null)):(ue(!1),rt(null),ht())},"data-testid":"quick-entry-agent-button",children:[t.jsx(En,{size:12,style:{verticalAlign:"middle"}}),Jt?` ${Jt}`:" Agent"]})}),k&&Ie&&we&&pa.createPortal(t.jsxs("div",{ref:ie,className:"dep-dropdown agent-picker-dropdown agent-picker-dropdown--portal",onMouseDown:ae=>ae.preventDefault(),style:{position:"fixed",top:`${we.top}px`,left:`${we.left}px`,width:`${we.width}px`,maxHeight:we.maxHeight?`${we.maxHeight}px`:void 0,overflowY:we.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),be&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!be&&te.filter(ae=>ae.state!=="terminated").map(ae=>t.jsxs("div",{className:`dep-dropdown-item${K===ae.id?" selected":""}`,onMouseDown:Me=>Me.preventDefault(),onClick:()=>{J(ae.id===K?null:ae.id),H(!1),Ee(null)},children:[t.jsx(En,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:ae.role}),t.jsx("span",{className:"dep-dropdown-title",children:ae.name})]},ae.id)),!be&&te.filter(ae=>ae.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),K&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:ae=>ae.preventDefault(),onClick:()=>{J(null),H(!1),Ee(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]}),Ie),t.jsx("button",{type:"button",className:`btn btn-sm ${$t?"btn-primary":""}`,onClick:()=>Tt(ae=>!ae),onMouseDown:ae=>ae.preventDefault(),"aria-pressed":$t,"data-testid":"quick-entry-fast-toggle",title:"Toggle fast execution mode",children:"Fast"}),t.jsxs("button",{type:"button",className:"btn btn-task-create btn-sm",onClick:le,onMouseDown:ae=>ae.preventDefault(),disabled:!f.trim()||g,"data-testid":"quick-entry-save",title:"Create task",children:[t.jsx(Ap,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Save"]})]}),S.length>0&&t.jsx("div",{className:"inline-create-previews",children:S.map((ae,Me)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:ae.previewUrl,alt:ae.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>et(Me),disabled:g,title:"Remove image","data-testid":`quick-entry-preview-remove-${Me}`,children:"×"})]},ae.previewUrl))}),ve&&Ie&&xe&&pa.createPortal(t.jsx("div",{ref:oe,className:"model-nested-menu model-nested-menu--portal",onMouseDown:ae=>ae.preventDefault(),"data-testid":"model-nested-menu",style:{position:"fixed",top:`${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:Y===null?t.jsxs("div",{className:"model-menu-items",children:[t.jsxs("button",{type:"button",className:`model-menu-item ${dt?"model-menu-item--active":""}`,onClick:()=>X("plan"),"data-testid":"model-menu-plan",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(ri,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Plan"]}),t.jsx("span",{className:"model-menu-item-value",children:dt?pn(nt,Xe):"Using default"}),t.jsx(gn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${Be?"model-menu-item--active":""}`,onClick:()=>X("executor"),"data-testid":"model-menu-executor",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(cs,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Executor"]}),t.jsx("span",{className:"model-menu-item-value",children:Be?pn(he,me):"Using default"}),t.jsx(gn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${Ke?"model-menu-item--active":""}`,onClick:()=>X("validator"),"data-testid":"model-menu-validator",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(Do,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Reviewer"]}),t.jsx("span",{className:"model-menu-item-value",children:Ke?pn(_e,Te):"Using default"}),t.jsx(gn,{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:()=>X(null),"data-testid":"model-submenu-back",children:[t.jsx(Yt,{size:12,style:{transform:"rotate(90deg)",marginRight:4}}),"Back"]}),t.jsxs("div",{className:"model-submenu-header",children:[Y==="plan"&&"Plan Model",Y==="executor"&&"Executor Model",Y==="validator"&&"Reviewer Model"]}),t.jsx(ns,{models:ot,value:Y==="plan"?ze:Y==="executor"?F:ge,onChange:Y==="plan"?Ln:Y==="executor"?ss:Pn,placeholder:"Using default",disabled:bt,id:`model-${Y}-select`,label:`${Y} model`,favoriteProviders:Oe,onToggleFavorite:nn,favoriteModels:ut,onToggleModelFavorite:vt}),re&&t.jsxs("div",{className:"model-submenu-error",children:[t.jsx("span",{children:re}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:mt,children:"Retry"})]})]})}),Ie)]}),t.jsx("input",{ref:C,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:ae=>{Zt(ae.target.files),ae.currentTarget.value=""},"data-testid":"quick-entry-file-input"}),t.jsx("div",{className:"quick-entry-hint",children:"Enter to create · Esc to cancel"})]})}function V1(e){return Sd(e)||e}function W1(e){const n=new Map(e.map(l=>[l.id,l])),s=[],i=new Set,r=new Set;function o(l){if(i.has(l)||r.has(l))return;r.add(l);const c=n.get(l);if(c)for(const u of c.dependencies||[])n.has(u)&&o(u);r.delete(l),i.add(l),s.push(l)}for(const l of e)o(l.id);return s}function K1(e,n,s){const i=e.filter(g=>g.worktree),r=e.filter(g=>!g.worktree),o=new Map;for(const g of i){const b=g.worktree,v=o.get(b)||[];v.push(g),o.set(b,v)}const l=new Map(n.map(g=>[g.id,g])),u=n.filter(g=>g.column==="todo").filter(g=>!g.paused&&(g.dependencies||[]).every(b=>{const v=l.get(b);return v&&(v.column==="done"||v.column==="in-review"||v.column==="archived")})),m=W1(u).map(g=>l.get(g)).filter(g=>g!==void 0&&u.includes(g)),h=[],f=Array.from(o.keys());for(const g of f)h.push({label:V1(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 tm=100,zl=50,nm=25;function G1({column:e,tasks:n,projectId:s,maxConcurrent:i,onMoveTask:r,onPauseTask:o,onOpenDetail:l,addToast:c,onQuickCreate:u,onNewTask:d,autoMerge:m,onToggleAutoMerge:h,globalPaused:f,onUpdateTask:p,onRetryTask:g,onArchiveTask:b,onUnarchiveTask:v,onDeleteTask:x,onArchiveAllDone:y,collapsed:j,onToggleCollapse:E,allTasks:C,availableModels:w,onPlanningMode:R,onSubtaskBreakdown:S,onOpenDetailWithTab:O,favoriteProviders:_,favoriteModels:P,onToggleFavorite:U,onToggleModelFavorite:G,isSearchActive:M,taskStuckTimeoutMs:T,onOpenMission:D,lastFetchTimeMs:K,workflowStepNameLookup:J}){const[te,N]=a.useState(!1),[z,I]=a.useState(zl),[k,H]=a.useState(!1),[Q,ue]=a.useState(!1),[be,V]=a.useState(!1),[ve,B]=a.useState(!1),Y=a.useRef(null),X=LN(n.length),{confirm:he}=Gs();a.useEffect(()=>{if(!k)return;function Ee(rt){Y.current?.contains(rt.target)||H(!1)}function Ve(rt){rt.key==="Escape"&&H(!1)}return document.addEventListener("mousedown",Ee),document.addEventListener("keydown",Ve),()=>{document.removeEventListener("mousedown",Ee),document.removeEventListener("keydown",Ve)}},[k]);const de=e==="archived",me=de&&j,se=!de&&!M&&e!=="in-progress"&&n.length>tm;a.useEffect(()=>{I(Ee=>e==="in-progress"||de||n.length<=tm?zl:Math.min(Math.max(Ee,zl),n.length))},[e,de,n.length]);const _e=a.useCallback(Ee=>{de||(Ee.preventDefault(),Ee.dataTransfer.dropEffect="move",N(!0))},[de]),Fe=a.useCallback(Ee=>{Ee.currentTarget.contains(Ee.relatedTarget)||N(!1)},[]),Te=a.useCallback(async Ee=>{Ee.preventDefault(),N(!1);const Ve=Ee.dataTransfer.getData("text/plain");if(!Ve)return;const rt=n.find(xe=>xe.id===Ve);if(!(rt&&rt.column===e))try{await r(Ve,e)}catch(xe){c(ke(xe),"error")}},[e,r,c,n]),st=a.useMemo(()=>e!=="in-progress"?[]:K1(n,n,i),[e,n,i]),nt=a.useMemo(()=>se?n.slice(0,z):n,[se,n,z]),qe=Math.max(0,n.length-nt.length),Xe=a.useCallback(()=>{I(Ee=>Math.min(Ee+nm,n.length))},[n.length]),$e=a.useCallback(async()=>{if(H(!1),!(n.length===0||!await he({title:"Replan All Tasks",message:`Move all ${n.length} todo task${n.length===1?"":"s"} back to planning to be replanned?`}))){ue(!0);try{const Ve=await Promise.allSettled(n.map(ce=>r(ce.id,"triage"))),rt=Ve.filter(ce=>ce.status==="rejected").length,xe=Ve.length-rt;rt===0?c(`Moved ${xe} task${xe===1?"":"s"} to planning for replanning`,"success"):c(`Moved ${xe} of ${Ve.length} tasks; ${rt} failed`,"error")}finally{ue(!1)}}},[n,r,c,he]),Ue=a.useMemo(()=>n.filter(Ee=>!Ee.paused),[n]),oe=Ue.length,je=e==="todo"||e==="in-progress"||e==="in-review",ie=Q||be||ve,Ae=a.useCallback(async()=>{if(!(!o||(H(!1),oe===0)||!await he({title:"Stop All Tasks",message:`Stop all ${oe} ${Wn[e].toLowerCase()} task${oe===1?"":"s"}?`,danger:!0}))){V(!0);try{const Ve=await Promise.allSettled(Ue.map(ce=>o(ce.id))),rt=Ve.filter(ce=>ce.status==="rejected").length,xe=Ve.length-rt;rt===0?c(`Stopped ${xe} task${xe===1?"":"s"}`,"success"):c(`Stopped ${xe} of ${Ve.length} tasks; ${rt} failed`,"error")}finally{V(!1)}}},[o,oe,e,Ue,c,he]),Le=a.useCallback(async()=>{if(H(!1),!(n.length===0||!await he({title:"Move All to Todo",message:`Move all ${n.length} ${Wn[e].toLowerCase()} task${n.length===1?"":"s"} to Todo?`}))){B(!0);try{const Ve=await Promise.allSettled(n.map(ce=>r(ce.id,"todo"))),rt=Ve.filter(ce=>ce.status==="rejected").length,xe=Ve.length-rt;rt===0?c(`Moved ${xe} task${xe===1?"":"s"} to Todo`,"success"):c(`Moved ${xe} of ${Ve.length} tasks to Todo; ${rt} failed`,"error")}finally{B(!1)}}},[n,e,r,c,he]),we=a.useCallback(async()=>{if(!(!y||n.length===0||!await he({title:"Archive All Done",message:`Archive all ${n.length} done tasks?`,danger:!0})))try{const Ve=await y();c(`Archived ${Ve.length} tasks`,"success")}catch(Ve){c(ke(Ve)||"Failed to archive tasks","error")}},[y,n.length,c,he]);return t.jsxs("div",{className:`column${te?" drag-over":""}${de?" column-archived":""}${me?" column-collapsed":""}`,"data-column":e,onDragOver:_e,onDragLeave:Fe,onDrop:Te,children:[t.jsxs("div",{className:"column-header",children:[t.jsx("div",{className:`column-dot dot-${e}`}),t.jsx("h2",{children:Wn[e]}),t.jsx("span",{className:`column-count${X?" count-flash":""}`,children:n.length}),e==="in-review"&&h&&t.jsxs("label",{className:"auto-merge-toggle",title:m?"Auto-merge enabled":"Auto-merge disabled",children:[t.jsx("input",{type:"checkbox",checked:!!m,onChange:h}),t.jsx("span",{className:"toggle-slider"}),t.jsx("span",{className:"toggle-label",children:"Auto-merge"})]}),d&&t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:d,children:"+ New Task"}),e==="done"&&y&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:we,disabled:n.length===0,title:"Archive all done tasks","aria-label":"Archive all done tasks",children:t.jsx(Ir,{})}),de&&E&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:E,title:j?"Expand archived tasks":"Collapse archived tasks","aria-label":j?"Expand archived tasks":"Collapse archived tasks",children:j?t.jsx(Yt,{size:16}):t.jsx(bi,{size:16})}),je&&t.jsxs("div",{className:"column-menu",ref:Y,children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>H(Ee=>!Ee),"aria-haspopup":"menu","aria-expanded":k,"aria-label":`${Wn[e]} column actions`,title:"Column actions",disabled:ie,children:t.jsx(nx,{})}),k&&t.jsxs("div",{className:"column-menu-popover",role:"menu",children:[e==="todo"&&t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void $e(),disabled:n.length===0||Q,children:["Replan All",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Planning"]})]}),(e==="in-progress"||e==="in-review")&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Ae(),disabled:oe===0||be||!o,children:["Stop All",t.jsx("span",{className:"column-menu-item-hint",children:n.length===0?"No tasks in this column":oe===0?"All tasks are already paused":`Pause ${oe} active task${oe===1?"":"s"}`})]}),t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Le(),disabled:n.length===0||ve,children:["Move All to Todo",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Todo"]})]})]})]})]})]}),!me&&t.jsx("p",{className:"column-desc",children:$N[e]}),!me&&t.jsxs("div",{className:"column-body",children:[e==="triage"&&u&&t.jsx(uf,{onCreate:u,addToast:c,tasks:C??[],availableModels:w,onPlanningMode:R,onSubtaskBreakdown:S,projectId:s,autoExpand:!1,favoriteProviders:_,favoriteModels:P,onToggleFavorite:U,onToggleModelFavorite:G}),e==="in-progress"?st.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):st.map(Ee=>t.jsx(df,{label:Ee.label,activeTasks:Ee.activeTasks,queuedTasks:Ee.queuedTasks,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onOpenDetailWithTab:O,taskStuckTimeoutMs:T,onOpenMission:D,lastFetchTimeMs:K,workflowStepNameLookup:J},Ee.label)):n.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):t.jsxs(t.Fragment,{children:[nt.map(Ee=>t.jsx(Mr,{task:Ee,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onArchiveTask:b,onUnarchiveTask:v,onDeleteTask:x,onOpenDetailWithTab:O,taskStuckTimeoutMs:T,onOpenMission:D,onMoveTask:r,lastFetchTimeMs:K,workflowStepNameLookup:J},Ee.id)),se&&qe>0&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Xe,children:["Load ",Math.min(nm,qe)," more (",qe," remaining)"]})]}),t.jsx(dl,{slotId:"board-column-footer",projectId:s})]})]})}const mf=a.memo(G1);mf.displayName="Column";function J1(e,n){return[...e].sort((s,i)=>{if(n==="in-review"){const r=s.status==="merging"||s.status==="merging-pr",o=i.status==="merging"||i.status==="merging-pr";if(r!==o)return r?-1:1}return s.columnMovedAt&&i.columnMovedAt?i.columnMovedAt.localeCompare(s.columnMovedAt):s.columnMovedAt&&!i.columnMovedAt?-1:!s.columnMovedAt&&i.columnMovedAt?1:s.createdAt.localeCompare(i.createdAt)})}function Y1(e,n){return e.length!==n.length?!1:e.every((s,i)=>s===n[i])}const sm=new Map;function Q1(e,n){if(e.size!==n.size)return!1;for(const[s,i]of e)if(n.get(s)!==i)return!1;return!0}function X1({tasks:e,projectId:n,maxConcurrent:s,onMoveTask:i,onPauseTask:r,onOpenDetail:o,addToast:l,onQuickCreate:c,onNewTask:u,autoMerge:d,onToggleAutoMerge:m,globalPaused:h,onUpdateTask:f,onRetryTask:p,onArchiveTask:g,onUnarchiveTask:b,onDeleteTask:v,onArchiveAllDone:x,onLoadArchivedTasks:y,searchQuery:j="",availableModels:E,onPlanningMode:C,onSubtaskBreakdown:w,onOpenDetailWithTab:R,favoriteProviders:S,favoriteModels:O,onToggleFavorite:_,onToggleModelFavorite:P,taskStuckTimeoutMs:U,onOpenMission:G,lastFetchTimeMs:M}){const[T,D]=a.useState(!0),K=a.useRef(!1),{fetchBatch:J}=n1(n),te=a.useRef(null),[N,z]=a.useState(sm),I=j.trim()!=="",k=a.useRef({triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]}),H=a.useCallback(()=>{D(be=>{const V=!be;return!V&&!K.current&&y&&(K.current=!0,y()),V})},[y]),Q=a.useMemo(()=>{const be=Object.fromEntries(Ui.map(B=>[B,[]]));for(const B of e)be[B.column].push(B);const V=k.current,ve={};for(const B of Ui){const Y=J1(be[B],B);ve[B]=Y1(V[B],Y)?V[B]:Y}return k.current=ve,ve},[e]);a.useEffect(()=>{let be=!1;return Br(n).then(V=>{if(be)return;const ve=new Map(V.map(B=>[B.id,B.name]));z(B=>Q1(B,ve)?B:ve)}).catch(()=>{be||z(V=>V.size===0?V:sm)}),()=>{be=!0}},[n]);const ue=a.useMemo(()=>e.filter(be=>be.prInfo||be.issueInfo).map(be=>be.id),[e]);return a.useEffect(()=>{if(ue.length!==0)return te.current&&clearTimeout(te.current),te.current=setTimeout(()=>{const be=[];for(let V=0;V<ue.length;V+=50)be.push(ue.slice(V,V+50));be.forEach(V=>{J(V)})},500),()=>{te.current&&clearTimeout(te.current)}},[ue,J]),t.jsx(t.Fragment,{children:t.jsx("main",{className:"board",id:"board",children:Ui.map(be=>t.jsx(mf,{column:be,tasks:Q[be],projectId:n,maxConcurrent:s,onMoveTask:i,onPauseTask:r,onOpenDetail:o,addToast:l,globalPaused:h,onUpdateTask:f,onRetryTask:p,onArchiveTask:g,onUnarchiveTask:b,onDeleteTask:v,allTasks:e,availableModels:E,onOpenDetailWithTab:R,favoriteProviders:S,favoriteModels:O,onToggleFavorite:_,onToggleModelFavorite:P,isSearchActive:I,taskStuckTimeoutMs:U,onOpenMission:G,lastFetchTimeMs:M,workflowStepNameLookup:N,...be==="triage"?{onQuickCreate:c,onNewTask:u,onPlanningMode:C,onSubtaskBreakdown:w}:{},...be==="in-review"?{autoMerge:d,onToggleAutoMerge:m}:{},...be==="done"?{onArchiveAllDone:x}:{},...be==="archived"?{collapsed:T,onToggleCollapse:H}:{}},be))})})}const Ga={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-secondary)"},im=new Set(["planning","researching","executing","finalizing","merging"]),Yc=["id","title","status","column","dependencies","progress"];function Z1(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function eS(e){return e==="online"?"●":e==="connecting"?"◐":e==="error"?"✕":"○"}function am(e){try{const n=Yn("kb-dashboard-list-columns",e);if(n){const i=JSON.parse(n).filter(r=>Yc.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set(Yc)}function rm(e){try{const n=Yn("kb-dashboard-hide-done",e);if(n!==null)return n==="true"}catch{}return!1}function om(e){try{const n=Yn("kb-dashboard-list-collapsed",e);if(n){const i=JSON.parse(n).filter(r=>Ui.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set}function lm(e){try{const n=Yn("kb-dashboard-selected-tasks",e);if(n){const s=JSON.parse(n);return new Set(s)}}catch{}return new Set}function tS(e){return e.status==="executing"||e.column==="in-progress"}function cm(e){const n=of(e);return n.total===0||!tS(e)?{label:"-",percent:0,hasProgress:!1}:{label:`${n.completed}/${n.total}`,percent:n.completed/n.total*100,hasProgress:!0}}function nS({tasks:e,onMoveTask:n,onOpenDetail:s,addToast:i,globalPaused:r,onNewTask:o,onQuickCreate:l,availableModels:c,favoriteProviders:u=[],favoriteModels:d=[],onToggleFavorite:m,onToggleModelFavorite:h,onPlanningMode:f,onSubtaskBreakdown:p,onTasksUpdated:g,projectId:b,projectName:v,taskStuckTimeoutMs:x,searchQuery:y="",lastFetchTimeMs:j}){const[E,C]=a.useState("id"),[w,R]=a.useState("desc"),[S,O]=a.useState(null),[_,P]=a.useState(null),[U,G]=a.useState(null),T=$a()==="mobile",[D,K]=a.useState(()=>am(b)),[J,te]=a.useState(()=>rm(b)),[N,z]=a.useState(()=>om(b));a.useEffect(()=>{typeof window<"u"&&fs("kb-dashboard-list-columns",JSON.stringify([...D]),b)},[b,D]),a.useEffect(()=>{typeof window<"u"&&fs("kb-dashboard-hide-done",J.toString(),b)},[J,b]),a.useEffect(()=>{typeof window<"u"&&fs("kb-dashboard-list-collapsed",JSON.stringify([...N]),b)},[N,b]);const[I,k]=a.useState(!1),H=a.useRef(null),[Q,ue]=a.useState(()=>lm(b));a.useEffect(()=>{K(am(b)),te(rm(b)),z(om(b)),ue(lm(b))},[b]),a.useEffect(()=>{typeof window<"u"&&fs("kb-dashboard-selected-tasks",JSON.stringify([...Q]),b)},[b,Q]);const be=a.useCallback(ee=>{ue(re=>{const Se=new Set(re);return Se.has(ee)?Se.delete(ee):Se.add(ee),Se})},[]),V=a.useCallback(()=>{ue(new Set)},[]),ve=a.useCallback(ee=>{K(re=>{const Se=new Set(re);return Se.has(ee)?Se.size>1&&Se.delete(ee):Se.add(ee),Se})},[]);a.useEffect(()=>{if(!I)return;const ee=Se=>{H.current&&!H.current.contains(Se.target)&&k(!1)},re=Se=>{Se.key==="Escape"&&k(!1)};return document.addEventListener("mousedown",ee),document.addEventListener("keydown",re),()=>{document.removeEventListener("mousedown",ee),document.removeEventListener("keydown",re)}},[I]);const B={id:"ID",title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},Y=a.useCallback(ee=>{E===ee?R(re=>re==="asc"?"desc":"asc"):(C(ee),R("asc"))},[E]),X=a.useCallback(ee=>{G(re=>re===ee?null:ee)},[]),he=a.useCallback(ee=>{z(re=>{const Se=new Set(re);return Se.has(ee)?Se.delete(ee):Se.add(ee),Se})},[]),de=a.useCallback(()=>{G(null)},[]),me=a.useMemo(()=>{let ee=y?e.filter(ne=>ne.id.toLowerCase().includes(y.toLowerCase())||ne.title&&ne.title.toLowerCase().includes(y.toLowerCase())||ne.description.toLowerCase().includes(y.toLowerCase())):[...e];J&&!U&&(ee=ee.filter(ne=>ne.column!=="done"&&ne.column!=="archived"));const Se=[...U?ee.filter(ne=>ne.column===U):ee].sort((ne,Ze)=>{let ft=0;switch(E){case"id":ft=ne.id.localeCompare(Ze.id);break;case"title":ft=(ne.title||ne.description).localeCompare(Ze.title||Ze.description);break;case"status":ft=(ne.status||"").localeCompare(Ze.status||"");break;case"column":ft=ne.column.localeCompare(Ze.column);break}return w==="asc"?ft:-ft}),ot={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};return Se.forEach(ne=>ot[ne.column].push(ne)),ot},[e,y,E,w,J,U]),se=a.useMemo(()=>Object.values(me).reduce((ee,re)=>ee+re.length,0),[me]),_e=a.useMemo(()=>e.filter(ee=>ee.column==="done"||ee.column==="archived").length,[e]),Fe=a.useMemo(()=>J?_e:0,[J,_e]),Te=a.useCallback(()=>{const ee=Object.values(me).flat().filter(re=>re.column!=="archived").map(re=>re.id);ue(re=>{if(ee.every(ot=>re.has(ot))){const ot=new Set(re);return ee.forEach(ne=>ot.delete(ne)),ot}else return new Set([...re,...ee])})},[me]),st=a.useMemo(()=>{const ee=Object.values(me).flat().filter(re=>re.column!=="archived");return ee.length===0?!1:ee.every(re=>Q.has(re.id))},[me,Q]),nt=a.useMemo(()=>{const ee=Object.values(me).flat().filter(Se=>Se.column!=="archived");if(ee.length===0)return!1;const re=ee.filter(Se=>Q.has(Se.id)).length;return re>0&&re<ee.length},[me,Q]),[qe,Xe]=a.useState("__no_change__"),[$e,Ue]=a.useState("__no_change__"),[oe,je]=a.useState("__no_change__"),[ie,Ae]=a.useState([]),[Le,we]=a.useState(!1),Ee=a.useMemo(()=>oe&&oe!=="__no_change__"?ie.find(ee=>ee.id===oe):void 0,[ie,oe]),[Ve,rt]=a.useState(!1);a.useEffect(()=>{if(Q.size===0)return;let ee=!1;return(async()=>{we(!0);try{const Se=await Bo();ee||Ae(Se)}catch(Se){console.error("Failed to fetch nodes for bulk edit",Se),ee||Ae([])}finally{ee||we(!1)}})(),()=>{ee=!0}},[Q.size]);const xe=a.useCallback(async()=>{if(Q.size===0)return;const ee=Array.from(Q).filter(Se=>{const ot=e.find(ne=>ne.id===Se);return ot&&ot.column!=="archived"});if(ee.length===0){i("No valid tasks to update (archived tasks cannot be modified)","error");return}const re={taskIds:ee};if(qe!=="__no_change__")if(qe==="")re.modelProvider=null,re.modelId=null;else{const Se=qe.indexOf("/");Se!==-1&&(re.modelProvider=qe.slice(0,Se),re.modelId=qe.slice(Se+1))}if($e!=="__no_change__")if($e==="")re.validatorModelProvider=null,re.validatorModelId=null;else{const Se=$e.indexOf("/");Se!==-1&&(re.validatorModelProvider=$e.slice(0,Se),re.validatorModelId=$e.slice(Se+1))}if(oe!=="__no_change__"&&(oe===""?re.nodeId=null:re.nodeId=oe),Object.keys(re).length===1){i("No changes to apply","info");return}rt(!0);try{const Se=await vy(re.taskIds,re.modelProvider,re.modelId,re.validatorModelProvider,re.validatorModelId,void 0,void 0,re.nodeId,b);g&&g(Se.updated),i(`Updated ${ee.length} task${ee.length===1?"":"s"}`,"success"),V(),Xe("__no_change__"),Ue("__no_change__"),je("__no_change__")}catch(Se){i(ke(Se)||"Failed to update models","error")}finally{rt(!1)}},[Q,e,qe,$e,oe,b,i,V,g]),ce=a.useCallback(ee=>{s(ee)},[s]),Pe=a.useCallback((ee,re)=>{if(re.paused){ee.preventDefault();return}ee.dataTransfer.setData("text/plain",re.id),ee.dataTransfer.effectAllowed="move",O(re.id)},[]),pe=a.useCallback(()=>{O(null),P(null)},[]),Re=a.useCallback((ee,re)=>{ee.preventDefault(),ee.dataTransfer.dropEffect="move",P(re)},[]),Qe=a.useCallback(()=>{P(null)},[]),Ie=a.useCallback(async(ee,re)=>{ee.preventDefault(),P(null);const Se=ee.dataTransfer.getData("text/plain");if(Se){if(re==="archived"){i("Tasks can only be archived via the archive button","error");return}try{await n(Se,re)}catch(ot){i(ke(ot),"error")}}},[n,i]),bt=ee=>E!==ee?t.jsx(wp,{size:14,className:"sort-icon"}):w==="asc"?t.jsx(Fi,{size:14,className:"sort-icon active"}):t.jsx($r,{size:14,className:"sort-icon active"});return t.jsxs("div",{className:"list-view",children:[t.jsxs("div",{className:"list-toolbar",children:[t.jsxs("div",{className:"list-column-toggle",ref:H,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>k(ee=>!ee),"aria-expanded":I,"aria-haspopup":"menu",children:[t.jsx(Jb,{size:14}),"Columns"]}),I&&t.jsx("div",{className:"list-column-dropdown",role:"menu",children:Yc.map(ee=>{const re=D.has(ee),Se=re&&D.size===1;return t.jsxs("label",{className:`list-column-dropdown-item${Se?" disabled":""}`,role:"menuitem",title:Se?"At least one column must be visible":"",children:[t.jsx("input",{type:"checkbox",checked:re,onChange:()=>ve(ee),disabled:Se}),t.jsx("span",{children:B[ee]})]},ee)})})]}),t.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>te(ee=>!ee),"aria-pressed":J,title:J?"Show done tasks":"Hide done tasks",children:[J?t.jsx(Ta,{size:14}):t.jsx(bd,{size:14}),J?"Show Done":"Hide Done"]}),t.jsxs("div",{className:"list-stats",children:[U?`${se} of ${e.length} tasks in ${Wn[U]}`:`${se} of ${e.length} tasks`,Fe>0&&!U&&t.jsxs("span",{className:"list-stats-hidden",children:[" (",Fe," hidden)"]}),U&&t.jsx("button",{className:"btn btn-sm",onClick:de,"aria-label":"Clear column filter",style:{marginLeft:"8px"},children:"Clear"})]}),Q.size>0&&t.jsxs("div",{className:"list-selection-stats",children:[t.jsxs("span",{className:"selection-count",children:[Q.size," selected"]}),t.jsx("button",{className:"btn btn-sm btn-link",onClick:V,children:"Clear"})]}),Q.size>0&&c&&c.length>0&&t.jsxs("div",{className:"bulk-edit-toolbar",children:[t.jsx("span",{className:"bulk-edit-label",children:"Bulk Edit Models & Node:"}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx(ns,{models:c,value:qe,onChange:Xe,label:"Executor Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:u,onToggleFavorite:m,favoriteModels:d,onToggleModelFavorite:h})}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx(ns,{models:c,value:$e,onChange:Ue,label:"Reviewer Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:u,onToggleFavorite:m,favoriteModels:d,onToggleModelFavorite:h})}),t.jsxs("div",{className:"bulk-edit-dropdown bulk-edit-node-wrap",children:[t.jsxs("select",{className:"select bulk-node-select",value:oe,onChange:ee=>je(ee.target.value),"aria-label":"Node Override",disabled:Le,children:[t.jsx("option",{value:"__no_change__",children:"No change"}),t.jsx("option",{value:"",children:"Use project default"}),ie.map(ee=>t.jsx("option",{value:ee.id,children:`${eS(ee.status)} ${ee.name||ee.id} (${Z1(ee.status)})`},ee.id))]}),Ee?t.jsx(Wi,{status:Ee.status,showLabel:!0}):null]}),t.jsx("button",{className:"btn btn-primary btn-sm bulk-edit-apply-btn",onClick:xe,disabled:Ve||qe==="__no_change__"&&$e==="__no_change__"&&oe==="__no_change__",children:Ve?"Applying...":"Apply"})]}),o?t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:o,children:"+ New Task"}):null]}),t.jsx("div",{className:"list-drop-zones",children:Ui.map(ee=>{const re=e.filter(Ze=>Ze.column===ee).length,Se=ee==="done"||ee==="archived",ot=J&&Se?0:re,ne=J&&Se&&re>0;return t.jsxs("div",{className:`list-drop-zone${_===ee?" drag-over":""}${U===ee?" active":""}`,onClick:()=>X(ee),onDragOver:Ze=>Re(Ze,ee),onDragLeave:Qe,onDrop:Ze=>Ie(Ze,ee),"data-column":ee,children:[t.jsx("span",{className:"drop-zone-dot",style:{background:Ga[ee]}}),t.jsx("span",{className:"drop-zone-label",children:Wn[ee]}),t.jsx("span",{className:"drop-zone-count",children:ne?`${ot} of ${re}`:re})]},ee)})}),t.jsxs("div",{className:"list-table-container",children:[t.jsx("div",{className:"list-quick-entry-above-table",children:t.jsx(uf,{onCreate:l??(async()=>i("Task creation not available","error")),addToast:i,tasks:e,availableModels:c,onPlanningMode:f,onSubtaskBreakdown:p,projectId:b,autoExpand:!1,favoriteProviders:u,favoriteModels:d,onToggleFavorite:m,onToggleModelFavorite:h})}),se===0?t.jsx("div",{className:"list-empty",children:y?"No tasks match your filter":"No tasks yet"}):T?t.jsx("div",{className:"list-cards",children:Ui.map(ee=>{if(U&&ee!==U||J&&(ee==="done"||ee==="archived")&&!U)return null;const re=me[ee],Se=re.length===0;if(y&&Se)return null;const ot=N.has(ee);return t.jsxs(a.Fragment,{children:[t.jsxs("div",{className:`list-card-section-header${ot?" list-section-header--collapsed":""}`,onClick:()=>he(ee),"aria-expanded":!ot,role:"button",tabIndex:0,onKeyDown:ne=>{(ne.key==="Enter"||ne.key===" ")&&(ne.preventDefault(),he(ee))},children:[t.jsx(gn,{size:14,className:`list-section-chevron${ot?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${ee}`}),t.jsx("span",{className:"list-section-title",children:Wn[ee]}),t.jsx("span",{className:"list-section-count",children:re.length})]}),!ot&&t.jsx(t.Fragment,{children:Se?t.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):re.map(ne=>{const Ze=ne.status==="failed",ft=ne.paused===!0,gt=qo(ne,x,j),St=!r&&!Ze&&!ft&&!gt&&(ne.column==="in-progress"||im.has(ne.status)),Nt=typeof ne.status=="string"&&ne.status.trim().length>0,pt=!!(ne.dependencies&&ne.dependencies.length>0),kt=cm(ne),Ht=kt.hasProgress,$t=Q.size>0;return t.jsxs("div",{className:`list-card${St?" agent-active":""}${$t?" list-card--selectable":""}`,onClick:()=>ce(ne),"data-id":ne.id,children:[$t&&t.jsx("label",{className:"list-card-checkbox",onClick:Tt=>Tt.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:Q.has(ne.id),onChange:Tt=>{Tt.stopPropagation(),be(ne.id)},onClick:Tt=>Tt.stopPropagation(),disabled:ne.column==="archived","aria-label":`Select ${ne.id}`})}),t.jsxs("div",{className:"list-card-row",children:[t.jsx("span",{className:"list-card-id",children:ne.id}),ne.executionMode==="fast"&&t.jsx("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",children:"Fast"}),t.jsx("span",{className:"list-card-spacer"}),gt?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):Nt?t.jsx("span",{className:`list-status-badge list-status-badge--${ne.column}${Ze?" failed":""}${St?" pulsing":""}`,children:ne.status}):null]}),t.jsx("div",{className:"list-card-row",children:t.jsx("div",{className:"list-card-title",children:ne.title||ne.description})}),(pt||Ht)&&t.jsxs("div",{className:"list-card-row list-card-meta",children:[pt&&t.jsxs("span",{className:"list-dep-badge",title:ne.dependencies.join(", "),children:[t.jsx(va,{size:12})," ",ne.dependencies.length]}),Ht&&t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${kt.percent}%`,backgroundColor:Ga[ne.column]}})}),t.jsx("span",{className:"list-progress-label",children:kt.label})]})]})]},ne.id)})})]},ee)})}):t.jsxs("table",{className:"list-table",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{className:"list-header-cell list-header-checkbox",children:t.jsx("input",{type:"checkbox",checked:st,ref:ee=>{ee&&(ee.indeterminate=nt)},onChange:Te,"aria-label":"Select all visible tasks"})}),D.has("id")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Y("id"),children:["ID ",bt("id")]}),D.has("title")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Y("title"),children:["Title ",bt("title")]}),D.has("status")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Y("status"),children:["Status ",bt("status")]}),D.has("column")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Y("column"),children:["Column ",bt("column")]}),D.has("dependencies")&&t.jsx("th",{className:"list-header-cell",children:"Dependencies"}),D.has("progress")&&t.jsx("th",{className:"list-header-cell",children:"Progress"})]})}),t.jsx("tbody",{children:Ui.map(ee=>{if(U&&ee!==U||J&&(ee==="done"||ee==="archived")&&!U)return null;const re=me[ee],Se=re.length===0;if(y&&Se)return null;const ot=N.has(ee);return t.jsxs(a.Fragment,{children:[t.jsx("tr",{className:`list-section-header${ot?" list-section-header--collapsed":""}`,onClick:()=>he(ee),"aria-expanded":!ot,children:t.jsxs("th",{colSpan:D.size+1,className:"list-section-cell",children:[t.jsx(gn,{size:14,className:`list-section-chevron${ot?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${ee}`}),t.jsx("span",{className:"list-section-title",children:Wn[ee]}),t.jsx("span",{className:"list-section-count",children:re.length})]})}),!ot&&t.jsx(t.Fragment,{children:Se?t.jsx("tr",{className:"list-section-empty",children:t.jsx("td",{colSpan:D.size+1,className:"list-empty-cell",children:"No tasks"})}):re.map(ne=>{const Ze=ne.status==="failed",ft=ne.paused===!0,gt=qo(ne,x,j),St=!r&&!Ze&&!ft&&!gt&&(ne.column==="in-progress"||im.has(ne.status)),Nt=S===ne.id;return t.jsxs("tr",{className:`list-row${Ze?" failed":""}${ft?" paused":""}${gt?" stuck":""}${St?" agent-active":""}${Nt?" dragging":""}`,onClick:()=>ce(ne),draggable:!ft,onDragStart:pt=>Pe(pt,ne),onDragEnd:pe,"data-id":ne.id,children:[t.jsx("td",{className:"list-cell list-cell-checkbox",children:t.jsx("input",{type:"checkbox",checked:Q.has(ne.id),onChange:pt=>{pt.stopPropagation(),be(ne.id)},onClick:pt=>pt.stopPropagation(),disabled:ne.column==="archived","aria-label":`Select ${ne.id}`})}),D.has("id")&&t.jsx("td",{className:"list-cell list-cell-id",children:ne.id}),D.has("title")&&t.jsx("td",{className:"list-cell list-cell-title",children:t.jsxs("div",{className:"list-title-content",children:[ne.executionMode==="fast"&&t.jsx("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",children:"Fast"}),t.jsx("span",{className:"list-title-text",children:ne.title||ne.description})]})}),D.has("status")&&t.jsx("td",{className:"list-cell",children:gt?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):ne.status?t.jsx("span",{className:`list-status-badge list-status-badge--${ne.column}${Ze?" failed":""}${St?" pulsing":""}`,children:ne.status}):t.jsx("span",{className:"list-status-badge",children:"-"})}),D.has("column")&&t.jsx("td",{className:"list-cell",children:t.jsx("span",{className:"list-column-badge",style:{background:`${Ga[ne.column]}20`,color:Ga[ne.column]},children:Wn[ne.column]})}),D.has("dependencies")&&t.jsx("td",{className:"list-cell list-cell-deps",children:ne.dependencies&&ne.dependencies.length>0?t.jsxs("span",{className:"list-dep-badge",title:ne.dependencies.join(", "),children:[t.jsx(va,{size:12})," ",ne.dependencies.length]}):"-"}),D.has("progress")&&t.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const pt=cm(ne);return pt.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:`${pt.percent}%`,backgroundColor:Ga[ne.column]}})}),t.jsx("span",{className:"list-progress-label",children:pt.label})]}):"-"})()})]},ne.id)})})]},ee)})})]})]})]})}const sS={active:{label:"Active",color:"var(--success)",icon:_n},paused:{label:"Paused",color:"var(--warning)",icon:Vs},errored:{label:"Error",color:"var(--color-error)",icon:gs},initializing:{label:"Initializing",color:"var(--info)",icon:lt}};function iS(e){if(!e)return"Never";const n=new Date(e),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),o=Math.floor(i/36e5),l=Math.floor(i/864e5);return r<1?"Just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString()}function aS(e,n=40){if(e.length<=n)return e;const s=e.slice(0,Math.floor(n/2)-2),i=e.slice(-Math.floor(n/2)+2);return`${s}...${i}`}function rS(e,n){if(e.project.id!==n.project.id||e.project.status!==n.project.status||e.project.name!==n.project.name||e.project.path!==n.project.path||e.project.lastActivityAt!==n.project.lastActivityAt||e.isLoading!==n.isLoading)return!1;const s=e.health,i=n.health;if(!s&&!i)return!0;if(!s||!i||s.activeTaskCount!==i.activeTaskCount||s.inFlightAgentCount!==i.inFlightAgentCount||s.totalTasksCompleted!==i.totalTasksCompleted||s.totalTasksFailed!==i.totalTasksFailed||s.status!==i.status)return!1;const r=e.node,o=n.node;return!r&&!o?e.nodeNameFallback===n.nodeNameFallback:!r||!o?!1:r.id===o.id&&r.name===o.name&&r.status===o.status&&r.type===o.type}function oS({project:e,health:n,onSelect:s,onPause:i,onResume:r,onRemove:o,node:l,nodeNameFallback:c,isLoading:u=!1}){const[d,m]=a.useState(!1),h=sS[e.status],f=h.icon,p=a.useCallback(()=>{s(e)},[s,e]),g=a.useCallback(E=>{E.stopPropagation(),i(e)},[i,e]),b=a.useCallback(E=>{E.stopPropagation(),r(e)},[r,e]),v=a.useCallback(E=>{if(E.stopPropagation(),!d){m(!0);return}o(e),m(!1)},[d,o,e]),x=e.status==="paused",y=e.status==="errored",j=e.status==="initializing";return t.jsxs("div",{className:`project-card ${u?"project-card-loading":""} ${y?"project-card-errored":""}`,onClick:p,"data-project-id":e.id,role:"button",tabIndex:0,onKeyDown:E=>{(E.key==="Enter"||E.key===" ")&&(E.preventDefault(),p())},children:[t.jsxs("div",{className:"project-card-header",children:[t.jsx("div",{className:"project-card-icon",children:t.jsx(ts,{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:aS(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:iS(e.lastActivityAt||n?.lastActivityAt)})]}),t.jsxs("div",{className:"project-card-actions",children:[x?t.jsxs("button",{className:"project-card-action project-card-action-resume",onClick:b,disabled:u,title:"Resume project","aria-label":"Resume project",children:[t.jsx(_n,{size:14}),t.jsx("span",{children:"Resume"})]}):t.jsxs("button",{className:"project-card-action project-card-action-pause",onClick:g,disabled:u||j,title:j?"Cannot pause while initializing":"Pause project","aria-label":"Pause project",children:[t.jsx(Vs,{size:14}),t.jsx("span",{children:"Pause"})]}),t.jsxs("button",{className:"project-card-action project-card-action-open",onClick:p,disabled:u,title:"Open project","aria-label":"Open project",children:[t.jsx(Dr,{size:14}),t.jsx("span",{children:"Open"})]}),t.jsxs("button",{className:`project-card-action project-card-action-remove ${d?"is-armed":""}`,onClick:v,disabled:u,title:d?"Confirm remove":"Remove project","aria-label":d?"Confirm remove project":"Remove project",children:[t.jsx(cn,{size:14}),t.jsx("span",{children:d?"Confirm":""})]})]})]})]})}const lS=a.memo(oS,rS);function cS(){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(ts,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(Ds,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(Nn,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(gs,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]})]})}),t.jsxs("div",{className:"project-overview__filters-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--tab"}),t.jsx("div",{className:"project-skeleton project-skeleton--tab"}),t.jsx("div",{className:"project-skeleton project-skeleton--tab"}),t.jsx("div",{className:"project-skeleton project-skeleton--tab"})]}),t.jsx("div",{className:"project-grid project-grid--skeleton",children:Array.from({length:6}).map((e,n)=>t.jsxs("div",{className:"project-card project-card--skeleton",children:[t.jsxs("div",{className:"project-card-skeleton__header",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon-circle"}),t.jsxs("div",{className:"project-skeleton__text-group",children:[t.jsx("div",{className:"project-skeleton project-skeleton--title"}),t.jsx("div",{className:"project-skeleton project-skeleton--path"})]}),t.jsx("div",{className:"project-skeleton project-skeleton--badge"})]}),t.jsxs("div",{className:"project-card-skeleton__health",children:[t.jsx("div",{className:"project-skeleton project-skeleton--metric"}),t.jsx("div",{className:"project-skeleton project-skeleton--metric"}),t.jsx("div",{className:"project-skeleton project-skeleton--metric"})]}),t.jsxs("div",{className:"project-card-skeleton__footer",children:[t.jsx("div",{className:"project-skeleton project-skeleton--activity"}),t.jsx("div",{className:"project-skeleton project-skeleton--actions"})]})]},n))})]})}const dS=1e4,dm=5;function uS(e){const[n,s]=a.useState({}),[i,r]=a.useState(!0),[o,l]=a.useState(null),c=a.useRef(null),u=a.useRef(null),d=a.useRef(!1),m=a.useCallback(async()=>{if(e.length===0){s({}),d.current||(d.current=!0),r(!1);return}u.current&&u.current.abort(),u.current=new AbortController,!d.current&&r(!0),l(null);try{const p={};for(let g=0;g<e.length;g+=dm){const b=e.slice(g,g+dm),v=await Promise.allSettled(b.map(async x=>{try{return await yu(x)}catch{return null}}));if(b.forEach((x,y)=>{const j=v[y];p[x]=j.status==="fulfilled"?j.value:null}),u.current?.signal.aborted)return}s(p),d.current=!0}catch(p){if(p instanceof Error&&p.name==="AbortError")return;l(p instanceof Error?p.message:"Failed to fetch health data"),d.current=!0}finally{r(!1)}},[e]),h=a.useCallback(async f=>{try{const p=await yu(f);s(g=>({...g,[f]:p}))}catch(p){console.error(`Failed to fetch health for project ${f}:`,p)}},[]);return a.useEffect(()=>(d.current=!1,m(),()=>{u.current&&u.current.abort()}),[m]),a.useEffect(()=>{if(e.length!==0)return c.current&&clearInterval(c.current),c.current=setInterval(()=>{m()},dS),()=>{c.current&&(clearInterval(c.current),c.current=null)}},[m,e.length]),{healthMap:n,loading:i,error:o,refresh:m,refreshProject:h}}function mS({projects:e,loading:n=!1,onSelectProject:s,onAddProject:i,onPauseProject:r,onResumeProject:o,onRemoveProject:l,nodes:c=[]}){const[u,d]=a.useState("all"),[m,h]=a.useState(null),[f,p]=a.useState("activity"),[g,b]=a.useState("desc");a.useEffect(()=>{if(typeof window>"u")return;const G=localStorage.getItem("kb-dashboard-recent-projects");if(G)try{const M=JSON.parse(G);x(M)}catch{}},[]);const[v,x]=a.useState([]),y=a.useMemo(()=>e.map(G=>G.id),[e]),{healthMap:j,loading:E}=uS(y),C=a.useMemo(()=>e.map(G=>({project:G,health:j[G.id]||null})),[e,j]),w=a.useMemo(()=>{let G=[...C];return u!=="all"&&(G=G.filter(({project:M})=>M.status===u)),m!==null&&(G=G.filter(({project:M})=>M.nodeId===m)),G},[C,u,m]),R=a.useMemo(()=>{const G=[...w];return G.sort((M,T)=>{let D=0;switch(f){case"name":D=M.project.name.localeCompare(T.project.name);break;case"activity":{const K=M.project.lastActivityAt||M.health?.lastActivityAt||M.project.updatedAt,J=T.project.lastActivityAt||T.health?.lastActivityAt||T.project.updatedAt;D=new Date(J).getTime()-new Date(K).getTime();break}case"status":{const K={errored:0,initializing:1,paused:2,active:3};D=K[M.project.status]-K[T.project.status];break}}return g==="asc"?D:-D}),G},[w,f,g]),S=a.useMemo(()=>{const G=e.length,M=e.filter(z=>z.status==="active").length,T=e.filter(z=>z.status==="errored").length,D=new Set;e.forEach(z=>{z.nodeId&&D.add(z.nodeId)});const K=D.size||(G>0?1:0);let J=0,te=0,N=0;return Object.values(j).forEach(z=>{z&&(J+=z.activeTaskCount,te+=z.totalTasksCompleted,N+=z.inFlightAgentCount)}),{totalProjects:G,activeProjects:M,erroredProjects:T,totalNodes:K,totalActiveTasks:J,totalCompletedTasks:te,totalInFlightAgents:N}},[e,j]),O=a.useMemo(()=>({all:e.length,active:e.filter(G=>G.status==="active").length,paused:e.filter(G=>G.status==="paused").length,errored:e.filter(G=>G.status==="errored").length}),[e]),_=a.useMemo(()=>{const G=new Map;return e.forEach(M=>{const T=M.nodeId,D=G.get(T);if(D)D.count++;else{const J=c.find(te=>te.id===T)?.name??M._sourceNodeName??"Local";G.set(T,{name:J,count:1})}}),Array.from(G.entries()).map(([M,{name:T,count:D}])=>({nodeId:M??null,name:T,count:D}))},[e,c]),P=a.useCallback(G=>{const M=[G.id,...v.filter(T=>T!==G.id)].slice(0,3);x(M),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify(M)),s(G)},[s,v]);return n||E&&e.length>0&&Object.keys(j).length===0?t.jsx(cS,{}):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(dr,{size:48})}),t.jsx("h2",{className:"project-empty-state__title",children:"No Projects Found"}),t.jsx("p",{className:"project-empty-state__description",children:"Get started by adding your first project. Projects allow you to organize and track tasks across multiple repositories."}),t.jsxs("button",{className:"btn btn-primary project-empty-state__cta",onClick:i,children:[t.jsx(dn,{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(Vi,{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(ts,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:S.totalProjects}),t.jsx("span",{className:"project-stat__label",children:"Total"})]})]}),t.jsxs("div",{className:"project-stat project-stat--active",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Ds,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:S.totalActiveTasks}),t.jsx("span",{className:"project-stat__label",children:"Active Tasks"})]})]}),t.jsxs("div",{className:"project-stat project-stat--completed",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Nn,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:S.totalCompletedTasks}),t.jsx("span",{className:"project-stat__label",children:"Completed"})]})]}),S.erroredProjects>0&&t.jsxs("div",{className:"project-stat project-stat--error",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(gs,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:S.erroredProjects}),t.jsx("span",{className:"project-stat__label",children:"Errored"})]})]}),S.totalNodes>1&&t.jsxs("div",{className:"project-stat project-stat--nodes",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Nr,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:S.totalNodes}),t.jsx("span",{className:"project-stat__label",children:"Nodes"})]})]})]}),t.jsxs("button",{className:"btn btn-primary project-overview__add-btn",onClick:i,children:[t.jsx(dn,{size:16}),"Add Project"]})]}),t.jsxs("div",{className:"project-overview__filters",children:[t.jsxs("div",{className:"project-filter-tabs",children:[t.jsxs("button",{className:`project-filter-tab ${u==="all"?"active":""}`,onClick:()=>d("all"),children:["All",t.jsx("span",{className:"project-filter-count",children:O.all})]}),t.jsxs("button",{className:`project-filter-tab ${u==="active"?"active":""}`,onClick:()=>d("active"),children:["Active",t.jsx("span",{className:"project-filter-count",children:O.active})]}),t.jsxs("button",{className:`project-filter-tab ${u==="paused"?"active":""}`,onClick:()=>d("paused"),children:["Paused",t.jsx("span",{className:"project-filter-count",children:O.paused})]}),t.jsxs("button",{className:`project-filter-tab ${u==="errored"?"active":""} ${O.errored>0?"has-errors":""}`,onClick:()=>d("errored"),children:["Errored",t.jsx("span",{className:"project-filter-count",children:O.errored})]})]}),_.length>1&&t.jsxs("div",{className:"project-node-filter",children:[t.jsx(Nr,{size:14}),t.jsxs("select",{value:m??"",onChange:G=>{h(G.target.value||null)},className:"project-node-filter-select","aria-label":"Filter by node",children:[t.jsx("option",{value:"",children:"All Nodes"}),_.map(({nodeId:G,name:M,count:T})=>t.jsxs("option",{value:G??"",children:[M," (",T,")"]},G??"local"))]})]}),t.jsxs("div",{className:"project-sort",children:[t.jsx(Lo,{size:14}),t.jsxs("select",{value:`${f}-${g}`,onChange:G=>{const[M,T]=G.target.value.split("-");p(M),b(T)},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(wp,{size:14})]})]}),t.jsx("div",{className:"project-grid",children:R.map(({project:G,health:M})=>{const T=c.find(K=>K.id===G.nodeId),D=T?void 0:G._sourceNodeName;return t.jsx(lS,{project:G,health:M,node:T,nodeNameFallback:D,onSelect:P,onPause:r,onResume:o,onRemove:l},G.id)})}),R.length===0&&t.jsxs("div",{className:"project-overview__no-results",children:[t.jsx(Lo,{size:32}),t.jsx("p",{children:"No projects match the current filter"}),t.jsx("button",{className:"btn btn-secondary",onClick:()=>d("all"),children:"Show All Projects"})]})]})}const hS=45e3,pS=3e3,fS=2e3,gS=1500,um="fusion:sse-client-id";let oa=null;const Ci=new Map;function mm(){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 hf(){if(!(typeof window>"u")){if(oa)return oa;try{const e=window.sessionStorage.getItem(um);if(e)return oa=e,e;const n=mm();return window.sessionStorage.setItem(um,n),oa=n,n}catch{return oa=mm(),oa}}}function pf(e){if(!(typeof window>"u"))try{return{parsed:new URL(e,window.location.origin),preserveRelativePath:e.startsWith("/")}}catch{return}}function ff(e){return e.origin===window.location.origin&&e.pathname==="/api/events"}function bS(e){const n=hf();if(!n)return e;const s=pf(e);return!s||!ff(s.parsed)?e:(s.parsed.searchParams.set("clientId",n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function _d(e,n){const s=hf();if(!s)return;const i=pf(e);if(!i||!ff(i.parsed))return;const r=new URL(`/api/events/${n}`,window.location.origin);r.searchParams.set("clientId",s);const o=i.parsed.searchParams.get("projectId");return o&&r.searchParams.set("projectId",o),oi(`${r.pathname}${r.search}${r.hash}`)}function xS(e){if(typeof window>"u")return;const n=_d(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 hl(e){e.keepaliveTimer&&(clearInterval(e.keepaliveTimer),e.keepaliveTimer=null)}function hm(e){if(typeof window>"u"||typeof window.fetch!="function")return;const n=_d(e.url,"keepalive");if(!n)return;const s=typeof AbortController<"u"?new AbortController:null,i=s?window.setTimeout(()=>s.abort(),gS):null;window.fetch(n,{method:"POST",cache:"no-store",signal:s?.signal}).catch(()=>{}).finally(()=>{i!==null&&window.clearTimeout(i)})}function vS(e){hl(e),_d(e.url,"keepalive")&&(hm(e),e.keepaliveTimer=window.setInterval(()=>{hm(e)},fS))}if(typeof window<"u"){const e=()=>{for(const s of Array.from(Ci.values()))if(!s.closed){if(hl(s),xS(s),s.es){try{s.es.close()}catch{}s.es=null}s.closed=!0}},n=s=>{if(s.persisted)for(const i of Array.from(Ci.values()))i.subscribers.size!==0&&(i.closed=!1,Md(i))};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e),window.addEventListener("pageshow",n)}function hr(e){e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),e.heartbeatTimer=setTimeout(()=>{gf(e)},hS)}function gf(e){if(e.heartbeatTimer&&(clearTimeout(e.heartbeatTimer),e.heartbeatTimer=null),e.es&&(e.es.close(),e.es=null),hl(e),e.nativeListeners.clear(),e.closed||e.subscribers.size===0||e.reconnectTimer)return;const n=Ci.get(e.url);if(!(!n||n!==e)){for(const s of e.subscribers)s.onReconnect?.();e.reconnectTimer=setTimeout(()=>{if(e.reconnectTimer=null,e.closed)return;const s=Ci.get(e.url);s&&s===e&&e.subscribers.size>0&&Md(e)},pS)}}function Md(e){if(e.es||e.closed)return;e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=null);const n=new EventSource(oi(bS(e.url)));e.es=n,vS(e),n.addEventListener("open",()=>{hr(e);const s=e.hasOpenedOnce;e.hasOpenedOnce=!0;for(const i of e.subscribers)i.onOpen?.(),s&&i.onReconnect?.()}),n.addEventListener("error",s=>{for(const i of e.subscribers)i.onError?.(s);gf(e)}),n.addEventListener("message",()=>hr(e)),n.addEventListener("heartbeat",()=>hr(e)),bf(e),hr(e)}function bf(e){if(!e.es)return;const n=new Set;for(const s of e.subscribers)for(const i of s.events.keys())n.add(i);for(const s of n){if(e.nativeListeners.has(s))continue;const i=r=>{hr(e);const o=r;for(const l of e.subscribers){const c=l.events.get(s);if(c)for(const u of c)u(o)}};e.nativeListeners.set(s,i),e.es.addEventListener(s,i)}}function yS(e){e.closed=!0,e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),hl(e),e.reconnectTimer&&clearTimeout(e.reconnectTimer),e.es&&e.es.close(),e.es=null,e.nativeListeners.clear(),Ci.delete(e.url)}function Js(e,n={}){let s=Ci.get(e);s||(s={url:e,es:null,subscribers:new Set,nativeListeners:new Map,heartbeatTimer:null,keepaliveTimer:null,reconnectTimer:null,hasOpenedOnce:!1,closed:!1},Ci.set(e,s));const i={events:new Map,onOpen:n.onOpen,onReconnect:n.onReconnect,onError:n.onError};if(n.events)for(const[l,c]of Object.entries(n.events)){let u=i.events.get(l);u||(u=new Set,i.events.set(l,u)),u.add(c)}s.subscribers.add(i);const r=!!s.es&&s.hasOpenedOnce;Md(s),bf(s),r&&queueMicrotask(()=>{s.subscribers.has(i)&&i.onOpen?.()});let o=!0;return()=>{if(!o)return;o=!1;const l=Ci.get(e);l&&(l.subscribers.delete(i),l.subscribers.size===0&&yS(l))}}const Ad="kb-planning-last-description",Rd="kb-subtask-last-description",Td="kb-mission-last-goal";function wS(e,n){fs(Ad,e,n)}function jS(e){return Yn(Ad,e)||""}function la(e){Ar(Ad,e)}function kS(e,n){fs(Rd,e,n)}function NS(e){return Yn(Rd,e)||""}function Ol(e){Ar(Rd,e)}function SS(e,n){fs(Td,e,n)}function CS(e){return Yn(Td,e)||""}function wi(e){Ar(Td,e)}function ES(e){const{question:n,response:s}=e;if(!n)return s;if(s&&typeof s=="object"&&!Array.isArray(s)){const i=s;if(n.id in i)return i[n.id]}return s}function _S(e,n){switch(e.type){case"text":return typeof n=="string"?n:n==null?"":String(n);case"single_select":return typeof n=="string"?e.options?.find(i=>i.id===n)?.label??n:n==null?"":String(n);case"multi_select":return Array.isArray(n)?n.map(s=>typeof s!="string"?String(s):e.options?.find(r=>r.id===s)?.label??s).join(", "):n==null?"":String(n);case"confirm":return n===!0?"Yes":n===!1?"No":n==null?"":String(n);default:return n==null?"":JSON.stringify(n)}}function MS(e){let n=0;const s=[];for(const i of e){if(i.question){n+=1,s.push({...i,questionNumber:n});continue}i.thinkingOutput&&s.push({...i,questionNumber:null})}return s}function Ls({entries:e,defaultShowThinking:n=!1}){const[s,i]=a.useState({}),r=MS(e);return r.length===0?null:t.jsx("div",{className:"conversation-history","data-testid":"conversation-history",children:r.map((o,l)=>{const c=!!o.question,u=!!o.thinkingOutput,d=s[l]??n,m=c?ES(o):void 0,h=o.question&&m!==void 0?_S(o.question,m):"";return t.jsxs("div",{className:"conversation-entry",children:[c?t.jsxs("div",{className:"conversation-entry-question",children:[t.jsxs("span",{className:"conversation-entry-question-label",children:["Q",o.questionNumber]}),t.jsx("p",{children:o.question?.question})]}):t.jsx("div",{className:"conversation-entry-question",children:t.jsx("span",{className:"conversation-entry-question-label",children:"AI Reasoning"})}),c&&t.jsxs("div",{className:"conversation-entry-response",children:[t.jsx("strong",{children:"Your response"}),t.jsx("p",{children:h||"—"})]}),u&&t.jsxs("div",{className:"conversation-entry-thinking",children:[t.jsxs("button",{type:"button",className:"conversation-thinking-toggle",onClick:()=>{i(f=>({...f,[l]:!d}))},"aria-expanded":d,children:[t.jsx("span",{"aria-hidden":"true",children:d?"▾":"▸"}),d?`Hide ${c?"AI thinking":"AI reasoning"}`:`Show ${c?"AI thinking":"AI reasoning"}`]}),d&&t.jsx("pre",{children:o.thinkingOutput})]})]},`${o.question?.id??"thinking"}-${l}`)})})}const pm="fusion-tab-id";function AS(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Qi(){if(typeof window>"u")return"server-tab";const e=window.sessionStorage.getItem(pm);if(e)return e;const n=AS();return window.sessionStorage.setItem(pm,n),n}function pl(e){const n=a.useMemo(()=>Qi(),[]),[s,i]=a.useState(!1),[r,o]=a.useState(null),[l,c]=a.useState(!1);a.useEffect(()=>{if(!e){i(!1),o(null),c(!1);return}let d=!0;return c(!0),Promise.resolve(Fk(e,n)).then(m=>{if(d){if(m.acquired){i(!1),o(null);return}i(!0),o(m.currentHolder)}}).catch(()=>{d&&(i(!1),o(null))}).finally(()=>{d&&c(!1)}),()=>{d=!1;try{const m=Uk(e,n);m&&typeof m.catch=="function"&&m.catch(()=>{})}catch{}}},[e,n]),a.useEffect(()=>{if(!e||typeof window>"u")return;const d=()=>{if(typeof navigator.sendBeacon!="function")return;const m=oi(`/api/ai-sessions/${encodeURIComponent(e)}/lock/beacon?tabId=${encodeURIComponent(n)}`);navigator.sendBeacon(m)};return window.addEventListener("beforeunload",d),()=>{window.removeEventListener("beforeunload",d)}},[e,n]),a.useEffect(()=>!e||typeof EventSource>"u"?void 0:Js("/api/events",{events:{"ai_session:updated":m=>{try{const h=JSON.parse(m.data);if(h.id!==e)return;const f=h.lockedByTab??null;o(f),i(!!(f&&f!==n))}catch{}}}}),[e,n]);const u=a.useCallback(async()=>{if(e){c(!0);try{await Promise.resolve(Bk(e,n)),i(!1),o(null)}finally{c(!1)}}},[e,n]);return{isLockedByOther:s,currentHolder:r,takeControl:u,isLoading:l}}const RS="fusion:ai-session-sync",fm="fusion:ai-session-sync",TS=3e4,PS=6e4;function ei(){return Date.now()}function IS(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function gm(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 $S{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=IS(),this.snapshot={tabId:this.tabId,sessions:new Map,activeTabMap:new Map},this.isBrowser()&&(this.initializeTransport(),this.startHeartbeat(),this.startStaleSweep(),this.setupBeforeUnloadCleanup())}subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}getSnapshot(){return this.snapshot}requestSync(){this.publish({type:"sync:request",tabId:this.tabId,timestamp:ei()})}broadcastUpdate(n){const s=n.timestamp??ei();this.applySessionUpdate({sessionId:n.sessionId,status:n.status,needsInput:n.needsInput??n.status==="awaiting_input",owningTabId:n.owningTabId,type:n.type,title:n.title,projectId:n.projectId,updatedAt:n.updatedAt},s),this.publish({type:"session:updated",sessionId:n.sessionId,status:n.status,needsInput:n.needsInput,owningTabId:n.owningTabId,sessionType:n.type,title:n.title,projectId:n.projectId,updatedAt:n.updatedAt,timestamp:s})}broadcastCompleted(n){const s=n.status??"complete",i=n.timestamp??ei();this.applySessionUpdate({sessionId:n.sessionId,status:s,needsInput:!1,owningTabId:null},i),this.ownershipBySession.delete(n.sessionId),this.ownedSessions.delete(n.sessionId),this.emit(),this.publish({type:"session:completed",sessionId:n.sessionId,status:s,timestamp:i})}broadcastLock(n,s){const i=ei();this.applyTabOwnership(n,s,i),this.ownedSessions.set(n,s),this.publish({type:"tab:active",tabId:s,sessionId:n,timestamp:i})}broadcastUnlock(n,s){const i=ei();this.releaseTabOwnership(n,s,i),this.ownedSessions.delete(n),this.publish({type:"tab:inactive",tabId:s,sessionId:n,timestamp:i})}broadcastHeartbeat(n){const s=ei();this.updateHeartbeat(n,s),this.publish({type:"tab:heartbeat",tabId:n,timestamp:s})}destroy(){this.cleanupStorageListener?.(),this.cleanupStorageListener=null,this.cleanupBeforeUnload?.(),this.cleanupBeforeUnload=null,this.channel&&(this.channel.close(),this.channel=null),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null),this.staleSweepInterval&&(clearInterval(this.staleSweepInterval),this.staleSweepInterval=null)}reset(){this.sessionStates.clear(),this.ownershipBySession.clear(),this.heartbeatByTab.clear(),this.ownedSessions.clear(),this.snapshot={tabId:this.tabId,sessions:new Map,activeTabMap:new Map},this.emit()}isBrowser(){return typeof window<"u"}initializeTransport(){if(typeof BroadcastChannel<"u")try{this.channel=new BroadcastChannel(RS),this.channel.onmessage=s=>{const i=gm(s.data);i&&this.handleIncomingMessage(i)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==fm||!s.newValue))try{const i=JSON.parse(s.newValue),r=gm(i.message);r&&this.handleIncomingMessage(r)}catch{}};window.addEventListener("storage",n),this.cleanupStorageListener=()=>{window.removeEventListener("storage",n)}}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{const n=ei();this.updateHeartbeat(this.tabId,n),this.publish({type:"tab:heartbeat",tabId:this.tabId,timestamp:n})},TS)}startStaleSweep(){this.staleSweepInterval=setInterval(()=>{this.emit()},1e4)}setupBeforeUnloadCleanup(){const n=()=>{for(const[s,i]of this.ownedSessions.entries()){const r=ei();this.publish({type:"tab:inactive",tabId:i,sessionId:s,timestamp:r})}};window.addEventListener("beforeunload",n),this.cleanupBeforeUnload=()=>{window.removeEventListener("beforeunload",n)}}publish(n){const s={...n,senderTabId:this.tabId};if(this.channel){this.channel.postMessage(s);return}if(this.usingStorageFallback)try{const i={id:`${s.type}-${s.timestamp}-${Math.random().toString(36).slice(2,8)}`,message:s};window.localStorage.setItem(fm,JSON.stringify(i))}catch{}}handleIncomingMessage(n){switch(n.type){case"session:updated":{this.applySessionUpdate({sessionId:n.sessionId,status:n.status,needsInput:n.needsInput,owningTabId:n.owningTabId,type:n.sessionType,title:n.title,projectId:n.projectId,updatedAt:n.updatedAt},n.timestamp);return}case"session:completed":{this.applySessionUpdate({sessionId:n.sessionId,status:n.status??"complete",needsInput:!1,owningTabId:null},n.timestamp),this.ownershipBySession.delete(n.sessionId),this.emit();return}case"tab:active":{this.applyTabOwnership(n.sessionId,n.tabId,n.timestamp);return}case"tab:inactive":{this.releaseTabOwnership(n.sessionId,n.tabId,n.timestamp);return}case"tab:heartbeat":{this.updateHeartbeat(n.tabId,n.timestamp);return}case"sync:request":{if(n.tabId===this.tabId)return;const s=[...this.sessionStates.values()].map(o=>{const l=this.ownershipBySession.get(o.sessionId);return{...o,owningTabId:l?.tabId??o.owningTabId??null}}),i=[...this.ownershipBySession.entries()].map(([o,l])=>({sessionId:o,tabId:l.tabId,timestamp:l.timestamp})),r=[...this.heartbeatByTab.entries()].map(([o,l])=>({tabId:o,timestamp:l}));this.publish({type:"sync:response",tabId:n.tabId,sessions:s,locks:i,heartbeats:r,timestamp:ei()});return}case"sync:response":{if(n.tabId!==this.tabId)return;for(const s of n.sessions)this.applySessionUpdate({sessionId:s.sessionId,status:s.status,needsInput:s.needsInput,owningTabId:s.owningTabId,type:s.type,title:s.title,projectId:s.projectId,updatedAt:s.updatedAt},s.lastEventTimestamp,!1);for(const s of n.locks??[])this.applyTabOwnership(s.sessionId,s.tabId,s.timestamp,!1);for(const s of n.heartbeats??[])this.updateHeartbeat(s.tabId,s.timestamp,!1);this.emit();return}default:return}}applySessionUpdate(n,s,i=!0){const r=this.sessionStates.get(n.sessionId);if(r&&s<r.lastEventTimestamp)return;const o=this.ownershipBySession.get(n.sessionId),l={sessionId:n.sessionId,status:n.status,needsInput:n.needsInput??n.status==="awaiting_input",lastEventTimestamp:s,owningTabId:n.owningTabId??o?.tabId??r?.owningTabId??null,type:n.type??r?.type,title:n.title??r?.title,projectId:n.projectId??r?.projectId,updatedAt:n.updatedAt??new Date(s).toISOString()};this.sessionStates.set(n.sessionId,l),n.owningTabId!==void 0&&(n.owningTabId?this.applyTabOwnership(n.sessionId,n.owningTabId,s,!1):this.ownershipBySession.delete(n.sessionId)),i&&this.emit()}applyTabOwnership(n,s,i,r=!0){const o=this.ownershipBySession.get(n);if(o&&i<o.timestamp)return;this.ownershipBySession.set(n,{tabId:s,timestamp:i}),this.updateHeartbeat(s,i,!1);const l=this.sessionStates.get(n);l&&i>=l.lastEventTimestamp&&this.sessionStates.set(n,{...l,owningTabId:s,lastEventTimestamp:i}),r&&this.emit()}releaseTabOwnership(n,s,i,r=!0){const o=this.ownershipBySession.get(n);if(!o||o.tabId!==s||i<o.timestamp)return;this.ownershipBySession.delete(n);const l=this.sessionStates.get(n);l&&i>=l.lastEventTimestamp&&this.sessionStates.set(n,{...l,owningTabId:null,lastEventTimestamp:i}),r&&this.emit()}updateHeartbeat(n,s,i=!0){const r=this.heartbeatByTab.get(n);r!==void 0&&s<r||(this.heartbeatByTab.set(n,s),i&&this.emit())}emit(){const n=ei(),s=new Map;for(const[r,o]of this.sessionStates.entries()){const l=this.ownershipBySession.get(r);s.set(r,{...o,owningTabId:l?.tabId??o.owningTabId??null})}const i=new Map;for(const[r,o]of this.ownershipBySession.entries()){const l=this.heartbeatByTab.get(o.tabId)??o.timestamp,c=n-l>PS;i.set(r,{sessionId:r,tabId:o.tabId,lastHeartbeatTimestamp:l,lastLockTimestamp:o.timestamp,stale:c})}this.snapshot={tabId:this.tabId,sessions:s,activeTabMap:i};for(const r of this.listeners)r()}}const ti=new $S;function La(){const e=a.useSyncExternalStore(c=>ti.subscribe(c),()=>ti.getSnapshot(),()=>ti.getSnapshot());a.useEffect(()=>{ti.requestSync()},[]);const n=a.useCallback(c=>{ti.broadcastUpdate(c)},[]),s=a.useCallback(c=>{ti.broadcastCompleted(c)},[]),i=a.useCallback((c,u)=>{ti.broadcastLock(c,u)},[]),r=a.useCallback((c,u)=>{ti.broadcastUnlock(c,u)},[]),o=a.useCallback(c=>{ti.broadcastHeartbeat(c)},[]),l=a.useCallback(()=>{ti.requestSync()},[]);return{tabId:e.tabId,sessions:e.sessions,activeTabMap:e.activeTabMap,broadcastUpdate:n,broadcastCompleted:s,broadcastLock:i,broadcastUnlock:r,broadcastHeartbeat:o,requestSync:l}}function DS(e,n){return e&&n?`${e}/${n}`:""}function LS(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 zS=["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 OS({isOpen:e,onClose:n,onMissionCreated:s,projectId:i,initialGoal:r,resumeSessionId:o}){const[l,c]=a.useState(""),[u,d]=a.useState({type:"initial"}),[m,h]=a.useState(null),[f,p]=a.useState([]),[g,b]=a.useState([]),[v,x]=a.useState(null),[y,j]=a.useState(!1),E=a.useRef(!1),[C,w]=a.useState(""),[R,S]=a.useState(!0),[O,_]=a.useState(!1),[P,U]=a.useState(!1),[G,M]=a.useState(!1),T=a.useRef(null),D=a.useRef(null),K=a.useRef(null),J=a.useRef(null),[te,N]=a.useState(o??null),z=a.useMemo(()=>Qi(),[]),{isLockedByOther:I,takeControl:k,isLoading:H}=pl(e?te:null),{activeTabMap:Q,broadcastUpdate:ue,broadcastCompleted:be,broadcastLock:V,broadcastUnlock:ve,broadcastHeartbeat:B}=La(),{confirm:Y}=Gs(),[X,he]=a.useState(void 0),[de,me]=a.useState(void 0),[se,_e]=a.useState([]),[Fe,Te]=a.useState(!0),[st,nt]=a.useState(null),[qe,Xe]=a.useState([]),[$e,Ue]=a.useState([]),oe=DS(X,de);a.useEffect(()=>{(async()=>{try{Te(!0);const re=await bs();_e(re.models),Xe(re.favoriteProviders),Ue(re.favoriteModels)}catch(re){nt(ke(re)||"Failed to load models")}finally{Te(!1)}})()},[]);const je=a.useCallback(ee=>{Xe(re=>{const Se=re,ne=Se.includes(ee)?Se.filter(Ze=>Ze!==ee):[ee,...Se];return bn({favoriteProviders:ne,favoriteModels:$e}).catch(()=>{Xe(Se)}),ne})},[$e]),ie=a.useCallback(ee=>{Ue(re=>{const Se=re,ne=Se.includes(ee)?Se.filter(Ze=>Ze!==ee):[ee,...Se];return bn({favoriteProviders:qe,favoriteModels:ne}).catch(()=>{Ue(Se)}),ne})},[qe]),Ae=a.useCallback((ee,re)=>{if(!ee||!re)return"Using default";const Se=se.find(ot=>ot.provider===ee&&ot.id===re);return Se?`${Se.provider}/${Se.id}`:`${ee}/${re}`},[se]),Le=a.useCallback(ee=>{D.current?.close();const re=Ck(ee,i,{onThinking:Se=>{w(ot=>ot+Se),ue({sessionId:ee,status:"generating",needsInput:!1,owningTabId:z,type:"mission_interview",title:l.trim()||void 0,projectId:i??null})},onQuestion:Se=>{_(!1),U(!1),wi(i),d({type:"question",sessionId:ee,question:Se}),w(""),j(!0),ue({sessionId:ee,status:"awaiting_input",needsInput:!0,owningTabId:z,type:"mission_interview",title:l.trim()||void 0,projectId:i??null})},onSummary:Se=>{_(!1),U(!1),wi(i),d({type:"summary",sessionId:ee,summary:Se}),x(Se),w(""),j(!0),ue({sessionId:ee,status:"complete",needsInput:!1,owningTabId:z,type:"mission_interview",title:l.trim()||void 0,projectId:i??null})},onError:Se=>{const ot=Se||"Session failed while contacting the AI.";_(!1),U(!1),h(null),d({type:"error",sessionId:ee,errorMessage:ot}),w(""),j(!0),K.current=ee,ue({sessionId:ee,status:"error",needsInput:!1,owningTabId:z,type:"mission_interview",title:l.trim()||void 0,projectId:i??null}),be({sessionId:ee,status:"error"})},onComplete:()=>{_(!1),U(!1),K.current=null,be({sessionId:ee,status:"complete"})},onConnectionStateChange:Se=>{_(Se==="reconnecting")}});D.current=re},[be,ue,l,i,z]),we=a.useCallback(async ee=>{const re=ee??l;if(re.trim()){h(null),w(""),p([]),b([]),_(!1),d({type:"loading"});try{const{sessionId:Se}=await jk(re.trim(),i,X&&de?{modelProvider:X,modelId:de}:void 0);K.current=Se,N(Se),wi(i),Le(Se),p([])}catch(Se){_(!1),h(ke(Se)||"Failed to start interview session"),d({type:"initial"}),K.current=null,N(null)}}},[Le,l,X,de,i]);a.useEffect(()=>{e&&u.type==="initial"&&T.current?.focus()},[e,u.type]),a.useEffect(()=>{if(e&&r&&!E.current&&u.type==="initial"){c(r);const ee=setTimeout(()=>{E.current=!0,we(r)},0);return()=>clearTimeout(ee)}else if(e&&!r&&!E.current&&u.type==="initial"){const ee=CS(i);ee&&c(ee)}},[e,r,u.type,we]),a.useEffect(()=>{e||(E.current=!1,_(!1),U(!1),N(null))},[e]),a.useEffect(()=>{if(!e||!o||u.type!=="initial")return;let ee=!1;return ai(o).then(re=>{if(ee||!re)return;const Se=ka(re.conversationHistory);if(b(Se),N(re.id),p(Se.map(ot=>ot.response).filter(ot=>!!(ot&&typeof ot=="object"&&!Array.isArray(ot)))),re.status==="awaiting_input"&&re.currentQuestion)try{wi(i);const ot=JSON.parse(re.currentQuestion);K.current=re.id,j(!0),d({type:"question",sessionId:re.id,question:ot})}catch{h("Failed to restore session question.")}else if(re.status==="complete"&&re.result)try{wi(i);const ot=JSON.parse(re.result);K.current=re.id,j(!0),x(ot),d({type:"summary",sessionId:re.id,summary:ot})}catch{h("Failed to restore session result.")}else re.status==="generating"?(K.current=re.id,j(!0),re.thinkingOutput&&w(re.thinkingOutput),d({type:"loading"}),Le(re.id)):re.status==="error"&&(K.current=re.id,j(!0),h(null),d({type:"error",sessionId:re.id,errorMessage:re.error??"The session encountered an error."}))}).catch(()=>{ee||h("Failed to resume session.")}),()=>{ee=!0}},[Le,e,o,u.type,i]),a.useEffect(()=>{if(!e){J.current&&(ve(J.current,z),J.current=null);return}if(te&&J.current!==te){J.current&&ve(J.current,z),V(te,z),J.current=te;return}!te&&J.current&&(ve(J.current,z),J.current=null)},[V,ve,e,te,z]),a.useEffect(()=>{if(!e||!te||J.current!==te)return;B(z);const ee=setInterval(()=>{B(z)},3e4);return()=>{clearInterval(ee)}},[B,e,te,z]),a.useEffect(()=>()=>{D.current?.close(),D.current=null,J.current&&(ve(J.current,z),J.current=null)},[ve,z]),a.useEffect(()=>{if(!e)return;const ee=re=>{(u.type==="question"||u.type==="summary")&&(re.preventDefault(),re.returnValue=""),D.current?.close()};return window.addEventListener("beforeunload",ee),()=>window.removeEventListener("beforeunload",ee)},[e,u]);const Ee=a.useCallback(()=>{D.current?.close(),D.current=null,n()},[n]),Ve=a.useCallback(async()=>{if(l&&SS(l,i),!(y&&!await Y({title:"Close Interview",message:"Are you sure you want to close? Your interview progress will be lost.",danger:!0}))){if(D.current?.close(),D.current=null,u.type==="question"||u.type==="summary"||u.type==="error")try{await Vp(u.sessionId,i,z)}catch{}c(""),d({type:"initial"}),h(null),p([]),b([]),x(null),w(""),_(!1),U(!1),j(!1),M(!1),he(void 0),me(void 0),K.current=null,N(null),n()}},[l,y,u,n,i,z,Y]);a.useEffect(()=>{if(!e)return;const ee=re=>{re.key==="Escape"&&Ve()};return document.addEventListener("keydown",ee),()=>document.removeEventListener("keydown",ee)},[e,Ve]);const rt=a.useCallback(async ee=>{if(u.type!=="question")return;const{sessionId:re}=u;h(null),p(Se=>[...Se,ee]),b(Se=>[...Se,{question:u.question,response:ee}]),d({type:"loading"}),w("");try{Le(re),await kk(re,ee,i,z),j(!0)}catch(Se){D.current?.close(),D.current=null,h(ke(Se)||"Failed to submit response"),d({type:"question",sessionId:re,question:u.question})}},[u,i,z,Le]),xe=a.useCallback(async()=>{if(u.type!=="error")return;const ee=u.sessionId;h(null),U(!0),w(""),d({type:"loading"}),Le(ee);try{K.current=ee,N(ee),await Nk(ee,i,z)}catch(re){let Se=re;if((ke(re)||"").includes("not in an error state"))try{const ne=await ai(ee);if(!ne)throw new Error("Failed to refresh interview session.");const Ze=ka(ne.conversationHistory);if(b(Ze),p(Ze.map(ft=>ft.response).filter(ft=>!!(ft&&typeof ft=="object"&&!Array.isArray(ft)))),K.current=ne.id,N(ne.id),j(!0),ne.status==="generating")w(ne.thinkingOutput??""),d({type:"loading"}),D.current?.isConnected()||Le(ne.id);else if(ne.status==="awaiting_input"){if(!ne.currentQuestion)throw new Error("Interview session is awaiting input but has no current question.");wi(i);const ft=JSON.parse(ne.currentQuestion);d({type:"question",sessionId:ne.id,question:ft}),D.current?.isConnected()||Le(ne.id)}else if(ne.status==="complete"){if(!ne.result)throw new Error("Interview session is complete but has no result.");wi(i);const ft=JSON.parse(ne.result);x(ft),d({type:"summary",sessionId:ne.id,summary:ft})}else ne.status==="error"&&d({type:"error",sessionId:ne.id,errorMessage:ne.error??"Retry failed. Please try again."});_(!1);return}catch(ne){Se=ne}D.current?.close(),D.current=null,d({type:"error",sessionId:ee,errorMessage:ke(Se)||"Retry failed. Please try again."}),_(!1)}finally{U(!1)}},[Le,i,z,u]),ce=a.useCallback(async()=>{if(u.type==="summary"){h(null),M(!0);try{const ee=await Sk(u.sessionId,v||void 0,i);s(ee),wi(i),D.current?.close(),D.current=null,c(""),d({type:"initial"}),h(null),p([]),b([]),x(null),w(""),_(!1),U(!1),j(!1),M(!1),K.current=null,N(null),n()}catch(ee){h(ke(ee)||"Failed to create mission"),M(!1)}}},[u,v,s,n,i]),Pe=()=>u.type==="question"?Math.min(f.length+1,6):6,pe=u.type==="loading"||u.type==="question"||u.type==="summary"||u.type==="error",Re=te?Q.get(te):null,Qe=Re&&Re.tabId!==z,Ie=!!(Qe&&!Re.stale),bt=I&&(!Qe||Re.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:ee=>ee.target===ee.currentTarget&&Ve(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(ks,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Plan Mission with AI"})]}),t.jsxs("div",{className:"modal-header-actions",children:[pe&&t.jsx("button",{className:"modal-send-to-background",onClick:Ee,title:"Send to background","aria-label":"Send to background",children:t.jsx(Or,{size:16})}),t.jsx("button",{className:"modal-close",onClick:Ve,"aria-label":"Close",children:t.jsx(qt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[m&&t.jsx("div",{className:"form-error planning-error",children:m}),O&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Ie&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),u.type==="initial"&&t.jsxs("div",{className:"planning-initial",children:[t.jsxs("div",{className:"planning-view-scroll",children:[t.jsxs("div",{className:"planning-intro",children:[t.jsx(cs,{size:32,className:"icon-triage-lg"}),t.jsx("h4",{children:"Transform your vision into a structured mission"}),t.jsx("p",{className:"text-muted",children:"Describe what you want to build. The AI will interview you to understand scope, constraints, and requirements, then produce a structured plan with milestones, slices, and features."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"mission-goal",children:"What do you want to build?"}),t.jsx("textarea",{ref:T,id:"mission-goal",rows:4,className:"planning-textarea",placeholder:"e.g., Build a real-time collaborative document editor with presence, comments, and version history...",value:l,onChange:ee=>c(ee.target.value),onKeyDown:ee=>{ee.key==="Enter"&&!ee.shiftKey&&l.trim()&&(ee.preventDefault(),we())}})]}),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:zS.map((ee,re)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>c(ee),children:ee.length>45?ee.slice(0,45)+"...":ee},re))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"mission-interview-modal-model",className:"form-label",children:["Planning Model",Fe&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(ns,{id:"mission-interview-modal-model",label:"Planning Model",value:oe,onChange:ee=>{const{provider:re,modelId:Se}=LS(ee);he(re),me(Se)},models:se,disabled:Fe,favoriteProviders:qe,onToggleFavorite:je,favoriteModels:$e,onToggleModelFavorite:ie}),st&&t.jsxs("div",{className:"form-hint form-hint-error",children:[st," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{Te(!0);const ee=await bs();_e(ee.models),Xe(ee.favoriteProviders),Ue(ee.favoriteModels),nt(null)}catch(ee){nt(ke(ee)||"Failed to load models")}finally{Te(!1)}})()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${X&&de?"model-badge-custom":"model-badge-default"}`,children:Ae(X,de)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>we(),disabled:!l.trim(),children:[t.jsx(ks,{size:16,className:"icon-mr-8"}),"Start Interview"]})})]}),u.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(lt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:C?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>S(!R),type:"button",children:R?"Hide thinking":"Show thinking"}),R&&C&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:C})})]})]}),u.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[g.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ls,{entries:g}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:u.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void xe(),disabled:P,children:[P?t.jsx(lt,{size:14,className:"spin"}):t.jsx(Fn,{size:14}),t.jsx("span",{className:"icon-ml-6",children:P?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Ve,disabled:P,children:"Cancel"})]})]})]})}),u.type==="question"&&t.jsx(FS,{question:u.question,progress:Pe(),historyEntries:g,onSubmit:rt}),u.type==="summary"&&v&&t.jsx(US,{summary:v,historyEntries:g,onSummaryChange:x,onApprove:ce,onStartOver:()=>{d({type:"initial"}),j(!1),x(null),p([]),b([]),N(null),D.current?.close(),D.current=null},isCreating:G}),I&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(il,{size:16}),t.jsx("span",{children:bt?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),bt&&t.jsx("button",{type:"button",onClick:()=>{k()},disabled:H,className:"btn btn-primary session-lock-take-control",children:H?"Taking control...":"Take Control"})]})})]})]})}):null}function FS({question:e,progress:n,historyEntries:s,onSubmit:i}){const[r,o]=a.useState({}),[l,c]=a.useState(""),u=a.useCallback(()=>{e.type==="text"?i({[e.id]:l}):e.type==="confirm"?i({[e.id]:r[e.id]===!0}):i(r)},[e,r,l,i]);a.useEffect(()=>{o({}),c("")},[e.id]);const d=()=>{switch(e.type){case"text":return l.trim().length>0;case"single_select":return r[e.id]!==void 0;case"multi_select":return Array.isArray(r[e.id])&&r[e.id].length>0;case"confirm":return r[e.id]!==void 0;default:return!0}};return t.jsxs("div",{className:"planning-question-form",children:[t.jsxs("div",{className:"planning-view-scroll planning-question-scroll",children:[s.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ls,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3,4,5,6].map(m=>t.jsx("div",{className:`planning-progress-step ${m<=n?"active":""}`},m))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~6"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:l,onChange:m=>c(m.target.value),onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&l.trim()&&(m.preventDefault(),u())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(m=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:m.id,checked:r[e.id]===m.id,onChange:()=>o({[e.id]:m.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(m=>{const h=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:m.id,checked:h.includes(m.id),onChange:f=>{const p=f.target.checked?[...h,m.id]:h.filter(g=>g!==m.id);o({[e.id]:p})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!0?"selected":""}`,onClick:()=>o({[e.id]:!0}),children:[t.jsx(Nn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(qt,{size:18}),"No"]})]})]})]})]})]}),t.jsx("div",{className:"planning-actions",children:t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:u,disabled:!d(),children:["Continue",t.jsx(Dr,{size:16,className:"icon-ml-4"})]})})]})}function US({summary:e,historyEntries:n,onSummaryChange:s,onApprove:i,onStartOver:r,isCreating:o}){const[l,c]=a.useState(()=>new Set(e.milestones.map((E,C)=>C))),[u,d]=a.useState(()=>{const E=new Set;return e.milestones.forEach((C,w)=>{C.slices.forEach((R,S)=>E.add(`${w}-${S}`))}),E}),m=E=>{c(C=>{const w=new Set(C);return w.has(E)?w.delete(E):w.add(E),w})},h=E=>{d(C=>{const w=new Set(C);return w.has(E)?w.delete(E):w.add(E),w})},f=(E,C)=>{const w=[...e.milestones];w[E]={...w[E],...C},s({...e,milestones:w})},p=(E,C,w)=>{const R=[...e.milestones],S=[...R[E].slices];S[C]={...S[C],...w},R[E]={...R[E],slices:S},s({...e,milestones:R})},g=(E,C,w,R)=>{const S=[...e.milestones],O=[...S[E].slices],_=[...O[C].features];_[w]={..._[w],...R},O[C]={...O[C],features:_},S[E]={...S[E],slices:O},s({...e,milestones:S})},b=E=>{const C=e.milestones.filter((w,R)=>R!==E);s({...e,milestones:C})},v=(E,C)=>{const w=[...e.milestones];w[E]={...w[E],slices:w[E].slices.filter((R,S)=>S!==C)},s({...e,milestones:w})},x=(E,C,w)=>{const R=[...e.milestones],S=[...R[E].slices];S[C]={...S[C],features:S[C].features.filter((O,_)=>_!==w)},R[E]={...R[E],slices:S},s({...e,milestones:R})},y=(E,C)=>{const w=[...e.milestones],R=[...w[E].slices];R[C]={...R[C],features:[...R[C].features,{title:"New feature",description:""}]},w[E]={...w[E],slices:R},s({...e,milestones:w})},j=e.milestones.reduce((E,C)=>E+C.slices.reduce((w,R)=>w+R.features.length,0),0);return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ls,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Nn,{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:E=>s({...e,missionTitle:E.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Mission Description"}),t.jsx("textarea",{className:"planning-textarea",rows:3,value:e.missionDescription||"",onChange:E=>s({...e,missionDescription:E.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Roadmap"}),t.jsx("div",{className:"roadmap-list",children:e.milestones.map((E,C)=>t.jsxs("div",{className:"roadmap-card",children:[t.jsxs("div",{className:"roadmap-card-header",onClick:()=>m(C),children:[l.has(C)?t.jsx(Yt,{size:16,className:"icon-text-secondary"}):t.jsx(gn,{size:16,className:"icon-text-secondary"}),t.jsx(qi,{size:16,className:"icon-milestone"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-title",value:E.title,onChange:w=>f(C,{title:w.target.value}),onClick:w=>w.stopPropagation()}),e.milestones.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:w=>{w.stopPropagation(),b(C)},title:"Remove milestone",children:t.jsx(cn,{size:14,className:"icon-text-secondary"})})]}),l.has(C)&&t.jsxs("div",{className:"roadmap-card-body",children:[t.jsx("textarea",{className:"planning-textarea roadmap-textarea-md",rows:2,placeholder:"Milestone description...",value:E.description||"",onChange:w=>f(C,{description:w.target.value})}),t.jsxs("div",{className:"roadmap-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Verification Criteria"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-sm",rows:2,placeholder:"How to confirm this milestone is complete...",value:E.verification||"",onChange:w=>f(C,{verification:w.target.value})})]}),E.slices.map((w,R)=>{const S=`${C}-${R}`;return t.jsxs("div",{className:"roadmap-slice-card",children:[t.jsxs("div",{className:"roadmap-slice-header",onClick:()=>h(S),children:[u.has(S)?t.jsx(Yt,{size:14,className:"icon-text-secondary"}):t.jsx(gn,{size:14,className:"icon-text-secondary"}),t.jsx(Oc,{size:14,className:"icon-slice"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:w.title,onChange:O=>p(C,R,{title:O.target.value}),onClick:O=>O.stopPropagation()}),E.slices.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:O=>{O.stopPropagation(),v(C,R)},title:"Remove slice",children:t.jsx(cn,{size:12,className:"icon-text-secondary"})})]}),u.has(S)&&t.jsxs("div",{className:"roadmap-slice-body",children:[t.jsxs("div",{className:"roadmap-slice-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Slice Verification"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-xs",rows:1,placeholder:"How to confirm this slice is done...",value:w.verification||"",onChange:O=>p(C,R,{verification:O.target.value})})]}),w.features.map((O,_)=>t.jsxs("div",{className:"roadmap-feature-row",children:[t.jsx(Tc,{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:O.title,onChange:P=>g(C,R,_,{title:P.target.value})}),O.description&&t.jsx("p",{className:"roadmap-feature-text",children:O.description}),O.acceptanceCriteria&&t.jsxs("p",{className:"roadmap-feature-text--italic",children:["AC: ",O.acceptanceCriteria]})]}),t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:()=>x(C,R,_),title:"Remove feature",children:t.jsx(cn,{size:12,className:"icon-text-secondary"})})]},_)),t.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>y(C,R),children:[t.jsx(dn,{size:12}),"Add Feature"]})]})]},R)})]})]},C))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:r,disabled:o,children:[t.jsx(Ra,{size:16,className:"icon-mr-4"}),"Start Over"]}),t.jsx("button",{className:"btn btn-primary",onClick:i,disabled:o||e.milestones.length===0,children:o?t.jsxs(t.Fragment,{children:[t.jsx(lt,{size:16,className:"spin icon-mr-8"}),"Creating Mission..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Nn,{size:16,className:"icon-mr-8"}),"Approve Plan"]})})]})]})}function BS({isOpen:e,onClose:n,onApplied:s,targetType:i,targetId:r,targetTitle:o,missionContext:l,projectId:c,resumeSessionId:u}){const[d,m]=a.useState({type:"initial"}),[h,f]=a.useState(null),[p,g]=a.useState([]),[b,v]=a.useState([]),[x,y]=a.useState(null),[j,E]=a.useState(""),[C,w]=a.useState(!0),[R,S]=a.useState(!1),[O,_]=a.useState(!1),P=a.useRef(null),U=a.useRef(null),G=a.useRef(null),M=a.useRef(null),[T,D]=a.useState(null),K=a.useMemo(()=>Qi(),[]);pl(e?T:null);const{activeTabMap:J,broadcastUpdate:te,broadcastCompleted:N,broadcastLock:z,broadcastUnlock:I,broadcastHeartbeat:k}=La(),H=i==="milestone"?Ek:Tk,Q=i==="milestone"?_k:Pk,ue=i==="milestone"?Mk:Ik,be=i==="milestone"?Ak:$k,V=i==="milestone"?Rk:Dk,ve=i==="milestone"?"Milestone":"Slice",B=i==="milestone"?"milestone_interview":"slice_interview",Y=a.useCallback($e=>{U.current?.close();const Ue=ue($e,c,{onThinking:oe=>{E(je=>je+oe),te({sessionId:$e,status:"generating",needsInput:!1,owningTabId:K,type:B,title:o,projectId:c??null})},onQuestion:oe=>{S(!1),X(),m({type:"question",sessionId:$e,question:oe}),E(""),te({sessionId:$e,status:"awaiting_input",needsInput:!0,owningTabId:K,type:B,title:o,projectId:c??null})},onSummary:oe=>{S(!1),X(),m({type:"summary",sessionId:$e,summary:oe}),y(oe),E(""),te({sessionId:$e,status:"complete",needsInput:!1,owningTabId:K,type:B,title:o,projectId:c??null})},onError:oe=>{const je=oe||"Session failed while contacting the AI.";S(!1),f(null),m({type:"error",sessionId:$e,errorMessage:je}),E(""),G.current=$e,te({sessionId:$e,status:"error",needsInput:!1,owningTabId:K,type:B,title:o,projectId:c??null}),N({sessionId:$e,status:"error"})},onComplete:()=>{S(!1),G.current=null,N({sessionId:$e,status:"complete"})},onConnectionStateChange:oe=>{S(oe==="reconnecting")}});U.current=Ue},[N,te,ue,B,c,K,o]),X=()=>{y(null),g([]),v([]),E("")},he=a.useCallback(async()=>{f(null),X(),S(!1),m({type:"loading"});try{const{sessionId:$e}=await H(r,c);G.current=$e,D($e),Y($e)}catch($e){S(!1),f(ke($e)||`Failed to start ${ve.toLowerCase()} interview`),m({type:"initial"}),G.current=null,D(null)}},[Y,c,H,r,ve]),de=a.useCallback(async()=>{f(null),_(!0);try{await V(r,c),s(),m({type:"applied"})}catch($e){f(ke($e)||`Failed to skip ${ve.toLowerCase()} interview`),_(!1)}},[s,c,V,r,ve]);a.useEffect(()=>{e&&d.type==="initial"&&P.current?.focus()},[e,d.type]),a.useEffect(()=>{if(!e||!u||d.type!=="initial")return;let $e=!1;return ai(u).then(Ue=>{if($e||!Ue)return;const oe=ka(Ue.conversationHistory);if(v(oe),D(Ue.id),g(oe.map(je=>je.response).filter(je=>!!(je&&typeof je=="object"&&!Array.isArray(je)))),Ue.status==="awaiting_input"&&Ue.currentQuestion)try{const je=JSON.parse(Ue.currentQuestion);G.current=Ue.id,m({type:"question",sessionId:Ue.id,question:je})}catch{f("Failed to restore session question.")}else if(Ue.status==="complete"&&Ue.result)try{const je=JSON.parse(Ue.result);G.current=Ue.id,y(je),m({type:"summary",sessionId:Ue.id,summary:je})}catch{f("Failed to restore session result.")}else Ue.status==="generating"?(G.current=Ue.id,Ue.thinkingOutput&&E(Ue.thinkingOutput),m({type:"loading"}),Y(Ue.id)):Ue.status==="error"&&(G.current=Ue.id,f(null),m({type:"error",sessionId:Ue.id,errorMessage:Ue.error??"The session encountered an error."}))}).catch(()=>{$e||f("Failed to resume session.")}),()=>{$e=!0}},[Y,e,u,d.type]),a.useEffect(()=>{e||(S(!1),D(null))},[e]),a.useEffect(()=>{if(!(!e||!T)){if(M.current!==T){M.current&&I(M.current,K),z(T,K),M.current=T;return}!T&&M.current&&(I(M.current,K),M.current=null)}},[z,I,e,T,K]),a.useEffect(()=>{if(!e||!T||M.current!==T)return;k(K);const $e=setInterval(()=>{k(K)},3e4);return()=>{clearInterval($e)}},[k,e,T,K]),a.useEffect(()=>()=>{U.current?.close(),U.current=null,M.current&&(I(M.current,K),M.current=null)},[I,K]);const me=a.useCallback(()=>{U.current?.close(),U.current=null,n()},[n]),se=a.useCallback(async()=>{U.current?.close(),U.current=null,X(),m({type:"initial"}),f(null),G.current=null,D(null),n()},[n]),_e=a.useCallback(async $e=>{if(d.type!=="question")return;const{sessionId:Ue}=d;f(null),g(oe=>[...oe,$e]),v(oe=>[...oe,{question:d.question,response:$e}]),m({type:"loading"}),E("");try{Y(Ue),await Q(Ue,$e,c,K)}catch(oe){U.current?.close(),U.current=null,f(ke(oe)||"Failed to submit response"),m({type:"question",sessionId:Ue,question:d.question})}},[Y,c,Q,K,d]),Fe=a.useCallback(async()=>{if(d.type==="summary"){f(null),_(!0);try{await be(d.sessionId,x||void 0,c),s(),m({type:"applied"})}catch($e){f(ke($e)||"Failed to apply interview results"),_(!1)}}},[be,x,s,c,d]),Te=()=>d.type==="question"?Math.min(p.length+1,6):6,st=d.type==="loading"||d.type==="question"||d.type==="summary"||d.type==="error",nt=T?J.get(T):null,Xe=!!(nt&&nt.tabId!==K&&!nt.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:$e=>$e.target===$e.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(cs,{size:20,className:"icon-triage"}),t.jsxs("h3",{children:["Plan ",ve,": ",o]})]}),t.jsxs("div",{className:"modal-header-actions",children:[st&&t.jsx("button",{className:"modal-send-to-background",onClick:me,title:"Send to background","aria-label":"Send to background",children:t.jsx(Or,{size:16})}),t.jsx("button",{className:"modal-close",onClick:se,"aria-label":"Close",children:t.jsx(qt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[h&&t.jsx("div",{className:"form-error planning-error",children:h}),R&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Xe&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),d.type==="initial"&&t.jsxs("div",{className:"planning-initial",children:[t.jsx("div",{className:"planning-view-scroll",children:t.jsxs("div",{className:"planning-intro",children:[t.jsx(cs,{size:32,className:"icon-triage-lg"}),t.jsxs("h4",{children:["Refine ",ve," scope with AI"]}),t.jsxs("p",{className:"text-muted",children:["The AI will interview you to refine the ",i,"'s scope, acceptance criteria, and verification methods. Each ",i," can have its own refined plan or inherit context from the mission level."]}),l&&t.jsxs("div",{className:"planning-context-info",children:[t.jsx("span",{className:"planning-context-label",children:"Mission context:"}),t.jsx("span",{className:"planning-context-text",children:l})]})]})}),t.jsxs("div",{className:"planning-view-footer",children:[t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>void he(),children:[t.jsx(cs,{size:16,className:"icon-mr-8"}),"Start Interview"]}),t.jsxs("button",{className:"btn planning-use-context-btn",onClick:()=>void de(),disabled:O,children:[O?t.jsx(lt,{size:16,className:"spin"}):null,"Use Mission Context"]}),t.jsx("button",{className:"btn",onClick:se,children:"Cancel"})]})]}),d.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(lt,{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:()=>w(!C),type:"button",children:C?"Hide thinking":"Show thinking"}),C&&j&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:j})})]})]}),d.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[b.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ls,{entries:b}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:d.errorMessage}),t.jsx("div",{className:"ai-error-actions",children:t.jsx("button",{className:"btn",onClick:se,children:"Cancel"})})]})]})}),d.type==="question"&&t.jsx(HS,{question:d.question,progress:Te(),historyEntries:b,onSubmit:_e}),d.type==="summary"&&x&&t.jsx(qS,{summary:x,historyEntries:b,onSummaryChange:y,onApply:Fe,onCancel:se,isApplying:O}),d.type==="applied"&&t.jsxs("div",{className:"planning-summary planning-applied",children:[t.jsx("div",{className:"planning-view-scroll",children:t.jsxs("div",{className:"planning-applied-content",children:[t.jsx(Nn,{size:48,className:"icon-success"}),t.jsxs("h4",{children:[ve," Updated"]}),t.jsxs("p",{className:"text-muted",children:["The ",i,"'s scope and verification have been ",d.type==="applied"?"applied":"updated","."]})]})}),t.jsx("div",{className:"planning-view-footer",children:t.jsx("button",{className:"btn btn-primary",onClick:s,children:"Done"})})]})]})]})}):null}function HS({question:e,progress:n,historyEntries:s,onSubmit:i}){const[r,o]=a.useState({}),[l,c]=a.useState(""),u=a.useCallback(()=>{e.type==="text"?i({[e.id]:l}):e.type==="confirm"?i({[e.id]:r[e.id]===!0}):i(r)},[e,r,l,i]);a.useEffect(()=>{o({}),c("")},[e.id]);const d=()=>{switch(e.type){case"text":return l.trim().length>0;case"single_select":return r[e.id]!==void 0;case"multi_select":return Array.isArray(r[e.id])&&r[e.id].length>0;case"confirm":return r[e.id]!==void 0;default:return!0}};return t.jsxs("div",{className:"planning-question-form",children:[t.jsxs("div",{className:"planning-view-scroll planning-question-scroll",children:[s.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ls,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3,4,5,6].map(m=>t.jsx("div",{className:`planning-progress-step ${m<=n?"active":""}`},m))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~6"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:l,onChange:m=>c(m.target.value),onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&l.trim()&&(m.preventDefault(),u())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(m=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:m.id,checked:r[e.id]===m.id,onChange:()=>o({[e.id]:m.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(m=>{const h=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:m.id,checked:h.includes(m.id),onChange:f=>{const p=f.target.checked?[...h,m.id]:h.filter(g=>g!==m.id);o({[e.id]:p})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!0?"selected":""}`,onClick:()=>o({[e.id]:!0}),children:[t.jsx(Nn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(qt,{size:18}),"No"]})]})]})]})]})]}),t.jsx("div",{className:"planning-actions",children:t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:u,disabled:!d(),children:["Continue",t.jsx(Dr,{size:16,className:"icon-ml-4"})]})})]})}function qS({summary:e,historyEntries:n,onSummaryChange:s,onApply:i,onCancel:r,isApplying:o}){const[l,c]=a.useState(e),[u,d]=a.useState(!0),m=(h,f)=>{const p={...l,[h]:f};c(p),s(p)};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ls,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-panel",children:[t.jsx("div",{className:"planning-summary-header",children:t.jsxs("button",{className:"planning-summary-toggle",onClick:()=>d(!u),"aria-expanded":u,children:[u?t.jsx(Yt,{size:16}):t.jsx(gn,{size:16}),t.jsx("span",{children:"Refined Scope"})]})}),u&&t.jsxs("div",{className:"planning-summary-content",children:[l.description&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:l.description,onChange:h=>m("description",h.target.value)})]}),l.planningNotes&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Planning Notes"}),t.jsx("textarea",{rows:3,value:l.planningNotes,onChange:h=>m("planningNotes",h.target.value)})]}),l.verification&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Verification Criteria"}),t.jsx("textarea",{rows:2,value:l.verification,onChange:h=>m("verification",h.target.value)})]}),!l.description&&!l.planningNotes&&!l.verification&&t.jsx("p",{className:"text-muted planning-summary-empty",children:"No additional details were generated for this item."})]})]})]}),t.jsxs("div",{className:"planning-view-footer",children:[t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:i,disabled:o,children:[o?t.jsx(lt,{size:16,className:"spin"}):null,"Apply"]}),t.jsx("button",{className:"btn",onClick:r,disabled:o,children:"Cancel"})]})]})}const Ja={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)"}},bm={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)"}},xm={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)"}},co={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)"}},uo={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)"}},mo={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)"}},vm={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)"}},VS=3;function WS(e){return e==="completed"?"planned":e==="needs_update"?"needs_update":"not_started"}function ym({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 wm(e){return e?e.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const Fl={title:"",description:"",status:"planning",autopilotEnabled:!1},Ul={title:"",description:"",status:"planning",dependencies:[]},Bl={title:"",description:"",status:"pending"},Hl={title:"",description:"",acceptanceCriteria:"",status:"defined"},KS=3600*1e3;function Vo(e){if(!e)return"—";const n=new Date(e).getTime();if(Number.isNaN(n))return"—";const s=Date.now()-n;if(s<0)return"just now";const i=Math.floor(s/(60*1e3));if(i<1)return"just now";if(i<60)return`${i}m ago`;const r=Math.floor(i/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function GS(e){if(!e)return"healthy";const n=typeof e.lastErrorAt=="string"&&Date.now()-new Date(e.lastErrorAt).getTime()<=KS,s=e.totalTasks>0&&e.tasksFailed>e.totalTasks*.3;return n||s?"error":e.tasksFailed>0?"warning":e.tasksFailed===0&&e.tasksInFlight<=e.totalTasks?"healthy":"warning"}function JS(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 YS(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 ql(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 xf=["feature_triaged","feature_completed"],vf=["slice_activated","slice_completed","milestone_completed"],yf=["mission_started","mission_paused","mission_resumed","mission_completed"],wf=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function jm(e,n){switch(n){case"errors":return e==="error"||e==="warning";case"state_changes":return yf.includes(e);case"tasks":return xf.includes(e);case"slices":return vf.includes(e);case"autopilot":return wf.includes(e);default:return!0}}function QS(e){return e==="error"||e==="warning"?"mission-event__type--error":yf.includes(e)?"mission-event__type--state":xf.includes(e)?"mission-event__type--task":vf.includes(e)?"mission-event__type--slice":wf.includes(e)?"mission-event__type--autopilot":"mission-event__type--default"}function XS(e){return e.replace(/_/g," ")}function ZS(e,n){return n?e==="watching"?`Watching since ${Vo(n)}`:`Last activation ${Vo(n)}`:null}function e0({isOpen:e,isInline:n=!1,onClose:s,addToast:i,projectId:r,onSelectTask:o,availableTasks:l=[],resumeSessionId:c,targetMissionId:u,milestoneSliceResumeSessionId:d,onMilestoneSliceResumeFetchError:m}){const h=n||e,[f,p]=a.useState([]),[g,b]=a.useState(null),[v,x]=a.useState(!0),[y,j]=a.useState(!1),[E,C]=a.useState(!1),[w,R]=a.useState(null),[S,O]=a.useState(Fl),[_,P]=a.useState(!1),[U,G]=a.useState(new Set),[M,T]=a.useState(new Set),[D,K]=a.useState(null),[J,te]=a.useState(Ul),[N,z]=a.useState(!1),[I,k]=a.useState(null),[H,Q]=a.useState(Bl),[ue,be]=a.useState(!1),[V,ve]=a.useState(null),[B,Y]=a.useState(null),[X,he]=a.useState(Hl),[de,me]=a.useState(!1),[se,_e]=a.useState(null),[Fe,Te]=a.useState(null),[st,nt]=a.useState(""),[qe,Xe]=a.useState(!1),[$e,Ue]=a.useState([]),[oe,je]=a.useState(void 0),ie=oe??c,[Ae,Le]=a.useState(null),[we,Ee]=a.useState(null),[Ve,rt]=a.useState(null);a.useEffect(()=>{h&&ie&&Xe(!0)},[h,ie]),a.useEffect(()=>{if(!h||ie)return;let q=!1;return jd(r).then(Ce=>{if(q)return;const De=Ce.filter(xt=>xt.type==="mission_interview"&&(xt.status==="awaiting_input"||xt.status==="error"));Ue(De)}).catch(Ce=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",Ce)}),()=>{q=!0}},[h,r,ie]),a.useEffect(()=>{if(!h||!d)return;let q=!1;return ai(d).then(Ce=>{if(!(q||!Ce))try{const De=JSON.parse(Ce.inputPayload||"{}");De.targetId&&De.targetType&&Le({type:De.targetType,id:De.targetId,title:De.targetTitle||Ce.title,resumeSessionId:d})}catch{Le({type:"milestone",id:"",title:Ce.title,resumeSessionId:d})}}).catch(Ce=>{q||(console.warn("[MissionManager] Failed to fetch session for milestone/slice resume:",Ce),m?.())}),()=>{q=!0}},[h,d,m]);const[xe,ce]=a.useState(null),[Pe,pe]=a.useState(new Map),[Re,Qe]=a.useState(null),[Ie,bt]=a.useState({title:"",assertion:"",status:"pending"}),[ee,re]=a.useState(!1),[Se,ot]=a.useState(null),[ne,Ze]=a.useState(new Map),[ft,gt]=a.useState(new Set),[St,Nt]=a.useState(new Set),[pt,kt]=a.useState(null),[Ht,$t]=a.useState(new Map),[Tt,Mt]=a.useState(null),[Ot,zt]=a.useState(null),[Ft,Et]=a.useState(!0),[Pt,Dt]=a.useState(new Set),[Wt,It]=a.useState(new Map),[Rt,fe]=a.useState(null),[Oe,ut]=a.useState(new Map),[L,F]=a.useState(null),[ge,ze]=a.useState(new Map),[Be,Ke]=a.useState(new Map),[dt,Xt]=a.useState("structure"),[Cn,pn]=a.useState([]),Kn=a.useRef([]),Lt=a.useRef([]),Zt=a.useRef(null),Ne=a.useRef(null),et=a.useRef("structure"),ln=a.useRef("all"),[wn,Gn]=a.useState(!1),[Tn,Un]=a.useState(0),[sn,un]=a.useState("all"),[Bn,Sn]=a.useState(new Set),an=a.useRef(null),Dn=a.useRef(null);Lt.current=f,Zt.current=g,Ne.current=Tt,et.current=dt,ln.current=sn;const Ln=a.useCallback((q="auto")=>{const Ce=Dn.current;if(Ce&&typeof Ce.scrollIntoView=="function"){Ce.scrollIntoView({block:"end",behavior:q});return}const De=an.current;De&&(De.scrollTop=De.scrollHeight)},[]),ss=a.useCallback(()=>{const q=an.current;return q?q.scrollHeight-q.scrollTop-q.clientHeight<=100:!0},[]),Pn=a.useCallback(async q=>{if(q.length===0){Ke(new Map);return}const Ce=await Jj(r);Ke(De=>{const xt=new Map(De);for(const[vn,_t]of Object.entries(Ce))JS(_t)&&xt.set(vn,_t);return xt})},[r]),nn=a.useCallback(async()=>{try{x(!0);const q=await qj(r);p(q),Pn(q)}catch(q){i(ke(q)||"Failed to load missions","error")}finally{x(!1)}},[i,r,Pn]),vt=a.useCallback(async q=>{try{j(!0);const Ce=await qp(q,r);if(b(Ce),Ce.milestones.length>0){const De=Ce.milestones[0].id;Mt(De),Et(!0),G(new Set([De])),_l(De,r).then(xt=>{pe(vn=>{const _t=new Map(vn);return _t.set(De,xt),_t})}).catch(()=>{}),Ml(De,r).then(xt=>{$t(vn=>{const _t=new Map(vn);return _t.set(De,xt),_t})}).catch(()=>{}),Ce.milestones[0].slices.length>0&&T(new Set([Ce.milestones[0].slices[0].id]))}else Mt(null),zt(null)}catch(Ce){i(ke(Ce)||"Failed to load mission details","error")}finally{j(!1)}},[i,r]);a.useEffect(()=>{if(!h||!Tt){zt(null);return}let q=!1;return zt(null),ju(Tt,r).then(Ce=>{if(!q){if(!ql(Ce)){zt(null);return}zt(Ce),$t(De=>{const xt=new Map(De);return xt.set(Tt,Ce.rollup),xt})}}).catch(()=>{q||zt(null)}),()=>{q=!0}},[h,Tt,r]),a.useEffect(()=>{Et(!0)},[Tt]);const rn=a.useCallback(q=>{!q||q!==Ne.current||ju(q,r).then(Ce=>{Ne.current!==q||!ql(Ce)||(zt(Ce),$t(De=>{const xt=new Map(De);return xt.set(q,Ce.rollup),xt}))}).catch(()=>{})},[r]),A=a.useCallback(async(q,Ce)=>{const De=Ce?.append??!1,xt=De?Kn.current.length:0;De||(Gn(!0),Sn(new Set));try{const vn=await Gj(q,{limit:50,offset:xt,eventType:void 0},r),_t=vn.events.filter(Gt=>jm(Gt.eventType,sn));pn(Gt=>{if(!De)return _t;const He=new Set(Gt.map(yt=>yt.id)),We=[...Gt];for(const yt of _t)He.has(yt.id)||We.push(yt);return We}),Un(vn.total),De||requestAnimationFrame(()=>{Ln("auto")})}catch(vn){i(ke(vn)||"Failed to load mission activity","error")}finally{De||Gn(!1)}},[i,sn,r,Ln]);a.useEffect(()=>{Kn.current=Cn},[Cn]),a.useEffect(()=>{h&&(nn(),b(null),Mt(null),zt(null),pn([]),Un(0),Xt("structure"),un("all"),Sn(new Set))},[h,nn]);const le=a.useRef(null);a.useEffect(()=>{h&&u&&le.current!==u&&f.length>0&&(le.current=u,vt(u))},[h,u,f,vt]),a.useEffect(()=>{h||(le.current=null)},[h]),a.useEffect(()=>{!h||!g||dt!=="activity"||A(g.id)},[dt,h,A,g,sn]),a.useEffect(()=>{if(!h||typeof EventSource>"u")return;const q=new URLSearchParams;r&&q.set("projectId",r);const Ce=`/api/events${q.size>0?`?${q.toString()}`:""}`,De=()=>{Pn(Lt.current)},xt=as=>{De();const An=as;if(An.data)try{const Vt=JSON.parse(An.data);Vt?.id&&p(Ii=>Ii.map(Ts=>Ts.id===Vt.id?{...Ts,...Vt}:Ts))}catch{}Zt.current&&vt(Zt.current.id)},vn=as=>{De(),Zt.current&&vt(Zt.current.id)},_t=()=>{De(),Zt.current&&vt(Zt.current.id)},Gt=as=>{De(),Zt.current&&vt(Zt.current.id)},He=as=>{const An=as;if(An.data)try{const Vt=JSON.parse(An.data);Vt&&Vt.featureId&&(Qs(Vt.featureId),mi(Vt.featureId),Vt.milestoneId&&rn(Vt.milestoneId))}catch{}},We=as=>{const An=as;if(An.data)try{const Vt=JSON.parse(An.data);Vt&&Vt.featureId&&(Qs(Vt.featureId),mi(Vt.featureId),Vt.milestoneId&&rn(Vt.milestoneId),Zt.current&&vt(Zt.current.id))}catch{}},yt=as=>{const An=as;if(An.data)try{const Vt=JSON.parse(An.data);Vt&&Vt.milestoneId&&(Xn(Vt.milestoneId),rn(Vt.milestoneId))}catch{}},jn=as=>{const An=as;if(An.data)try{const Vt=JSON.parse(An.data);Vt&&Vt.milestoneId&&($n(Vt.milestoneId),Xn(Vt.milestoneId),rn(Vt.milestoneId))}catch{}};return Js(Ce,{events:{"mission:updated":xt,"slice:updated":vn,"feature:updated":_t,"milestone:updated":Gt,"mission:event":as=>{De();const An=Zt.current;if(!An||et.current!=="activity")return;const Vt=ss(),Ii=as;if(Ii.data)try{const Ts=JSON.parse(Ii.data);if(!YS(Ts)||Ts.missionId!==An.id||!jm(Ts.eventType,ln.current))return;pn(pi=>{const kl=pi.filter(Nl=>Nl.id!==Ts.id);return[Ts,...kl].slice(0,100)}),Un(pi=>pi+1),Vt&&requestAnimationFrame(()=>{const pi=an.current;pi&&(pi.scrollTop=0)})}catch{}},"validator-run:started":He,"validator-run:completed":We,"milestone:validation:updated":yt,"assertion:created":jn,"assertion:updated":jn,"assertion:deleted":jn,"assertion:linked":jn,"assertion:unlinked":jn,"fix-feature:created":as=>{const An=as;if(An.data)try{const Vt=JSON.parse(An.data);if(Vt&&Vt.sourceFeatureId){Qs(Vt.sourceFeatureId);const Ii=Vt?.feature?.sliceId,Ts=Zt.current;if(Ii&&Ts){const pi=Ts.milestones.find(kl=>kl.slices.some(Nl=>Nl.id===Ii));pi&&rn(pi.id)}Zt.current&&vt(Zt.current.id)}}catch{}}}})},[h,ss,vt,Pn,r,rn]);const ye=a.useCallback(()=>{C(!0),R(null),O(Fl)},[]),Ye=a.useCallback(q=>{R(q.id),C(!1),O({title:q.title,description:q.description||"",status:q.status,autopilotEnabled:q.autopilotEnabled??!1})},[]),mt=a.useCallback(()=>{R(null),C(!1),O(Fl)},[]),ht=a.useCallback(async()=>{if(!S.title.trim()){i("Mission title is required","error");return}try{if(P(!0),E)await Vj({title:S.title.trim(),description:S.description.trim()||void 0,autopilotEnabled:S.autopilotEnabled},r),i("Mission created","success");else if(w){const q={title:S.title.trim(),description:S.description.trim()||void 0,status:S.status,autopilotEnabled:S.autopilotEnabled};S.autopilotEnabled&&(q.autoAdvance=!0),await Wj(w,q,r),i("Mission updated","success"),g?.id===w&&await vt(w)}await nn(),mt()}catch(q){i(ke(q)||"Failed to save mission","error")}finally{P(!1)}},[S,E,w,i,nn,vt,g,mt,r]),Kt=a.useCallback(async q=>{try{await Kj(q,r),i("Mission deleted","success"),g?.id===q&&b(null),await nn(),ce(null)}catch(Ce){i(ke(Ce)||"Failed to delete mission","error")}},[i,nn,g,r]),Jt=a.useCallback(()=>{z(!0),K(null),te(Ul)},[]),zn=a.useCallback(q=>{K(q.id),z(!1),te({title:q.title,description:q.description||"",status:q.status,dependencies:q.dependencies})},[]),Hn=a.useCallback(()=>{K(null),z(!1),te(Ul)},[]),zs=a.useCallback(async()=>{if(!J.title.trim()){i("Milestone title is required","error");return}try{P(!0),N&&g?(await Yj(g.id,{title:J.title.trim(),description:J.description.trim()||void 0,dependencies:J.dependencies},r),i("Milestone created","success")):D&&(await Qj(D,{title:J.title.trim(),description:J.description.trim()||void 0,status:J.status,dependencies:J.dependencies},r),i("Milestone updated","success")),await vt(g.id),Hn()}catch(q){i(ke(q)||"Failed to save milestone","error")}finally{P(!1)}},[J,N,D,g,i,vt,Hn,S.title,r]),ae=a.useCallback(async q=>{try{await Xj(q,r),i("Milestone deleted","success"),await vt(g.id),ce(null)}catch(Ce){i(ke(Ce)||"Failed to delete milestone","error")}},[i,vt,g,r]),Me=a.useCallback(q=>{Mt(q),Et(!0),G(Ce=>{const De=new Set(Ce);return!De.has(q)?(De.add(q),_l(q,r).then(vn=>{pe(_t=>{const Gt=new Map(_t);return Gt.set(q,vn),Gt})}).catch(()=>{}),Ml(q,r).then(vn=>{$t(_t=>{const Gt=new Map(_t);return Gt.set(q,vn),Gt})}).catch(()=>{})):De.delete(q),De})},[r]),it=a.useCallback(q=>{ve(q),be(!0),k(null),Q(Bl)},[]),wt=a.useCallback(q=>{k(q.id),be(!1),Q({title:q.title,description:q.description||"",status:q.status})},[]),jt=a.useCallback(()=>{k(null),be(!1),ve(null),Q(Bl)},[]),fn=a.useCallback(async()=>{if(!H.title.trim()){i("Slice title is required","error");return}try{P(!0),ue&&V?(await Zj(V,{title:H.title.trim(),description:H.description.trim()||void 0},r),i("Slice created","success")):I&&(await ek(I,{title:H.title.trim(),description:H.description.trim()||void 0,status:H.status},r),i("Slice updated","success")),await vt(g.id),jt()}catch(q){i(ke(q)||"Failed to save slice","error")}finally{P(!1)}},[H,ue,I,V,g,i,vt,jt,r]),mn=a.useCallback(async q=>{try{await tk(q,r),i("Slice deleted","success"),await vt(g.id),ce(null)}catch(Ce){i(ke(Ce)||"Failed to delete slice","error")}},[i,vt,g,r]),en=a.useCallback(async q=>{try{await nk(q,r),i("Slice activated","success"),await vt(g.id)}catch(Ce){i(ke(Ce)||"Failed to activate slice","error")}},[i,vt,g,r]),on=a.useCallback(q=>{T(Ce=>{const De=new Set(Ce);return De.has(q)?De.delete(q):De.add(q),De})},[]),xn=a.useCallback(q=>{_e(q),me(!0),Y(null),he(Hl)},[]),qn=a.useCallback(q=>{Y(q.id),me(!1),he({title:q.title,description:q.description||"",acceptanceCriteria:q.acceptanceCriteria||"",status:q.status})},[]),On=a.useCallback(()=>{Y(null),me(!1),_e(null),he(Hl)},[]),tt=a.useCallback(async()=>{if(!X.title.trim()){i("Feature title is required","error");return}try{P(!0),de&&se?(await sk(se,{title:X.title.trim(),description:X.description.trim()||void 0,acceptanceCriteria:X.acceptanceCriteria.trim()||void 0},r),i("Feature created","success")):B&&(await ik(B,{title:X.title.trim(),description:X.description.trim()||void 0,acceptanceCriteria:X.acceptanceCriteria.trim()||void 0,status:X.status},r),i("Feature updated","success")),await vt(g.id),On()}catch(q){i(ke(q)||"Failed to save feature","error")}finally{P(!1)}},[X,de,B,se,g,i,vt,On,r]),At=a.useCallback(async q=>{try{await ak(q,r),i("Feature deleted","success"),await vt(g.id),ce(null)}catch(Ce){i(ke(Ce)||"Failed to delete feature","error")}},[i,vt,g,r]),Mn=a.useCallback(async()=>{if(!Fe||!st.trim()){i("Task ID is required","error");return}try{await rk(Fe,st.trim(),r),i("Feature linked to task","success"),await vt(g.id),Te(null),nt("")}catch(q){i(ke(q)||"Failed to link feature to task","error")}},[Fe,st,i,vt,g,r]),xs=a.useCallback(async q=>{try{await ok(q,r),i("Feature unlinked from task","success"),await vt(g.id)}catch(Ce){i(ke(Ce)||"Failed to unlink feature","error")}},[i,vt,g,r]),In=a.useCallback(async q=>{try{P(!0),await lk(q,void 0,void 0,r),i("Feature triaged — task created","success"),await vt(g.id)}catch(Ce){i(ke(Ce)||"Failed to triage feature","error")}finally{P(!1)}},[i,vt,g,r]),Qn=a.useCallback(async q=>{rt(q);try{const Ce=await Lk(q,r);Ee({featureId:q,enrichedDescription:Ce.description})}catch{await In(q)}finally{rt(null)}},[In,r]),vs=a.useCallback(async()=>{we&&(Ee(null),await In(we.featureId))},[In,we]),Os=a.useCallback(()=>{Ee(null)},[]),ys=a.useCallback(async q=>{try{P(!0);const Ce=await ck(q,r);i(`Triaged ${Ce.count} feature${Ce.count!==1?"s":""}`,"success"),await vt(g.id)}catch(Ce){i(ke(Ce)||"Failed to triage slice features","error")}finally{P(!1)}},[i,vt,g,r]),$n=a.useCallback(async q=>{try{const Ce=await _l(q,r);pe(De=>{const xt=new Map(De);return xt.set(q,Ce),xt})}catch{}},[r]),Xn=a.useCallback(async q=>{try{const Ce=await Ml(q,r);$t(De=>{const xt=new Map(De);return xt.set(q,Ce),xt})}catch{}},[r]),Fs=a.useCallback(async q=>{if(!Ie.title.trim()||!Ie.assertion.trim()){i("Title and assertion text are required","error");return}try{P(!0),await dk(q,{title:Ie.title.trim(),assertion:Ie.assertion.trim(),status:Ie.status},r),i("Assertion created","success"),await $n(q),await Xn(q),re(!1),bt({title:"",assertion:"",status:"pending"})}catch(Ce){i(ke(Ce)||"Failed to create assertion","error")}finally{P(!1)}},[Ie,i,$n,Xn,r]),Ri=a.useCallback(q=>{Qe(q.id),bt({title:q.title,assertion:q.assertion,status:q.status})},[]),Ti=a.useCallback(()=>{Qe(null),re(!1),bt({title:"",assertion:"",status:"pending"})},[]),Gr=a.useCallback(async(q,Ce)=>{if(!Ie.title.trim()||!Ie.assertion.trim()){i("Title and assertion text are required","error");return}try{P(!0),await uk(q,{title:Ie.title.trim(),assertion:Ie.assertion.trim(),status:Ie.status},r),i("Assertion updated","success"),await $n(Ce),await Xn(Ce),Ti()}catch(De){i(ke(De)||"Failed to update assertion","error")}finally{P(!1)}},[Ie,i,$n,Xn,Ti,r]),Ys=a.useCallback(async q=>{try{const Ce=await pk(q,r);Ze(De=>{const xt=new Map(De);return xt.set(q,Ce),xt})}catch{}},[r]),yi=a.useCallback(async q=>{const Ce=Se!==q;ot(De=>De===q?null:q),Ce&&await Ys(q)},[Se,Ys]),Zi=a.useCallback(q=>{ot(q),Ys(q),requestAnimationFrame(()=>{const Ce=document.querySelector(`[data-mission-assertion-id="${q}"]`);Ce instanceof HTMLElement&&typeof Ce.scrollIntoView=="function"&&Ce.scrollIntoView({behavior:"smooth",block:"center"})})},[Ys]),yl=a.useCallback(async(q,Ce)=>{try{gt(De=>new Set(De).add(Ce)),await mk(q,Ce,r),i("Feature linked to assertion","success"),await Ys(Ce),kt(null)}catch(De){i(ke(De)||"Failed to link feature","error")}finally{gt(De=>{const xt=new Set(De);return xt.delete(Ce),xt})}},[i,Ys,r]),wl=a.useCallback(async(q,Ce)=>{const De=`${q}-${Ce}`;try{Nt(xt=>new Set(xt).add(De)),await hk(q,Ce,r),i("Feature unlinked from assertion","success"),await Ys(Ce)}catch(xt){i(ke(xt)||"Failed to unlink feature","error")}finally{Nt(xt=>{const vn=new Set(xt);return vn.delete(De),vn})}},[i,Ys,r]),Jr=a.useCallback(async q=>{try{Dt(De=>new Set(De).add(q)),await fk(q,r),i("Validation triggered","success");const Ce=await ku(q,r);It(De=>{const xt=new Map(De);return xt.set(q,Ce),xt})}catch(Ce){i(ke(Ce)||"Failed to trigger validation","error")}finally{Dt(Ce=>{const De=new Set(Ce);return De.delete(q),De})}},[i,r]),Qs=a.useCallback(async q=>{try{const Ce=await ku(q,r);It(De=>{const xt=new Map(De);return xt.set(q,Ce),xt})}catch{}},[r]),mi=a.useCallback(async q=>{try{const Ce=await gk(q,{limit:10},r);ut(De=>{const xt=new Map(De);return xt.set(q,Ce),xt})}catch{}},[r]),ea=a.useCallback(q=>{const Ce=Zt.current;if(Ce){for(const De of Ce.milestones)for(const xt of De.slices)if(xt.features.find(_t=>_t.id===q)){G(_t=>{const Gt=new Set(_t);return Gt.add(De.id),Gt}),T(_t=>{const Gt=new Set(_t);return Gt.add(xt.id),Gt}),fe(q),Mt(De.id),Qs(q),mi(q),requestAnimationFrame(()=>{const _t=document.querySelector(`[data-mission-feature-id="${q}"]`);_t instanceof HTMLElement&&typeof _t.scrollIntoView=="function"&&_t.scrollIntoView({behavior:"smooth",block:"center"})});return}}},[Qs,mi]),Yr=a.useCallback(async q=>{try{const Ce=await bk(q,r);ze(De=>{const xt=new Map(De);return xt.set(q,Ce),xt})}catch{}},[r]),Qr=a.useCallback(async q=>{Rt===q?fe(null):(fe(q),await Qs(q),await mi(q))},[Rt,Qs,mi]),is=a.useCallback(async q=>{L===q?F(null):(F(q),await Yr(q))},[L,Yr]),ta=a.useCallback(async q=>{try{await xk(q,r),i("Mission resumed","success"),await vt(q),nn()}catch(Ce){i(ke(Ce)||"Failed to resume mission","error")}},[i,vt,nn,r]),ms=a.useCallback(async q=>{try{const De=(await vk(q,r)).pausedTaskIds?.length??0;i(`Mission stopped (${De} task${De!==1?"s":""} paused)`,"success"),await vt(q),nn()}catch(Ce){i(ke(Ce)||"Failed to stop mission","error")}},[i,vt,nn,r]),Fa=a.useCallback(async q=>{try{await yk(q,r),i("Mission started — first slice activated","success"),await vt(q),nn()}catch(Ce){i(ke(Ce)||"Failed to start mission","error")}},[i,vt,nn,r]),Xr=a.useCallback(async(q,Ce)=>{try{await wk(q,{enabled:Ce},r),i(Ce?"Autopilot enabled":"Autopilot disabled","success"),await vt(q),nn()}catch(De){i(ke(De)||"Failed to update autopilot","error")}},[i,vt,nn,r]),Ua=a.useCallback(q=>{Xt("structure"),Mt(null),zt(null),pn([]),Un(0),un("all"),Sn(new Set),vt(q.id)},[vt]),na=a.useCallback(()=>{b(null),Mt(null),zt(null),Xt("structure"),pn([]),Un(0),un("all"),Sn(new Set),nn()},[nn]),Ba=Cn.length<Tn,hi=g?.autopilotState??"inactive",Z=hi==="watching"||hi==="activating",Ge=ZS(hi,g?.lastAutopilotActivityAt),ct=a.useMemo(()=>!Ot||!Tt||!ql(Ot)?null:Ot.rollup.milestoneId===Tt?Ot:null,[Tt,Ot]),Ut=a.useMemo(()=>{const q=new Map;for(const Ce of ct?.validationTelemetry.validationRounds??[]){const De=q.get(Ce.featureId);(!De||Ce.startedAt>De.startedAt)&&q.set(Ce.featureId,Ce)}return q},[ct]),Xs=a.useCallback(()=>{!g||wn||!Ba||A(g.id,{append:!0})},[wn,Ba,A,g]),Us=a.useCallback(q=>{Sn(Ce=>{const De=new Set(Ce);return De.has(q)?De.delete(q):De.add(q),De})},[]),Ha=a.useCallback(q=>{q.key==="Enter"&&!q.shiftKey&&(q.preventDefault(),ht())},[ht]),qa=a.useCallback(q=>{q.key==="Enter"&&!q.shiftKey&&(q.preventDefault(),zs())},[zs]),Zr=a.useCallback(q=>{q.key==="Enter"&&!q.shiftKey&&(q.preventDefault(),fn())},[fn]),eo=a.useCallback(q=>{q.key==="Enter"&&!q.shiftKey&&(q.preventDefault(),tt())},[tt]),jl=a.useRef(null);if(a.useEffect(()=>{if(!h)return;const q=Ce=>{Ce.key==="Escape"&&s()};return document.addEventListener("keydown",q),()=>document.removeEventListener("keydown",q)},[h,s]),!h)return null;const to=t.jsxs("div",{ref:jl,className:`mission-manager${n?" mission-manager--inline":""}`,role:n?void 0:"dialog","aria-modal":n?void 0:!0,"aria-label":n?void 0:"Mission Manager","data-testid":"mission-manager-dialog",children:[t.jsxs("div",{className:`mission-manager__header${n?" mission-manager__header--inline":""}`,children:[t.jsxs("div",{className:"mission-manager__header-title",children:[g?t.jsx("button",{className:"mission-manager__back-btn",onClick:na,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:t.jsx(el,{size:18})}):null,t.jsx(ks,{size:18,className:"mission-manager__header-icon"}),t.jsx("h2",{className:"mission-manager__title",children:g?g.title:"Missions"})]}),!n&&t.jsx("button",{className:"modal-close",onClick:s,title:"Close","aria-label":"Close Mission Manager","data-testid":"mission-close-btn",children:t.jsx(qt,{size:18})})]}),t.jsx("div",{className:"mission-manager__body",children:v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(lt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(lt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):g?t.jsxs("div",{className:"mission-detail",children:[t.jsxs("div",{className:"mission-detail__header",children:[t.jsxs("div",{className:"mission-detail__title-row",children:[t.jsxs("div",{className:"mission-detail__title-text",children:[Z&&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:(Ja[g.status]||Ja.planning).bg,color:(Ja[g.status]||Ja.planning).text},children:g.status})]}),g.description&&t.jsx("p",{className:"mission-detail__description",children:g.description}),t.jsx("div",{className:"mission-detail__meta",children:t.jsxs("span",{className:"mission-detail__meta-info",children:[g.milestones.length," milestones"]})}),t.jsxs("div",{className:"mission-detail__autopilot",children:[t.jsxs("div",{className:"mission-detail__autopilot-toggle",children:[t.jsxs("label",{className:"mission-toggle","data-testid":"mission-autopilot-toggle",children:[t.jsx("input",{type:"checkbox",checked:g.autopilotEnabled??!1,onChange:q=>Xr(g.id,q.target.checked),"aria-label":"Autopilot"}),t.jsx("span",{className:"mission-toggle__track","aria-hidden":"true",children:t.jsx("span",{className:"mission-toggle__thumb"})}),t.jsxs("span",{className:"mission-toggle__label",children:[t.jsx(es,{size:14,className:"mission-detail__autopilot-icon"}),"Autopilot"]})]}),t.jsxs("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(uo[hi]||uo.inactive).bg,color:(uo[hi]||uo.inactive).text},"data-testid":"autopilot-state-badge",children:[Z&&t.jsx("span",{className:"mission-detail__autopilot-pulse"}),hi]})]}),Ge&&t.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:Ge})]}),t.jsxs("div",{className:"mission-detail__actions",children:[g.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ms(g.id),title:"Stop mission","aria-label":"Stop mission",children:t.jsx(Cs,{size:14})}),g.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>ta(g.id),title:"Resume mission","aria-label":"Resume mission",children:t.jsx(_n,{size:14})}),g.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Fa(g.id),title:"Start mission","aria-label":"Start mission",children:t.jsx(_n,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ye(g),title:"Edit mission","aria-label":"Edit mission",children:t.jsx(hs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ce({type:"mission",id:g.id}),title:"Delete mission","aria-label":"Delete mission",children:t.jsx(cn,{size:14})})]})]}),w===g.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:S.title,onChange:q=>O({...S,title:q.target.value}),onKeyDown:Ha,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:S.description,onChange:q=>O({...S,description:q.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:S.status,onChange:q=>O({...S,status:q.target.value}),children:[t.jsx("option",{value:"planning",children:"Planning"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"blocked",children:"Blocked"}),t.jsx("option",{value:"complete",children:"Complete"}),t.jsx("option",{value:"archived",children:"Archived"})]}),t.jsxs("label",{className:"mission-checkbox",children:[t.jsx("input",{type:"checkbox",checked:S.autopilotEnabled,onChange:q=>O({...S,autopilotEnabled:q.target.checked})}),t.jsx(es,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:ht,disabled:_,children:[_?t.jsx(lt,{size:14,className:"spinner"}):t.jsx(Jn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:mt,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-detail__tabs",role:"tablist","aria-label":"Mission detail tabs",children:[t.jsx("button",{className:`mission-btn ${dt==="structure"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Xt("structure"),role:"tab","aria-selected":dt==="structure","data-testid":"mission-tab-structure",children:"Structure"}),t.jsxs("button",{className:`mission-btn ${dt==="activity"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Xt("activity"),role:"tab","aria-selected":dt==="activity","data-testid":"mission-tab-activity",children:["Activity (",Tn,")"]})]}),dt==="structure"?t.jsxs("div",{className:"mission-detail__milestones",children:[g.milestones.map(q=>{const Ce=ct?.rollup.milestoneId===q.id?ct:null,De=Ce?.rollup??Ht.get(q.id),xt=Ce?.validationTelemetry.validationRounds??[],vn=Ce?.fixFeatures??[],_t=vm[De?.state??"not_started"]??vm.not_started,Gt=De&&(De.state==="blocked"||De.state==="failed")?Ce?.validationTelemetry.validationRounds.find(He=>He.blockedReason)?.blockedReason:void 0;return t.jsxs("div",{className:"mission-milestone",children:[t.jsxs("div",{className:"mission-milestone__header",onClick:()=>Me(q.id),children:[t.jsx("button",{className:"mission-milestone__expand",children:U.has(q.id)?t.jsx(Yt,{size:16}):t.jsx(gn,{size:16})}),t.jsx(qi,{size:16,className:"mission-milestone__icon"}),t.jsx("span",{className:"mission-milestone__title",children:q.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:bm[q.status].bg,color:bm[q.status].text},children:q.status}),t.jsxs("span",{className:"mission-milestone__count",children:[q.slices.length," slices"]}),t.jsx(ym,{state:WS(q.interviewState)}),De&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:_t.bg,color:_t.text},title:"Validation state",children:wm(De.state)}),De.totalAssertions>0&&t.jsx("div",{className:"mission-milestone__coverage-bar",title:`${De.passedAssertions??0} of ${De.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-milestone__coverage-bar-fill",style:{width:`${(De.passedAssertions??0)/De.totalAssertions*100}%`,backgroundColor:(De.passedAssertions??0)===De.totalAssertions?"var(--color-success)":"var(--color-warning)"}})})]}),q.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Le({type:"milestone",id:q.id,title:q.title}),title:"Plan milestone","aria-label":"Plan milestone",children:t.jsx(Hi,{size:14})}),t.jsxs("div",{className:"mission-milestone__actions",onClick:He=>He.stopPropagation(),children:[t.jsx("button",{className:"mission-icon-btn",onClick:()=>it(q.id),title:"Add slice",children:t.jsx(dn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>zn(q),title:"Edit milestone",children:t.jsx(hs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ce({type:"milestone",id:q.id}),title:"Delete milestone",children:t.jsx(cn,{size:14})})]})]}),U.has(q.id)&&t.jsxs("div",{className:"mission-milestone__body",children:[(N||D===q.id)&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:J.title,onChange:He=>te({...J,title:He.target.value}),onKeyDown:qa,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:J.description,onChange:He=>te({...J,description:He.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:zs,disabled:_,children:[_?t.jsx(lt,{size:14,className:"spinner"}):t.jsx(Jn,{size:14}),D?"Update":"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Hn,children:"Cancel"})]})]}),Ce&&t.jsxs("div",{className:"mission-validation-telemetry",children:[t.jsxs("div",{className:"mission-validation-telemetry__header",children:[t.jsx("span",{className:"mission-validation-telemetry__title",children:"Validation Telemetry"}),t.jsxs("span",{className:"mission-validation-telemetry__meta",children:[Ce.validationTelemetry.totalRuns," rounds",Ce.validationTelemetry.lastValidatorStatus?` · Last ${Ce.validationTelemetry.lastValidatorStatus}`:""]})]}),Gt&&t.jsxs("div",{className:"mission-blocked-reason",children:[t.jsx("strong",{children:"Blocked reason:"})," ",Gt]}),xt.length>0&&t.jsxs("div",{className:"mission-validation-rounds",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm mission-validation-rounds__toggle",onClick:()=>Et(He=>!He),title:Ft?"Hide validation rounds":"Show validation rounds",children:[Ft?t.jsx(Yt,{size:12}):t.jsx(gn,{size:12}),"Validation rounds (",xt.length,")"]}),Ft&&t.jsx("div",{className:"mission-validation-rounds__list",children:xt.map(He=>t.jsxs("div",{className:"mission-validation-round",children:[t.jsxs("div",{className:"mission-validation-round__header",children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-validation-round__status mission-validation-round__status--${He.validatorStatus}`,children:He.validatorStatus}),t.jsx("span",{className:"mission-validation-round__feature",children:He.featureTitle}),t.jsxs("span",{className:"mission-validation-round__attempts",children:["impl #",He.implementationAttempt," · reviewer #",He.validatorAttempt]})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),He.failedAssertionIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:He.failedAssertionIds.map(We=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Zi(We),title:`Jump to assertion ${We}`,children:We},`${He.roundId}-${We}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Generated fix features:"}),He.generatedFixFeatureIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:He.generatedFixFeatureIds.map(We=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>ea(We),title:`Jump to fix feature ${We}`,children:We},`${He.roundId}-${We}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),He.blockedReason&&t.jsx("div",{className:"mission-validation-round__blocked-reason",children:He.blockedReason})]},He.roundId))})]}),vn.length>0&&t.jsxs("div",{className:"mission-fix-features",children:[t.jsx("div",{className:"mission-fix-features__title",children:"Generated Fix Features"}),t.jsx("div",{className:"mission-fix-features__list",children:vn.map(He=>t.jsxs("div",{className:"mission-fix-feature",children:[t.jsxs("div",{className:"mission-fix-feature__header",children:[t.jsx("button",{className:"mission-fix-feature__title",onClick:()=>ea(He.id),title:`Jump to feature ${He.id}`,children:He.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:co[He.status].bg,color:co[He.status].text},children:He.status}),He.loopState&&t.jsx("span",{className:`mission-loop-state mission-loop-state--${He.loopState}`,children:He.loopState})]}),t.jsxs("div",{className:"mission-fix-feature__meta",children:[t.jsx("span",{children:"Source:"}),t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>ea(He.sourceFeatureId),title:`Jump to source feature ${He.sourceFeatureId}`,children:He.sourceFeatureId}),t.jsx("span",{children:"Run:"}),t.jsx("span",{className:"mission-fix-feature__run",children:He.runId})]}),He.failedAssertionIds.length>0&&t.jsxs("div",{className:"mission-fix-feature__assertions",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),t.jsx("div",{className:"mission-validation-round__chip-list",children:He.failedAssertionIds.map(We=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Zi(We),title:`Jump to assertion ${We}`,children:We},`${He.id}-${We}`))})]})]},He.id))})]})]}),t.jsxs("div",{className:"mission-slices",children:[q.slices.map(He=>t.jsxs("div",{className:"mission-slice",children:[t.jsxs("div",{className:"mission-slice__header",onClick:()=>on(He.id),children:[t.jsx("button",{className:"mission-slice__expand",children:M.has(He.id)?t.jsx(Yt,{size:16}):t.jsx(gn,{size:16})}),t.jsx(Oc,{size:16,className:"mission-slice__icon"}),t.jsx("span",{className:"mission-slice__title",children:He.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:xm[He.status].bg,color:xm[He.status].text},children:He.status}),t.jsxs("span",{className:"mission-slice__count",children:[He.features?.length||0," features"]}),t.jsx(ym,{state:He.planState??"not_started"}),He.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Le({type:"slice",id:He.id,title:He.title}),title:"Plan slice","aria-label":"Plan slice",children:t.jsx(Hi,{size:14})}),t.jsxs("div",{className:"mission-slice__actions",onClick:We=>We.stopPropagation(),children:[He.status==="pending"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>en(He.id),title:"Activate slice",children:t.jsx(_n,{size:14})}),He.status==="active"&&He.features?.some(We=>We.status==="defined")&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>ys(He.id),title:"Triage all features",disabled:_,children:_?t.jsx(lt,{size:14,className:"spinner"}):t.jsx(es,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>xn(He.id),title:"Add feature",children:t.jsx(dn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>wt(He),title:"Edit slice",children:t.jsx(hs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ce({type:"slice",id:He.id}),title:"Delete slice",children:t.jsx(cn,{size:14})})]})]}),M.has(He.id)&&t.jsxs("div",{className:"mission-slice__body",children:[ue&&V===q.id&&!I&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:H.title,onChange:We=>Q({...H,title:We.target.value}),onKeyDown:Zr,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:H.description,onChange:We=>Q({...H,description:We.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:fn,disabled:_,children:[_?t.jsx(lt,{size:14,className:"spinner"}):t.jsx(Jn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:jt,children:"Cancel"})]})]}),I===He.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:H.title,onChange:We=>Q({...H,title:We.target.value}),onKeyDown:Zr,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:H.description,onChange:We=>Q({...H,description:We.target.value}),rows:2}),t.jsxs("select",{value:H.status,onChange:We=>Q({...H,status:We.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:fn,disabled:_,children:[_?t.jsx(lt,{size:14,className:"spinner"}):t.jsx(Jn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:jt,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-features",children:[He.features?.map(We=>t.jsxs("div",{className:"mission-feature","data-mission-feature-id":We.id,children:[t.jsxs("div",{className:"mission-feature__header",children:[t.jsx("button",{className:"mission-feature__expand",onClick:()=>Qr(We.id),title:Rt===We.id?"Collapse details":"Expand to show run history",children:Rt===We.id?t.jsx(Yt,{size:14}):t.jsx(gn,{size:14})}),t.jsx(Tc,{size:14,className:"mission-feature__icon"}),t.jsx("span",{className:"mission-feature__title",children:We.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:co[We.status].bg,color:co[We.status].text},children:We.status}),We.loopState&&We.loopState!=="idle"&&t.jsxs("span",{className:`mission-loop-state mission-loop-state--${We.loopState}`,title:`Loop state: ${We.loopState}`,children:[We.loopState==="implementing"&&"⏳",We.loopState==="validating"&&"🔄",We.loopState==="needs_fix"&&"🔧",We.loopState==="passed"&&"✅",We.loopState==="blocked"&&"🚫"]}),We.generatedFromFeatureId&&t.jsx("button",{className:"mission-feature__lineage",onClick:()=>ea(We.generatedFromFeatureId),title:`Generated from feature: ${We.generatedFromFeatureId}`,children:"🔗 Fix"}),(We.loopState==="validating"||We.loopState==="needs_fix")&&(()=>{const yt=Wt.get(We.id),jn=Ut.get(We.id),Rs=yt?.implementationAttemptCount??jn?.implementationAttempt??We.implementationAttemptCount??0,Pi=yt?.retryBudgetRemaining??Math.max(0,VS-Rs);return t.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",Rs," · ",Pi," ",Pi===1?"retry":"retries"," left"]})})(),We.loopState==="implementing"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>Jr(We.id),title:"Validate feature",disabled:Pt.has(We.id),children:Pt.has(We.id)?t.jsx(lt,{size:14,className:"spinner"}):t.jsx(cs,{size:14})}),We.taskId&&t.jsx("span",{className:"mission-feature__task-link",onClick:()=>o?.(We.taskId),title:"Click to view task",children:We.taskId}),t.jsxs("div",{className:"mission-feature__actions",children:[We.status==="defined"&&!We.taskId&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Qn(We.id),title:"Triage — create task",disabled:_||Ve===We.id,children:Ve===We.id?t.jsx(lt,{size:14,className:"spinner"}):t.jsx(es,{size:14})}),We.taskId?t.jsx("button",{className:"mission-icon-btn",onClick:()=>xs(We.id),title:"Unlink task",children:t.jsx(eu,{size:14})}):We.status!=="defined"?t.jsx("button",{className:"mission-icon-btn",onClick:()=>Te(We.id),title:"Link to task",children:t.jsx(va,{size:14})}):null,t.jsx("button",{className:"mission-icon-btn",onClick:()=>qn(We),title:"Edit feature",children:t.jsx(hs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ce({type:"feature",id:We.id}),title:"Delete feature",children:t.jsx(cn,{size:14})})]})]}),We.description&&t.jsx("p",{className:"mission-feature__description",children:We.description}),We.acceptanceCriteria&&t.jsxs("p",{className:"mission-feature__criteria",children:[t.jsx("strong",{children:"Acceptance:"})," ",We.acceptanceCriteria]}),we?.featureId===We.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:we.enrichedDescription}),t.jsxs("div",{className:"mission-triage-preview__actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:vs,disabled:_,children:[_?t.jsx(lt,{size:14,className:"spinner"}):null,"Create Task"]}),t.jsx("button",{className:"btn",onClick:Os,disabled:_,children:"Cancel"})]})]}),B===We.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:X.title,onChange:yt=>he({...X,title:yt.target.value}),onKeyDown:eo,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:X.description,onChange:yt=>he({...X,description:yt.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:X.acceptanceCriteria,onChange:yt=>he({...X,acceptanceCriteria:yt.target.value}),rows:2}),t.jsxs("select",{value:X.status,onChange:yt=>he({...X,status:yt.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:tt,disabled:_,children:[_?t.jsx(lt,{size:14,className:"spinner"}):t.jsx(Jn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:On,children:"Cancel"})]})]}),Rt===We.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"})}),(Oe.get(We.id)??[]).map(yt=>t.jsxs("div",{className:"mission-run",children:[t.jsxs("div",{className:"mission-run__header",onClick:()=>is(yt.id),children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-run__status mission-run__status--${yt.status}`,title:yt.status,children:yt.status}),t.jsx("span",{className:"mission-run__time",children:new Date(yt.startedAt).toLocaleString()}),yt.completedAt&&t.jsxs("span",{className:"mission-run__duration",children:[Math.round((new Date(yt.completedAt).getTime()-new Date(yt.startedAt).getTime())/1e3),"s"]}),yt.triggerType&&t.jsx("span",{className:"mission-run__trigger",children:yt.triggerType}),t.jsx("button",{className:"mission-icon-btn",title:L===yt.id?"Hide details":"Show details",children:L===yt.id?t.jsx(Yt,{size:12}):t.jsx(gn,{size:12})})]}),L===yt.id&&ge.get(yt.id)&&t.jsxs("div",{className:"mission-run__details",children:[yt.summary&&t.jsx("p",{className:"mission-run__summary",children:yt.summary}),yt.blockedReason&&t.jsxs("p",{className:"mission-run__blocked-reason",children:[t.jsx("strong",{children:"Blocked:"})," ",yt.blockedReason]}),ge.get(yt.id)?.failures&&ge.get(yt.id).failures.length>0&&t.jsxs("div",{className:"mission-run__failures",children:[t.jsx("span",{className:"mission-run__failures-title",children:"Failed Assertions:"}),ge.get(yt.id).failures.map(jn=>t.jsxs("div",{className:"mission-run__failure",children:[t.jsx("span",{className:"mission-run__failure-message",children:jn.message}),jn.expected&&t.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",jn.expected]}),jn.actual&&t.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",jn.actual]})]},jn.id))]}),(!ge.get(yt.id)?.failures||ge.get(yt.id).failures.length===0)&&t.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},yt.id)),(!Oe.get(We.id)||Oe.get(We.id).length===0)&&t.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},We.id)),de&&se===He.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:X.title,onChange:We=>he({...X,title:We.target.value}),onKeyDown:eo,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:X.description,onChange:We=>he({...X,description:We.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:X.acceptanceCriteria,onChange:We=>he({...X,acceptanceCriteria:We.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:tt,disabled:_,children:[_?t.jsx(lt,{size:14,className:"spinner"}):t.jsx(Jn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:On,children:"Cancel"})]})]}),!de&&(!He.features||He.features.length===0)&&t.jsxs("div",{className:"mission-manager__empty mission-features__empty",children:[t.jsx(Tc,{size:16}),t.jsx("span",{children:"No fix features generated."})]})]})]})]},He.id)),q.slices.length===0&&!ue&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Oc,{size:16}),t.jsx("span",{children:"No slices yet"})]}),t.jsxs("div",{className:"mission-assertions",children:[t.jsxs("div",{className:"mission-assertions__header",children:[t.jsx("span",{className:"mission-assertions__title",children:"Assertions"}),De&&t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:_t.bg,color:_t.text},children:wm(De.state)}),De&&De.totalAssertions>0&&t.jsx("div",{className:"mission-assertions__coverage-bar",title:`${De.passedAssertions??0} of ${De.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-assertions__coverage-bar-fill",style:{width:`${(De.passedAssertions??0)/De.totalAssertions*100}%`,backgroundColor:(De.passedAssertions??0)===De.totalAssertions?"var(--color-success)":"var(--color-warning)"}})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>{re(!0),Qe(null),bt({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:t.jsx(dn,{size:14})})]}),ee&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:Ie.title,onChange:He=>bt({...Ie,title:He.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:Ie.assertion,onChange:He=>bt({...Ie,assertion:He.target.value}),rows:2}),t.jsxs("select",{value:Ie.status,onChange:He=>bt({...Ie,status:He.target.value}),children:[t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"passed",children:"Passed"}),t.jsx("option",{value:"failed",children:"Failed"}),t.jsx("option",{value:"blocked",children:"Blocked"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:()=>Fs(q.id),disabled:_,children:[_?t.jsx(lt,{size:14,className:"spinner"}):t.jsx(Jn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Ti,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-assertions__list",children:[(Array.isArray(Pe.get(q.id))?Pe.get(q.id):[]).map(He=>t.jsxs("div",{className:"mission-assertion","data-mission-assertion-id":He.id,children:[t.jsx("div",{className:"mission-assertion__header",children:Re===He.id?t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:Ie.title,onChange:We=>bt({...Ie,title:We.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text",value:Ie.assertion,onChange:We=>bt({...Ie,assertion:We.target.value}),rows:2}),t.jsxs("select",{value:Ie.status,onChange:We=>bt({...Ie,status:We.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:()=>Gr(He.id,q.id),disabled:_,children:[_?t.jsx(lt,{size:14,className:"spinner"}):t.jsx(Jn,{size:14}),"Save"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Ti,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(mo[He.status]??mo.pending).bg,color:(mo[He.status]??mo.pending).text},children:He.status}),t.jsx("span",{className:"mission-assertion__title",children:He.title}),(()=>{const yt=ne.get(He.id)?.length??0;return yt>0?t.jsxs("span",{className:"mission-assertion__linked-count",title:`${yt} linked feature${yt!==1?"s":""}`,children:["(",yt," linked)"]}):null})(),t.jsx("button",{className:"mission-icon-btn",onClick:()=>yi(He.id),title:"Toggle details",children:Se===He.id?t.jsx(Yt,{size:14}):t.jsx(gn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ri(He),title:"Edit assertion",children:t.jsx(hs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ce({type:"assertion",id:He.id}),title:"Delete assertion",children:t.jsx(cn,{size:14})})]})}),Se===He.id&&t.jsxs("div",{className:"mission-assertion__body",children:[t.jsx("p",{className:"mission-assertion__text",children:He.assertion}),t.jsxs("div",{className:"mission-assertion__linked-features",children:[t.jsxs("div",{className:"mission-assertion__linked-features-header",children:[t.jsx("span",{className:"mission-assertion__linked-features-label",children:"Linked Features"}),t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:async()=>{Se!==He.id&&await yi(He.id),kt(pt===He.id?null:He.id)},title:"Link a feature",children:[t.jsx(va,{size:12}),"Link Feature"]})]}),pt===He.id&&t.jsx("div",{className:"mission-assertion__feature-picker",children:t.jsx("div",{className:"mission-assertion__feature-picker-dropdown",children:(()=>{const We=new Set((ne.get(He.id)??[]).map(jn=>jn.id)),yt=[];return g?.milestones.forEach(jn=>jn.slices.forEach(Rs=>yt.push(...Rs.features.filter(Pi=>!We.has(Pi.id))))),yt.length===0?t.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):yt.map(jn=>t.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>yl(jn.id,He.id),disabled:ft.has(He.id),children:[t.jsx("span",{className:"mission-assertion__feature-picker-title",children:jn.title}),ft.has(He.id)&&t.jsx(lt,{size:12,className:"spinner"})]},jn.id))})()})}),(()=>{const We=ne.get(He.id)??[];return We.length===0?t.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):We.map(yt=>{const jn=`${yt.id}-${He.id}`,Rs=St.has(jn);return t.jsxs("div",{className:"mission-assertion__linked-feature",children:[t.jsx("span",{className:"mission-assertion__linked-feature-title",children:yt.title}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>wl(yt.id,He.id),disabled:Rs,title:"Unlink feature",children:Rs?t.jsx(lt,{size:12,className:"spinner"}):t.jsx(eu,{size:12})})]},yt.id)})})()]})]})]},He.id)),(!Pe.get(q.id)||Pe.get(q.id)?.length===0)&&!ee&&t.jsx("div",{className:"mission-manager__empty mission-assertions__empty",children:t.jsx("span",{children:"No assertions defined. Add one to define completion criteria."})})]})]})]})]})]},q.id)}),g&&!N&&D===null&&t.jsxs("button",{className:"mission-add-btn",onClick:Jt,children:[t.jsx(dn,{size:16}),"Add Milestone"]}),N&&D===null&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:J.title,onChange:q=>te({...J,title:q.target.value}),onKeyDown:qa,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:J.description,onChange:q=>te({...J,description:q.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:zs,disabled:_,children:[_?t.jsx(lt,{size:14,className:"spinner"}):t.jsx(Jn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Hn,children:"Cancel"})]})]}),g.milestones.length===0&&!N&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(qi,{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:sn,onChange:q=>un(q.target.value),"data-testid":"mission-activity-filter",children:[t.jsx("option",{value:"all",children:"All events"}),t.jsx("option",{value:"errors",children:"Errors & warnings"}),t.jsx("option",{value:"state_changes",children:"State changes"}),t.jsx("option",{value:"tasks",children:"Task events"}),t.jsx("option",{value:"slices",children:"Slice & milestone events"}),t.jsx("option",{value:"autopilot",children:"Autopilot events"})]})]}),t.jsxs("span",{className:"mission-detail__activity-count",children:[Cn.length," of ",Tn]})]}),!wn&&Ba&&t.jsx("div",{className:"mission-detail__activity-load-more mission-detail__activity-load-more--top",children:t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Xs,"data-testid":"mission-activity-load-more",children:"Load more"})}),wn?t.jsxs("div",{className:"mission-manager__loading mission-detail__activity-loading",children:[t.jsx(lt,{size:18,className:"spinner"}),t.jsx("span",{children:"Loading mission activity..."})]}):Cn.length===0?t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Ds,{size:18}),t.jsx("span",{children:"No events yet."})]}):t.jsxs("div",{ref:an,className:"mission-events","data-testid":"mission-activity-events",children:[Cn.map(q=>{const Ce=!!(q.metadata&&Object.keys(q.metadata).length>0),De=Bn.has(q.id);return t.jsxs("div",{className:"mission-event",children:[t.jsxs("div",{className:"mission-event__header",children:[t.jsx("span",{className:`mission-event__type ${QS(q.eventType)}`,children:XS(q.eventType)}),t.jsx("span",{className:"mission-event__time",children:Vo(q.timestamp)})]}),t.jsx("p",{className:"mission-event__description",children:q.description}),t.jsx("span",{className:"mission-event__timestamp",children:new Date(q.timestamp).toLocaleString()}),Ce&&t.jsxs("div",{className:"mission-event__metadata",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>Us(q.id),"data-testid":`mission-event-metadata-${q.id}`,children:[De?"Hide":"Show"," metadata"]}),De&&t.jsx("pre",{className:"mission-event__metadata-content",children:JSON.stringify(q.metadata,null,2)})]})]},q.id)}),t.jsx("div",{ref:Dn})]})]})]}):t.jsxs("div",{className:"mission-list",children:[E&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:S.title,onChange:q=>O({...S,title:q.target.value}),onKeyDown:Ha,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:S.description,onChange:q=>O({...S,description:q.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:ht,disabled:_,children:[_?t.jsx(lt,{size:14,className:"spinner"}):t.jsx(Jn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:mt,children:"Cancel"})]})]}),f.map(q=>{const Ce=q,De=g,xt=De&&De.id===Ce.id,vn=Ja[Ce.status]||{bg:"",text:""},_t=Ce.summary,Gt=Be.get(Ce.id),He=GS(Gt),We=!!(_t&&(_t.totalMilestones>0||_t.totalFeatures>0)),yt=Gt?.totalTasks??0,jn=Gt?.tasksCompleted??0,Rs=Gt?.tasksFailed??0,Pi=Gt?.estimatedCompletionPercent??_t?.progressPercent??0,as=We||yt>0||Rs>0||!!Gt?.lastActivityAt,An=Ce.status==="active"&&(Gt?.currentMilestoneId||Gt?.currentSliceId)?"Current milestone/slice in progress":null;return t.jsxs("div",{className:`mission-list__item ${xt?"mission-list__item--selected":""}`,onClick:()=>Ua(q),children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(ks,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{className:"mission-list__item-title",children:Ce.title}),q.autopilotEnabled&&t.jsx("span",{title:"Autopilot enabled",children:t.jsx(es,{size:12,className:"mission-list__item-autopilot-icon"})}),t.jsx("span",{className:`mission-health-badge mission-health-badge--${He}`,"data-testid":`mission-health-badge-${Ce.id}`,"aria-label":`Mission health: ${He}`}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:vn.bg,color:vn.text},children:Ce.status})]}),Ce.description&&t.jsx("p",{className:"mission-list__item-description",children:Ce.description}),An&&t.jsxs("p",{className:"mission-list__item-active-slice",children:["Active: ",An]}),as&&t.jsxs("div",{className:"mission-list__item-summary",children:[We&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"mission-list__item-stat",children:[_t.completedMilestones,"/",_t.totalMilestones," milestones"]}),t.jsxs("span",{className:"mission-list__item-stat",children:[_t.completedFeatures,"/",_t.totalFeatures," features"]})]}),t.jsxs("span",{className:"mission-list__item-stat","data-testid":`mission-task-stats-${Ce.id}`,children:[jn,"/",yt," tasks"]}),Rs>0&&t.jsxs("button",{className:"mission-list__item-failed",onClick:Vt=>{Vt.stopPropagation(),Ua(q)},"data-testid":`mission-failed-${Ce.id}`,title:"View mission failures",children:[Rs," failed"]}),t.jsxs("span",{className:"mission-relative-time","data-testid":`mission-last-activity-${Ce.id}`,children:["Activity ",Vo(Gt?.lastActivityAt)]}),t.jsx("div",{className:`mission-list__item-progress mission-list__item-progress--${He}`,children:t.jsx("div",{className:"mission-list__item-progress-bar",style:{width:`${Pi}%`}})})]})]}),t.jsxs("div",{className:"mission-list__item-actions",onClick:Vt=>Vt.stopPropagation(),children:[Ce.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ms(Ce.id),title:"Stop mission",children:t.jsx(Cs,{size:14})}),Ce.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>ta(Ce.id),title:"Resume mission",children:t.jsx(_n,{size:14})}),Ce.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Fa(Ce.id),title:"Start mission",children:t.jsx(_n,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ye(q),title:"Edit mission",children:t.jsx(hs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ce({type:"mission",id:Ce.id}),title:"Delete mission",children:t.jsx(cn,{size:14})})]})]},Ce.id)}),w&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:S.title,onChange:q=>O({...S,title:q.target.value}),onKeyDown:Ha,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:S.description,onChange:q=>O({...S,description:q.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:S.status,onChange:q=>O({...S,status:q.target.value}),children:[t.jsx("option",{value:"planning",children:"Planning"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"blocked",children:"Blocked"}),t.jsx("option",{value:"complete",children:"Complete"}),t.jsx("option",{value:"archived",children:"Archived"})]}),t.jsxs("label",{className:"mission-checkbox",children:[t.jsx("input",{type:"checkbox",checked:S.autopilotEnabled,onChange:q=>O({...S,autopilotEnabled:q.target.checked})}),t.jsx(es,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:ht,disabled:_,children:[_?t.jsx(lt,{size:14,className:"spinner"}):t.jsx(Jn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:mt,children:"Cancel"})]})]}),f.length===0&&!E&&t.jsxs("div",{className:"mission-manager__empty mission-manager__empty--large",children:[t.jsx(ks,{size:32}),t.jsx("span",{children:"No missions yet. Create one to start planning."})]}),!E&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[$e.length>0&&t.jsxs("div",{className:"mission-resume-prompt",children:[t.jsx(gs,{size:16}),t.jsx("span",{children:$e.length===1?`Resume "${$e[0].title}"?`:`${$e.length} interview sessions pending`}),t.jsx("div",{style:{display:"flex",gap:"4px",marginLeft:"auto"},children:$e.map(q=>t.jsxs("button",{className:"mission-add-btn",onClick:()=>{je(q.id),Xe(!0),Ue([])},children:[q.status==="error"?t.jsx(Fn,{size:14}):t.jsx(cs,{size:14}),q.status==="error"?"Retry":"Resume"]},q.id))})]}),t.jsxs("div",{style:{display:"flex",gap:"8px"},children:[t.jsxs("button",{className:"mission-add-btn",onClick:()=>Xe(!0),children:[t.jsx(cs,{size:16}),"Plan with AI"]}),t.jsxs("button",{className:"mission-add-btn",onClick:ye,children:[t.jsx(dn,{size:16}),"New Mission"]})]})]})]})}),xe&&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 ",xe.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()=>{xe.type==="mission"?await Kt(xe.id):xe.type==="milestone"?await ae(xe.id):xe.type==="slice"?await mn(xe.id):xe.type==="feature"&&await At(xe.id)},children:"Delete"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>ce(null),children:"Cancel"})]})]})}),Fe&&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:st,onChange:q=>nt(q.target.value),autoFocus:!0}),l.length>0&&t.jsxs("div",{className:"mission-task-suggestions",children:[t.jsx("small",{children:"Or select:"}),t.jsx("div",{className:"mission-task-suggestions__list",children:l.slice(0,5).map(q=>t.jsxs("button",{className:"mission-task-suggestions__item",onClick:()=>nt(q.id),children:[q.id,": ",q.title||"Untitled"]},q.id))})]}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--primary",onClick:Mn,children:"Link"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>{Te(null),nt("")},children:"Cancel"})]})]})})]}),no=t.jsx(OS,{isOpen:qe,onClose:()=>Xe(!1),onMissionCreated:()=>{nn(),i("Mission created from AI interview","success")},projectId:r,resumeSessionId:ie}),sa=Ae?t.jsx(BS,{isOpen:!0,onClose:()=>Le(null),onApplied:()=>{Le(null),g&&vt(g.id)},targetType:Ae.type,targetId:Ae.id,targetTitle:Ae.title,missionContext:g?.title,projectId:r,resumeSessionId:Ae.resumeSessionId}):null;return n?t.jsxs(t.Fragment,{children:[to,no,sa]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mission-manager-overlay open",onClick:q=>q.target===q.currentTarget&&s(),"data-testid":"mission-manager-overlay",role:"dialog","aria-modal":"true",children:to}),no,sa]})}const ho=2e3;function km({recipient:e,replyContext:n,agents:s=[],projectId:i,onSend:r,onCancel:o,addToast:l,isLoadingAgents:c=!1}){const[u,d]=a.useState(e?.id??""),[m,h]=a.useState(e?.type??"agent"),[f,p]=a.useState(""),[g,b]=a.useState(!1),[v,x]=a.useState(null),y=u.trim()!==""&&f.trim().length>0&&f.length<=ho,j=a.useCallback(async()=>{if(!(!y||g)){b(!0),x(null);try{const C=m==="agent"?"user-to-agent":"system";await Wk({toId:u.trim(),toType:m,content:f.trim(),type:C,...n?{metadata:{replyTo:{messageId:n.messageId}}}:{}},i),r()}catch(C){const w=ke(C)||"Failed to send message";x(w),l?.(w,"error")}finally{b(!1)}}},[y,g,u,m,f,n,i,r,l]),E=a.useCallback(C=>{d(C),h("agent")},[]);return t.jsxs("div",{className:"message-composer","data-testid":"message-composer",children:[t.jsxs("div",{className:"message-composer-header",children:[t.jsx("span",{children:n?"Reply":"New Message"}),t.jsx("button",{className:"btn-icon",onClick:o,"aria-label":"Cancel","data-testid":"message-composer-cancel",children:t.jsx(qt,{size:16})})]}),t.jsxs("div",{className:"message-composer-body",children:[!e&&t.jsxs("div",{className:"message-composer-field",children:[t.jsx("label",{className:"message-composer-label",htmlFor:"message-recipient",children:"To:"}),t.jsxs("select",{id:"message-recipient",className:"message-composer-select",value:u,onChange:C=>E(C.target.value),disabled:c||s.length===0,"data-testid":"message-composer-recipient",children:[t.jsx("option",{value:"",children:c?"Loading agents…":s.length===0?"No agents available":"Select agent…"}),s.map(C=>t.jsx("option",{value:C.id,children:C.name||C.id},C.id))]})]}),e&&t.jsxs("div",{className:"message-composer-field",children:[t.jsx("span",{className:"message-composer-label",children:"To:"}),t.jsxs("span",{className:"message-composer-recipient-fixed",children:[t.jsx(En,{size:14}),e.id]})]}),n&&t.jsxs("div",{className:"message-composer-field","data-testid":"message-composer-reply-context",children:[t.jsx("span",{className:"message-composer-label",children:"Replying to:"}),t.jsx("span",{className:"message-composer-recipient-fixed",children:n.preview?.trim()?n.preview:`Message ${n.messageId}`})]}),t.jsxs("div",{className:"message-composer-field message-composer-field--content",children:[t.jsx("label",{className:"message-composer-label",htmlFor:"message-content",children:"Message:"}),t.jsx("textarea",{id:"message-content",className:"message-composer-textarea",placeholder:"Type your message…",value:f,onChange:C=>p(C.target.value),maxLength:ho,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>ho?"over-limit":"",children:[f.length,"/",ho]})})]}),v&&t.jsxs("div",{className:"message-composer-error","data-testid":"message-composer-error",children:[t.jsx(gs,{size:14}),t.jsx("span",{children:v})]})]}),t.jsxs("div",{className:"message-composer-footer",children:[t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:o,"data-testid":"message-composer-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:j,disabled:!y||g,"data-testid":"message-composer-send",children:g?t.jsxs(t.Fragment,{children:[t.jsx(lt,{size:14,className:"spin"}),t.jsx("span",{children:"Sending…"})]}):t.jsxs(t.Fragment,{children:[t.jsx(Oi,{size:14}),t.jsx("span",{children:"Send"})]})})]})]})}function ca(e){const n=new Date(e),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),o=Math.floor(i/36e5),l=Math.floor(i/864e5);return r<1?"Just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function t0(e,n,s){if(n==="user")return e==="dashboard"?"You":`User: ${e}`;if(n==="agent"){const i=s?.get(e)?.trim();return i?i===e?`Agent: ${e}`:`Agent: ${i} (${e})`:`Agent: ${e}`}return"System"}function n0(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 Nm(e,n=80){return e.length<=n?e:`${e.slice(0,n)}…`}function s0(e){const n=new Map;for(const s of e){const i=`${s.fromType}:${s.fromId}`,r=n.get(i);r?(r.messages.push(s),new Date(s.createdAt)>new Date(r.latestMessage.createdAt)&&(r.latestMessage=s),s.read||r.unreadCount++):n.set(i,{key:i,fromId:s.fromId,fromType:s.fromType,latestMessage:s,messages:[s],unreadCount:s.read?0:1})}return Array.from(n.values()).sort((s,i)=>new Date(i.latestMessage.createdAt).getTime()-new Date(s.latestMessage.createdAt).getTime())}function i0({projectId:e,addToast:n,onUnreadCountChange:s}){const[i,r]=a.useState("inbox"),[o,l]=a.useState(null),[c,u]=a.useState(null),[d,m]=a.useState(0),[h,f]=a.useState(!1),[p,g]=a.useState(null),[b,v]=a.useState([]),[x,y]=a.useState(!1),[j,E]=a.useState(null),[C,w]=a.useState(null),[R,S]=a.useState(null),[O,_]=a.useState("inbox"),[P,U]=a.useState(null),[G,M]=a.useState([]),T=a.useMemo(()=>new Map(G.map(se=>[se.id,se.name??""])),[G]),D=a.useCallback((se,_e)=>t0(se,_e,T),[T]),J=$a()==="mobile",te=!J,N=a.useCallback(async()=>{f(!0);try{const se=await qk({limit:50},e);l(se),m(se.unreadCount),s?.(se.unreadCount)}catch{}finally{f(!1)}},[e,s]),z=a.useCallback(async()=>{f(!0);try{const se=await Vk({limit:50},e);u(se)}catch{}finally{f(!1)}},[e]),I=a.useCallback(async se=>{f(!0);try{const _e=await Qk(se,e);U(_e)}catch{}finally{f(!1)}},[e]),k=a.useCallback(async()=>{try{const se=await Ia(void 0,e);M(se)}catch{}},[e]),H=a.useCallback(async()=>{try{const se=await Kp(e);m(se.unreadCount),s?.(se.unreadCount)}catch{}},[e,s]);a.useEffect(()=>{i==="inbox"?N():i==="outbox"?z():i==="agents"&&k()},[i,N,z,k]),a.useEffect(()=>{R&&I(R)},[R,I]),a.useEffect(()=>{H()},[H]),a.useEffect(()=>{k()},[k]),a.useEffect(()=>{if(typeof EventSource>"u")return;const se=e?`?projectId=${encodeURIComponent(e)}`:"",_e=()=>{H(),i==="inbox"?N():i==="outbox"&&z(),R&&I(R)};return Js(`/api/events${se}`,{events:{"message:sent":_e,"message:received":_e,"message:read":_e,"message:deleted":_e}})},[e,i,R,H,N,z,I]);const Q=a.useCallback(async se=>{if(g(se),!se.read)try{const _e=await Kk(se.id,e);_e&&l(Te=>Te&&{...Te,messages:Te.messages.map(st=>st.id===_e.id?_e:st),unreadCount:Math.max(0,Te.unreadCount-1)});const Fe=Math.max(0,d-1);m(Fe),s?.(Fe)}catch{}try{const _e=await Yk(se.fromId,se.fromType,e);v(_e)}catch{v([se])}},[e,d,s]),ue=a.useCallback(()=>{g(null),v([])},[]),be=a.useCallback(async()=>{try{const se=await Gk(e);m(0),s?.(0),l(_e=>_e&&{..._e,messages:_e.messages.map(Fe=>({...Fe,read:!0})),unreadCount:0}),n?.(`Marked ${se.markedAsRead} messages as read`,"success")}catch{n?.("Failed to mark messages as read","error")}},[e,n,s]),V=a.useCallback(async se=>{try{await Jk(se,e),g(null),v([]),i==="inbox"?N():i==="outbox"?z():R&&I(R),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[e,i,R,N,z,I,n]),ve=a.useCallback(se=>{E({id:se.fromId,type:se.fromType}),w({messageId:se.id,preview:Nm(se.content,120)}),y(!0)},[]),B=a.useCallback(()=>{y(!1),E(null),w(null),n?.("Message sent","success"),i==="outbox"?z():i==="agents"&&R&&I(R),H()},[i,z,R,I,n,H]),Y=a.useCallback(()=>{E(i==="agents"&&R?{id:R,type:"agent"}:null),w(null),y(!0)},[i,R]),X=a.useCallback(()=>{y(!1),E(null),w(null)},[]),he=()=>!p||x?null:t.jsxs("div",{className:"mailbox-message-detail","data-testid":"mailbox-message-detail",children:[t.jsxs("div",{className:"mailbox-message-detail-header",children:[J&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:ue,"data-testid":"mailbox-back-to-list",children:"← Back"}),t.jsxs("div",{className:"mailbox-message-detail-meta",children:[t.jsx("span",{className:"mailbox-message-type",children:n0(p.type)}),t.jsx("span",{className:"mailbox-message-time",children:ca(p.createdAt)})]}),t.jsxs("div",{className:"mailbox-message-detail-actions",children:[p.fromType==="agent"&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>ve(p),"data-testid":"mailbox-reply",children:[t.jsx(Si,{size:14}),t.jsx("span",{children:"Reply"})]}),t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>V(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(En,{size:14}):t.jsx(ia,{size:14}),D(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(En,{size:14}):t.jsx(ia,{size:14}),D(p.toId,p.toType)]})]})]}),b.length>1&&t.jsxs("div",{className:"mailbox-conversation","data-testid":"mailbox-conversation",children:[t.jsx("div",{className:"mailbox-conversation-label",children:"Conversation"}),b.map(se=>{const _e=se.metadata?.replyTo?.messageId,Fe=_e?b.find(Te=>Te.id===_e):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:D(se.fromId,se.fromType)}),t.jsx("span",{className:"mailbox-message-time",children:ca(se.createdAt)})]}),_e&&t.jsxs("div",{className:"mailbox-reply-context","data-testid":`mailbox-reply-context-${se.id}`,children:["↪ Replying to ",Fe?Nm(Fe.content,60):`message ${_e}`]}),t.jsx("div",{className:"mailbox-conversation-msg-body",children:se.content})]},se.id)})]}),b.length<=1&&t.jsxs(t.Fragment,{children:[p.metadata?.replyTo?.messageId&&t.jsxs("div",{className:"mailbox-reply-context","data-testid":"mailbox-selected-reply-context",children:["↪ Replying to message ",p.metadata.replyTo.messageId]}),t.jsx("div",{className:"mailbox-message-body","data-testid":"mailbox-message-body",children:p.content})]})]}),de=()=>t.jsxs(t.Fragment,{children:[i==="inbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[h&&!o&&t.jsx(Vl,{}),o&&o.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-inbox-empty",children:[t.jsx(dr,{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:s0(o.messages).map(se=>t.jsxs("div",{className:`mailbox-conversation-group ${se.unreadCount>0?"unread":""}`,onClick:()=>Q(se.latestMessage),"data-testid":`mailbox-conversation-${se.key}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:se.fromType==="agent"?t.jsx(En,{size:16}):t.jsx(ia,{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:D(se.fromId,se.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:ca(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))})]}),i==="outbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-outbox-list",children:[h&&!c&&t.jsx(Vl,{}),c&&c.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-outbox-empty",children:[t.jsx(Oi,{size:32}),t.jsx("p",{children:"No sent messages"})]}),c?.messages.map(se=>t.jsxs("div",{className:"mailbox-item",onClick:()=>Q(se),"data-testid":`mailbox-item-${se.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:se.toType==="agent"?t.jsx(En,{size:16}):t.jsx(ia,{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: ",D(se.toId,se.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:ca(se.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[se.content.slice(0,80),se.content.length>80?"…":""]})]})]},se.id))]}),i==="agents"&&t.jsx("div",{className:"mailbox-agents","data-testid":"mailbox-agents",children:G.length===0?t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(En,{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:R??"",onChange:se=>{S(se.target.value||null),_("inbox")},"data-testid":"mailbox-agent-select",children:[t.jsx("option",{value:"",children:"Select an agent…"}),G.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:Y,"data-testid":"mailbox-compose-btn",children:[t.jsx(Si,{size:14}),t.jsx("span",{children:"Compose"})]})]}),R&&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 ${O==="inbox"?"active":""}`,onClick:()=>_("inbox"),"data-testid":"mailbox-agent-subtab-inbox",children:[t.jsx(dr,{size:12}),t.jsx("span",{children:"Inbox"}),P&&P.unreadCount>0&&t.jsx("span",{className:"mailbox-tab-badge",children:P.unreadCount})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${O==="outbox"?"active":""}`,onClick:()=>_("outbox"),"data-testid":"mailbox-agent-subtab-outbox",children:[t.jsx(Oi,{size:12}),t.jsx("span",{children:"Outbox"})]})]}),t.jsxs("div",{className:"mailbox-agents-content",children:[!R&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(En,{size:32}),t.jsx("p",{children:"Select an agent to view their mailbox"})]}),R&&h&&!P&&t.jsx(Vl,{}),R&&P&&O==="inbox"&&P.inbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(dr,{size:32}),t.jsx("p",{children:"No received messages for this agent"})]}),R&&P&&O==="outbox"&&P.outbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Oi,{size:32}),t.jsx("p",{children:"No sent messages for this agent"})]}),R&&P&&O==="inbox"&&P.inbox.map(se=>t.jsxs("div",{className:`mailbox-item ${se.read?"":"unread"}`,onClick:()=>Q(se),"data-testid":`mailbox-item-${se.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:se.fromType==="agent"?t.jsx(En,{size:16}):t.jsx(ia,{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:D(se.fromId,se.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:ca(se.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[se.content.slice(0,80),se.content.length>80?"…":""]})]})]},se.id)),R&&P&&O==="outbox"&&P.outbox.map(se=>t.jsxs("div",{className:"mailbox-item",onClick:()=>Q(se),"data-testid":`mailbox-item-${se.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:se.toType==="agent"?t.jsx(En,{size:16}):t.jsx(ia,{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: ",D(se.toId,se.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:ca(se.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[se.content.slice(0,80),se.content.length>80?"…":""]})]})]},se.id))]})]})})]}),me=()=>x?t.jsx(km,{recipient:j,replyContext:C,agents:G,projectId:e,onSend:B,onCancel:X,addToast:n}):p?he():t.jsxs("div",{className:"mailbox-split-empty","data-testid":"mailbox-split-empty",children:[t.jsx(ya,{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(ya,{size:18}),t.jsx("span",{children:"Mailbox"}),d>0&&t.jsx("span",{className:"mailbox-unread-badge","data-testid":"mailbox-unread-badge",children:d})]}),t.jsxs("div",{className:"mailbox-header-actions",children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:Y,title:"Compose message","data-testid":"mailbox-header-compose",children:[t.jsx(Si,{size:14}),t.jsx("span",{children:"Compose"})]}),i==="inbox"&&d>0&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:be,title:"Mark all as read","data-testid":"mailbox-mark-all-read",children:[t.jsx(Rb,{size:14}),t.jsx("span",{children:"Mark all read"})]}),t.jsx("button",{className:"btn-icon",onClick:()=>{i==="inbox"?N():i==="outbox"?z():R&&I(R)},disabled:h,title:"Refresh","data-testid":"mailbox-refresh",children:h?t.jsx(lt,{size:14,className:"spin"}):t.jsx(Fn,{size:14})})]})]}),t.jsxs("div",{className:"mailbox-tabs","data-testid":"mailbox-tabs",children:[t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="inbox"?"active":""}`,onClick:()=>{r("inbox"),g(null)},"data-testid":"mailbox-tab-inbox",children:[t.jsx(dr,{size:14}),t.jsx("span",{children:"Inbox"}),d>0&&t.jsx("span",{className:"mailbox-tab-badge",children:d})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="outbox"?"active":""}`,onClick:()=>{r("outbox"),g(null)},"data-testid":"mailbox-tab-outbox",children:[t.jsx(Oi,{size:14}),t.jsx("span",{children:"Outbox"})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="agents"?"active":""}`,onClick:()=>{r("agents"),g(null)},"data-testid":"mailbox-tab-agents",children:[t.jsx(En,{size:14}),t.jsx("span",{children:"Agents"})]})]}),t.jsx("div",{className:"mailbox-content","data-testid":"mailbox-content",children:te?t.jsxs("div",{className:"mailbox-split-layout","data-testid":"mailbox-split-layout",children:[t.jsx("div",{className:"mailbox-split-list-pane","data-testid":"mailbox-split-list-pane",children:de()}),t.jsx("div",{className:"mailbox-split-detail-pane","data-testid":"mailbox-split-detail-pane",children:me()})]}):t.jsxs(t.Fragment,{children:[he(),x&&t.jsx(km,{recipient:j,replyContext:C,agents:G,projectId:e,onSend:B,onCancel:X,addToast:n}),!p&&!x&&de()]})})]})}function Vl(){return t.jsx("div",{className:"mailbox-skeleton","data-testid":"mailbox-skeleton",children:Array.from({length:5}).map((e,n)=>t.jsxs("div",{className:"mailbox-skeleton-item",children:[t.jsx("div",{className:"mailbox-skeleton-avatar"}),t.jsxs("div",{className:"mailbox-skeleton-content",children:[t.jsx("div",{className:"mailbox-skeleton-line mailbox-skeleton-line--short"}),t.jsx("div",{className:"mailbox-skeleton-line mailbox-skeleton-line--long"})]})]},n))})}function di(e,n,s){a.useEffect(()=>{if(!n)return;const i=e.current;if(!i)return;try{const u=localStorage.getItem(s);if(u){const{width:d,height:m}=JSON.parse(u);typeof d=="number"&&d>0&&(i.style.width=`${d}px`),typeof m=="number"&&m>0&&(i.style.height=`${m}px`)}}catch{}if(typeof ResizeObserver>"u")return;let r=i.offsetWidth,o=i.offsetHeight,l=null;const c=new ResizeObserver(()=>{const u=i.offsetWidth,d=i.offsetHeight;u===r&&d===o||(r=u,o=d,l&&clearTimeout(l),l=setTimeout(()=>{try{localStorage.setItem(s,JSON.stringify({width:u,height:d}))}catch{}},200))});return c.observe(i),()=>{c.disconnect(),l&&clearTimeout(l)}},[e,n,s])}function Mi(e){const n=a.useRef(!1),s=a.useCallback(r=>{n.current=r.target===r.currentTarget},[]),i=a.useCallback(r=>{const o=n.current&&r.target===r.currentTarget;n.current=!1,o&&e()},[e]);return{onMouseDown:s,onMouseUp:i}}function a0(e,n){const s={};return(e[e.length-1]===""?[...e,""]:e).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const r0=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,o0=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,l0={};function Sm(e,n){return(l0.jsx?o0:r0).test(e)}const c0=/[ \t\n\f\r]/g;function d0(e){return typeof e=="object"?e.type==="text"?Cm(e.value):!1:Cm(e)}function Cm(e){return e.replace(c0,"")===""}class Vr{constructor(n,s,i){this.normal=s,this.property=n,i&&(this.space=i)}}Vr.prototype.normal={};Vr.prototype.property={};Vr.prototype.space=void 0;function jf(e,n){const s={},i={};for(const r of e)Object.assign(s,r.property),Object.assign(i,r.normal);return new Vr(s,i,n)}function Qc(e){return e.toLowerCase()}class Ns{constructor(n,s){this.attribute=s,this.property=n}}Ns.prototype.attribute="";Ns.prototype.booleanish=!1;Ns.prototype.boolean=!1;Ns.prototype.commaOrSpaceSeparated=!1;Ns.prototype.commaSeparated=!1;Ns.prototype.defined=!1;Ns.prototype.mustUseProperty=!1;Ns.prototype.number=!1;Ns.prototype.overloadedBoolean=!1;Ns.prototype.property="";Ns.prototype.spaceSeparated=!1;Ns.prototype.space=void 0;let u0=0;const Bt=Xi(),Vn=Xi(),Xc=Xi(),at=Xi(),kn=Xi(),xa=Xi(),Ss=Xi();function Xi(){return 2**++u0}const Zc=Object.freeze(Object.defineProperty({__proto__:null,boolean:Bt,booleanish:Vn,commaOrSpaceSeparated:Ss,commaSeparated:xa,number:at,overloadedBoolean:Xc,spaceSeparated:kn},Symbol.toStringTag,{value:"Module"})),Wl=Object.keys(Zc);class Pd extends Ns{constructor(n,s,i,r){let o=-1;if(super(n,s),Em(this,"space",r),typeof i=="number")for(;++o<Wl.length;){const l=Wl[o];Em(this,Wl[o],(i&Zc[l])===Zc[l])}}}Pd.prototype.defined=!0;function Em(e,n,s){s&&(e[n]=s)}function za(e){const n={},s={};for(const[i,r]of Object.entries(e.properties)){const o=new Pd(i,e.transform(e.attributes||{},i),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(i)&&(o.mustUseProperty=!0),n[i]=o,s[Qc(i)]=i,s[Qc(o.attribute)]=i}return new Vr(n,s,e.space)}const kf=za({properties:{ariaActiveDescendant:null,ariaAtomic:Vn,ariaAutoComplete:null,ariaBusy:Vn,ariaChecked:Vn,ariaColCount:at,ariaColIndex:at,ariaColSpan:at,ariaControls:kn,ariaCurrent:null,ariaDescribedBy:kn,ariaDetails:null,ariaDisabled:Vn,ariaDropEffect:kn,ariaErrorMessage:null,ariaExpanded:Vn,ariaFlowTo:kn,ariaGrabbed:Vn,ariaHasPopup:null,ariaHidden:Vn,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:kn,ariaLevel:at,ariaLive:null,ariaModal:Vn,ariaMultiLine:Vn,ariaMultiSelectable:Vn,ariaOrientation:null,ariaOwns:kn,ariaPlaceholder:null,ariaPosInSet:at,ariaPressed:Vn,ariaReadOnly:Vn,ariaRelevant:null,ariaRequired:Vn,ariaRoleDescription:kn,ariaRowCount:at,ariaRowIndex:at,ariaRowSpan:at,ariaSelected:Vn,ariaSetSize:at,ariaSort:null,ariaValueMax:at,ariaValueMin:at,ariaValueNow:at,ariaValueText:null,role:null},transform(e,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function Nf(e,n){return n in e?e[n]:n}function Sf(e,n){return Nf(e,n.toLowerCase())}const m0=za({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:xa,acceptCharset:kn,accessKey:kn,action:null,allow:null,allowFullScreen:Bt,allowPaymentRequest:Bt,allowUserMedia:Bt,alt:null,as:null,async:Bt,autoCapitalize:null,autoComplete:kn,autoFocus:Bt,autoPlay:Bt,blocking:kn,capture:null,charSet:null,checked:Bt,cite:null,className:kn,cols:at,colSpan:null,content:null,contentEditable:Vn,controls:Bt,controlsList:kn,coords:at|xa,crossOrigin:null,data:null,dateTime:null,decoding:null,default:Bt,defer:Bt,dir:null,dirName:null,disabled:Bt,download:Xc,draggable:Vn,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:Bt,formTarget:null,headers:kn,height:at,hidden:Xc,high:at,href:null,hrefLang:null,htmlFor:kn,httpEquiv:kn,id:null,imageSizes:null,imageSrcSet:null,inert:Bt,inputMode:null,integrity:null,is:null,isMap:Bt,itemId:null,itemProp:kn,itemRef:kn,itemScope:Bt,itemType:kn,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:Bt,low:at,manifest:null,max:null,maxLength:at,media:null,method:null,min:null,minLength:at,multiple:Bt,muted:Bt,name:null,nonce:null,noModule:Bt,noValidate:Bt,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:Bt,optimum:at,pattern:null,ping:kn,placeholder:null,playsInline:Bt,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:Bt,referrerPolicy:null,rel:kn,required:Bt,reversed:Bt,rows:at,rowSpan:at,sandbox:kn,scope:null,scoped:Bt,seamless:Bt,selected:Bt,shadowRootClonable:Bt,shadowRootDelegatesFocus:Bt,shadowRootMode:null,shape:null,size:at,sizes:null,slot:null,span:at,spellCheck:Vn,src:null,srcDoc:null,srcLang:null,srcSet:null,start:at,step:null,style:null,tabIndex:at,target:null,title:null,translate:null,type:null,typeMustMatch:Bt,useMap:null,value:Vn,width:at,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:kn,axis:null,background:null,bgColor:null,border:at,borderColor:null,bottomMargin:at,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:Bt,declare:Bt,event:null,face:null,frame:null,frameBorder:null,hSpace:at,leftMargin:at,link:null,longDesc:null,lowSrc:null,marginHeight:at,marginWidth:at,noResize:Bt,noHref:Bt,noShade:Bt,noWrap:Bt,object:null,profile:null,prompt:null,rev:null,rightMargin:at,rules:null,scheme:null,scrolling:Vn,standby:null,summary:null,text:null,topMargin:at,valueType:null,version:null,vAlign:null,vLink:null,vSpace:at,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:Bt,disableRemotePlayback:Bt,prefix:null,property:null,results:at,security:null,unselectable:null},space:"html",transform:Sf}),h0=za({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:Ss,accentHeight:at,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:at,amplitude:at,arabicForm:null,ascent:at,attributeName:null,attributeType:null,azimuth:at,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:at,by:null,calcMode:null,capHeight:at,className:kn,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:at,diffuseConstant:at,direction:null,display:null,dur:null,divisor:at,dominantBaseline:null,download:Bt,dx:null,dy:null,edgeMode:null,editable:null,elevation:at,enableBackground:null,end:null,event:null,exponent:at,externalResourcesRequired:null,fill:null,fillOpacity:at,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:xa,g2:xa,glyphName:xa,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:at,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:at,horizOriginX:at,horizOriginY:at,id:null,ideographic:at,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:at,k:at,k1:at,k2:at,k3:at,k4:at,kernelMatrix:Ss,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:at,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:at,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:at,overlineThickness:at,paintOrder:null,panose1:null,path:null,pathLength:at,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:kn,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:at,pointsAtY:at,pointsAtZ:at,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Ss,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Ss,rev:Ss,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Ss,requiredFeatures:Ss,requiredFonts:Ss,requiredFormats:Ss,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:at,specularExponent:at,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:at,strikethroughThickness:at,string:null,stroke:null,strokeDashArray:Ss,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:at,strokeOpacity:at,strokeWidth:null,style:null,surfaceScale:at,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Ss,tabIndex:at,tableValues:null,target:null,targetX:at,targetY:at,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Ss,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:at,underlineThickness:at,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:at,values:null,vAlphabetic:at,vMathematical:at,vectorEffect:null,vHanging:at,vIdeographic:at,version:null,vertAdvY:at,vertOriginX:at,vertOriginY:at,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:at,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Nf}),Cf=za({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,n){return"xlink:"+n.slice(5).toLowerCase()}}),Ef=za({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Sf}),_f=za({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,n){return"xml:"+n.slice(3).toLowerCase()}}),p0={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"},f0=/[A-Z]/g,_m=/-[a-z]/g,g0=/^data[-\w.:]+$/i;function b0(e,n){const s=Qc(n);let i=n,r=Ns;if(s in e.normal)return e.property[e.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&g0.test(n)){if(n.charAt(4)==="-"){const o=n.slice(5).replace(_m,v0);i="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=n.slice(4);if(!_m.test(o)){let l=o.replace(f0,x0);l.charAt(0)!=="-"&&(l="-"+l),n="data"+l}}r=Pd}return new r(i,n)}function x0(e){return"-"+e.toLowerCase()}function v0(e){return e.charAt(1).toUpperCase()}const y0=jf([kf,m0,Cf,Ef,_f],"html"),Id=jf([kf,h0,Cf,Ef,_f],"svg");function w0(e){return e.join(" ").trim()}var da={},Kl,Mm;function j0(){if(Mm)return Kl;Mm=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,n=/\n/g,s=/^\s*/,i=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,r=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,l=/^[;\s]*/,c=/^\s+|\s+$/g,u=`
|
|
624
|
-
`,d="/",m="*",h="",f="comment",p="declaration";function g(v,x){if(typeof v!="string")throw new TypeError("First argument must be a string");if(!v)return[];x=x||{};var y=1,j=1;function E(M){var T=M.match(n);T&&(y+=T.length);var D=M.lastIndexOf(u);j=~D?M.length-D:j+M.length}function C(){var M={line:y,column:j};return function(T){return T.position=new w(M),O(),T}}function w(M){this.start=M,this.end={line:y,column:j},this.source=x.source}w.prototype.content=v;function R(M){var T=new Error(x.source+":"+y+":"+j+": "+M);if(T.reason=M,T.filename=x.source,T.line=y,T.column=j,T.source=v,!x.silent)throw T}function S(M){var T=M.exec(v);if(T){var D=T[0];return E(D),v=v.slice(D.length),T}}function O(){S(s)}function _(M){var T;for(M=M||[];T=P();)T!==!1&&M.push(T);return M}function P(){var M=C();if(!(d!=v.charAt(0)||m!=v.charAt(1))){for(var T=2;h!=v.charAt(T)&&(m!=v.charAt(T)||d!=v.charAt(T+1));)++T;if(T+=2,h===v.charAt(T-1))return R("End of comment missing");var D=v.slice(2,T-2);return j+=2,E(D),v=v.slice(T),j+=2,M({type:f,comment:D})}}function U(){var M=C(),T=S(i);if(T){if(P(),!S(r))return R("property missing ':'");var D=S(o),K=M({type:p,property:b(T[0].replace(e,h)),value:D?b(D[0].replace(e,h)):h});return S(l),K}}function G(){var M=[];_(M);for(var T;T=U();)T!==!1&&(M.push(T),_(M));return M}return O(),G()}function b(v){return v?v.replace(c,h):h}return Kl=g,Kl}var Am;function k0(){if(Am)return da;Am=1;var e=da&&da.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(da,"__esModule",{value:!0}),da.default=s;const n=e(j0());function s(i,r){let o=null;if(!i||typeof i!="string")return o;const l=(0,n.default)(i),c=typeof r=="function";return l.forEach(u=>{if(u.type!=="declaration")return;const{property:d,value:m}=u;c?r(d,m,u):m&&(o=o||{},o[d]=m)}),o}return da}var Ya={},Rm;function N0(){if(Rm)return Ya;Rm=1,Object.defineProperty(Ya,"__esModule",{value:!0}),Ya.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,n=/-([a-z])/g,s=/^[^-]+$/,i=/^-(webkit|moz|ms|o|khtml)-/,r=/^-(ms)-/,o=function(d){return!d||s.test(d)||e.test(d)},l=function(d,m){return m.toUpperCase()},c=function(d,m){return"".concat(m,"-")},u=function(d,m){return m===void 0&&(m={}),o(d)?d:(d=d.toLowerCase(),m.reactCompat?d=d.replace(r,c):d=d.replace(i,c),d.replace(n,l))};return Ya.camelCase=u,Ya}var Qa,Tm;function S0(){if(Tm)return Qa;Tm=1;var e=Qa&&Qa.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},n=e(k0()),s=N0();function i(r,o){var l={};return!r||typeof r!="string"||(0,n.default)(r,function(c,u){c&&u&&(l[(0,s.camelCase)(c,o)]=u)}),l}return i.default=i,Qa=i,Qa}var C0=S0();const E0=vp(C0),Mf=Af("end"),$d=Af("start");function Af(e){return n;function n(s){const i=s&&s.position&&s.position[e]||{};if(typeof i.line=="number"&&i.line>0&&typeof i.column=="number"&&i.column>0)return{line:i.line,column:i.column,offset:typeof i.offset=="number"&&i.offset>-1?i.offset:void 0}}}function _0(e){const n=$d(e),s=Mf(e);if(n&&s)return{start:n,end:s}}function vr(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Pm(e.position):"start"in e||"end"in e?Pm(e):"line"in e||"column"in e?ed(e):""}function ed(e){return Im(e&&e.line)+":"+Im(e&&e.column)}function Pm(e){return ed(e&&e.start)+"-"+ed(e&&e.end)}function Im(e){return e&&typeof e=="number"?e:1}class us extends Error{constructor(n,s,i){super(),typeof s=="string"&&(i=s,s=void 0);let r="",o={},l=!1;if(s&&("line"in s&&"column"in s?o={place:s}:"start"in s&&"end"in s?o={place:s}:"type"in s?o={ancestors:[s],place:s.position}:o={...s}),typeof n=="string"?r=n:!o.cause&&n&&(l=!0,r=n.message,o.cause=n),!o.ruleId&&!o.source&&typeof i=="string"){const u=i.indexOf(":");u===-1?o.ruleId=i:(o.source=i.slice(0,u),o.ruleId=i.slice(u+1))}if(!o.place&&o.ancestors&&o.ancestors){const u=o.ancestors[o.ancestors.length-1];u&&(o.place=u.position)}const c=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=c?c.column:void 0,this.fatal=void 0,this.file="",this.message=r,this.line=c?c.line:void 0,this.name=vr(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=l&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}us.prototype.file="";us.prototype.name="";us.prototype.reason="";us.prototype.message="";us.prototype.stack="";us.prototype.column=void 0;us.prototype.line=void 0;us.prototype.ancestors=void 0;us.prototype.cause=void 0;us.prototype.fatal=void 0;us.prototype.place=void 0;us.prototype.ruleId=void 0;us.prototype.source=void 0;const Dd={}.hasOwnProperty,M0=new Map,A0=/[A-Z]/g,R0=new Set(["table","tbody","thead","tfoot","tr"]),T0=new Set(["td","th"]),Rf="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function P0(e,n){if(!n||n.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const s=n.filePath||void 0;let i;if(n.development){if(typeof n.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");i=U0(s,n.jsxDEV)}else{if(typeof n.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof n.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");i=F0(s,n.jsx,n.jsxs)}const r={Fragment:n.Fragment,ancestors:[],components:n.components||{},create:i,elementAttributeNameCase:n.elementAttributeNameCase||"react",evaluater:n.createEvaluater?n.createEvaluater():void 0,filePath:s,ignoreInvalidStyle:n.ignoreInvalidStyle||!1,passKeys:n.passKeys!==!1,passNode:n.passNode||!1,schema:n.space==="svg"?Id:y0,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},o=Tf(r,e,void 0);return o&&typeof o!="string"?o:r.create(e,r.Fragment,{children:o||void 0},void 0)}function Tf(e,n,s){if(n.type==="element")return I0(e,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return $0(e,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return L0(e,n,s);if(n.type==="mdxjsEsm")return D0(e,n);if(n.type==="root")return z0(e,n,s);if(n.type==="text")return O0(e,n)}function I0(e,n,s){const i=e.schema;let r=i;n.tagName.toLowerCase()==="svg"&&i.space==="html"&&(r=Id,e.schema=r),e.ancestors.push(n);const o=If(e,n.tagName,!1),l=B0(e,n);let c=zd(e,n);return R0.has(n.tagName)&&(c=c.filter(function(u){return typeof u=="string"?!d0(u):!0})),Pf(e,l,o,n),Ld(l,c),e.ancestors.pop(),e.schema=i,e.create(n,o,l,s)}function $0(e,n){if(n.data&&n.data.estree&&e.evaluater){const i=n.data.estree.body[0];return i.type,e.evaluater.evaluateExpression(i.expression)}Rr(e,n.position)}function D0(e,n){if(n.data&&n.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(n.data.estree);Rr(e,n.position)}function L0(e,n,s){const i=e.schema;let r=i;n.name==="svg"&&i.space==="html"&&(r=Id,e.schema=r),e.ancestors.push(n);const o=n.name===null?e.Fragment:If(e,n.name,!0),l=H0(e,n),c=zd(e,n);return Pf(e,l,o,n),Ld(l,c),e.ancestors.pop(),e.schema=i,e.create(n,o,l,s)}function z0(e,n,s){const i={};return Ld(i,zd(e,n)),e.create(n,e.Fragment,i,s)}function O0(e,n){return n.value}function Pf(e,n,s,i){typeof s!="string"&&s!==e.Fragment&&e.passNode&&(n.node=i)}function Ld(e,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(e.children=s)}}function F0(e,n,s){return i;function i(r,o,l,c){const d=Array.isArray(l.children)?s:n;return c?d(o,l,c):d(o,l)}}function U0(e,n){return s;function s(i,r,o,l){const c=Array.isArray(o.children),u=$d(i);return n(r,o,l,c,{columnNumber:u?u.column-1:void 0,fileName:e,lineNumber:u?u.line:void 0},void 0)}}function B0(e,n){const s={};let i,r;for(r in n.properties)if(r!=="children"&&Dd.call(n.properties,r)){const o=q0(e,r,n.properties[r]);if(o){const[l,c]=o;e.tableCellAlignToStyle&&l==="align"&&typeof c=="string"&&T0.has(n.tagName)?i=c:s[l]=c}}if(i){const o=s.style||(s.style={});o[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=i}return s}function H0(e,n){const s={};for(const i of n.attributes)if(i.type==="mdxJsxExpressionAttribute")if(i.data&&i.data.estree&&e.evaluater){const o=i.data.estree.body[0];o.type;const l=o.expression;l.type;const c=l.properties[0];c.type,Object.assign(s,e.evaluater.evaluateExpression(c.argument))}else Rr(e,n.position);else{const r=i.name;let o;if(i.value&&typeof i.value=="object")if(i.value.data&&i.value.data.estree&&e.evaluater){const c=i.value.data.estree.body[0];c.type,o=e.evaluater.evaluateExpression(c.expression)}else Rr(e,n.position);else o=i.value===null?!0:i.value;s[r]=o}return s}function zd(e,n){const s=[];let i=-1;const r=e.passKeys?new Map:M0;for(;++i<n.children.length;){const o=n.children[i];let l;if(e.passKeys){const u=o.type==="element"?o.tagName:o.type==="mdxJsxFlowElement"||o.type==="mdxJsxTextElement"?o.name:void 0;if(u){const d=r.get(u)||0;l=u+"-"+d,r.set(u,d+1)}}const c=Tf(e,o,l);c!==void 0&&s.push(c)}return s}function q0(e,n,s){const i=b0(e.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=i.commaSeparated?a0(s):w0(s)),i.property==="style"){let r=typeof s=="object"?s:V0(e,String(s));return e.stylePropertyNameCase==="css"&&(r=W0(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&i.space?p0[i.property]||i.property:i.attribute,s]}}function V0(e,n){try{return E0(n,{reactCompat:!0})}catch(s){if(e.ignoreInvalidStyle)return{};const i=s,r=new us("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:i,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw r.file=e.filePath||void 0,r.url=Rf+"#cannot-parse-style-attribute",r}}function If(e,n,s){let i;if(!s)i={type:"Literal",value:n};else if(n.includes(".")){const r=n.split(".");let o=-1,l;for(;++o<r.length;){const c=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}i=l}else i=Sm(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(i.type==="Literal"){const r=i.value;return Dd.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(i);Rr(e)}function Rr(e,n){const s=new us("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:n,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw s.file=e.filePath||void 0,s.url=Rf+"#cannot-handle-mdx-estrees-without-createevaluater",s}function W0(e){const n={};let s;for(s in e)Dd.call(e,s)&&(n[K0(s)]=e[s]);return n}function K0(e){let n=e.replace(A0,G0);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function G0(e){return"-"+e.toLowerCase()}const Gl={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"]},J0={};function Od(e,n){const s=J0,i=typeof s.includeImageAlt=="boolean"?s.includeImageAlt:!0,r=typeof s.includeHtml=="boolean"?s.includeHtml:!0;return $f(e,i,r)}function $f(e,n,s){if(Y0(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 i=[];let r=-1;for(;++r<e.length;)i[r]=$f(e[r],n,s);return i.join("")}function Y0(e){return!!(e&&typeof e=="object")}const Dm=document.createElement("i");function Fd(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 Ms(e,n,s,i){const r=e.length;let o=0,l;if(n<0?n=-n>r?0:r+n:n=n>r?r:n,s=s>0?s:0,i.length<1e4)l=Array.from(i),l.unshift(n,s),e.splice(...l);else for(s&&e.splice(n,s);o<i.length;)l=i.slice(o,o+1e4),l.unshift(n,0),e.splice(...l),o+=1e4,n+=1e4}function $s(e,n){return e.length>0?(Ms(e,e.length,0,n),e):n}const Lm={}.hasOwnProperty;function Df(e){const n={};let s=-1;for(;++s<e.length;)Q0(n,e[s]);return n}function Q0(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];X0(r[l],Array.isArray(c)?c:c?[c]:[])}}}function X0(e,n){let s=-1;const i=[];for(;++s<n.length;)(n[s].add==="after"?e:i).push(n[s]);Ms(e,0,0,i)}function Lf(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 Ws(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const ps=Ai(/[A-Za-z]/),ls=Ai(/[\dA-Za-z]/),Z0=Ai(/[#-'*+\--9=?A-Z^-~]/);function Wo(e){return e!==null&&(e<32||e===127)}const td=Ai(/\d/),eC=Ai(/[\dA-Fa-f]/),tC=Ai(/[!-/:-@[-`{-~]/);function Ct(e){return e!==null&&e<-2}function yn(e){return e!==null&&(e<0||e===32)}function Qt(e){return e===-2||e===-1||e===32}const fl=Ai(/\p{P}|\p{S}/u),Gi=Ai(/\s/);function Ai(e){return n;function n(s){return s!==null&&s>-1&&e.test(String.fromCharCode(s))}}function Oa(e){const n=[];let s=-1,i=0,r=0;for(;++s<e.length;){const o=e.charCodeAt(s);let l="";if(o===37&&ls(e.charCodeAt(s+1))&&ls(e.charCodeAt(s+2)))r=2;else if(o<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(o))||(l=String.fromCharCode(o));else if(o>55295&&o<57344){const c=e.charCodeAt(s+1);o<56320&&c>56319&&c<57344?(l=String.fromCharCode(o,c),r=1):l="�"}else l=String.fromCharCode(o);l&&(n.push(e.slice(i,s),encodeURIComponent(l)),i=s+r+1,l=""),r&&(s+=r,r=0)}return n.join("")+e.slice(i)}function tn(e,n,s,i){const r=i?i-1:Number.POSITIVE_INFINITY;let o=0;return l;function l(u){return Qt(u)?(e.enter(s),c(u)):n(u)}function c(u){return Qt(u)&&o++<r?(e.consume(u),c):(e.exit(s),n(u))}}const nC={tokenize:sC};function sC(e){const n=e.attempt(this.parser.constructs.contentInitial,i,r);let s;return n;function i(c){if(c===null){e.consume(c);return}return e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),tn(e,n,"linePrefix")}function r(c){return e.enter("paragraph"),o(c)}function o(c){const u=e.enter("chunkText",{contentType:"text",previous:s});return s&&(s.next=u),s=u,l(c)}function l(c){if(c===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(c);return}return Ct(c)?(e.consume(c),e.exit("chunkText"),o):(e.consume(c),l)}}const iC={tokenize:aC},zm={tokenize:rC};function aC(e){const n=this,s=[];let i=0,r,o,l;return c;function c(j){if(i<s.length){const E=s[i];return n.containerState=E[1],e.attempt(E[0].continuation,u,d)(j)}return d(j)}function u(j){if(i++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,r&&y();const E=n.events.length;let C=E,w;for(;C--;)if(n.events[C][0]==="exit"&&n.events[C][1].type==="chunkFlow"){w=n.events[C][1].end;break}x(i);let R=E;for(;R<n.events.length;)n.events[R][1].end={...w},R++;return Ms(n.events,C+1,0,n.events.slice(E)),n.events.length=R,d(j)}return c(j)}function d(j){if(i===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(zm,m,h)(j)}function m(j){return r&&y(),x(i),f(j)}function h(j){return n.parser.lazy[n.now().line]=i!==s.length,l=n.now().offset,g(j)}function f(j){return n.containerState={},e.attempt(zm,p,g)(j)}function p(j){return i++,s.push([n.currentConstruct,n.containerState]),f(j)}function g(j){if(j===null){r&&y(),x(0),e.consume(j);return}return r=r||n.parser.flow(n.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:o}),b(j)}function b(j){if(j===null){v(e.exit("chunkFlow"),!0),x(0),e.consume(j);return}return Ct(j)?(e.consume(j),v(e.exit("chunkFlow")),i=0,n.interrupt=void 0,c):(e.consume(j),b)}function v(j,E){const C=n.sliceStream(j);if(E&&C.push(null),j.previous=o,o&&(o.next=j),o=j,r.defineSkip(j.start),r.write(C),n.parser.lazy[j.start.line]){let w=r.events.length;for(;w--;)if(r.events[w][1].start.offset<l&&(!r.events[w][1].end||r.events[w][1].end.offset>l))return;const R=n.events.length;let S=R,O,_;for(;S--;)if(n.events[S][0]==="exit"&&n.events[S][1].type==="chunkFlow"){if(O){_=n.events[S][1].end;break}O=!0}for(x(i),w=R;w<n.events.length;)n.events[w][1].end={..._},w++;Ms(n.events,S+1,0,n.events.slice(R)),n.events.length=w}}function x(j){let E=s.length;for(;E-- >j;){const C=s[E];n.containerState=C[1],C[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 rC(e,n,s){return tn(e,e.attempt(this.parser.constructs.document,n,s),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Na(e){if(e===null||yn(e)||Gi(e))return 1;if(fl(e))return 2}function gl(e,n,s){const i=[];let r=-1;for(;++r<e.length;){const o=e[r].resolveAll;o&&!i.includes(o)&&(n=o(n,s),i.push(o))}return n}const nd={name:"attention",resolveAll:oC,tokenize:lC};function oC(e,n){let s=-1,i,r,o,l,c,u,d,m;for(;++s<e.length;)if(e[s][0]==="enter"&&e[s][1].type==="attentionSequence"&&e[s][1]._close){for(i=s;i--;)if(e[i][0]==="exit"&&e[i][1].type==="attentionSequence"&&e[i][1]._open&&n.sliceSerialize(e[i][1]).charCodeAt(0)===n.sliceSerialize(e[s][1]).charCodeAt(0)){if((e[i][1]._close||e[s][1]._open)&&(e[s][1].end.offset-e[s][1].start.offset)%3&&!((e[i][1].end.offset-e[i][1].start.offset+e[s][1].end.offset-e[s][1].start.offset)%3))continue;u=e[i][1].end.offset-e[i][1].start.offset>1&&e[s][1].end.offset-e[s][1].start.offset>1?2:1;const h={...e[i][1].end},f={...e[s][1].start};Om(h,-u),Om(f,u),l={type:u>1?"strongSequence":"emphasisSequence",start:h,end:{...e[i][1].end}},c={type:u>1?"strongSequence":"emphasisSequence",start:{...e[s][1].start},end:f},o={type:u>1?"strongText":"emphasisText",start:{...e[i][1].end},end:{...e[s][1].start}},r={type:u>1?"strong":"emphasis",start:{...l.start},end:{...c.end}},e[i][1].end={...l.start},e[s][1].start={...c.end},d=[],e[i][1].end.offset-e[i][1].start.offset&&(d=$s(d,[["enter",e[i][1],n],["exit",e[i][1],n]])),d=$s(d,[["enter",r,n],["enter",l,n],["exit",l,n],["enter",o,n]]),d=$s(d,gl(n.parser.constructs.insideSpan.null,e.slice(i+1,s),n)),d=$s(d,[["exit",o,n],["enter",c,n],["exit",c,n],["exit",r,n]]),e[s][1].end.offset-e[s][1].start.offset?(m=2,d=$s(d,[["enter",e[s][1],n],["exit",e[s][1],n]])):m=0,Ms(e,i-1,s-i+3,d),s=i+d.length-m-2;break}}for(s=-1;++s<e.length;)e[s][1].type==="attentionSequence"&&(e[s][1].type="data");return e}function lC(e,n){const s=this.parser.constructs.attentionMarkers.null,i=this.previous,r=Na(i);let o;return l;function l(u){return o=u,e.enter("attentionSequence"),c(u)}function c(u){if(u===o)return e.consume(u),c;const d=e.exit("attentionSequence"),m=Na(u),h=!m||m===2&&r||s.includes(u),f=!r||r===2&&m||s.includes(i);return d._open=!!(o===42?h:h&&(r||!f)),d._close=!!(o===42?f:f&&(m||!h)),n(u)}}function Om(e,n){e.column+=n,e.offset+=n,e._bufferIndex+=n}const cC={name:"autolink",tokenize:dC};function dC(e,n,s){let i=0;return r;function r(p){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),o}function o(p){return ps(p)?(e.consume(p),l):p===64?s(p):d(p)}function l(p){return p===43||p===45||p===46||ls(p)?(i=1,c(p)):d(p)}function c(p){return p===58?(e.consume(p),i=0,u):(p===43||p===45||p===46||ls(p))&&i++<32?(e.consume(p),c):(i=0,d(p))}function u(p){return p===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.exit("autolink"),n):p===null||p===32||p===60||Wo(p)?s(p):(e.consume(p),u)}function d(p){return p===64?(e.consume(p),m):Z0(p)?(e.consume(p),d):s(p)}function m(p){return ls(p)?h(p):s(p)}function h(p){return p===46?(e.consume(p),i=0,m):p===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.exit("autolink"),n):f(p)}function f(p){if((p===45||ls(p))&&i++<63){const g=p===45?f:h;return e.consume(p),g}return s(p)}}const Wr={partial:!0,tokenize:uC};function uC(e,n,s){return i;function i(o){return Qt(o)?tn(e,r,"linePrefix")(o):r(o)}function r(o){return o===null||Ct(o)?n(o):s(o)}}const zf={continuation:{tokenize:hC},exit:pC,name:"blockQuote",tokenize:mC};function mC(e,n,s){const i=this;return r;function r(l){if(l===62){const c=i.containerState;return c.open||(e.enter("blockQuote",{_container:!0}),c.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(l),e.exit("blockQuoteMarker"),o}return s(l)}function o(l){return Qt(l)?(e.enter("blockQuotePrefixWhitespace"),e.consume(l),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),n):(e.exit("blockQuotePrefix"),n(l))}}function hC(e,n,s){const i=this;return r;function r(l){return Qt(l)?tn(e,o,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l):o(l)}function o(l){return e.attempt(zf,n,s)(l)}}function pC(e){e.exit("blockQuote")}const Of={name:"characterEscape",tokenize:fC};function fC(e,n,s){return i;function i(o){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(o),e.exit("escapeMarker"),r}function r(o){return tC(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),n):s(o)}}const Ff={name:"characterReference",tokenize:gC};function gC(e,n,s){const i=this;let r=0,o,l;return c;function c(h){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(h),e.exit("characterReferenceMarker"),u}function u(h){return h===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(h),e.exit("characterReferenceMarkerNumeric"),d):(e.enter("characterReferenceValue"),o=31,l=ls,m(h))}function d(h){return h===88||h===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(h),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),o=6,l=eC,m):(e.enter("characterReferenceValue"),o=7,l=td,m(h))}function m(h){if(h===59&&r){const f=e.exit("characterReferenceValue");return l===ls&&!Fd(i.sliceSerialize(f))?s(h):(e.enter("characterReferenceMarker"),e.consume(h),e.exit("characterReferenceMarker"),e.exit("characterReference"),n)}return l(h)&&r++<o?(e.consume(h),m):s(h)}}const Fm={partial:!0,tokenize:xC},Um={concrete:!0,name:"codeFenced",tokenize:bC};function bC(e,n,s){const i=this,r={partial:!0,tokenize:C};let o=0,l=0,c;return u;function u(w){return d(w)}function d(w){const R=i.events[i.events.length-1];return o=R&&R[1].type==="linePrefix"?R[2].sliceSerialize(R[1],!0).length:0,c=w,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),m(w)}function m(w){return w===c?(l++,e.consume(w),m):l<3?s(w):(e.exit("codeFencedFenceSequence"),Qt(w)?tn(e,h,"whitespace")(w):h(w))}function h(w){return w===null||Ct(w)?(e.exit("codeFencedFence"),i.interrupt?n(w):e.check(Fm,b,E)(w)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),f(w))}function f(w){return w===null||Ct(w)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),h(w)):Qt(w)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),tn(e,p,"whitespace")(w)):w===96&&w===c?s(w):(e.consume(w),f)}function p(w){return w===null||Ct(w)?h(w):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(w))}function g(w){return w===null||Ct(w)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),h(w)):w===96&&w===c?s(w):(e.consume(w),g)}function b(w){return e.attempt(r,E,v)(w)}function v(w){return e.enter("lineEnding"),e.consume(w),e.exit("lineEnding"),x}function x(w){return o>0&&Qt(w)?tn(e,y,"linePrefix",o+1)(w):y(w)}function y(w){return w===null||Ct(w)?e.check(Fm,b,E)(w):(e.enter("codeFlowValue"),j(w))}function j(w){return w===null||Ct(w)?(e.exit("codeFlowValue"),y(w)):(e.consume(w),j)}function E(w){return e.exit("codeFenced"),n(w)}function C(w,R,S){let O=0;return _;function _(T){return w.enter("lineEnding"),w.consume(T),w.exit("lineEnding"),P}function P(T){return w.enter("codeFencedFence"),Qt(T)?tn(w,U,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(T):U(T)}function U(T){return T===c?(w.enter("codeFencedFenceSequence"),G(T)):S(T)}function G(T){return T===c?(O++,w.consume(T),G):O>=l?(w.exit("codeFencedFenceSequence"),Qt(T)?tn(w,M,"whitespace")(T):M(T)):S(T)}function M(T){return T===null||Ct(T)?(w.exit("codeFencedFence"),R(T)):S(T)}}}function xC(e,n,s){const i=this;return r;function r(l){return l===null?s(l):(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),o)}function o(l){return i.parser.lazy[i.now().line]?s(l):n(l)}}const Jl={name:"codeIndented",tokenize:yC},vC={partial:!0,tokenize:wC};function yC(e,n,s){const i=this;return r;function r(d){return e.enter("codeIndented"),tn(e,o,"linePrefix",5)(d)}function o(d){const m=i.events[i.events.length-1];return m&&m[1].type==="linePrefix"&&m[2].sliceSerialize(m[1],!0).length>=4?l(d):s(d)}function l(d){return d===null?u(d):Ct(d)?e.attempt(vC,l,u)(d):(e.enter("codeFlowValue"),c(d))}function c(d){return d===null||Ct(d)?(e.exit("codeFlowValue"),l(d)):(e.consume(d),c)}function u(d){return e.exit("codeIndented"),n(d)}}function wC(e,n,s){const i=this;return r;function r(l){return i.parser.lazy[i.now().line]?s(l):Ct(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),r):tn(e,o,"linePrefix",5)(l)}function o(l){const c=i.events[i.events.length-1];return c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?n(l):Ct(l)?r(l):s(l)}}const jC={name:"codeText",previous:NC,resolve:kC,tokenize:SC};function kC(e){let n=e.length-4,s=3,i,r;if((e[s][1].type==="lineEnding"||e[s][1].type==="space")&&(e[n][1].type==="lineEnding"||e[n][1].type==="space")){for(i=s;++i<n;)if(e[i][1].type==="codeTextData"){e[s][1].type="codeTextPadding",e[n][1].type="codeTextPadding",s+=2,n-=2;break}}for(i=s-1,n++;++i<=n;)r===void 0?i!==n&&e[i][1].type!=="lineEnding"&&(r=i):(i===n||e[i][1].type==="lineEnding")&&(e[r][1].type="codeTextData",i!==r+2&&(e[r][1].end=e[i-1][1].end,e.splice(r+2,i-r-2),n-=i-r-2,i=r+2),r=void 0);return e}function NC(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function SC(e,n,s){let i=0,r,o;return l;function l(h){return e.enter("codeText"),e.enter("codeTextSequence"),c(h)}function c(h){return h===96?(e.consume(h),i++,c):(e.exit("codeTextSequence"),u(h))}function u(h){return h===null?s(h):h===32?(e.enter("space"),e.consume(h),e.exit("space"),u):h===96?(o=e.enter("codeTextSequence"),r=0,m(h)):Ct(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),u):(e.enter("codeTextData"),d(h))}function d(h){return h===null||h===32||h===96||Ct(h)?(e.exit("codeTextData"),u(h)):(e.consume(h),d)}function m(h){return h===96?(e.consume(h),r++,m):r===i?(e.exit("codeTextSequence"),e.exit("codeText"),n(h)):(o.type="codeTextData",d(h))}}class CC{constructor(n){this.left=n?[...n]:[],this.right=[]}get(n){if(n<0||n>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+n+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return n<this.left.length?this.left[n]:this.right[this.right.length-n+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(n,s){const i=s??Number.POSITIVE_INFINITY;return i<this.left.length?this.left.slice(n,i):n>this.left.length?this.right.slice(this.right.length-i+this.left.length,this.right.length-n+this.left.length).reverse():this.left.slice(n).concat(this.right.slice(this.right.length-i+this.left.length).reverse())}splice(n,s,i){const r=s||0;this.setCursor(Math.trunc(n));const o=this.right.splice(this.right.length-r,Number.POSITIVE_INFINITY);return i&&Xa(this.left,i),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(n){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(n)}pushMany(n){this.setCursor(Number.POSITIVE_INFINITY),Xa(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),Xa(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);Xa(this.right,s.reverse())}else{const s=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);Xa(this.left,s.reverse())}}}function Xa(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 Uf(e){const n={};let s=-1,i,r,o,l,c,u,d;const m=new CC(e);for(;++s<m.length;){for(;s in n;)s=n[s];if(i=m.get(s),s&&i[1].type==="chunkFlow"&&m.get(s-1)[1].type==="listItemPrefix"&&(u=i[1]._tokenizer.events,o=0,o<u.length&&u[o][1].type==="lineEndingBlank"&&(o+=2),o<u.length&&u[o][1].type==="content"))for(;++o<u.length&&u[o][1].type!=="content";)u[o][1].type==="chunkText"&&(u[o][1]._isInFirstContentOfListItem=!0,o++);if(i[0]==="enter")i[1].contentType&&(Object.assign(n,EC(m,s)),s=n[s],d=!0);else if(i[1]._container){for(o=s,r=void 0;o--;)if(l=m.get(o),l[1].type==="lineEnding"||l[1].type==="lineEndingBlank")l[0]==="enter"&&(r&&(m.get(r)[1].type="lineEndingBlank"),l[1].type="lineEnding",r=o);else if(!(l[1].type==="linePrefix"||l[1].type==="listItemIndent"))break;r&&(i[1].end={...m.get(r)[1].start},c=m.slice(r,s),c.unshift(i),m.splice(r,s-r+1,c))}}return Ms(e,0,Number.POSITIVE_INFINITY,m.slice(0)),!d}function EC(e,n){const s=e.get(n)[1],i=e.get(n)[2];let r=n-1;const o=[];let l=s._tokenizer;l||(l=i.parser[s.contentType](s.start),s._contentTypeTextTrailing&&(l._contentTypeTextTrailing=!0));const c=l.events,u=[],d={};let m,h,f=-1,p=s,g=0,b=0;const v=[b];for(;p;){for(;e.get(++r)[1]!==p;);o.push(r),p._tokenizer||(m=i.sliceStream(p),p.next||m.push(null),h&&l.defineSkip(p.start),p._isInFirstContentOfListItem&&(l._gfmTasklistFirstContentOfListItem=!0),l.write(m),p._isInFirstContentOfListItem&&(l._gfmTasklistFirstContentOfListItem=void 0)),h=p,p=p.next}for(p=s;++f<c.length;)c[f][0]==="exit"&&c[f-1][0]==="enter"&&c[f][1].type===c[f-1][1].type&&c[f][1].start.line!==c[f][1].end.line&&(b=f+1,v.push(b),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(l.events=[],p?(p._tokenizer=void 0,p.previous=void 0):v.pop(),f=v.length;f--;){const x=c.slice(v[f],v[f+1]),y=o.pop();u.push([y,y+x.length-1]),e.splice(y,2,x)}for(u.reverse(),f=-1;++f<u.length;)d[g+u[f][0]]=g+u[f][1],g+=u[f][1]-u[f][0]-1;return d}const _C={resolve:AC,tokenize:RC},MC={partial:!0,tokenize:TC};function AC(e){return Uf(e),e}function RC(e,n){let s;return i;function i(c){return e.enter("content"),s=e.enter("chunkContent",{contentType:"content"}),r(c)}function r(c){return c===null?o(c):Ct(c)?e.check(MC,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 TC(e,n,s){const i=this;return r;function r(l){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),tn(e,o,"linePrefix")}function o(l){if(l===null||Ct(l))return s(l);const c=i.events[i.events.length-1];return!i.parser.constructs.disable.null.includes("codeIndented")&&c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?n(l):e.interrupt(i.parser.constructs.flow,s,n)(l)}}function Bf(e,n,s,i,r,o,l,c,u){const d=u||Number.POSITIVE_INFINITY;let m=0;return h;function h(x){return x===60?(e.enter(i),e.enter(r),e.enter(o),e.consume(x),e.exit(o),f):x===null||x===32||x===41||Wo(x)?s(x):(e.enter(i),e.enter(l),e.enter(c),e.enter("chunkString",{contentType:"string"}),b(x))}function f(x){return x===62?(e.enter(o),e.consume(x),e.exit(o),e.exit(r),e.exit(i),n):(e.enter(c),e.enter("chunkString",{contentType:"string"}),p(x))}function p(x){return x===62?(e.exit("chunkString"),e.exit(c),f(x)):x===null||x===60||Ct(x)?s(x):(e.consume(x),x===92?g:p)}function g(x){return x===60||x===62||x===92?(e.consume(x),p):p(x)}function b(x){return!m&&(x===null||x===41||yn(x))?(e.exit("chunkString"),e.exit(c),e.exit(l),e.exit(i),n(x)):m<d&&x===40?(e.consume(x),m++,b):x===41?(e.consume(x),m--,b):x===null||x===32||x===40||Wo(x)?s(x):(e.consume(x),x===92?v:b)}function v(x){return x===40||x===41||x===92?(e.consume(x),b):b(x)}}function Hf(e,n,s,i,r,o){const l=this;let c=0,u;return d;function d(p){return e.enter(i),e.enter(r),e.consume(p),e.exit(r),e.enter(o),m}function m(p){return c>999||p===null||p===91||p===93&&!u||p===94&&!c&&"_hiddenFootnoteSupport"in l.parser.constructs?s(p):p===93?(e.exit(o),e.enter(r),e.consume(p),e.exit(r),e.exit(i),n):Ct(p)?(e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),m):(e.enter("chunkString",{contentType:"string"}),h(p))}function h(p){return p===null||p===91||p===93||Ct(p)||c++>999?(e.exit("chunkString"),m(p)):(e.consume(p),u||(u=!Qt(p)),p===92?f:h)}function f(p){return p===91||p===92||p===93?(e.consume(p),c++,h):h(p)}}function qf(e,n,s,i,r,o){let l;return c;function c(f){return f===34||f===39||f===40?(e.enter(i),e.enter(r),e.consume(f),e.exit(r),l=f===40?41:f,u):s(f)}function u(f){return f===l?(e.enter(r),e.consume(f),e.exit(r),e.exit(i),n):(e.enter(o),d(f))}function d(f){return f===l?(e.exit(o),u(l)):f===null?s(f):Ct(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),tn(e,d,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),m(f))}function m(f){return f===l||f===null||Ct(f)?(e.exit("chunkString"),d(f)):(e.consume(f),f===92?h:m)}function h(f){return f===l||f===92?(e.consume(f),m):m(f)}}function yr(e,n){let s;return i;function i(r){return Ct(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),s=!0,i):Qt(r)?tn(e,i,s?"linePrefix":"lineSuffix")(r):n(r)}}const PC={name:"definition",tokenize:$C},IC={partial:!0,tokenize:DC};function $C(e,n,s){const i=this;let r;return o;function o(p){return e.enter("definition"),l(p)}function l(p){return Hf.call(i,e,c,s,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function c(p){return r=Ws(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)),p===58?(e.enter("definitionMarker"),e.consume(p),e.exit("definitionMarker"),u):s(p)}function u(p){return yn(p)?yr(e,d)(p):d(p)}function d(p){return Bf(e,m,s,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function m(p){return e.attempt(IC,h,h)(p)}function h(p){return Qt(p)?tn(e,f,"whitespace")(p):f(p)}function f(p){return p===null||Ct(p)?(e.exit("definition"),i.parser.defined.push(r),n(p)):s(p)}}function DC(e,n,s){return i;function i(c){return yn(c)?yr(e,r)(c):s(c)}function r(c){return qf(e,o,s,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function o(c){return Qt(c)?tn(e,l,"whitespace")(c):l(c)}function l(c){return c===null||Ct(c)?n(c):s(c)}}const LC={name:"hardBreakEscape",tokenize:zC};function zC(e,n,s){return i;function i(o){return e.enter("hardBreakEscape"),e.consume(o),r}function r(o){return Ct(o)?(e.exit("hardBreakEscape"),n(o)):s(o)}}const OC={name:"headingAtx",resolve:FC,tokenize:UC};function FC(e,n){let s=e.length-2,i=3,r,o;return e[i][1].type==="whitespace"&&(i+=2),s-2>i&&e[s][1].type==="whitespace"&&(s-=2),e[s][1].type==="atxHeadingSequence"&&(i===s-1||s-4>i&&e[s-2][1].type==="whitespace")&&(s-=i+1===s?2:4),s>i&&(r={type:"atxHeadingText",start:e[i][1].start,end:e[s][1].end},o={type:"chunkText",start:e[i][1].start,end:e[s][1].end,contentType:"text"},Ms(e,i,s-i+1,[["enter",r,n],["enter",o,n],["exit",o,n],["exit",r,n]])),e}function UC(e,n,s){let i=0;return r;function r(m){return e.enter("atxHeading"),o(m)}function o(m){return e.enter("atxHeadingSequence"),l(m)}function l(m){return m===35&&i++<6?(e.consume(m),l):m===null||yn(m)?(e.exit("atxHeadingSequence"),c(m)):s(m)}function c(m){return m===35?(e.enter("atxHeadingSequence"),u(m)):m===null||Ct(m)?(e.exit("atxHeading"),n(m)):Qt(m)?tn(e,c,"whitespace")(m):(e.enter("atxHeadingText"),d(m))}function u(m){return m===35?(e.consume(m),u):(e.exit("atxHeadingSequence"),c(m))}function d(m){return m===null||m===35||yn(m)?(e.exit("atxHeadingText"),c(m)):(e.consume(m),d)}}const BC=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Bm=["pre","script","style","textarea"],HC={concrete:!0,name:"htmlFlow",resolveTo:WC,tokenize:KC},qC={partial:!0,tokenize:JC},VC={partial:!0,tokenize:GC};function WC(e){let n=e.length;for(;n--&&!(e[n][0]==="enter"&&e[n][1].type==="htmlFlow"););return n>1&&e[n-2][1].type==="linePrefix"&&(e[n][1].start=e[n-2][1].start,e[n+1][1].start=e[n-2][1].start,e.splice(n-2,2)),e}function KC(e,n,s){const i=this;let r,o,l,c,u;return d;function d(k){return m(k)}function m(k){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(k),h}function h(k){return k===33?(e.consume(k),f):k===47?(e.consume(k),o=!0,b):k===63?(e.consume(k),r=3,i.interrupt?n:N):ps(k)?(e.consume(k),l=String.fromCharCode(k),v):s(k)}function f(k){return k===45?(e.consume(k),r=2,p):k===91?(e.consume(k),r=5,c=0,g):ps(k)?(e.consume(k),r=4,i.interrupt?n:N):s(k)}function p(k){return k===45?(e.consume(k),i.interrupt?n:N):s(k)}function g(k){const H="CDATA[";return k===H.charCodeAt(c++)?(e.consume(k),c===H.length?i.interrupt?n:U:g):s(k)}function b(k){return ps(k)?(e.consume(k),l=String.fromCharCode(k),v):s(k)}function v(k){if(k===null||k===47||k===62||yn(k)){const H=k===47,Q=l.toLowerCase();return!H&&!o&&Bm.includes(Q)?(r=1,i.interrupt?n(k):U(k)):BC.includes(l.toLowerCase())?(r=6,H?(e.consume(k),x):i.interrupt?n(k):U(k)):(r=7,i.interrupt&&!i.parser.lazy[i.now().line]?s(k):o?y(k):j(k))}return k===45||ls(k)?(e.consume(k),l+=String.fromCharCode(k),v):s(k)}function x(k){return k===62?(e.consume(k),i.interrupt?n:U):s(k)}function y(k){return Qt(k)?(e.consume(k),y):_(k)}function j(k){return k===47?(e.consume(k),_):k===58||k===95||ps(k)?(e.consume(k),E):Qt(k)?(e.consume(k),j):_(k)}function E(k){return k===45||k===46||k===58||k===95||ls(k)?(e.consume(k),E):C(k)}function C(k){return k===61?(e.consume(k),w):Qt(k)?(e.consume(k),C):j(k)}function w(k){return k===null||k===60||k===61||k===62||k===96?s(k):k===34||k===39?(e.consume(k),u=k,R):Qt(k)?(e.consume(k),w):S(k)}function R(k){return k===u?(e.consume(k),u=null,O):k===null||Ct(k)?s(k):(e.consume(k),R)}function S(k){return k===null||k===34||k===39||k===47||k===60||k===61||k===62||k===96||yn(k)?C(k):(e.consume(k),S)}function O(k){return k===47||k===62||Qt(k)?j(k):s(k)}function _(k){return k===62?(e.consume(k),P):s(k)}function P(k){return k===null||Ct(k)?U(k):Qt(k)?(e.consume(k),P):s(k)}function U(k){return k===45&&r===2?(e.consume(k),D):k===60&&r===1?(e.consume(k),K):k===62&&r===4?(e.consume(k),z):k===63&&r===3?(e.consume(k),N):k===93&&r===5?(e.consume(k),te):Ct(k)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(qC,I,G)(k)):k===null||Ct(k)?(e.exit("htmlFlowData"),G(k)):(e.consume(k),U)}function G(k){return e.check(VC,M,I)(k)}function M(k){return e.enter("lineEnding"),e.consume(k),e.exit("lineEnding"),T}function T(k){return k===null||Ct(k)?G(k):(e.enter("htmlFlowData"),U(k))}function D(k){return k===45?(e.consume(k),N):U(k)}function K(k){return k===47?(e.consume(k),l="",J):U(k)}function J(k){if(k===62){const H=l.toLowerCase();return Bm.includes(H)?(e.consume(k),z):U(k)}return ps(k)&&l.length<8?(e.consume(k),l+=String.fromCharCode(k),J):U(k)}function te(k){return k===93?(e.consume(k),N):U(k)}function N(k){return k===62?(e.consume(k),z):k===45&&r===2?(e.consume(k),N):U(k)}function z(k){return k===null||Ct(k)?(e.exit("htmlFlowData"),I(k)):(e.consume(k),z)}function I(k){return e.exit("htmlFlow"),n(k)}}function GC(e,n,s){const i=this;return r;function r(l){return Ct(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),o):s(l)}function o(l){return i.parser.lazy[i.now().line]?s(l):n(l)}}function JC(e,n,s){return i;function i(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(Wr,n,s)}}const YC={name:"htmlText",tokenize:QC};function QC(e,n,s){const i=this;let r,o,l;return c;function c(N){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(N),u}function u(N){return N===33?(e.consume(N),d):N===47?(e.consume(N),C):N===63?(e.consume(N),j):ps(N)?(e.consume(N),S):s(N)}function d(N){return N===45?(e.consume(N),m):N===91?(e.consume(N),o=0,g):ps(N)?(e.consume(N),y):s(N)}function m(N){return N===45?(e.consume(N),p):s(N)}function h(N){return N===null?s(N):N===45?(e.consume(N),f):Ct(N)?(l=h,K(N)):(e.consume(N),h)}function f(N){return N===45?(e.consume(N),p):h(N)}function p(N){return N===62?D(N):N===45?f(N):h(N)}function g(N){const z="CDATA[";return N===z.charCodeAt(o++)?(e.consume(N),o===z.length?b:g):s(N)}function b(N){return N===null?s(N):N===93?(e.consume(N),v):Ct(N)?(l=b,K(N)):(e.consume(N),b)}function v(N){return N===93?(e.consume(N),x):b(N)}function x(N){return N===62?D(N):N===93?(e.consume(N),x):b(N)}function y(N){return N===null||N===62?D(N):Ct(N)?(l=y,K(N)):(e.consume(N),y)}function j(N){return N===null?s(N):N===63?(e.consume(N),E):Ct(N)?(l=j,K(N)):(e.consume(N),j)}function E(N){return N===62?D(N):j(N)}function C(N){return ps(N)?(e.consume(N),w):s(N)}function w(N){return N===45||ls(N)?(e.consume(N),w):R(N)}function R(N){return Ct(N)?(l=R,K(N)):Qt(N)?(e.consume(N),R):D(N)}function S(N){return N===45||ls(N)?(e.consume(N),S):N===47||N===62||yn(N)?O(N):s(N)}function O(N){return N===47?(e.consume(N),D):N===58||N===95||ps(N)?(e.consume(N),_):Ct(N)?(l=O,K(N)):Qt(N)?(e.consume(N),O):D(N)}function _(N){return N===45||N===46||N===58||N===95||ls(N)?(e.consume(N),_):P(N)}function P(N){return N===61?(e.consume(N),U):Ct(N)?(l=P,K(N)):Qt(N)?(e.consume(N),P):O(N)}function U(N){return N===null||N===60||N===61||N===62||N===96?s(N):N===34||N===39?(e.consume(N),r=N,G):Ct(N)?(l=U,K(N)):Qt(N)?(e.consume(N),U):(e.consume(N),M)}function G(N){return N===r?(e.consume(N),r=void 0,T):N===null?s(N):Ct(N)?(l=G,K(N)):(e.consume(N),G)}function M(N){return N===null||N===34||N===39||N===60||N===61||N===96?s(N):N===47||N===62||yn(N)?O(N):(e.consume(N),M)}function T(N){return N===47||N===62||yn(N)?O(N):s(N)}function D(N){return N===62?(e.consume(N),e.exit("htmlTextData"),e.exit("htmlText"),n):s(N)}function K(N){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(N),e.exit("lineEnding"),J}function J(N){return Qt(N)?tn(e,te,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(N):te(N)}function te(N){return e.enter("htmlTextData"),l(N)}}const Ud={name:"labelEnd",resolveAll:t2,resolveTo:n2,tokenize:s2},XC={tokenize:i2},ZC={tokenize:a2},e2={tokenize:r2};function t2(e){let n=-1;const s=[];for(;++n<e.length;){const i=e[n][1];if(s.push(e[n]),i.type==="labelImage"||i.type==="labelLink"||i.type==="labelEnd"){const r=i.type==="labelImage"?4:2;i.type="data",n+=r}}return e.length!==s.length&&Ms(e,0,e.length,s),e}function n2(e,n){let s=e.length,i=0,r,o,l,c;for(;s--;)if(r=e[s][1],o){if(r.type==="link"||r.type==="labelLink"&&r._inactive)break;e[s][0]==="enter"&&r.type==="labelLink"&&(r._inactive=!0)}else if(l){if(e[s][0]==="enter"&&(r.type==="labelImage"||r.type==="labelLink")&&!r._balanced&&(o=s,r.type!=="labelLink")){i=2;break}}else r.type==="labelEnd"&&(l=s);const u={type:e[o][1].type==="labelLink"?"link":"image",start:{...e[o][1].start},end:{...e[e.length-1][1].end}},d={type:"label",start:{...e[o][1].start},end:{...e[l][1].end}},m={type:"labelText",start:{...e[o+i+2][1].end},end:{...e[l-2][1].start}};return c=[["enter",u,n],["enter",d,n]],c=$s(c,e.slice(o+1,o+i+3)),c=$s(c,[["enter",m,n]]),c=$s(c,gl(n.parser.constructs.insideSpan.null,e.slice(o+i+4,l-3),n)),c=$s(c,[["exit",m,n],e[l-2],e[l-1],["exit",d,n]]),c=$s(c,e.slice(l+1)),c=$s(c,[["exit",u,n]]),Ms(e,o,e.length,c),e}function s2(e,n,s){const i=this;let r=i.events.length,o,l;for(;r--;)if((i.events[r][1].type==="labelImage"||i.events[r][1].type==="labelLink")&&!i.events[r][1]._balanced){o=i.events[r][1];break}return c;function c(f){return o?o._inactive?h(f):(l=i.parser.defined.includes(Ws(i.sliceSerialize({start:o.end,end:i.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(f),e.exit("labelMarker"),e.exit("labelEnd"),u):s(f)}function u(f){return f===40?e.attempt(XC,m,l?m:h)(f):f===91?e.attempt(ZC,m,l?d:h)(f):l?m(f):h(f)}function d(f){return e.attempt(e2,m,h)(f)}function m(f){return n(f)}function h(f){return o._balanced=!0,s(f)}}function i2(e,n,s){return i;function i(h){return e.enter("resource"),e.enter("resourceMarker"),e.consume(h),e.exit("resourceMarker"),r}function r(h){return yn(h)?yr(e,o)(h):o(h)}function o(h){return h===41?m(h):Bf(e,l,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function l(h){return yn(h)?yr(e,u)(h):m(h)}function c(h){return s(h)}function u(h){return h===34||h===39||h===40?qf(e,d,s,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):m(h)}function d(h){return yn(h)?yr(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 a2(e,n,s){const i=this;return r;function r(c){return Hf.call(i,e,o,l,"reference","referenceMarker","referenceString")(c)}function o(c){return i.parser.defined.includes(Ws(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)))?n(c):s(c)}function l(c){return s(c)}}function r2(e,n,s){return i;function i(o){return e.enter("reference"),e.enter("referenceMarker"),e.consume(o),e.exit("referenceMarker"),r}function r(o){return o===93?(e.enter("referenceMarker"),e.consume(o),e.exit("referenceMarker"),e.exit("reference"),n):s(o)}}const o2={name:"labelStartImage",resolveAll:Ud.resolveAll,tokenize:l2};function l2(e,n,s){const i=this;return r;function r(c){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(c),e.exit("labelImageMarker"),o}function o(c){return c===91?(e.enter("labelMarker"),e.consume(c),e.exit("labelMarker"),e.exit("labelImage"),l):s(c)}function l(c){return c===94&&"_hiddenFootnoteSupport"in i.parser.constructs?s(c):n(c)}}const c2={name:"labelStartLink",resolveAll:Ud.resolveAll,tokenize:d2};function d2(e,n,s){const i=this;return r;function r(l){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(l),e.exit("labelMarker"),e.exit("labelLink"),o}function o(l){return l===94&&"_hiddenFootnoteSupport"in i.parser.constructs?s(l):n(l)}}const Yl={name:"lineEnding",tokenize:u2};function u2(e,n){return s;function s(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),tn(e,n,"linePrefix")}}const To={name:"thematicBreak",tokenize:m2};function m2(e,n,s){let i=0,r;return o;function o(d){return e.enter("thematicBreak"),l(d)}function l(d){return r=d,c(d)}function c(d){return d===r?(e.enter("thematicBreakSequence"),u(d)):i>=3&&(d===null||Ct(d))?(e.exit("thematicBreak"),n(d)):s(d)}function u(d){return d===r?(e.consume(d),i++,u):(e.exit("thematicBreakSequence"),Qt(d)?tn(e,c,"whitespace")(d):c(d))}}const ws={continuation:{tokenize:g2},exit:x2,name:"list",tokenize:f2},h2={partial:!0,tokenize:v2},p2={partial:!0,tokenize:b2};function f2(e,n,s){const i=this,r=i.events[i.events.length-1];let o=r&&r[1].type==="linePrefix"?r[2].sliceSerialize(r[1],!0).length:0,l=0;return c;function c(p){const g=i.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(g==="listUnordered"?!i.containerState.marker||p===i.containerState.marker:td(p)){if(i.containerState.type||(i.containerState.type=g,e.enter(g,{_container:!0})),g==="listUnordered")return e.enter("listItemPrefix"),p===42||p===45?e.check(To,s,d)(p):d(p);if(!i.interrupt||p===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),u(p)}return s(p)}function u(p){return td(p)&&++l<10?(e.consume(p),u):(!i.interrupt||l<2)&&(i.containerState.marker?p===i.containerState.marker:p===41||p===46)?(e.exit("listItemValue"),d(p)):s(p)}function d(p){return e.enter("listItemMarker"),e.consume(p),e.exit("listItemMarker"),i.containerState.marker=i.containerState.marker||p,e.check(Wr,i.interrupt?s:m,e.attempt(h2,f,h))}function m(p){return i.containerState.initialBlankLine=!0,o++,f(p)}function h(p){return Qt(p)?(e.enter("listItemPrefixWhitespace"),e.consume(p),e.exit("listItemPrefixWhitespace"),f):s(p)}function f(p){return i.containerState.size=o+i.sliceSerialize(e.exit("listItemPrefix"),!0).length,n(p)}}function g2(e,n,s){const i=this;return i.containerState._closeFlow=void 0,e.check(Wr,r,o);function r(c){return i.containerState.furtherBlankLines=i.containerState.furtherBlankLines||i.containerState.initialBlankLine,tn(e,n,"listItemIndent",i.containerState.size+1)(c)}function o(c){return i.containerState.furtherBlankLines||!Qt(c)?(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,l(c)):(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,e.attempt(p2,n,l)(c))}function l(c){return i.containerState._closeFlow=!0,i.interrupt=void 0,tn(e,e.attempt(ws,n,s),"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function b2(e,n,s){const i=this;return tn(e,r,"listItemIndent",i.containerState.size+1);function r(o){const l=i.events[i.events.length-1];return l&&l[1].type==="listItemIndent"&&l[2].sliceSerialize(l[1],!0).length===i.containerState.size?n(o):s(o)}}function x2(e){e.exit(this.containerState.type)}function v2(e,n,s){const i=this;return tn(e,r,"listItemPrefixWhitespace",i.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function r(o){const l=i.events[i.events.length-1];return!Qt(o)&&l&&l[1].type==="listItemPrefixWhitespace"?n(o):s(o)}}const Hm={name:"setextUnderline",resolveTo:y2,tokenize:w2};function y2(e,n){let s=e.length,i,r,o;for(;s--;)if(e[s][0]==="enter"){if(e[s][1].type==="content"){i=s;break}e[s][1].type==="paragraph"&&(r=s)}else e[s][1].type==="content"&&e.splice(s,1),!o&&e[s][1].type==="definition"&&(o=s);const l={type:"setextHeading",start:{...e[i][1].start},end:{...e[e.length-1][1].end}};return e[r][1].type="setextHeadingText",o?(e.splice(r,0,["enter",l,n]),e.splice(o+1,0,["exit",e[i][1],n]),e[i][1].end={...e[o][1].end}):e[i][1]=l,e.push(["exit",l,n]),e}function w2(e,n,s){const i=this;let r;return o;function o(d){let m=i.events.length,h;for(;m--;)if(i.events[m][1].type!=="lineEnding"&&i.events[m][1].type!=="linePrefix"&&i.events[m][1].type!=="content"){h=i.events[m][1].type==="paragraph";break}return!i.parser.lazy[i.now().line]&&(i.interrupt||h)?(e.enter("setextHeadingLine"),r=d,l(d)):s(d)}function l(d){return e.enter("setextHeadingLineSequence"),c(d)}function c(d){return d===r?(e.consume(d),c):(e.exit("setextHeadingLineSequence"),Qt(d)?tn(e,u,"lineSuffix")(d):u(d))}function u(d){return d===null||Ct(d)?(e.exit("setextHeadingLine"),n(d)):s(d)}}const j2={tokenize:k2};function k2(e){const n=this,s=e.attempt(Wr,i,e.attempt(this.parser.constructs.flowInitial,r,tn(e,e.attempt(this.parser.constructs.flow,r,e.attempt(_C,r)),"linePrefix")));return s;function i(o){if(o===null){e.consume(o);return}return e.enter("lineEndingBlank"),e.consume(o),e.exit("lineEndingBlank"),n.currentConstruct=void 0,s}function r(o){if(o===null){e.consume(o);return}return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),n.currentConstruct=void 0,s}}const N2={resolveAll:Wf()},S2=Vf("string"),C2=Vf("text");function Vf(e){return{resolveAll:Wf(e==="text"?E2:void 0),tokenize:n};function n(s){const i=this,r=this.parser.constructs[e],o=s.attempt(r,l,c);return l;function l(m){return d(m)?o(m):c(m)}function c(m){if(m===null){s.consume(m);return}return s.enter("data"),s.consume(m),u}function u(m){return d(m)?(s.exit("data"),o(m)):(s.consume(m),u)}function d(m){if(m===null)return!0;const h=r[m];let f=-1;if(h)for(;++f<h.length;){const p=h[f];if(!p.previous||p.previous.call(i,i.previous))return!0}return!1}}}function Wf(e){return n;function n(s,i){let r=-1,o;for(;++r<=s.length;)o===void 0?s[r]&&s[r][1].type==="data"&&(o=r,r++):(!s[r]||s[r][1].type!=="data")&&(r!==o+2&&(s[o][1].end=s[r-1][1].end,s.splice(o+2,r-o-2),r=o+2),o=void 0);return e?e(s,i):s}}function E2(e,n){let s=0;for(;++s<=e.length;)if((s===e.length||e[s][1].type==="lineEnding")&&e[s-1][1].type==="data"){const i=e[s-1][1],r=n.sliceStream(i);let o=r.length,l=-1,c=0,u;for(;o--;){const d=r[o];if(typeof d=="string"){for(l=d.length;d.charCodeAt(l-1)===32;)c++,l--;if(l)break;l=-1}else if(d===-2)u=!0,c++;else if(d!==-1){o++;break}}if(n._contentTypeTextTrailing&&s===e.length&&(c=0),c){const d={type:s===e.length||u||c<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:o?l:i.start._bufferIndex+l,_index:i.start._index+o,line:i.end.line,column:i.end.column-c,offset:i.end.offset-c},end:{...i.end}};i.end={...d.start},i.start.offset===i.end.offset?Object.assign(i,d):(e.splice(s,0,["enter",d,n],["exit",d,n]),s+=2)}s++}return e}const _2={42:ws,43:ws,45:ws,48:ws,49:ws,50:ws,51:ws,52:ws,53:ws,54:ws,55:ws,56:ws,57:ws,62:zf},M2={91:PC},A2={[-2]:Jl,[-1]:Jl,32:Jl},R2={35:OC,42:To,45:[Hm,To],60:HC,61:Hm,95:To,96:Um,126:Um},T2={38:Ff,92:Of},P2={[-5]:Yl,[-4]:Yl,[-3]:Yl,33:o2,38:Ff,42:nd,60:[cC,YC],91:c2,92:[LC,Of],93:Ud,95:nd,96:jC},I2={null:[nd,N2]},$2={null:[42,95]},D2={null:[]},L2=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:$2,contentInitial:M2,disable:D2,document:_2,flow:R2,flowInitial:A2,insideSpan:I2,string:T2,text:P2},Symbol.toStringTag,{value:"Module"}));function z2(e,n,s){let i={_bufferIndex:-1,_index:0,line:s&&s.line||1,column:s&&s.column||1,offset:s&&s.offset||0};const r={},o=[];let l=[],c=[];const u={attempt:R(C),check:R(w),consume:y,enter:j,exit:E,interrupt:R(w,{interrupt:!0})},d={code:null,containerState:{},defineSkip:b,events:[],now:g,parser:e,previous:null,sliceSerialize:f,sliceStream:p,write:h};let m=n.tokenize.call(d,u);return n.resolveAll&&o.push(n),d;function h(P){return l=$s(l,P),v(),l[l.length-1]!==null?[]:(S(n,0),d.events=gl(o,d.events,d),d.events)}function f(P,U){return F2(p(P),U)}function p(P){return O2(l,P)}function g(){const{_bufferIndex:P,_index:U,line:G,column:M,offset:T}=i;return{_bufferIndex:P,_index:U,line:G,column:M,offset:T}}function b(P){r[P.line]=P.column,_()}function v(){let P;for(;i._index<l.length;){const U=l[i._index];if(typeof U=="string")for(P=i._index,i._bufferIndex<0&&(i._bufferIndex=0);i._index===P&&i._bufferIndex<U.length;)x(U.charCodeAt(i._bufferIndex));else x(U)}}function x(P){m=m(P)}function y(P){Ct(P)?(i.line++,i.column=1,i.offset+=P===-3?2:1,_()):P!==-1&&(i.column++,i.offset++),i._bufferIndex<0?i._index++:(i._bufferIndex++,i._bufferIndex===l[i._index].length&&(i._bufferIndex=-1,i._index++)),d.previous=P}function j(P,U){const G=U||{};return G.type=P,G.start=g(),d.events.push(["enter",G,d]),c.push(G),G}function E(P){const U=c.pop();return U.end=g(),d.events.push(["exit",U,d]),U}function C(P,U){S(P,U.from)}function w(P,U){U.restore()}function R(P,U){return G;function G(M,T,D){let K,J,te,N;return Array.isArray(M)?I(M):"tokenize"in M?I([M]):z(M);function z(ue){return be;function be(V){const ve=V!==null&&ue[V],B=V!==null&&ue.null,Y=[...Array.isArray(ve)?ve:ve?[ve]:[],...Array.isArray(B)?B:B?[B]:[]];return I(Y)(V)}}function I(ue){return K=ue,J=0,ue.length===0?D:k(ue[J])}function k(ue){return be;function be(V){return N=O(),te=ue,ue.partial||(d.currentConstruct=ue),ue.name&&d.parser.constructs.disable.null.includes(ue.name)?Q():ue.tokenize.call(U?Object.assign(Object.create(d),U):d,u,H,Q)(V)}}function H(ue){return P(te,N),T}function Q(ue){return N.restore(),++J<K.length?k(K[J]):D}}}function S(P,U){P.resolveAll&&!o.includes(P)&&o.push(P),P.resolve&&Ms(d.events,U,d.events.length-U,P.resolve(d.events.slice(U),d)),P.resolveTo&&(d.events=P.resolveTo(d.events,d))}function O(){const P=g(),U=d.previous,G=d.currentConstruct,M=d.events.length,T=Array.from(c);return{from:M,restore:D};function D(){i=P,d.previous=U,d.currentConstruct=G,d.events.length=M,c=T,_()}}function _(){i.line in r&&i.column<2&&(i.column=r[i.line],i.offset+=r[i.line]-1)}}function O2(e,n){const s=n.start._index,i=n.start._bufferIndex,r=n.end._index,o=n.end._bufferIndex;let l;if(s===r)l=[e[s].slice(i,o)];else{if(l=e.slice(s,r),i>-1){const c=l[0];typeof c=="string"?l[0]=c.slice(i):l.shift()}o>0&&l.push(e[r].slice(0,o))}return l}function F2(e,n){let s=-1;const i=[];let r;for(;++s<e.length;){const o=e[s];let l;if(typeof o=="string")l=o;else switch(o){case-5:{l="\r";break}case-4:{l=`
|
|
625
|
-
`;break}case-3:{l=`\r
|
|
626
|
-
`;break}case-2:{l=n?" ":" ";break}case-1:{if(!n&&r)continue;l=" ";break}default:l=String.fromCharCode(o)}r=o===-2,i.push(l)}return i.join("")}function U2(e){const i={constructs:Df([L2,...(e||{}).extensions||[]]),content:r(nC),defined:[],document:r(iC),flow:r(j2),lazy:{},string:r(S2),text:r(C2)};return i;function r(o){return l;function l(c){return z2(i,o,c)}}}function B2(e){for(;!Uf(e););return e}const qm=/[\0\t\n\r]/g;function H2(){let e=1,n="",s=!0,i;return r;function r(o,l,c){const u=[];let d,m,h,f,p;for(o=n+(typeof o=="string"?o.toString():new TextDecoder(l||void 0).decode(o)),h=0,n="",s&&(o.charCodeAt(0)===65279&&h++,s=void 0);h<o.length;){if(qm.lastIndex=h,d=qm.exec(o),f=d&&d.index!==void 0?d.index:o.length,p=o.charCodeAt(f),!d){n=o.slice(h);break}if(p===10&&h===f&&i)u.push(-3),i=void 0;else switch(i&&(u.push(-5),i=void 0),h<f&&(u.push(o.slice(h,f)),e+=f-h),p){case 0:{u.push(65533),e++;break}case 9:{for(m=Math.ceil(e/4)*4,u.push(-2);e++<m;)u.push(-1);break}case 10:{u.push(-4),e=1;break}default:i=!0,e=1}h=f+1}return c&&(i&&u.push(-5),n&&u.push(n),u.push(null)),u}}const q2=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function V2(e){return e.replace(q2,W2)}function W2(e,n,s){if(n)return n;if(s.charCodeAt(0)===35){const r=s.charCodeAt(1),o=r===120||r===88;return Lf(s.slice(o?2:1),o?16:10)}return Fd(s)||e}const Kf={}.hasOwnProperty;function K2(e,n,s){return n&&typeof n=="object"&&(s=n,n=void 0),G2(s)(B2(U2(s).document().write(H2()(e,n,!0))))}function G2(e){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(Te),autolinkProtocol:O,autolinkEmail:O,atxHeading:o(me),blockQuote:o(B),characterEscape:O,characterReference:O,codeFenced:o(Y),codeFencedFenceInfo:l,codeFencedFenceMeta:l,codeIndented:o(Y,l),codeText:o(X,l),codeTextData:O,data:O,codeFlowValue:O,definition:o(he),definitionDestinationString:l,definitionLabelString:l,definitionTitleString:l,emphasis:o(de),hardBreakEscape:o(se),hardBreakTrailing:o(se),htmlFlow:o(_e,l),htmlFlowData:O,htmlText:o(_e,l),htmlTextData:O,image:o(Fe),label:l,link:o(Te),listItem:o(nt),listItemValue:f,listOrdered:o(st,h),listUnordered:o(st),paragraph:o(qe),reference:k,referenceString:l,resourceDestinationString:l,resourceTitleString:l,setextHeading:o(me),strong:o(Xe),thematicBreak:o(Ue)},exit:{atxHeading:u(),atxHeadingSequence:C,autolink:u(),autolinkEmail:ve,autolinkProtocol:V,blockQuote:u(),characterEscapeValue:_,characterReferenceMarkerHexadecimal:Q,characterReferenceMarkerNumeric:Q,characterReferenceValue:ue,characterReference:be,codeFenced:u(v),codeFencedFence:b,codeFencedFenceInfo:p,codeFencedFenceMeta:g,codeFlowValue:_,codeIndented:u(x),codeText:u(T),codeTextData:_,data:_,definition:u(),definitionDestinationString:E,definitionLabelString:y,definitionTitleString:j,emphasis:u(),hardBreakEscape:u(U),hardBreakTrailing:u(U),htmlFlow:u(G),htmlFlowData:_,htmlText:u(M),htmlTextData:_,image:u(K),label:te,labelText:J,lineEnding:P,link:u(D),listItem:u(),listOrdered:u(),listUnordered:u(),paragraph:u(),referenceString:H,resourceDestinationString:N,resourceTitleString:z,resource:I,setextHeading:u(S),setextHeadingLineSequence:R,setextHeadingText:w,strong:u(),thematicBreak:u()}};Gf(n,(e||{}).mdastExtensions||[]);const s={};return i;function i(oe){let je={type:"root",children:[]};const ie={stack:[je],tokenStack:[],config:n,enter:c,exit:d,buffer:l,resume:m,data:s},Ae=[];let Le=-1;for(;++Le<oe.length;)if(oe[Le][1].type==="listOrdered"||oe[Le][1].type==="listUnordered")if(oe[Le][0]==="enter")Ae.push(Le);else{const we=Ae.pop();Le=r(oe,we,Le)}for(Le=-1;++Le<oe.length;){const we=n[oe[Le][0]];Kf.call(we,oe[Le][1].type)&&we[oe[Le][1].type].call(Object.assign({sliceSerialize:oe[Le][2].sliceSerialize},ie),oe[Le][1])}if(ie.tokenStack.length>0){const we=ie.tokenStack[ie.tokenStack.length-1];(we[1]||Vm).call(ie,void 0,we[0])}for(je.position={start:ji(oe.length>0?oe[0][1].start:{line:1,column:1,offset:0}),end:ji(oe.length>0?oe[oe.length-2][1].end:{line:1,column:1,offset:0})},Le=-1;++Le<n.transforms.length;)je=n.transforms[Le](je)||je;return je}function r(oe,je,ie){let Ae=je-1,Le=-1,we=!1,Ee,Ve,rt,xe;for(;++Ae<=ie;){const ce=oe[Ae];switch(ce[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{ce[0]==="enter"?Le++:Le--,xe=void 0;break}case"lineEndingBlank":{ce[0]==="enter"&&(Ee&&!xe&&!Le&&!rt&&(rt=Ae),xe=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:xe=void 0}if(!Le&&ce[0]==="enter"&&ce[1].type==="listItemPrefix"||Le===-1&&ce[0]==="exit"&&(ce[1].type==="listUnordered"||ce[1].type==="listOrdered")){if(Ee){let Pe=Ae;for(Ve=void 0;Pe--;){const pe=oe[Pe];if(pe[1].type==="lineEnding"||pe[1].type==="lineEndingBlank"){if(pe[0]==="exit")continue;Ve&&(oe[Ve][1].type="lineEndingBlank",we=!0),pe[1].type="lineEnding",Ve=Pe}else if(!(pe[1].type==="linePrefix"||pe[1].type==="blockQuotePrefix"||pe[1].type==="blockQuotePrefixWhitespace"||pe[1].type==="blockQuoteMarker"||pe[1].type==="listItemIndent"))break}rt&&(!Ve||rt<Ve)&&(Ee._spread=!0),Ee.end=Object.assign({},Ve?oe[Ve][1].start:ce[1].end),oe.splice(Ve||Ae,0,["exit",Ee,ce[2]]),Ae++,ie++}if(ce[1].type==="listItemPrefix"){const Pe={type:"listItem",_spread:!1,start:Object.assign({},ce[1].start),end:void 0};Ee=Pe,oe.splice(Ae,0,["enter",Pe,ce[2]]),Ae++,ie++,rt=void 0,xe=!0}}}return oe[je][1]._spread=we,ie}function o(oe,je){return ie;function ie(Ae){c.call(this,oe(Ae),Ae),je&&je.call(this,Ae)}}function l(){this.stack.push({type:"fragment",children:[]})}function c(oe,je,ie){this.stack[this.stack.length-1].children.push(oe),this.stack.push(oe),this.tokenStack.push([je,ie||void 0]),oe.position={start:ji(je.start),end:void 0}}function u(oe){return je;function je(ie){oe&&oe.call(this,ie),d.call(this,ie)}}function d(oe,je){const ie=this.stack.pop(),Ae=this.tokenStack.pop();if(Ae)Ae[0].type!==oe.type&&(je?je.call(this,oe,Ae[0]):(Ae[1]||Vm).call(this,oe,Ae[0]));else throw new Error("Cannot close `"+oe.type+"` ("+vr({start:oe.start,end:oe.end})+"): it’s not open");ie.position.end=ji(oe.end)}function m(){return Od(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function f(oe){if(this.data.expectingFirstListItemValue){const je=this.stack[this.stack.length-2];je.start=Number.parseInt(this.sliceSerialize(oe),10),this.data.expectingFirstListItemValue=void 0}}function p(){const oe=this.resume(),je=this.stack[this.stack.length-1];je.lang=oe}function g(){const oe=this.resume(),je=this.stack[this.stack.length-1];je.meta=oe}function b(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function v(){const oe=this.resume(),je=this.stack[this.stack.length-1];je.value=oe.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function x(){const oe=this.resume(),je=this.stack[this.stack.length-1];je.value=oe.replace(/(\r?\n|\r)$/g,"")}function y(oe){const je=this.resume(),ie=this.stack[this.stack.length-1];ie.label=je,ie.identifier=Ws(this.sliceSerialize(oe)).toLowerCase()}function j(){const oe=this.resume(),je=this.stack[this.stack.length-1];je.title=oe}function E(){const oe=this.resume(),je=this.stack[this.stack.length-1];je.url=oe}function C(oe){const je=this.stack[this.stack.length-1];if(!je.depth){const ie=this.sliceSerialize(oe).length;je.depth=ie}}function w(){this.data.setextHeadingSlurpLineEnding=!0}function R(oe){const je=this.stack[this.stack.length-1];je.depth=this.sliceSerialize(oe).codePointAt(0)===61?1:2}function S(){this.data.setextHeadingSlurpLineEnding=void 0}function O(oe){const ie=this.stack[this.stack.length-1].children;let Ae=ie[ie.length-1];(!Ae||Ae.type!=="text")&&(Ae=$e(),Ae.position={start:ji(oe.start),end:void 0},ie.push(Ae)),this.stack.push(Ae)}function _(oe){const je=this.stack.pop();je.value+=this.sliceSerialize(oe),je.position.end=ji(oe.end)}function P(oe){const je=this.stack[this.stack.length-1];if(this.data.atHardBreak){const ie=je.children[je.children.length-1];ie.position.end=ji(oe.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(je.type)&&(O.call(this,oe),_.call(this,oe))}function U(){this.data.atHardBreak=!0}function G(){const oe=this.resume(),je=this.stack[this.stack.length-1];je.value=oe}function M(){const oe=this.resume(),je=this.stack[this.stack.length-1];je.value=oe}function T(){const oe=this.resume(),je=this.stack[this.stack.length-1];je.value=oe}function D(){const oe=this.stack[this.stack.length-1];if(this.data.inReference){const je=this.data.referenceType||"shortcut";oe.type+="Reference",oe.referenceType=je,delete oe.url,delete oe.title}else delete oe.identifier,delete oe.label;this.data.referenceType=void 0}function K(){const oe=this.stack[this.stack.length-1];if(this.data.inReference){const je=this.data.referenceType||"shortcut";oe.type+="Reference",oe.referenceType=je,delete oe.url,delete oe.title}else delete oe.identifier,delete oe.label;this.data.referenceType=void 0}function J(oe){const je=this.sliceSerialize(oe),ie=this.stack[this.stack.length-2];ie.label=V2(je),ie.identifier=Ws(je).toLowerCase()}function te(){const oe=this.stack[this.stack.length-1],je=this.resume(),ie=this.stack[this.stack.length-1];if(this.data.inReference=!0,ie.type==="link"){const Ae=oe.children;ie.children=Ae}else ie.alt=je}function N(){const oe=this.resume(),je=this.stack[this.stack.length-1];je.url=oe}function z(){const oe=this.resume(),je=this.stack[this.stack.length-1];je.title=oe}function I(){this.data.inReference=void 0}function k(){this.data.referenceType="collapsed"}function H(oe){const je=this.resume(),ie=this.stack[this.stack.length-1];ie.label=je,ie.identifier=Ws(this.sliceSerialize(oe)).toLowerCase(),this.data.referenceType="full"}function Q(oe){this.data.characterReferenceType=oe.type}function ue(oe){const je=this.sliceSerialize(oe),ie=this.data.characterReferenceType;let Ae;ie?(Ae=Lf(je,ie==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Ae=Fd(je);const Le=this.stack[this.stack.length-1];Le.value+=Ae}function be(oe){const je=this.stack.pop();je.position.end=ji(oe.end)}function V(oe){_.call(this,oe);const je=this.stack[this.stack.length-1];je.url=this.sliceSerialize(oe)}function ve(oe){_.call(this,oe);const je=this.stack[this.stack.length-1];je.url="mailto:"+this.sliceSerialize(oe)}function B(){return{type:"blockquote",children:[]}}function Y(){return{type:"code",lang:null,meta:null,value:""}}function X(){return{type:"inlineCode",value:""}}function he(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function de(){return{type:"emphasis",children:[]}}function me(){return{type:"heading",depth:0,children:[]}}function se(){return{type:"break"}}function _e(){return{type:"html",value:""}}function Fe(){return{type:"image",title:null,url:"",alt:null}}function Te(){return{type:"link",title:null,url:"",children:[]}}function st(oe){return{type:"list",ordered:oe.type==="listOrdered",start:null,spread:oe._spread,children:[]}}function nt(oe){return{type:"listItem",spread:oe._spread,checked:null,children:[]}}function qe(){return{type:"paragraph",children:[]}}function Xe(){return{type:"strong",children:[]}}function $e(){return{type:"text",value:""}}function Ue(){return{type:"thematicBreak"}}}function ji(e){return{line:e.line,column:e.column,offset:e.offset}}function Gf(e,n){let s=-1;for(;++s<n.length;){const i=n[s];Array.isArray(i)?Gf(e,i):J2(e,i)}}function J2(e,n){let s;for(s in n)if(Kf.call(n,s))switch(s){case"canContainEols":{const i=n[s];i&&e[s].push(...i);break}case"transforms":{const i=n[s];i&&e[s].push(...i);break}case"enter":case"exit":{const i=n[s];i&&Object.assign(e[s],i);break}}}function Vm(e,n){throw e?new Error("Cannot close `"+e.type+"` ("+vr({start:e.start,end:e.end})+"): a different token (`"+n.type+"`, "+vr({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+vr({start:n.start,end:n.end})+") is still open")}function Y2(e){const n=this;n.parser=s;function s(i){return K2(i,{...n.data("settings"),...e,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function Q2(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 X2(e,n){const s={type:"element",tagName:"br",properties:{},children:[]};return e.patch(n,s),[e.applyData(n,s),{type:"text",value:`
|
|
627
|
-
`}]}function Z2(e,n){const s=n.value?n.value+`
|
|
628
|
-
`:"",i={},r=n.lang?n.lang.split(/\s+/):[];r.length>0&&(i.className=["language-"+r[0]]);let o={type:"element",tagName:"code",properties:i,children:[{type:"text",value:s}]};return n.meta&&(o.data={meta:n.meta}),e.patch(n,o),o=e.applyData(n,o),o={type:"element",tagName:"pre",properties:{},children:[o]},e.patch(n,o),o}function eE(e,n){const s={type:"element",tagName:"del",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function tE(e,n){const s={type:"element",tagName:"em",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function nE(e,n){const s=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=String(n.identifier).toUpperCase(),r=Oa(i.toLowerCase()),o=e.footnoteOrder.indexOf(i);let l,c=e.footnoteCounts.get(i);c===void 0?(c=0,e.footnoteOrder.push(i),l=e.footnoteOrder.length):l=o+1,c+=1,e.footnoteCounts.set(i,c);const u={type:"element",tagName:"a",properties:{href:"#"+s+"fn-"+r,id:s+"fnref-"+r+(c>1?"-"+c:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(l)}]};e.patch(n,u);const d={type:"element",tagName:"sup",properties:{},children:[u]};return e.patch(n,d),e.applyData(n,d)}function sE(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 iE(e,n){if(e.options.allowDangerousHtml){const s={type:"raw",value:n.value};return e.patch(n,s),e.applyData(n,s)}}function Jf(e,n){const s=n.referenceType;let i="]";if(s==="collapsed"?i+="[]":s==="full"&&(i+="["+(n.label||n.identifier)+"]"),n.type==="imageReference")return[{type:"text",value:"!["+n.alt+i}];const r=e.all(n),o=r[0];o&&o.type==="text"?o.value="["+o.value:r.unshift({type:"text",value:"["});const l=r[r.length-1];return l&&l.type==="text"?l.value+=i:r.push({type:"text",value:i}),r}function aE(e,n){const s=String(n.identifier).toUpperCase(),i=e.definitionById.get(s);if(!i)return Jf(e,n);const r={src:Oa(i.url||""),alt:n.alt};i.title!==null&&i.title!==void 0&&(r.title=i.title);const o={type:"element",tagName:"img",properties:r,children:[]};return e.patch(n,o),e.applyData(n,o)}function rE(e,n){const s={src:Oa(n.url)};n.alt!==null&&n.alt!==void 0&&(s.alt=n.alt),n.title!==null&&n.title!==void 0&&(s.title=n.title);const i={type:"element",tagName:"img",properties:s,children:[]};return e.patch(n,i),e.applyData(n,i)}function oE(e,n){const s={type:"text",value:n.value.replace(/\r?\n|\r/g," ")};e.patch(n,s);const i={type:"element",tagName:"code",properties:{},children:[s]};return e.patch(n,i),e.applyData(n,i)}function lE(e,n){const s=String(n.identifier).toUpperCase(),i=e.definitionById.get(s);if(!i)return Jf(e,n);const r={href:Oa(i.url||"")};i.title!==null&&i.title!==void 0&&(r.title=i.title);const o={type:"element",tagName:"a",properties:r,children:e.all(n)};return e.patch(n,o),e.applyData(n,o)}function cE(e,n){const s={href:Oa(n.url)};n.title!==null&&n.title!==void 0&&(s.title=n.title);const i={type:"element",tagName:"a",properties:s,children:e.all(n)};return e.patch(n,i),e.applyData(n,i)}function dE(e,n,s){const i=e.all(n),r=s?uE(s):Yf(n),o={},l=[];if(typeof n.checked=="boolean"){const m=i[0];let h;m&&m.type==="element"&&m.tagName==="p"?h=m:(h={type:"element",tagName:"p",properties:{},children:[]},i.unshift(h)),h.children.length>0&&h.children.unshift({type:"text",value:" "}),h.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:n.checked,disabled:!0},children:[]}),o.className=["task-list-item"]}let c=-1;for(;++c<i.length;){const m=i[c];(r||c!==0||m.type!=="element"||m.tagName!=="p")&&l.push({type:"text",value:`
|
|
629
|
-
`}),m.type==="element"&&m.tagName==="p"&&!r?l.push(...m.children):l.push(m)}const u=i[i.length-1];u&&(r||u.type!=="element"||u.tagName!=="p")&&l.push({type:"text",value:`
|
|
630
|
-
`});const d={type:"element",tagName:"li",properties:o,children:l};return e.patch(n,d),e.applyData(n,d)}function uE(e){let n=!1;if(e.type==="list"){n=e.spread||!1;const s=e.children;let i=-1;for(;!n&&++i<s.length;)n=Yf(s[i])}return n}function Yf(e){const n=e.spread;return n??e.children.length>1}function mE(e,n){const s={},i=e.all(n);let r=-1;for(typeof n.start=="number"&&n.start!==1&&(s.start=n.start);++r<i.length;){const l=i[r];if(l.type==="element"&&l.tagName==="li"&&l.properties&&Array.isArray(l.properties.className)&&l.properties.className.includes("task-list-item")){s.className=["contains-task-list"];break}}const o={type:"element",tagName:n.ordered?"ol":"ul",properties:s,children:e.wrap(i,!0)};return e.patch(n,o),e.applyData(n,o)}function hE(e,n){const s={type:"element",tagName:"p",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function pE(e,n){const s={type:"root",children:e.wrap(e.all(n))};return e.patch(n,s),e.applyData(n,s)}function fE(e,n){const s={type:"element",tagName:"strong",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function gE(e,n){const s=e.all(n),i=s.shift(),r=[];if(i){const l={type:"element",tagName:"thead",properties:{},children:e.wrap([i],!0)};e.patch(n.children[0],l),r.push(l)}if(s.length>0){const l={type:"element",tagName:"tbody",properties:{},children:e.wrap(s,!0)},c=$d(n.children[1]),u=Mf(n.children[n.children.length-1]);c&&u&&(l.position={start:c,end:u}),r.push(l)}const o={type:"element",tagName:"table",properties:{},children:e.wrap(r,!0)};return e.patch(n,o),e.applyData(n,o)}function bE(e,n,s){const i=s?s.children:void 0,o=(i?i.indexOf(n):1)===0?"th":"td",l=s&&s.type==="table"?s.align:void 0,c=l?l.length:n.children.length;let u=-1;const d=[];for(;++u<c;){const h=n.children[u],f={},p=l?l[u]:void 0;p&&(f.align=p);let g={type:"element",tagName:o,properties:f,children:[]};h&&(g.children=e.all(h),e.patch(h,g),g=e.applyData(h,g)),d.push(g)}const m={type:"element",tagName:"tr",properties:{},children:e.wrap(d,!0)};return e.patch(n,m),e.applyData(n,m)}function xE(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 vE(e){const n=String(e),s=/\r?\n|\r/g;let i=s.exec(n),r=0;const o=[];for(;i;)o.push(Gm(n.slice(r,i.index),r>0,!0),i[0]),r=i.index+i[0].length,i=s.exec(n);return o.push(Gm(n.slice(r),r>0,!1)),o.join("")}function Gm(e,n,s){let i=0,r=e.length;if(n){let o=e.codePointAt(i);for(;o===Wm||o===Km;)i++,o=e.codePointAt(i)}if(s){let o=e.codePointAt(r-1);for(;o===Wm||o===Km;)r--,o=e.codePointAt(r-1)}return r>i?e.slice(i,r):""}function yE(e,n){const s={type:"text",value:vE(String(n.value))};return e.patch(n,s),e.applyData(n,s)}function wE(e,n){const s={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(n,s),e.applyData(n,s)}const jE={blockquote:Q2,break:X2,code:Z2,delete:eE,emphasis:tE,footnoteReference:nE,heading:sE,html:iE,imageReference:aE,image:rE,inlineCode:oE,linkReference:lE,link:cE,listItem:dE,list:mE,paragraph:hE,root:pE,strong:fE,table:gE,tableCell:xE,tableRow:bE,text:yE,thematicBreak:wE,toml:po,yaml:po,definition:po,footnoteDefinition:po};function po(){}const Qf=-1,bl=0,wr=1,Ko=2,Bd=3,Hd=4,qd=5,Vd=6,Xf=7,Zf=8,Jm=typeof self=="object"?self:globalThis,kE=(e,n)=>{const s=(r,o)=>(e.set(o,r),r),i=r=>{if(e.has(r))return e.get(r);const[o,l]=n[r];switch(o){case bl:case Qf:return s(l,r);case wr:{const c=s([],r);for(const u of l)c.push(i(u));return c}case Ko:{const c=s({},r);for(const[u,d]of l)c[i(u)]=i(d);return c}case Bd:return s(new Date(l),r);case Hd:{const{source:c,flags:u}=l;return s(new RegExp(c,u),r)}case qd:{const c=s(new Map,r);for(const[u,d]of l)c.set(i(u),i(d));return c}case Vd:{const c=s(new Set,r);for(const u of l)c.add(i(u));return c}case Xf:{const{name:c,message:u}=l;return s(new Jm[c](u),r)}case Zf: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 i},Ym=e=>kE(new Map,e)(0),ua="",{toString:NE}={},{keys:SE}=Object,Za=e=>{const n=typeof e;if(n!=="object"||!e)return[bl,n];const s=NE.call(e).slice(8,-1);switch(s){case"Array":return[wr,ua];case"Object":return[Ko,ua];case"Date":return[Bd,ua];case"RegExp":return[Hd,ua];case"Map":return[qd,ua];case"Set":return[Vd,ua];case"DataView":return[wr,s]}return s.includes("Array")?[wr,s]:s.includes("Error")?[Xf,s]:[Ko,s]},fo=([e,n])=>e===bl&&(n==="function"||n==="symbol"),CE=(e,n,s,i)=>{const r=(l,c)=>{const u=i.push(l)-1;return s.set(c,u),u},o=l=>{if(s.has(l))return s.get(l);let[c,u]=Za(l);switch(c){case bl:{let m=l;switch(u){case"bigint":c=Zf,m=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+u);m=null;break;case"undefined":return r([Qf],l)}return r([c,m],l)}case wr:{if(u){let f=l;return u==="DataView"?f=new Uint8Array(l.buffer):u==="ArrayBuffer"&&(f=new Uint8Array(l)),r([u,[...f]],l)}const m=[],h=r([c,m],l);for(const f of l)m.push(o(f));return h}case Ko:{if(u)switch(u){case"BigInt":return r([u,l.toString()],l);case"Boolean":case"Number":case"String":return r([u,l.valueOf()],l)}if(n&&"toJSON"in l)return o(l.toJSON());const m=[],h=r([c,m],l);for(const f of SE(l))(e||!fo(Za(l[f])))&&m.push([o(f),o(l[f])]);return h}case Bd:return r([c,l.toISOString()],l);case Hd:{const{source:m,flags:h}=l;return r([c,{source:m,flags:h}],l)}case qd:{const m=[],h=r([c,m],l);for(const[f,p]of l)(e||!(fo(Za(f))||fo(Za(p))))&&m.push([o(f),o(p)]);return h}case Vd:{const m=[],h=r([c,m],l);for(const f of l)(e||!fo(Za(f)))&&m.push(o(f));return h}}const{message:d}=l;return r([c,{name:u,message:d}],l)};return o},Qm=(e,{json:n,lossy:s}={})=>{const i=[];return CE(!(n||s),!!n,new Map,i)(e),i},Go=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 EE(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 _E(e,n){return"Back to reference "+(e+1)+(n>1?"-"+n:"")}function ME(e){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=e.options.footnoteBackContent||EE,i=e.options.footnoteBackLabel||_E,r=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",l=e.options.footnoteLabelProperties||{className:["sr-only"]},c=[];let u=-1;for(;++u<e.footnoteOrder.length;){const d=e.footnoteById.get(e.footnoteOrder[u]);if(!d)continue;const m=e.all(d),h=String(d.identifier).toUpperCase(),f=Oa(h.toLowerCase());let p=0;const g=[],b=e.footnoteCounts.get(h);for(;b!==void 0&&++p<=b;){g.length>0&&g.push({type:"text",value:" "});let y=typeof s=="string"?s:s(u,p);typeof y=="string"&&(y={type:"text",value:y}),g.push({type:"element",tagName:"a",properties:{href:"#"+n+"fnref-"+f+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof i=="string"?i:i(u,p),className:["data-footnote-backref"]},children:Array.isArray(y)?y:[y]})}const v=m[m.length-1];if(v&&v.type==="element"&&v.tagName==="p"){const y=v.children[v.children.length-1];y&&y.type==="text"?y.value+=" ":v.children.push({type:"text",value:" "}),v.children.push(...g)}else m.push(...g);const x={type:"element",tagName:"li",properties:{id:n+"fn-"+f},children:e.wrap(m,!0)};e.patch(d,x),c.push(x)}if(c.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...Go(l),id:"footnote-label"},children:[{type:"text",value:r}]},{type:"text",value:`
|
|
631
|
-
`},{type:"element",tagName:"ol",properties:{},children:e.wrap(c,!0)},{type:"text",value:`
|
|
632
|
-
`}]}}const xl=(function(e){if(e==null)return PE;if(typeof e=="function")return vl(e);if(typeof e=="object")return Array.isArray(e)?AE(e):RE(e);if(typeof e=="string")return TE(e);throw new Error("Expected function, string, or object as test")});function AE(e){const n=[];let s=-1;for(;++s<e.length;)n[s]=xl(e[s]);return vl(i);function i(...r){let o=-1;for(;++o<n.length;)if(n[o].apply(this,r))return!0;return!1}}function RE(e){const n=e;return vl(s);function s(i){const r=i;let o;for(o in e)if(r[o]!==n[o])return!1;return!0}}function TE(e){return vl(n);function n(s){return s&&s.type===e}}function vl(e){return n;function n(s,i,r){return!!(IE(s)&&e.call(this,s,typeof i=="number"?i:void 0,r||void 0))}}function PE(){return!0}function IE(e){return e!==null&&typeof e=="object"&&"type"in e}const eg=[],$E=!0,sd=!1,DE="skip";function tg(e,n,s,i){let r;typeof n=="function"&&typeof s!="function"?(i=s,s=n):r=n;const o=xl(r),l=i?-1:1;c(e,void 0,[])();function c(u,d,m){const h=u&&typeof u=="object"?u:{};if(typeof h.type=="string"){const p=typeof h.tagName=="string"?h.tagName:typeof h.name=="string"?h.name:void 0;Object.defineProperty(f,"name",{value:"node ("+(u.type+(p?"<"+p+">":""))+")"})}return f;function f(){let p=eg,g,b,v;if((!n||o(u,d,m[m.length-1]||void 0))&&(p=LE(s(u,m)),p[0]===sd))return p;if("children"in u&&u.children){const x=u;if(x.children&&p[0]!==DE)for(b=(i?x.children.length:-1)+l,v=m.concat(x);b>-1&&b<x.children.length;){const y=x.children[b];if(g=c(y,b,v)(),g[0]===sd)return g;b=typeof g[1]=="number"?g[1]:b+l}}return p}}}function LE(e){return Array.isArray(e)?e:typeof e=="number"?[$E,e]:e==null?eg:[e]}function Wd(e,n,s,i){let r,o,l;typeof n=="function"&&typeof s!="function"?(o=void 0,l=n,r=s):(o=n,l=s,r=i),tg(e,o,c,r);function c(u,d){const m=d[d.length-1],h=m?m.children.indexOf(u):void 0;return l(u,h,m)}}const id={}.hasOwnProperty,zE={};function OE(e,n){const s=n||zE,i=new Map,r=new Map,o=new Map,l={...jE,...s.handlers},c={all:d,applyData:UE,definitionById:i,footnoteById:r,footnoteCounts:o,footnoteOrder:[],handlers:l,one:u,options:s,patch:FE,wrap:HE};return Wd(e,function(m){if(m.type==="definition"||m.type==="footnoteDefinition"){const h=m.type==="definition"?i:r,f=String(m.identifier).toUpperCase();h.has(f)||h.set(f,m)}}),c;function u(m,h){const f=m.type,p=c.handlers[f];if(id.call(c.handlers,f)&&p)return p(c,m,h);if(c.options.passThrough&&c.options.passThrough.includes(f)){if("children"in m){const{children:b,...v}=m,x=Go(v);return x.children=c.all(m),x}return Go(m)}return(c.options.unknownHandler||BE)(c,m,h)}function d(m){const h=[];if("children"in m){const f=m.children;let p=-1;for(;++p<f.length;){const g=c.one(f[p],m);if(g){if(p&&f[p-1].type==="break"&&(!Array.isArray(g)&&g.type==="text"&&(g.value=Xm(g.value)),!Array.isArray(g)&&g.type==="element")){const b=g.children[0];b&&b.type==="text"&&(b.value=Xm(b.value))}Array.isArray(g)?h.push(...g):h.push(g)}}}return h}}function FE(e,n){e.position&&(n.position=_0(e))}function UE(e,n){let s=n;if(e&&e.data){const i=e.data.hName,r=e.data.hChildren,o=e.data.hProperties;if(typeof i=="string")if(s.type==="element")s.tagName=i;else{const l="children"in s?s.children:[s];s={type:"element",tagName:i,properties:{},children:l}}s.type==="element"&&o&&Object.assign(s.properties,Go(o)),"children"in s&&s.children&&r!==null&&r!==void 0&&(s.children=r)}return s}function BE(e,n){const s=n.data||{},i="value"in n&&!(id.call(s,"hProperties")||id.call(s,"hChildren"))?{type:"text",value:n.value}:{type:"element",tagName:"div",properties:{},children:e.all(n)};return e.patch(n,i),e.applyData(n,i)}function HE(e,n){const s=[];let i=-1;for(n&&s.push({type:"text",value:`
|
|
633
|
-
`});++i<e.length;)i&&s.push({type:"text",value:`
|
|
634
|
-
`}),s.push(e[i]);return n&&e.length>0&&s.push({type:"text",value:`
|
|
635
|
-
`}),s}function 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=OE(e,n),i=s.one(e,void 0),r=ME(s),o=Array.isArray(i)?{type:"root",children:i}:i||{type:"root",children:[]};return r&&o.children.push({type:"text",value:`
|
|
636
|
-
`},r),o}function qE(e,n){return e&&"run"in e?async function(s,i){const r=Zm(s,{file:i,...n});await e.run(r,i)}:function(s,i){return Zm(s,{file:i,...e||n})}}function eh(e){if(e)throw e}var Ql,th;function VE(){if(th)return Ql;th=1;var e=Object.prototype.hasOwnProperty,n=Object.prototype.toString,s=Object.defineProperty,i=Object.getOwnPropertyDescriptor,r=function(d){return typeof Array.isArray=="function"?Array.isArray(d):n.call(d)==="[object Array]"},o=function(d){if(!d||n.call(d)!=="[object Object]")return!1;var m=e.call(d,"constructor"),h=d.constructor&&d.constructor.prototype&&e.call(d.constructor.prototype,"isPrototypeOf");if(d.constructor&&!m&&!h)return!1;var f;for(f in d);return typeof f>"u"||e.call(d,f)},l=function(d,m){s&&m.name==="__proto__"?s(d,m.name,{enumerable:!0,configurable:!0,value:m.newValue,writable:!0}):d[m.name]=m.newValue},c=function(d,m){if(m==="__proto__")if(e.call(d,m)){if(i)return i(d,m).value}else return;return d[m]};return Ql=function u(){var d,m,h,f,p,g,b=arguments[0],v=1,x=arguments.length,y=!1;for(typeof b=="boolean"&&(y=b,b=arguments[1]||{},v=2),(b==null||typeof b!="object"&&typeof b!="function")&&(b={});v<x;++v)if(d=arguments[v],d!=null)for(m in d)h=c(b,m),f=c(d,m),b!==f&&(y&&f&&(o(f)||(p=r(f)))?(p?(p=!1,g=h&&r(h)?h:[]):g=h&&o(h)?h:{},l(b,{name:m,newValue:u(y,g,f)})):typeof f<"u"&&l(b,{name:m,newValue:f}));return b},Ql}var WE=VE();const Xl=vp(WE);function ad(e){if(typeof e!="object"||e===null)return!1;const n=Object.getPrototypeOf(e);return(n===null||n===Object.prototype||Object.getPrototypeOf(n)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function KE(){const e=[],n={run:s,use:i};return n;function s(...r){let o=-1;const l=r.pop();if(typeof l!="function")throw new TypeError("Expected function as last argument, not "+l);c(null,...r);function c(u,...d){const m=e[++o];let h=-1;if(u){l(u);return}for(;++h<r.length;)(d[h]===null||d[h]===void 0)&&(d[h]=r[h]);r=d,m?GE(m,c)(...d):l(null,...d)}}function i(r){if(typeof r!="function")throw new TypeError("Expected `middelware` to be a function, not "+r);return e.push(r),n}}function GE(e,n){let s;return i;function i(...l){const c=e.length>l.length;let u;c&&l.push(r);try{u=e.apply(this,l)}catch(d){const m=d;if(c&&s)throw m;return r(m)}c||(u&&u.then&&typeof u.then=="function"?u.then(o,r):u instanceof Error?r(u):o(u))}function r(l,...c){s||(s=!0,n(l,...c))}function o(l){r(null,l)}}const ni={basename:JE,dirname:YE,extname:QE,join:XE,sep:"/"};function JE(e,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');Kr(e);let s=0,i=-1,r=e.length,o;if(n===void 0||n.length===0||n.length>e.length){for(;r--;)if(e.codePointAt(r)===47){if(o){s=r+1;break}}else i<0&&(o=!0,i=r+1);return i<0?"":e.slice(s,i)}if(n===e)return"";let l=-1,c=n.length-1;for(;r--;)if(e.codePointAt(r)===47){if(o){s=r+1;break}}else l<0&&(o=!0,l=r+1),c>-1&&(e.codePointAt(r)===n.codePointAt(c--)?c<0&&(i=r):(c=-1,i=l));return s===i?i=l:i<0&&(i=e.length),e.slice(s,i)}function YE(e){if(Kr(e),e.length===0)return".";let n=-1,s=e.length,i;for(;--s;)if(e.codePointAt(s)===47){if(i){n=s;break}}else i||(i=!0);return n<0?e.codePointAt(0)===47?"/":".":n===1&&e.codePointAt(0)===47?"//":e.slice(0,n)}function QE(e){Kr(e);let n=e.length,s=-1,i=0,r=-1,o=0,l;for(;n--;){const c=e.codePointAt(n);if(c===47){if(l){i=n+1;break}continue}s<0&&(l=!0,s=n+1),c===46?r<0?r=n:o!==1&&(o=1):r>-1&&(o=-1)}return r<0||s<0||o===0||o===1&&r===s-1&&r===i+1?"":e.slice(r,s)}function XE(...e){let n=-1,s;for(;++n<e.length;)Kr(e[n]),e[n]&&(s=s===void 0?e[n]:s+"/"+e[n]);return s===void 0?".":ZE(s)}function ZE(e){Kr(e);const n=e.codePointAt(0)===47;let s=e_(e,!n);return s.length===0&&!n&&(s="."),s.length>0&&e.codePointAt(e.length-1)===47&&(s+="/"),n?"/"+s:s}function e_(e,n){let s="",i=0,r=-1,o=0,l=-1,c,u;for(;++l<=e.length;){if(l<e.length)c=e.codePointAt(l);else{if(c===47)break;c=47}if(c===47){if(!(r===l-1||o===1))if(r!==l-1&&o===2){if(s.length<2||i!==2||s.codePointAt(s.length-1)!==46||s.codePointAt(s.length-2)!==46){if(s.length>2){if(u=s.lastIndexOf("/"),u!==s.length-1){u<0?(s="",i=0):(s=s.slice(0,u),i=s.length-1-s.lastIndexOf("/")),r=l,o=0;continue}}else if(s.length>0){s="",i=0,r=l,o=0;continue}}n&&(s=s.length>0?s+"/..":"..",i=2)}else s.length>0?s+="/"+e.slice(r+1,l):s=e.slice(r+1,l),i=l-r-1;r=l,o=0}else c===46&&o>-1?o++:o=-1}return s}function Kr(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const t_={cwd:n_};function n_(){return"/"}function rd(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function s_(e){if(typeof e=="string")e=new URL(e);else if(!rd(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 i_(e)}function i_(e){if(e.hostname!==""){const i=new TypeError('File URL host must be "localhost" or empty on darwin');throw i.code="ERR_INVALID_FILE_URL_HOST",i}const n=e.pathname;let s=-1;for(;++s<n.length;)if(n.codePointAt(s)===37&&n.codePointAt(s+1)===50){const i=n.codePointAt(s+2);if(i===70||i===102){const r=new TypeError("File URL path must not include encoded / characters");throw r.code="ERR_INVALID_FILE_URL_PATH",r}}return decodeURIComponent(n)}const Zl=["history","path","basename","stem","extname","dirname"];class ng{constructor(n){let s;n?rd(n)?s={path:n}:typeof n=="string"||a_(n)?s={value:n}:s=n:s={},this.cwd="cwd"in s?"":t_.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let i=-1;for(;++i<Zl.length;){const o=Zl[i];o in s&&s[o]!==void 0&&s[o]!==null&&(this[o]=o==="history"?[...s[o]]:s[o])}let r;for(r in s)Zl.includes(r)||(this[r]=s[r])}get basename(){return typeof this.path=="string"?ni.basename(this.path):void 0}set basename(n){tc(n,"basename"),ec(n,"basename"),this.path=ni.join(this.dirname||"",n)}get dirname(){return typeof this.path=="string"?ni.dirname(this.path):void 0}set dirname(n){nh(this.basename,"dirname"),this.path=ni.join(n||"",this.basename)}get extname(){return typeof this.path=="string"?ni.extname(this.path):void 0}set extname(n){if(ec(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=ni.join(this.dirname,this.stem+(n||""))}get path(){return this.history[this.history.length-1]}set path(n){rd(n)&&(n=s_(n)),tc(n,"path"),this.path!==n&&this.history.push(n)}get stem(){return typeof this.path=="string"?ni.basename(this.path,this.extname):void 0}set stem(n){tc(n,"stem"),ec(n,"stem"),this.path=ni.join(this.dirname||"",n+(this.extname||""))}fail(n,s,i){const r=this.message(n,s,i);throw r.fatal=!0,r}info(n,s,i){const r=this.message(n,s,i);return r.fatal=void 0,r}message(n,s,i){const r=new us(n,s,i);return this.path&&(r.name=this.path+":"+r.name,r.file=this.path),r.fatal=!1,this.messages.push(r),r}toString(n){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(n||void 0).decode(this.value)}}function ec(e,n){if(e&&e.includes(ni.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+ni.sep+"`")}function tc(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 a_(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const r_=(function(e){const i=this.constructor.prototype,r=i[e],o=function(){return r.apply(o,arguments)};return Object.setPrototypeOf(o,i),o}),o_={}.hasOwnProperty;class Kd extends r_{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=KE()}copy(){const n=new Kd;let s=-1;for(;++s<this.attachers.length;){const i=this.attachers[s];n.use(...i)}return n.data(Xl(!0,{},this.namespace)),n}data(n,s){return typeof n=="string"?arguments.length===2?(ic("data",this.frozen),this.namespace[n]=s,this):o_.call(this.namespace,n)&&this.namespace[n]||void 0:n?(ic("data",this.frozen),this.namespace=n,this):this.namespace}freeze(){if(this.frozen)return this;const n=this;for(;++this.freezeIndex<this.attachers.length;){const[s,...i]=this.attachers[this.freezeIndex];if(i[0]===!1)continue;i[0]===!0&&(i[0]=void 0);const r=s.call(n,...i);typeof r=="function"&&this.transformers.use(r)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(n){this.freeze();const s=go(n),i=this.parser||this.Parser;return nc("parse",i),i(String(s),s)}process(n,s){const i=this;return this.freeze(),nc("process",this.parser||this.Parser),sc("process",this.compiler||this.Compiler),s?r(void 0,s):new Promise(r);function r(o,l){const c=go(n),u=i.parse(c);i.run(u,c,function(m,h,f){if(m||!h||!f)return d(m);const p=h,g=i.stringify(p,f);d_(g)?f.value=g:f.result=g,d(m,f)});function d(m,h){m||!h?l(m):o?o(h):s(void 0,h)}}}processSync(n){let s=!1,i;return this.freeze(),nc("processSync",this.parser||this.Parser),sc("processSync",this.compiler||this.Compiler),this.process(n,r),ih("processSync","process",s),i;function r(o,l){s=!0,eh(o),i=l}}run(n,s,i){sh(n),this.freeze();const r=this.transformers;return!i&&typeof s=="function"&&(i=s,s=void 0),i?o(void 0,i):new Promise(o);function o(l,c){const u=go(s);r.run(n,u,d);function d(m,h,f){const p=h||n;m?c(m):l?l(p):i(void 0,p,f)}}}runSync(n,s){let i=!1,r;return this.run(n,s,o),ih("runSync","run",i),r;function o(l,c){eh(l),r=c,i=!0}}stringify(n,s){this.freeze();const i=go(s),r=this.compiler||this.Compiler;return sc("stringify",r),sh(n),r(n,i)}use(n,...s){const i=this.attachers,r=this.namespace;if(ic("use",this.frozen),n!=null)if(typeof n=="function")u(n,s);else if(typeof n=="object")Array.isArray(n)?c(n):l(n);else throw new TypeError("Expected usable value, not `"+n+"`");return this;function o(d){if(typeof d=="function")u(d,[]);else if(typeof d=="object")if(Array.isArray(d)){const[m,...h]=d;u(m,h)}else l(d);else throw new TypeError("Expected usable value, not `"+d+"`")}function l(d){if(!("plugins"in d)&&!("settings"in d))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");c(d.plugins),d.settings&&(r.settings=Xl(!0,r.settings,d.settings))}function c(d){let m=-1;if(d!=null)if(Array.isArray(d))for(;++m<d.length;){const h=d[m];o(h)}else throw new TypeError("Expected a list of plugins, not `"+d+"`")}function u(d,m){let h=-1,f=-1;for(;++h<i.length;)if(i[h][0]===d){f=h;break}if(f===-1)i.push([d,...m]);else if(m.length>0){let[p,...g]=m;const b=i[f][1];ad(b)&&ad(p)&&(p=Xl(!0,b,p)),i[f]=[d,p,...g]}}}}const l_=new Kd().freeze();function nc(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function sc(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function ic(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(!ad(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 go(e){return c_(e)?e:new ng(e)}function c_(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function d_(e){return typeof e=="string"||u_(e)}function u_(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const m_="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",ah=[],rh={allowDangerousHtml:!0},h_=/^(https?|ircs?|mailto|xmpp)$/i,p_=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function li(e){const n=f_(e),s=g_(e);return b_(n.runSync(n.parse(s),s),e)}function f_(e){const n=e.rehypePlugins||ah,s=e.remarkPlugins||ah,i=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...rh}:rh;return l_().use(Y2).use(s).use(qE,i).use(n)}function g_(e){const n=e.children||"",s=new ng;return typeof n=="string"&&(s.value=n),s}function b_(e,n){const s=n.allowedElements,i=n.allowElement,r=n.components,o=n.disallowedElements,l=n.skipHtml,c=n.unwrapDisallowed,u=n.urlTransform||x_;for(const m of p_)Object.hasOwn(n,m.from)&&(""+m.from+(m.to?"use `"+m.to+"` instead":"remove it")+m_+m.id,void 0);return Wd(e,d),P0(e,{Fragment:t.Fragment,components:r,ignoreInvalidStyle:!0,jsx:t.jsx,jsxs:t.jsxs,passKeys:!0,passNode:!0});function d(m,h,f){if(m.type==="raw"&&f&&typeof h=="number")return l?f.children.splice(h,1):f.children[h]={type:"text",value:m.value},h;if(m.type==="element"){let p;for(p in Gl)if(Object.hasOwn(Gl,p)&&Object.hasOwn(m.properties,p)){const g=m.properties[p],b=Gl[p];(b===null||b.includes(m.tagName))&&(m.properties[p]=u(String(g||""),p,m))}}if(m.type==="element"){let p=s?!s.includes(m.tagName):o?o.includes(m.tagName):!1;if(!p&&i&&typeof h=="number"&&(p=!i(m,h,f)),p&&f&&typeof h=="number")return c&&m.children?f.children.splice(h,1,...m.children):f.children.splice(h,1),h}}}function x_(e){const n=e.indexOf(":"),s=e.indexOf("?"),i=e.indexOf("#"),r=e.indexOf("/");return n===-1||r!==-1&&n>r||s!==-1&&n>s||i!==-1&&n>i||h_.test(e.slice(0,n))?e:""}function oh(e,n){const s=String(e);if(typeof n!="string")throw new TypeError("Expected character");let i=0,r=s.indexOf(n);for(;r!==-1;)i++,r=s.indexOf(n,r+n.length);return i}function v_(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function y_(e,n,s){const r=xl((s||{}).ignore||[]),o=w_(n);let l=-1;for(;++l<o.length;)tg(e,"text",c);function c(d,m){let h=-1,f;for(;++h<m.length;){const p=m[h],g=f?f.children:void 0;if(r(p,g?g.indexOf(p):void 0,f))return;f=p}if(f)return u(d,m)}function u(d,m){const h=m[m.length-1],f=o[l][0],p=o[l][1];let g=0;const v=h.children.indexOf(d);let x=!1,y=[];f.lastIndex=0;let j=f.exec(d.value);for(;j;){const E=j.index,C={index:j.index,input:j.input,stack:[...m,d]};let w=p(...j,C);if(typeof w=="string"&&(w=w.length>0?{type:"text",value:w}:void 0),w===!1?f.lastIndex=E+1:(g!==E&&y.push({type:"text",value:d.value.slice(g,E)}),Array.isArray(w)?y.push(...w):w&&y.push(w),g=E+j[0].length,x=!0),!f.global)break;j=f.exec(d.value)}return x?(g<d.value.length&&y.push({type:"text",value:d.value.slice(g)}),h.children.splice(v,1,...y)):y=[d],v+y.length}}function w_(e){const n=[];if(!Array.isArray(e))throw new TypeError("Expected find and replace tuple or list of tuples");const s=!e[0]||Array.isArray(e[0])?e:[e];let i=-1;for(;++i<s.length;){const r=s[i];n.push([j_(r[0]),k_(r[1])])}return n}function j_(e){return typeof e=="string"?new RegExp(v_(e),"g"):e}function k_(e){return typeof e=="function"?e:function(){return e}}const ac="phrasing",rc=["autolink","link","image","label"];function N_(){return{transforms:[R_],enter:{literalAutolink:C_,literalAutolinkEmail:oc,literalAutolinkHttp:oc,literalAutolinkWww:oc},exit:{literalAutolink:A_,literalAutolinkEmail:M_,literalAutolinkHttp:E_,literalAutolinkWww:__}}}function S_(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:ac,notInConstruct:rc},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:ac,notInConstruct:rc},{character:":",before:"[ps]",after:"\\/",inConstruct:ac,notInConstruct:rc}]}}function C_(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function oc(e){this.config.enter.autolinkProtocol.call(this,e)}function E_(e){this.config.exit.autolinkProtocol.call(this,e)}function __(e){this.config.exit.data.call(this,e);const n=this.stack[this.stack.length-1];n.type,n.url="http://"+this.sliceSerialize(e)}function M_(e){this.config.exit.autolinkEmail.call(this,e)}function A_(e){this.exit(e)}function R_(e){y_(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,T_],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,P_]],{ignore:["link","linkReference"]})}function T_(e,n,s,i,r){let o="";if(!sg(r)||(/^w/i.test(n)&&(s=n+s,n="",o="http://"),!I_(s)))return!1;const l=$_(s+i);if(!l[0])return!1;const c={type:"link",title:null,url:o+n+l[0],children:[{type:"text",value:n+l[0]}]};return l[1]?[c,{type:"text",value:l[1]}]:c}function P_(e,n,s,i){return!sg(i,!0)||/[-\d_]$/.test(s)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+s,children:[{type:"text",value:n+"@"+s}]}}function I_(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 $_(e){const n=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!n)return[e,void 0];e=e.slice(0,n.index);let s=n[0],i=s.indexOf(")");const r=oh(e,"(");let o=oh(e,")");for(;i!==-1&&r>o;)e+=s.slice(0,i+1),s=s.slice(i+1),i=s.indexOf(")"),o++;return[e,s]}function sg(e,n){const s=e.input.charCodeAt(e.index-1);return(e.index===0||Gi(s)||fl(s))&&(!n||s!==47)}ig.peek=q_;function D_(){this.buffer()}function L_(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function z_(){this.buffer()}function O_(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function F_(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=Ws(this.sliceSerialize(e)).toLowerCase(),s.label=n}function U_(e){this.exit(e)}function B_(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=Ws(this.sliceSerialize(e)).toLowerCase(),s.label=n}function H_(e){this.exit(e)}function q_(){return"["}function ig(e,n,s,i){const r=s.createTracker(i);let o=r.move("[^");const l=s.enter("footnoteReference"),c=s.enter("reference");return o+=r.move(s.safe(s.associationId(e),{after:"]",before:o})),c(),l(),o+=r.move("]"),o}function V_(){return{enter:{gfmFootnoteCallString:D_,gfmFootnoteCall:L_,gfmFootnoteDefinitionLabelString:z_,gfmFootnoteDefinition:O_},exit:{gfmFootnoteCallString:F_,gfmFootnoteCall:U_,gfmFootnoteDefinitionLabelString:B_,gfmFootnoteDefinition:H_}}}function W_(e){let n=!1;return e&&e.firstLineBlank&&(n=!0),{handlers:{footnoteDefinition:s,footnoteReference:ig},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function s(i,r,o,l){const c=o.createTracker(l);let u=c.move("[^");const d=o.enter("footnoteDefinition"),m=o.enter("label");return u+=c.move(o.safe(o.associationId(i),{before:u,after:"]"})),m(),u+=c.move("]:"),i.children&&i.children.length>0&&(c.shift(4),u+=c.move((n?`
|
|
637
|
-
`:" ")+o.indentLines(o.containerFlow(i,c.current()),n?ag:K_))),d(),u}}function K_(e,n,s){return n===0?e:ag(e,n,s)}function ag(e,n,s){return(s?"":" ")+e}const G_=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];rg.peek=Z_;function J_(){return{canContainEols:["delete"],enter:{strikethrough:Q_},exit:{strikethrough:X_}}}function Y_(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:G_}],handlers:{delete:rg}}}function Q_(e){this.enter({type:"delete",children:[]},e)}function X_(e){this.exit(e)}function rg(e,n,s,i){const r=s.createTracker(i),o=s.enter("strikethrough");let l=r.move("~~");return l+=s.containerPhrasing(e,{...r.current(),before:l,after:"~"}),l+=r.move("~~"),o(),l}function Z_(){return"~"}function eM(e){return e.length}function tM(e,n){const s=n||{},i=(s.align||[]).concat(),r=s.stringLength||eM,o=[],l=[],c=[],u=[];let d=0,m=-1;for(;++m<e.length;){const b=[],v=[];let x=-1;for(e[m].length>d&&(d=e[m].length);++x<e[m].length;){const y=nM(e[m][x]);if(s.alignDelimiters!==!1){const j=r(y);v[x]=j,(u[x]===void 0||j>u[x])&&(u[x]=j)}b.push(y)}l[m]=b,c[m]=v}let h=-1;if(typeof i=="object"&&"length"in i)for(;++h<d;)o[h]=lh(i[h]);else{const b=lh(i);for(;++h<d;)o[h]=b}h=-1;const f=[],p=[];for(;++h<d;){const b=o[h];let v="",x="";b===99?(v=":",x=":"):b===108?v=":":b===114&&(x=":");let y=s.alignDelimiters===!1?1:Math.max(1,u[h]-v.length-x.length);const j=v+"-".repeat(y)+x;s.alignDelimiters!==!1&&(y=v.length+y+x.length,y>u[h]&&(u[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 b=l[m],v=c[m];h=-1;const x=[];for(;++h<d;){const y=b[h]||"";let j="",E="";if(s.alignDelimiters!==!1){const C=u[h]-(v[h]||0),w=o[h];w===114?j=" ".repeat(C):w===99?C%2?(j=" ".repeat(C/2+.5),E=" ".repeat(C/2-.5)):(j=" ".repeat(C/2),E=j):E=" ".repeat(C)}s.delimiterStart!==!1&&!h&&x.push("|"),s.padding!==!1&&!(s.alignDelimiters===!1&&y==="")&&(s.delimiterStart!==!1||h)&&x.push(" "),s.alignDelimiters!==!1&&x.push(j),x.push(y),s.alignDelimiters!==!1&&x.push(E),s.padding!==!1&&x.push(" "),(s.delimiterEnd!==!1||h!==d-1)&&x.push("|")}g.push(s.delimiterEnd===!1?x.join("").replace(/ +$/,""):x.join(""))}return g.join(`
|
|
638
|
-
`)}function nM(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 sM(e,n,s,i){const r=s.enter("blockquote"),o=s.createTracker(i);o.move("> "),o.shift(2);const l=s.indentLines(s.containerFlow(e,o.current()),iM);return r(),l}function iM(e,n,s){return">"+(s?"":" ")+e}function aM(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 i=-1;for(;++i<n.length;)if(e.includes(n[i]))return!0;return!1}function dh(e,n,s,i){let r=-1;for(;++r<s.unsafe.length;)if(s.unsafe[r].character===`
|
|
639
|
-
`&&aM(s.stack,s.unsafe[r]))return/[ \t]/.test(i.before)?"":" ";return`\\
|
|
640
|
-
`}function rM(e,n){const s=String(e);let i=s.indexOf(n),r=i,o=0,l=0;if(typeof n!="string")throw new TypeError("Expected substring");for(;i!==-1;)i===r?++o>l&&(l=o):o=1,r=i+n.length,i=s.indexOf(n,r);return l}function oM(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 lM(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 cM(e,n,s,i){const r=lM(s),o=e.value||"",l=r==="`"?"GraveAccent":"Tilde";if(oM(e,s)){const h=s.enter("codeIndented"),f=s.indentLines(o,dM);return h(),f}const c=s.createTracker(i),u=r.repeat(Math.max(rM(o,r)+1,3)),d=s.enter("codeFenced");let m=c.move(u);if(e.lang){const h=s.enter(`codeFencedLang${l}`);m+=c.move(s.safe(e.lang,{before:m,after:" ",encode:["`"],...c.current()})),h()}if(e.lang&&e.meta){const h=s.enter(`codeFencedMeta${l}`);m+=c.move(" "),m+=c.move(s.safe(e.meta,{before:m,after:`
|
|
641
|
-
`,encode:["`"],...c.current()})),h()}return m+=c.move(`
|
|
642
|
-
`),o&&(m+=c.move(o+`
|
|
643
|
-
`)),m+=c.move(u),d(),m}function dM(e,n,s){return(s?"":" ")+e}function Gd(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 uM(e,n,s,i){const r=Gd(s),o=r==='"'?"Quote":"Apostrophe",l=s.enter("definition");let c=s.enter("label");const u=s.createTracker(i);let d=u.move("[");return d+=u.move(s.safe(s.associationId(e),{before:d,after:"]",...u.current()})),d+=u.move("]: "),c(),!e.url||/[\0- \u007F]/.test(e.url)?(c=s.enter("destinationLiteral"),d+=u.move("<"),d+=u.move(s.safe(e.url,{before:d,after:">",...u.current()})),d+=u.move(">")):(c=s.enter("destinationRaw"),d+=u.move(s.safe(e.url,{before:d,after:e.title?" ":`
|
|
644
|
-
`,...u.current()}))),c(),e.title&&(c=s.enter(`title${o}`),d+=u.move(" "+r),d+=u.move(s.safe(e.title,{before:d,after:r,...u.current()})),d+=u.move(r),c()),l(),d}function mM(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 Tr(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Jo(e,n,s){const i=Na(e),r=Na(n);return i===void 0?r===void 0?s==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:r===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:i===1?r===void 0?{inside:!1,outside:!1}:r===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:r===void 0?{inside:!1,outside:!1}:r===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}og.peek=hM;function og(e,n,s,i){const r=mM(s),o=s.enter("emphasis"),l=s.createTracker(i),c=l.move(r);let u=l.move(s.containerPhrasing(e,{after:r,before:c,...l.current()}));const d=u.charCodeAt(0),m=Jo(i.before.charCodeAt(i.before.length-1),d,r);m.inside&&(u=Tr(d)+u.slice(1));const h=u.charCodeAt(u.length-1),f=Jo(i.after.charCodeAt(0),h,r);f.inside&&(u=u.slice(0,-1)+Tr(h));const p=l.move(r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+u+p}function hM(e,n,s){return s.options.emphasis||"*"}function pM(e,n){let s=!1;return Wd(e,function(i){if("value"in i&&/\r?\n|\r/.test(i.value)||i.type==="break")return s=!0,sd}),!!((!e.depth||e.depth<3)&&Od(e)&&(n.options.setext||s))}function fM(e,n,s,i){const r=Math.max(Math.min(6,e.depth||1),1),o=s.createTracker(i);if(pM(e,s)){const m=s.enter("headingSetext"),h=s.enter("phrasing"),f=s.containerPhrasing(e,{...o.current(),before:`
|
|
645
|
-
`,after:`
|
|
646
|
-
`});return h(),m(),f+`
|
|
647
|
-
`+(r===1?"=":"-").repeat(f.length-(Math.max(f.lastIndexOf("\r"),f.lastIndexOf(`
|
|
648
|
-
`))+1))}const l="#".repeat(r),c=s.enter("headingAtx"),u=s.enter("phrasing");o.move(l+" ");let d=s.containerPhrasing(e,{before:"# ",after:`
|
|
649
|
-
`,...o.current()});return/^[\t ]/.test(d)&&(d=Tr(d.charCodeAt(0))+d.slice(1)),d=d?l+" "+d:l,s.options.closeAtx&&(d+=" "+l),u(),c(),d}lg.peek=gM;function lg(e){return e.value||""}function gM(){return"<"}cg.peek=bM;function cg(e,n,s,i){const r=Gd(s),o=r==='"'?"Quote":"Apostrophe",l=s.enter("image");let c=s.enter("label");const u=s.createTracker(i);let d=u.move("![");return d+=u.move(s.safe(e.alt,{before:d,after:"]",...u.current()})),d+=u.move("]("),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=s.enter("destinationLiteral"),d+=u.move("<"),d+=u.move(s.safe(e.url,{before:d,after:">",...u.current()})),d+=u.move(">")):(c=s.enter("destinationRaw"),d+=u.move(s.safe(e.url,{before:d,after:e.title?" ":")",...u.current()}))),c(),e.title&&(c=s.enter(`title${o}`),d+=u.move(" "+r),d+=u.move(s.safe(e.title,{before:d,after:r,...u.current()})),d+=u.move(r),c()),d+=u.move(")"),l(),d}function bM(){return"!"}dg.peek=xM;function dg(e,n,s,i){const r=e.referenceType,o=s.enter("imageReference");let l=s.enter("label");const c=s.createTracker(i);let u=c.move("![");const d=s.safe(e.alt,{before:u,after:"]",...c.current()});u+=c.move(d+"]["),l();const m=s.stack;s.stack=[],l=s.enter("reference");const h=s.safe(s.associationId(e),{before:u,after:"]",...c.current()});return l(),s.stack=m,o(),r==="full"||!d||d!==h?u+=c.move(h+"]"):r==="shortcut"?u=u.slice(0,-1):u+=c.move("]"),u}function xM(){return"!"}ug.peek=vM;function ug(e,n,s){let i=e.value||"",r="`",o=-1;for(;new RegExp("(^|[^`])"+r+"([^`]|$)").test(i);)r+="`";for(/[^ \r\n]/.test(i)&&(/^[ \r\n]/.test(i)&&/[ \r\n]$/.test(i)||/^`|`$/.test(i))&&(i=" "+i+" ");++o<s.unsafe.length;){const l=s.unsafe[o],c=s.compilePattern(l);let u;if(l.atBreak)for(;u=c.exec(i);){let d=u.index;i.charCodeAt(d)===10&&i.charCodeAt(d-1)===13&&d--,i=i.slice(0,d)+" "+i.slice(u.index+1)}}return r+i+r}function vM(){return"`"}function mg(e,n){const s=Od(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))}hg.peek=yM;function hg(e,n,s,i){const r=Gd(s),o=r==='"'?"Quote":"Apostrophe",l=s.createTracker(i);let c,u;if(mg(e,s)){const m=s.stack;s.stack=[],c=s.enter("autolink");let h=l.move("<");return h+=l.move(s.containerPhrasing(e,{before:h,after:">",...l.current()})),h+=l.move(">"),c(),s.stack=m,h}c=s.enter("link"),u=s.enter("label");let d=l.move("[");return d+=l.move(s.containerPhrasing(e,{before:d,after:"](",...l.current()})),d+=l.move("]("),u(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(u=s.enter("destinationLiteral"),d+=l.move("<"),d+=l.move(s.safe(e.url,{before:d,after:">",...l.current()})),d+=l.move(">")):(u=s.enter("destinationRaw"),d+=l.move(s.safe(e.url,{before:d,after:e.title?" ":")",...l.current()}))),u(),e.title&&(u=s.enter(`title${o}`),d+=l.move(" "+r),d+=l.move(s.safe(e.title,{before:d,after:r,...l.current()})),d+=l.move(r),u()),d+=l.move(")"),c(),d}function yM(e,n,s){return mg(e,s)?"<":"["}pg.peek=wM;function pg(e,n,s,i){const r=e.referenceType,o=s.enter("linkReference");let l=s.enter("label");const c=s.createTracker(i);let u=c.move("[");const d=s.containerPhrasing(e,{before:u,after:"]",...c.current()});u+=c.move(d+"]["),l();const m=s.stack;s.stack=[],l=s.enter("reference");const h=s.safe(s.associationId(e),{before:u,after:"]",...c.current()});return l(),s.stack=m,o(),r==="full"||!d||d!==h?u+=c.move(h+"]"):r==="shortcut"?u=u.slice(0,-1):u+=c.move("]"),u}function wM(){return"["}function Jd(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 jM(e){const n=Jd(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 kM(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 fg(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 NM(e,n,s,i){const r=s.enter("list"),o=s.bulletCurrent;let l=e.ordered?kM(s):Jd(s);const c=e.ordered?l==="."?")":".":jM(s);let u=n&&s.bulletLastUsed?l===s.bulletLastUsed:!1;if(!e.ordered){const m=e.children?e.children[0]:void 0;if((l==="*"||l==="-")&&m&&(!m.children||!m.children[0])&&s.stack[s.stack.length-1]==="list"&&s.stack[s.stack.length-2]==="listItem"&&s.stack[s.stack.length-3]==="list"&&s.stack[s.stack.length-4]==="listItem"&&s.indexStack[s.indexStack.length-1]===0&&s.indexStack[s.indexStack.length-2]===0&&s.indexStack[s.indexStack.length-3]===0&&(u=!0),fg(s)===l&&m){let h=-1;for(;++h<e.children.length;){const f=e.children[h];if(f&&f.type==="listItem"&&f.children&&f.children[0]&&f.children[0].type==="thematicBreak"){u=!0;break}}}}u&&(l=c),s.bulletCurrent=l;const d=s.containerFlow(e,i);return s.bulletLastUsed=l,s.bulletCurrent=o,r(),d}function SM(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 CM(e,n,s,i){const r=SM(s);let o=s.bulletCurrent||Jd(s);n&&n.type==="list"&&n.ordered&&(o=(typeof n.start=="number"&&n.start>-1?n.start:1)+(s.options.incrementListMarker===!1?0:n.children.indexOf(e))+o);let l=o.length+1;(r==="tab"||r==="mixed"&&(n&&n.type==="list"&&n.spread||e.spread))&&(l=Math.ceil(l/4)*4);const c=s.createTracker(i);c.move(o+" ".repeat(l-o.length)),c.shift(l);const u=s.enter("listItem"),d=s.indentLines(s.containerFlow(e,c.current()),m);return u(),d;function m(h,f,p){return f?(p?"":" ".repeat(l))+h:(p?o:o+" ".repeat(l-o.length))+h}}function EM(e,n,s,i){const r=s.enter("paragraph"),o=s.enter("phrasing"),l=s.containerPhrasing(e,i);return o(),r(),l}const _M=xl(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function MM(e,n,s,i){return(e.children.some(function(l){return _M(l)})?s.containerPhrasing:s.containerFlow).call(s,e,i)}function AM(e){const n=e.options.strong||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize strong with `"+n+"` for `options.strong`, expected `*`, or `_`");return n}gg.peek=RM;function gg(e,n,s,i){const r=AM(s),o=s.enter("strong"),l=s.createTracker(i),c=l.move(r+r);let u=l.move(s.containerPhrasing(e,{after:r,before:c,...l.current()}));const d=u.charCodeAt(0),m=Jo(i.before.charCodeAt(i.before.length-1),d,r);m.inside&&(u=Tr(d)+u.slice(1));const h=u.charCodeAt(u.length-1),f=Jo(i.after.charCodeAt(0),h,r);f.inside&&(u=u.slice(0,-1)+Tr(h));const p=l.move(r+r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+u+p}function RM(e,n,s){return s.options.strong||"*"}function TM(e,n,s,i){return s.safe(e.value,i)}function PM(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 IM(e,n,s){const i=(fg(s)+(s.options.ruleSpaces?" ":"")).repeat(PM(s));return s.options.ruleSpaces?i.slice(0,-1):i}const bg={blockquote:sM,break:dh,code:cM,definition:uM,emphasis:og,hardBreak:dh,heading:fM,html:lg,image:cg,imageReference:dg,inlineCode:ug,link:hg,linkReference:pg,list:NM,listItem:CM,paragraph:EM,root:MM,strong:gg,text:TM,thematicBreak:IM};function $M(){return{enter:{table:DM,tableData:uh,tableHeader:uh,tableRow:zM},exit:{codeText:OM,table:LM,tableData:lc,tableHeader:lc,tableRow:lc}}}function DM(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 LM(e){this.exit(e),this.data.inTable=void 0}function zM(e){this.enter({type:"tableRow",children:[]},e)}function lc(e){this.exit(e)}function uh(e){this.enter({type:"tableCell",children:[]},e)}function OM(e){let n=this.resume();this.data.inTable&&(n=n.replace(/\\([\\|])/g,FM));const s=this.stack[this.stack.length-1];s.type,s.value=n,this.exit(e)}function FM(e,n){return n==="|"?n:e}function UM(e){const n=e||{},s=n.tableCellPadding,i=n.tablePipeAlign,r=n.stringLength,o=s?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
|
|
650
|
-
`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:f,table:l,tableCell:u,tableRow:c}};function l(p,g,b,v){return d(m(p,b,v),p.align)}function c(p,g,b,v){const x=h(p,b,v),y=d([x]);return y.slice(0,y.indexOf(`
|
|
651
|
-
`))}function u(p,g,b,v){const x=b.enter("tableCell"),y=b.enter("phrasing"),j=b.containerPhrasing(p,{...v,before:o,after:o});return y(),x(),j}function d(p,g){return tM(p,{align:g,alignDelimiters:i,padding:s,stringLength:r})}function m(p,g,b){const v=p.children;let x=-1;const y=[],j=g.enter("table");for(;++x<v.length;)y[x]=h(v[x],g,b);return j(),y}function h(p,g,b){const v=p.children;let x=-1;const y=[],j=g.enter("tableRow");for(;++x<v.length;)y[x]=u(v[x],p,g,b);return j(),y}function f(p,g,b){let v=bg.inlineCode(p,g,b);return b.stack.includes("tableCell")&&(v=v.replace(/\|/g,"\\$&")),v}}function BM(){return{exit:{taskListCheckValueChecked:mh,taskListCheckValueUnchecked:mh,paragraph:qM}}}function HM(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:VM}}}function mh(e){const n=this.stack[this.stack.length-2];n.type,n.checked=e.type==="taskListCheckValueChecked"}function qM(e){const n=this.stack[this.stack.length-2];if(n&&n.type==="listItem"&&typeof n.checked=="boolean"){const s=this.stack[this.stack.length-1];s.type;const i=s.children[0];if(i&&i.type==="text"){const r=n.children;let o=-1,l;for(;++o<r.length;){const c=r[o];if(c.type==="paragraph"){l=c;break}}l===s&&(i.value=i.value.slice(1),i.value.length===0?s.children.shift():s.position&&i.position&&typeof i.position.start.offset=="number"&&(i.position.start.column++,i.position.start.offset++,s.position.start=Object.assign({},i.position.start)))}}this.exit(e)}function VM(e,n,s,i){const r=e.children[0],o=typeof e.checked=="boolean"&&r&&r.type==="paragraph",l="["+(e.checked?"x":" ")+"] ",c=s.createTracker(i);o&&c.move(l);let u=bg.listItem(e,n,s,{...i,...c.current()});return o&&(u=u.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,d)),u;function d(m){return m+l}}function WM(){return[N_(),V_(),J_(),$M(),BM()]}function KM(e){return{extensions:[S_(),W_(e),Y_(),UM(e),HM()]}}const GM={tokenize:eA,partial:!0},xg={tokenize:tA,partial:!0},vg={tokenize:nA,partial:!0},yg={tokenize:sA,partial:!0},JM={tokenize:iA,partial:!0},wg={name:"wwwAutolink",tokenize:XM,previous:kg},jg={name:"protocolAutolink",tokenize:ZM,previous:Ng},vi={name:"emailAutolink",tokenize:QM,previous:Sg},ui={};function YM(){return{text:ui}}let zi=48;for(;zi<123;)ui[zi]=vi,zi++,zi===58?zi=65:zi===91&&(zi=97);ui[43]=vi;ui[45]=vi;ui[46]=vi;ui[95]=vi;ui[72]=[vi,jg];ui[104]=[vi,jg];ui[87]=[vi,wg];ui[119]=[vi,wg];function QM(e,n,s){const i=this;let r,o;return l;function l(h){return!od(h)||!Sg.call(i,i.previous)||Yd(i.events)?s(h):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(h))}function c(h){return od(h)?(e.consume(h),c):h===64?(e.consume(h),u):s(h)}function u(h){return h===46?e.check(JM,m,d)(h):h===45||h===95||ls(h)?(o=!0,e.consume(h),u):m(h)}function d(h){return e.consume(h),r=!0,u}function m(h){return o&&r&&ps(i.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),n(h)):s(h)}}function XM(e,n,s){const i=this;return r;function r(l){return l!==87&&l!==119||!kg.call(i,i.previous)||Yd(i.events)?s(l):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(GM,e.attempt(xg,e.attempt(vg,o),s),s)(l))}function o(l){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),n(l)}}function ZM(e,n,s){const i=this;let r="",o=!1;return l;function l(h){return(h===72||h===104)&&Ng.call(i,i.previous)&&!Yd(i.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),r+=String.fromCodePoint(h),e.consume(h),c):s(h)}function c(h){if(ps(h)&&r.length<5)return r+=String.fromCodePoint(h),e.consume(h),c;if(h===58){const f=r.toLowerCase();if(f==="http"||f==="https")return e.consume(h),u}return s(h)}function u(h){return h===47?(e.consume(h),o?d:(o=!0,u)):s(h)}function d(h){return h===null||Wo(h)||yn(h)||Gi(h)||fl(h)?s(h):e.attempt(xg,e.attempt(vg,m),s)(h)}function m(h){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),n(h)}}function eA(e,n,s){let i=0;return r;function r(l){return(l===87||l===119)&&i<3?(i++,e.consume(l),r):l===46&&i===3?(e.consume(l),o):s(l)}function o(l){return l===null?s(l):n(l)}}function tA(e,n,s){let i,r,o;return l;function l(d){return d===46||d===95?e.check(yg,u,c)(d):d===null||yn(d)||Gi(d)||d!==45&&fl(d)?u(d):(o=!0,e.consume(d),l)}function c(d){return d===95?i=!0:(r=i,i=void 0),e.consume(d),l}function u(d){return r||i||!o?s(d):n(d)}}function nA(e,n){let s=0,i=0;return r;function r(l){return l===40?(s++,e.consume(l),r):l===41&&i<s?o(l):l===33||l===34||l===38||l===39||l===41||l===42||l===44||l===46||l===58||l===59||l===60||l===63||l===93||l===95||l===126?e.check(yg,n,o)(l):l===null||yn(l)||Gi(l)?n(l):(e.consume(l),r)}function o(l){return l===41&&i++,e.consume(l),r}}function sA(e,n,s){return i;function i(c){return c===33||c===34||c===39||c===41||c===42||c===44||c===46||c===58||c===59||c===63||c===95||c===126?(e.consume(c),i):c===38?(e.consume(c),o):c===93?(e.consume(c),r):c===60||c===null||yn(c)||Gi(c)?n(c):s(c)}function r(c){return c===null||c===40||c===91||yn(c)||Gi(c)?n(c):i(c)}function o(c){return ps(c)?l(c):s(c)}function l(c){return c===59?(e.consume(c),i):ps(c)?(e.consume(c),l):s(c)}}function iA(e,n,s){return i;function i(o){return e.consume(o),r}function r(o){return ls(o)?s(o):n(o)}}function kg(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||yn(e)}function Ng(e){return!ps(e)}function Sg(e){return!(e===47||od(e))}function od(e){return e===43||e===45||e===46||e===95||ls(e)}function Yd(e){let n=e.length,s=!1;for(;n--;){const i=e[n][1];if((i.type==="labelLink"||i.type==="labelImage")&&!i._balanced){s=!0;break}if(i._gfmAutolinkLiteralWalkedInto){s=!1;break}}return e.length>0&&!s&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),s}const aA={tokenize:hA,partial:!0};function rA(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:dA,continuation:{tokenize:uA},exit:mA}},text:{91:{name:"gfmFootnoteCall",tokenize:cA},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:oA,resolveTo:lA}}}}function oA(e,n,s){const i=this;let r=i.events.length;const o=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);let l;for(;r--;){const u=i.events[r][1];if(u.type==="labelImage"){l=u;break}if(u.type==="gfmFootnoteCall"||u.type==="labelLink"||u.type==="label"||u.type==="image"||u.type==="link")break}return c;function c(u){if(!l||!l._balanced)return s(u);const d=Ws(i.sliceSerialize({start:l.end,end:i.now()}));return d.codePointAt(0)!==94||!o.includes(d.slice(1))?s(u):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(u),e.exit("gfmFootnoteCallLabelMarker"),n(u))}}function lA(e,n){let s=e.length;for(;s--;)if(e[s][1].type==="labelImage"&&e[s][0]==="enter"){e[s][1];break}e[s+1][1].type="data",e[s+3][1].type="gfmFootnoteCallLabelMarker";const i={type:"gfmFootnoteCall",start:Object.assign({},e[s+3][1].start),end:Object.assign({},e[e.length-1][1].end)},r={type:"gfmFootnoteCallMarker",start:Object.assign({},e[s+3][1].end),end:Object.assign({},e[s+3][1].end)};r.end.column++,r.end.offset++,r.end._bufferIndex++;const o={type:"gfmFootnoteCallString",start:Object.assign({},r.end),end:Object.assign({},e[e.length-1][1].start)},l={type:"chunkString",contentType:"string",start:Object.assign({},o.start),end:Object.assign({},o.end)},c=[e[s+1],e[s+2],["enter",i,n],e[s+3],e[s+4],["enter",r,n],["exit",r,n],["enter",o,n],["enter",l,n],["exit",l,n],["exit",o,n],e[e.length-2],e[e.length-1],["exit",i,n]];return e.splice(s,e.length-s+1,...c),e}function cA(e,n,s){const i=this,r=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);let o=0,l;return c;function c(h){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),u}function u(h){return h!==94?s(h):(e.enter("gfmFootnoteCallMarker"),e.consume(h),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",d)}function d(h){if(o>999||h===93&&!l||h===null||h===91||yn(h))return s(h);if(h===93){e.exit("chunkString");const f=e.exit("gfmFootnoteCallString");return r.includes(Ws(i.sliceSerialize(f)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),n):s(h)}return yn(h)||(l=!0),o++,e.consume(h),h===92?m:d}function m(h){return h===91||h===92||h===93?(e.consume(h),o++,d):d(h)}}function dA(e,n,s){const i=this,r=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);let o,l=0,c;return u;function u(g){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),d}function d(g){return g===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",m):s(g)}function m(g){if(l>999||g===93&&!c||g===null||g===91||yn(g))return s(g);if(g===93){e.exit("chunkString");const b=e.exit("gfmFootnoteDefinitionLabelString");return o=Ws(i.sliceSerialize(b)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),f}return yn(g)||(c=!0),l++,e.consume(g),g===92?h:m}function h(g){return g===91||g===92||g===93?(e.consume(g),l++,m):m(g)}function f(g){return g===58?(e.enter("definitionMarker"),e.consume(g),e.exit("definitionMarker"),r.includes(o)||r.push(o),tn(e,p,"gfmFootnoteDefinitionWhitespace")):s(g)}function p(g){return n(g)}}function uA(e,n,s){return e.check(Wr,n,e.attempt(aA,n,s))}function mA(e){e.exit("gfmFootnoteDefinition")}function hA(e,n,s){const i=this;return tn(e,r,"gfmFootnoteDefinitionIndent",5);function r(o){const l=i.events[i.events.length-1];return l&&l[1].type==="gfmFootnoteDefinitionIndent"&&l[2].sliceSerialize(l[1],!0).length===4?n(o):s(o)}}function pA(e){let s=(e||{}).singleTilde;const i={name:"strikethrough",tokenize:o,resolveAll:r};return s==null&&(s=!0),{text:{126:i},insideSpan:{null:[i]},attentionMarkers:{null:[126]}};function r(l,c){let u=-1;for(;++u<l.length;)if(l[u][0]==="enter"&&l[u][1].type==="strikethroughSequenceTemporary"&&l[u][1]._close){let d=u;for(;d--;)if(l[d][0]==="exit"&&l[d][1].type==="strikethroughSequenceTemporary"&&l[d][1]._open&&l[u][1].end.offset-l[u][1].start.offset===l[d][1].end.offset-l[d][1].start.offset){l[u][1].type="strikethroughSequence",l[d][1].type="strikethroughSequence";const m={type:"strikethrough",start:Object.assign({},l[d][1].start),end:Object.assign({},l[u][1].end)},h={type:"strikethroughText",start:Object.assign({},l[d][1].end),end:Object.assign({},l[u][1].start)},f=[["enter",m,c],["enter",l[d][1],c],["exit",l[d][1],c],["enter",h,c]],p=c.parser.constructs.insideSpan.null;p&&Ms(f,f.length,0,gl(p,l.slice(d+1,u),c)),Ms(f,f.length,0,[["exit",h,c],["enter",l[u][1],c],["exit",l[u][1],c],["exit",m,c]]),Ms(l,d-1,u-d+3,f),u=d+f.length-2;break}}for(u=-1;++u<l.length;)l[u][1].type==="strikethroughSequenceTemporary"&&(l[u][1].type="data");return l}function o(l,c,u){const d=this.previous,m=this.events;let h=0;return f;function f(g){return d===126&&m[m.length-1][1].type!=="characterEscape"?u(g):(l.enter("strikethroughSequenceTemporary"),p(g))}function p(g){const b=Na(d);if(g===126)return h>1?u(g):(l.consume(g),h++,p);if(h<2&&!s)return u(g);const v=l.exit("strikethroughSequenceTemporary"),x=Na(g);return v._open=!x||x===2&&!!b,v._close=!b||b===2&&!!x,c(g)}}}class fA{constructor(){this.map=[]}add(n,s,i){gA(this,n,s,i)}consume(n){if(this.map.sort(function(o,l){return o[0]-l[0]}),this.map.length===0)return;let s=this.map.length;const i=[];for(;s>0;)s-=1,i.push(n.slice(this.map[s][0]+this.map[s][1]),this.map[s][2]),n.length=this.map[s][0];i.push(n.slice()),n.length=0;let r=i.pop();for(;r;){for(const o of r)n.push(o);r=i.pop()}this.map.length=0}}function gA(e,n,s,i){let r=0;if(!(s===0&&i.length===0)){for(;r<e.map.length;){if(e.map[r][0]===n){e.map[r][1]+=s,e.map[r][2].push(...i);return}r+=1}e.map.push([n,s,i])}}function bA(e,n){let s=!1;const i=[];for(;n<e.length;){const r=e[n];if(s){if(r[0]==="enter")r[1].type==="tableContent"&&i.push(e[n+1][1].type==="tableDelimiterMarker"?"left":"none");else if(r[1].type==="tableContent"){if(e[n-1][1].type==="tableDelimiterMarker"){const o=i.length-1;i[o]=i[o]==="left"?"center":"right"}}else if(r[1].type==="tableDelimiterRow")break}else r[0]==="enter"&&r[1].type==="tableDelimiterRow"&&(s=!0);n+=1}return i}function xA(){return{flow:{null:{name:"table",tokenize:vA,resolveAll:yA}}}}function vA(e,n,s){const i=this;let r=0,o=0,l;return c;function c(_){let P=i.events.length-1;for(;P>-1;){const M=i.events[P][1].type;if(M==="lineEnding"||M==="linePrefix")P--;else break}const U=P>-1?i.events[P][1].type:null,G=U==="tableHead"||U==="tableRow"?w:u;return G===w&&i.parser.lazy[i.now().line]?s(_):G(_)}function u(_){return e.enter("tableHead"),e.enter("tableRow"),d(_)}function d(_){return _===124||(l=!0,o+=1),m(_)}function m(_){return _===null?s(_):Ct(_)?o>1?(o=0,i.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(_),e.exit("lineEnding"),p):s(_):Qt(_)?tn(e,m,"whitespace")(_):(o+=1,l&&(l=!1,r+=1),_===124?(e.enter("tableCellDivider"),e.consume(_),e.exit("tableCellDivider"),l=!0,m):(e.enter("data"),h(_)))}function h(_){return _===null||_===124||yn(_)?(e.exit("data"),m(_)):(e.consume(_),_===92?f:h)}function f(_){return _===92||_===124?(e.consume(_),h):h(_)}function p(_){return i.interrupt=!1,i.parser.lazy[i.now().line]?s(_):(e.enter("tableDelimiterRow"),l=!1,Qt(_)?tn(e,g,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(_):g(_))}function g(_){return _===45||_===58?v(_):_===124?(l=!0,e.enter("tableCellDivider"),e.consume(_),e.exit("tableCellDivider"),b):C(_)}function b(_){return Qt(_)?tn(e,v,"whitespace")(_):v(_)}function v(_){return _===58?(o+=1,l=!0,e.enter("tableDelimiterMarker"),e.consume(_),e.exit("tableDelimiterMarker"),x):_===45?(o+=1,x(_)):_===null||Ct(_)?E(_):C(_)}function x(_){return _===45?(e.enter("tableDelimiterFiller"),y(_)):C(_)}function y(_){return _===45?(e.consume(_),y):_===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(_),e.exit("tableDelimiterMarker"),j):(e.exit("tableDelimiterFiller"),j(_))}function j(_){return Qt(_)?tn(e,E,"whitespace")(_):E(_)}function E(_){return _===124?g(_):_===null||Ct(_)?!l||r!==o?C(_):(e.exit("tableDelimiterRow"),e.exit("tableHead"),n(_)):C(_)}function C(_){return s(_)}function w(_){return e.enter("tableRow"),R(_)}function R(_){return _===124?(e.enter("tableCellDivider"),e.consume(_),e.exit("tableCellDivider"),R):_===null||Ct(_)?(e.exit("tableRow"),n(_)):Qt(_)?tn(e,R,"whitespace")(_):(e.enter("data"),S(_))}function S(_){return _===null||_===124||yn(_)?(e.exit("data"),R(_)):(e.consume(_),_===92?O:S)}function O(_){return _===92||_===124?(e.consume(_),S):S(_)}}function yA(e,n){let s=-1,i=!0,r=0,o=[0,0,0,0],l=[0,0,0,0],c=!1,u=0,d,m,h;const f=new fA;for(;++s<e.length;){const p=e[s],g=p[1];p[0]==="enter"?g.type==="tableHead"?(c=!1,u!==0&&(hh(f,n,u,d,m),m=void 0,u=0),d={type:"table",start:Object.assign({},g.start),end:Object.assign({},g.end)},f.add(s,0,[["enter",d,n]])):g.type==="tableRow"||g.type==="tableDelimiterRow"?(i=!0,h=void 0,o=[0,0,0,0],l=[0,s+1,0,0],c&&(c=!1,m={type:"tableBody",start:Object.assign({},g.start),end:Object.assign({},g.end)},f.add(s,0,[["enter",m,n]])),r=g.type==="tableDelimiterRow"?2:m?3:1):r&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")?(i=!1,l[2]===0&&(o[1]!==0&&(l[0]=l[1],h=bo(f,n,o,r,void 0,h),o=[0,0,0,0]),l[2]=s)):g.type==="tableCellDivider"&&(i?i=!1:(o[1]!==0&&(l[0]=l[1],h=bo(f,n,o,r,void 0,h)),o=l,l=[o[1],s,0,0])):g.type==="tableHead"?(c=!0,u=s):g.type==="tableRow"||g.type==="tableDelimiterRow"?(u=s,o[1]!==0?(l[0]=l[1],h=bo(f,n,o,r,s,h)):l[1]!==0&&(h=bo(f,n,l,r,s,h)),r=0):r&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")&&(l[3]=s)}for(u!==0&&hh(f,n,u,d,m),f.consume(n.events),s=-1;++s<n.events.length;){const p=n.events[s];p[0]==="enter"&&p[1].type==="table"&&(p[1]._align=bA(n.events,s))}return e}function bo(e,n,s,i,r,o){const l=i===1?"tableHeader":i===2?"tableDelimiter":"tableData",c="tableContent";s[0]!==0&&(o.end=Object.assign({},fa(n.events,s[0])),e.add(s[0],0,[["exit",o,n]]));const u=fa(n.events,s[1]);if(o={type:l,start:Object.assign({},u),end:Object.assign({},u)},e.add(s[1],0,[["enter",o,n]]),s[2]!==0){const d=fa(n.events,s[2]),m=fa(n.events,s[3]),h={type:c,start:Object.assign({},d),end:Object.assign({},m)};if(e.add(s[2],0,[["enter",h,n]]),i!==2){const f=n.events[s[2]],p=n.events[s[3]];if(f[1].end=Object.assign({},p[1].end),f[1].type="chunkText",f[1].contentType="text",s[3]>s[2]+1){const g=s[2]+1,b=s[3]-s[2]-1;e.add(g,b,[])}}e.add(s[3]+1,0,[["exit",h,n]])}return r!==void 0&&(o.end=Object.assign({},fa(n.events,r)),e.add(r,0,[["exit",o,n]]),o=void 0),o}function hh(e,n,s,i,r){const o=[],l=fa(n.events,s);r&&(r.end=Object.assign({},l),o.push(["exit",r,n])),i.end=Object.assign({},l),o.push(["exit",i,n]),e.add(s+1,0,o)}function fa(e,n){const s=e[n],i=s[0]==="enter"?"start":"end";return s[1][i]}const wA={name:"tasklistCheck",tokenize:kA};function jA(){return{text:{91:wA}}}function kA(e,n,s){const i=this;return r;function r(u){return i.previous!==null||!i._gfmTasklistFirstContentOfListItem?s(u):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(u),e.exit("taskListCheckMarker"),o)}function o(u){return yn(u)?(e.enter("taskListCheckValueUnchecked"),e.consume(u),e.exit("taskListCheckValueUnchecked"),l):u===88||u===120?(e.enter("taskListCheckValueChecked"),e.consume(u),e.exit("taskListCheckValueChecked"),l):s(u)}function l(u){return u===93?(e.enter("taskListCheckMarker"),e.consume(u),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),c):s(u)}function c(u){return Ct(u)?n(u):Qt(u)?e.check({tokenize:NA},n,s)(u):s(u)}}function NA(e,n,s){return tn(e,i,"whitespace");function i(r){return r===null?s(r):n(r)}}function SA(e){return Df([YM(),rA(),pA(e),xA(),jA()])}const CA={};function ci(e){const n=this,s=e||CA,i=n.data(),r=i.micromarkExtensions||(i.micromarkExtensions=[]),o=i.fromMarkdownExtensions||(i.fromMarkdownExtensions=[]),l=i.toMarkdownExtensions||(i.toMarkdownExtensions=[]);r.push(SA(s)),o.push(WM()),l.push(KM(s))}const ph=100;function Cg(e,n,s){const[i,r]=a.useState([]),[o,l]=a.useState(!1),[c,u]=a.useState(!1),[d,m]=a.useState(null),[h,f]=a.useState(!1),p=a.useRef(null),g=a.useRef(!1),b=a.useRef(0),v=a.useRef(e),x=a.useRef(s),y=a.useRef(n),j=a.useRef(0);(v.current!==e||x.current!==s||y.current!==n)&&(v.current=e,x.current=s,y.current=n,b.current++,g.current=!0,r([]),l(!1),u(!1),m(null),f(!1),p.current&&(p.current(),p.current=null)),a.useEffect(()=>{if(!e||!n){p.current&&(p.current(),p.current=null);return}const R=b.current,S=++j.current;g.current=!1;const O=e,_=s;async function P(){if(!O)return;l(!0),f(!1);try{const G=await ru(O,_,{limit:ph});if(g.current||b.current!==R||j.current!==S)return;r(G.entries),u(G.hasMore),m(G.total)}catch{if(g.current||b.current!==R||j.current!==S)return;r([]),u(!1),m(null)}finally{!g.current&&b.current===R&&j.current===S&&l(!1)}const U=_?`?projectId=${encodeURIComponent(_)}`:"";p.current=Js(`/api/tasks/${O}/logs/stream${U}`,{events:{"agent:log":G=>{if(!(g.current||b.current!==R))try{const M=JSON.parse(G.data);r(T=>[...T,M]),m(T=>T!==null?T+1:null)}catch{}}}})}return P(),()=>{g.current=!0,p.current&&(p.current(),p.current=null)}},[e,n,s]);const C=a.useCallback(async()=>{if(!e||h)return;const R=b.current,S=i.length,O=e;f(!0);try{const _=await ru(O,s,{limit:ph,offset:S});if(g.current||b.current!==R)return;r(P=>[..._.entries,...P]),u(_.hasMore),m(_.total)}catch{}finally{f(!1)}},[e,s,i.length,h]),w=a.useCallback(()=>r([]),[]);return{entries:i,loading:o,clear:w,loadMore:C,hasMore:c,total:d,loadingMore:h}}function EA(e){const n=new Date(e),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),o=Math.floor(r/60),l=Math.floor(o/24);return r<1?"just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString()}const fh={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})},Eg=50,_A={triage:"Plan"};function gh(e){return e.scrollHeight-(e.scrollTop+e.clientHeight)<=Eg}function ld(e){return[e.taskId,e.timestamp,e.agent??"",e.type,e.text,e.detail??""].join("|")}function MA(e){const n=new Map;return e.map(s=>{const i=ld(s),r=n.get(i)??0;return n.set(i,r+1),`${i}|${r}`})}function AA(e){return e==="tool"||e==="tool_result"||e==="tool_error"}function cc({detail:e}){const[n,s]=a.useState(!1),i=a.useId(),r=e.split(`
|
|
652
|
-
`).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":i,"data-testid":"tool-detail-toggle",children:[n?t.jsx(Yt,{size:14}):t.jsx(gn,{size:14}),t.jsx("span",{children:o})]}),t.jsx("div",{id:i,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 RA(e,n){return e.agent?AA(e.type)?!0:!n||n.agent!==e.agent||n.type!==e.type:!1}function TA(e,n){const s=[];for(let i=0;i<e.length;i+=1){const r=e[i],o=n[i]??`${ld(r)}|fallback`,l=i>0?e[i-1]:void 0,c=RA(r,l);if(r.type==="text"||r.type==="thinking"){const u=[r];let d=i+1;for(;d<e.length;){const h=e[d];if(h.type!==r.type||h.agent!==r.agent)break;u.push(h),d+=1}const m=n[d-1]??`${ld(e[d-1])}|fallback`;s.push({kind:r.type,entries:u,key:`${o}->${m}`,showBadge:c}),i=d-1;continue}s.push({kind:"single",entry:r,key:o,showBadge:c})}return s}function PA({entries:e,loading:n,executorModel:s,validatorModel:i,planningModel:r,hasMore:o=!1,onLoadMore:l,loadingMore:c=!1,totalCount:u=null}){const d=a.useRef(null),m=a.useRef(0),h=a.useRef(0),f=a.useRef(null),p=a.useRef(null),[g,b]=a.useState(!0),[v,x]=a.useState(!1),[y,j]=a.useState(!1),[E,C]=a.useState(!0),w=a.useMemo(()=>MA(e),[e]),R=a.useMemo(()=>TA(e,w),[e,w]);a.useLayoutEffect(()=>{const T=d.current;if(!T)return;const D=e.length,K=m.current,J=h.current||T.scrollHeight,te=w[0]??null,N=w[w.length-1]??null,z=f.current!==te,I=p.current!==N;if(D>K)if(K===0)T.scrollTop=T.scrollHeight;else{const k=J-(T.scrollTop+T.clientHeight)<=Eg,H=I&&!z,Q=z&&!I;if(H&&k&&(T.scrollTop=T.scrollHeight),Q){const ue=T.scrollHeight-J;ue>0&&(T.scrollTop+=ue)}}m.current=D,h.current=T.scrollHeight,f.current=te,p.current=N,C(gh(T))},[e,w]);const S=a.useCallback(()=>{const T=d.current;T&&C(gh(T))},[]),O=a.useCallback(()=>{const T=d.current;T&&(T.scrollTop=T.scrollHeight,C(!0))},[]),_=a.useCallback(T=>{T.key==="Escape"&&v&&x(!1)},[v]);a.useEffect(()=>{if(v)return document.addEventListener("keydown",_),()=>{document.removeEventListener("keydown",_)}},[v,_]);const P=s?.provider&&s?.modelId,U=i?.provider&&i?.modelId,G=r?.provider&&r?.modelId,M=a.useMemo(()=>{const T=[];return P&&T.push({role:"Executor",provider:s.provider,modelId:s.modelId}),U&&T.push({role:"Reviewer",provider:i.provider,modelId:i.modelId}),G&&T.push({role:"Planning",provider:r.provider,modelId:r.modelId}),T},[P,s,U,i,G,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:[M.map(T=>t.jsx(Rn,{provider:T.provider,size:"sm"},`${T.role}-${T.provider}-${T.modelId??"default"}`)),t.jsx("button",{className:"agent-log-model-expand-btn",onClick:()=>j(T=>!T),"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(Yt,{size:14}):t.jsx(gn,{size:14})})]}),t.jsxs("div",{className:"agent-log-model-header-toggle",children:[t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>b(T=>!T),"aria-label":g?"Switch to plain text mode":"Switch to markdown mode","aria-pressed":g,"data-testid":"agent-log-mode-toggle",title:g?"Show raw text":"Show formatted markdown",children:g?"Markdown":"Plain"}),t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>x(T=>!T),"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(Or,{size:14}):t.jsx(al,{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:"}),P?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Rn,{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:"}),U?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Rn,{provider:i.provider,size:"sm"}),t.jsxs("span",{children:[i.provider,"/",i.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]}),t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Planning:"}),G?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Rn,{provider:r.provider,size:"sm"}),t.jsxs("span",{children:[r.provider,"/",r.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]})]})]}),t.jsxs("div",{ref:d,className:"agent-log-viewer-scroll",onScroll:S,children:[u!==null&&t.jsxs("div",{className:"agent-log-summary","data-testid":"agent-log-summary",children:["Showing ",e.length," of ",u," entries"]}),o&&l&&t.jsx("div",{className:"agent-log-load-more","data-testid":"agent-log-load-more",children:t.jsx("button",{className:"agent-log-mode-toggle",onClick:l,disabled:c,"data-testid":"agent-log-load-more-button",children:c?t.jsxs(t.Fragment,{children:[t.jsx(lt,{size:14,className:"animate-spin"}),"Loading…"]}):"Load More"})}),R.map(T=>{const D=T.kind==="single"?T.entry:T.entries[0],K=T.showBadge?t.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:EA(D.timestamp)}):null,J=T.showBadge?t.jsxs("span",{className:"agent-log-badge-row",children:[t.jsxs("span",{className:"agent-log-agent-badge",children:["[",_A[D.agent]??D.agent,"]"]}),K]}):null;if(T.kind==="single"){const{entry:N}=T;if(N.type==="tool")return t.jsxs("div",{className:"agent-log-tool",children:[J,t.jsxs("div",{className:"agent-log-tool-title",children:["⚡ ",N.text]}),N.detail?t.jsx(cc,{detail:N.detail,type:"tool"}):null]},T.key);if(N.type==="tool_result")return t.jsxs("div",{className:"agent-log-tool-result",children:[J,t.jsxs("div",{className:"agent-log-tool-title",children:["✓ ",N.text]}),N.detail?t.jsx(cc,{detail:N.detail,type:"tool_result"}):null]},T.key);if(N.type==="tool_error")return t.jsxs("div",{className:"agent-log-tool-error",children:[J,t.jsxs("div",{className:"agent-log-tool-title",children:["✗ ",N.text]}),N.detail?t.jsx(cc,{detail:N.detail,type:"tool_error"}):null]},T.key)}const te=T.kind==="single"?D.text:T.entries.map(N=>N.text).join("");return T.kind==="thinking"?t.jsxs("div",{className:"agent-log-thinking",children:[J,g?t.jsx("div",{className:"markdown-body",children:t.jsx(li,{remarkPlugins:[ci],components:fh,children:te})}):t.jsx("pre",{className:"agent-log-plain-block",children:te})]},T.key):t.jsxs("div",{className:"agent-log-text",children:[J,g?t.jsx("div",{className:"markdown-body",children:t.jsx(li,{remarkPlugins:[ci],components:fh,children:te})}):t.jsx("pre",{className:"agent-log-plain-block",children:te})]},T.key)}),!E&&t.jsxs("button",{type:"button",className:"agent-log-return-to-live",onClick:O,"data-testid":"agent-log-return-to-live",children:[t.jsx(Yt,{size:12}),t.jsx("span",{children:"Live"})]})]})]})}function Sa(e){return e??void 0}function xo(e){return{provider:Sa(e.modelProvider),modelId:Sa(e.modelId)}}function vo(e){return{provider:Sa(e.validatorModelProvider),modelId:Sa(e.validatorModelId)}}function yo(e){return{provider:Sa(e.planningModelProvider),modelId:Sa(e.planningModelId)}}function IA(e,n){return Zp(e,n)}function $A(e,n){return ef(e,n)}function DA(e,n){return tf(e,n)}function dc(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 uc(e){return e.provider&&e.modelId?`${e.provider}/${e.modelId}`:""}function mc(e,n){return e.provider===n.provider&&e.modelId===n.modelId}function LA(e,n){const i={executor:"Executor",validator:"Reviewer",planning:"Planning"}[e]||e;return!n.provider||!n.modelId?`${i} model set to default`:`${i} model set to ${n.provider}/${n.modelId}`}function zA({task:e,addToast:n,onTaskUpdated:s,settings:i}){const[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState([]),[m,h]=a.useState(!1),[f,p]=a.useState(null),[g,b]=a.useState(()=>xo(e)),[v,x]=a.useState(()=>xo(e)),[y,j]=a.useState(()=>vo(e)),[E,C]=a.useState(()=>vo(e)),[w,R]=a.useState(()=>yo(e)),[S,O]=a.useState(()=>yo(e)),[_,P]=a.useState(()=>e.thinkingLevel??null),[U,G]=a.useState(()=>e.thinkingLevel??null),[M,T]=a.useState(null),D=a.useRef(e.id);a.useEffect(()=>{h(!0),p(null),bs().then(de=>{o(de.models),c(de.favoriteProviders),d(de.favoriteModels)}).catch(de=>{p(de.message||"Failed to load models")}).finally(()=>{h(!1)})},[]);const K=a.useCallback(async de=>{const me=l,_e=me.includes(de)?me.filter(Fe=>Fe!==de):[de,...me];c(_e);try{await bn({favoriteProviders:_e,favoriteModels:u})}catch{c(me),n("Failed to update favorites","error")}},[l,u,n]),J=a.useCallback(async de=>{const me=u,_e=me.includes(de)?me.filter(Fe=>Fe!==de):[de,...me];d(_e);try{await bn({favoriteProviders:l,favoriteModels:_e})}catch{d(me),n("Failed to update model favorites","error")}},[u,l,n]);a.useEffect(()=>{D.current=e.id;const de=xo(e),me=vo(e),se=yo(e);b(de),x(de),j(me),C(me),R(se),O(se);const _e=e.thinkingLevel??null;P(_e),G(_e),T(null)},[e.id,e.modelProvider,e.modelId,e.validatorModelProvider,e.validatorModelId,e.planningModelProvider,e.planningModelId,e.thinkingLevel]);const te=a.useMemo(()=>uc(g),[g]),N=a.useMemo(()=>uc(y),[y]),z=a.useMemo(()=>uc(w),[w]),I=a.useMemo(()=>IA(e,i),[e,i]),k=a.useMemo(()=>$A(e,i),[e,i]),H=a.useMemo(()=>DA(e,i),[e,i]),Q=M!==null,ue=a.useCallback(async(de,me)=>{const se=e.id,_e=v,Fe=E,Te=S;T(de);try{const st=s?de==="executor"?{modelProvider:me.provider??null,modelId:me.modelId??null}:de==="validator"?{validatorModelProvider:me.provider??null,validatorModelId:me.modelId??null}:{planningModelProvider:me.provider??null,planningModelId:me.modelId??null}:{modelProvider:(de==="executor"?me:v).provider??null,modelId:(de==="executor"?me:v).modelId??null,validatorModelProvider:(de==="validator"?me:E).provider??null,validatorModelId:(de==="validator"?me:E).modelId??null,planningModelProvider:(de==="planning"?me:S).provider??null,planningModelId:(de==="planning"?me:S).modelId??null},nt=await ii(se,st);if(D.current!==se)return;const qe=xo(nt),Xe=vo(nt),$e=yo(nt);x(qe),b(qe),C(Xe),j(Xe),O($e),R($e),s?.(nt),n(LA(de,{executor:qe,validator:Xe,planning:$e}[de]),"success")}catch(st){if(D.current!==se)return;de==="executor"?b(_e):de==="validator"?j(Fe):R(Te),n(ke(st)||"Failed to save model settings","error")}finally{D.current===se&&T(null)}},[e.id,v,E,S,n,s]),be=a.useCallback(de=>{const me=dc(de);b(me),!mc(me,v)&&ue("executor",me)},[v,ue]),V=a.useCallback(de=>{const me=dc(de);j(me),!mc(me,E)&&ue("validator",me)},[E,ue]),ve=a.useCallback(de=>{const me=dc(de);R(me),!mc(me,S)&&ue("planning",me)},[S,ue]),B=a.useCallback(async de=>{const me=e.id,se=U,_e=de===""?null:de;P(_e),T("thinking");try{const Fe=await ii(me,{thinkingLevel:_e});if(D.current!==me)return;const Te=Fe.thinkingLevel??null;G(Te),P(Te),s?.(Fe);const st=i?.defaultThinkingLevel??"off";n(Te===null?`Thinking level set to default (${st})`:`Thinking level set to ${Te}`,"success")}catch(Fe){if(D.current!==me)return;P(se),n(ke(Fe)||"Failed to save thinking level","error")}finally{D.current===me&&T(null)}},[e.id,U,i,n,s]),Y=!v.provider&&!v.modelId,X=!E.provider&&!E.modelId,he=!S.provider&&!S.modelId;return t.jsxs("div",{className:"model-selector-tab",children:[t.jsx("h4",{children:"Model Configuration"}),t.jsx("p",{className:"model-selector-intro",children:"Override the AI models used for this task. When not specified, project or global defaults are used."}),m?t.jsx("div",{className:"model-selector-loading",children:"Loading available models…"}):f?t.jsxs("div",{className:"model-selector-error",children:["Error loading models: ",f,t.jsx("button",{className:"btn btn-sm",onClick:()=>{h(!0),p(null),bs().then(de=>{o(de.models),c(de.favoriteProviders),d(de.favoriteModels)}).catch(de=>p(de.message)).finally(()=>h(!1))},style:{marginLeft:"8px"},children:"Retry"})]}):r.length===0?t.jsx("div",{className:"model-selector-empty",children:"No models available. Configure authentication in Settings to enable model selection."}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"executorModel",children:"Executor Model"}),t.jsx("div",{className:"model-selector-current",children:Y?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",I.provider&&I.modelId?` (${I.provider}/${I.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[v.provider&&t.jsx(Rn,{provider:v.provider,size:"sm"}),v.provider,"/",v.modelId]})}),t.jsx(ns,{id:"executorModel",label:"Executor Model",value:te,onChange:be,models:r,disabled:Q,placeholder:"Select executor model…",favoriteProviders:l,onToggleFavorite:K,favoriteModels:u,onToggleModelFavorite:J}),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:X?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",k.provider&&k.modelId?` (${k.provider}/${k.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[E.provider&&t.jsx(Rn,{provider:E.provider,size:"sm"}),E.provider,"/",E.modelId]})}),t.jsx(ns,{id:"validatorModel",label:"Reviewer Model",value:N,onChange:V,models:r,disabled:Q,placeholder:"Select reviewer model…",favoriteProviders:l,onToggleFavorite:K,favoriteModels:u,onToggleModelFavorite:J}),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:he?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",H.provider&&H.modelId?` (${H.provider}/${H.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[S.provider&&t.jsx(Rn,{provider:S.provider,size:"sm"}),S.provider,"/",S.modelId]})}),t.jsx(ns,{id:"planningModel",label:"Planning Model",value:z,onChange:ve,models:r,disabled:Q,placeholder:"Select planning model…",favoriteProviders:l,onToggleFavorite:K,favoriteModels:u,onToggleModelFavorite:J}),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:U===null?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default (",i?.defaultThinkingLevel??"off",")"]}):t.jsx("span",{className:"model-badge model-badge-custom",children:U})}),t.jsxs("select",{id:"thinkingLevel",value:_??"",onChange:de=>B(de.target.value),disabled:Q,className:"thinking-level-select",children:[t.jsxs("option",{value:"",children:["Default (",i?.defaultThinkingLevel??"off",")"]}),t.jsx("option",{value:"off",children:"Off"}),t.jsx("option",{value:"minimal",children:"Minimal"}),t.jsx("option",{value:"low",children:"Low"}),t.jsx("option",{value:"medium",children:"Medium"}),t.jsx("option",{value:"high",children:"High"})]}),t.jsx("small",{children:"Controls the reasoning effort for the AI agent. Higher levels use more tokens."})]}),t.jsx("div",{className:"model-selector-status",children:Y&&X&&he&&U===null?"Using project or global default models.":"Model settings are up to date."})]})]})}const OA={open:t.jsx(tl,{size:16}),closed:t.jsx(Lr,{size:16}),merged:t.jsx(Cp,{size:16})};function FA({taskId:e,projectId:n,prInfo:s,automationStatus:i,autoMerge:r=!1,prAuthAvailable:o,onPrCreated:l,onPrUpdated:c,addToast:u}){const[d,m]=a.useState(!1),[h,f]=a.useState(""),[p,g]=a.useState(""),[b,v]=a.useState(!1),[x,y]=a.useState(!1),[j,E]=a.useState(null),C=a.useCallback(async()=>{if(h.trim()){v(!0);try{const O=await fw(e,{title:h.trim(),body:p.trim()||void 0},n);l(O),m(!1),f(""),g(""),u(`Created PR #${O.number}`,"success")}catch(O){u(ke(O)||"Failed to create PR","error")}finally{v(!1)}}},[e,h,p,n,l,u]),w=a.useCallback(async()=>{if(s){y(!0);try{const O=await gw(e,n);E(O),c(O.prInfo),u("PR status refreshed","success")}catch(O){u(ke(O)||"Failed to refresh PR","error")}finally{y(!1)}}},[e,s,n,c,u]);if(!s)return i==="creating-pr"?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Es,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsx("div",{className:"pr-hint pr-hint--muted",children:"fn is creating a pull request automatically for this task."})]}):r?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Es,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsx("div",{className:"pr-hint pr-hint--muted",children:"Auto-merge will handle this task automatically."})]}):d?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Es,{size:16,className:"pr-section-icon"}),"Create Pull Request"]}),t.jsxs("div",{className:"pr-form",children:[t.jsx("input",{type:"text",placeholder:"PR title",value:h,onChange:O=>f(O.target.value),disabled:b,className:"pr-input"}),t.jsx("textarea",{placeholder:"PR description (optional)",value:p,onChange:O=>g(O.target.value),disabled:b,className:"pr-textarea",rows:3}),t.jsxs("div",{className:"pr-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>m(!1),disabled:b,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:C,disabled:!h.trim()||b,children:b?"Creating…":"Create PR"})]})]})]}):t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Es,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>m(!0),disabled:!o,title:o?"Create a PR for this task":"PR auth unavailable — run 'gh auth login'",children:[t.jsx(dn,{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 R=OA[s.status]??t.jsx(tl,{size:16}),S=j?.blockingReasons??[];return t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Es,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsxs("div",{className:`pr-card pr-card--status-${s.status}`,children:[t.jsxs("div",{className:"pr-header",children:[t.jsx("span",{className:"pr-status-icon",children:R}),t.jsx("span",{className:`pr-status-badge pr-status-badge--${s.status}`,children:s.status}),t.jsxs("span",{className:"pr-number",children:["#",s.number]}),t.jsx("div",{className:"pr-spacer"}),t.jsx("button",{className:"btn btn-sm pr-refresh-btn",onClick:w,disabled:x,title:"Refresh PR status",children:t.jsx(Fn,{size:14,style:{verticalAlign:"middle",opacity:x?.5:1}})})]}),t.jsx("div",{className:"pr-title",children:s.title}),t.jsxs("div",{className:"pr-meta",children:[t.jsx("span",{children:s.headBranch}),t.jsx("span",{className:"pr-meta-arrow",children:"→"}),t.jsx("span",{children:s.baseBranch})]}),i==="merging-pr"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:"fn is merging this pull request automatically."}),i==="awaiting-pr-checks"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:S.length>0?`Waiting for: ${S.join("; ")}`:"Waiting for required checks or review feedback before auto-merge."}),s.status==="merged"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:"This PR is merged. fn will finish local cleanup and move the task to Done."}),t.jsxs("div",{className:"pr-footer",children:[s.commentCount>0&&t.jsxs("span",{className:"pr-comments",children:[t.jsx(Si,{size:14}),s.commentCount]}),t.jsxs("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"pr-link",children:[t.jsx(ax,{size:14}),"View on GitHub"]})]})]})]})}const bh=2e3;function UA(e){const n=e.updatedAt||e.createdAt,s=new Date(n).toLocaleString();return e.updatedAt?`${s} (edited)`:s}function BA(e){return e==="agent"||e==="system"}function HA({task:e,onTaskUpdated:n,addToast:s,currentAuthor:i="user",projectId:r}){const[o,l]=a.useState(""),[c,u]=a.useState(null),[d,m]=a.useState(""),[h,f]=a.useState(!1),[p,g]=a.useState(null),b=a.useMemo(()=>[...e.comments||[]].sort((R,S)=>new Date(S.createdAt).getTime()-new Date(R.createdAt).getTime()),[e.comments]),v=o.length>bh;async function x(){const R=o.trim();if(R){f(!0);try{const S=await Fy(e.id,R,r);l(""),n?.(S),s("Comment added","success")}catch(S){s(ke(S)||"Failed to add comment","error")}finally{f(!1)}}}async function y(R){const S=d.trim();if(S){f(!0);try{const O=await $y(e.id,R,S,r);u(null),m(""),n?.(O),s("Comment updated","success")}catch(O){s(ke(O)||"Failed to update comment","error")}finally{f(!1)}}}async function j(R){g(R);try{const S=await Dy(e.id,R,r);n?.(S),s("Comment deleted","success")}catch(S){s(ke(S)||"Failed to delete comment","error")}finally{g(null)}}function E(R){R.key==="Enter"&&(R.ctrlKey||R.metaKey)&&(R.preventDefault(),x())}return t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Comments"}),b.length===0?t.jsx("div",{className:"detail-log-empty",children:"No comments yet."}):t.jsx("div",{className:"detail-activity-list",children:b.map(R=>{const S=R.author===i,O=c===R.id,_=BA(R.author);return t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header comments-header-row",children:[t.jsxs("div",{className:"comments-author-row",children:[_?t.jsx("span",{className:"ai-guidance-badge","data-testid":"ai-guidance-badge",children:"AI Guidance"}):t.jsx("strong",{children:R.author}),t.jsx("span",{className:"detail-log-timestamp",children:UA(R)})]}),S&&!O?t.jsxs("div",{className:"comments-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{u(R.id),m(R.text)},children:"Edit"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void j(R.id),disabled:p===R.id,children:p===R.id?"Deleting…":"Delete"})]}):null]}),O?t.jsxs("div",{className:"comments-edit-form",children:[t.jsx("textarea",{value:d,onChange:P=>m(P.target.value),rows:3,className:"comments-textarea"}),t.jsxs("div",{className:"comments-edit-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{u(null),m("")},disabled:h,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void y(R.id),disabled:h||!d.trim(),children:"Save"})]})]}):t.jsx("div",{className:"detail-log-outcome comments-outcome-text",children:R.text})]},R.id)})}),t.jsxs("div",{className:"comments-compose-form",children:[t.jsx("textarea",{value:o,onChange:R=>l(R.target.value),onKeyDown:E,rows:3,placeholder:"Add a comment",className:"comments-textarea"}),t.jsxs("div",{className:"comments-footer-row",children:[t.jsxs("span",{className:`comments-char-count${v?" comments-char-count--over":""}`,children:[o.length," / ",bh]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void x(),disabled:h||!o.trim()||v,children:h?"Posting…":"Add Comment"})]})]})]})}function qA(e){return e?e.slice(0,7):"Unknown"}function VA({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:qA(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 _g(e){return e.split(`
|
|
653
|
-
`).map((s,i)=>{let r="";return s.startsWith("+")&&!s.startsWith("+++")?r="diff-add":s.startsWith("-")&&!s.startsWith("---")?r="diff-del":s.startsWith("@@")&&(r="diff-hunk"),r?t.jsx("span",{className:r,children:`${s}
|
|
654
|
-
`},i):t.jsx($o.Fragment,{children:`${s}
|
|
655
|
-
`},i)})}function WA(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function KA({isOpen:e,taskId:n,files:s,stats:i,mergeDetails:r,column:o,onClose:l,onRefresh:c}){const[u,d]=a.useState(null),[m,h]=a.useState(!0),f=a.useRef(null);di(f,e,"fusion:changes-diff-modal-size");const p=Mi(l);a.useEffect(()=>{s.length>0&&u===null&&d(0)},[s,u]);const g=a.useCallback(()=>{d(y=>y!==null&&y>0?y-1:y)},[]),b=a.useCallback(()=>{d(y=>y!==null&&y<s.length-1?y+1:y)},[]);if(a.useEffect(()=>{if(!e)return;const y=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(),b())};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[e,l,g,b]),!e)return null;const v=u!==null?s[u]:null,x=o==="done";return t.jsx("div",{className:"modal-overlay open",...p,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal changes-diff-modal",ref:f,children:[t.jsxs("div",{className:"modal-header changes-diff-modal-header",children:[t.jsxs("div",{className:"changes-diff-header-title",children:[t.jsx(qs,{size:18}),t.jsxs("span",{children:["Changes — ",n]}),t.jsxs("span",{className:"changes-stat-summary",children:[t.jsxs("span",{className:"diff-add",children:["+",i.additions]})," ",t.jsxs("span",{className:"diff-del",children:["-",i.deletions]})]})]}),t.jsxs("div",{className:"changes-diff-header-actions",children:[s.length>0&&t.jsxs("div",{className:"changes-nav",children:[t.jsx("button",{className:"btn btn-sm btn-icon",onClick:g,disabled:u===null||u<=0,title:"Previous file (Ctrl+↑)","aria-label":"Previous file",children:t.jsx(el,{})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:u!==null?`${u+1}/${s.length}`:`—/${s.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:b,disabled:u===null||u>=s.length-1,title:"Next file (Ctrl+↓)","aria-label":"Next file",children:t.jsx(gn,{})})]}),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(Oo,{size:14})}),c&&t.jsxs("button",{className:"btn btn-sm",onClick:c,children:[t.jsx(Fn,{size:14}),"Refresh"]}),t.jsx("button",{className:"modal-close",onClick:l,"aria-label":"Close",children:t.jsx(qt,{size:20})})]})]}),t.jsxs("div",{className:"changes-diff-body",children:[t.jsxs("div",{className:"changes-diff-sidebar",children:[x&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(zr,{size:14}),t.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergeCommitMessage&&t.jsx("div",{className:"commit-diff-message",children:r.mergeCommitMessage}),r.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),t.jsx("div",{className:"changes-diff-file-list",children:s.map((y,j)=>t.jsxs("button",{className:`changes-diff-file-item ${u===j?"selected":""}`,onClick:()=>d(j),title:y.path,children:[t.jsx("span",{className:`changes-file-status changes-file-status--${y.status}`,children:WA(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:_g(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(qs,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to view its diff"})]})})]})]})})}function Mg(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function hc(e,n,s){return t.jsxs("div",{className:"detail-section task-changes-tab",children:[n&&s&&t.jsxs("div",{className:"commit-diff-meta",children:[s.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(zr,{size:14}),t.jsx("code",{children:s.commitSha.slice(0,7)})]}),s.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(s.mergedAt).toLocaleString()]})]}),t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(qs,{size:24}),t.jsxs("p",{children:[e.length," file",e.length===1?"":"s"," modified during execution."]}),t.jsx("span",{className:"task-changes-state-hint",children:n?"The recorded merge commit has no diff (likely collapsed into a squash on main). Showing file paths only — patches unavailable.":"The live worktree diff is empty. Showing the last file paths captured during execution — patches unavailable."})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:e.map(i=>t.jsx("div",{className:"changes-file-item",children:t.jsxs("div",{className:"changes-file-header changes-file-header--static",children:[t.jsx("span",{className:"changes-file-status changes-file-status--unknown",title:"status unknown",children:Mg("unknown")}),t.jsx("span",{className:"changes-file-path",title:i,children:t.jsx("bdo",{dir:"ltr",children:i})})]})},i))})]})}function GA({taskId:e,worktree:n,projectId:s,column:i,mergeDetails:r,modifiedFiles:o}){const[l,c]=a.useState([]),[u,d]=a.useState({filesChanged:0,additions:0,deletions:0}),[m,h]=a.useState(!0),[f,p]=a.useState(null),[g,b]=a.useState(new Set),[v,x]=a.useState(null),[y,j]=a.useState(!0),[E,C]=a.useState(!1),w=i==="done",R=w&&!!r?.commitSha,S=i==="in-progress"||i==="in-review"||R,O=a.useCallback(async()=>{if(!S){h(!1);return}try{h(!0),p(null);const M=await Hp(e,void 0,s),T=M.files.map(D=>({path:D.path,status:D.status,additions:D.additions,deletions:D.deletions,patch:D.patch}));c(T),d(M.stats),T.length>0&&(b(new Set([T[0].path])),x(0))}catch(M){p(ke(M)||"Failed to load diff")}finally{h(!1)}},[e,s,S]);a.useEffect(()=>{O()},[O]);const _=M=>{b(T=>{const D=new Set(T);if(D.has(M))D.delete(M);else{D.add(M);const K=l.findIndex(J=>J.path===M);K!==-1&&x(K)}return D})},P=M=>{if(M<0||M>=l.length)return;const T=l[M].path;b(new Set([T])),x(M)},U=v!==null&&v>0,G=v!==null&&v<l.length-1;if(m)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--loading",children:[t.jsx("div",{className:"loading-spinner"}),t.jsx("span",{children:"Loading changes..."})]})});if(f)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--error",children:[t.jsx(gs,{size:16}),t.jsxs("span",{children:["Error loading changes: ",f]})]})});if(!w&&!n)return o&&o.length>0?hc(o,!1):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(qs,{size:24}),t.jsx("p",{children:"No worktree available for this task."}),t.jsx("span",{className:"task-changes-state-hint",children:"Changes will be shown once the task is in progress."})]})});if(w&&!R){if(o&&o.length>0)return hc(o,!0,r);const M=r?.filesChanged,T=r?.insertions,D=r?.deletions,K=M!=null||T!=null||D!=null;return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(qs,{size:24}),t.jsx("p",{children:"Detailed file changes unavailable."}),t.jsx("span",{className:"task-changes-state-hint",children:K?`Merge summary: ${M??0} file${(M??0)===1?"":"s"} changed, +${T??0} additions, -${D??0} deletions.`:"No merge commit was recorded for this task."})]})})}return l.length===0?o&&o.length>0?hc(o,w,r):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(qs,{size:24}),t.jsx("p",{children:"No files modified."}),t.jsx("span",{className:"task-changes-state-hint",children:w?"No file changes were recorded in the merge commit.":"The agent did not modify any files during execution."})]})}):t.jsxs("div",{className:"detail-section task-changes-tab",children:[w&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(zr,{size:14}),t.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergeCommitMessage&&t.jsx("div",{className:"commit-diff-message",children:r.mergeCommitMessage}),r.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),t.jsxs("div",{className:"changes-header",children:[t.jsxs("div",{className:"task-changes-header-title",children:[t.jsxs("h4",{children:[t.jsx(qs,{size:16}),"Files Changed (",u.filesChanged,")"]}),t.jsxs("span",{className:"task-changes-stats changes-stat-summary",children:[t.jsxs("span",{className:"diff-add",children:["+",u.additions]})," ",t.jsxs("span",{className:"diff-del",children:["-",u.deletions]})]})]}),t.jsxs("div",{className:"changes-header-actions-wrapper",children:[t.jsxs("div",{className:"changes-header-actions",children:[l.length>0&&t.jsxs("div",{className:"changes-nav",children:[t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>U&&P(v-1),disabled:!U,title:"Previous file","aria-label":"Previous file",children:t.jsx(el,{})}),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:()=>G&&P(v+1),disabled:!G,title:"Next file","aria-label":"Next file",children:t.jsx(gn,{})})]}),t.jsx("button",{className:`btn btn-sm ${y?"btn-primary":""}`,onClick:()=>j(M=>!M),title:y?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(Oo,{size:14})})]}),t.jsxs("div",{className:"changes-header-actions-secondary",children:[t.jsx("button",{className:"btn btn-sm",onClick:O,disabled:m,children:"Refresh"}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>C(!0),title:"Expand to full-screen diff view","aria-label":"Expand diff view",children:t.jsx(al,{})})]})]})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:l.map(M=>{const T=g.has(M.path);return t.jsxs("div",{className:`changes-file-item ${T?"expanded":""}`,children:[t.jsxs("button",{className:"changes-file-header",onClick:()=>_(M.path),children:[t.jsx("span",{className:"changes-file-toggle",children:T?t.jsx(Yt,{size:14}):t.jsx(gn,{size:14})}),t.jsx("span",{className:`changes-file-status changes-file-status--${M.status}`,title:M.status,children:Mg(M.status)}),t.jsx("span",{className:"changes-file-path",title:M.path,children:t.jsx("bdo",{dir:"ltr",children:M.path})}),t.jsxs("span",{className:"changes-file-stat",title:`+${M.additions} -${M.deletions}`,children:["+",M.additions," -",M.deletions]})]}),T&&M.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:_g(M.patch)})})})]},M.path)})}),t.jsx(KA,{isOpen:E,taskId:e,files:l,stats:u,mergeDetails:r,column:i,onClose:()=>C(!1),onRefresh:O})]})}function xh(e){return{executorValue:e?.executorProvider&&e?.executorModelId?`${e.executorProvider}/${e.executorModelId}`:"",validatorValue:e?.validatorProvider&&e?.validatorModelId?`${e.validatorProvider}/${e.validatorModelId}`:""}}function JA(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function G3(e,n){const s=JA(e),i=new Set(n.map(c=>c.id));if(!i.has(s))return s;const r=30;let o=s,l=1;for(;i.has(o)&&l<100;){const c=`-${l}`;o=`${s.slice(0,r-c.length)}${c}`,l++}return o}function YA(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}const vh=["image/png","image/jpeg","image/gif","image/webp"];function QA(e,n,s){const i=e==="post-merge"?"phase-badge--post-merge":"phase-badge--pre-merge";return t.jsx("span",{className:`phase-badge ${i}`,"data-testid":`${s}-${n}`,children:e==="post-merge"?"Post-merge":"Pre-merge"})}function Ag({mode:e,description:n,onDescriptionChange:s,title:i,onTitleChange:r,dependencies:o,onDependenciesChange:l,nodeId:c,onNodeIdChange:u,nodeOptions:d,nodeOverrideDisabled:m=!1,nodeOverrideDisabledReason:h,priority:f,onPriorityChange:p,executorModel:g,onExecutorModelChange:b,validatorModel:v,onValidatorModelChange:x,planningModel:y,onPlanningModelChange:j,thinkingLevel:E,onThinkingLevelChange:C,presetMode:w,onPresetModeChange:R,selectedPresetId:S,onSelectedPresetIdChange:O,selectedWorkflowSteps:_,onWorkflowStepsChange:P,onDefaultOnApplied:U,pendingImages:G,onImagesChange:M,tasks:T,projectId:D,disabled:K=!1,addToast:J,isActive:te=!0,onAutoSaveDescription:N,onPlanningMode:z,onSubtaskBreakdown:I,onClose:k,renderBelowPrimary:H,renderBelowModelConfiguration:Q,hideDependencies:ue,autoExpandMoreOptionsOnSelection:be=!0,reviewLevel:V,onReviewLevelChange:ve,executionMode:B,onExecutionModeChange:Y}){const X=(ue?!1:o.length>0)||G.length>0||_.length>0||w!=="default"||(f??_s)!==_s||g!==""||v!==""||(y||"")!==""||(E||"")!==""||V!==void 0||B==="fast"||(c||"")!=="",[he,de]=a.useState(!1),[me,se]=a.useState(be?X:!1),[_e,Fe]=a.useState(""),[Te,st]=a.useState([]),[nt,qe]=a.useState([]),[Xe,$e]=a.useState([]),[Ue,oe]=a.useState(!1),[je,ie]=a.useState(null),[Ae,Le]=a.useState([]),[we,Ee]=a.useState("idle"),[Ve,rt]=a.useState(!1),[xe,ce]=a.useState(!1),[Pe,pe]=a.useState(!1),Re=a.useRef(null),Qe=a.useRef(null),Ie=a.useRef(null),bt=a.useRef(null),ee=a.useRef(null),re=a.useRef(null),Se=a.useRef(null),ot=a.useRef(!1),ne=a.useRef(X),Ze=a.useRef(n.trim()),ft=a.useRef(n.trim());a.useEffect(()=>{te&&(oe(!0),bs().then(L=>{st(L.models),qe(L.favoriteProviders),$e(L.favoriteModels)}).catch(()=>{}).finally(()=>oe(!1)),ll(D).then(L=>ie(L)).catch(()=>ie(null)),Br(D).then(L=>Le(L.filter(F=>F.enabled))).catch(()=>Le([])))},[te,D]);const gt=je?.modelPresets||[],St=gt.find(L=>L.id===S),Nt=(ue?!1:o.length>0)||G.length>0||_.length>0||w!=="default"||(f??_s)!==_s||g!==""||v!==""||(y||"")!==""||(E||"")!==""||V!==void 0||B==="fast"||(c||"")!=="";a.useEffect(()=>{if(e!=="create"||!te||!je?.autoSelectModelPreset)return;const L=(je.defaultPresetBySize,void 0);if(L){const F=xh(L);O(L.id),R("preset"),b(F.executorValue),x(F.validatorValue)}},[te,je,gt,e]);const pt=a.useRef(!1);a.useEffect(()=>{if(e!=="create"||!te||pt.current||Ae.length===0)return;const L=Ae.filter(ge=>ge.defaultOn);if(L.length===0)return;pt.current=!0;const F=L.map(ge=>ge.id);P(F),U?.(F)},[e,te,Ae]),a.useEffect(()=>{te||(pt.current=!1)},[te]),a.useEffect(()=>{if(!be){ne.current=Nt;return}Nt&&!ne.current&&se(!0),ne.current=Nt},[Nt,be]),a.useEffect(()=>{me||(de(!1),Fe(""))},[me]),a.useEffect(()=>{e!=="edit"||!te||bt.current&&(bt.current.focus(),bt.current.select())},[e,te]),a.useEffect(()=>{if(!he)return;const L=F=>{Qe.current&&!Qe.current.contains(F.target)&&de(!1)};return document.addEventListener("mousedown",L),()=>document.removeEventListener("mousedown",L)},[he]),a.useEffect(()=>{(e!=="edit"||K)&&pe(!1)},[e,K]),a.useEffect(()=>{if(e!=="edit"){Ee("idle");return}const L=n.trim();Ze.current=L,ft.current=L,Ee("idle")},[e]),a.useEffect(()=>{if(e!=="edit"||!N||!te)return;const L=n.trim(),F=Ze.current;if(L===F||L===ft.current){re.current&&(clearTimeout(re.current),re.current=null),ot.current||Ee("idle");return}return re.current&&clearTimeout(re.current),re.current=setTimeout(async()=>{if(!ot.current){ot.current=!0,Ee("saving");try{await N(L),ft.current=L,Ee("saved"),Se.current&&clearTimeout(Se.current),Se.current=setTimeout(()=>{Ee("idle"),Se.current=null},2e3)}catch{Ee("idle")}finally{ot.current=!1,re.current=null}}},1500),()=>{re.current&&(clearTimeout(re.current),re.current=null)}},[e,n,N,te]),a.useEffect(()=>()=>{re.current&&clearTimeout(re.current),Se.current&&clearTimeout(Se.current)},[]),a.useEffect(()=>{if(!Ve)return;const L=F=>{Re.current&&!Re.current.contains(F.target)&&rt(!1)};return document.addEventListener("mousedown",L),()=>document.removeEventListener("mousedown",L)},[Ve]);const kt=a.useCallback(L=>{const F=L.clipboardData?.items;if(F)for(let ge=0;ge<F.length;ge++){const ze=F[ge];if(ze.type.startsWith("image/")){const Be=ze.getAsFile();if(Be&&vh.includes(Be.type)){L.preventDefault(),M([...G,{file:Be,previewUrl:URL.createObjectURL(Be)}]);return}}}},[G,M]),Ht=a.useCallback(L=>{L.preventDefault();const F=L.dataTransfer.files;for(let ge=0;ge<F.length;ge++){const ze=F[ge];if(vh.includes(ze.type)){M([...G,{file:ze,previewUrl:URL.createObjectURL(ze)}]);return}}},[G,M]),$t=a.useCallback(L=>{const F=G[L];F&&URL.revokeObjectURL(F.previewUrl),M(G.filter((ge,ze)=>ze!==L))},[G,M]),Tt=a.useCallback(L=>{l(o.includes(L)?o.filter(F=>F!==L):[...o,L])},[o,l]),Mt=(L,F)=>L.length>F?L.slice(0,F)+"…":L,Ot=a.useCallback(L=>{s(L.target.value);const F=L.target;F.style.height="auto",F.style.height=F.scrollHeight+"px"},[s]),zt=a.useCallback(()=>{pe(L=>!L)},[]),Ft=a.useCallback(L=>{!Pe||L.key!=="Escape"||(L.preventDefault(),L.stopPropagation(),pe(!1))},[Pe]),Et=a.useCallback(async L=>{const F=n.trim();if(!(!F||xe)){ce(!0);try{const ge=await Op(F,L,D);s(ge),rt(!1),J("Description refined with AI","success"),Ie.current&&(Ie.current.style.height="auto",Ie.current.style.height=Ie.current.scrollHeight+"px")}catch(ge){const ze=Fp(ge);J(ze,"error")}finally{ce(!1)}}},[n,xe,J,s,D]),Pt=a.useCallback(async L=>{const F=nt,ze=F.includes(L)?F.filter(Be=>Be!==L):[L,...F];qe(ze);try{await bn({favoriteProviders:ze,favoriteModels:Xe})}catch{qe(F)}},[nt,Xe]),Dt=a.useCallback(async L=>{const F=Xe,ze=F.includes(L)?F.filter(Be=>Be!==L):[L,...F];$e(ze);try{await bn({favoriteProviders:nt,favoriteModels:ze})}catch{$e(F)}},[Xe,nt]),Wt=a.useCallback(L=>{if(L<=0)return;const F=[..._];[F[L-1],F[L]]=[F[L],F[L-1]],P(F)},[_,P]),It=a.useCallback(L=>{if(L>=_.length-1)return;const F=[..._];[F[L],F[L+1]]=[F[L+1],F[L]],P(F)},[_,P]),Rt=a.useCallback(L=>{P(_.filter(F=>F!==L))},[_,P]),fe=new Map;for(const L of Ae)fe.set(L.id,{name:L.name,description:L.description});const Oe=T.filter(L=>!o.includes(L.id)).sort((L,F)=>{const ge=F.createdAt.localeCompare(L.createdAt);if(ge!==0)return ge;const ze=parseInt(L.id.slice(L.id.lastIndexOf("-")+1),10)||0;return(parseInt(F.id.slice(F.id.lastIndexOf("-")+1),10)||0)-ze}),ut=_e?Oe.filter(L=>L.id.toLowerCase().includes(_e.toLowerCase())||L.title&&L.title.toLowerCase().includes(_e.toLowerCase())||L.description&&L.description.toLowerCase().includes(_e.toLowerCase())):Oe;return t.jsxs("div",{className:"task-form",onDrop:Ht,onDragOver:L=>L.preventDefault(),onPaste:kt,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:bt,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:"Task title",value:i||"",onChange:L=>r(L.target.value),disabled:K})]}),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${we==="idle"?"":" is-visible"}`,"aria-live":"polite",children:we==="saving"?"Saving...":we==="saved"?"Saved":""})]}),t.jsxs("div",{className:`description-with-refine${Pe?" description--fullscreen":""}`,ref:Re,onKeyDown:Ft,children:[Pe&&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:zt,"aria-label":"Collapse description",title:"Collapse description",children:t.jsx(Or,{size:14})})]}),t.jsx("textarea",{ref:Ie,autoFocus:e==="create",id:"task-form-description",value:n,onChange:Ot,placeholder:"What needs to be done?",rows:e==="edit"?8:5,disabled:K||xe}),(()=>{const L=!!n.trim()&&!K;return t.jsxs(t.Fragment,{children:[!Pe&&t.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${L?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:zt,"aria-label":"Expand description",title:"Expand description",children:t.jsx(al,{size:14})}),L&&t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${xe?"refine-button--loading":""}`,onClick:()=>rt(F=>!F),disabled:xe,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(cs,{size:12,style:{verticalAlign:"middle"}}),xe?"Refining...":"Refine"]})]})})(),Ve&&t.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:L=>L.preventDefault(),children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>Et("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:()=>Et("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:()=>Et("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:()=>Et("simplify"),"data-testid":"refine-simplify",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Simplify"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Simplify and make more concise"})]})]})]})]}),e==="create"&&(z||I)&&t.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[z&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const L=n.trim();if(!L){J("Enter a description first","error");return}k?.(),z(L)},disabled:K||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),I&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const L=n.trim();if(!L){J("Enter a description first","error");return}k?.(),I(L)},disabled:K||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),H,t.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>se(L=>!L),"aria-expanded":me,"aria-controls":"task-form-more-options",disabled:K,"data-testid":"task-form-more-options-toggle",children:[t.jsx("span",{children:"More options"}),me?t.jsx(bi,{size:14}):t.jsx(Yt,{size:14})]}),t.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${me?"":" collapsed"}`,"aria-hidden":!me,hidden:!me,"data-testid":"task-form-more-options",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Attachments"}),G.length>0&&t.jsx("div",{className:"inline-create-previews",children:G.map((L,F)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:L.previewUrl,alt:L.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>$t(F),disabled:K,title:"Remove image",children:"×"})]},L.previewUrl))}),t.jsx("input",{ref:ee,type:"file",accept:"image/*",onChange:L=>{const F=L.target.files?.[0];F&&(M([...G,{file:F,previewUrl:URL.createObjectURL(F)}]),L.target.value="")},style:{display:"none"}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>ee.current?.click(),disabled:K,children:"Attach Screenshot"}),t.jsx("small",{children:"You can also paste images or drag & drop"})]}),u&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"task-node-select",children:"Execution Node Override"}),t.jsxs("select",{id:"task-node-select",className:"select",value:c??"",onChange:L=>u(L.target.value||void 0),disabled:K||m,children:[t.jsx("option",{value:"",children:"Use project default / local"}),(d??[]).map(L=>t.jsxs("option",{value:L.id,children:[L.name," (",YA(L.status),")"]},L.id))]}),(()=>{const L=(d??[]).find(F=>F.id===c);return L?t.jsx("div",{className:"task-form-node-status",children:t.jsx(Wi,{status:L.status,showLabel:!0})}):null})(),t.jsx("small",{children:h??"Task override takes priority over project default node routing."})]}),!ue&&t.jsx(t.Fragment,{children:t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"dep-trigger-wrap",ref:Qe,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>de(L=>!L),disabled:K,children:o.length>0?`${o.length} selected`:"Add dependencies"}),he&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:_e,onChange:L=>Fe(L.target.value),onClick:L=>L.stopPropagation()}),ut.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):ut.map(L=>t.jsxs("div",{className:`dep-dropdown-item${o.includes(L.id)?" selected":""}`,onClick:()=>Tt(L.id),onMouseDown:F=>F.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:L.id}),t.jsx("span",{className:"dep-dropdown-title",children:Mt(L.title||L.description||L.id,30)})]},L.id))]})]}),o.length>0&&t.jsx("div",{className:"selected-deps",children:o.map(L=>t.jsxs("span",{className:"dep-chip",children:[L,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>Tt(L),disabled:K,children:"×"})]},L))})]})}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Model Configuration"}),p&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"task-priority",className:"model-select-label",children:"Priority"}),t.jsx("select",{id:"task-priority","data-testid":"task-priority-select",value:f??_s,onChange:L=>p(L.target.value),disabled:K,children:Cd.map(L=>t.jsx("option",{value:L,children:L[0].toUpperCase()+L.slice(1)},L))})]}),Y&&B!==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:B,onChange:L=>Y(L.target.value),disabled:K,children:[t.jsx("option",{value:"standard",children:"Standard"}),t.jsx("option",{value:"fast",children:"Fast"})]})]}),Ue?t.jsx("div",{className:"model-selector-loading",children:"Loading models…"}):Te.length===0?t.jsx("small",{children:"No models available. Configure authentication in Settings."}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"model-preset",className:"model-select-label",children:"Preset"}),t.jsxs("select",{id:"model-preset",value:w==="preset"?S:w,onChange:L=>{const F=L.target.value;if(F==="default"){R("default"),O(""),b(""),x("");return}if(F==="custom"){R("custom"),O("");return}const ge=gt.find(Be=>Be.id===F),ze=xh(ge);R("preset"),O(F),b(ze.executorValue),x(ze.validatorValue)},disabled:K,children:[t.jsx("option",{value:"default",children:"Use default"}),gt.length>0?t.jsx("option",{disabled:!0,children:"──────────"}):null,gt.map(L=>t.jsx("option",{value:L.id,children:L.name},L.id)),t.jsx("option",{value:"custom",children:"Custom"})]})]}),w==="preset"&&St?t.jsxs("small",{children:["Using preset: ",St.name]}):null,w==="preset"?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>R("custom"),disabled:K,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(ns,{id:"executor-model",label:"Executor Model",value:g,onChange:L=>{R("custom"),O(""),b(L)},models:Te,disabled:K||w==="preset",favoriteProviders:nt,onToggleFavorite:Pt,favoriteModels:Xe,onToggleModelFavorite:Dt})]}),t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"validator-model",className:"model-select-label",children:"Reviewer"}),t.jsx(ns,{id:"validator-model",label:"Reviewer Model",value:v,onChange:L=>{R("custom"),O(""),x(L)},models:Te,disabled:K||w==="preset",favoriteProviders:nt,onToggleFavorite:Pt,favoriteModels:Xe,onToggleModelFavorite:Dt})]}),j&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"planning-model",className:"model-select-label",children:"Planning"}),t.jsx(ns,{id:"planning-model",label:"Planning Model",value:y||"",onChange:L=>{R("custom"),O(""),j(L)},models:Te,disabled:K||w==="preset",favoriteProviders:nt,onToggleFavorite:Pt,favoriteModels:Xe,onToggleModelFavorite:Dt})]}),C&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"thinking-level",className:"model-select-label",children:"Thinking"}),t.jsxs("select",{id:"thinking-level",value:E||"",onChange:L=>C(L.target.value),disabled:K||w==="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"})]})]}),ve&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"review-level",className:"model-select-label",children:"Review"}),t.jsxs("select",{id:"review-level",value:V??"",onChange:L=>ve(L.target.value===""?void 0:parseInt(L.target.value,10)),disabled:K,children:[t.jsx("option",{value:"",children:"Default (Auto — triage decides)"}),t.jsx("option",{value:"0",children:"0 — None"}),t.jsx("option",{value:"1",children:"1 — Plan Only"}),t.jsx("option",{value:"2",children:"2 — Plan and Code"}),t.jsx("option",{value:"3",children:"3 — Full"})]})]})]})]}),Q,t.jsxs("div",{className:"form-group","data-testid":"workflow-steps-section",children:[t.jsx("label",{children:"Workflow Steps"}),t.jsxs("div",{className:"workflow-steps-section",children:[t.jsx("small",{className:"workflow-steps-description",children:"Select steps to run after task implementation completes"}),t.jsx("div",{className:"workflow-steps-list",children:Ae.length>0&&Ae.map(L=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${L.id}`,children:[t.jsx("input",{type:"checkbox",checked:_.includes(L.id),onChange:F=>{P(F.target.checked?[..._,L.id]:_.filter(ge=>ge!==L.id))},disabled:K}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[L.name,QA(L.phase||"pre-merge",L.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:L.description})]})]},L.id))})]}),_.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),_.map((L,F)=>{const ge=fe.get(L);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${L}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:F+1}),t.jsx("span",{className:"workflow-step-order-name",children:ge?.name||L}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Wt(F),disabled:K||F===0,"data-testid":`workflow-step-move-up-${L}`,title:"Move up",children:t.jsx(bi,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>It(F),disabled:K||F===_.length-1,"data-testid":`workflow-step-move-down-${L}`,title:"Move down",children:t.jsx(Yt,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Rt(L),disabled:K,"data-testid":`workflow-step-remove-${L}`,title:"Remove",children:t.jsx(qt,{})})]})]},L)})]})]})]})]})}const yh={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 XA(e){switch(e){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return e}}function ZA(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 eR(e){return e?new Date(e).toLocaleString():null}function tR(e){const n=e.split(`
|
|
656
|
-
`);return n.length<=1?e:`${n.length} lines`}function wo(e,n,s){const i=e==="post-merge"?"phase-badge--post-merge":"phase-badge--pre-merge";return t.jsx("span",{className:`phase-badge ${i}`,"data-testid":`${s}-${n}`,children:e==="post-merge"?"Post-merge":"Pre-merge"})}function nR({entries:e,startedAt:n,stepId:s}){const i=a.useRef(null),r=new Date(n).getTime(),o=e.filter(l=>new Date(l.timestamp).getTime()>=r);return a.useEffect(()=>{const l=i.current;l&&(l.scrollTop=l.scrollHeight)},[o.length]),e.length===0?t.jsx("div",{className:"workflow-live-log","data-testid":`workflow-live-log-${s}`,children:t.jsx("div",{className:"workflow-live-log-empty",children:"Waiting for agent output…"})}):t.jsx("div",{ref:i,className:"workflow-live-log","data-testid":`workflow-live-log-${s}`,children:o.map((l,c)=>l.type==="tool"?t.jsxs("div",{className:"workflow-live-log-tool",children:["⚡ ",l.text,l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",l.detail]})]},c):l.type==="tool_result"?t.jsxs("div",{className:"workflow-live-log-tool-result",children:["✓ ",l.text,l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",l.detail]})]},c):l.type==="tool_error"?t.jsxs("div",{className:"workflow-live-log-tool-error",children:["✗ ",l.text,l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",l.detail]})]},c):l.type==="thinking"?t.jsx("div",{className:"workflow-live-log-thinking",children:l.text},c):t.jsx("span",{className:"workflow-live-log-text",children:l.text},c))})}function sR({taskId:e,results:n,loading:s,enabledWorkflowSteps:i,canEdit:r,projectId:o,isTaskInProgress:l,onWorkflowStepsChange:c}){const[u,d]=a.useState({}),[m,h]=a.useState({}),[f,p]=a.useState(null),[g,b]=a.useState([]),[v,x]=a.useState(!1),y=n.some(k=>k.status==="pending"),{entries:j}=Cg(e,!!l&&y,o);a.useEffect(()=>{let k=!1;return Br(o).then(H=>{k||b(H.filter(Q=>Q.enabled))}).catch(()=>{k||b([])}),()=>{k=!0}},[o]);const E=i??[],C=a.useMemo(()=>g.map(k=>({id:k.id,name:k.name,description:k.description,phase:k.phase||"pre-merge"})),[g]),w=a.useMemo(()=>new Map(C.map(k=>[k.id,k])),[C]),R=k=>{d(H=>({...H,[k]:!H[k]}))},S=k=>{h(H=>{const Q=H[k]??"markdown";return{...H,[k]:Q==="markdown"?"plain":"markdown"}})},O=k=>{p(k)},_=()=>{p(null)};a.useEffect(()=>{if(!f)return;const k=H=>{H.key==="Escape"&&_()};return document.addEventListener("keydown",k),()=>{document.removeEventListener("keydown",k)}},[f]);const P=a.useCallback((k,H)=>{if(c){if(H){if(E.includes(k)){c(E);return}c([...E,k]);return}c(E.filter(Q=>Q!==k))}},[c,E]),U=a.useCallback(k=>{if(!c||k<=0)return;const H=[...E];[H[k-1],H[k]]=[H[k],H[k-1]],c(H)},[c,E]),G=a.useCallback(k=>{if(!c||k>=E.length-1)return;const H=[...E];[H[k],H[k+1]]=[H[k+1],H[k]],c(H)},[c,E]),M=a.useCallback(k=>{c&&c(E.filter(H=>H!==k))},[c,E]),T=n.length>0,D=E.length>0;a.useEffect(()=>{r||x(!1)},[r]);const K=a.useMemo(()=>E.map(k=>{const H=w.get(k);return{id:k,name:H?.name||k,description:H?.description||"Step definition not found.",phase:H?.phase||"pre-merge"}}),[E,w]),J=()=>!r||!v||s?null:t.jsxs("div",{className:"workflow-results-editor","data-testid":"workflow-steps-editor",children:[t.jsxs("div",{className:"workflow-steps-section",children:[t.jsx("small",{className:"workflow-steps-description",children:"Select steps to run after task implementation completes"}),t.jsx("div",{className:"workflow-steps-list",children:C.map(k=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${k.id}`,children:[t.jsx("input",{type:"checkbox",checked:E.includes(k.id),onChange:H=>P(k.id,H.target.checked)}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[k.name,wo(k.phase,k.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:k.description})]})]},k.id))})]}),E.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),E.map((k,H)=>{const Q=w.get(k);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${k}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:H+1}),t.jsx("span",{className:"workflow-step-order-name",children:Q?.name||k}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>U(H),disabled:H===0,"data-testid":`workflow-step-move-up-${k}`,title:"Move up",children:t.jsx(bi,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>G(H),disabled:H===E.length-1,"data-testid":`workflow-step-move-down-${k}`,title:"Move down",children:t.jsx(Yt,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>M(k),"data-testid":`workflow-step-remove-${k}`,title:"Remove",children:t.jsx(qt,{})})]})]},k)})]})]}),te=()=>{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(!T)return t.jsxs("div",{className:"workflow-results-empty","data-testid":"workflow-results-empty",children:[t.jsx("p",{children:"No workflow steps configured for this task."}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."})]});const k=n.filter(V=>V.status==="passed").length,H=n.filter(V=>V.status==="failed").length,Q=n.filter(V=>V.status==="skipped").length,ue=n.filter(V=>V.status==="pending").length,be=[`${n.length} step${n.length!==1?"s":""}`];return k>0&&be.push(`${k} passed`),H>0&&be.push(`${H} failed`),Q>0&&be.push(`${Q} skipped`),ue>0&&be.push(`${ue} running`),t.jsxs("div",{className:"workflow-results-list","data-testid":"workflow-results-list",children:[t.jsx("div",{className:"workflow-results-summary-bar","data-testid":"workflow-results-summary",children:be.join(" · ")}),n.map((V,ve)=>{const B=V.phase||"pre-merge",Y=u[V.workflowStepId]??!1;return t.jsxs("div",{className:`workflow-result-item workflow-result-item--${V.status}`,"data-testid":`workflow-result-item-${V.workflowStepId}`,children:[t.jsxs("div",{className:"workflow-result-header",children:[t.jsxs("div",{className:"workflow-result-name",children:[V.workflowStepName,wo(B,V.workflowStepId,"workflow-result-phase")]}),t.jsx("span",{className:`workflow-result-badge workflow-result-badge--${V.status}`,"data-testid":`workflow-result-badge-${V.workflowStepId}`,children:XA(V.status)})]}),t.jsxs("div",{className:"workflow-result-meta",children:[V.startedAt&&t.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",eR(V.startedAt)]}),V.completedAt&&t.jsx("span",{className:"workflow-result-duration",children:ZA(V.startedAt,V.completedAt)})]}),V.status==="pending"&&V.startedAt?t.jsx(nR,{entries:j,startedAt:V.startedAt,stepId:V.workflowStepId}):V.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:()=>R(V.workflowStepId),"data-testid":`workflow-result-toggle-${V.workflowStepId}`,children:Y?"Hide output":"Show output"}),!Y&&t.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${V.workflowStepId}`,children:tR(V.output)}),Y&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>S(V.workflowStepId),"data-testid":`workflow-result-mode-toggle-${V.workflowStepId}`,title:(m[V.workflowStepId]??"markdown")==="markdown"?"Switch to plain text":"Switch to markdown",children:(m[V.workflowStepId]??"markdown")==="markdown"?"Markdown":"Plain"}),t.jsx("button",{className:"workflow-result-expand-toggle",onClick:()=>O(V.workflowStepId),"data-testid":`workflow-result-expand-${V.workflowStepId}`,title:"Expand output",children:t.jsx(al,{size:12})})]})]}),Y&&t.jsx("div",{className:`workflow-result-output${(m[V.workflowStepId]??"markdown")==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":`workflow-result-output-${V.workflowStepId}`,children:(m[V.workflowStepId]??"markdown")==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(li,{remarkPlugins:[ci],components:yh,children:V.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:V.output})})]}):null]},`${V.workflowStepId}-${ve}`)})]})},N=r?t.jsx("button",{type:"button",className:"modal-edit-btn workflow-results-edit-toggle",onClick:()=>x(k=>!k),"data-testid":"workflow-steps-edit-toggle","aria-label":v?"Done editing workflow steps":"Edit workflow steps",title:v?"Done":"Edit",children:v?t.jsxs(t.Fragment,{children:[t.jsx(Jn,{size:14}),"Done"]}):t.jsxs(t.Fragment,{children:[t.jsx(hs,{size:14}),"Edit"]})}):null,z=!s&&!T&&D,I=r&&T;return t.jsxs("div",{className:"workflow-results-tab","data-task-id":e,children:[z?t.jsxs("div",{className:"workflow-configured-steps","data-testid":"workflow-configured-steps",children:[t.jsxs("div",{className:"workflow-configured-header","data-testid":"workflow-configured-header",children:[t.jsxs("div",{className:"workflow-configured-title-row",children:[t.jsx("h4",{children:"Configured Workflow Steps"}),t.jsxs("span",{className:"workflow-configured-count","data-testid":"workflow-configured-count",children:[K.length," step",K.length===1?"":"s"]})]}),N]}),t.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:K.map(k=>t.jsxs("div",{className:"workflow-configured-item","data-testid":`workflow-configured-step-${k.id}`,children:[t.jsxs("div",{className:"workflow-configured-name",children:[k.name,wo(k.phase,k.id,"workflow-configured-phase")]}),t.jsx("p",{className:"workflow-configured-description",children:k.description})]},k.id))}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."}),J()]}):t.jsxs(t.Fragment,{children:[I&&t.jsxs("div",{className:"workflow-results-edit-header","data-testid":"workflow-results-edit-header",children:[t.jsx("h4",{children:"Workflow Steps"}),N]}),te(),J()]}),f&&(()=>{const k=n.find(ue=>ue.workflowStepId===f);if(!k)return null;const H=m[k.workflowStepId]??"markdown",Q=k.phase||"pre-merge";return t.jsx("div",{className:"workflow-output-modal-overlay",onClick:ue=>{ue.target===ue.currentTarget&&_()},"data-testid":"workflow-output-modal",children:t.jsxs("div",{className:"workflow-output-modal",role:"dialog","aria-modal":"true",children:[t.jsxs("div",{className:"workflow-output-modal-header",children:[t.jsxs("div",{className:"workflow-output-modal-title",children:[t.jsx("span",{className:"workflow-output-modal-name",children:k.workflowStepName}),wo(Q,k.workflowStepId,"workflow-output-modal-phase")]}),t.jsxs("div",{className:"workflow-output-modal-controls",children:[t.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>S(k.workflowStepId),"data-testid":"workflow-output-modal-mode-toggle",title:H==="markdown"?"Switch to plain text":"Switch to markdown",children:H==="markdown"?"Markdown":"Plain"}),t.jsx("button",{className:"workflow-output-modal-close",onClick:_,"data-testid":"workflow-output-modal-close","aria-label":"Close",children:t.jsx(qt,{size:16})})]})]}),t.jsx("div",{className:"workflow-output-modal-body",children:t.jsx("div",{className:`workflow-result-output workflow-result-output--expanded${H==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":"workflow-output-modal-content",children:H==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(li,{remarkPlugins:[ci],components:yh,children:k.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:k.output})})})]})})})()]})}function iR(e){return e==="block"?"Block execution":e==="fallback-local"?"Fall back to local":"Not configured"}const aR=new Set(["planning","researching","executing","finalizing","merging"]);function rR(e){return e!==void 0&&e!=="online"}function oR({task:e,settings:n,addToast:s,onTaskUpdated:i}){const[r,o]=a.useState([]),[l,c]=a.useState(!1),[u,d]=a.useState(null),[m,h]=a.useState(e.nodeId??""),[f,p]=a.useState(!1),g=a.useRef(e.id);a.useEffect(()=>{g.current=e.id,h(e.nodeId??""),p(!1)},[e.id,e.nodeId]),a.useEffect(()=>{c(!0),d(null),Bo().then(_=>{o(_)}).catch(_=>{d(ke(_)||"Failed to load nodes")}).finally(()=>{c(!1)})},[]);const b=a.useMemo(()=>new Map(r.map(_=>[_.id,_])),[r]),v=a.useMemo(()=>[...r].sort((_,P)=>_.name.localeCompare(P.name)),[r]),x=n,y=e.nodeId??x?.defaultNodeId??null,j=e.nodeId?"Per-task override":x?.defaultNodeId?"Project default":"No routing",E=y?b.get(y):void 0,C=E?`${E.name} (${E.type})`:y?`${y} (node unavailable or unknown)`:"Local (no routing configured)",w=e.column==="in-progress"||aR.has(e.status),R=w||f||l,S=a.useCallback(async _=>{if(_===m)return;const P=e.id,U=m;h(_),p(!0);try{const G=await ii(P,{nodeId:_||null});if(g.current!==P)return;h(G.nodeId??""),i?.(G),s(_?"Node override updated":"Node override cleared","success")}catch(G){if(g.current!==P)return;h(U),s(ke(G)||"Failed to update node override","error")}finally{g.current===P&&p(!1)}},[s,i,m,e.id]),O=a.useCallback(()=>{S("")},[S]);return t.jsxs("div",{className:"routing-tab",children:[t.jsx("h4",{children:"Task Routing"}),t.jsx("p",{className:"routing-tab__intro",children:"View the effective execution node and control per-task node override."}),t.jsxs("section",{className:"routing-tab__section",children:[t.jsx("h5",{children:"Routing Summary"}),t.jsxs("div",{className:"routing-summary-grid",role:"list",children:[t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Effective node"}),t.jsxs("span",{className:"routing-summary-value",children:[E?t.jsx(Wi,{status:E.status,compact:!0}):null,C,rR(E?.status)?t.jsx("span",{className:"routing-summary-warning",children:"Unhealthy"}):null]})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Routing source"}),t.jsx("span",{className:"routing-summary-value",children: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:iR(x?.unavailableNodePolicy)})]})]}),w&&y?t.jsx("div",{className:"routing-tab__info-banner",children:"Routing is locked while this task is active. Node override cannot be changed until the task is no longer active."}):null]}),t.jsxs("section",{className:"routing-tab__section",children:[t.jsx("h5",{children:"Node Override"}),w?t.jsx("div",{className:"routing-tab__warning-banner",children:"Node override cannot be changed while the task is active."}):null,t.jsx("label",{className:"routing-tab__selector-label",htmlFor:`routing-node-${e.id}`,children:"Select execution node"}),t.jsxs("select",{id:`routing-node-${e.id}`,className:"select routing-tab__selector",value:m,disabled:R,onChange:_=>{S(_.target.value)},children:[t.jsx("option",{value:"",children:"Use project default"}),v.map(_=>t.jsxs("option",{value:_.id,title:`Status: ${_.status}`,children:[_.name," (",_.type,") — ",_.status]},_.id))]}),u?t.jsx("div",{className:"routing-tab__error",children:u}):null,e.nodeId?t.jsxs("div",{className:"routing-tab__override-row",children:[t.jsxs("span",{className:"routing-tab__override-text",children:["Override set to: ",b.get(e.nodeId)?.name??e.nodeId]}),t.jsx("button",{type:"button",className:"btn btn-sm",disabled:w||f,onClick:O,children:"Clear override"})]}):null]})]})}const lR=/^[a-zA-Z0-9_-]{1,64}$/,cR=200;function wh(e){return e?new Date(e).toLocaleString():""}function dR(e,n=cR){return e.length<=n?e:e.substring(0,n)+"…"}function uR({taskId:e,addToast:n,onTaskUpdated:s,projectId:i,canEdit:r=!1}){const[o,l]=a.useState([]),[c,u]=a.useState(!0),[d,m]=a.useState(null),[h,f]=a.useState(""),[p,g]=a.useState(null),[b,v]=a.useState(""),[x,y]=a.useState(null),[j,E]=a.useState([]),[C,w]=a.useState(!1),[R,S]=a.useState(!1),[O,_]=a.useState(""),[P,U]=a.useState(""),[G,M]=a.useState(!1),[T,D]=a.useState(null),[K,J]=a.useState(null),[te,N]=a.useState(!1),z=a.useCallback(async()=>{try{const B=await Ly(e,i);l(B)}catch(B){n(ke(B)||"Failed to load documents","error")}finally{u(!1)}},[e,i,n]);a.useEffect(()=>{z()},[z]);async function I(B){d===B.key?(m(null),f(""),g(null),v(""),y(null),E([]),N(!1)):(m(B.key),f(B.content),g(null),v(""),y(null),E([]),N(!1))}async function k(B){if(x===B)y(null),E([]);else{y(B),w(!0);try{const Y=await zy(e,B,i);E(Y)}catch(Y){n(ke(Y)||"Failed to load revisions","error")}finally{w(!1)}}}function H(){d&&(g(d),v(h))}function Q(){g(null),v("")}async function ue(){if(!(!p||!b.trim())){M(!0);try{await ou(e,p,b,{},i),g(null),v(""),await z();const B=o.find(Y=>Y.key===p);B&&f(B.content),n("Document saved","success")}catch(B){n(ke(B)||"Failed to save document","error")}finally{M(!1)}}}async function be(){const B=O.trim(),Y=P.trim();if(!B){n("Document key is required","error");return}if(!lR.test(B)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!Y){n("Content is required","error");return}M(!0);try{await ou(e,B,Y,{},i),S(!1),_(""),U(""),await z(),n("Document created","success")}catch(X){n(ke(X)||"Failed to create document","error")}finally{M(!1)}}async function V(B){D(B);try{await Oy(e,B,i),J(null),D(null),d===B&&(m(null),f("")),x===B&&(y(null),E([])),await z(),n("Document deleted","success")}catch(Y){n(ke(Y)||"Failed to delete document","error")}finally{D(null)}}function ve(B){f(B.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"}),R&&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:O,onChange:B=>_(B.target.value),placeholder:"e.g., plan, notes, research",disabled:G}),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:P,onChange:B=>U(B.target.value),rows:6,placeholder:"Enter document content…",disabled:G})]}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{S(!1),_(""),U("")},disabled:G,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void be(),disabled:G||!O.trim()||!P.trim(),children:G?"Creating…":"Create"})]})]}),o.length===0&&!R?t.jsx("div",{className:"detail-log-empty",children:"No documents yet."}):t.jsx("div",{className:"task-documents-list",children:o.map(B=>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(Hi,{size:14}),t.jsx("span",{className:"task-document-key",children:B.key}),t.jsxs("span",{className:"task-document-revision-badge",children:["v",B.revision]})]}),t.jsxs("div",{className:"task-document-meta",children:[t.jsx("span",{className:"task-document-author",children:B.author}),t.jsx("span",{className:"task-document-timestamp",children:wh(B.updatedAt||B.createdAt)})]})]}),d===B.key&&p!==B.key&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"task-document-content-header",children:t.jsx("button",{className:"btn btn-sm document-mode-toggle",onClick:()=>N(Y=>!Y),"aria-label":te?"Switch to plain text":"Switch to markdown","aria-pressed":te,title:te?"Switch to plain text":"Switch to markdown",children:te?"Markdown":"Plain"})}),t.jsx("div",{className:"task-document-content",children:te?t.jsx("div",{className:"task-document-content-markdown",children:t.jsx("div",{className:"markdown-body",children:t.jsx(li,{remarkPlugins:[ci],children:h})})}):t.jsx("pre",{className:"task-document-content-text",children:h})}),x===B.key&&t.jsxs("div",{className:"task-document-revisions",children:[t.jsx("h5",{children:"Revision History"}),C?t.jsx("div",{className:"detail-log-empty",children:"Loading…"}):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(Y=>Y.revision<B.revision).sort((Y,X)=>X.revision-Y.revision).map(Y=>t.jsxs("div",{className:"task-document-revision-item",onClick:()=>ve(Y),children:[t.jsxs("div",{className:"revision-header",children:[t.jsxs("span",{className:"revision-badge",children:["v",Y.revision]}),t.jsx("span",{className:"revision-author",children:Y.author}),t.jsx("span",{className:"revision-timestamp",children:wh(Y.createdAt)})]}),t.jsx("div",{className:"revision-preview",children:dR(Y.content,100)})]},Y.id))})]})]}),p===B.key&&t.jsxs("div",{className:"task-document-edit-form",children:[t.jsx("textarea",{value:b,onChange:Y=>v(Y.target.value),rows:10,disabled:G}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:Q,disabled:G,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void ue(),disabled:G||!b.trim(),children:G?"Saving…":"Save"})]})]}),t.jsxs("div",{className:"task-document-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>void I(B),children:d===B.key?t.jsxs(t.Fragment,{children:[t.jsx(bi,{size:14})," Collapse"]}):t.jsxs(t.Fragment,{children:[t.jsx(Yt,{size:14})," Expand"]})}),d===B.key&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>void k(B.key),children:[t.jsx(jr,{size:14})," History"]}),r&&p!==B.key&&t.jsx("button",{className:"btn btn-sm",onClick:H,children:"Edit"}),r&&(K===B.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 V(B.key),disabled:T===B.key,children:T===B.key?"…":"Yes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>J(null),disabled:T===B.key,children:"No"})]}):t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>J(B.key),children:t.jsx(cn,{size:14})}))]})]})]},B.key))}),r&&!R&&t.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>S(!0),children:[t.jsx(dn,{size:14})," New Document"]})]})}function jo(e){return e.toLocaleString()}function pc(e){const n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString()}function er(e){if(e<1e3)return`${Math.round(e)} ms`;const n=e/1e3;if(n<60)return`${n.toFixed(1)} s`;const s=Math.floor(n/60),i=Math.round(n%60);return`${s}m ${i}s`}function mR(e){const n=Date.now(),s=e.map(o=>{if(!o.startedAt)return null;const l=new Date(o.startedAt).getTime();if(Number.isNaN(l))return null;let c;if(o.completedAt){const u=new Date(o.completedAt).getTime();if(Number.isNaN(u)||u<l)return null;c=u}else c=Math.max(l,n);return{name:o.workflowStepName||o.workflowStepId,durationMs:c-l}}).filter(o=>o!==null),i=s.reduce((o,l)=>o+l.durationMs,0),r=s.reduce((o,l)=>!o||l.durationMs>o.durationMs?l:o,void 0);return{timedStepCount:s.length,totalDurationMs:i,longestStep:r}}function hR({tokenUsage:e,loading:n,task:s}){const i=lf(s?.log??[]),r=i.filter(m=>typeof m.durationMs=="number"),o=r.reduce((m,h)=>m+(h.durationMs??0),0),l=Math.max(o,s?.timedExecutionMs??0),c=r.reduce((m,h)=>!m||(h.durationMs??0)>(m.durationMs??0)?h:m,void 0),u=mR(s?.workflowStepResults??[]),d=s?.steps?.length??0;return t.jsxs("section",{className:"task-token-stats-panel","aria-label":"Task execution statistics",children:[t.jsx("h4",{children:"Execution & Token Stats"}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Execution Timing"}),t.jsxs("div",{className:"task-token-stats-panel__grid",role:"list","aria-label":"Execution timing metrics",children:[t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Timing events"}),t.jsx("span",{className:"task-token-stats-panel__value",children:i.length.toLocaleString()})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Timed duration"}),t.jsx("span",{className:"task-token-stats-panel__value",children:er(l)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Workflow timed steps"}),t.jsx("span",{className:"task-token-stats-panel__value",children:u.timedStepCount.toLocaleString()})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Workflow runtime"}),t.jsx("span",{className:"task-token-stats-panel__value",children:er(u.totalDurationMs)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Total execution time"}),t.jsx("span",{className:"task-token-stats-panel__value",children:er(l+u.totalDurationMs)})]})]}),t.jsxs("dl",{className:"task-token-stats-panel__timestamps",children:[t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Longest timing event"}),t.jsx("dd",{children:c?.durationMs?`${c.summary} (${er(c.durationMs)})`:"No timed events recorded yet."})]}),t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Longest workflow step"}),t.jsx("dd",{children:u.longestStep?`${u.longestStep.name} (${er(u.longestStep.durationMs)})`:"No completed workflow step timings yet."})]})]})]}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Execution Details"}),t.jsxs("dl",{className:"task-token-stats-panel__details",children:[t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Execution mode"}),t.jsx("dd",{children:s?.executionMode==="fast"?"Fast":"Standard"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Runtime status"}),t.jsx("dd",{children:s?.status??"Not set"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Paused"}),t.jsx("dd",{children:s?.paused?"Yes":"No"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Step progress"}),t.jsx("dd",{children:d>0?`${Math.min((s?.currentStep??0)+1,d)} / ${d}`:"No steps"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Retries (recovery / workflow / merge / task_done)"}),t.jsx("dd",{children:`${s?.recoveryRetryCount??0} / ${s?.workflowStepRetries??0} / ${s?.mergeRetries??0} / ${s?.taskDoneRetryCount??0}`})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Recovery state"}),t.jsx("dd",{children:s?.nextRecoveryAt?`Next recovery at ${pc(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:jo(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:jo(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:jo(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:jo(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:pc(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:pc(e.lastUsedAt)})})]})]})]}):t.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:"No token usage recorded for this task yet."})]})]})}const pR=new Set(["planning","researching","executing","finalizing","merging"]);function fR(e,n){return Zp(e,n)}function gR(e,n){return ef(e,n)}function bR(e){let n=null;for(const s of e){if(s.agent!=="triage"||s.type!=="text")continue;const i=s.text.match(/^Triage using model: (.+?)\/(.+)$/);i&&(n={provider:i[1],modelId:i[2]})}return n}function xR(e,n,s){if(e.planningModelProvider&&e.planningModelId)return{provider:e.planningModelProvider,modelId:e.planningModelId};const i=bR(n);return i||tf(e,s)}function vR(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 yR(e){const n=new Date(e),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),o=Math.floor(r/60),l=Math.floor(o/24);return r<1?"just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString()}function wR(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function jR(e){if(!(e instanceof Error))return null;const n=e.details;if(n?.code==="TASK_HAS_DEPENDENTS"&&Array.isArray(n.dependentIds))return{dependentIds:n.dependentIds.filter(i=>typeof i=="string")};const s=e.message.match(/[A-Z]+-\d+/g)??[];return s.length>1?{dependentIds:[...new Set(s.slice(1))]}:null}function jh(e,n){return e.length>n?e.slice(0,n)+"…":e}function kh(e=[],n=[]){return e.length===n.length&&e.every((s,i)=>s===n[i])}function fc(e){const n=e.indexOf("/");return!e||n===-1?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function gc(e){return e.trim()}function kR(e){const n=e.trim();return n.length>0?n:void 0}function tr(e){return typeof e=="string"&&Cd.includes(e)?e:_s}function nr(e){return e==="fast"?"fast":"standard"}function NR(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}const SR=a.lazy(()=>hn(()=>import("./AgentDetailView-B1zViykq.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8])).then(e=>({default:e.AgentDetailView})));function CR(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:NR(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 bc=200,ER=new Set(["triage","todo"]);function _R({task:e,projectId:n,tasks:s=[],onClose:i,onOpenDetail:r,onMoveTask:o,onDeleteTask:l,onMergeTask:c,onRetryTask:u,onResetTask:d,onDuplicateTask:m,onTaskUpdated:h,addToast:f,prAuthAvailable:p,initialTab:g="definition"}){const[b,v]=a.useState(g),[x,y]=a.useState(()=>"prompt"in e?e:null),[j,E]=a.useState(()=>!("prompt"in e));a.useEffect(()=>{if("prompt"in e){y(e),E(!1);return}let Z=!1;return E(!0),y(null),Sr(e.id,n).then(Ge=>{Z||(y(Ge),E(!1))}).catch(()=>{Z||E(!1)}),()=>{Z=!0}},[e.id,n]);const C=x?{...x,...e,prompt:x.prompt,log:x.log}:{...e,prompt:""},w=e.status==="failed"||e.status==="stuck-killed"||e.status==="planning"||e.status==="needs-replan"||(e.stuckKillCount??0)>0||(e.recoveryRetryCount??0)>0||!!e.nextRecoveryAt,[R,S]=a.useState(null),[O,_]=a.useState(null),P=CR(C,{sourceAgentName:R?.name});a.useEffect(()=>{v(g)},[g]),a.useEffect(()=>{T(!1)},[e.id]);const[U,G]=a.useState("activity"),[M,T]=a.useState(!1),[D,K]=a.useState(e.attachments||[]),[J,te]=a.useState(!1),[N,z]=a.useState(e.dependencies||[]),[I,k]=a.useState(!1),[H,Q]=a.useState(""),[ue,be]=a.useState(null),[V,ve]=a.useState([]),[B,Y]=a.useState(!1),[X,he]=a.useState(!1),[de,me]=a.useState(!1),[se,_e]=a.useState(!1),[Fe,Te]=a.useState(!1),[st,nt]=a.useState(C.prompt||""),[qe,Xe]=a.useState(""),[$e,Ue]=a.useState(!1),[oe,je]=a.useState(""),[ie,Ae]=a.useState(!1),[Le,we]=a.useState(!1),[Ee,Ve]=a.useState(e.title||""),[rt,xe]=a.useState(e.description||""),[ce,Pe]=a.useState(e.dependencies||[]),[pe,Re]=a.useState(""),[Qe,Ie]=a.useState(""),[bt,ee]=a.useState(""),[re,Se]=a.useState(""),[ot,ne]=a.useState("default"),[Ze,ft]=a.useState(void 0),[gt,St]=a.useState(_s),[Nt,pt]=a.useState(e.nodeId),[kt,Ht]=a.useState(nr(e.executionMode)),[$t,Tt]=a.useState(""),[Mt,Ot]=a.useState(e.enabledWorkflowSteps||[]),[zt,Ft]=a.useState(e.sourceIssue?.provider??""),[Et,Pt]=a.useState(e.sourceIssue?.repository??""),[Dt,Wt]=a.useState(e.sourceIssue?.externalIssueId??""),[It,Rt]=a.useState(e.sourceIssue?.url??""),[fe,Oe]=a.useState([]),[ut,L]=a.useState(!1),F=a.useRef(!1),[ge,ze]=a.useState(!1),[Be,Ke]=a.useState(!1),[dt,Xt]=a.useState(!1),Cn=a.useRef(null),pn=a.useRef(null),Kn=a.useRef(null),Lt=a.useRef(null);di(Lt,!0,"fusion:task-detail-modal-size");const{getSlotsForId:Zt}=Gp(n),Ne=Zt("task-detail-tab");a.useEffect(()=>(F.current=!0,()=>{F.current=!1}),[]);const[et,ln]=a.useState(void 0),[wn,Gn]=a.useState([]),[Tn,Un]=a.useState(!1),[sn,un]=a.useState(e.enabledWorkflowSteps||[]),Bn=e.column==="in-progress"||pR.has(e.status);a.useEffect(()=>{Ve(e.title||""),xe(e.description||""),Ft(e.sourceIssue?.provider??""),Pt(e.sourceIssue?.repository??""),Wt(e.sourceIssue?.externalIssueId??""),Rt(e.sourceIssue?.url??""),Ht(nr(e.executionMode)),Xt(!1),we(!1)},[e.id,e.title,e.description,e.sourceIssue,e.executionMode]),a.useEffect(()=>{un(e.enabledWorkflowSteps||[])},[e.id,e.enabledWorkflowSteps]),a.useEffect(()=>{let Z=!1;return ll(n).then(Ge=>{Z||ln(Ge)}).catch(()=>{}),()=>{Z=!0}},[n]),a.useEffect(()=>{if(b!=="workflow")return;let Z=!1;return Un(!0),bj(e.id,n).then(Ge=>{Z||Gn(Ge)}).catch(Ge=>{Z||f(`Failed to load workflow results: ${ke(Ge)}`,"error")}).finally(()=>{Z||Un(!1)}),()=>{Z=!0}},[b,e.id,n,f]),a.useEffect(()=>{if(b!=="workflow")return;const Z=n?`?projectId=${encodeURIComponent(n)}`:"",Ge=ct=>{try{const Ut=JSON.parse(ct.data);Ut.id===e.id&&Array.isArray(Ut.workflowStepResults)&&Gn(Ut.workflowStepResults)}catch{}};return Js(`/api/events${Z}`,{events:{"task:updated":Ge}})},[b,e.id,n]),a.useEffect(()=>{I||Q("")},[I]),a.useEffect(()=>{if(!e.assignedAgentId){be(null);return}const Z=V.find(ct=>ct.id===e.assignedAgentId);if(Z){be(Z);return}let Ge=!1;return Vc(e.assignedAgentId,n).then(ct=>{Ge||be(ct)}).catch(()=>{Ge||be(null)}),()=>{Ge=!0}},[e.assignedAgentId,n,V]),a.useEffect(()=>{if(!e.sourceAgentId){S(null);return}const Z=V.find(ct=>ct.id===e.sourceAgentId);if(Z){S(Z);return}let Ge=!1;return Promise.resolve(Vc(e.sourceAgentId,n)).then(ct=>{Ge||S(ct??null)}).catch(()=>{Ge||S(null)}),()=>{Ge=!0}},[e.sourceAgentId,n,V]),a.useEffect(()=>{Y(!1)},[e.id]),a.useEffect(()=>{if(!(ge||Be))return;const Ge=ct=>{const Ut=ct.target,Xs=Cn.current?.contains(Ut),Us=Kn.current?.contains(Ut);!Xs&&ge&&ze(!1),!Us&&Be&&Ke(!1)};return document.addEventListener("mousedown",Ge),()=>document.removeEventListener("mousedown",Ge)},[ge,Be]),a.useEffect(()=>{if(!(ge||Be))return;const Ge=ct=>{ct.key==="Escape"&&(ct.stopPropagation(),ge&&ze(!1),Be&&Ke(!1))};return document.addEventListener("keydown",Ge),()=>document.removeEventListener("keydown",Ge)},[ge,Be]),a.useEffect(()=>{Te(!1),nt(C.prompt||""),Xe("")},[e.id,C.prompt]);const Sn=ER.has(e.column)&&!ut,an=a.useCallback(()=>{if(!Sn)return;we(!0),Ve(e.title||""),xe(e.description||""),Pe(e.dependencies||[]);const Z=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"",Ge=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"",ct=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";Re(Z),Ie(Ge),ee(ct),Se(e.thinkingLevel??""),pt(e.nodeId),ne(Z||Ge||ct?"custom":"default"),Tt(""),Ot(e.enabledWorkflowSteps||[]),Ht(nr(e.executionMode)),Ft(e.sourceIssue?.provider??""),Pt(e.sourceIssue?.repository??""),Wt(e.sourceIssue?.externalIssueId??""),Rt(e.sourceIssue?.url??""),Oe([]),ft(e.reviewLevel),St(tr(e.priority))},[Sn,e]),Dn=a.useCallback(()=>{we(!1),Ve(e.title||""),xe(e.description||""),Pe(e.dependencies||[]),pt(e.nodeId),Ft(e.sourceIssue?.provider??""),Pt(e.sourceIssue?.repository??""),Wt(e.sourceIssue?.externalIssueId??""),Rt(e.sourceIssue?.url??""),St(tr(e.priority)),Ht(nr(e.executionMode)),fe.forEach(Z=>URL.revokeObjectURL(Z.previewUrl)),Oe([])},[e.title,e.description,e.dependencies,e.nodeId,e.priority,e.executionMode,fe]),Ln=a.useCallback(async()=>{L(!0);try{const Z={},Ge=Ee.trim(),ct=rt.trim();Ge&&Ge!==(e.title??"")&&(Z.title=Ge),ct&&ct!==(e.description??"")&&(Z.description=ct),kh(ce,e.dependencies??[])||(Z.dependencies=ce),kh(Mt,e.enabledWorkflowSteps??[])||(Z.enabledWorkflowSteps=Mt);const Ut=fc(pe),Xs=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"";pe!==Xs&&(Z.modelProvider=Ut?.provider??null,Z.modelId=Ut?.modelId??null);const Us=fc(Qe),Ha=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"";Qe!==Ha&&(Z.validatorModelProvider=Us?.provider??null,Z.validatorModelId=Us?.modelId??null);const qa=fc(bt),Zr=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";bt!==Zr&&(Z.planningModelProvider=qa?.provider??null,Z.planningModelId=qa?.modelId??null);const eo=e.thinkingLevel??"";re!==eo&&(Z.thinkingLevel=re!==""?re:null),(e.nodeId??void 0)!==Nt&&(Z.nodeId=Nt??null);const jl=e.reviewLevel;Ze!==jl&&(Z.reviewLevel=Ze);const to=tr(e.priority);gt!==to&&(Z.priority=gt);const no=nr(e.executionMode);kt!==no&&(Z.executionMode=kt==="fast"?"fast":null);const sa=gc(zt),q=gc(Et),Ce=gc(Dt),De=kR(It);if(sa.length===0&&q.length===0&&Ce.length===0&&!De)e.sourceIssue&&(Z.sourceIssue=null);else{if(!sa||!q||!Ce){f("Source issue provider, repository, and issue identifier are required","error"),L(!1);return}const _t=Number.parseInt(Ce,10),Gt=e.sourceIssue?.issueNumber??_t;if(!Number.isFinite(Gt)||Gt<=0){f("Source issue identifier must be numeric for new metadata","error"),L(!1);return}const He={provider:sa,repository:q,externalIssueId:Ce,issueNumber:Gt,...De?{url:De}:{}},We=e.sourceIssue;(!We||We.provider!==He.provider||We.repository!==He.repository||We.externalIssueId!==He.externalIssueId||We.issueNumber!==He.issueNumber||(We.url??void 0)!==He.url)&&(Z.sourceIssue=He)}if(Object.keys(Z).length>0){const _t=await ii(e.id,Z,n);h?.(_t)}if(fe.length>0){const _t=[];for(const Gt of fe)try{const He=await Cr(e.id,Gt.file,n);K(We=>[...We,He])}catch{_t.push(Gt.file.name)}_t.length>0&&f(`Failed to upload: ${_t.join(", ")}`,"error")}fe.forEach(_t=>URL.revokeObjectURL(_t.previewUrl)),Oe([]),f(`Updated ${e.id}`,"success"),we(!1)}catch(Z){f(`Failed to update ${e.id}: ${ke(Z)}`,"error")}finally{F.current&&L(!1)}},[e,Ee,rt,ce,pe,Qe,bt,re,Nt,Ze,gt,kt,Mt,zt,Et,Dt,It,fe,f,n,h]),ss=a.useCallback(async Z=>{try{await ii(e.id,{description:Z},n),f("Description saved","success")}catch(Ge){f(`Failed to save: ${ke(Ge)}`,"error")}},[e.id,f,n]),Pn=a.useCallback(Z=>{Le&&(Z.key==="Escape"?(Z.preventDefault(),Dn()):Z.key==="Enter"&&(Z.ctrlKey||Z.metaKey)&&(Z.preventDefault(),Ln()))},[Le,Dn,Ln]);a.useEffect(()=>{if(Le)return document.addEventListener("keydown",Pn),()=>document.removeEventListener("keydown",Pn)},[Le,Pn]);const nn=a.useRef(null),{nodes:vt}=ml(),{confirm:rn}=Gs(),{entries:A,loading:le,loadMore:ye,hasMore:Ye,total:mt,loadingMore:ht}=Cg(e.id,b==="logs"&&U==="agent-log",n);a.useEffect(()=>{const Z=Ge=>{Ge.key==="Escape"&&!Le&&i()};return document.addEventListener("keydown",Z),()=>document.removeEventListener("keydown",Z)},[i,Le]);const Kt=Mi(i),Jt=a.useCallback(async Z=>{try{await o(e.id,Z),i(),f(`Moved to ${Wn[Z]}`,"success")}catch(Ge){f(ke(Ge),"error")}},[e.id,o,i,f]),zn=a.useCallback(async()=>{if(await rn({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0}))try{await l(e.id),i(),f(`Deleted ${e.id}`,"info")}catch(Ge){const ct=jR(Ge);if(!ct||ct.dependentIds.length===0){f(ke(Ge),"error");return}const Ut=ct.dependentIds.join(", ");if(!await rn({title:"Force Delete Task",message:`${e.id} is a dependency of ${Ut}.
|
|
657
|
-
|
|
658
|
-
Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await l(e.id,{removeDependencyReferences:!0}),i(),f(`Deleted ${e.id} after removing dependency references`,"info")}catch(Us){f(ke(Us),"error")}}},[e.id,l,i,f,rn]),Hn=a.useCallback(async()=>{await rn({title:"Merge Task",message:`Merge ${e.id} into the current branch?`})&&(i(),f(`Merging ${e.id}...`,"info"),c(e.id).then(Ge=>{const ct=Ge.merged?`Merged ${e.id} (branch: ${Ge.branch})`:`Closed ${e.id} (${Ge.error||"no branch to merge"})`;f(ct,"success")}).catch(Ge=>{f(ke(Ge),"error")}))},[e.id,c,i,f,rn]),zs=a.useCallback(()=>{u&&(i(),u(e.id).then(()=>{f(`Retried ${e.id}`,"success")}).catch(Z=>{f(ke(Z),"error")}))},[e.id,u,i,f]),ae=a.useCallback(()=>{d&&window.confirm(`This will erase all progress for ${e.id} and start the task from scratch. Continue?`)&&(i(),d(e.id).then(()=>{f(`Reset ${e.id} — fresh run will be allocated`,"success")}).catch(Z=>{f(ke(Z),"error")}))},[e.id,d,i,f]),Me=a.useCallback(async()=>{if(!(!m||!await rn({title:"Duplicate Task",message:`Duplicate ${e.id}? This will create a new task in Triage with the same description and prompt.`})))try{const Ge=await m(e.id);i(),f(`Duplicated ${e.id} → ${Ge.id}`,"success")}catch(Ge){f(ke(Ge),"error")}},[e.id,m,i,f,rn]),it=a.useCallback(async()=>{try{e.paused?(await Cy(e.id,n),f(`Unpaused ${e.id}`,"success")):(await $p(e.id,n),f(`Paused ${e.id}`,"success")),i()}catch(Z){f(ke(Z),"error")}},[e.id,e.paused,i,f]),wt=a.useCallback(async()=>{try{await Ay(e.id,n),f(`Plan approved — ${e.id} moved to Todo`,"success"),i()}catch(Z){f(ke(Z),"error")}},[e.id,i,f]),jt=a.useCallback(async()=>{if(await rn({title:"Reject Plan",message:"Reject this plan? The specification will be discarded and regenerated.",danger:!0}))try{await Ry(e.id,n),f(`Plan rejected — ${e.id} returned to Planning for replanning`,"info"),i()}catch(Ge){f(ke(Ge),"error")}},[e.id,i,f,rn]),fn=a.useCallback(async()=>{if(await rn({title:"Rebuild Plan",message:"Rebuild the plan for this task? The task will move to planning for replanning."}))try{await By(e.id,n),i(),f(`Replanning ${e.id}...`,"info")}catch(Ge){f(ke(Ge),"error")}},[e.id,n,i,f,rn]),mn=a.useCallback(()=>{Ue(!0),je("")},[]),en=a.useCallback(()=>{ze(!1),Ke(!1)},[]),on=a.useCallback(Z=>{en(),Jt(Z)},[en]),xn=a.useCallback(Z=>{en(),Z()},[en]),qn=a.useCallback(()=>{en(),Hn()},[en,Hn]),On=a.useCallback(()=>{Ue(!1),je(""),Ae(!1)},[]),tt=a.useCallback(async()=>{if(!oe.trim()){f("Please enter feedback describing what needs refinement","error");return}if(oe.length>2e3){f("Feedback must be 2000 characters or less","error");return}Ae(!0);try{const Z=await Hy(e.id,oe.trim(),n);f(`Refinement task created: ${Z.id}`,"success"),i()}catch(Z){f(ke(Z),"error")}finally{Ae(!1)}},[e.id,oe,f,i]),At=a.useCallback(async Z=>{te(!0);try{const Ge=await Cr(e.id,Z,n);K(ct=>[...ct,Ge]),f("Screenshot attached","success")}catch(Ge){f(ke(Ge),"error")}finally{te(!1)}},[e.id,f]),Mn=a.useCallback(async Z=>{const Ge=Z.target.files?.[0];Ge&&(await At(Ge),nn.current&&(nn.current.value=""))},[At]);a.useEffect(()=>{const Z=Ge=>{const ct=Ge.clipboardData?.items;if(ct)for(let Ut=0;Ut<ct.length;Ut++){const Xs=ct[Ut];if(Xs.type.startsWith("image/")){const Us=Xs.getAsFile();if(Us){Ge.preventDefault(),At(Us);return}}}};return document.addEventListener("paste",Z),()=>document.removeEventListener("paste",Z)},[At]);const xs=a.useCallback(Z=>{Z.preventDefault()},[]),In=a.useCallback(Z=>{Z.preventDefault();const Ge=Z.dataTransfer.files;for(let ct=0;ct<Ge.length;ct++){const Ut=Ge[ct];if(Ut.type.startsWith("image/")){At(Ut);return}}},[At]),Qn=a.useCallback(async Z=>{try{await Iy(e.id,Z,n),K(Ge=>Ge.filter(ct=>ct.filename!==Z)),f("Attachment deleted","info")}catch(Ge){f(ke(Ge),"error")}},[e.id,f]),vs=a.useCallback(async Z=>{const Ge=sn;un(Z);try{const ct=await ii(e.id,{enabledWorkflowSteps:Z},n);f("Workflow steps updated","success"),h?.(ct)}catch(ct){un(Ge),f(`Failed to update workflow steps: ${ke(ct)}`,"error")}},[e.id,n,sn,h,f]),Os=a.useCallback(async()=>{he(!0);try{const Z=await Ia(void 0,n);ve(Z),Y(!0)}catch(Z){f(`Failed to load agents: ${ke(Z)}`,"error"),Y(!1)}finally{he(!1)}},[n,f]),ys=a.useCallback(async Z=>{try{const Ge=await xu(e.id,Z,n),ct=V.find(Ut=>Ut.id===Z)??null;be(ct||(Ut=>Ut?.id===Z?Ut:null)),Y(!1),h?.(Ge),f("Assigned agent updated","success")}catch(Ge){f(`Failed to assign agent: ${ke(Ge)}`,"error")}},[e.id,n,V,h,f]),$n=a.useCallback(async()=>{try{const Z=await xu(e.id,null,n);be(null),Y(!1),h?.(Z),f("Agent unassigned","success")}catch(Z){f(`Failed to unassign agent: ${ke(Z)}`,"error")}},[e.id,n,h,f]),Xn=a.useCallback(async Z=>{const Ge=[...N,Z];z(Ge);try{await ii(e.id,{dependencies:Ge},n)}catch(ct){z(N),f(ke(ct),"error")}},[e.id,N,f]),Fs=a.useCallback(async(Z,Ge)=>{Z.stopPropagation();const ct=N.filter(Ut=>Ut!==Ge);z(ct);try{await ii(e.id,{dependencies:ct},n)}catch(Ut){z(N),f(ke(Ut),"error")}},[e.id,N,f]),Ri=a.useCallback(async Z=>{try{const Ge=await Sr(Z,n);r(Ge)}catch{f(`Failed to load dependency ${Z}`,"error")}},[r,f]),Ti=a.useCallback(async Z=>{me(!0);try{await ii(C.id,{prompt:Z},n),f("Spec updated","success"),x&&(x.prompt=Z)}catch(Ge){throw f(ke(Ge),"error"),Ge}finally{me(!1)}},[C,x,f]),Gr=a.useCallback(async Z=>{_e(!0);try{await Uy(e.id,Z,n),f("AI revision requested. Task moved to planning.","success"),i()}catch(Ge){const ct=ke(Ge);ct.includes("done")||ct.includes("archived")?f("Cannot request revision: Task must be in 'triage', 'todo', 'in-progress', or 'in-review' column.","error"):f(ct,"error")}finally{_e(!1)}},[e.id,f,i]),Ys=a.useCallback(()=>{Te(!0),nt(C.prompt||""),Xe("")},[C.prompt]),yi=a.useCallback(()=>{Te(!1),nt(C.prompt||""),Xe("")},[C.prompt]),Zi=a.useCallback(async()=>{if(st===(C.prompt||"")){yi();return}Te(!1);try{await Ti(st)}catch(Z){throw Te(!0),Z}},[st,C.prompt,Ti,yi]),yl=a.useCallback(async()=>{qe.trim()&&await Gr(qe.trim())},[qe,Gr]),wl=a.useCallback(Z=>{Z.key==="Escape"?(Z.preventDefault(),yi()):Z.key==="Enter"&&(Z.ctrlKey||Z.metaKey)&&(Z.preventDefault(),Zi())},[yi,Zi]),Jr=s.filter(Z=>Z.id!==e.id&&!N.includes(Z.id)).sort((Z,Ge)=>{const ct=Ge.createdAt.localeCompare(Z.createdAt);if(ct!==0)return ct;const Ut=parseInt(Z.id.slice(Z.id.lastIndexOf("-")+1),10)||0;return(parseInt(Ge.id.slice(Ge.id.lastIndexOf("-")+1),10)||0)-Ut}),Qs=ue?.name??e.assignedAgentId??null,mi=a.useMemo(()=>{const Z=[];return C.modelProvider&&Z.push(C.modelProvider),C.validatorModelProvider&&!Z.includes(C.validatorModelProvider)&&Z.push(C.validatorModelProvider),C.planningModelProvider&&!Z.includes(C.planningModelProvider)&&Z.push(C.planningModelProvider),Z},[C.modelProvider,C.validatorModelProvider,C.planningModelProvider]),ea=Wc[e.column]||[],Yr=["todo","in-progress"],Qr=e.column==="in-review"?Yr:ea,is=Qr[0],ta=Qr.slice(1),ms=ta.length>0,Fa=a.useCallback(()=>{ze(!1),pn.current?.focus()},[]),Xr=a.useCallback(Z=>{if(!ms){is&&on(is);return}const Ge=Z.currentTarget.querySelector(".detail-move-btn__arrow");if(!!(Z.target instanceof Element&&Z.target.closest(".detail-move-btn__arrow")||Ge&&Z.clientX>0&&Z.clientX>=Ge.getBoundingClientRect().left)){ze(Ut=>!Ut),Ke(!1);return}is&&on(is)},[ms,is,on]),Ua=a.useCallback(Z=>{!ms||!(Z.key==="ArrowDown"||Z.altKey&&Z.key==="ArrowDown")||(Z.preventDefault(),ze(!0),Ke(!1))},[ms]),na=a.useCallback(Z=>{Z.key==="Escape"&&(Z.preventDefault(),Z.stopPropagation(),Fa())},[Fa]);a.useEffect(()=>{if(!ge)return;Cn.current?.querySelector(".detail-move-menu-item")?.focus()},[ge]);const Ba={"creating-pr":"Creating PR…","awaiting-pr-checks":"Awaiting PR checks","merging-pr":"Merging PR…"},hi=e.status?Ba[e.status]:void 0;return t.jsx("div",{className:"modal-overlay open",...Kt,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg task-detail-modal",ref:Lt,onDragOver:xs,onDrop:In,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx("span",{className:"detail-id",children:e.id}),t.jsx("span",{className:`detail-column-badge badge-${e.column}`,children:Wn[e.column]})]}),t.jsxs("div",{className:"modal-header-actions",children:[!Le&&Sn&&t.jsx("button",{className:"modal-edit-btn",onClick:an,title:"Edit task","aria-label":"Edit task",children:t.jsx(hs,{size:14})}),t.jsx("button",{className:"modal-close",onClick:i,"aria-label":"Close",children:"×"})]})]}),t.jsxs("div",{className:`detail-body${b==="logs"&&U==="agent-log"&&!Le?" detail-body--agent-log":""}`,children:[Le?t.jsx("div",{className:"modal-edit-form",children:t.jsx(Ag,{mode:"edit",title:Ee,onTitleChange:Ve,description:rt,onDescriptionChange:xe,dependencies:ce,onDependenciesChange:Pe,executorModel:pe,onExecutorModelChange:Re,validatorModel:Qe,onValidatorModelChange:Ie,planningModel:bt,onPlanningModelChange:ee,thinkingLevel:re,onThinkingLevelChange:Se,presetMode:ot,onPresetModeChange:ne,selectedPresetId:$t,onSelectedPresetIdChange:Tt,selectedWorkflowSteps:Mt,onWorkflowStepsChange:Ot,pendingImages:fe,onImagesChange:Oe,tasks:s.filter(Z=>Z.id!==e.id),projectId:n,disabled:ut,addToast:f,isActive:Le,onAutoSaveDescription:ss,reviewLevel:Ze,onReviewLevelChange:ft,priority:gt,onPriorityChange:St,nodeId:Nt,onNodeIdChange:pt,nodeOptions:vt,nodeOverrideDisabled:Bn,nodeOverrideDisabledReason:Bn?"Execution node override is locked while a task is active/in progress.":void 0,executionMode:kt,onExecutionModeChange:Ht,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:zt,onChange:Z=>Ft(Z.target.value),disabled:ut,"data-testid":"task-source-provider-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Repository (e.g. owner/repo)",value:Et,onChange:Z=>Pt(Z.target.value),disabled:ut,"data-testid":"task-source-repository-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Issue identifier",value:Dt,onChange:Z=>Wt(Z.target.value),disabled:ut,"data-testid":"task-source-external-id-input"}),t.jsx("input",{type:"url",className:"modal-edit-input",placeholder:"Issue URL",value:It,onChange:Z=>Rt(Z.target.value),disabled:ut,"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 Z=e.title||e.description||e.id,Ge=!M&&Z.length>bc;return t.jsxs(t.Fragment,{children:[t.jsx("h2",{className:"detail-title",children:Ge?Z.slice(0,bc)+"…":Z}),Z.length>bc&&t.jsx("button",{className:"detail-description-toggle",onClick:()=>T(!M),children:M?"Show less":"Show more"})]})})(),t.jsxs("div",{className:"detail-meta",children:["Created ",new Date(e.createdAt).toLocaleDateString()," · Updated"," ",new Date(e.updatedAt).toLocaleDateString()," ·",t.jsxs("span",{className:`detail-priority-chip detail-priority-chip--${tr(e.priority)}`,children:["Priority: ",tr(e.priority)]}),P&&t.jsxs("div",{className:"detail-provenance",children:[t.jsx(Ks,{"aria-hidden":"true"}),t.jsxs("span",{children:[C.sourceType==="agent_heartbeat"?t.jsxs(t.Fragment,{children:["Created by"," ",P.sourceAgentId?t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>_(P.sourceAgentId),children:P.label}):P.label]}):t.jsxs(t.Fragment,{children:["Created via ",P.label]}),P.parentTaskId&&t.jsxs(t.Fragment,{children:[" ","of"," ",t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>Ri(P.parentTaskId),children:P.parentTaskId})]}),P.contextInfo?` (${P.contextInfo})`:""]})]})]})]}),e.status==="failed"&&e.error&&t.jsxs("div",{className:"detail-error-alert",children:[t.jsx("span",{className:"detail-error-icon",children:"⚠"}),t.jsxs("div",{className:"detail-error-content",children:[t.jsx("div",{className:"detail-error-title",children:"Task Failed"}),t.jsx("div",{className:"detail-error-message",children:e.error})]})]}),!Le&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"detail-tabs",children:[t.jsx("button",{className:`detail-tab${b==="definition"?" detail-tab-active":""}`,onClick:()=>v("definition"),children:"Definition"}),t.jsx("button",{className:`detail-tab${b==="logs"?" detail-tab-active":""}`,onClick:()=>v("logs"),children:"Logs"}),(e.column==="in-progress"||e.column==="in-review"||e.column==="done")&&t.jsx("button",{className:`detail-tab${b==="changes"?" detail-tab-active":""}`,onClick:()=>v("changes"),children:"Changes"}),t.jsx("button",{className:`detail-tab${b==="comments"?" detail-tab-active":""}`,onClick:()=>v("comments"),children:"Comments"}),t.jsx("button",{className:`detail-tab${b==="documents"?" detail-tab-active":""}`,onClick:()=>v("documents"),children:"Documents"}),t.jsx("button",{className:`detail-tab${b==="model"?" detail-tab-active":""}`,onClick:()=>v("model"),children:"Model"}),t.jsx("button",{className:`detail-tab${b==="workflow"?" detail-tab-active":""}`,onClick:()=>v("workflow"),children:"Workflow"}),t.jsx("button",{className:`detail-tab${b==="stats"?" detail-tab-active":""}`,onClick:()=>v("stats"),children:"Stats"}),t.jsx("button",{className:`detail-tab${b==="routing"?" detail-tab-active":""}`,onClick:()=>v("routing"),children:"Routing"}),Ne.map((Z,Ge)=>{const ct=`plugin-${Ge}`;return t.jsx("button",{className:`detail-tab${b===ct?" detail-tab-active":""}`,onClick:()=>v(ct),children:Z.slot.label},`plugin-tab-${Z.pluginId}`)})]}),b==="workflow"?t.jsx("div",{className:"detail-section",children:t.jsx(sR,{taskId:e.id,results:wn,loading:Tn,enabledWorkflowSteps:sn,canEdit:Sn,projectId:n,isTaskInProgress:e.column==="in-progress"&&e.status!=="paused",onWorkflowStepsChange:vs})}):b==="model"?t.jsx("div",{className:"detail-section",children:t.jsx(zA,{task:e,addToast:f,onTaskUpdated:h,settings:et})}):b==="logs"?t.jsxs("div",{className:`detail-section${U==="agent-log"?" detail-section--agent-log":""}`,children:[t.jsxs("div",{className:"log-subview-toggle",children:[t.jsx("button",{className:`log-subview-btn${U==="activity"?" log-subview-btn-active":""}`,onClick:()=>G("activity"),children:"Activity"}),t.jsx("button",{className:`log-subview-btn${U==="agent-log"?" log-subview-btn-active":""}`,onClick:()=>G("agent-log"),children:"Agent Log"})]}),U==="agent-log"?t.jsx(PA,{entries:A,loading:le,executorModel:fR(e,et),validatorModel:gR(e,et),planningModel:xR(e,A,et),hasMore:Ye,onLoadMore:ye,loadingMore:ht,totalCount:mt}):t.jsxs("div",{className:"detail-activity",children:[t.jsx("h4",{children:"Activity"}),C.activityLogTruncatedCount?t.jsxs("div",{className:"detail-log-truncated",children:["Showing the most recent ",C.log.length," activity entries."]}):null,C.log&&C.log.length>0?t.jsx("div",{className:"detail-activity-list",children:[...C.log].reverse().map((Z,Ge)=>t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-timestamp",children:yR(Z.timestamp)}),t.jsx("span",{className:"detail-log-action",children:Z.action})]}),Z.outcome&&t.jsx("div",{className:"detail-log-outcome",children:Z.outcome})]},Ge))}):t.jsx("div",{className:"detail-log-empty",children:"(no activity)"})]})]}):b==="changes"?t.jsx(GA,{taskId:e.id,worktree:e.worktree,projectId:n,column:e.column,mergeDetails:e.mergeDetails,modifiedFiles:e.modifiedFiles}):b==="comments"?t.jsx(HA,{task:e,addToast:f,projectId:n,onTaskUpdated:h}):b==="documents"?t.jsx(uR,{taskId:e.id,addToast:f,projectId:n,onTaskUpdated:h,canEdit:Sn}):typeof b=="string"&&b.startsWith("plugin-")?t.jsx("div",{className:"detail-section",children:t.jsx(dl,{slotId:"task-detail-tab",projectId:n})}):b==="stats"?t.jsx("div",{className:"detail-section",children:t.jsx(hR,{tokenUsage:C.tokenUsage,loading:j,task:C})}):b==="routing"?t.jsx("div",{className:"detail-section",children:t.jsx(oR,{task:e,settings:et,addToast:f,onTaskUpdated:h})}):t.jsxs(t.Fragment,{children:[e.column==="done"&&e.summary&&t.jsxs("div",{className:"detail-section detail-summary",children:[t.jsx("h4",{children:"Summary"}),t.jsx("div",{className:"markdown-body",children:t.jsx(li,{remarkPlugins:[ci],children:e.summary})})]}),t.jsx(VA,{task:e}),e.sourceIssue&&t.jsxs("div",{className:"detail-section detail-source-section",children:[t.jsxs("div",{className:"detail-source-header",children:[t.jsxs("div",{className:"detail-source-summary",children:[t.jsx("span",{className:"detail-source-label",children:"Source issue"}),e.sourceIssue.url?t.jsx("a",{className:"detail-source-link detail-source-number",href:e.sourceIssue.url,target:"_blank",rel:"noopener noreferrer",children:`(#${e.sourceIssue.issueNumber})`}):t.jsx("span",{className:"detail-source-number",children:`(#${e.sourceIssue.issueNumber})`})]}),t.jsx("button",{type:"button",className:"detail-source-toggle","aria-expanded":dt,"aria-label":dt?"Collapse source issue details":"Expand source issue details",onClick:()=>Xt(Z=>!Z),children:t.jsx(gn,{size:16,className:dt?"detail-source-chevron--expanded":void 0})})]}),dt&&t.jsxs("dl",{className:"detail-source-grid",children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Provider"}),t.jsx("dd",{children:e.sourceIssue.provider})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Repository"}),t.jsx("dd",{children:e.sourceIssue.repository})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Issue Identifier"}),t.jsx("dd",{children:e.sourceIssue.externalIssueId})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"URL"}),t.jsx("dd",{children:e.sourceIssue.url?t.jsx("a",{className:"detail-source-link",href:e.sourceIssue.url,target:"_blank",rel:"noopener noreferrer",children:e.sourceIssue.url}):t.jsx("span",{className:"detail-source-empty",children:"(none)"})})]})]})]}),t.jsx("div",{className:"detail-section detail-agent-section",children:t.jsxs("div",{className:"detail-meta-row",children:[t.jsxs("div",{className:"detail-meta-left",children:[mi.length>0&&t.jsx("span",{className:"detail-provider-icons","data-testid":"detail-provider-icons",children:mi.map(Z=>t.jsx(Rn,{provider:Z,size:"sm"},Z))}),t.jsxs("span",{className:"detail-meta-label",children:[t.jsx(En,{size:14,style:{verticalAlign:"middle",marginRight:6}}),"Agent"]})]}),t.jsxs("div",{className:"detail-agent-actions",children:[Qs?t.jsxs("span",{className:"detail-agent-chip",children:[t.jsx(En,{size:14}),Qs,t.jsx("button",{className:"detail-agent-clear",onClick:()=>void $n(),title:"Unassign agent",children:t.jsx(qt,{size:12})})]}):t.jsx("button",{className:"btn btn-sm",onClick:()=>{B?Y(!1):Os()},children:"Assign Agent"}),B&&t.jsxs("div",{className:"agent-picker-dropdown",children:[X&&t.jsx("div",{className:"agent-picker-loading",children:"Loading agents..."}),!X&&V.filter(Z=>Z.state!=="terminated").map(Z=>t.jsxs("button",{className:`agent-picker-item${e.assignedAgentId===Z.id?" selected":""}`,onClick:()=>void ys(Z.id),children:[t.jsx(En,{size:14}),t.jsx("span",{className:"agent-picker-name",children:Z.name}),t.jsx("span",{className:"agent-picker-role",children:Z.role})]},Z.id)),!X&&V.filter(Z=>Z.state!=="terminated").length===0&&t.jsx("div",{className:"agent-picker-empty",children:"No agents available"})]})]})]})}),t.jsxs("div",{className:"detail-section detail-step-progress",children:[t.jsx("h4",{children:"Progress"}),C.steps&&C.steps.length>0?t.jsxs("div",{className:"step-progress-wrapper",children:[t.jsx("div",{className:"step-progress-bar",children:C.steps.map((Z,Ge)=>t.jsx("div",{className:`step-progress-segment step-progress-segment--${Z.status}`,"data-tooltip":`${Z.name} (${Z.status})`,style:{backgroundColor:vR(Z.status)}},Ge))}),t.jsxs("span",{className:"step-progress-label",children:[C.steps.filter(Z=>Z.status==="done").length,"/",C.steps.length," step",C.steps.length===1?"":"s"]})]}):t.jsx("div",{className:"step-progress-empty",children:"(no steps defined)"})]}),t.jsxs("div",{className:"detail-section",children:[!Fe&&t.jsx("div",{className:"detail-spec-edit-trigger",children:t.jsx("button",{className:"btn btn-sm",onClick:Ys,children:"Edit"})}),Fe?t.jsxs("div",{className:"spec-editor-edit-mode",children:[t.jsx("textarea",{className:"spec-editor-textarea",value:st,onChange:Z=>nt(Z.target.value),onKeyDown:wl,disabled:de,placeholder:"Enter task specification in Markdown...",rows:12}),t.jsxs("div",{className:"spec-editor-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:yi,disabled:de,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Zi(),disabled:st===(C.prompt||"")||de,children:de?"Saving…":"Save"})]}),t.jsxs("div",{className:"spec-editor-hint",children:[t.jsx("kbd",{children:"Ctrl"}),"+",t.jsx("kbd",{children:"Enter"})," to save · ",t.jsx("kbd",{children:"Escape"})," to cancel"]}),t.jsxs("div",{className:"spec-editor-revision",children:[t.jsx("h4",{children:"Ask AI to Revise"}),t.jsx("p",{className:"spec-editor-revision-help",children:"Provide feedback for the AI to improve this specification. The task will move to planning for replanning."}),t.jsx("textarea",{className:"spec-editor-feedback",value:qe,onChange:Z=>Xe(Z.target.value),placeholder:"e.g., 'Add more details about error handling', 'Split this into smaller steps', 'Include tests for the API endpoints'...",disabled:se,rows:4,maxLength:2e3}),t.jsxs("div",{className:"spec-editor-revision-actions",children:[t.jsxs("span",{className:"spec-editor-char-count",children:[qe.length,"/2000"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void yl(),disabled:!qe.trim()||se,children:se?"Requesting…":"Request AI Revision"})]})]})]}):j?t.jsx("div",{className:"spec-loading",children:"Loading specification…"}):C.prompt?t.jsx("div",{className:"markdown-body",children:t.jsx(li,{remarkPlugins:[ci],children:C.prompt.replace(/^#\s+[^\n]*\n+/,"")})}):t.jsx("div",{className:"detail-prompt",children:"(no prompt)"})]}),t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Attachments"}),D.length>0?t.jsx("div",{className:"detail-attachments-grid",children:D.map(Z=>{const Ge=oi(`/api/tasks/${e.id}/attachments/${Z.filename}`);return t.jsxs("div",{className:"detail-attachment-card",children:[t.jsx("a",{className:"detail-attachment-link",href:Ge,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{src:Ge,alt:Z.originalName,className:"detail-attachment-image"})}),t.jsxs("div",{className:"detail-attachment-meta",children:[Z.originalName," (",wR(Z.size),")"]}),t.jsx("button",{className:"detail-attachment-delete",onClick:()=>Qn(Z.filename),title:"Delete attachment",children:"×"})]},Z.filename)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no attachments)"}),t.jsx("input",{className:"detail-hidden-file-input",ref:nn,type:"file",accept:"image/*",onChange:Mn}),t.jsx("button",{className:"btn btn-sm",onClick:()=>nn.current?.click(),disabled:J,children:J?"Uploading…":"Attach Screenshot"})]}),t.jsxs("div",{className:"detail-deps",children:[t.jsx("h4",{children:"Dependencies"}),N.length>0?t.jsx("ul",{className:"detail-dep-list",children:N.map(Z=>{const Ge=s.find(Ut=>Ut.id===Z),ct=Ge?.title||Ge?.description||Z;return t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>Ri(Z),onKeyDown:Ut=>{(Ut.key==="Enter"||Ut.key===" ")&&(Ut.preventDefault(),Ri(Z))},role:"link",tabIndex:0,title:`Click to view ${Z}`,children:[t.jsx("span",{className:"detail-dep-id",children:Z}),t.jsx("span",{className:"detail-dep-label",children:jh(ct,40)})]}),t.jsx("button",{className:"dep-remove-btn",onClick:Ut=>Fs(Ut,Z),title:`Remove dependency ${Z}`,children:"×"})]},Z)})}):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:()=>{I&&Q(""),k(Z=>!Z)},children:"Add Dependency"}),I&&(()=>{const Z=H.toLowerCase(),Ge=Z?Jr.filter(ct=>ct.id.toLowerCase().includes(Z)||ct.title&&ct.title.toLowerCase().includes(Z)||ct.description&&ct.description.toLowerCase().includes(Z)):Jr;return t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:H,onChange:ct=>Q(ct.target.value),onClick:ct=>ct.stopPropagation()}),Ge.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Ge.map(ct=>t.jsxs("div",{className:"dep-dropdown-item",onClick:()=>{Xn(ct.id),k(!1)},children:[t.jsx("span",{className:"dep-dropdown-id",children:ct.id}),t.jsx("span",{className:"dep-dropdown-title",children:jh(ct.title||ct.description||ct.id,30)})]},ct.id))]})})()]})]}),e.column==="in-review"&&t.jsx(FA,{taskId:e.id,projectId:n,prInfo:e.prInfo,automationStatus:e.status??null,autoMerge:et?.autoMerge??!1,prAuthAvailable:p??!1,onPrCreated:Z=>{e.prInfo=Z,f(`PR #${Z.number} created`,"success")},onPrUpdated:Z=>{e.prInfo=Z},addToast:f})]})]})]}),t.jsx("div",{className:"modal-actions",children:Le?t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"modal-edit-hint",children:[t.jsx("kbd",{children:"Ctrl+Enter"})," to save · ",t.jsx("kbd",{children:"Escape"})," to cancel"]}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("button",{className:"btn btn-sm",onClick:Dn,disabled:ut,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Ln,disabled:ut,children:ut?"Saving…":"Save"})]}):t.jsxs(t.Fragment,{children:[e.column==="triage"&&e.status==="awaiting-approval"&&C.prompt&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:wt,children:"Approve Plan"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:jt,children:"Reject Plan"})]}),e.column==="triage"&&e.status!=="awaiting-approval"&&!w&&t.jsx("button",{className:"btn btn-sm btn-danger",onClick:zn,"aria-label":"Delete task",title:"Delete task",children:"Delete"}),(e.column!=="triage"||e.status==="awaiting-approval"||w||e.paused)&&t.jsxs("div",{className:"detail-actions-dropdown",ref:Kn,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>{Ke(Z=>!Z),ze(!1)},"aria-haspopup":"menu","aria-expanded":Be,children:["Actions",t.jsx(Yt,{size:12})]}),Be&&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:()=>xn(zn),children:"Delete"}),m&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>xn(Me),children:"Duplicate"}),(e.column==="done"||e.column==="in-review")&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>xn(mn),children:"Refine"}),t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>xn(fn),children:"Respecify"}),w&&u&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>xn(zs),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:()=>xn(ae),children:"Reset"}),e.column!=="done"&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>xn(it),children:e.paused?"Unpause":"Pause"})]})]}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("div",{className:"detail-move-dropdown",ref:Cn,children:e.column==="in-review"?t.jsxs("div",{className:"detail-move-actions-in-review",children:[t.jsxs("div",{children:[t.jsxs("button",{ref:pn,className:"btn btn-primary btn-sm detail-move-btn",onClick:Xr,onKeyDown:Ua,disabled:!is,"aria-label":is?`Move to ${Wn[is]}`:void 0,"aria-haspopup":ms?"menu":void 0,"aria-expanded":ms?ge:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",is?Wn[is]:""]}),ms&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(Yt,{size:12})})]}),ge&&ms&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:na,children:ta.map(Z=>t.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>on(Z),onKeyDown:na,children:Z==="in-progress"?"Back to In Progress":`Move to ${Wn[Z]}`},Z))})]}),hi?t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!0,children:hi}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:qn,children:"Merge & Close"})]}):t.jsxs("div",{children:[t.jsxs("button",{ref:pn,className:"btn btn-primary btn-sm detail-move-btn",onClick:Xr,onKeyDown:Ua,disabled:!is,"aria-label":is?`Move to ${Wn[is]}`:void 0,"aria-haspopup":ms?"menu":void 0,"aria-expanded":ms?ge:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",is?Wn[is]:""]}),ms&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(Yt,{size:12})})]}),ge&&ms&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:na,children:ta.map(Z=>t.jsxs("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>on(Z),onKeyDown:na,children:["Move to ",Wn[Z]]},Z))})]})})]})}),$e&&t.jsx("div",{className:"modal-overlay open detail-refine-overlay",onClick:On,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal detail-refine-modal",onClick:Z=>Z.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:On,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"detail-body",children:[t.jsx("p",{className:"detail-refine-help",children:"Describe what needs to be refined or improved..."}),t.jsx("textarea",{className:"detail-refine-textarea",value:oe,onChange:Z=>je(Z.target.value),placeholder:"Enter your feedback here...",rows:6,maxLength:2e3,autoFocus:!0}),t.jsxs("div",{className:"detail-refine-input-group",children:[t.jsxs("div",{className:"detail-refine-char-count",children:[oe.length,"/2000 characters"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:tt,disabled:!oe.trim()||ie,children:ie?"Creating...":"Create Refinement Task"})]})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:On,disabled:ie,children:"Cancel"})})]})}),O&&t.jsx(a.Suspense,{fallback:null,children:t.jsx(SR,{agentId:O,projectId:n,onClose:()=>_(null),addToast:f})})]})})}const MR=640;function AR({isOpen:e,onClose:n,onImport:s,tasks:i,projectId:r}){const[o,l]=a.useState(""),[c,u]=a.useState(""),[d,m]=a.useState(""),[h,f]=a.useState(!1),[p,g]=a.useState("issues"),[b,v]=a.useState([]),[x,y]=a.useState(null),[j,E]=a.useState([]),[C,w]=a.useState(null),[R,S]=a.useState(null),[O,_]=a.useState(!1),[P,U]=a.useState([]),[G,M]=a.useState(!1),[T,D]=a.useState(""),K=a.useRef(!1),J=a.useRef(null);di(J,e,"fusion:github-modal-size");const te=Mi(n),[N,z]=a.useState(!1),[I,k]=a.useState("list"),H=a.useRef(null),Q=new Set;for(const we of i){const Ee=we.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);Ee&&Q.add(Ee[1]);const Ve=we.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);Ve&&Q.add(Ve[1])}a.useEffect(()=>{if(e)return l(""),u(""),m(""),v([]),y(null),E([]),w(null),g("issues"),S(null),_(!1),U([]),M(!0),D(""),H.current=null,K.current=!0,cw().then(we=>{if(K.current)if(U(we),M(!1),we.length===1){const Ee=we[0];l(Ee.owner),u(Ee.repo),D(Ee.name)}else we.length>1&&(l(""),u(""),D(""))}).catch(()=>{K.current&&M(!1)}),()=>{K.current=!1}},[e]);const ue=a.useCallback(we=>{if(D(we),we==="")l(""),u("");else{const Ee=P.find(Ve=>Ve.name===we);Ee&&(l(Ee.owner),u(Ee.repo))}},[P]),be=a.useCallback(async()=>{if(!o.trim()||!c.trim()){S("Repository must be selected");return}f(!0),S(null),v([]),y(null);try{const we=d.split(",").map(Ve=>Ve.trim()).filter(Boolean),Ee=await aw(o.trim(),c.trim(),30,we.length>0?we:void 0);v(Ee),Ee.length===0&&S("No open issues found")}catch(we){S(ke(we)||"Failed to fetch issues")}finally{f(!1)}},[o,c,d]),V=a.useCallback(async()=>{if(!o.trim()||!c.trim()){S("Repository must be selected");return}f(!0),S(null),E([]),w(null);try{const we=await ow(o.trim(),c.trim(),30);E(we),we.length===0&&S("No open pull requests found")}catch(we){S(ke(we)||"Failed to fetch pull requests")}finally{f(!1)}},[o,c]);a.useEffect(()=>{if(!e||!o.trim()||!c.trim()||h||O)return;const we={owner:o.trim(),repo:c.trim(),labels:d.trim(),tab:p};H.current?.owner===we.owner&&H.current?.repo===we.repo&&H.current?.labels===we.labels&&H.current?.tab===we.tab||(H.current=we,p==="issues"?be():V())},[o,c,d,p,e,h,O,be,V]),a.useEffect(()=>{if(!e)return;const we=Ee=>{Ee.key==="Escape"&&n()};return document.addEventListener("keydown",we),()=>document.removeEventListener("keydown",we)},[e,n]),a.useEffect(()=>{if(!e)return;const we=()=>{z(window.innerWidth<=MR)};return we(),window.addEventListener("resize",we),()=>window.removeEventListener("resize",we)},[e]);const ve=a.useCallback(we=>{y(we),N&&k("preview")},[N]),B=a.useCallback(we=>{w(we),N&&k("preview")},[N]),Y=a.useCallback(()=>{k("list")},[]),X=a.useCallback(async()=>{if(p==="issues"){if(x===null)return;_(!0),S(null);try{const we=await rw(o.trim(),c.trim(),x,r);s(we),y(null),N&&I==="preview"&&k("list")}catch(we){const Ee=ke(we);Ee?.includes("already imported")?S(Ee):S(Ee||"Failed to import issue")}finally{_(!1)}}else{if(C===null)return;_(!0),S(null);try{const we=await lw(o.trim(),c.trim(),C,r);s(we),w(null),N&&I==="preview"&&k("list")}catch(we){const Ee=ke(we);Ee?.includes("already imported")?S(Ee):S(Ee||"Failed to import pull request")}finally{_(!1)}}},[p,x,C,o,c,s,N,I]),he=b.find(we=>we.number===x),de=j.find(we=>we.number===C);if(!e)return null;const me=P.length>0,se=P.length===1,_e=b.filter(we=>Q.has(we.html_url)).length,Fe=j.filter(we=>Q.has(we.html_url)).length,Te=R==="No open issues found",st=R==="No open pull requests found",nt=p==="issues"?Te:st,qe=!!R&&!Te&&b.length===0&&!h,Xe=!!R&&!st&&j.length===0&&!h,$e=p==="issues"?qe:Xe,Ue=h||b.length>0||Te||qe,oe=h||j.length>0||st||Xe,je=p==="issues"?Ue:oe,ie=!!R&&b.length>0&&!Te,Ae=!!R&&j.length>0&&!st,Le=p==="issues"?ie:Ae;return t.jsx("div",{className:"modal-overlay open",...te,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg github-import-modal",ref:J,children:[t.jsxs("div",{className:"modal-header github-import-modal__header",children:[t.jsxs("div",{children:[t.jsx("h3",{children:"Import from GitHub"}),t.jsx("p",{className:"github-import-modal__subtitle",children:"Choose a detected remote, load open issues or pull requests, and import one into the board."})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close import modal",children:"×"})]}),t.jsxs("div",{className:"modal-body github-import-modal__body",children:[t.jsxs("div",{className:"github-import-tabs",role:"tablist","aria-label":"Import type",children:[t.jsxs("button",{role:"tab","aria-selected":p==="issues","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="issues"?"active":""}`,onClick:()=>{g("issues"),w(null)},disabled:h||O,children:[t.jsx(tl,{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||O,children:[t.jsx(Es,{size:16}),t.jsx("span",{children:"Pull Requests"})]})]}),t.jsxs("div",{className:"github-import-toolbar","data-testid":"github-import-toolbar",role:"toolbar","aria-label":"GitHub import controls",children:[t.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--remote",children:G?t.jsxs("div",{className:"github-import-toolbar__loading",role:"status","aria-live":"polite",children:[t.jsx(lt,{size:16,className:"spin"}),t.jsx("span",{children:"Detecting…"})]}):me?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:P[0].name}),t.jsxs("span",{className:"github-import-remote-pill__repo",children:[P[0].owner,"/",P[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:T,onChange:we=>ue(we.target.value),disabled:h||O,"aria-label":"Select Git remote",children:[t.jsx("option",{value:"",children:"Select remote…"}),P.map(we=>t.jsxs("option",{value:we.name,children:[we.name," (",we.owner,"/",we.repo,")"]},we.name))]})]}):t.jsx("span",{className:"github-import-toolbar__no-remote",children:"No remotes"})}),t.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--filter",children:p==="issues"?t.jsxs(t.Fragment,{children:[t.jsx("label",{htmlFor:"gh-labels",className:"visually-hidden",children:"Filter by labels"}),t.jsx("input",{id:"gh-labels",type:"text",placeholder:"Filter: bug,enhancement…",value:d,onChange:we=>m(we.target.value),onKeyDown:we=>we.key==="Enter"&&be(),disabled:h||O||!me,"aria-label":"Filter issues by labels"})]}):t.jsxs("span",{className:"github-import-filter-hint",children:["Open pull requests from ",o||"selected remote"]})}),t.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--action",children:t.jsxs("button",{id:"gh-load",className:"btn btn-primary github-import-load-button",onClick:p==="issues"?be:V,disabled:h||O||!o.trim()||!c.trim(),"aria-label":h?`Loading ${p}`:`Load ${p} from repository`,title:h?"Loading…":`Load ${p}`,children:[h?t.jsx(lt,{size:14,className:"spin"}):t.jsx(Fn,{size:14}),t.jsx("span",{children:h?"Loading…":"Load"})]})})]}),!G&&!me&&t.jsxs("div",{className:"github-import-state github-import-state--warning",role:"alert",children:[t.jsxs("div",{children:[t.jsx("strong",{children:"No GitHub remotes detected"}),t.jsx("span",{children:"Add a GitHub remote to this repository, then reopen the modal."})]}),t.jsx("code",{className:"github-import-command",children:"git remote add origin https://github.com/owner/repo.git"})]}),Le&&t.jsx("div",{className:"form-error github-import-banner",role:"alert",children:R}),t.jsxs("div",{className:"github-import-workspace",children:[t.jsxs("section",{className:`github-import-list-pane ${N?"mobile":""} ${I==="list"?"active":""}`,"data-testid":"github-import-list-pane","aria-labelledby":"github-import-results-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[t.jsx("h4",{id:"github-import-results-heading",children:p==="issues"?"Issues":"Pull Requests"}),p==="issues"&&b.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[b.length," issue",b.length===1?"":"s"]}),t.jsxs("span",{children:[_e," imported"]})]}),p==="pulls"&&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:[Fe," 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(lt,{size:16,className:"spin"}),t.jsxs("div",{children:[t.jsxs("strong",{children:["Loading open ",p==="issues"?"issues":"pull requests","…"]}),t.jsx("span",{children:"Fetching the latest list from GitHub."})]})]}),$e&&t.jsx("div",{className:"github-import-state github-import-state--error",role:"alert",children:t.jsxs("div",{children:[t.jsxs("strong",{children:["Could not load ",p==="issues"?"issues":"pull requests"]}),t.jsx("span",{children:R})]})}),nt&&t.jsx("div",{className:"github-import-state github-import-state--empty",role:"status",children:t.jsxs("div",{children:[t.jsxs("strong",{children:["No open ",p==="issues"?"issues":"pull requests"," found"]}),t.jsx("span",{children:p==="issues"?"Try a different label filter or choose another repository.":"Choose another repository."})]})}),p==="issues"&&b.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:b.map(we=>{const Ee=Q.has(we.html_url);return t.jsxs("div",{className:`issue-item ${x===we.number?"selected":""} ${Ee?"imported":""}`,onClick:()=>!Ee&&ve(we.number),children:[t.jsx("input",{type:"radio",name:"issue",checked:x===we.number,onChange:()=>ve(we.number),disabled:Ee,"aria-label":`Select issue #${we.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",we.number]}),t.jsx("span",{className:"issue-title",children:we.title})]}),we.labels.length>0&&t.jsx("span",{className:"issue-labels",children:we.labels.map(Ve=>t.jsx("span",{className:"label-chip",children:Ve.name},Ve.name))})]}),Ee&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},we.number)})}),p==="pulls"&&j.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:j.map(we=>{const Ee=Q.has(we.html_url);return t.jsxs("div",{className:`issue-item ${C===we.number?"selected":""} ${Ee?"imported":""}`,onClick:()=>!Ee&&B(we.number),children:[t.jsx("input",{type:"radio",name:"pull",checked:C===we.number,onChange:()=>B(we.number),disabled:Ee,"aria-label":`Select pull request #${we.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",we.number]}),t.jsx("span",{className:"issue-title",children:we.title})]}),t.jsxs("span",{className:"pull-branch-info",children:[we.headBranch," → ",we.baseBranch]})]}),Ee&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},we.number)})})]})]}),t.jsxs("section",{className:`github-import-preview-pane ${N?"mobile":""} ${I==="preview"?"active":""}`,"data-testid":"github-import-preview-pane","aria-labelledby":"github-import-preview-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[N&&t.jsxs("button",{className:"github-import-back-button",onClick:Y,"data-testid":"github-import-back-button","aria-label":`Back to ${p==="issues"?"issues":"pull requests"} list`,children:[t.jsx(Ra,{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"&&he?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Issue #",he.number]}),t.jsx("div",{className:"preview-title",children:he.title}),t.jsx("div",{className:"preview-body",children:he.body?he.body.slice(0,200)+(he.body.length>200?"…":""):"(no description)"})]}):p==="issues"?t.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-preview-empty",children:t.jsxs("div",{children:[t.jsx("strong",{children:"No issue selected"}),t.jsx("span",{children:"Choose an issue from the list to inspect its title and description."})]})}):null,p==="pulls"&&de?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Pull Request #",de.number]}),t.jsx("div",{className:"preview-title",children:de.title}),t.jsxs("div",{className:"preview-branch",children:[t.jsx("strong",{children:"Branch:"})," ",de.headBranch," → ",de.baseBranch]}),t.jsx("div",{className:"preview-body",children:de.body?de.body.slice(0,200)+(de.body.length>200?"…":""):"(no description)"})]}):p==="pulls"?t.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-preview-empty",children:t.jsxs("div",{children:[t.jsx("strong",{children:"No pull request selected"}),t.jsx("span",{children:"Choose a pull request from the list to inspect its details."})]})}):null]})]})]})]}),t.jsxs("div",{className:"modal-actions github-import-modal__actions",children:[t.jsx("button",{className:"btn",onClick:n,disabled:O,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:X,disabled:(p==="issues"?x===null:C===null)||O,children:O?t.jsx(lt,{size:14,className:"spin"}):"Import"})]})]})})}function RR({summary:e,children:n,className:s="",onToggle:i}){const[r,o]=a.useState(!1);return t.jsxs("div",{className:`onboarding-disclosure ${s}`.trim(),children:[t.jsxs("button",{className:"onboarding-disclosure-trigger",onClick:()=>{const l=!r;o(l),i?.(l)},"aria-expanded":r,type:"button",children:[t.jsx(gn,{size:14,className:"onboarding-disclosure-chevron","aria-hidden":"true"}),t.jsx("span",{children:e})]}),r?t.jsx("div",{className:"onboarding-disclosure-content",children:n}):null]})}const TR=["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 PR(e,n){return e&&n?`${e}/${n}`:""}function IR(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 $R({isOpen:e,onClose:n,onTaskCreated:s,onTasksCreated:i,tasks:r,initialPlan:o,projectId:l,resumeSessionId:c}){const[u,d]=a.useState(""),[m,h]=a.useState({type:"initial"}),[f,p]=a.useState(null),[g,b]=a.useState([]),[v,x]=a.useState([]),[y,j]=a.useState(null),E=a.useRef(!1),C=a.useRef(!1),[w,R]=a.useState(""),[S,O]=a.useState(!0),[_,P]=a.useState(!1),[U,G]=a.useState(!1),[M,T]=a.useState(null),[D,K]=a.useState(0),J=a.useRef(null),te=a.useRef(null),N=a.useRef(null),z=a.useRef(null),I=a.useRef(null),[k,H]=a.useState(c??null),Q=a.useMemo(()=>Qi(),[]),{isLockedByOther:ue,takeControl:be,isLoading:V}=pl(e?k:null),{activeTabMap:ve,broadcastUpdate:B,broadcastCompleted:Y,broadcastLock:X,broadcastUnlock:he,broadcastHeartbeat:de}=La(),[me,se]=a.useState(void 0),[_e,Fe]=a.useState(void 0),[Te,st]=a.useState([]),[nt,qe]=a.useState(!1),[Xe,$e]=a.useState(null),[Ue,oe]=a.useState([]),[je,ie]=a.useState([]),Ae=a.useRef(null),[Le,we]=a.useState([]),[Ee,Ve]=a.useState(!1),[rt,xe]=a.useState(c??null),[ce,Pe]=a.useState(!!c),[pe,Re]=a.useState(null),[Qe,Ie]=a.useState(!1),bt=a.useRef(!1),ee=a.useRef(null);di(te,e,"fusion:planning-modal-size"),a.useEffect(()=>{const F=ee.current;if(!F)return;F.scrollHeight-F.scrollTop-F.clientHeight<32&&(F.scrollTop=F.scrollHeight)},[w]),a.useEffect(()=>{if(m.type!=="loading"){T(null),K(0);return}const F=Date.now();T(F),K(0);const ge=setInterval(()=>{K(Math.max(0,Math.floor((Date.now()-F)/1e3)))},1e3);return()=>clearInterval(ge)},[m.type]),a.useEffect(()=>{if(m.type!=="loading")return;const F=z.current;if(!F)return;let ge=!1;const Be=setInterval(async()=>{try{const Ke=await ai(F);if(ge||!Ke||z.current!==F)return;if(Ke.status==="awaiting_input"&&Ke.currentQuestion){const dt=JSON.parse(Ke.currentQuestion);h({type:"question",session:{sessionId:F,currentQuestion:dt,summary:null}}),R("")}else if(Ke.status==="complete"&&Ke.result){const dt=JSON.parse(Ke.result);h({type:"summary",session:{sessionId:F,currentQuestion:null,summary:dt},summary:dt}),j(dt),R("")}}catch{}},8e3);return()=>{ge=!0,clearInterval(Be)}},[m.type]);const re=a.useCallback(()=>{d(""),h({type:"initial"}),p(null),b([]),x([]),j(null),R(""),P(!1),G(!1),se(void 0),Fe(void 0),z.current=null,H(null)},[]),Se=PR(me,_e),ot=a.useCallback((F,ge)=>{if(!F||!ge)return"Using default";const ze=Te.find(Be=>Be.provider===F&&Be.id===ge);return ze?`${ze.provider}/${ze.id}`:`${F}/${ge}`},[Te]),ne=a.useCallback(async()=>{qe(!0),$e(null);try{const F=await bs();st(F.models),oe(F.favoriteProviders),ie(F.favoriteModels)}catch(F){$e(ke(F)||"Failed to load models")}finally{qe(!1)}},[]),Ze=a.useCallback(F=>{oe(ge=>{const ze=ge,Ke=ze.includes(F)?ze.filter(dt=>dt!==F):[F,...ze];return bn({favoriteProviders:Ke,favoriteModels:je}).catch(()=>{oe(ze)}),Ke})},[je]),ft=a.useCallback(F=>{ie(ge=>{const ze=ge,Ke=ze.includes(F)?ze.filter(dt=>dt!==F):[F,...ze];return bn({favoriteProviders:Ue,favoriteModels:Ke}).catch(()=>{ie(ze)}),Ke})},[Ue]),gt=a.useCallback(F=>{N.current?.close();const ge=()=>z.current!==F,ze=cj(F,l,{onThinking:Be=>{ge()||(R(Ke=>Ke+Be),B({sessionId:F,status:"generating",needsInput:!1,owningTabId:Q,type:"planning",title:u.trim()||void 0,projectId:l??null}))},onQuestion:Be=>{ge()||(P(!1),G(!1),la(l),h({type:"question",session:{sessionId:F,currentQuestion:Be,summary:null}}),R(""),B({sessionId:F,status:"awaiting_input",needsInput:!0,owningTabId:Q,type:"planning",title:u.trim()||void 0,projectId:l??null}))},onSummary:Be=>{ge()||(P(!1),G(!1),la(l),h({type:"summary",session:{sessionId:F,currentQuestion:null,summary:Be},summary:Be}),j(Be),R(""),B({sessionId:F,status:"complete",needsInput:!1,owningTabId:Q,type:"planning",title:u.trim()||void 0,projectId:l??null}))},onError:Be=>{const Ke=Be||"Session failed while contacting the AI.";P(!0),(async()=>{try{const dt=await ai(F);if(dt&&(dt.status==="generating"||dt.status==="awaiting_input")){gt(F);return}}catch{}P(!1),G(!1),p(null),h(dt=>dt.type==="question"||dt.type==="summary"||dt.type==="error"?{type:"error",session:dt.session,errorMessage:Ke}:{type:"error",session:{sessionId:F,currentQuestion:null,summary:null},errorMessage:Ke}),R(""),z.current=F,B({sessionId:F,status:"error",needsInput:!1,owningTabId:Q,type:"planning",title:u.trim()||void 0,projectId:l??null}),Y({sessionId:F,status:"error"})})()},onComplete:()=>{P(!1),G(!1),z.current=null,Y({sessionId:F,status:"complete"})},onConnectionStateChange:Be=>{P(Be==="reconnecting")}});N.current=ze},[Y,B,u,l,Q]),St=a.useCallback(async F=>{const ge=F??u;if(ge.trim()){p(null),R(""),x([]),b([]),P(!1),h({type:"loading"});try{const ze=me&&_e?{planningModelProvider:me,planningModelId:_e}:void 0,{sessionId:Be}=await Vw(ge.trim(),l,ze);z.current=Be,H(Be),xe(Be),gt(Be),b([])}catch(ze){P(!1),p(ke(ze)||"Failed to start planning session"),h({type:"initial"}),z.current=null,H(null)}}},[gt,u,_e,me,l]);a.useEffect(()=>{e&&m.type==="initial"&&J.current?.focus()},[e,m.type]),a.useEffect(()=>{e&&ne()},[e,ne]),a.useEffect(()=>{if(e&&o&&!E.current&&m.type==="initial"){d(o);const F=setTimeout(()=>{E.current=!0,St(o)},0);return()=>clearTimeout(F)}else if(e&&!o&&!E.current&&!C.current&&m.type==="initial"){C.current=!0;const F=jS(l);F&&d(F)}},[e,o,m.type,St,l]);const Nt=a.useCallback(async F=>{N.current?.close(),N.current=null,p(null),R(""),b([]),x([]),j(null),G(!1),h({type:"loading"});try{const ge=await ai(F);if(!ge){xe(null),Pe(!1),h({type:"initial"});return}z.current=F,H(F);const ze=ka(ge.conversationHistory);if(x(ze),b(ze.map(Be=>Be.response).filter(Be=>!!(Be&&typeof Be=="object"&&!Array.isArray(Be)))),ge.status==="awaiting_input"&&ge.currentQuestion){la(l);const Be=JSON.parse(ge.currentQuestion);h({type:"question",session:{sessionId:F,currentQuestion:Be,summary:null}}),ge.thinkingOutput&&R(ge.thinkingOutput),gt(F)}else if(ge.status==="complete"&&ge.result){la(l);const Be=JSON.parse(ge.result);h({type:"summary",session:{sessionId:F,currentQuestion:null,summary:Be},summary:Be}),j(Be)}else ge.status==="generating"?(h({type:"loading"}),ge.thinkingOutput&&R(ge.thinkingOutput),gt(F)):ge.status==="error"&&h({type:"error",session:{sessionId:F,currentQuestion:null,summary:null},errorMessage:ge.error||"Session failed"})}catch{p("Failed to load session"),h({type:"initial"})}},[gt,l]);a.useEffect(()=>{!e||!c||z.current!==c&&I.current!==c&&(xe(c),Pe(!0),Nt(c))},[e,c]),a.useEffect(()=>{e&&rt&&(c&&c===rt||Nt(rt))},[e]);const pt=a.useCallback(async()=>{Ve(!0);try{const ge=(await jd(l,{includeCompleted:!0,includeArchived:Qe})).filter(ze=>ze.type==="planning").sort((ze,Be)=>Date.parse(Be.updatedAt)-Date.parse(ze.updatedAt));we(ge)}catch{}finally{Ve(!1)}},[l,Qe]);a.useEffect(()=>{e&&pt()},[e,pt]),a.useEffect(()=>{if(!e)return;const F=l?`?projectId=${encodeURIComponent(l)}`:"",ge=Be=>{try{const Ke=JSON.parse(Be.data);if(Ke.type!=="planning")return;we(dt=>{const Xt=dt.findIndex(pn=>pn.id===Ke.id);return(Xt>=0?[...dt.slice(0,Xt),Ke,...dt.slice(Xt+1)]:[Ke,...dt]).sort((pn,Kn)=>Date.parse(Kn.updatedAt)-Date.parse(pn.updatedAt))})}catch{}},ze=Be=>{try{const Ke=JSON.parse(Be.data);we(dt=>dt.filter(Xt=>Xt.id!==Ke))}catch{}};return Js(`/api/events${F}`,{events:{"ai_session:updated":ge,"ai_session:deleted":ze},onReconnect:()=>{pt()}})},[e,l,pt]);const kt=a.useCallback(F=>{if(rt===F){Pe(!0);return}xe(F),Pe(!0),Nt(F)},[Nt,rt]),Ht=a.useCallback(()=>{N.current?.close(),N.current=null,c&&(I.current=c),re(),xe(null),Pe(!0)},[re,c]),$t=a.useCallback(()=>{Pe(!1)},[]),Tt=a.useCallback(async F=>{const ge=Be=>Be==="generating"||Be==="awaiting_input",ze=Le.find(Be=>Be.id===F);if(ze&&ge(ze.status))try{await zp(F,l,Q)}catch{}try{await Wp(F)}catch{}Y({sessionId:F,status:"complete",timestamp:Date.now()}),we(Be=>Be.filter(Ke=>Ke.id!==F)),rt===F&&(N.current?.close(),N.current=null,re(),xe(null),Pe(!1)),Re(null)},[Y,Le,l,re,rt,Q]),Mt=a.useCallback(async F=>{const ze=Le.find(Be=>Be.id===F)?.archived===!0;try{ze?await Ok(F):await zk(F)}catch{return}we(Be=>!ze&&!Qe?Be.filter(Ke=>Ke.id!==F):Be.map(Ke=>Ke.id===F?{...Ke,archived:!ze}:Ke)),!ze&&rt===F&&!Qe&&(N.current?.close(),N.current=null,re(),xe(null),Pe(!1))},[Le,re,rt,Pe,Qe]);a.useEffect(()=>{e||(E.current=!1,C.current=!1,P(!1),G(!1),H(null))},[e]),a.useEffect(()=>{if(!e){Ae.current&&(he(Ae.current,Q),Ae.current=null);return}if(k&&Ae.current!==k){Ae.current&&he(Ae.current,Q),X(k,Q),Ae.current=k;return}!k&&Ae.current&&(he(Ae.current,Q),Ae.current=null)},[X,he,e,k,Q]),a.useEffect(()=>{if(!e||!k||Ae.current!==k)return;de(Q);const F=setInterval(()=>{de(Q)},3e4);return()=>{clearInterval(F)}},[de,e,k,Q]),a.useEffect(()=>()=>{N.current?.close(),N.current=null,Ae.current&&(he(Ae.current,Q),Ae.current=null)},[he,Q]),a.useEffect(()=>{if(!e)return;const F=()=>{N.current?.close(),N.current=null};return window.addEventListener("beforeunload",F),()=>window.removeEventListener("beforeunload",F)},[e]);const Ot=a.useCallback(()=>{u&&m.type==="initial"&&wS(u,l),N.current?.close(),N.current=null,P(!1),G(!1),n()},[u,n,l,m.type]);a.useEffect(()=>{if(!e)return;const F=ge=>{ge.key==="Escape"&&Ot()};return document.addEventListener("keydown",F),()=>document.removeEventListener("keydown",F)},[e,Ot]);const zt=a.useCallback(async F=>{if(m.type!=="question")return;const{session:ge}=m,ze=ge.sessionId,Be=ge.currentQuestion;if(!Be){p("No active question in session");return}p(null),b(Ke=>[...Ke,F]),x(Ke=>[...Ke,{question:Be,response:F}]),h({type:"loading"}),R("");try{await Ww(ze,F,l,Q)}catch(Ke){p(ke(Ke)||"Failed to submit response"),h({type:"question",session:ge})}},[l,Q,m]),Ft=a.useCallback(async()=>{const F=z.current;if(F){try{await Gw(F,l,Q)}catch{}N.current?.close(),N.current=null,P(!1),G(!1),h({type:"error",session:{sessionId:F,currentQuestion:null,summary:null},errorMessage:"Generation stopped by user. You can retry or start a new session."}),R("")}},[l,Q]),Et=a.useCallback(async()=>{if(m.type!=="error")return;const F=m.session;p(null),G(!0),R(""),h({type:"loading"}),gt(F.sessionId);try{z.current=F.sessionId,H(F.sessionId),await Kw(F.sessionId,l,Q)}catch(ge){let ze=ge;if((ke(ge)||"").includes("not in an error state"))try{const Ke=await ai(F.sessionId);if(!Ke)throw new Error("Failed to refresh planning session.");if(z.current=Ke.id,H(Ke.id),Ke.status==="generating")R(Ke.thinkingOutput??""),h({type:"loading"});else if(Ke.status==="awaiting_input"){if(!Ke.currentQuestion)throw new Error("Planning session is awaiting input but has no current question.");const dt=JSON.parse(Ke.currentQuestion);la(l),h({type:"question",session:{sessionId:Ke.id,currentQuestion:dt,summary:null}}),N.current?.isConnected()||gt(Ke.id)}else if(Ke.status==="complete"){if(!Ke.result)throw new Error("Planning session is complete but has no result.");const dt=JSON.parse(Ke.result);la(l),h({type:"summary",session:{sessionId:Ke.id,currentQuestion:null,summary:dt},summary:dt}),j(dt)}else Ke.status==="error"&&h({type:"error",session:{sessionId:Ke.id,currentQuestion:null,summary:null},errorMessage:Ke.error||"Retry failed. Please try again."});P(!1);return}catch(Ke){ze=Ke}N.current?.close(),N.current=null,h({type:"error",session:F,errorMessage:ke(ze)||"Retry failed. Please try again."}),P(!1)}finally{G(!1)}},[gt,l,Q,m]),Pt=a.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const F=m.session.sessionId,ge=await Jw(F,y??void 0,l);s(ge),xe(null),we(ze=>ze.filter(Be=>Be.id!==F)),Y({sessionId:F,status:"complete",timestamp:Date.now()}),Ot()}catch(F){p(ke(F)||"Failed to create task"),h({type:"summary",session:m.session,summary:m.summary})}}},[Y,y,m,l,s,Ot]),Dt=a.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const F=await Yw(m.session.sessionId,y??void 0,l);H(F.sessionId),h({type:"breakdown",sessionId:F.sessionId,subtasks:F.subtasks,dirty:!1})}catch(F){p(ke(F)||"Failed to start breakdown"),h({type:"summary",session:m.session,summary:m.summary})}}},[y,m,l]),Wt=a.useCallback(async()=>{if(m.type==="breakdown"){p(null),h({type:"creating"});try{const F=m.sessionId,ge=await Qw(F,m.subtasks,l);i(ge.tasks),we(ze=>ze.filter(Be=>Be.id!==F)),Y({sessionId:F,status:"complete",timestamp:Date.now()}),d(""),h({type:"initial"}),p(null),b([]),x([]),j(null),R(""),se(void 0),Fe(void 0),z.current=null,H(null),xe(null),n()}catch(F){p(ke(F)||"Failed to create tasks"),h({type:"breakdown",sessionId:m.sessionId,subtasks:m.subtasks,dirty:m.dirty})}}},[Y,m,i,n,l]),It=a.useCallback(()=>{if(m.type==="question"&&g.length>0){const F=g.slice(0,-1);b(F),h({type:"question",session:m.session})}},[m,g]),Rt=()=>m.type==="question"?Math.min(g.length+1,3):3,fe=k?ve.get(k):null,Oe=fe&&fe.tabId!==Q,ut=!!(Oe&&!fe.stale),L=ue&&(!Oe||fe.stale);return e?t.jsx("div",{className:"modal-overlay open",onMouseDown:F=>{bt.current=F.target===F.currentTarget},onClick:F=>{F.target===F.currentTarget&&bt.current&&Ot(),bt.current=!1},role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",ref:te,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[ce&&t.jsx("button",{className:"modal-back planning-mobile-back",onClick:$t,"aria-label":"Back to sessions",title:"Back to sessions",children:t.jsx(el,{size:18})}),t.jsx(ri,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Planning Mode"})]}),t.jsx("div",{className:"modal-header-actions",children:t.jsx("button",{className:"modal-close",onClick:Ot,"aria-label":"Close",children:t.jsx(qt,{size:20})})})]}),t.jsxs("div",{className:`planning-modal-body planning-modal-body--split ${ce?"planning-modal-body--show-detail":"planning-modal-body--show-list"}`,children:[t.jsx(FR,{sessions:Le,loading:Ee,selectedSessionId:rt,pendingDeleteId:pe,showArchived:Qe,onToggleShowArchived:()=>Ie(F=>!F),onArchive:F=>void Mt(F),onSelectSession:kt,onNewSession:Ht,onRequestDelete:Re,onConfirmDelete:F=>void Tt(F),onCancelDelete:()=>Re(null)}),t.jsxs("div",{className:"planning-detail",children:[f&&t.jsx("div",{className:"form-error planning-error",children:f}),_&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),ut&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),m.type==="initial"&&t.jsxs("div",{className:"planning-initial",children:[t.jsxs("div",{className:"planning-view-scroll",children:[t.jsxs("div",{className:"planning-intro",children:[t.jsx(cs,{size:32,className:"icon-triage-lg"}),t.jsx("h4",{children:"Transform your idea into a detailed task"}),t.jsx("p",{className:"text-muted",children:"Describe what you want to build in plain language. The AI will ask clarifying questions and help you structure a well-defined task."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"initial-plan",children:"What do you want to build?"}),t.jsx("textarea",{ref:J,id:"initial-plan",rows:4,className:"planning-textarea",placeholder:"e.g., Build a user authentication system with login, signup, and password reset...",value:u,onChange:F=>d(F.target.value),onKeyDown:F=>{F.key==="Enter"&&!F.shiftKey&&u.trim()&&(F.preventDefault(),St())}})]}),t.jsxs("div",{className:"planning-examples",children:[t.jsx("span",{className:"planning-examples-label",children:"Try an example:"}),t.jsx("div",{className:"planning-example-chips",children:TR.map((F,ge)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>d(F),children:F.length>40?F.slice(0,40)+"...":F},ge))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"planning-modal-model",className:"form-label",children:["Planning Model",nt&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(ns,{id:"planning-modal-model",label:"Planning Model",value:Se,onChange:F=>{const{provider:ge,modelId:ze}=IR(F);se(ge),Fe(ze)},models:Te,disabled:nt,favoriteProviders:Ue,onToggleFavorite:Ze,favoriteModels:je,onToggleModelFavorite:ft}),Xe&&t.jsxs("div",{className:"form-hint form-hint-error",children:[Xe," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{ne()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${me&&_e?"model-badge-custom":"model-badge-default"}`,children:ot(me,_e)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>St(),disabled:!u.trim(),children:[t.jsx(ri,{size:16,className:"icon-mr-8"}),"Start Planning"]})})]}),m.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(lt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:w?"AI is thinking...":"Generating next question..."}),M&&t.jsxs("div",{className:"planning-elapsed",children:["Thinking… (",D,"s)"]}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>O(!S),type:"button",children:S?"Hide thinking":"Show thinking"}),t.jsx("div",{className:"planning-loading-actions",children:t.jsxs("button",{className:"btn planning-stop-btn",type:"button",onClick:()=>void Ft(),children:[t.jsx(Bb,{size:14}),t.jsx("span",{className:"icon-ml-6",children:"Stop"})]})}),S&&w&&t.jsx("div",{className:"planning-thinking-output",ref:ee,children:t.jsx("pre",{children:w})})]})]}),m.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[v.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ls,{entries:v}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:m.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void Et(),disabled:U,children:[U?t.jsx(lt,{size:14,className:"spin"}):t.jsx(Fn,{size:14}),t.jsx("span",{className:"icon-ml-6",children:U?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Ot,disabled:U,children:"Dismiss"})]})]})]})}),m.type==="creating"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(lt,{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(DR,{question:m.session.currentQuestion,progress:Rt(),historyEntries:v,onSubmit:zt,onBack:g.length>0?It:void 0})}),m.type==="summary"&&y&&t.jsx(LR,{summary:y,historyEntries:v,onSummaryChange:j,tasks:r,onCreateTask:Pt,onBreakIntoTasks:Dt,onRefine:()=>{h({type:"question",session:m.session})},isLoading:!1}),m.type==="breakdown"&&t.jsx(OR,{subtasks:m.subtasks,dirty:m.dirty,isLoading:!1,onUpdateSubtasks:F=>h({...m,subtasks:F,dirty:!0}),onCreateTasks:Wt,onBack:()=>{const ge={sessionId:m.sessionId,currentQuestion:null,summary:y??null};y&&h({type:"summary",session:ge,summary:y})}})]}),ue&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(il,{size:16}),t.jsx("span",{children:L?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),L&&t.jsx("button",{type:"button",onClick:()=>{be()},disabled:V,className:"btn btn-primary session-lock-take-control",children:V?"Taking control...":"Take Control"})]})})]})]})}):null}function DR({question:e,progress:n,historyEntries:s,onSubmit:i,onBack:r}){const[o,l]=a.useState({}),[c,u]=a.useState(""),d=a.useCallback(()=>{e.type==="text"?i({[e.id]:c}):e.type==="confirm"?i({[e.id]:o[e.id]===!0}):i(o)},[e,o,c,i]);a.useEffect(()=>{l({}),u("")},[e.id]);const m=()=>{switch(e.type){case"text":return c.trim().length>0;case"single_select":return o[e.id]!==void 0;case"multi_select":return Array.isArray(o[e.id])&&o[e.id].length>0;case"confirm":return o[e.id]!==void 0;default:return!0}};return t.jsxs("div",{className:"planning-question-form",children:[t.jsxs("div",{className:"planning-view-scroll planning-question-scroll",children:[s.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ls,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3].map(h=>t.jsx("div",{className:`planning-progress-step ${h<=n?"active":""}`},h))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~3"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:c,onChange:h=>u(h.target.value),onKeyDown:h=>{h.key==="Enter"&&!h.shiftKey&&c.trim()&&(h.preventDefault(),d())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(h=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:h.id,checked:o[e.id]===h.id,onChange:()=>l({[e.id]:h.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:h.label}),h.description&&t.jsx("span",{className:"planning-option-desc",children:h.description})]})]},h.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(h=>{const f=o[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:h.id,checked:f.includes(h.id),onChange:p=>{const g=p.target.checked?[...f,h.id]:f.filter(b=>b!==h.id);l({[e.id]:g})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:h.label}),h.description&&t.jsx("span",{className:"planning-option-desc",children:h.description})]})]},h.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!0?"selected":""}`,onClick:()=>l({[e.id]:!0}),children:[t.jsx(Nn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!1?"selected":""}`,onClick:()=>l({[e.id]:!1}),children:[t.jsx(qt,{size:18}),"No"]})]})]})]})]})]}),t.jsxs("div",{className:"planning-actions",children:[r&&t.jsxs("button",{className:"btn",onClick:r,children:[t.jsx(Ra,{size:16,className:"icon-mr-4"}),"Back"]}),t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:d,disabled:!m(),children:["Continue",t.jsx(Dr,{size:16,className:"icon-ml-4"})]})]})]})}function LR({summary:e,historyEntries:n,onSummaryChange:s,tasks:i,onCreateTask:r,onBreakIntoTasks:o,onRefine:l,isLoading:c}){const[u,d]=a.useState(!1),[m,h]=a.useState(e.suggestedDependencies),f=p=>{const g=m.includes(p)?m.filter(b=>b!==p):[...m,p];h(g),s({...e,suggestedDependencies:g})};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(RR,{summary:"Show user Q&A",className:"planning-summary-qa-disclosure",children:[t.jsx(Ls,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Nn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Planning Complete!"}),t.jsx("p",{className:"text-muted",children:"Review and refine your task before creating it."})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{children:["Description",t.jsx("button",{type:"button",className:"planning-expand-btn",onClick:()=>d(!u),children:u?"Collapse":"Expand"})]}),t.jsx("textarea",{className:`planning-textarea ${u?"expanded":""}`,rows:u?10:4,value:e.description,onChange:p=>s({...e,description:p.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Suggested Size"}),t.jsxs("select",{className:"planning-size-select",value:e.suggestedSize,onChange:p=>s({...e,suggestedSize:p.target.value}),disabled:c,children:[t.jsx("option",{value:"S",children:"S (Small)"}),t.jsx("option",{value:"M",children:"M (Medium)"}),t.jsx("option",{value:"L",children:"L (Large)"})]})]}),i.length>0&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Suggested Dependencies"}),t.jsx("div",{className:"planning-deps-list",children:i.map(p=>t.jsxs("label",{className:`planning-dep-chip ${m.includes(p.id)?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:m.includes(p.id),onChange:()=>f(p.id)}),t.jsx("span",{className:"planning-dep-id",children:p.id}),t.jsx("span",{className:"planning-dep-title",children:p.title||p.description.slice(0,30)})]},p.id))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Key Deliverables"}),t.jsx("ul",{className:"planning-deliverables",children:e.keyDeliverables.map((p,g)=>t.jsx("li",{children:p},g))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:l,disabled:c,children:[t.jsx(Ra,{size:16,className:"icon-mr-4"}),"Refine Further"]}),t.jsxs("div",{className:"planning-summary-actions-right",children:[t.jsx("button",{className:"btn",onClick:o,disabled:c,title:"Break the plan into multiple tasks with dependencies",children:c?t.jsxs(t.Fragment,{children:[t.jsx(lt,{size:16,className:"spin icon-mr-8"}),"Breaking down..."]}):t.jsxs(t.Fragment,{children:[t.jsx(sl,{size:16,className:"icon-mr-8"}),"Break into Tasks"]})}),t.jsx("button",{className:"btn btn-primary",onClick:r,disabled:c,children:c?t.jsxs(t.Fragment,{children:[t.jsx(lt,{size:16,className:"spin icon-mr-8"}),"Creating..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Nn,{size:16,className:"icon-mr-8"}),"Create Task"]})})]})]})]})}function Nh(e){const n=new Map(e.map(o=>[o.id,o.dependsOn])),s=new Set,i=new Set,r=o=>{if(s.has(o))return!0;if(i.has(o))return!1;s.add(o);for(const l of n.get(o)??[])if(n.has(l)&&r(l))return!0;return s.delete(o),i.add(o),!1};return e.some(o=>r(o.id))}function zR(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function OR({subtasks:e,dirty:n,isLoading:s,onUpdateSubtasks:i,onCreateTasks:r,onBack:o}){const[l,c]=a.useState(null),[u,d]=a.useState(null),[m,h]=a.useState(null),f=a.useRef([]),p=a.useMemo(()=>e.length===0||e.some(R=>!R.title.trim())?!0:Nh(e),[e]),g=a.useCallback((R,S)=>{i(e.map(O=>O.id===R?{...O,...S}:O))},[e,i]),b=a.useCallback(()=>{i([...e,zR(e.length+1)])},[e,i]),v=a.useCallback(R=>{i(e.filter(S=>S.id!==R).map(S=>({...S,dependsOn:S.dependsOn.filter(O=>O!==R)})))},[e,i]),x=a.useCallback((R,S)=>{if(S<0||S>=e.length)return;const O=[...e],[_]=O.splice(R,1);O.splice(S,0,_),i(O)},[e,i]),y=a.useCallback(R=>S=>{c(R),S.dataTransfer.setData("text/plain",R),S.dataTransfer.effectAllowed="move"},[]),j=a.useCallback(()=>{c(null),d(null),h(null)},[]),E=a.useCallback(R=>S=>{if(S.preventDefault(),R===l)return;const O=S.currentTarget.getBoundingClientRect(),_=O.top+O.height/2,P=S.clientY<_?"before":"after";d(R),h(P)},[l]),C=a.useCallback(R=>S=>{S.preventDefault();const O=S.dataTransfer.getData("text/plain");if(!O||O===R){j();return}const _=e.findIndex(T=>T.id===O),P=e.findIndex(T=>T.id===R);if(_===-1||P===-1){j();return}const U=[...e],[G]=U.splice(_,1);let M=P;m==="after"&&_<P&&M--,m==="after"&&M++,U.splice(M,0,G),i(U),j()},[e,m,i,j]),w=a.useCallback(R=>{const S=R.currentTarget.getBoundingClientRect(),O=R.clientX,_=R.clientY;(O<S.left||O>S.right||_<S.top||_>S.bottom)&&(d(null),h(null))},[]);return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(sl,{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((R,S)=>{const O=l===R.id,_=u===R.id,P=["task-detail-section","subtask-item",O?"subtask-item-dragging":"",_?"subtask-item-drop-target":"",_&&m==="before"?"subtask-item-drop-before":"",_&&m==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:P,"data-testid":`subtask-item-${S}`,draggable:!s,onDragStart:y(R.id),onDragEnd:j,onDragOver:E(R.id),onDrop:C(R.id),onDragLeave:w,children:[t.jsxs("div",{className:"detail-title-row subtask-item-header subtask-item-header--between",children:[t.jsxs("div",{className:"subtask-drag-handle",title:"Drag to reorder",children:[t.jsx(xd,{size:16}),t.jsx("strong",{children:R.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>x(S,S-1),disabled:s||S===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(Fi,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>x(S,S+1),disabled:s||S===e.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx($r,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>v(R.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:U=>{f.current[S]=U},value:R.title,onChange:U=>g(R.id,{title:U.target.value}),onKeyDown:U=>{U.key==="Enter"&&(U.preventDefault(),S<e.length-1&&f.current[S+1]?.focus())},disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:R.description,onChange:U=>g(R.id,{description:U.target.value}),disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Size"}),t.jsxs("select",{className:"planning-size-select",value:R.suggestedSize,onChange:U=>g(R.id,{suggestedSize:U.target.value}),disabled:s,children:[t.jsx("option",{value:"S",children:"S"}),t.jsx("option",{value:"M",children:"M"}),t.jsx("option",{value:"L",children:"L"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"planning-deps-list",children:[e.slice(0,S).filter(U=>U.id!==R.id).map(U=>{const G=R.dependsOn.includes(U.id);return t.jsxs("label",{className:`planning-dep-chip ${G?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:G,onChange:()=>{const M=G?R.dependsOn.filter(T=>T!==U.id):[...R.dependsOn,U.id];g(R.id,{dependsOn:M})},disabled:s}),t.jsx("span",{className:"planning-dep-id",children:U.id}),t.jsx("span",{className:"planning-dep-title",children:U.title||"Untitled"})]},U.id)}),S===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),S>0&&e.slice(0,S).filter(U=>U.id!==R.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},R.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:b,disabled:s,children:[t.jsx(dn,{size:16,className:"icon-mr-6"})," Add subtask"]}),Nh(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(Ra,{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(lt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]})}function FR({sessions:e,loading:n,selectedSessionId:s,pendingDeleteId:i,showArchived:r,onToggleShowArchived:o,onArchive:l,onSelectSession:c,onNewSession:u,onRequestDelete:d,onConfirmDelete:m,onCancelDelete:h}){return t.jsxs("aside",{className:"planning-sidebar","aria-label":"Planning sessions",children:[t.jsx("div",{className:"planning-sidebar-header",children:t.jsxs("button",{className:`planning-sidebar-new ${s===null?"active":""}`,onClick:u,type:"button",children:[t.jsx(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=i===f.id,b=f.archived===!0,v=f.status==="complete"||f.status==="error";return t.jsxs("div",{className:`planning-sidebar-item ${p?"selected":""} ${g?"pending-delete":""} ${b?"archived":""}`,children:[t.jsxs("button",{type:"button",className:"planning-sidebar-item-button",onClick:()=>c(f.id),children:[t.jsx(UR,{status:f.status}),t.jsxs("span",{className:"planning-sidebar-item-body",children:[t.jsx("span",{className:"planning-sidebar-item-title",children:f.title||"Untitled session"}),t.jsxs("span",{className:"planning-sidebar-item-meta",children:[t.jsx(BR,{status:f.status}),t.jsx("span",{"aria-hidden":!0,children:" · "}),t.jsx("span",{children:HR(f.updatedAt)})]})]})]}),g?t.jsxs("div",{className:"planning-sidebar-confirm",children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-danger",onClick:()=>m(f.id),children:"Delete"}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,children:"Cancel"})]}):t.jsxs("div",{className:"planning-sidebar-item-actions",children:[v&&t.jsx("button",{type:"button",className:"planning-sidebar-item-archive",onClick:x=>{x.stopPropagation(),l(f.id)},"aria-label":b?"Unarchive session":"Archive session",title:b?"Unarchive session":"Archive session",children:b?t.jsx(bb,{size:14}):t.jsx(Ir,{size:14})}),t.jsx("button",{type:"button",className:"planning-sidebar-item-delete",onClick:x=>{x.stopPropagation(),d(f.id)},"aria-label":"Delete session",title:"Delete session",children:t.jsx(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 UR({status:e}){switch(e){case"generating":return t.jsx(lt,{size:14,className:"spin planning-sidebar-status-icon planning-sidebar-status-generating"});case"awaiting_input":return t.jsx(Pc,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-awaiting"});case"complete":return t.jsx(Nn,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-complete"});case"error":return t.jsx(gs,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-error"});default:return t.jsx(Ei,{size:14,className:"planning-sidebar-status-icon"})}}function BR({status:e}){switch(e){case"generating":return t.jsx("span",{children:"Generating"});case"awaiting_input":return t.jsx("span",{children:"Needs input"});case"complete":return t.jsx("span",{children:"Complete"});case"error":return t.jsx("span",{children:"Error"});default:return t.jsx("span",{children:e})}}function HR(e){const n=Date.now()-Date.parse(e);if(!Number.isFinite(n)||n<0)return"";const s=Math.floor(n/1e3);if(s<60)return"just now";const i=Math.floor(s/60);if(i<60)return`${i}m ago`;const r=Math.floor(i/60);if(r<24)return`${r}h ago`;const o=Math.floor(r/24);if(o<7)return`${o}d ago`;const l=Math.floor(o/7);return l<4?`${l}w ago`:new Date(e).toLocaleDateString()}function qR(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function Sh(e){const n=new Map(e.map(o=>[o.id,o.dependsOn])),s=new Set,i=new Set,r=o=>{if(s.has(o))return!0;if(i.has(o))return!1;s.add(o);for(const l of n.get(o)??[])if(n.has(l)&&r(l))return!0;return s.delete(o),i.add(o),!1};return e.some(o=>r(o.id))}function VR({isOpen:e,onClose:n,initialDescription:s,onTasksCreated:i,parentTaskId:r,projectId:o,resumeSessionId:l}){const[c,u]=a.useState({type:"initial"}),[d,m]=a.useState([]),[h,f]=a.useState([]),[p,g]=a.useState(""),[b,v]=a.useState(!0),[x,y]=a.useState(!1),[j,E]=a.useState(!1),[C,w]=a.useState(s),[R,S]=a.useState(null),[O,_]=a.useState(!1),[P,U]=a.useState(null),[G,M]=a.useState(null),[T,D]=a.useState(null),K=a.useRef(null),J=a.useRef([]),te=a.useRef(!1),N=a.useRef(null),z=c.type==="generating"||c.type==="editing"||c.type==="creating"||c.type==="error"?c.sessionId:null,I=a.useMemo(()=>Qi(),[]),{isLockedByOther:k,takeControl:H,isLoading:Q}=pl(e?z:null),{activeTabMap:ue,broadcastUpdate:be,broadcastCompleted:V,broadcastLock:ve,broadcastUnlock:B,broadcastHeartbeat:Y}=La(),X=a.useMemo(()=>d.length===0||d.some(ce=>!ce.title.trim())?!0:Sh(d),[d]),he=c.type==="generating"||c.type==="editing"||c.type==="error",de=z?ue.get(z):null,{confirm:me}=Gs(),se=de&&de.tabId!==I,_e=!!(se&&!de.stale),Fe=k&&(!se||de.stale),Te=a.useCallback(()=>{C&&kS(C,o),K.current?.close(),K.current=null,u({type:"initial"}),m([]),f([]),g(""),v(!0),y(!1),E(!1),S(null),_(!1),te.current=!1},[C,o]),st=a.useCallback(()=>{K.current?.close(),K.current=null,n()},[n]),nt=a.useCallback(async()=>{if(!((O||c.type==="editing"||c.type==="creating")&&!await me({title:"Discard Changes",message:"Close subtask breakdown? Unsaved changes will be lost.",danger:!0}))){if(z)try{await Up(z,o,I)}catch{}Te(),n()}},[O,n,Te,z,I,c.type,o,me]),qe=a.useCallback(ce=>{K.current?.close(),K.current=Sj(ce,o,{onThinking:Pe=>{g(pe=>pe+Pe),be({sessionId:ce,status:"generating",needsInput:!1,owningTabId:I,type:"subtask",title:C.trim()||void 0,projectId:o??null})},onSubtasks:Pe=>{y(!1),E(!1),Ol(o),m(Pe),u({type:"editing",sessionId:ce}),_(!1),be({sessionId:ce,status:"awaiting_input",needsInput:!0,owningTabId:I,type:"subtask",title:C.trim()||void 0,projectId:o??null})},onError:Pe=>{const pe=Pe||"Session failed while contacting the AI.";y(!1),E(!1),S(null),u({type:"error",sessionId:ce,errorMessage:pe}),be({sessionId:ce,status:"error",needsInput:!1,owningTabId:I,type:"subtask",title:C.trim()||void 0,projectId:o??null}),V({sessionId:ce,status:"error"})},onComplete:()=>{V({sessionId:ce,status:"complete"})},onConnectionStateChange:Pe=>{y(Pe==="reconnecting")}})},[V,be,C,o,I]),Xe=a.useCallback(async()=>{if(C.trim()){S(null),f([]),g(""),y(!1);try{const{sessionId:ce}=await jj(C.trim(),o);u({type:"generating",sessionId:ce}),qe(ce)}catch(ce){S(ke(ce)||"Failed to start subtask breakdown"),u({type:"initial"})}}},[qe,C,o]);a.useEffect(()=>{if(!e){Te();return}if(e&&s&&!te.current)w(s),te.current=!0,Xe();else if(e&&!s&&!te.current){const ce=NS(o);ce&&w(ce)}},[e,s,Xe,Te]),a.useEffect(()=>{!e||!l||c.type!=="initial"||(async()=>{try{const ce=await ai(l);if(!ce)return;const Pe=ka(ce.conversationHistory);if(f(Pe),ce.status==="generating"||ce.status==="awaiting_input")g(ce.thinkingOutput??""),u({type:"generating",sessionId:l}),qe(l);else if(ce.status==="complete"&&ce.result){Ol(o);const pe=JSON.parse(ce.result);m(pe),u({type:"editing",sessionId:l})}else ce.status==="error"&&(S(null),u({type:"error",sessionId:l,errorMessage:ce.error??"Session encountered an error"}))}catch(ce){S(ke(ce)||"Failed to resume session")}})()},[qe,e,l,c.type,o]),a.useEffect(()=>{if(!e){N.current&&(B(N.current,I),N.current=null);return}if(z&&N.current!==z){N.current&&B(N.current,I),ve(z,I),N.current=z;return}!z&&N.current&&(B(N.current,I),N.current=null)},[ve,B,e,z,I]),a.useEffect(()=>{if(!e||!z||N.current!==z)return;Y(I);const ce=setInterval(()=>{Y(I)},3e4);return()=>{clearInterval(ce)}},[Y,e,z,I]),a.useEffect(()=>()=>{K.current?.close(),N.current&&(B(N.current,I),N.current=null)},[B,I]),a.useEffect(()=>{if(!e)return;const ce=Pe=>{Pe.key==="Escape"&&(Pe.preventDefault(),nt())};return document.addEventListener("keydown",ce),()=>document.removeEventListener("keydown",ce)},[e,nt]);const $e=a.useCallback((ce,Pe)=>{m(pe=>pe.map(Re=>Re.id===ce?{...Re,...Pe}:Re)),_(!0)},[]),Ue=a.useCallback(()=>{m(ce=>[...ce,qR(ce.length+1)]),_(!0)},[]),oe=a.useCallback(ce=>{m(Pe=>Pe.filter(pe=>pe.id!==ce).map(pe=>({...pe,dependsOn:pe.dependsOn.filter(Re=>Re!==ce)}))),_(!0)},[]),je=a.useCallback(ce=>Pe=>{U(ce),Pe.dataTransfer.setData("text/plain",ce),Pe.dataTransfer.effectAllowed="move"},[]),ie=a.useCallback(()=>{U(null),M(null),D(null)},[]),Ae=a.useCallback(ce=>Pe=>{if(Pe.preventDefault(),ce===P)return;const pe=Pe.currentTarget.getBoundingClientRect(),Re=pe.top+pe.height/2,Qe=Pe.clientY<Re?"before":"after";M(ce),D(Qe)},[P]),Le=a.useCallback(ce=>Pe=>{Pe.preventDefault();const pe=Pe.dataTransfer.getData("text/plain");if(!pe||pe===ce){U(null),M(null),D(null);return}m(Re=>{const Qe=Re.findIndex(Se=>Se.id===pe),Ie=Re.findIndex(Se=>Se.id===ce);if(Qe===-1||Ie===-1)return Re;const bt=[...Re],[ee]=bt.splice(Qe,1);let re=Ie;return T==="after"&&Qe<Ie&&re--,T==="after"&&re++,bt.splice(re,0,ee),bt}),_(!0),U(null),M(null),D(null)},[T]),we=a.useCallback(ce=>{const Pe=ce.currentTarget.getBoundingClientRect(),pe=ce.clientX,Re=ce.clientY;(pe<Pe.left||pe>Pe.right||Re<Pe.top||Re>Pe.bottom)&&(M(null),D(null))},[]),Ee=a.useCallback((ce,Pe)=>{Pe<0||Pe>=d.length||(m(pe=>{const Re=[...pe],[Qe]=Re.splice(ce,1);return Re.splice(Pe,0,Qe),Re}),_(!0))},[d.length]),Ve=a.useCallback(ce=>{J.current[ce+1]?.focus()},[]),rt=a.useCallback(async()=>{if(!(!z||X)){S(null),u({type:"creating",sessionId:z});try{const ce=await Cj(z,d,r,o);i(ce.tasks),Te(),n()}catch(ce){S(ke(ce)||"Failed to create tasks"),u({type:"editing",sessionId:z})}}},[X,n,i,r,o,Te,z,d]),xe=a.useCallback(async()=>{if(c.type!=="error")return;const ce=c.sessionId;S(null),E(!0),g(""),u({type:"generating",sessionId:ce}),qe(ce);try{await kj(ce,o,I)}catch(Pe){let pe=Pe;if((ke(Pe)||"").includes("not in an error state"))try{const Qe=await ai(ce);if(!Qe)throw new Error("Failed to refresh subtask session.");if(f(ka(Qe.conversationHistory)),Qe.status==="generating"||Qe.status==="awaiting_input")g(Qe.thinkingOutput??""),u({type:"generating",sessionId:Qe.id}),K.current?.isConnected()||qe(Qe.id);else if(Qe.status==="complete"){if(!Qe.result)throw new Error("Subtask session is complete but has no result.");Ol(o);const Ie=JSON.parse(Qe.result);m(Ie),u({type:"editing",sessionId:Qe.id}),_(!1)}else Qe.status==="error"&&u({type:"error",sessionId:Qe.id,errorMessage:Qe.error??"Retry failed. Please try again."});y(!1);return}catch(Qe){pe=Qe}K.current?.close(),K.current=null,u({type:"error",sessionId:ce,errorMessage:ke(pe)||"Retry failed. Please try again."}),y(!1)}finally{E(!1)}},[qe,o,I,c]);return e?t.jsx("div",{className:"modal-overlay open",onClick:ce=>ce.target===ce.currentTarget&&void nt(),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(sl,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Subtask Breakdown"})]}),t.jsxs("div",{className:"modal-header-actions",children:[he&&t.jsx("button",{className:"modal-send-to-background",onClick:st,title:"Send to background","aria-label":"Send to background",children:t.jsx(Or,{size:16})}),t.jsx("button",{className:"modal-close",onClick:()=>void nt(),"aria-label":"Close",children:t.jsx(qt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[R&&t.jsx("div",{className:"form-error planning-error",children:R}),x&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),_e&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),c.type==="initial"&&t.jsx("div",{className:"planning-initial",children:t.jsxs("div",{className:"planning-view-scroll",children:[t.jsx("p",{className:"text-muted",children:"Preparing to break this task into subtasks."}),t.jsx("pre",{className:"planning-thinking-output",children:C})]})}),c.type==="generating"&&t.jsxs("div",{className:"planning-loading",children:[h.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ls,{entries:h,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsx(lt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:"AI is generating subtasks..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>v(!b),type:"button",children:b?"Hide thinking":"Show thinking"}),b&&p&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:p})})]})]}),c.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[h.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ls,{entries:h,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:c.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void xe(),disabled:j,children:[j?t.jsx(lt,{size:14,className:"spin"}):t.jsx(Fn,{size:14}),t.jsx("span",{className:"icon-ml-6",children:j?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:()=>void nt(),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(Ls,{entries:h}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Nn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Review your subtasks"}),t.jsx("p",{className:"text-muted",children:"Edit titles, descriptions, sizes, and dependencies before creating all tasks at once."})]}),t.jsxs("div",{className:"planning-summary-form",children:[d.map((ce,Pe)=>{const pe=P===ce.id,Re=G===ce.id,Qe=["task-detail-section","subtask-item",pe?"subtask-item-dragging":"",Re?"subtask-item-drop-target":"",Re&&T==="before"?"subtask-item-drop-before":"",Re&&T==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:Qe,"data-testid":`subtask-item-${Pe}`,draggable:c.type!=="creating",onDragStart:je(ce.id),onDragEnd:ie,onDragOver:Ae(ce.id),onDrop:Le(ce.id),onDragLeave:we,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(xd,{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:()=>Ee(Pe,Pe-1),disabled:c.type==="creating"||Pe===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(Fi,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Ee(Pe,Pe+1),disabled:c.type==="creating"||Pe===d.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx($r,{})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>oe(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:Ie=>{J.current[Pe]=Ie},value:ce.title,onChange:Ie=>$e(ce.id,{title:Ie.target.value}),onKeyDown:Ie=>{Ie.key==="Enter"&&(Ie.preventDefault(),Ve(Pe))},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:Ie=>$e(ce.id,{description:Ie.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:Ie=>$e(ce.id,{suggestedSize:Ie.target.value}),disabled:c.type==="creating",children:[t.jsx("option",{value:"S",children:"S"}),t.jsx("option",{value:"M",children:"M"}),t.jsx("option",{value:"L",children:"L"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"planning-deps-list",children:[d.slice(0,Pe).filter(Ie=>Ie.id!==ce.id).map(Ie=>{const bt=ce.dependsOn.includes(Ie.id);return t.jsxs("label",{className:`planning-dep-chip ${bt?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:bt,onChange:()=>{const ee=bt?ce.dependsOn.filter(re=>re!==Ie.id):[...ce.dependsOn,Ie.id];$e(ce.id,{dependsOn:ee})},disabled:c.type==="creating"}),t.jsx("span",{className:"planning-dep-id",children:Ie.id}),t.jsx("span",{className:"planning-dep-title",children:Ie.title||"Untitled"})]},Ie.id)}),Pe===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),Pe>0&&d.slice(0,Pe).filter(Ie=>Ie.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:Ue,disabled:c.type==="creating",children:[t.jsx(dn,{size:16,className:"icon-mr-6"})," Add subtask"]}),Sh(d)&&t.jsx("div",{className:"form-error planning-error",children:"Dependencies contain a cycle. Remove circular references before creating tasks."})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsx("button",{className:"btn",onClick:()=>void nt(),disabled:c.type==="creating",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:()=>void rt(),disabled:c.type==="creating"||X,children:c.type==="creating"?t.jsxs(t.Fragment,{children:[t.jsx(lt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]}),k&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(il,{size:16}),t.jsx("span",{children:Fe?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),Fe&&t.jsx("button",{type:"button",onClick:()=>{H()},disabled:Q,className:"btn btn-primary session-lock-take-control",children:Q?"Taking control...":"Take Control"})]})})]})]})}):null}const WR=5,KR=1e3,GR=45e3;function ko(){return{scrollback:null,connected:null,data:[]}}function JR(e,n){const[s,i]=a.useState("disconnected"),r=a.useRef(0),o=a.useRef(e),l=a.useRef(n),c=o.current!==e||l.current!==n;c&&(o.current=e,l.current=n,r.current++);const u=a.useRef(null),d=a.useRef(0),m=a.useRef(null),h=a.useRef(null),f=a.useRef(!1),p=a.useRef(new Set),g=a.useRef(new Set),b=a.useRef(new Set),v=a.useRef(new Set),x=a.useRef(new Set),y=a.useRef(ko()),j=a.useCallback(M=>{p.current.add(M);const T=y.current;return T.data.length>0&&(T.data.forEach(D=>M(D)),T.data=[]),()=>p.current.delete(M)},[]),E=a.useCallback(M=>(g.current.add(M),()=>g.current.delete(M)),[]),C=a.useCallback(M=>{b.current.add(M);const T=y.current;return T.connected&&(M(T.connected),T.connected=null),()=>b.current.delete(M)},[]),w=a.useCallback(M=>{v.current.add(M);const T=y.current;return T.scrollback&&(M(T.scrollback),T.scrollback=null),()=>v.current.delete(M)},[]),R=a.useCallback(M=>(x.current.add(M),()=>x.current.delete(M)),[]),S=a.useCallback(M=>{const T=u.current;T?.readyState===WebSocket.OPEN&&T.send(JSON.stringify({type:"input",data:M}))},[]),O=a.useCallback((M,T)=>{const D=u.current;D?.readyState===WebSocket.OPEN&&D.send(JSON.stringify({type:"resize",cols:M,rows:T}))},[]),_=a.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.current=null),u.current&&(u.current.onopen=null,u.current.onmessage=null,u.current.onclose=null,u.current.onerror=null,u.current.close(),u.current=null),y.current=ko()},[]),P=a.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.current=null),u.current&&(f.current=!0,u.current.close(),u.current=null),y.current=ko()},[]),U=a.useCallback(()=>{if(!e){i("disconnected");return}if(u.current?.readyState===WebSocket.OPEN)return;u.current&&(f.current=!0,u.current.close()),f.current=!1,i("connecting");const M=r.current;let D=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/terminal/ws?sessionId=${encodeURIComponent(e)}`;n&&(D+=`&projectId=${encodeURIComponent(n)}`);const K=new WebSocket(oi(D));u.current=K,K.onopen=()=>{if(r.current!==M){K.close();return}y.current=ko(),i("connected"),d.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{r.current===M&&K.readyState===WebSocket.OPEN&&K.send(JSON.stringify({type:"ping"}))},GR)},K.onmessage=J=>{if(r.current===M)try{const te=JSON.parse(J.data),N=y.current;switch(te.type){case"data":te.data&&(p.current.size===0&&N.data.push(te.data),p.current.forEach(z=>z(te.data)));break;case"scrollback":te.data&&(N.scrollback=te.data,v.current.forEach(z=>z(te.data)));break;case"connected":te.shell&&te.cwd&&(N.connected={shell:te.shell,cwd:te.cwd},b.current.forEach(z=>z({shell:te.shell,cwd:te.cwd})));break;case"exit":te.exitCode!==void 0&&g.current.forEach(z=>z(te.exitCode));break;case"ping":K.readyState===WebSocket.OPEN&&K.send(JSON.stringify({type:"pong"}));break;case"pong":break}}catch{}},K.onclose=J=>{if(r.current!==M)return;if(u.current=null,h.current&&(clearInterval(h.current),h.current=null),f.current){i("disconnected");return}if(J.code===4e3||J.code===4004){i("disconnected"),J.code===4004&&x.current.forEach(z=>z());return}if(d.current++,d.current>WR){i("disconnected");return}const te=KR*Math.pow(2,d.current-1);i("reconnecting");const N=r.current;m.current=setTimeout(()=>{r.current===N&&(f.current||U())},Math.min(te,16e3))},K.onerror=()=>{}},[e,n]),G=a.useCallback(()=>{d.current=0,P(),U()},[P,U]);return a.useEffect(()=>(c&&(_(),d.current=0,i("disconnected")),e?U():i("disconnected"),P),[e,n,c,U,P,_]),{connectionStatus:s,sendInput:S,resize:O,onData:j,onExit:E,onConnect:C,onScrollback:w,reconnect:G,onSessionInvalid:R}}const Rg="kb-terminal-tabs",YR=15e3,QR=15e3;function Ch(){return`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function Eh(e){if(typeof window>"u")return[];try{const n=Yn(Rg,e);if(n)return JSON.parse(n)}catch{}return[]}function xc(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return n.includes("Failed to parse URL")||n.includes("Invalid URL")}function _h(e,n,s){let i;const r=new Promise((o,l)=>{i=setTimeout(()=>l(new Error(`${s} timed out after ${n}ms`)),n)});return Promise.race([e,r]).finally(()=>clearTimeout(i))}function XR(e){const[n,s]=a.useState(()=>Eh(e)),[i,r]=a.useState(!1),[o,l]=a.useState(!0),[c,u]=a.useState(null),[d,m]=a.useState(0),h=a.useRef(0);a.useEffect(()=>{h.current+=1,s(Eh(e)),r(!1),l(!0),u(null)},[e]),a.useEffect(()=>{try{fs(Rg,JSON.stringify(n),e)}catch{}},[e,n]),a.useEffect(()=>{let C=!1;const w=h.current;return(async()=>{if(!C)try{const S=await _h(xw(e),YR,"listTerminalSessions");if(C||w!==h.current)return;const O=new Set(S.map(_=>_.id));l(!0),s(_=>{if(C||w!==h.current)return _;const U=_.map(T=>({...T,_verified:O.has(T.sessionId)})).filter(T=>T._verified);if(U.length===0)return[];const G=U.map(({_verified:T,...D})=>D);return G.find(T=>T.isActive)?G:G.map((T,D)=>({...T,isActive:D===0}))}),r(!0)}catch(S){if(C||w!==h.current)return;const O=xc(S);O||console.warn("Failed to validate terminal sessions with server:",S),l(!O),r(!0)}})(),()=>{C=!0}},[e]),a.useEffect(()=>{if(n.length===0&&i&&o){const C=h.current,w=setTimeout(()=>{_h(io(void 0,void 0,void 0,e),QR,"createTerminalSession").then(R=>{if(C!==h.current)return;const S={id:Ch(),sessionId:R.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};s(O=>O.length>0?O:[...O.map(P=>({...P,isActive:!1})),S]),u(null)}).catch(R=>{if(C!==h.current)return;xc(R)||console.error(R);const S=R instanceof Error?R.message:typeof R=="string"?R:"Failed to create terminal session";u(S)})},0);return()=>clearTimeout(w)}},[i,o,n.length,d]);const f=a.useCallback(async()=>{const C=await io(void 0,void 0,void 0,e),w={id:Ch(),sessionId:C.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};return s(R=>[...R.map(O=>({...O,isActive:!1})),w]),w},[n.length]),p=a.useCallback(async()=>f(),[f]),g=a.useCallback(C=>{s(w=>{const R=w.find(P=>P.id===C);if(!R)return w;lu(R.sessionId,e).catch(P=>{console.warn(`Failed to kill terminal session ${R.sessionId}:`,P)});const S=w.findIndex(P=>P.id===C),O=R.isActive,_=w.filter(P=>P.id!==C);if(_.length===0)return[];if(O){const P=Math.min(S,_.length-1);return _.map((U,G)=>({...U,isActive:G===P}))}return _})},[]),b=a.useCallback(C=>{s(w=>{let R=!1;const S=w.map(O=>O.id===C?(R=!0,{...O,isActive:!0}):{...O,isActive:!1});return R?S:w})},[]),v=a.useCallback((C,w)=>{s(R=>R.map(S=>S.id===C?{...S,title:w}:S))},[]),x=a.useCallback(async()=>{s(R=>{const S=R.find(O=>O.isActive);return S&&lu(S.sessionId,e).catch(O=>{console.warn(`Failed to kill old session ${S.sessionId}:`,O)}),R});const C=n.find(R=>R.isActive);if(!C)return;const w=await io(void 0,void 0,void 0,e);s(R=>R.map(S=>S.id===C.id?{...S,sessionId:w.sessionId}:S))},[n]),y=a.useCallback(async()=>{const C=n.find(w=>w.isActive);if(C)try{const w=await io(void 0,void 0,void 0,e);s(R=>R.map(S=>S.id===C.id?{...S,sessionId:w.sessionId}:S)),u(null)}catch(w){xc(w)||console.error(w);const R=w instanceof Error?w.message:typeof w=="string"?w:"Failed to create terminal session";u(R)}},[n]),j=n.find(C=>C.isActive)??null,E=a.useCallback(()=>{u(null),h.current+=1,m(C=>C+1)},[]);return{tabs:n,activeTab:j,isReady:i,bootstrapError:c,createTab:p,closeTab:g,setActiveTab:b,updateTabTitle:v,restartActiveTab:x,retryBootstrap:E,replaceActiveTabSession:y}}const ZR=1e4,eT=[500,1500,3e3],Tg="kb-terminal-font-size",pr=14,tT=8,nT=32,sT='"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 iT(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 aT(e){return`\x1B${e}`}const rT=[{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 fr(e){return Math.min(nT,Math.max(tT,e))}function oT(){if(typeof window>"u")return pr;try{const e=window.localStorage.getItem(Tg);if(!e)return pr;const n=Number.parseInt(e,10);return Number.isFinite(n)?fr(n):pr}catch{return pr}}function lT(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 cT(e){return new Promise(n=>setTimeout(n,e))}async function dT(e,n=eT){let s;for(let i=0;i<=n.length;i+=1)try{return await e()}catch(r){if(!lT(r))throw r;s===void 0&&(s=r);const o=n[i];if(o===void 0)throw s??r;const l=r instanceof Error?r.message:String(r);console.warn(`[TerminalModal] Dynamic xterm import failed (attempt ${i+1}/${n.length+1}). Retrying in ${o}ms...`,l),await cT(o)}throw s??new Error("Dynamic import failed")}function Mh(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}function uT(){if(typeof window>"u"||!window.visualViewport)return 0;const e=window.visualViewport,n=Math.max(0,window.innerHeight-e.offsetTop-e.height);if(n>0)return n;const i=mT()-e.offsetTop-e.height;return i>=30&&i>80?i:0}let vc=null;function mT(){return vc===null&&(vc=window.innerHeight),vc}function hT({isOpen:e,onClose:n,initialCommand:s,projectId:i}){const[r,o]=a.useState(null),[l,c]=a.useState(null),[u,d]=a.useState(!1),[m,h]=a.useState(null),[f,p]=a.useState(0),[g,b]=a.useState(0),[v,x]=a.useState(null),[y,j]=a.useState(()=>oT()),[E,C]=a.useState(!1),[w,R]=a.useState(null),S=a.useRef(null),O=a.useRef(null),_=a.useRef(!1);di(O,e,"fusion:terminal-modal-size");const P=a.useRef(null),U=a.useRef(null),G=a.useRef(!1),M=a.useRef(!1),T=a.useRef(null),D=a.useRef(()=>{}),K=a.useRef(null),J=a.useRef(0),te=a.useRef(y),N=a.useRef(null),z=a.useRef(i);J.current=g,te.current=y;const I=a.useCallback(pe=>{if(pe&&M.current!==pe)return;const Re=U.current,Qe=P.current,Ie=T.current;if(!(!Re||!Qe)&&!(pe&&M.current!==pe))try{Re.fit(),Ie&&Ie(Qe.cols,Qe.rows)}catch{}},[]);a.useEffect(()=>{e&&p(pe=>pe+1)},[e]),a.useEffect(()=>{if(!e||!Mh())return;const pe=window.visualViewport;if(!pe)return;const Re=()=>{const Qe=uT();b(Qe),x(pe.height),Qe>0&&O.current?.scrollIntoView&&O.current.scrollIntoView({block:"end",behavior:"smooth"}),N.current!==null&&(cancelAnimationFrame(N.current),N.current=null);const Ie=typeof M.current=="string"?M.current:void 0;N.current=requestAnimationFrame(()=>{N.current=null,I(Ie)})};return Re(),pe.addEventListener("resize",Re),pe.addEventListener("scroll",Re),()=>{pe.removeEventListener("resize",Re),pe.removeEventListener("scroll",Re),N.current!==null&&(cancelAnimationFrame(N.current),N.current=null),b(0),x(null)}},[I,e]),a.useEffect(()=>{if(!e)return;const pe=O.current;if(!pe||typeof ResizeObserver>"u")return;let Re=null;const Qe=new ResizeObserver(()=>{Re!==null&&cancelAnimationFrame(Re),Re=requestAnimationFrame(()=>{Re=null;const Ie=typeof M.current=="string"?M.current:void 0;I(Ie)})});return Qe.observe(pe),()=>{Qe.disconnect(),Re!==null&&cancelAnimationFrame(Re)}},[I,e]);const{tabs:k,activeTab:H,isReady:Q,bootstrapError:ue,createTab:be,closeTab:V,setActiveTab:ve,updateTabTitle:B,restartActiveTab:Y,retryBootstrap:X,replaceActiveTabSession:he}=XR(i),{connectionStatus:de,sendInput:me,resize:se,onData:_e,onConnect:Fe,onExit:Te,onScrollback:st,reconnect:nt,onSessionInvalid:qe}=JR(H?.sessionId??null,i);T.current=se,D.current=me,a.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Tg,String(y))}catch{}},[y]);const Xe=a.useCallback(()=>{const pe=P.current;if(pe)try{U.current?.fit(),se(pe.cols,pe.rows)}catch{}},[se]);a.useEffect(()=>{if(!e||!Q)return;const pe=H?.sessionId;if(!pe)return;const Re=z.current!==i;if(Re&&(z.current=i),M.current===pe&&P.current&&!Re)return;P.current&&(M.current!==pe||Re)&&(P.current.dispose(),P.current=null,U.current=null,M.current=!1,K.current&&(window.removeEventListener("resize",K.current),K.current=null),d(!1),h(null));let Qe=!0,Ie;return(async()=>{const ee=dT(()=>Promise.all([hn(()=>import("./vendor-xterm-DzcZoU0P.js").then(ne=>ne.x),__vite__mapDeps([6,1,7])),hn(()=>import("./addon-fit-C7jRorKK.js").then(ne=>ne.a),__vite__mapDeps([9,1])),hn(()=>import("./addon-web-links-CkJwd4cQ.js").then(ne=>ne.a),__vite__mapDeps([10,1]))])),re=new Promise((ne,Ze)=>{Ie=setTimeout(()=>{Ze(new Error("xterm initialization timed out"))},ZR)});let Se,ot;try{const[{Terminal:ne},{FitAddon:Ze},{WebLinksAddon:ft}]=await Promise.race([ee,re]);if(!Qe||!S.current||P.current)return;Se=new ne({cursorBlink:!0,cursorStyle:"block",fontSize:te.current,fontFamily:sT,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}),ot=new Ze,Se.loadAddon(ot);const gt=new ft;if(Se.loadAddon(gt),!Mh())try{const{WebglAddon:pt}=await hn(async()=>{const{WebglAddon:Ht}=await import("./addon-webgl-BjvOw43o.js").then($t=>$t.a);return{WebglAddon:Ht}},__vite__mapDeps([11,1])),kt=new pt;kt.onContextLoss(()=>{kt.dispose()}),Se.loadAddon(kt)}catch{}Se.open(S.current),Ie&&clearTimeout(Ie);const St=S.current?.querySelector(".xterm-helper-textarea");if(St&&St.focus(),S.current)try{S.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}setTimeout(()=>{ot.fit();const pt=S.current?.querySelector(".xterm-helper-textarea");pt&&pt.focus()},50),P.current=Se,U.current=ot,M.current=pe,J.current>0&&(N.current!==null&&(cancelAnimationFrame(N.current),N.current=null),N.current=requestAnimationFrame(()=>{N.current=null,I(pe)})),Se.onData(pt=>{M.current===pe&&D.current(pt)});const Nt=()=>{if(M.current===pe&&U.current&&P.current)try{U.current.fit();const{cols:pt,rows:kt}=P.current;T.current?.(pt,kt)}catch{}};window.addEventListener("resize",Nt),K.current&&window.removeEventListener("resize",K.current),K.current=Nt,d(!0),h(null)}catch(ne){if(Ie&&clearTimeout(Ie),!Qe)return;const Ze=ne instanceof Error?ne.message:"xterm initialization failed";h(Ze)}})(),()=>{Qe=!1,Ie&&clearTimeout(Ie)}},[I,e,Q,H?.sessionId,i]),a.useEffect(()=>{e||(P.current&&(P.current.dispose(),P.current=null),U.current=null,M.current=!1,K.current&&(window.removeEventListener("resize",K.current),K.current=null),d(!1),h(null),G.current=!1,o(null),c(null),C(!1),R(null))},[e]),a.useEffect(()=>{if(!u||!P.current||!H)return;const pe=H.sessionId,Re=re=>{M.current===pe&&P.current?.write(re)},Qe=_e(re=>{Re(re)}),Ie=st(re=>{Re(re)}),bt=Fe(re=>{B(H.id,Sd(re.shell)||re.shell)}),ee=Te(re=>{M.current===pe&&(c(re),P.current?.write(`\r
|
|
659
|
-
\x1B[33m[Process exited with code ${re}]\x1B[0m\r
|
|
660
|
-
`))});return()=>{Qe(),Ie(),bt(),ee()}},[u,H?.sessionId,H?.id,H,de,_e,st,Fe,Te,B]),a.useEffect(()=>{de==="connected"&&s&&G.current!==s&&H&&(G.current=s,setTimeout(()=>{me(s+`
|
|
661
|
-
`)},500))},[de,s,me,H,f]),a.useEffect(()=>{if(!u||!P.current)return;P.current.options.fontSize=y,N.current!==null&&(cancelAnimationFrame(N.current),N.current=null);const pe=requestAnimationFrame(()=>{N.current=null,Xe()});return N.current=pe,()=>{N.current===pe&&(cancelAnimationFrame(pe),N.current=null)}},[y,u,Xe]),a.useEffect(()=>{if(!e)return;const pe=Re=>{if(!(!Re.ctrlKey&&!Re.metaKey)){if(Re.code==="Equal"||Re.code==="NumpadAdd"){Re.preventDefault(),j(Qe=>fr(Qe+1));return}if(Re.code==="Minus"||Re.code==="NumpadSubtract"){Re.preventDefault(),j(Qe=>fr(Qe-1));return}if(Re.code==="Digit0"||Re.code==="Numpad0"){Re.preventDefault(),j(pr);return}}};return window.addEventListener("keydown",pe),()=>window.removeEventListener("keydown",pe)},[e,Xe]),a.useEffect(()=>{if(!e)return;const pe=Re=>{Re.key==="Escape"&&n()};return document.addEventListener("keydown",pe),()=>document.removeEventListener("keydown",pe)},[e,n]),a.useEffect(()=>{de==="connected"&&P.current&&setTimeout(()=>{if(!P.current||!S.current)return;const pe=S.current.querySelector(".xterm-helper-textarea");pe&&pe.focus();try{S.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[de]);const $e=a.useCallback(()=>{if(!S.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;P.current?.focus();const Re=S.current.querySelector(".xterm-helper-textarea");if(!Re)return;Re.autocapitalize="off",Re.autocomplete="off",Re.autocorrect="off",Re.spellcheck=!1,Re.setAttribute("inputmode","text");try{Re.focus({preventScroll:!0})}catch{Re.focus()}const Qe=Re.value.length;Re.setSelectionRange(Qe,Qe)},[]);a.useEffect(()=>qe(()=>{P.current?.clear(),c(null),G.current=!1,P.current&&(P.current.dispose(),P.current=null),U.current=null,M.current=!1,K.current&&(window.removeEventListener("resize",K.current),K.current=null),d(!1),h(null),he().catch(Re=>{console.error("Failed to replace invalid terminal session:",Re)})}),[qe,he]);const Ue=a.useCallback(pe=>{pe.target===pe.currentTarget&&(_.current=!0)},[]),oe=a.useCallback(pe=>{_.current&&pe.target===pe.currentTarget&&n(),_.current=!1},[n]),je=a.useCallback(()=>{P.current?.clear()},[]),ie=a.useCallback(async()=>{P.current?.clear(),c(null),G.current=!1;try{await Y()}catch(pe){o(ke(pe)||"Failed to restart terminal session")}},[Y]),Ae=a.useCallback(()=>{P.current&&(P.current.dispose(),P.current=null),U.current=null,M.current=!1,K.current&&(window.removeEventListener("resize",K.current),K.current=null),h(null),d(!1)},[]),Le=a.useCallback(()=>{window.location.reload()},[]),we=a.useCallback(()=>{j(pe=>fr(pe+1))},[]),Ee=a.useCallback(()=>{j(pe=>fr(pe-1))},[]),Ve=a.useCallback(pe=>{R(Re=>Re===pe?null:pe)},[]),rt=a.useCallback(pe=>{if(w==="ctrl"){me(iT(pe)),R(null);return}if(w==="alt"){me(aT(pe)),R(null);return}me(pe)},[me,w]),xe=a.useCallback(pe=>{me(pe),R(null)},[me]);if(!e)return null;const ce=()=>{switch(de){case"connected":return t.jsx("span",{className:"terminal-status connected",title:"Connected"});case"connecting":case"reconnecting":return t.jsx("span",{className:"terminal-status connecting",title:"Connecting..."});case"disconnected":return t.jsx("span",{className:"terminal-status disconnected",title:"Disconnected"});default:return null}},Pe=!Q||!H&&!ue;return t.jsx("div",{className:"modal-overlay open",onMouseDown:Ue,onMouseUp:oe,role:"dialog","aria-modal":"true","data-testid":"terminal-modal-overlay",style:g>0?{"--overlay-padding-top":"0px"}:void 0,children:t.jsxs("div",{ref:O,className:"modal terminal-modal","data-testid":"terminal-modal",style:g>0?{"--keyboard-overlap":`${g}px`,"--vv-height":v?`${v}px`:void 0}:void 0,children:[t.jsxs("div",{className:"terminal-header",children:[t.jsxs("div",{className:"terminal-tabs","data-testid":"terminal-tabs",children:[k.map(pe=>t.jsxs("div",{className:`terminal-tab ${pe.isActive?"terminal-tab--active":""}`,onClick:()=>ve(pe.id),title:pe.title,role:"tab","aria-selected":pe.isActive,children:[t.jsx("span",{className:"terminal-tab-label",children:pe.title}),k.length>1&&t.jsx("button",{className:"terminal-tab-close",onClick:Re=>{Re.stopPropagation(),V(pe.id)},title:"Close tab",children:"×"})]},pe.id)),t.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:be,title:"New terminal",children:"+"})]}),t.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[t.jsx(gi,{size:16}),ce()]}),t.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[de==="disconnected"&&H&&t.jsxs("button",{className:"terminal-reconnect-btn",onClick:nt,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[t.jsx(Fn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),l!==null&&t.jsxs("button",{className:"terminal-restart-btn",onClick:ie,title:"New Session","data-testid":"terminal-restart-btn",children:[t.jsx(Fn,{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:()=>C(pe=>!pe),"data-testid":"terminal-shortcut-toggle",title:"Shortcuts","aria-pressed":E,children:[t.jsx(Fx,{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(qt,{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:[Pe&&!ue&&t.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[t.jsx("div",{className:"terminal-spinner"}),t.jsx("span",{children:"Starting terminal..."})]}),ue&&!H&&t.jsx("div",{className:"terminal-loading","data-testid":"terminal-bootstrap-error",children:t.jsxs("div",{className:"terminal-error-content",children:[t.jsxs("span",{children:["Failed to start terminal: ",ue]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:X,"data-testid":"terminal-retry-btn",children:[t.jsx(Fn,{size:14}),"Retry"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Le,"data-testid":"terminal-bootstrap-refresh-btn",children:[t.jsx(Fn,{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:Ae,"data-testid":"terminal-reinit-btn",children:[t.jsx(Fn,{size:14}),"Reinitialize"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Le,"data-testid":"terminal-xterm-refresh-btn",children:[t.jsx(Fn,{size:14}),"Refresh page"]})]})]})}),t.jsx("div",{ref:S,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:$e,onTouchStart:$e},H?.sessionId)]}),E&&t.jsxs("div",{className:"terminal-shortcut-panel","data-testid":"terminal-shortcut-panel",children:[t.jsxs("div",{className:"terminal-shortcut-modifier-row",children:[t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${w==="ctrl"?"is-active":""}`,"data-testid":"terminal-modifier-ctrl",onClick:()=>Ve("ctrl"),"aria-pressed":w==="ctrl",children:"Ctrl"}),t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${w==="alt"?"is-active":""}`,"data-testid":"terminal-modifier-alt",onClick:()=>Ve("alt"),"aria-pressed":w==="alt",children:"Alt"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>xe("\x1B"),children:"ESC"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>xe(" "),children:"Tab"})]}),rT.map(pe=>t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>rt(pe.key),title:pe.description,children:pe.label},pe.label))]}),t.jsxs("div",{className:"terminal-status-bar","data-testid":"terminal-status-bar",children:[t.jsxs("span",{className:`terminal-connection-status ${de}`,children:[de==="connected"&&"Connected",de==="connecting"&&"Connecting...",de==="reconnecting"&&"Reconnecting...",de==="disconnected"&&"Disconnected"]}),l!==null&&t.jsxs("span",{className:"terminal-exit-code","data-testid":"terminal-exit-code",children:["Exit: ",l]}),t.jsxs("span",{className:"terminal-font-size-controls",children:[t.jsx("button",{type:"button",className:"terminal-font-size-btn",onClick:Ee,"data-testid":"terminal-font-size-decrease","aria-label":"Decrease terminal font size",children:t.jsx(av,{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:we,"data-testid":"terminal-font-size-increase","aria-label":"Increase terminal font size",children:t.jsx(dn,{size:14})})]}),t.jsx("span",{className:"terminal-shortcuts",children:"Ctrl++/- zoom • ⌨ Shortcuts panel • Esc close"})]})]})})}const sr={name:"",command:""};function Ah(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function pT(e,n=60){return e.length<=n?e:e.slice(0,n-3)+"..."}function fT({isOpen:e,onClose:n,addToast:s,projectId:i,onRunScript:r}){const[o,l]=a.useState({}),[c,u]=a.useState(!0),[d,m]=a.useState(!1),[h,f]=a.useState(null),[p,g]=a.useState(sr),[b,v]=a.useState(!1),[x,y]=a.useState(null),[j,E]=a.useState(null),C=Mi(n),w=a.useCallback(async()=>{try{u(!0);const D=await _r(i);l(D)}catch(D){s(ke(D)||"Failed to load scripts","error")}finally{u(!1)}},[s,i]);a.useEffect(()=>{e&&w()},[e,w]);const R=a.useCallback(()=>{m(!0),f(null),g(sr),E(null)},[]),S=a.useCallback((D,K)=>{f(D),m(!1),g({name:D,command:K}),E(null)},[]),O=a.useCallback(()=>{f(null),m(!1),g(sr),E(null)},[]),_=a.useCallback(D=>{g(K=>({...K,name:D})),D&&!Ah(D)?E("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):E(null)},[]),P=a.useCallback(async()=>{const D=p.name.trim(),K=p.command.trim();if(!D){s("Script name is required","error");return}if(!Ah(D)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!K){s("Script command is required","error");return}v(!0);try{await yj(D,K,i),s(h?"Script updated":"Script created","success"),f(null),m(!1),g(sr),E(null),await w()}catch(J){const te=ke(J);te?.includes("already exists")?s("A script with this name already exists","error"):s(te||"Failed to save script","error")}finally{v(!1)}},[p,h,s,w,i]),U=a.useCallback(async D=>{try{await wj(D,i),s("Script deleted","success"),y(null),h===D&&(f(null),g(sr)),await w()}catch(K){s(ke(K)||"Failed to delete script","error")}},[h,s,w,i]),G=a.useCallback((D,K)=>{r&&r(D,K)},[r]);if(!e)return null;const M=d||h!==null,T=Object.entries(o).map(([D,K])=>({name:D,command:K}));return t.jsx("div",{className:"modal-overlay open",...C,"data-testid":"scripts-modal",children:t.jsxs("div",{className:"modal scripts-modal",role:"dialog","aria-modal":"true","aria-label":"Scripts",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{children:[t.jsx(gi,{size:18,style:{marginRight:"8px",verticalAlign:"middle"}}),"Scripts"]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]}),t.jsx("div",{className:"modal-body scripts-modal-body",children:c?t.jsxs("div",{style:{textAlign:"center",padding:"32px",color:"var(--text-muted)"},children:[t.jsx(lt,{size:24,className:"spin",style:{margin:"0 auto 8px",display:"block"}}),"Loading scripts..."]}):M?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:D=>_(D.target.value),placeholder:"e.g., build, test, lint",disabled:b||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:D=>g(K=>({...K,command:D.target.value})),placeholder:"e.g., npm run build",rows:3,disabled:b,"data-testid":"script-command-input",style:{width:"100%",resize:"vertical",fontFamily:"monospace"}})]}),t.jsxs("div",{className:"scripts-modal-form-actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end"},children:[t.jsx("button",{className:"btn btn-secondary",onClick:O,disabled:b,"data-testid":"script-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:P,disabled:b||!!j,"data-testid":"script-save-btn",children:b?t.jsxs(t.Fragment,{children:[t.jsx(lt,{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:T.length===0?"No scripts defined":`${T.length} script${T.length===1?"":"s"}`}),t.jsxs("button",{className:"btn btn-primary",onClick:R,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx(dn,{size:14}),"Add Script"]})]}),T.length===0?t.jsxs("div",{style:{textAlign:"center",padding:"32px",color:"var(--text-muted)",fontSize:"14px",border:"1px dashed var(--border)",borderRadius:"8px"},"data-testid":"empty-state",children:[t.jsx(gi,{size:32,style:{margin:"0 auto 12px",opacity:.5}}),t.jsx("div",{children:"No scripts defined yet."}),t.jsx("div",{style:{marginTop:"4px",fontSize:"12px"},children:"Add scripts to quickly run common commands from the dashboard."})]}):t.jsx("div",{className:"scripts-modal-list",style:{display:"flex",flexDirection:"column",gap:"8px"},children:T.map(D=>t.jsx("div",{className:"script-card","data-testid":`script-${D.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:D.name})}),t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:D.command,children:pT(D.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:()=>G(D.name,D.command),title:"Run script","aria-label":`Run ${D.name}`,"data-testid":`run-script-${D.name}`,style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 10px",fontSize:"12px"},children:[t.jsx(_n,{size:12}),"Run"]}),t.jsx("button",{className:"btn-icon",onClick:()=>S(D.name,D.command),title:"Edit","aria-label":`Edit ${D.name}`,"data-testid":`edit-script-${D.name}`,children:t.jsx(dn,{size:14,style:{transform:"rotate(45deg)"}})}),x===D.name?t.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[t.jsx("button",{className:"btn-icon",onClick:()=>U(D.name),title:"Confirm delete","aria-label":`Confirm delete ${D.name}`,"data-testid":`confirm-delete-script-${D.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-${D.name}`,children:t.jsx(qt,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>y(D.name),title:"Delete","aria-label":`Delete ${D.name}`,"data-testid":`delete-script-${D.name}`,children:t.jsx(cn,{size:14})})]})]})},D.name))})]})})]})})}function gT(e,n,s){const[i,r]=a.useState([]),[o,l]=a.useState("."),[c,u]=a.useState(!1),[d,m]=a.useState(null),[h,f]=a.useState(0),p=a.useCallback(()=>{f(b=>b+1)},[]),g=a.useCallback(b=>{l(b),m(null)},[]);return a.useEffect(()=>{l("."),m(null),r([])},[e]),a.useEffect(()=>{if(!n||!e)return;let b=!1;async function v(){u(!0),m(null);try{const x=await Dw(e,o==="."?void 0:o,s);b||r(x.entries)}catch(x){b||(m(ke(x)||"Failed to load files"),r([]))}finally{b||u(!1)}}return v(),()=>{b=!0}},[e,o,n,h,s]),{entries:i,currentPath:o,setPath:g,loading:c,error:d,refresh:p}}function bT(e,n,s,i){const[r,o]=a.useState(""),[l,c]=a.useState(""),[u,d]=a.useState(null),[m,h]=a.useState(!1),[f,p]=a.useState(!1),[g,b]=a.useState(null),v=a.useCallback(j=>{o(j),b(null)},[]);a.useEffect(()=>{if(!e||!n){o(""),c(""),d(null),b(null);return}let j=!1;async function E(){h(!0),b(null);try{const C=await Lw(e,n,i);j||(o(C.content),c(C.content),d(C.mtime))}catch(C){j||(b(ke(C)||"Failed to load file"),o(""),c(""),d(null))}finally{j||h(!1)}}return E(),()=>{j=!0}},[e,n,s,i]);const x=r!==l,y=a.useCallback(async()=>{if(!(!e||!n||!x)){p(!0),b(null);try{const j=await zw(e,n,r,i);c(r),d(j.mtime)}catch(j){throw b(ke(j)||"Failed to save file"),j}finally{p(!1)}}},[e,n,r,x,i]);return{content:r,setContent:v,originalContent:l,loading:m,saving:f,error:g,save:y,hasChanges:x,mtime:u}}const xT=1e4;function vT(e){const s=e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||e||"Project Root"}function yT(e){return{id:e.id,label:e.id,title:e.title,worktree:e.worktree,kind:"task"}}function wT(e){const[n,s]=a.useState("Project Root"),[i,r]=a.useState([]),[o,l]=a.useState(!0),[c,u]=a.useState(null);return a.useEffect(()=>{let d=!1;async function m(){try{const f=await $w(e);if(d)return;s(vT(f.project)),r(f.tasks.map(yT)),u(null)}catch(f){d||u(ke(f)||"Failed to load workspaces")}finally{d||l(!1)}}m();const h=window.setInterval(()=>{m()},xT);return()=>{d=!0,window.clearInterval(h)}},[e]),{projectName:n,workspaces:i,loading:o,error:c}}function jT(e){return e===void 0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function kT(e){return e?new Date(e).toLocaleDateString():""}function Rh(e,n){return dN(e,n)}const ir={visible:!1,x:0,y:0,entry:null,entryFullPath:""},yc={type:null,entry:null,entryFullPath:""},NT=200,ST=500,Th=10;function CT({x:e,y:n,entry:s,onAction:i,onClose:r}){const o=a.useRef(null),[l,c]=a.useState({x:e,y:n});a.useEffect(()=>{const m=o.current;if(!m)return;const h=m.getBoundingClientRect(),f=window.visualViewport,p=f?.width&&f.width>0?f.width:window.innerWidth,g=f?.height&&f.height>0?f.height:window.innerHeight,b=f?.offsetLeft??0,v=f?.offsetTop??0,x=8;let y=e-b,j=n-v;y+h.width>p-x&&(y=p-x-h.width),j+h.height>g-x&&(j=g-x-h.height),y<x&&(y=x),j<x&&(j=x),c({x:y+b,y:j+v})},[e,n]),a.useEffect(()=>{const m=h=>{h.key==="Escape"&&r()};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[r]);const u=s.type==="directory",d=[{id:"copy",label:"Copy",icon:Bi,disabled:!1},{id:"move",label:"Move",icon:lv,disabled:!1},{id:"rename",label:"Rename",icon:hs,disabled:!1},...u?[{id:"download-zip",label:"Download as ZIP",icon:Ir,disabled:!1}]:[{id:"download",label:"Download",icon:ex,disabled:!1}],{id:"divider",label:"",icon:Bi,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:d.map(m=>m.id==="divider"?t.jsx("div",{className:"file-browser-context-menu__divider",role:"separator"},"divider"):t.jsxs("button",{role:"menuitem",className:`file-browser-context-menu__item ${m.disabled?"file-browser-context-menu__disabled":""} ${m.id==="delete"?"file-browser-context-menu__item--danger":""}`,disabled:m.disabled,onClick:()=>i(m.id),children:[t.jsx(m.icon,{size:14,className:"file-browser-context-menu__item-icon"}),t.jsx("span",{children:m.label})]},m.id))})})}function ET({type:e,entry:n,entryFullPath:s,onConfirm:i,onCancel:r,loading:o,error:l}){const c=a.useRef(null),u=e==="rename"?n.name:"",[d,m]=a.useState(u);a.useEffect(()=>{setTimeout(()=>c.current?.focus(),50)},[]),a.useEffect(()=>{if(e==="rename"&&c.current){const g=n.name.lastIndexOf(".");g>0?c.current.setSelectionRange(0,g):c.current.select()}},[e,n.name]);const h=g=>{g.key==="Enter"&&d.trim()&&i(d.trim()),g.key==="Escape"&&r()};if(e==="delete")return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsxs("div",{className:"file-browser-dialog",onClick:g=>g.stopPropagation(),children:[t.jsxs("div",{className:"file-browser-dialog-title",children:["Delete ",n.type==="directory"?"Folder":"File"]}),t.jsxs("div",{className:"file-browser-dialog-message",children:["Are you sure you want to delete ",t.jsx("strong",{children:n.name}),"?",n.type==="directory"&&" This will delete all contents recursively."]}),l&&t.jsx("div",{className:"file-browser-dialog-error",children:l}),t.jsxs("div",{className:"file-browser-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:r,disabled:o,children:"Cancel"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>i(""),disabled:o,children:o?"Deleting...":"Delete"})]})]})});const p={copy:{title:"Copy",placeholder:"Destination path",confirm:"Copy"},move:{title:"Move",placeholder:"Destination path",confirm:"Move"},rename:{title:"Rename",placeholder:"New name",confirm:"Rename"}}[e];return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsxs("div",{className:"file-browser-dialog",onClick:g=>g.stopPropagation(),children:[t.jsx("div",{className:"file-browser-dialog-title",children:p.title}),t.jsx("div",{className:"file-browser-dialog-info",children:e==="rename"?n.name:s}),t.jsx("input",{ref:c,className:"file-browser-dialog-input",type:"text",value:d,onChange:g=>m(g.target.value),placeholder:p.placeholder,onKeyDown:h,disabled:o}),l&&t.jsx("div",{className:"file-browser-dialog-error",children:l}),t.jsxs("div",{className:"file-browser-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:r,disabled:o,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>i(d.trim()),disabled:o||!d.trim(),children:o?`${p.confirm}ing...`:p.confirm})]})]})})}function _T({entries:e,currentPath:n,onSelectFile:s,onNavigate:i,loading:r,error:o,onRetry:l,workspace:c,onRefresh:u,projectId:d}){const[m,h]=a.useState(ir),[f,p]=a.useState(yc),[g,b]=a.useState(!1),[v,x]=a.useState(null),[y,j]=a.useState(!1),[E,C]=a.useState(null),w=a.useRef(null),R=a.useRef(null),S=a.useRef(null),O=a.useRef(!1),_=a.useCallback(()=>{w.current!==null&&(window.clearTimeout(w.current),w.current=null),R.current!==null&&(window.clearTimeout(R.current),R.current=null)},[]),P=a.useCallback(()=>{_(),S.current=null,j(!1),C(null)},[_]);a.useEffect(()=>()=>{_()},[_]);const U=a.useCallback((z,I,k,H)=>{h({visible:!0,x:z,y:I,entry:k,entryFullPath:H})},[]),G=a.useCallback((z,I,k)=>{if(z.touches.length!==1)return;const H=z.touches[0];H&&(P(),S.current={x:H.clientX,y:H.clientY},R.current=window.setTimeout(()=>{j(!0),C(k)},NT),w.current=window.setTimeout(()=>{const Q=S.current;Q&&(O.current=!0,j(!1),C(null),_(),U(Q.x,Q.y,I,k))},ST))},[P,_,U]),M=a.useCallback(z=>{const I=S.current,k=z.touches[0];!I||!k||(Math.abs(k.clientX-I.x)>Th||Math.abs(k.clientY-I.y)>Th)&&P()},[P]),T=a.useCallback(()=>{P()},[P]);a.useEffect(()=>{if(!m.visible)return;const z=document.querySelector(".file-browser-list"),I=()=>{O.current=!1,P(),h(ir)};return z?.addEventListener("scroll",I),()=>z?.removeEventListener("scroll",I)},[P,m.visible]),a.useEffect(()=>{if(!m.visible)return;const z=I=>{I.key==="Escape"&&(O.current=!1,h(ir))};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[m.visible]);const D=a.useCallback((z,I)=>{z.preventDefault(),z.stopPropagation(),P(),O.current=!1,U(z.clientX,z.clientY,I,Rh(n,I.name))},[P,n,U]),K=a.useCallback(z=>{if(!m.entry)return;O.current=!1;const I=m.entry,k=m.entryFullPath;if(h(ir),z==="download"){if(!c)return;const H=Lp(c,k,d);window.open(oi(H),"_blank");return}if(z==="download-zip"){if(!c)return;const H=qw(c,k,d);window.open(oi(H),"_blank");return}p({type:z,entry:I,entryFullPath:k}),x(null)},[m,c,d]),J=a.useCallback(async z=>{if(!(!f.type||!f.entry||!c)){b(!0),x(null);try{switch(f.type){case"copy":await Fw(c,f.entryFullPath,z,d);break;case"move":await Uw(c,f.entryFullPath,z,d);break;case"rename":await Hw(c,f.entryFullPath,z,d);break;case"delete":await Bw(c,f.entryFullPath,d);break}p(yc),u?.()}catch(I){x(ke(I)||"Operation failed")}finally{b(!1)}}},[f,c,u,d]),te=a.useCallback(()=>{p(yc),x(null)},[]),N=a.useCallback((z,I)=>{if(O.current){O.current=!1;return}m.visible||(z.type==="directory"?i(I):s(I))},[m.visible,i,s]);return r?t.jsxs("div",{className:"file-browser-loading",children:[t.jsx(lt,{className:"spin",size:24}),t.jsx("span",{children:"Loading files..."})]}):o?t.jsxs("div",{className:"file-browser-error",children:[t.jsxs("p",{children:["Error: ",o]}),l&&t.jsx("button",{className:"btn btn-sm",onClick:l,children:"Retry"})]}):t.jsxs("div",{className:"file-browser",children:[t.jsxs("div",{className:"file-browser-header",children:[n!=="."&&t.jsxs("button",{className:"file-browser-up",onClick:()=>{i(uN(n))},children:[t.jsx(gn,{size:16,style:{transform:"rotate(-90deg)"}}),"Up one level"]}),t.jsx("span",{className:"file-browser-path",children:n==="."?"Root":Da(n)})]}),t.jsx("div",{className:"file-browser-list",children:e.length===0?t.jsx("div",{className:"file-browser-empty",children:"(empty directory)"}):e.map(z=>{const I=Rh(n,z.name),k=y&&E===I;return t.jsxs("div",{className:`file-node file-node--${z.type} ${k?"file-node--long-pressing":""}`,onClick:()=>N(z,I),onContextMenu:H=>D(H,z),onTouchStart:H=>G(H,z,I),onTouchMove:M,onTouchEnd:T,onTouchCancel:T,children:[t.jsx("div",{className:"file-node-icon",children:z.type==="directory"?t.jsx(ts,{size:16}):t.jsx(Sp,{size:16})}),t.jsx("div",{className:"file-node-name",children:z.name}),z.type==="file"&&z.size!==void 0&&t.jsx("div",{className:"file-node-size",children:jT(z.size)}),z.mtime&&t.jsx("div",{className:"file-node-time",children:kT(z.mtime)})]},z.name)})}),m.visible&&m.entry&&t.jsx(CT,{x:m.x,y:m.y,entry:m.entry,onAction:K,onClose:()=>{O.current=!1,h(ir)}}),f.type&&f.entry&&t.jsx(ET,{type:f.type,entry:f.entry,entryFullPath:f.entryFullPath,onConfirm:J,onCancel:te,loading:g,error:v})]})}function MT(e){if(!e)return!1;const n=e.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function AT({content:e,onChange:n,readOnly:s,filePath:i}){const[r,o]=a.useState(!1),[l,c]=a.useState(!0),u=MT(i),d=u&&(s?!0:r),m=a.useCallback(()=>{o(!1)},[]),h=a.useCallback(()=>{o(!0)},[]),f=a.useCallback(()=>{c(p=>!p)},[]);return t.jsxs("div",{className:"file-editor-container",children:[u?t.jsxs("div",{className:"file-editor-toolbar",children:[t.jsxs("div",{className:"file-editor-mode-toggle",children:[!s&&t.jsxs("button",{className:`btn btn-sm ${d?"":"btn-primary"}`,onClick:m,disabled:!d,"aria-label":"Edit mode",children:[t.jsx(Np,{size:14}),"Edit"]}),t.jsxs("button",{className:`btn btn-sm ${d?"btn-primary":""}`,onClick:h,disabled:d,"aria-label":"Preview mode",children:[t.jsx(Ta,{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(Oo,{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(Oo,{size:14})})]}),d?t.jsx("div",{className:"file-editor-preview markdown-body",children:t.jsx(li,{remarkPlugins:[ci],children:e})}):t.jsx("textarea",{className:`file-editor-textarea ${l?"file-editor-textarea--wrap":""}`,value:e,onChange:p=>n(p.target.value),readOnly:s,spellCheck:!1,"aria-label":i?`Editor for ${i}`:"File editor"})]})}function RT(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function TT({currentWorkspace:e,projectName:n,workspaces:s,onSelect:i}){const[r,o]=a.useState(!1),l=a.useMemo(()=>e==="project"?n||"Project Root":s.find(u=>u.id===e)?.label??e,[e,n,s]);return t.jsxs("div",{className:"workspace-selector",children:[t.jsxs("button",{type:"button",className:"workspace-selector-trigger",onClick:()=>o(c=>!c),"aria-haspopup":"listbox","aria-expanded":r,children:[e==="project"?t.jsx(Xd,{size:14}):t.jsx(Dc,{size:14}),t.jsx("span",{className:"workspace-selector-trigger-label",children:l}),t.jsx(Yt,{size:14,className:`workspace-selector-trigger-icon${r?" open":""}`})]}),r&&t.jsxs("div",{className:"workspace-selector-menu",role:"listbox","aria-label":"Select workspace",children:[t.jsxs("button",{type:"button",className:`workspace-selector-option${e==="project"?" active":""}`,onClick:()=>{i("project"),o(!1)},children:[t.jsxs("div",{className:"workspace-selector-option-main",children:[t.jsx(Xd,{size:14}),t.jsx("span",{children:"Project Root"})]}),t.jsx("span",{className:"workspace-selector-option-meta",children:n})]}),s.length>0&&t.jsxs("div",{className:"workspace-selector-group",children:[t.jsx("div",{className:"workspace-selector-group-label",children:"Task Worktrees"}),s.map(c=>t.jsxs("button",{type:"button",className:`workspace-selector-option${e===c.id?" active":""}`,onClick:()=>{i(c.id),o(!1)},children:[t.jsxs("div",{className:"workspace-selector-option-main",children:[t.jsx(Dc,{size:14}),t.jsx("span",{children:c.id})]}),c.title&&t.jsx("span",{className:"workspace-selector-option-meta",title:c.title,children:RT(c.title)})]},c.id))]})]})]})}const PT=768,IT=280,No=180,So=500,Ph="fusion:file-browser-sidebar-width",Pg=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),$T=new Set([...Pg,".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 Ih(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return $T.has(n)}function DT(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return Pg.has(n)}function LT({initialWorkspace:e="project",onClose:n,onWorkspaceChange:s,projectId:i}){const{projectName:r,workspaces:o}=wT(i),l=a.useRef(null);di(l,!0,"fusion:files-modal-size");const c=Mi(n),[u,d]=a.useState(e),[m,h]=a.useState(null),[f,p]=a.useState(!1),[g,b]=a.useState("list"),[v,x]=a.useState(IT),{entries:y,currentPath:j,setPath:E,loading:C,error:w,refresh:R}=gT(u,!0,i),{content:S,setContent:O,originalContent:_,loading:P,saving:U,error:G,save:M,hasChanges:T,mtime:D}=bT(u,m,!0,i);a.useEffect(()=>{d(e)},[e]),a.useEffect(()=>{const V=()=>{p(window.innerWidth<=PT)};return V(),window.addEventListener("resize",V),()=>window.removeEventListener("resize",V)},[]),a.useEffect(()=>{m||b("list")},[m]),a.useEffect(()=>{try{const V=localStorage.getItem(Ph);if(!V)return;const ve=Number.parseInt(V,10);if(!Number.isNaN(ve)){const B=Math.max(No,Math.min(So,ve));x(B)}}catch{}},[]),a.useEffect(()=>{const V=ve=>{ve.key==="Escape"&&n(),(ve.metaKey||ve.ctrlKey)&&ve.key==="s"&&(ve.preventDefault(),T&&!U&&M())};return document.addEventListener("keydown",V),()=>document.removeEventListener("keydown",V)},[n,T,U,M]);const K=a.useCallback(V=>{h(V),f&&b("editor")},[f]),J=a.useCallback(()=>{b("list")},[]),te=a.useCallback(()=>{O(_)},[_,O]),N=a.useCallback(V=>{d(V),h(null),b("list"),s?.(V)},[s]),z=a.useCallback(V=>{try{localStorage.setItem(Ph,String(V))}catch{}},[]),I=a.useCallback(V=>{if(f)return;V.preventDefault(),V.stopPropagation();const ve=V.currentTarget;typeof ve.setPointerCapture=="function"&&ve.setPointerCapture(V.pointerId);const B=V.clientX,Y=v;let X=Y;document.body.style.userSelect="none";const he=me=>{const se=me.clientX-B,_e=Math.max(No,Math.min(So,Y+se));X=_e,x(_e)},de=me=>{typeof ve.releasePointerCapture=="function"&&ve.releasePointerCapture(me.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",he),document.removeEventListener("pointerup",de),z(X)};document.addEventListener("pointermove",he),document.addEventListener("pointerup",de)},[f,z,v]),k=a.useCallback(V=>{if(f)return;const ve=20;if(V.key!=="ArrowLeft"&&V.key!=="ArrowRight")return;V.preventDefault();const B=V.key==="ArrowLeft"?-ve:ve,Y=Math.max(No,Math.min(So,v+B));x(Y),z(Y)},[f,z,v]),Q=`Files — ${a.useMemo(()=>u==="project"?"Project":o.find(V=>V.id===u)?.id??u,[u,o])}`,ue=a.useMemo(()=>!m||!DT(m)?null:Lp(u,m,i),[m,u,i]),be=V=>{const ve=new Blob([V]).size;return ve<1024?`${ve} B`:`${(ve/1024).toFixed(1)} KB`};return t.jsx("div",{className:"modal-overlay open",...c,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal file-browser-modal",ref:l,children:[t.jsxs("div",{className:"modal-header file-browser-modal-header",children:[t.jsxs("div",{className:"file-browser-header-title",children:[t.jsx(ts,{size:18}),t.jsx("span",{children:Q}),m&&t.jsx("span",{className:"file-browser-header-path",children:m})]}),t.jsxs("div",{className:"file-browser-header-actions",children:[t.jsx(TT,{currentWorkspace:u,projectName:r,workspaces:o,onSelect:N}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(qt,{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(_T,{entries:y,currentPath:j,onSelectFile:K,onNavigate:E,loading:C,error:w,onRetry:R,workspace:u,onRefresh:R,projectId:i})}),!f&&t.jsx("div",{className:"file-browser-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":No,"aria-valuemax":So,"aria-valuenow":v,"aria-label":"Resize sidebar",tabIndex:0,onPointerDown:I,onKeyDown:k}),t.jsx("div",{className:`file-browser-content ${f?"mobile":""} ${g==="editor"?"active":""}`,children:m?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"file-browser-toolbar",children:[t.jsxs("div",{className:"file-browser-file-info",children:[f&&g==="editor"&&t.jsxs("button",{className:"file-browser-back-button",onClick:J,"aria-label":"Back to file list",children:[t.jsx(Ra,{size:16}),t.jsx("span",{children:"Back"})]}),m,Ih(m)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(vx,{size:12}),"Binary file — read only"]}),D&&t.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date(D).toLocaleString()]}),P&&t.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),t.jsx("div",{className:"file-browser-actions",children:!ue&&T&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:te,disabled:U,children:[t.jsx(vv,{size:14}),"Discard"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void M(),disabled:U,children:[t.jsx(Ap,{size:14}),U?"Saving...":"Save"]})]})})]}),G&&!ue&&t.jsx("div",{className:"file-browser-error-banner",children:G}),ue?t.jsx("div",{className:"file-browser-image-preview",children:t.jsx("img",{src:ue,alt:m??"",className:"file-browser-image"})}):t.jsx("div",{className:"file-editor-wrapper",children:t.jsx(AT,{content:S,onChange:O,filePath:m,readOnly:Ih(m)})}),!ue&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:be(S)}),T&&t.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):t.jsxs("div",{className:"file-browser-placeholder",children:[t.jsx(ts,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to edit"})]})})]})]})})}function zT(e={}){const{pollInterval:n=3e4,autoRefresh:s=!0}=e,[i,r]=a.useState({providers:[],loading:!0,error:null,lastUpdated:null}),o=a.useRef(null),l=a.useRef(null),c=a.useCallback(async(d=!1)=>{l.current&&l.current.abort(),l.current=new AbortController,d&&r(m=>({...m,loading:!0,error:null}));try{const{providers:m}=await qy();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:ke(m)||"Failed to fetch usage data"}))}},[]);a.useEffect(()=>{c()},[c]),a.useEffect(()=>{if(s)return o.current=setInterval(()=>{c(!1)},n),()=>{o.current&&(clearInterval(o.current),o.current=null)}},[s,n,c]),a.useEffect(()=>()=>{l.current&&l.current.abort(),o.current&&clearInterval(o.current)},[]);const u=a.useCallback(()=>c(!0),[c]);return{providers:i.providers,loading:i.loading,error:i.error,lastUpdated:i.lastUpdated,refresh:u}}function OT(e){const n=new Date(e),s=new Date,i=n.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit",hour12:!0});if(n.toDateString()===s.toDateString())return i;const o=new Date(s.getFullYear(),s.getMonth(),s.getDate()),l=new Date(n.getFullYear(),n.getMonth(),n.getDate()),c=Math.round((l.getTime()-o.getTime())/(1440*60*1e3));return c>=1&&c<=7?`${n.toLocaleDateString(void 0,{weekday:"short"})} ${i}`:`${n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}, ${i}`}function FT(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}const Ig="kb-usage-hidden-windows",$g="kb-usage-modal-size";function $h(e){const n=Yn($g,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 Dh(e){const n=Yn(Ig,e);if(!n)return{};try{const s=JSON.parse(n);return!s||typeof s!="object"?{}:Object.entries(s).reduce((i,[r,o])=>{if(Array.isArray(o)){const l=o.filter(c=>typeof c=="string");l.length>0&&(i[r]=l)}return i},{})}catch{return{}}}function UT(e,n){fs(Ig,JSON.stringify(e),n)}function Dg(e,n,s){return s[e]?.includes(n)??!1}function BT({window:e,viewMode:n,isHidden:s,onToggleHidden:i}){const r=FT(e.percentUsed),o=n==="remaining",l=Math.round(o?e.percentLeft:e.percentUsed),c=o?`${Math.round(e.percentLeft)}% remaining`:`${Math.round(e.percentUsed)}% used`,u=o?`${Math.round(e.percentUsed)}% used`:`${Math.round(e.percentLeft)}% left`;let d=e.resetText;if(!d&&e.resetAt){const v=new Date(e.resetAt).getTime()-Date.now();if(v>0){const x=Math.floor(v/36e5),y=Math.floor(x/24),j=x%24;y>0&&j>0?d=`resets in ${y}d ${j}h`:y>0?d=`resets in ${y}d`:x>0?d=`resets in ${x}h`:d=`resets in ${Math.floor(v/6e4)}m`}}const m=e.pace,h=m!==void 0;let f=0;h&&(f=o?100-m.percentElapsed:m.percentElapsed);const p=m?.status==="ahead",g=m?.status==="behind",b=m?.status==="on-track";return t.jsxs("div",{className:`usage-window ${s?"usage-window--hidden":""}`,children:[t.jsxs("div",{className:"usage-window-header",children:[t.jsx("span",{className:"usage-window-label",children:e.label}),t.jsxs("div",{className:"usage-window-header-controls",children:[!s&&t.jsx("span",{className:"usage-window-percentage",children:c}),!s&&t.jsx("button",{className:"btn-icon usage-window-hide-btn",onClick:i,"aria-label":`Hide ${e.label}`,"data-testid":"usage-window-hide-btn",children:t.jsx(Ta,{size:14})})]})]}),t.jsxs("div",{className:"usage-progress-wrapper",children:[t.jsx("div",{className:"usage-progress-bar",children:t.jsx("div",{className:`usage-progress-fill ${r}`,style:{width:`${l}%`},role:"progressbar","aria-valuenow":l,"aria-valuemin":0,"aria-valuemax":100,"aria-label":`${e.label}: ${c}`})}),h&&t.jsx("div",{className:"usage-pace-marker",style:{left:`${f}%`},"aria-hidden":"true","data-testid":"pace-marker"})]}),t.jsxs("div",{className:"usage-window-footer",children:[t.jsx("span",{className:"usage-window-left",children:u}),t.jsxs("span",{className:"usage-window-reset-group",children:[d&&t.jsx("span",{className:"usage-window-reset",children:d}),e.resetAt&&t.jsx("span",{className:"usage-window-reset-at",children:OT(e.resetAt)})]})]}),h&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[p&&t.jsxs(t.Fragment,{children:[t.jsx(rl,{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(Uv,{size:14,className:"pace-icon pace-behind"}),t.jsx("span",{className:"pace-text pace-behind",children:m.message})]}),b&&t.jsxs(t.Fragment,{children:[t.jsx(Nn,{size:14,className:"pace-icon pace-ontrack"}),t.jsx("span",{className:"pace-text pace-ontrack",children:m.message})]})]})]})}function HT(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 qT({provider:e,viewMode:n,hiddenWindows:s,onToggleWindow:i,onShowAllHidden:r}){const o=s[e.name]?.length??0,l=()=>{switch(e.status){case"ok":return null;case"error":return t.jsx("span",{className:"usage-status-badge usage-status-badge--error",children:"Error"});case"no-auth":default:return t.jsx("span",{className:"usage-status-badge usage-status-badge--not-configured",children:"Not configured"})}};return t.jsxs("div",{className:"usage-provider","data-provider":e.name,"data-status":e.status,children:[t.jsxs("div",{className:"usage-provider-header",children:[t.jsxs("div",{className:"usage-provider-info",children:[t.jsx(Rn,{provider:HT(e.name),size:"md"}),t.jsx("span",{className:"usage-provider-name",children:e.name}),o>0&&t.jsxs("button",{className:"btn btn-sm usage-show-hidden-btn",onClick:()=>r(e.name),"data-testid":"usage-show-hidden-btn",children:["Show hidden (",o,")"]})]}),t.jsx("div",{className:"usage-provider-actions",children:l()})]}),e.error&&t.jsx("div",{className:"usage-provider-error",children:e.error}),e.plan&&t.jsx("div",{className:"usage-provider-meta",children:t.jsx("span",{className:"usage-provider-plan",children:e.plan})}),e.windows.length>0?t.jsx("div",{className:"usage-provider-windows",children:e.windows.map((c,u)=>{const d=Dg(e.name,c.label,s);return t.jsx(BT,{window:c,viewMode:n,isHidden:d,onToggleHidden:()=>i(e.name,c.label)},`${e.name}-${c.label}-${u}`)})}):e.status==="ok"?t.jsx("div",{className:"usage-provider-empty",children:"No usage data available"}):null]})}function VT(){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 WT({isOpen:e,onClose:n,projectId:s,anchorRect:i}){const{providers:r,loading:o,error:l,lastUpdated:c,refresh:u}=zT({autoRefresh:e}),[d,m]=a.useState(!1),[h,f]=a.useState(()=>typeof window<"u"?window.innerWidth>=769:!1),[p,g]=a.useState("used"),[b,v]=a.useState(()=>Dh(s)),x=a.useRef(null),y=a.useRef(null),j=a.useRef(e),E=a.useRef(!1),[C,w]=a.useState(()=>$h(s));a.useEffect(()=>{w($h(s))},[s]),a.useEffect(()=>{if(!e||!h)return;const z=y.current;if(!z||typeof ResizeObserver>"u")return;let I=null;const k=new ResizeObserver(H=>{const Q=H[0];if(!Q)return;const{width:ue,height:be}=Q.contentRect;ue<=0||be<=0||(I&&clearTimeout(I),I=setTimeout(()=>{fs($g,JSON.stringify({width:Math.round(ue),height:Math.round(be)}),s)},250))});return k.observe(z),()=>{I&&clearTimeout(I),k.disconnect()}},[e,h,s]),a.useEffect(()=>{e||(E.current=!1)},[e]),a.useEffect(()=>{r.length>0&&(E.current=!0)},[r.length]),a.useEffect(()=>{if(typeof window>"u")return;const z=()=>{f(window.innerWidth>=769)};return window.addEventListener("resize",z),()=>window.removeEventListener("resize",z)},[]),a.useEffect(()=>{!j.current&&e&&(!c||Date.now()-c.getTime()>5e3)&&u(),j.current=e},[e,c,u]),a.useEffect(()=>{const z=Yn("kb-usage-view-mode",s);if(z==="used"||z==="remaining"){g(z);return}g("used")},[s]);const R=a.useCallback(z=>{g(z),fs("kb-usage-view-mode",z,s)},[s]);a.useEffect(()=>{v(Dh(s))},[s]),a.useEffect(()=>{UT(b,s)},[b,s]);const S=a.useCallback((z,I)=>{v(k=>{if(Dg(z,I,k)){const H=(k[z]??[]).filter(Q=>Q!==I);if(H.length===0){const{[z]:Q,...ue}=k;return ue}return{...k,[z]:H}}return{...k,[z]:[...k[z]??[],I]}})},[]),O=a.useCallback(z=>{v(I=>{if(!I[z])return I;const{[z]:k,...H}=I;return H})},[]),_=a.useCallback(async()=>{m(!0),await u(),m(!1)},[u]);a.useEffect(()=>{if(!e)return;const z=I=>{I.key==="Escape"&&n()};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[e,n]);const P=a.useCallback(z=>{z.target===z.currentTarget&&n()},[n]);if(!e)return null;const U=!!(i&&h),G=8,M=12,D=C?.width??420,K=U?Math.min((i?.bottom??0)+G,window.innerHeight-M):void 0,J=U?Math.max(8,(i?.right??0)-D):void 0,te=h&&C?{width:C.width,height:C.height}:{},N=t.jsxs("div",{ref:y,className:`usage-modal${U?" usage-modal--popover":" modal"}`,"data-testid":"usage-modal",style:U?{position:"fixed",top:K,left:J,...te}:te,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"usage-header",children:[t.jsx(Ds,{size:18,className:"usage-header-icon"}),t.jsx("h3",{children:"Usage"})]}),t.jsxs("div",{className:"usage-header-actions",children:[t.jsxs("div",{className:"usage-view-toggle",role:"group","aria-label":"Usage view mode",children:[t.jsx("button",{className:`usage-view-toggle-btn ${p==="used"?"active":""}`,onClick:()=>R("used"),"aria-pressed":p==="used","data-testid":"usage-view-toggle-used",children:"Used"}),t.jsx("button",{className:`usage-view-toggle-btn ${p==="remaining"?"active":""}`,onClick:()=>R("remaining"),"aria-pressed":p==="remaining","data-testid":"usage-view-toggle-remaining",children:"Remaining"})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close usage modal","data-testid":"usage-modal-close",children:t.jsx(qt,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:x,children:(o||!E.current&&!l)&&r.length===0?t.jsx(VT,{}):l&&r.length===0?t.jsxs("div",{className:"usage-error",children:[t.jsx("p",{children:"Failed to load usage data"}),t.jsx("p",{className:"usage-error-message",children:l}),t.jsx("button",{className:"btn btn-sm",onClick:_,children:"Retry"})]}):r.length===0?t.jsxs("div",{className:"usage-empty",children:[t.jsx("p",{children:"No AI providers configured"}),t.jsx("p",{className:"usage-empty-hint",children:"Configure authentication in Settings to see usage data."})]}):t.jsx("div",{className:"usage-providers",children:r.map(z=>t.jsx(qT,{provider:z,viewMode:p,hiddenWindows:b,onToggleWindow:S,onShowAllHidden:O},z.name))})}),t.jsxs("div",{className:"modal-actions usage-actions",children:[t.jsx("div",{className:"modal-actions-left usage-actions-left",children:t.jsx("div",{className:"usage-last-updated",children:c&&t.jsxs("span",{children:["Last updated: ",c.toLocaleTimeString()]})})}),t.jsxs("div",{className:"modal-actions-right usage-actions-right",children:[t.jsxs("button",{className:"btn btn-sm",onClick:_,disabled:o||d,"data-testid":"usage-refresh-btn",children:[t.jsx(Fn,{size:14,className:d?"spin":"",style:{marginRight:6}}),"Refresh"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]});return U?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"usage-popover-backdrop",onClick:n,"data-testid":"usage-modal-overlay"}),N]}):t.jsx("div",{className:"modal-overlay open",onClick:P,"data-testid":"usage-modal-overlay",children:N})}function Lg(e){if(e<1e3)return`${e}ms`;const n=Math.floor(e/1e3);if(n<60)return`${n}s`;const s=Math.floor(n/60),i=n%60;if(s<60)return i>0?`${s}m ${i}s`:`${s}m`;const r=Math.floor(s/60),o=s%60;return o>0?`${r}h ${o}m`:`${r}h`}function Yo(e){const n=Date.now(),s=new Date(e).getTime(),i=n-s;if(i<0){const r=Math.abs(i);return r<6e4?"in a moment":r<36e5?`in ${Math.floor(r/6e4)}m`:r<864e5?`in ${Math.floor(r/36e5)}h`:`in ${Math.floor(r/864e5)}d`}return i<6e4?"just now":i<36e5?`${Math.floor(i/6e4)}m ago`:i<864e5?`${Math.floor(i/36e5)}h ago`:`${Math.floor(i/864e5)}d ago`}const KT={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},zg={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},GT={cron:jp,webhook:Tp,api:kp,manual:es},JT={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},YT={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function QT({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(Nn,{size:12}):t.jsx(Lr,{size:12}),t.jsx("span",{children:e.success?"Success":"Failed"}),n>0&&t.jsx("span",{className:"schedule-run-duration",children:Lg(n)})]})}function XT({result:e,index:n}){const[s,i]=a.useState(!1),r=e.completedAt&&e.startedAt?new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime():0;return t.jsxs("div",{className:"schedule-history-item",children:[t.jsxs("button",{className:"schedule-history-header",onClick:()=>i(!s),"aria-expanded":s,"aria-label":`Run #${n+1}: ${e.success?"succeeded":"failed"} ${Yo(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx(Nn,{size:12}):t.jsx(Lr,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:Yo(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:zg[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:Lg(r)}),s?t.jsx(bi,{size:12}):t.jsx(Yt,{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 ZT({routine:e,onEdit:n,onDelete:s,onRun:i,onToggle:r,running:o,lastRunOutput:l}){const[c,u]=a.useState(!1),{confirm:d}=Gs(),m=a.useCallback(async()=>{await d({title:"Delete Routine",message:`Delete routine "${e.name}"? This cannot be undone.`,danger:!0})&&s(e)},[e,s,d]),h=KT[e.trigger.type],f=GT[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}),zg[e.trigger.type]]}),e.scope&&t.jsxs("span",{className:`routine-scope-badge${e.scope==="global"?" global":" project"}`,title:`${e.scope==="global"?"Global":"Project"}-scoped routine`,children:[e.scope==="global"?t.jsx(nl,{size:10}):t.jsx(ts,{size:10}),e.scope]})]}),e.description&&t.jsx("p",{className:"routine-card-description",children:e.description})]}),t.jsxs("div",{className:"routine-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>i(e),disabled:o,title:o?"Running…":"Run now","aria-label":o?"Running…":`Run ${e.name} now`,children:o?t.jsx(lt,{className:"spinner"}):t.jsx(_n,{})}),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(Vs,{}):t.jsx(_n,{})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:"Edit","aria-label":`Edit ${e.name}`,children:t.jsx(hs,{})}),t.jsx("button",{className:"btn-icon",onClick:m,title:"Delete","aria-label":`Delete ${e.name}`,children:t.jsx(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(qi,{size:12}),t.jsxs("span",{className:"routine-policy-badge",children:[e.steps.length," step",e.steps.length===1?"":"s"]})]}):e.command?t.jsx("div",{className:"routine-meta-item routine-meta-command-preview",title:e.command,children:t.jsx("code",{className:"routine-cron",children:e.command})}):null,e.trigger.type==="cron"&&p&&t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(Ei,{size:12}),t.jsx("code",{className:"routine-cron",children:p})]}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Execution policy: ${e.executionPolicy}`,children:JT[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:YT[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:Yo(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:Yo(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(QT,{result:e.lastRunResult}),t.jsxs("div",{className:"routine-meta-item",children:[t.jsx("span",{className:"routine-meta-label",children:"Runs:"}),t.jsx("span",{children:e.runCount})]})]}),l&&t.jsxs("div",{className:`routine-run-output ${l.success?"success":"failure"}`,children:[l.output&&t.jsx("pre",{className:"routine-run-output-text",children:l.output}),l.error&&t.jsx("div",{className:"routine-run-output-error",children:l.error})]}),e.runHistory.length>0&&t.jsxs("div",{className:"routine-card-history",children:[t.jsxs("button",{className:"schedule-history-toggle",onClick:()=>u(g=>!g),"aria-expanded":c,children:[c?t.jsx(bi,{size:12}):t.jsx(Yt,{size:12}),t.jsxs("span",{children:["Run History (",e.runHistory.length,")"]})]}),c&&t.jsxs("div",{className:"schedule-history-list",children:[e.runHistory.slice(0,10).map((g,b)=>t.jsx(XT,{result:g,index:b},`${g.startedAt}-${b}`)),e.runHistory.length>10&&t.jsxs("div",{className:"schedule-history-more",children:["…and ",e.runHistory.length-10," more"]})]})]})]})}function eP({type:e,size:n=12}){return e==="command"?t.jsxs("span",{className:"step-type-badge step-type-command",title:"Command step",children:[t.jsx(gi,{size:n}),t.jsx("span",{children:"Command"})]}):e==="create-task"?t.jsxs("span",{className:"step-type-badge step-type-create-task",title:"Create Task step",children:[t.jsx(Wx,{size:n}),t.jsx("span",{children:"Create Task"})]}):t.jsxs("span",{className:"step-type-badge step-type-ai-prompt",title:"AI Prompt step",children:[t.jsx(cs,{size:n}),t.jsx("span",{children:"AI Prompt"})]})}function wc(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function tP(e){return e==="command"?{id:wc(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:wc(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:wc(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function nP({step:e,onSave:n,onCancel:s}){const[i,r]=a.useState(e.name),[o,l]=a.useState(e.type),[c,u]=a.useState(e.command??""),[d,m]=a.useState(e.prompt??""),[h,f]=a.useState(e.modelProvider??""),[p,g]=a.useState(e.modelId??""),[b,v]=a.useState(e.taskTitle??""),[x,y]=a.useState(e.taskDescription??""),[j,E]=a.useState(e.taskColumn??"triage"),[C,w]=a.useState(e.timeoutMs),[R,S]=a.useState(e.continueOnFailure??!1),[O,_]=a.useState({}),[P,U]=a.useState([]),[G,M]=a.useState(!1),[T,D]=a.useState(null);a.useEffect(()=>{let z=!1;return M(!0),D(null),bs().then(I=>{z||U(I.models)}).catch(I=>{z||D(I instanceof Error?I.message:"Failed to load models")}).finally(()=>{z||M(!1)}),()=>{z=!0}},[]);const K=a.useCallback(()=>{const z={};return i.trim()||(z.name="Step name is required"),o==="command"&&!c.trim()&&(z.command="Command is required"),o==="ai-prompt"&&!d.trim()&&(z.prompt="Prompt is required"),o==="create-task"&&!x.trim()&&(z.taskDescription="Task description is required"),(o==="ai-prompt"||o==="create-task")&&(h||p)&&(!h||!p)&&(z.modelProvider="Both model provider and model ID must be set together"),C!==void 0&&C<1e3&&(z.timeoutMs="Timeout must be at least 1 second (1000ms)"),_(z),Object.keys(z).length===0},[i,o,c,d,x,h,p,C]),J=h&&p?`${h}/${p}`:"",te=a.useCallback(z=>{if(!z)f(""),g("");else{const I=z.indexOf("/");I!==-1&&(f(z.slice(0,I)),g(z.slice(I+1)))}},[]),N=a.useCallback(()=>{if(!K())return;const z={...e,name:i.trim(),type:o,command:o==="command"?c.trim():void 0,prompt:o==="ai-prompt"?d.trim():void 0,taskTitle:o==="create-task"&&b.trim()?b.trim():void 0,taskDescription:o==="create-task"&&x.trim()?x.trim():void 0,taskColumn:o==="create-task"?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:C||void 0,continueOnFailure:R};o!=="ai-prompt"&&delete z.prompt,o!=="create-task"&&(delete z.taskTitle,delete z.taskDescription,delete z.taskColumn),n(z)},[K,n,e,i,o,c,d,b,x,j,h,p,C,R]);return t.jsxs("div",{className:"step-editor",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-name-${e.id}`,children:"Step Name"}),t.jsx("input",{id:`step-name-${e.id}`,type:"text",placeholder:"e.g. Run tests",value:i,onChange:z=>r(z.target.value),"aria-invalid":!!O.name}),O.name&&t.jsx("small",{className:"field-error",children:O.name})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-type-${e.id}`,children:"Step Type"}),t.jsxs("select",{id:`step-type-${e.id}`,value:o,onChange:z=>l(z.target.value),children:[t.jsx("option",{value:"command",children:"Command"}),t.jsx("option",{value:"ai-prompt",children:"AI Prompt"}),t.jsx("option",{value:"create-task",children:"Create Task"})]})]}),o==="command"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-command-${e.id}`,children:"Command"}),t.jsx("textarea",{id:`step-command-${e.id}`,placeholder:"e.g. npm test",value:c,onChange:z=>u(z.target.value),rows:2,"aria-invalid":!!O.command}),O.command&&t.jsx("small",{className:"field-error",children:O.command})]}),o==="ai-prompt"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-prompt-${e.id}`,children:"Prompt"}),t.jsx("textarea",{id:`step-prompt-${e.id}`,placeholder:"e.g. Summarize the test results and highlight any failures",value:d,onChange:z=>m(z.target.value),rows:3,"aria-invalid":!!O.prompt}),O.prompt&&t.jsx("small",{className:"field-error",children:O.prompt})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-model-${e.id}`,children:"Model (optional)"}),t.jsx(ns,{id:`step-model-${e.id}`,label:"Model",models:P,value:J,onChange:te,placeholder:"Use default",disabled:G}),T&&t.jsx("small",{className:"field-error",children:T}),t.jsx("small",{children:"AI model for this step. Uses default if not selected."})]})]}),o==="create-task"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-title-${e.id}`,children:"Task Title (optional)"}),t.jsx("input",{id:`step-task-title-${e.id}`,type:"text",placeholder:"e.g. Review weekly dependencies",value:b,onChange:z=>v(z.target.value)}),t.jsx("small",{children:"Leave blank to auto-summarize from description"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-description-${e.id}`,children:"Task Description *"}),t.jsx("textarea",{id:`step-task-description-${e.id}`,placeholder:"e.g. Check all npm dependencies for security vulnerabilities and update outdated packages",value:x,onChange:z=>y(z.target.value),rows:4,"aria-invalid":!!O.taskDescription}),O.taskDescription&&t.jsx("small",{className:"field-error",children:O.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:z=>E(z.target.value),children:[t.jsx("option",{value:"triage",children:"Triage"}),t.jsx("option",{value:"todo",children:"To Do"})]}),t.jsx("small",{children:"Column where the new task will be created"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-model-${e.id}`,children:"Executor Model (optional)"}),t.jsx(ns,{id:`step-task-model-${e.id}`,label:"Model",models:P,value:J,onChange:te,placeholder:"Use default",disabled:G}),T&&t.jsx("small",{className:"field-error",children:T}),O.modelProvider&&t.jsx("small",{className:"field-error",children:O.modelProvider}),t.jsx("small",{children:"AI model for executing the created task. Uses default if not selected."})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-timeout-${e.id}`,children:"Timeout (ms, optional)"}),t.jsx("input",{id:`step-timeout-${e.id}`,type:"number",min:1e3,step:1e3,placeholder:"Override schedule timeout",value:C??"",onChange:z=>w(z.target.value?Number(z.target.value):void 0),"aria-invalid":!!O.timeoutMs}),O.timeoutMs&&t.jsx("small",{className:"field-error",children:O.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:R,onChange:z=>S(z.target.checked)}),"Continue on failure"]}),t.jsx("small",{children:"If checked, the next step will run even if this one fails"})]}),t.jsxs("div",{className:"step-editor-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:N,children:"Save Step"})]})]})}function sP({steps:e,onChange:n,onEditingChange:s}){const[i,r]=a.useState(null);a.useEffect(()=>{s?.(i!==null)},[i,s]);const o=a.useCallback(d=>{const m=tP(d);n([...e,m]),r(m.id)},[e,n]),l=a.useCallback(d=>{n(e.filter(m=>m.id!==d)),i===d&&r(null)},[e,n,i]),c=a.useCallback((d,m)=>{const h=e.findIndex(g=>g.id===d);if(h<0)return;const f=m==="up"?h-1:h+1;if(f<0||f>=e.length)return;const p=[...e];[p[h],p[f]]=[p[f],p[h]],n(p)},[e,n]),u=a.useCallback(d=>{n(e.map(m=>m.id===d.id?d:m)),r(null)},[e,n]);return t.jsxs("div",{className:"steps-editor",children:[t.jsx("div",{className:"steps-editor-header",children:t.jsxs("span",{className:"steps-editor-title",children:["Steps (",e.length,")"]})}),e.length===0&&t.jsx("div",{className:"steps-empty-state",children:t.jsx("p",{children:"No steps added yet. Add a command or AI prompt step to get started."})}),t.jsx("div",{className:"steps-list",children:e.map((d,m)=>t.jsx("div",{className:"step-card",children:i===d.id?t.jsx(nP,{step:d,onSave:u,onCancel:()=>r(null)}):t.jsxs("div",{className:"step-card-row",children:[t.jsx("div",{className:"step-card-drag",children:t.jsx(xd,{size:14})}),t.jsx("span",{className:"step-card-index",children:m+1}),t.jsx(eP,{type:d.type}),t.jsx("span",{className:"step-card-name",children:d.name}),d.continueOnFailure&&t.jsx("span",{className:"step-card-flag",title:"Continues on failure",children:"⚡"}),t.jsxs("div",{className:"step-card-actions",children:[t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>c(d.id,"up"),disabled:m===0,title:"Move up","aria-label":`Move ${d.name} up`,children:t.jsx(bi,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>c(d.id,"down"),disabled:m===e.length-1,title:"Move down","aria-label":`Move ${d.name} down`,children:t.jsx(Yt,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(d.id),title:"Edit","aria-label":`Edit ${d.name}`,children:t.jsx(hs,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>l(d.id),title:"Delete","aria-label":`Delete ${d.name}`,children:t.jsx(cn,{})})]})]})},d.id))}),t.jsxs("div",{className:"steps-add-buttons",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("command"),children:[t.jsx(dn,{size:14}),"Add Command Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ai-prompt"),children:[t.jsx(dn,{size:14}),"Add AI Prompt Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("create-task"),children:[t.jsx(dn,{size:14}),"Add Create Task Step"]})]})]})}const Og={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},iP={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function aP(e){const n=e.trim();for(const[s,i]of Object.entries(Og))if(i===n)return s;return"custom"}function rP(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function oP(e,n,s,i,r){switch(e){case"cron":return{type:"cron",cronExpression:n};case"webhook":return{type:"webhook",webhookPath:s||"/trigger/"+Math.random().toString(36).slice(2,10),secret:i||void 0};case"api":return{type:"api",endpoint:r||"/api/routine/"+Math.random().toString(36).slice(2,10)};case"manual":return{type:"manual"}}}function lP(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 cP=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],dP=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function Lh(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function zh({routine:e,onSubmit:n,onCancel:s,scope:i,projectId:r,onScopeChange:o}){const l=!!e,c=e?lP(e):{triggerType:"cron",cronExpression:"0 * * * *",webhookPath:"",webhookSecret:"",endpoint:""},[u,d]=a.useState(e?.name??""),[m,h]=a.useState(e?.description??""),[f,p]=a.useState(c.triggerType),[g,b]=a.useState(c.cronExpression),[v,x]=a.useState(()=>c.triggerType!=="cron"?"custom":aP(c.cronExpression)),[y,j]=a.useState(c.webhookPath),[E,C]=a.useState(c.webhookSecret),[w,R]=a.useState(c.endpoint),[S,O]=a.useState(e?.executionPolicy??"queue"),[_,P]=a.useState(e?.catchUpPolicy??"run_one"),[U,G]=a.useState(e?.enabled??!0),M=e?.steps&&e.steps.length===1&&e.steps[0].type==="ai-prompt"&&!e.command,T=e?.steps&&e.steps.length===1&&e.steps[0].type==="create-task"&&!e.command,[D,K]=a.useState(e?.steps&&e.steps.length>0&&!M&&!T?"advanced":"simple"),[J,te]=a.useState(()=>M?"ai-prompt":T?"create-task":"command"),[N,z]=a.useState(e?.command??""),[I,k]=a.useState(e?.steps??[]),[H,Q]=a.useState(!1),[ue,be]=a.useState(e?.timeoutMs??3e5),[V,ve]=a.useState(M?e.steps?.[0]?.prompt??"":""),[B,Y]=a.useState(T?e.steps?.[0]?.taskTitle??"":""),[X,he]=a.useState(T?e.steps?.[0]?.taskDescription??"":""),[de,me]=a.useState(T?e.steps?.[0]?.taskColumn??"triage":"triage"),[se,_e]=a.useState(M||T?e.steps?.[0]?.modelProvider??"":""),[Fe,Te]=a.useState(M||T?e.steps?.[0]?.modelId??"":""),[st,nt]=a.useState([]),[qe,Xe]=a.useState(!1),[$e,Ue]=a.useState(null),[oe,je]=a.useState(i??"global"),[ie,Ae]=a.useState({}),[Le,we]=a.useState(!1),Ee=a.useRef(!0);a.useEffect(()=>()=>{Ee.current=!1},[]),a.useEffect(()=>{i&&je(i)},[i]),a.useEffect(()=>{let ne=!1;return Xe(!0),Ue(null),bs().then(Ze=>{ne||nt(Ze.models)}).catch(Ze=>{ne||Ue(Ze instanceof Error?Ze.message:"Failed to load models")}).finally(()=>{ne||Xe(!1)}),()=>{ne=!0}},[]);const Ve=se&&Fe?`${se}/${Fe}`:"",rt=a.useCallback(ne=>{if(!ne){_e(""),Te("");return}const Ze=ne.indexOf("/");Ze!==-1&&(_e(ne.slice(0,Ze)),Te(ne.slice(Ze+1)))},[]),xe=a.useCallback(()=>{const ne={};if(u.trim()||(ne.name="Name is required"),oe==="project"&&!r&&(ne.scope="Project-specific entries require an active project."),f==="cron"&&v==="custom"&&(g.trim()?rP(g)||(ne.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):ne.cronExpression="Cron expression is required"),f==="webhook"&&!y.trim()&&(ne.webhookPath="Webhook path is required"),f==="api"&&!w.trim()&&(ne.endpoint="API endpoint is required"),D==="simple")J==="command"&&!N.trim()&&(ne.command="Command is required"),J==="ai-prompt"&&!V.trim()&&(ne.prompt="Prompt is required"),J==="create-task"&&!X.trim()&&(ne.taskDescription="Task description is required"),(se.trim()&&!Fe.trim()||!se.trim()&&Fe.trim())&&(ne.model="Both model provider and model ID must be set, or both must be empty");else{I.length===0&&(ne.steps="At least one step is required"),H&&(ne.stepsEditing="Please save or cancel all step edits before saving the routine");const Ze=[];I.forEach((ft,gt)=>{ft.name?.trim()||Ze.push(`Step ${gt+1}: Name is required`),ft.type==="command"&&!ft.command?.trim()&&Ze.push(`Step ${gt+1}: Command is required`),ft.type==="ai-prompt"&&!ft.prompt?.trim()&&Ze.push(`Step ${gt+1}: Prompt is required`),ft.type==="create-task"&&!ft.taskDescription?.trim()&&Ze.push(`Step ${gt+1}: Task description is required`)}),Ze.length>0&&(ne.steps=Ze.join("; "))}return ue<1e3&&(ne.timeoutMs="Timeout must be at least 1 second (1000ms)"),Ae(ne),Object.keys(ne).length===0},[u,f,g,v,y,w,oe,r,D,J,N,V,X,se,Fe,I,H,ue]),ce=a.useCallback(async ne=>{if(ne.preventDefault(),!!xe()){we(!0);try{let Ze=e?.scope??oe??(r?"project":"global");Ze==="project"&&!r&&(Ze="global");const ft=oP(f,g,y,E,w);let gt,St;D==="simple"?J==="command"?gt=N.trim()||void 0:J==="ai-prompt"?St=[{id:Lh(),type:"ai-prompt",name:u.trim(),prompt:V.trim(),modelProvider:se.trim()||void 0,modelId:Fe.trim()||void 0}]:St=[{id:Lh(),type:"create-task",name:u.trim(),taskTitle:B.trim()||void 0,taskDescription:X.trim(),taskColumn:de,modelProvider:se.trim()||void 0,modelId:Fe.trim()||void 0}]:St=I;const Nt={name:u.trim(),agentId:e?.agentId??"",description:m.trim()||void 0,trigger:ft,command:gt,steps:St,timeoutMs:ue,executionPolicy:S,catchUpPolicy:_,enabled:U,scope:Ze};await n(Nt)}finally{Ee.current&&we(!1)}}},[xe,n,u,m,f,g,y,E,w,D,J,N,V,se,Fe,B,X,de,I,ue,S,_,U,oe,r,e?.scope,e?.agentId]),Pe="routine-name-error",pe="routine-cron-error",Re="routine-webhook-error",Qe="routine-endpoint-error",Ie="routine-command-error",bt="routine-prompt-error",ee="routine-task-description-error",re="routine-model-error",Se="routine-timeout-error",ot=a.useCallback(ne=>{x(ne),ne!=="custom"&&b(Og[ne])},[]);return t.jsxs("form",{className:"routine-form",onSubmit:ce,noValidate:!0,children:[t.jsx("h4",{className:"settings-section-heading",children:l?"Edit Routine":"New Routine"}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-name",children:"Name"}),t.jsx("input",{id:"routine-name",type:"text",placeholder:"e.g. Daily standup reminder",value:u,onChange:ne=>d(ne.target.value),"aria-invalid":!!ie.name,"aria-describedby":ie.name?Pe:void 0}),ie.name&&t.jsx("small",{id:Pe,className:"field-error",children:ie.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:ne=>h(ne.target.value),rows:2})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Scope"}),t.jsxs("div",{className:"routine-scope-toggle",role:"radiogroup","aria-label":"Routine scope",children:[t.jsxs("button",{type:"button",className:`routine-scope-btn${oe==="global"?" active":""}`,onClick:()=>{je("global"),o?.("global")},role:"radio","aria-checked":oe==="global"?"true":"false",disabled:!!e?.scope,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:"Global scope",children:[t.jsx(nl,{size:12}),"Global"]}),t.jsxs("button",{type:"button",className:`routine-scope-btn${oe==="project"?" active":""}`,onClick:()=>{je("project"),o?.("project")},role:"radio","aria-checked":oe==="project"?"true":"false",disabled:!!e?.scope||!r,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:r?"Project scope":"Select a project to enable project scope",children:[t.jsx(ts,{size:12}),"Project"]})]}),t.jsx("small",{children:!r&&!e?.scope?"No active project. Routines will be created at global scope.":oe==="project"&&r?"This routine will be scoped to the current project.":"This routine will be created at global scope."}),ie.scope&&t.jsx("small",{className:"field-error",children:ie.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(Tp,{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(kp,{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(es,{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:ne=>ot(ne.target.value),children:Object.entries(iP).map(([ne,Ze])=>t.jsx("option",{value:ne,children:Ze},ne))}),t.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),t.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:g,onChange:ne=>b(ne.target.value),disabled:v!=="custom","aria-invalid":!!ie.cronExpression,"aria-describedby":ie.cronExpression?pe:void 0}),ie.cronExpression?t.jsx("small",{id:pe,className:"field-error",children:ie.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:ne=>j(ne.target.value),"aria-invalid":!!ie.webhookPath,"aria-describedby":ie.webhookPath?Re:void 0}),ie.webhookPath?t.jsx("small",{id:Re,className:"field-error",children:ie.webhookPath}):t.jsx("small",{children:"URL path for the webhook endpoint"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-secret",children:"Webhook Secret (optional)"}),t.jsx("input",{id:"routine-webhook-secret",type:"password",placeholder:"Optional — leave empty for unauthenticated webhooks",value:E,onChange:ne=>C(ne.target.value)}),t.jsx("small",{children:"HMAC secret for signature verification. Leave empty for unauthenticated webhooks."})]})]}),f==="api"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-endpoint",children:"API Endpoint"}),t.jsx("input",{id:"routine-endpoint",type:"text",placeholder:"/api/routine/my-routine",value:w,onChange:ne=>R(ne.target.value),"aria-invalid":!!ie.endpoint,"aria-describedby":ie.endpoint?Qe:void 0}),ie.endpoint?t.jsx("small",{id:Qe,className:"field-error",children:ie.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${D==="simple"?" active":""}`,onClick:()=>K("simple"),role:"radio","aria-checked":D==="simple",children:"Simple"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${D==="advanced"?" active":""}`,onClick:()=>K("advanced"),role:"radio","aria-checked":D==="advanced",children:"Multi-Step"})]}),t.jsx("small",{children:D==="simple"?"Run one command, prompt, or task creation action":"Run multiple actions sequentially"})]}),D==="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${J==="command"?" active":""}`,onClick:()=>te("command"),role:"radio","aria-checked":J==="command",children:"Command"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${J==="ai-prompt"?" active":""}`,onClick:()=>te("ai-prompt"),role:"radio","aria-checked":J==="ai-prompt",children:"AI Prompt"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${J==="create-task"?" active":""}`,onClick:()=>te("create-task"),role:"radio","aria-checked":J==="create-task",children:"Create Task"})]})]}),J==="command"?t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-command",children:"Command"}),t.jsx("input",{id:"routine-command",type:"text",placeholder:"e.g. npx runfusion.ai backup --create",value:N,onChange:ne=>z(ne.target.value),"aria-invalid":!!ie.command,"aria-describedby":ie.command?Ie:void 0}),ie.command?t.jsx("small",{id:Ie,className:"field-error",children:ie.command}):t.jsx("small",{children:"Shell command to execute."})]}):J==="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:V,onChange:ne=>ve(ne.target.value),rows:3,"aria-invalid":!!ie.prompt,"aria-describedby":ie.prompt?bt:void 0}),ie.prompt?t.jsx("small",{id:bt,className:"field-error",children:ie.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(ns,{id:"routine-model",label:"Model",models:st,value:Ve,onChange:rt,placeholder:"Use default",disabled:qe}),$e&&t.jsx("small",{className:"field-error",children:$e}),ie.model&&t.jsx("small",{id:re,className:"field-error",children:ie.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:B,onChange:ne=>Y(ne.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:X,onChange:ne=>he(ne.target.value),rows:4,"aria-invalid":!!ie.taskDescription,"aria-describedby":ie.taskDescription?ee:void 0}),ie.taskDescription?t.jsx("small",{id:ee,className:"field-error",children:ie.taskDescription}):t.jsx("small",{children:"Describes the task that will be created."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-column",children:"Target Column"}),t.jsxs("select",{id:"routine-task-column",value:de,onChange:ne=>me(ne.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(ns,{id:"routine-task-model",label:"Executor Model",models:st,value:Ve,onChange:rt,placeholder:"Use default",disabled:qe}),$e&&t.jsx("small",{className:"field-error",children:$e}),ie.model&&t.jsx("small",{id:re,className:"field-error",children:ie.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(sP,{steps:I,onChange:k,onEditingChange:Q}),ie.steps&&t.jsx("small",{className:"field-error",children:ie.steps}),ie.stepsEditing&&t.jsx("small",{className:"field-error",children:ie.stepsEditing})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-timeout",children:"Timeout (ms)"}),t.jsx("input",{id:"routine-timeout",type:"number",min:1e3,step:1e3,value:ue,onChange:ne=>be(Number(ne.target.value)),"aria-invalid":!!ie.timeoutMs,"aria-describedby":ie.timeoutMs?Se:void 0}),ie.timeoutMs?t.jsx("small",{id:Se,className:"field-error",children:ie.timeoutMs}):t.jsx("small",{children:"Maximum execution time in milliseconds."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-execution-policy",children:"Execution Policy"}),t.jsx("select",{id:"routine-execution-policy",value:S,onChange:ne=>O(ne.target.value),children:cP.map(ne=>t.jsx("option",{value:ne.value,children:ne.label},ne.value))}),t.jsx("small",{children:"How to handle concurrent executions of this routine"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-catchup-policy",children:"Catch-up Policy"}),t.jsx("select",{id:"routine-catchup-policy",value:_,onChange:ne=>P(ne.target.value),children:dP.map(ne=>t.jsx("option",{value:ne.value,children:ne.label},ne.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:U,onChange:ne=>G(ne.target.checked)}),"Enabled"]}),t.jsx("small",{children:"When disabled, the routine will not run automatically"})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,disabled:Le,children:"Cancel"}),t.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:Le,children:Le?"Saving…":l?"Save Changes":"Create Routine"})]})]})}const uP=3e4;function mP({onClose:e,addToast:n,projectId:s}){const[i,r]=a.useState(()=>s?"project":"global"),[o,l]=a.useState([]),[c,u]=a.useState("list"),[d,m]=a.useState(),[h,f]=a.useState(null),[p,g]=a.useState({}),b=a.useRef(null);di(b,!0,"fusion:automation-modal-size");const v=a.useMemo(()=>({scope:i,projectId:i==="project"?s:void 0}),[i,s]),x=a.useCallback(async()=>{try{const M=await dj(v);l(M),g(T=>{const D={...T};for(const K of M){const J=D[K.id];if(!J||!K.lastRunResult)continue;const te=K.lastRunResult;te.success===J.success&&(te.output||"")===J.output&&(te.error||"")===(J.error||"")&&delete D[K.id]}return D})}catch(M){n(ke(M)||"Failed to load routines","error")}},[n,v]);a.useEffect(()=>{x()},[x]),a.useEffect(()=>{const M=setInterval(()=>{x()},uP);return()=>clearInterval(M)},[x]),a.useEffect(()=>{const M=T=>{T.key==="Escape"&&(c!=="list"?(u("list"),m(void 0)):e())};return document.addEventListener("keydown",M),()=>document.removeEventListener("keydown",M)},[e,c]);const y=Mi(e),j=a.useCallback(async M=>{try{await uj(M,v),n("Routine created","success"),u("list"),await x()}catch(T){n(ke(T)||"Failed to create routine","error")}},[n,x,v]),E=a.useCallback(M=>{m(M),u("edit")},[]),C=a.useCallback(async M=>{if(d)try{await pu(d.id,M,v),n("Routine updated","success"),u("list"),m(void 0),await x()}catch(T){n(ke(T)||"Failed to update routine","error")}},[d,n,x,v]),w=a.useCallback(async M=>{try{await mj(M.id,v),n(`Deleted "${M.name}"`,"success"),await x()}catch(T){n(ke(T)||"Failed to delete routine","error")}},[n,x,v]),R=a.useCallback(async M=>{f(M.id);try{const{result:T}=await hj(M.id,v);g(D=>({...D,[M.id]:{output:T.output||"",error:T.error,success:T.success}})),T.success?n(`"${M.name}" completed successfully`,"success"):n(`"${M.name}" failed: ${T.error||"Unknown error"}`,"error"),await x()}catch(T){n(ke(T)||"Failed to run routine","error")}finally{f(null)}},[n,x,v]),S=a.useCallback(async M=>{try{await pu(M.id,{enabled:!M.enabled},v),n(`"${M.name}" ${M.enabled?"disabled":"enabled"}`,"success"),await x()}catch(T){n(ke(T)||"Failed to toggle routine","error")}},[n,x,v]),O=a.useCallback(()=>{u("list"),m(void 0)},[]);a.useEffect(()=>{c!=="list"&&g({})},[c]);const _=a.useCallback(M=>{r(M),u("list"),m(void 0),g({})},[]),P=()=>c==="create"?t.jsx(zh,{onSubmit:j,onCancel:O,scope:i,projectId:s}):c==="edit"&&d?t.jsx(zh,{routine:d,onSubmit:C,onCancel:O,scope:i,projectId:s}):o.length===0?t.jsxs("div",{className:"routine-empty-state",children:[t.jsx(es,{size:48,strokeWidth:1}),t.jsx("h4",{children:"No automations yet"}),t.jsx("p",{children:"Create an automation with a schedule, webhook, API, or manual trigger."}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>u("create"),children:[t.jsx(dn,{size:14}),"Create your first automation"]})]}):t.jsx("div",{className:"routine-list",children:o.map(M=>t.jsx(ZT,{routine:M,onEdit:E,onDelete:w,onRun:R,onToggle:S,running:h===M.id,lastRunOutput:p[M.id]??null},M.id))}),U=()=>P(),G=c==="list"&&o.length>0;return t.jsx("div",{className:"modal-overlay open",...y,children:t.jsxs("div",{ref:b,className:"modal modal-lg automation-modal",role:"dialog","aria-modal":"true","aria-labelledby":"schedules-modal-title",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(es,{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(qt,{size:20})})]}),t.jsxs("div",{className:"scheduling-toolbar","aria-live":"polite",children:[t.jsxs("div",{className:"scheduling-toolbar-left",role:"group","aria-label":"Scheduling scope",children:[t.jsxs("div",{className:"scheduling-scope-selector",children:[t.jsxs("button",{type:"button",className:`scope-btn${i==="global"?" active":""}`,onClick:()=>_("global"),"aria-pressed":i==="global",title:"Global (user-level) automations",children:[t.jsx(nl,{size:14}),"Global"]}),t.jsxs("button",{type:"button",className:`scope-btn${i==="project"?" active":""}`,onClick:()=>_("project"),"aria-pressed":i==="project",title:"Project-scoped automations",children:[t.jsx(ts,{size:14}),"Project"]})]}),t.jsxs("span",{className:"scheduling-count",children:[t.jsx(es,{size:14}),o.length," automation",o.length===1?"":"s"]})]}),t.jsx("div",{className:"scheduling-toolbar-right",children:G&&t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>u("create"),"aria-label":"Create new automation",children:[t.jsx(dn,{size:14}),"New Automation"]})})]}),t.jsx("div",{className:"schedule-modal-content",id:"scheduled-tasks-content",children:U()})]})})}const hP=3e4,cd=new Map,jc=new Map;function Oh(e){return e??"default"}function Fh(e){const n=cd.get(e);return n?Date.now()>=n.expiresAt?(cd.delete(e),null):n:null}function pP(e,n){const s=e.some(r=>r.id!=="github"&&r.authenticated),i=e.some(r=>r.id==="github"&&r.authenticated)||(n?.authenticated??!1);return{hasAiProvider:s,hasGithub:i}}async function fP(e){const n=jc.get(e);if(n)return n;const s=Er().then(({providers:i,ghCli:r})=>{const l={...pP(i,r),ghCli:r,expiresAt:Date.now()+hP};return cd.set(e,l),l}).finally(()=>{jc.delete(e)});return jc.set(e,s),s}function Fg(e){const n=Oh(e),s=Fh(n),[i,r]=a.useState(s?.hasAiProvider??!1),[o,l]=a.useState(s?.hasGithub??!1),[,c]=a.useState(s?.ghCli),[u,d]=a.useState(s==null),m=a.useRef(!!s);return a.useEffect(()=>{let h=!1;const f=Oh(e),p=Fh(f);if(p)return r(p.hasAiProvider),l(p.hasGithub),c(p.ghCli),d(!1),m.current=!0,()=>{h=!0};m.current=!1;async function g(){!m.current&&d(!0);try{const v=await fP(f);if(h)return;r(v.hasAiProvider),l(v.hasGithub),c(v.ghCli)}catch{}finally{h||(m.current=!0,d(!1))}}return g(),()=>{h=!0}},[e]),a.useMemo(()=>({hasAiProvider:i,hasGithub:o,loading:u,hasWarnings:!i||!o}),[i,o,u])}function Ug({hasAiProvider:e,hasGithub:n,compact:s=!1,onDismiss:i}){if(e&&n)return null;const r=i?t.jsx("button",{type:"button",className:"setup-warning-banner__dismiss touch-target","aria-label":"Dismiss setup warning",onClick:i,children:t.jsx(qt,{size:16,"aria-hidden":"true"})}):null;if(s)return t.jsxs("div",{className:`setup-warning-banner setup-warning-banner--compact${i?" setup-warning-banner--dismissible":""}`,role:"status","aria-live":"polite",children:[t.jsx("p",{className:"setup-warning-banner__compact-text",children:"⚠ Setup incomplete — AI and/or GitHub features will be limited."}),r]});const o=[];return e||o.push({key:"ai",title:"No AI provider connected",description:"AI agents won't be able to work on tasks until you connect a provider. Set one up in Settings → AI Setup."}),n||o.push({key:"github",title:"GitHub not connected",description:"You won't be able to import issues from GitHub, but you can still create tasks manually."}),t.jsxs("div",{className:`setup-warning-banner${i?" setup-warning-banner--dismissible":""}`,role:"status","aria-live":"polite",children:[r,o.map(l=>t.jsxs("div",{className:"setup-warning-banner__item",children:[t.jsx("strong",{className:"setup-warning-banner__title",children:l.title}),t.jsx("p",{className:"setup-warning-banner__description",children:l.description})]},l.key))]})}function gP({isOpen:e,onClose:n,projectId:s,tasks:i,onCreateTask:r,addToast:o,onPlanningMode:l,onSubtaskBreakdown:c}){const{confirm:u}=Gs(),[d,m]=a.useState(""),[h,f]=a.useState([]),[p,g]=a.useState([]),[b,v]=a.useState(!1),[x,y]=a.useState(""),[j,E]=a.useState(""),[C,w]=a.useState(""),[R,S]=a.useState(""),[O,_]=a.useState(""),[P,U]=a.useState("default"),[G,M]=a.useState(!1),[T,D]=a.useState([]),[K,J]=a.useState(!1),[te,N]=a.useState(void 0),[z,I]=a.useState(_s),[k,H]=a.useState(void 0),[Q,ue]=a.useState(null),[be,V]=a.useState([]),[ve,B]=a.useState(!1),[Y,X]=a.useState(!1),he=a.useRef(null),[de,me]=a.useState(!1),[se,_e]=a.useState(""),Fe=a.useRef(null),{hasAiProvider:Te,hasGithub:st,loading:nt}=Fg(s),{nodes:qe}=ml(),Xe=a.useCallback(xe=>{J(!0),D(xe)},[]),$e=a.useCallback(()=>{J(!1)},[]),Ue=a.useCallback(async()=>{if(be.length>0){B(!0);return}X(!0);try{const xe=await Ia(void 0,s);V(xe),B(!0)}catch(xe){const ce=ke(xe);o(ce?`Failed to load agents: ${ce}`:"Failed to load agents","error"),B(!1)}finally{X(!1)}},[be.length,s,o]);a.useEffect(()=>{if(!ve)return;const xe=ce=>{he.current&&!he.current.contains(ce.target)&&B(!1)};return document.addEventListener("mousedown",xe),()=>document.removeEventListener("mousedown",xe)},[ve]),a.useEffect(()=>{if(!de)return;const xe=ce=>{Fe.current&&!Fe.current.contains(ce.target)&&(me(!1),_e(""))};return document.addEventListener("mousedown",xe),()=>document.removeEventListener("mousedown",xe)},[de]);const oe=i.filter(xe=>!h.includes(xe.id)).sort((xe,ce)=>{const Pe=ce.createdAt.localeCompare(xe.createdAt);if(Pe!==0)return Pe;const pe=parseInt(xe.id.slice(xe.id.lastIndexOf("-")+1),10)||0;return(parseInt(ce.id.slice(ce.id.lastIndexOf("-")+1),10)||0)-pe}),je=se?oe.filter(xe=>xe.id.toLowerCase().includes(se.toLowerCase())||xe.title&&xe.title.toLowerCase().includes(se.toLowerCase())||xe.description&&xe.description.toLowerCase().includes(se.toLowerCase())):oe,ie=(xe,ce)=>xe.length>ce?xe.slice(0,ce)+"…":xe;a.useEffect(()=>{const xe=d.trim()!==""||h.length>0||p.length>0||x!==""||j!==""||C!==""||R!==""||T.length>0||Q!==null||te!==void 0||z!==_s||k!==void 0;M(xe)},[d,h,p,x,j,C,R,T,Q,te,z,k]);const Ae=a.useCallback(async()=>{G&&!await u({title:"Discard Changes",message:"You have unsaved changes. Discard them?",danger:!0})||(p.forEach(xe=>URL.revokeObjectURL(xe.previewUrl)),g([]),m(""),f([]),y(""),E(""),w(""),S(""),_(""),U("default"),D([]),J(!1),ue(null),B(!1),N(void 0),I(_s),H(void 0),M(!1),n())},[G,n,p,u]),Le=a.useCallback(async()=>{const xe=d.trim();if(!(!xe||b)){v(!0);try{const ce=x.indexOf("/"),Pe=j.indexOf("/"),pe=C.indexOf("/"),Re=await r({title:void 0,description:xe,column:"triage",dependencies:h.length?h:void 0,enabledWorkflowSteps:K?T.length>0?T:[]:void 0,...Q?{assignedAgentId:Q}:{},modelPresetId:P==="preset"&&O||void 0,modelProvider:x&&ce!==-1?x.slice(0,ce):void 0,modelId:x&&ce!==-1?x.slice(ce+1):void 0,validatorModelProvider:j&&Pe!==-1?j.slice(0,Pe):void 0,validatorModelId:j&&Pe!==-1?j.slice(Pe+1):void 0,planningModelProvider:C&&pe!==-1?C.slice(0,pe):void 0,planningModelId:C&&pe!==-1?C.slice(pe+1):void 0,thinkingLevel:R!==""?R:void 0,reviewLevel:te,priority:z,nodeId:k});if(p.length>0){const Qe=[];for(const Ie of p)try{await Cr(Re.id,Ie.file,s)}catch{Qe.push(Ie.file.name)}Qe.length>0&&o(`Failed to upload: ${Qe.join(", ")}`,"error")}p.forEach(Qe=>URL.revokeObjectURL(Qe.previewUrl)),g([]),m(""),f([]),y(""),E(""),w(""),S(""),_(""),U("default"),D([]),J(!1),ue(null),B(!1),N(void 0),I(_s),H(void 0),o(`Created ${Re.id}`,"success"),n()}catch(ce){o(ke(ce)||"Failed to create task","error")}finally{v(!1)}}},[d,h,p,x,j,C,R,b,r,o,n,s,P,O,T,K,Q,te,z,k]),we=a.useCallback(xe=>{xe.key==="Escape"&&(xe.preventDefault(),Ae())},[Ae]),Ve=(Q?be.find(xe=>xe.id===Q):void 0)?.name??Q,rt=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:Fe,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>me(xe=>!xe),disabled:b,"data-testid":"dep-trigger",children:h.length>0?`${h.length} selected`:"Add dependencies"}),de&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:se,onChange:xe=>_e(xe.target.value),onClick:xe=>xe.stopPropagation()}),je.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):je.map(xe=>t.jsxs("div",{className:`dep-dropdown-item${h.includes(xe.id)?" selected":""}`,onClick:()=>{f(h.includes(xe.id)?h.filter(ce=>ce!==xe.id):[...h,xe.id]),me(!1),_e("")},onMouseDown:ce=>ce.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:xe.id}),t.jsx("span",{className:"dep-dropdown-title",children:ie(xe.title||xe.description||xe.id,30)})]},xe.id))]})]}),h.length>0&&t.jsx("div",{className:"selected-deps",children:h.map(xe=>t.jsxs("span",{className:"dep-chip",children:[xe,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>f(h.filter(ce=>ce!==xe)),disabled:b,children:"×"})]},xe))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Assign Agent"}),t.jsxs("div",{className:"agent-trigger-wrap",ref:he,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{ve?B(!1):Ue()},disabled:b,"data-testid":"new-task-agent-button",children:[t.jsx(En,{size:12,style:{verticalAlign:"middle"}}),Ve?` ${Ve}`:" Assign agent"]}),ve&&t.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:xe=>xe.preventDefault(),children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),Y&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!Y&&be.filter(xe=>xe.state!=="terminated").map(xe=>t.jsxs("div",{className:`dep-dropdown-item${Q===xe.id?" selected":""}`,onMouseDown:ce=>ce.preventDefault(),onClick:()=>{ue(xe.id===Q?null:xe.id),B(!1)},"data-testid":`agent-option-${xe.id}`,children:[t.jsx(En,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:xe.role}),t.jsx("span",{className:"dep-dropdown-title",children:xe.name})]},xe.id)),!Y&&be.filter(xe=>xe.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),Q&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:xe=>xe.preventDefault(),onClick:()=>{ue(null),B(!1)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return e?t.jsx("div",{className:"modal-overlay open",onClick:Ae,onKeyDown:we,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:xe=>xe.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:"New Task"}),t.jsx("button",{className:"modal-close",onClick:Ae,disabled:b,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!nt&&t.jsx(Ug,{hasAiProvider:Te,hasGithub:st}),t.jsx(Ag,{mode:"create",description:d,onDescriptionChange:m,dependencies:h,onDependenciesChange:f,executorModel:x,onExecutorModelChange:y,validatorModel:j,onValidatorModelChange:E,presetMode:P,onPresetModeChange:U,selectedPresetId:O,onSelectedPresetIdChange:_,selectedWorkflowSteps:T,onWorkflowStepsChange:Xe,onDefaultOnApplied:$e,pendingImages:p,onImagesChange:g,tasks:i,projectId:s,disabled:b,addToast:o,isActive:e,onPlanningMode:l,onSubtaskBreakdown:c,onClose:Ae,planningModel:C,onPlanningModelChange:w,thinkingLevel:R,onThinkingLevelChange:S,reviewLevel:te,onReviewLevelChange:N,priority:z,onPriorityChange:I,nodeId:k,onNodeIdChange:H,nodeOptions:qe,renderBelowPrimary:rt,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:Ae,disabled:b,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Le,disabled:!d.trim()||b,children:b?"Creating...":"Create Task"})]})]})}):null}function Hs(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 Uh(e,n){return!Number.isFinite(e)||!Number.isFinite(n)||n<=0?"—":`${(e/n*100).toFixed(1)}%`}function bP(e,n){if(n<=0)return"normal";const s=e/n;return s>=.85?"critical":s>=.65?"warning":"normal"}function xP(e,n){if(n<=0)return"normal";const s=e/n;return s>=.5?"critical":s>=.25?"warning":"normal"}function vP(e,n){if(n<=0)return"normal";const s=e/n;return s>=.9?"critical":s>=.75?"warning":"normal"}function kc(e){return e==="critical"?"system-stats-modal__value--critical":e==="warning"?"system-stats-modal__value--warning":""}function yP(e){if(!e)return"Not yet";const n=new Date(e);return Number.isNaN(n.getTime())?"Not yet":n.toLocaleString()}function wP({isOpen:e,onClose:n,projectId:s}){const[i,r]=a.useState(null),[o,l]=a.useState(!1),[c,u]=a.useState(null),[d,m]=a.useState(!0),[h,f]=a.useState(90),[p,g]=a.useState(!1),[b,v]=a.useState(!1),[x,y]=a.useState(null),[j,E]=a.useState(null),[C,w]=a.useState(null),R=a.useCallback(async H=>{l(!0);try{const Q=await Oj(s);r(Q),u(null),w(Date.now()),H?.preserveKillResult||y(null)}catch(Q){u(Q instanceof Error?Q.message:"Failed to load system stats")}finally{l(!1)}},[s]);a.useEffect(()=>{if(!e)return;R();const H=window.setInterval(()=>{R()},5e3);return()=>{window.clearInterval(H)}},[e,R]),a.useEffect(()=>{if(!e)return;(async()=>{try{const Q=await Yi();m(Q.vitestAutoKillEnabled??!0),f(Q.vitestKillThresholdPct??90),E(null)}catch(Q){E(Q instanceof Error?Q.message:"Failed to load vitest settings")}})()},[e]),a.useEffect(()=>{if(!e)return;const H=Q=>{Q.key==="Escape"&&n()};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[e,n]);const S=a.useMemo(()=>{if(!i)return[];const H=i.systemStats,Q=kc(bP(H.heapUsed,H.heapLimit)),ue=kc(xP(H.rss,H.systemTotalMem));return[{label:"RSS",value:Hs(H.rss),detail:Uh(H.rss,H.systemTotalMem),className:ue},{label:"Heap Used",value:Hs(H.heapUsed),detail:`of ${Hs(H.heapTotal)}`,className:Q},{label:"Heap Limit",value:Hs(H.heapLimit),detail:"V8 limit"},{label:"External",value:Hs(H.external)},{label:"Array Buffers",value:Hs(H.arrayBuffers)}]},[i]),O=a.useCallback(async H=>{m(H);try{await bn({vitestAutoKillEnabled:H}),E(null)}catch(Q){E(Q instanceof Error?Q.message:"Failed to save vitest settings")}},[]),_=a.useCallback(async H=>{const Q=Math.min(99,Math.max(50,Number.isFinite(H)?Math.round(H):90));f(Q);try{await bn({vitestKillThresholdPct:Q}),E(null)}catch(ue){E(ue instanceof Error?ue.message:"Failed to save vitest settings")}},[]),P=a.useCallback(async()=>{if(!p){if(!b){v(!0);return}g(!0);try{const H=await Fj(s);y(H),v(!1),await R({preserveKillResult:!0})}catch(H){u(H instanceof Error?H.message:"Failed to kill vitest processes")}finally{g(!1)}}},[b,p,R,s]);if(!e)return null;const U=i?.systemStats,G=o&&!!i,M=C?`Updated ${new Date(C).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`:"Waiting for first update",T=i?.taskStats,D=U?U.systemTotalMem-U.systemFreeMem:0,K=U?vP(D,U.systemTotalMem):"normal",J=U?kc(K):"",te=U&&Number.isFinite(U.systemTotalMem)&&U.systemTotalMem>0?Math.max(0,Math.min(100,D/U.systemTotalMem*100)):0,N=U?`System memory used: ${te.toFixed(1)}% (${Hs(D)} of ${Hs(U.systemTotalMem)})`:"System memory usage unavailable",z=i?.vitestProcessCount,I=x?x.killed>0?"system-stats-modal__kill-result system-stats-modal__kill-result--success":"system-stats-modal__kill-result system-stats-modal__kill-result--error":"",k=yP(i?.vitestLastAutoKillAt);return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"system-stats-modal-title",onClick:H=>{H.target===H.currentTarget&&n()},"data-testid":"system-stats-modal-overlay",children:t.jsxs("div",{className:"modal modal-lg system-stats-modal","data-testid":"system-stats-modal",children:[t.jsxs("div",{className:"modal-header system-stats-modal__header",children:[t.jsxs("h2",{id:"system-stats-modal-title",className:"system-stats-modal__title",children:[t.jsx(kr,{}),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:M})]}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>void R(),title:"Refresh","aria-label":"Refresh system stats",children:t.jsx(Fn,{size:16,className:G?"system-stats-modal__refresh--spinning":void 0})}),t.jsx("button",{type:"button",className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(qt,{})})]})]}),o&&!i&&t.jsx("div",{className:"system-stats-modal__state",children:"Loading system stats…"}),c&&!i&&t.jsx("div",{className:"system-stats-modal__state system-stats-modal__state--error",role:"alert",children:c}),i&&t.jsxs("div",{className:"system-stats-modal__content",children:[t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Process stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Process"}),t.jsx("dl",{className:"system-stats-modal__grid",children:S.map(H=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:H.label}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${H.className}`.trim(),children:H.value}),H.detail?t.jsx("span",{className:"system-stats-modal__detail",children:H.detail}):null]})]},H.label))})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"CPU and load stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"CPU & Load"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Load Avg"}),t.jsx("dd",{children:U?.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:U?.cpuCount??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Platform"}),t.jsx("dd",{children:U?.platform??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Node"}),t.jsx("dd",{children:U?.nodeVersion??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"PID"}),t.jsx("dd",{children:U?.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 ${J}`.trim(),children:U?Hs(D):"—"}),t.jsx("span",{className:"system-stats-modal__detail",children:U?`${Uh(D,U.systemTotalMem)} of ${Hs(U.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--${K}`,role:"progressbar","aria-valuenow":Math.round(te),"aria-valuemin":0,"aria-valuemax":100,"aria-label":N,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${K}`,style:{width:`${te}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Memory Free"}),t.jsx("dd",{children:U?Hs(U.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:T?.total??0})]}),Object.entries(T?.byColumn??{}).map(([H,Q])=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:H}),t.jsx("dd",{children:Q})]},H))]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Agent stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Agents"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"idle"}),t.jsx("dd",{children:T?.agents.idle??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"active"}),t.jsx("dd",{children:T?.agents.active??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"running"}),t.jsx("dd",{children:T?.agents.running??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"error"}),t.jsx("dd",{children:T?.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(_v,{}),t.jsx("span",{children:"Vitest Controls"})]}),t.jsx("dl",{className:"system-stats-modal__grid system-stats-modal__vitest-controls",children:t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Vitest Processes"}),t.jsx("dd",{children:z??"—"})]})}),t.jsxs("div",{className:"system-stats-modal__vitest-controls",children:[t.jsx("div",{className:"system-stats-modal__kill-row",children:t.jsxs("button",{type:"button",className:"btn btn-danger",onClick:()=>void P(),disabled:p||z===0,children:[t.jsx(Tv,{}),t.jsx("span",{children:b?"Confirm Kill?":"Kill Vitest Processes"})]})}),t.jsxs("label",{className:"system-stats-modal__toggle-row",children:[t.jsx("input",{type:"checkbox",checked:d,onChange:H=>{O(H.target.checked)}}),t.jsx("span",{children:"Auto-kill vitest on memory pressure"})]}),t.jsxs("div",{className:"system-stats-modal__threshold-row",children:[t.jsx("label",{htmlFor:"vitest-threshold-number",children:"Kill threshold (%)"}),t.jsxs("div",{className:"system-stats-modal__threshold-controls",children:[t.jsx("input",{id:"vitest-threshold-range",type:"range",min:50,max:99,value:h,"aria-label":"Kill threshold slider (%)",onChange:H=>{const Q=Number.parseInt(H.target.value,10);_(Number.isNaN(Q)?90:Q)}}),t.jsx("input",{id:"vitest-threshold-number",type:"number",className:"input",min:50,max:99,value:h,"aria-label":"Kill threshold (%)",onChange:H=>{const Q=Number.parseInt(H.target.value,10);_(Number.isNaN(Q)?90:Q)},onBlur:()=>{_(h)}})]})]}),x&&t.jsxs("p",{className:I,children:["Killed ",x.killed," processes"]}),t.jsxs("p",{className:"system-stats-modal__last-kill",children:["Last auto-kill: ",k]}),j&&t.jsx("p",{className:"system-stats-modal__kill-result system-stats-modal__kill-result--error",children:j})]})]})]}),c&&i&&t.jsxs("div",{className:"system-stats-modal__footer-error",children:["Latest refresh failed: ",c]})]})})}const jP=5e3;function kP(e={}){const{projectId:n,type:s,limit:i=50,autoRefresh:r=!0,useCentralFeed:o=!1}=e,[l,c]=a.useState([]),[u,d]=a.useState(!1),[m,h]=a.useState(null),[f,p]=a.useState(!1),g=a.useRef(null),b=a.useRef(void 0),v=a.useCallback(async()=>{try{d(!0),h(null);let j;o?j=await wu({limit:i,projectId:n,type:s}):j=(await fu({limit:i,type:s,projectId:n})).map(C=>({...C,projectId:n??"",projectName:""})),c(j),p(j.length===i),j.length>0&&(b.current=j[j.length-1].timestamp)}catch(j){h(j instanceof Error?j.message:"Failed to load activity log")}finally{d(!1)}},[i,n,s,o]),x=a.useCallback(async()=>{if(b.current)try{d(!0);let j;o?j=await wu({limit:i,projectId:n,type:s,since:b.current}):j=(await fu({limit:i,type:s,since:b.current,projectId:n})).map(C=>({...C,projectId:n??"",projectName:""})),c(E=>[...E,...j]),p(j.length===i),j.length>0&&(b.current=j[j.length-1].timestamp)}catch(j){h(j instanceof Error?j.message:"Failed to load more entries")}finally{d(!1)}},[i,n,s,o]),y=a.useCallback(()=>{c([]),p(!1),b.current=void 0},[]);return a.useEffect(()=>{v()},[v]),a.useEffect(()=>{if(r)return g.current=setInterval(()=>{v()},jP),()=>{g.current&&(clearInterval(g.current),g.current=null)}},[r,v]),{entries:l,loading:u,error:m,refresh:v,clear:y,hasMore:f,loadMore:x}}const Nc={"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"},NP={"task:created":t.jsx(dn,{size:14,className:"activity-icon created"}),"task:moved":t.jsx(Dr,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx(Fn,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(qt,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx(Nn,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(Lr,{size:14,className:"activity-icon failed"}),"settings:updated":t.jsx(br,{size:14,className:"activity-icon settings"})};function SP(e){const n=new Date(e),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),o=Math.floor(i/36e5),l=Math.floor(i/864e5);return r<1?"Just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function CP({isOpen:e,onClose:n,tasks:s,onOpenTaskDetail:i,projectId:r,projects:o=[],onProjectFilterChange:l,currentProject:c}){const[u,d]=a.useState("all"),[m,h]=a.useState(r||"all"),[f,p]=a.useState(!1);a.useEffect(()=>{h(r||"all")},[r]);const g=u==="all"?void 0:u,b=m==="all"?void 0:m,v=!c&&o.length>0,{entries:x,loading:y,error:j,refresh:E,hasMore:C}=kP({projectId:b,type:g,limit:100,autoRefresh:e,useCentralFeed:v}),w=x.map(P=>({id:P.id,timestamp:P.timestamp,type:P.type,taskId:P.taskId,taskTitle:P.taskTitle,details:P.details,metadata:P.metadata,projectId:P.projectId,projectName:P.projectName})),R=async()=>{try{await pj(),E(),p(!1)}catch{p(!1)}},S=P=>{i&&i(P)},O=P=>{h(P),l?.(P==="all"?void 0:P)};a.useEffect(()=>{if(!e)return;const P=U=>{U.key==="Escape"&&(f?p(!1):n())};return document.addEventListener("keydown",P),()=>document.removeEventListener("keydown",P)},[e,n,f]);const _=u!=="all"||m!=="all";return e?t.jsx("div",{className:"modal-overlay open",onClick:P=>{P.target===P.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(jr,{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(ts,{size:14}),t.jsxs("select",{value:m,onChange:P=>O(P.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[t.jsx("option",{value:"all",children:"All Projects"}),o.map(P=>t.jsx("option",{value:P.id,children:P.name},P.id))]})]}),t.jsxs("div",{className:"activity-log-filter",children:[t.jsx(Lo,{size:14}),t.jsxs("select",{value:u,onChange:P=>d(P.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:"All Events"}),Object.entries(Nc).map(([P,U])=>t.jsx("option",{value:P,children:U},P))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>E(),title:"Refresh","data-testid":"activity-refresh",children:y?t.jsx(lt,{size:14,className:"spin"}):t.jsx(Fn,{size:14})}),w.length>0&&t.jsx("button",{className:"activity-log-clear",onClick:()=>p(!0),title:"Clear Log","data-testid":"activity-clear",children:t.jsx(cn,{size:14})})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",title:"Close","data-testid":"activity-close",children:"×"})]}),_&&t.jsxs("div",{className:"activity-log-active-filters",children:[t.jsx("span",{className:"activity-log-filter-label",children:"Active filters:"}),m!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Project: ",o.find(P=>P.id===m)?.name||m]}),u!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",Nc[u]]}),t.jsx("button",{className:"activity-log-clear-filters",onClick:()=>{d("all"),h("all"),l?.(void 0)},children:"Clear all"})]}),t.jsxs("div",{className:"activity-log-content","data-testid":"activity-log-content",children:[j&&t.jsxs("div",{className:"activity-log-error","data-testid":"activity-error",children:[t.jsx(gs,{size:16}),t.jsx("span",{children:j})]}),w.length===0&&!y&&!j&&t.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[t.jsx(jr,{size:48,className:"activity-log-empty-icon"}),t.jsx("p",{children:_?"No activity matches the current filters":"No activity recorded yet"}),_&&t.jsx("button",{className:"btn btn-secondary",onClick:()=>{d("all"),h("all"),l?.(void 0)},children:"Clear Filters"})]}),t.jsx("div",{className:"activity-log-list",children:w.map(P=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:NP[P.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:Nc[P.type]}),t.jsx("span",{className:"activity-log-entry-time",children:SP(P.timestamp)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[P.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>S(P.taskId),"data-testid":"activity-task-link",children:P.taskId}),P.taskTitle&&t.jsx("span",{className:"activity-log-task-title",children:P.taskTitle}),t.jsx("span",{className:"activity-log-entry-text",children:P.details})]}),P.metadata&&Object.keys(P.metadata).length>0&&t.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof P.metadata.from=="string"&&typeof P.metadata.to=="string"&&t.jsxs("span",{className:"activity-log-metadata-item",children:[P.metadata.from," → ",P.metadata.to]}),typeof P.metadata.merged=="boolean"&&t.jsx("span",{className:`activity-log-metadata-item ${P.metadata.merged?"success":"error"}`,children:P.metadata.merged?"Merged":"Not merged"})]})]})]},P.id))}),C&&!y&&t.jsx("button",{className:"activity-log-load-more",onClick:E,"data-testid":"activity-load-more",children:"Load More"}),y&&w.length>0&&t.jsx("div",{className:"activity-log-loading",children:t.jsx(lt,{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:R,children:"Clear Log"})]})]})})]})}):null}const ar=[{id:"status",label:"Status",icon:Mp},{id:"changes",label:"Changes",icon:$c},{id:"commits",label:"Commits",icon:zr},{id:"branches",label:"Branches",icon:Ks},{id:"worktrees",label:"Worktrees",icon:Px},{id:"stashes",label:"Stashes",icon:Ir},{id:"remotes",label:"Remotes",icon:Cp}];function Bh({status:e}){switch(e){case"added":case"untracked":return t.jsx(px,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(Np,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(ux,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return t.jsx(Hi,{size:14,className:"gm-file-icon gm-file-renamed"});default:return t.jsx(gx,{size:14,className:"gm-file-icon"})}}function Hh({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 EP(e){return a.useCallback(async(n,s)=>{try{await navigator.clipboard.writeText(n),e(`Copied ${s||"to clipboard"}`,"success")}catch{e("Failed to copy","error")}},[e])}function Ca(e){if(!e)return"—";const n=new Date(e);if(isNaN(n.getTime()))return"—";const i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4);if(r<1)return"just now";if(r<60)return`${r}m ago`;const o=Math.floor(r/60);if(o<24)return`${o}h ago`;const l=Math.floor(o/24);return l<30?`${l}d ago`:n.toLocaleDateString()}function _P({isOpen:e,onClose:n,tasks:s,addToast:i,projectId:r}){const o=Gs(),[l,c]=a.useState("status"),[u,d]=a.useState(!1),[m,h]=a.useState(null),f=a.useRef(null);di(f,e,"fusion:git-modal-size");const p=Mi(n),g=EP(i),[b,v]=a.useState(null),[x,y]=a.useState([]),[j,E]=a.useState(new Set),[C,w]=a.useState(""),[R,S]=a.useState(!1),[O,_]=a.useState(null),[P,U]=a.useState(!1),[G,M]=a.useState(null),[T,D]=a.useState(null),K=a.useRef(0),[J,te]=a.useState([]),[N,z]=a.useState(null),[I,k]=a.useState(null),[H,Q]=a.useState(!1),[ue,be]=a.useState(20),[V,ve]=a.useState(""),[B,Y]=a.useState([]),[X,he]=a.useState(""),[de,me]=a.useState(""),[se,_e]=a.useState(""),[Fe,Te]=a.useState(null),[st,nt]=a.useState([]),[qe,Xe]=a.useState(!1),[$e,Ue]=a.useState(null),[oe,je]=a.useState(null),[ie,Ae]=a.useState(!1),[Le,we]=a.useState([]),[Ee,Ve]=a.useState([]),[rt,xe]=a.useState(""),[ce,Pe]=a.useState(null),[pe,Re]=a.useState(null),[Qe,Ie]=a.useState(null),bt=a.useCallback(async()=>{if(e){d(!0),h(null);try{switch(l){case"status":{const fe=await Bs(r);v(fe);break}case"changes":{const[fe,Oe]=await Promise.all([Bs(r),aa(r)]);v(fe),y(Oe),E(new Set),D(null),_(null),M(null);break}case"commits":{const fe=await vw(ue,r);te(fe);break}case"branches":{const[fe,Oe]=await Promise.all([Va(r),Bs(r)]);Y(fe),v(Oe);break}case"worktrees":{const fe=await kw(r);we(fe);break}case"stashes":{const fe=await ao(r);Ve(fe);break}case"remotes":{const fe=await Bs(r);v(fe);break}}}catch(fe){h(ke(fe)||"Failed to fetch git data"),i(ke(fe)||"Failed to fetch git data","error")}finally{d(!1)}}},[l,e,ue,i,r]);a.useEffect(()=>{e&&bt()},[bt,e]),a.useEffect(()=>{if(!e)return;const fe=Oe=>{if(Oe.key==="Escape"){n();return}if((Oe.key==="ArrowUp"||Oe.key==="ArrowDown")&&Oe.altKey){Oe.preventDefault();const ut=ar.findIndex(L=>L.id===l);Oe.key==="ArrowUp"&&ut>0?c(ar[ut-1].id):Oe.key==="ArrowDown"&&ut<ar.length-1&&c(ar[ut+1].id)}};return document.addEventListener("keydown",fe),()=>document.removeEventListener("keydown",fe)},[e,n,l]);const ee=a.useCallback(async fe=>{try{await du(fe,r),i(`Staged ${fe.length} file(s)`,"success");const Oe=await aa(r);y(Oe),E(new Set),D(null),_(null),M(null)}catch(Oe){i(ke(Oe)||"Failed to stage files","error")}},[i,r]),re=a.useCallback(async fe=>{try{await Pw(fe,r),i(`Unstaged ${fe.length} file(s)`,"success");const Oe=await aa(r);y(Oe),E(new Set),D(null),_(null),M(null)}catch(Oe){i(ke(Oe)||"Failed to unstage files","error")}},[i,r]),Se=a.useCallback(async fe=>{if(await o.confirm({title:"Discard Changes",message:`Discard changes to ${fe.length} file(s)? This cannot be undone.`,danger:!0}))try{await Iw(fe,r),i(`Discarded changes to ${fe.length} file(s)`,"success");const[ut,L]=await Promise.all([aa(r),Bs(r)]);y(ut),v(L),E(new Set),D(null),_(null),M(null)}catch(ut){i(ke(ut)||"Failed to discard changes","error")}},[i,r,confirm]),ot=a.useCallback(async fe=>{if(fe.preventDefault(),!!C.trim()){S(!0);try{const Oe=await uu(C.trim(),r);i(`Committed: ${Oe.hash}`,"success"),w("");const[ut,L]=await Promise.all([aa(r),Bs(r)]);y(ut),v(L),D(null),_(null),M(null)}catch(Oe){i(ke(Oe)||"Failed to commit","error")}finally{S(!1)}}},[C,i,r]),ne=a.useCallback(async()=>{if(C.trim()){S(!0);try{const fe=x.filter(F=>!F.staged).map(F=>F.file);fe.length>0&&await du(fe,r);const Oe=await uu(C.trim(),r);i(`Committed: ${Oe.hash}`,"success"),w("");const[ut,L]=await Promise.all([aa(r),Bs(r)]);y(ut),v(L),D(null),_(null),M(null)}catch(fe){i(ke(fe)||"Failed to commit","error")}finally{S(!1)}}},[C,x,i,r]),Ze=a.useCallback(async(fe,Oe)=>{D({file:fe,staged:Oe}),U(!0),M(null);const ut=K.current+1;K.current=ut;try{const L=await Tw(fe,Oe,r);if(K.current!==ut)return;_(L)}catch(L){if(K.current!==ut)return;const F=ke(L)||"Failed to load file diff";_(null),M(F),i(F,"error")}finally{K.current===ut&&U(!1)}},[i,r]),ft=a.useCallback(fe=>{E(Oe=>{const ut=new Set(Oe);return ut.has(fe)?ut.delete(fe):ut.add(fe),ut})},[]),gt=a.useCallback(async fe=>{if(N===fe){z(null),k(null);return}z(fe),Q(!0);try{const Oe=await Uo(fe,r);k(Oe)}catch(Oe){i(ke(Oe)||"Failed to load diff","error"),k(null)}finally{Q(!1)}},[N,i,r]),St=a.useCallback(()=>{be(fe=>Math.min(fe+20,100))},[]),Nt=a.useMemo(()=>{if(!V.trim())return J;const fe=V.toLowerCase();return J.filter(Oe=>Oe.message.toLowerCase().includes(fe)||Oe.author.toLowerCase().includes(fe)||Oe.shortHash.toLowerCase().includes(fe))},[J,V]),pt=a.useCallback(async fe=>{if(fe.preventDefault(),!!X.trim()){d(!0);try{await Nw(X.trim(),de.trim()||void 0,r),i(`Created branch ${X}`,"success"),he(""),me("");const Oe=await Va(r);Y(Oe)}catch(Oe){i(ke(Oe)||"Failed to create branch","error")}finally{d(!1)}}},[X,de,i,r]),kt=a.useCallback(async fe=>{d(!0);try{await Sw(fe,r),i(`Switched to ${fe}`,"success");const[Oe,ut]=await Promise.all([Bs(r),Va(r)]);v(Oe),Y(ut)}catch(Oe){i(ke(Oe)||"Failed to checkout branch","error")}finally{d(!1)}},[i,r]),Ht=a.useCallback(async fe=>{if(await o.confirm({title:"Delete Branch",message:`Delete branch "${fe}"?`,danger:!0})){d(!0);try{await cu(fe,void 0,r),i(`Deleted branch ${fe}`,"success");const ut=await Va(r);Y(ut)}catch(ut){if(ke(ut).includes("not fully merged")){if(await o.confirm({title:"Force Delete Branch",message:"Branch has unmerged commits. Force delete?",danger:!0}))try{await cu(fe,!0,r),i(`Force deleted branch ${fe}`,"success");const F=await Va(r);Y(F)}catch(F){i(ke(F)||"Failed to delete branch","error")}}else i(ke(ut)||"Failed to delete branch","error")}finally{d(!1)}}},[i,r,confirm]),$t=a.useMemo(()=>{if(!se.trim())return B;const fe=se.toLowerCase();return B.filter(Oe=>Oe.name.toLowerCase().includes(fe))},[B,se]),Tt=a.useCallback(async fe=>{if(Fe===fe){Te(null),nt([]),Ue(null),je(null);return}Te(fe),nt([]),Ue(null),je(null),Xe(!0);try{const Oe=await jw(fe,10,r);nt(Oe)}catch{nt([])}finally{Xe(!1)}},[Fe,r]),Mt=a.useCallback(async fe=>{if($e===fe){Ue(null),je(null);return}Ue(fe),je(null),Ae(!0);try{const Oe=await Uo(fe,r);je(Oe)}catch{je(null)}finally{Ae(!1)}},[$e,r]),Ot=a.useCallback(()=>{Te(null),nt([]),Ue(null),je(null)},[]),zt=a.useCallback(async fe=>{fe.preventDefault(),Pe("create");try{await Mw(rt.trim()||void 0,r),i("Changes stashed","success"),xe("");const Oe=await ao(r);Ve(Oe)}catch(Oe){i(ke(Oe)||"Failed to stash changes","error")}finally{Pe(null)}},[rt,i,r]),Ft=a.useCallback(async(fe,Oe=!1)=>{Pe(`apply-${fe}`);try{await Aw(fe,Oe,r),i(Oe?"Stash popped":"Stash applied","success");const ut=await ao(r);Ve(ut)}catch(ut){i(ke(ut)||"Failed to apply stash","error")}finally{Pe(null)}},[i,r]),Et=a.useCallback(async fe=>{if(await o.confirm({title:"Drop Stash",message:`Drop stash@{${fe}}? This cannot be undone.`,danger:!0})){Pe(`drop-${fe}`);try{await Rw(fe,r),i("Stash dropped","success");const ut=await ao(r);Ve(ut)}catch(ut){i(ke(ut)||"Failed to drop stash","error")}finally{Pe(null)}}},[i,r,confirm]),Pt=a.useCallback(async()=>{Re("fetch");try{const fe=await Cw(void 0,r);Ie(fe),i(fe.message||"Fetch completed",fe.fetched?"success":"info");const Oe=await Bs(r);v(Oe)}catch(fe){i(ke(fe)||"Fetch failed","error")}finally{Re(null)}},[i,r]),Dt=a.useCallback(async()=>{Re("pull");try{const fe=await Ew(r);Ie(fe),fe.conflict?i("Merge conflict detected. Resolve manually.","error"):i(fe.message||"Pull completed","success");const Oe=await Bs(r);v(Oe)}catch(fe){i(ke(fe)||"Pull failed","error")}finally{Re(null)}},[i,r]),Wt=a.useCallback(async()=>{Re("push");try{const fe=await _w(r);Ie(fe),i(fe.message||"Push completed","success");const Oe=await Bs(r);v(Oe)}catch(fe){i(ke(fe)||"Push failed","error")}finally{Re(null)}},[i,r]),It=a.useMemo(()=>x.filter(fe=>fe.staged),[x]),Rt=a.useMemo(()=>x.filter(fe=>!fe.staged),[x]);return e?t.jsx("div",{className:"modal-overlay open",...p,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal gm-modal",ref:f,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h3",{children:[t.jsx(Dc,{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:bt,disabled:u,title:"Refresh",children:t.jsx(Fn,{size:14,className:u?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(qt,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:ar.map(fe=>{const Oe=fe.icon;return t.jsxs("button",{role:"tab","aria-selected":l===fe.id,className:`gm-nav-item${l===fe.id?" active":""}`,onClick:()=>c(fe.id),children:[t.jsx(Oe,{size:16}),t.jsx("span",{className:"gm-nav-label",children:fe.label})]},fe.id)})}),t.jsxs("div",{className:"gm-content",role:"tabpanel",children:[u&&t.jsxs("div",{className:"gm-loading",children:[t.jsx(lt,{size:24,className:"spin"}),t.jsx("span",{children:"Loading..."})]}),m&&!u&&t.jsxs("div",{className:"gm-error",children:[t.jsx(gs,{size:18}),t.jsx("span",{children:m}),t.jsx("button",{className:"btn btn-sm",onClick:bt,children:"Retry"})]}),l==="status"&&!u&&b&&t.jsx(MP,{status:b,copyToClipboard:g}),l==="changes"&&!u&&t.jsx(AP,{status:b,stagedFiles:It,unstagedFiles:Rt,selectedFiles:j,toggleFileSelection:ft,onStageFiles:ee,onUnstageFiles:re,onDiscardChanges:Se,onSelectDiffFile:Ze,selectedDiffTarget:T,changeDiff:O,loadingChangeDiff:P,changeDiffError:G,commitMessage:C,setCommitMessage:w,onCommit:ot,onStageAllAndCommit:ne,committing:R}),l==="commits"&&!u&&t.jsx(RP,{commits:Nt,commitSearch:V,setCommitSearch:ve,selectedCommit:N,commitDiff:I,loadingDiff:H,onCommitClick:gt,onLoadMore:St,canLoadMore:J.length>=ue&&ue<100,copyToClipboard:g}),l==="branches"&&!u&&t.jsx(TP,{branches:$t,branchSearch:se,setBranchSearch:_e,newBranchName:X,setNewBranchName:he,branchBase:de,setBranchBase:me,onCreateBranch:pt,onCheckoutBranch:kt,onDeleteBranch:Ht,loading:u,allBranches:B,selectedBranch:Fe,branchCommits:st,loadingBranchCommits:qe,expandedBranchCommit:$e,branchCommitDiff:oe,loadingBranchCommitDiff:ie,onSelectBranch:Tt,onBranchCommitClick:Mt,onCloseBranchDetails:Ot}),l==="worktrees"&&!u&&t.jsx(PP,{worktrees:Le}),l==="stashes"&&!u&&t.jsx(IP,{stashes:Ee,stashMessage:rt,setStashMessage:xe,onCreateStash:zt,onApplyStash:Ft,onDropStash:Et,stashLoading:ce}),l==="remotes"&&!u&&t.jsx($P,{status:b,remoteLoading:pe,lastRemoteResult:Qe,onFetch:Pt,onPull:Dt,onPush:Wt,addToast:i,projectId:r,copyToClipboard:g})]})]})]})}):null}function MP({status:e,copyToClipboard:n}){return t.jsxs("div",{className:"gm-panel","data-testid":"status-panel",children:[t.jsx("div",{className:"gm-panel-header",children:t.jsx("h4",{children:"Repository Status"})}),t.jsxs("div",{className:"gm-status-grid",children:[t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Branch"}),t.jsxs("span",{className:"gm-status-value",children:[t.jsx(Ks,{size:14}),t.jsx("span",{children:e.branch})]})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Commit"}),t.jsxs("span",{className:"gm-status-value",children:[t.jsx("code",{className:"gm-hash",children:e.commit}),t.jsx("button",{className:"gm-icon-btn",onClick:()=>n(e.commit,"commit hash"),title:"Copy commit hash",children:t.jsx(Bi,{size:12})})]})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Working Tree"}),t.jsx("span",{className:`gm-status-badge ${e.isDirty?"dirty":"clean"}`,children:e.isDirty?t.jsxs(t.Fragment,{children:[t.jsx(gs,{size:12}),"Modified"]}):t.jsxs(t.Fragment,{children:[t.jsx(Nn,{size:12}),"Clean"]})})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Remote Sync"}),t.jsxs("span",{className:"gm-status-value",children:[e.ahead>0&&t.jsxs("span",{className:"gm-ahead",title:`${e.ahead} commit(s) ahead`,children:[t.jsx(Fi,{size:12}),e.ahead]}),e.behind>0&&t.jsxs("span",{className:"gm-behind",title:`${e.behind} commit(s) behind`,children:[t.jsx($r,{size:12}),e.behind]}),e.ahead===0&&e.behind===0&&t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(Nn,{size:12}),"Up to date"]})]})]})]})]})}function AP({status:e,stagedFiles:n,unstagedFiles:s,selectedFiles:i,toggleFileSelection:r,onStageFiles:o,onUnstageFiles:l,onDiscardChanges:c,onSelectDiffFile:u,selectedDiffTarget:d,changeDiff:m,loadingChangeDiff:h,changeDiffError:f,commitMessage:p,setCommitMessage:g,onCommit:b,onStageAllAndCommit:v,committing:x}){const y=s.filter(E=>i.has(`unstaged:${E.file}`)),j=n.filter(E=>i.has(`staged:${E.file}`));return t.jsxs("div",{className:"gm-panel","data-testid":"changes-panel",children:[e&&t.jsxs("div",{className:"gm-changes-header",children:[t.jsxs("span",{className:"gm-branch-indicator",children:[t.jsx(Ks,{size:14}),e.branch]}),e.isDirty&&t.jsx("span",{className:"gm-dirty-badge",children:"Modified"})]}),t.jsxs("div",{className:"gm-changes-split",children:[t.jsxs("div",{className:"gm-changes-lists",children:[t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Unstaged Changes (",s.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[y.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>o(y.map(E=>E.file)),title:"Stage selected",children:[t.jsx(dn,{size:12})," Stage (",y.length,")"]}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>c(y.map(E=>E.file)),title:"Discard selected",children:t.jsx(Lr,{size:12})})]}),s.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>o(s.map(E=>E.file)),title:"Stage all",children:"Stage All"})]})]}),t.jsx("div",{className:"gm-file-list",children:s.length===0?t.jsx("div",{className:"gm-empty",children:"No unstaged changes"}):s.map(E=>{const C=d?.file===E.file&&d.staged===!1;return t.jsxs("div",{className:`gm-file-item${C?" active":""}`,onClick:()=>u(E.file,!1),role:"button",tabIndex:0,onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),u(E.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:w=>w.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`unstaged:${E.file}`),onChange:()=>r(`unstaged:${E.file}`)})}),t.jsx(Bh,{status:E.status}),t.jsx("span",{className:"gm-file-name",title:E.file,children:t.jsx("bdo",{dir:"ltr",children:E.file})}),t.jsx(Hh,{status:E.status}),t.jsx("button",{className:"gm-icon-btn",onClick:w=>{w.stopPropagation(),o([E.file])},title:"Stage file",children:t.jsx(dn,{size:12})})]},`unstaged:${E.file}`)})})]}),t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Staged Changes (",n.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[j.length>0&&t.jsxs("button",{className:"btn btn-sm",onClick:()=>l(j.map(E=>E.file)),title:"Unstage selected",children:["Unstage (",j.length,")"]}),n.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(n.map(E=>E.file)),title:"Unstage all",children:"Unstage All"})]})]}),t.jsx("div",{className:"gm-file-list",children:n.length===0?t.jsx("div",{className:"gm-empty",children:"No staged changes"}):n.map(E=>{const C=d?.file===E.file&&d.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${C?" active":""}`,onClick:()=>u(E.file,!0),role:"button",tabIndex:0,onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),u(E.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:w=>w.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`staged:${E.file}`),onChange:()=>r(`staged:${E.file}`)})}),t.jsx(Bh,{status:E.status}),t.jsx("span",{className:"gm-file-name",title:E.file,children:t.jsx("bdo",{dir:"ltr",children:E.file})}),t.jsx(Hh,{status:E.status}),t.jsx("button",{className:"gm-icon-btn",onClick:w=>{w.stopPropagation(),l([E.file])},title:"Unstage file",children:t.jsx(qt,{size:12})})]},`staged:${E.file}`)})})]})]}),t.jsx("div",{className:"gm-changes-diff",children:d||h||m||f?t.jsxs("div",{className:"gm-diff-section",children:[d&&t.jsxs("div",{className:"gm-diff-target",children:[t.jsx($c,{size:14}),t.jsxs("span",{children:[d.staged?"Staged":"Unstaged"," diff: "]}),t.jsx("code",{children:d.file})]}),h&&t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(lt,{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($c,{size:20}),t.jsx("span",{children:"Select a file to view its diff"})]})})]}),t.jsxs("form",{className:"gm-commit-form",onSubmit:b,children:[t.jsx("textarea",{className:"gm-commit-input",placeholder:"Commit message...",value:p,onChange:E=>g(E.target.value),rows:3,disabled:x}),t.jsxs("div",{className:"gm-commit-actions",children:[t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:x||!p.trim()||n.length===0,title:n.length===0?"No staged changes to commit":"Commit staged changes",children:[x?t.jsx(lt,{size:14,className:"spin"}):t.jsx(Oi,{size:14}),"Commit"]}),s.length>0&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:v,disabled:x||!p.trim(),title:"Stage all and commit",children:"Stage All & Commit"})]})]})]})}function RP({commits:e,commitSearch:n,setCommitSearch:s,selectedCommit:i,commitDiff:r,loadingDiff:o,onCommitClick:l,onLoadMore:c,canLoadMore:u,copyToClipboard:d}){return t.jsxs("div",{className:"gm-panel","data-testid":"commits-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Commits"}),t.jsxs("div",{className:"gm-search-box",children:[t.jsx(Ni,{size:14}),t.jsx("input",{type:"text",placeholder:"Search commits...",value:n,onChange:m=>s(m.target.value)})]})]}),t.jsx("div",{className:"gm-commits-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:n?"No matching commits":"No commits found"}):e.map((m,h)=>t.jsxs("div",{className:"gm-commit-item",children:[t.jsxs("div",{className:"gm-commit-graph",children:[t.jsx("div",{className:"gm-commit-dot"}),h<e.length-1&&t.jsx("div",{className:"gm-commit-line"})]}),t.jsxs("div",{className:"gm-commit-body",children:[t.jsxs("button",{className:"gm-commit-header",onClick:()=>l(m.hash),children:[t.jsxs("div",{className:"gm-commit-top-row",children:[t.jsx("code",{className:"gm-hash",children:m.shortHash}),t.jsx("span",{className:"gm-commit-message",title:m.message,children:m.message})]}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:m.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Ca(m.date)}),m.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),t.jsx("div",{className:"gm-commit-actions-row",children:t.jsx("button",{className:"gm-icon-btn",onClick:()=>d(m.hash,"commit hash"),title:"Copy full hash",children:t.jsx(Bi,{size:12})})}),i===m.hash&&t.jsx("div",{className:"gm-commit-diff",children:o?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(lt,{size:16,className:"spin"}),"Loading diff..."]}):r?t.jsxs(t.Fragment,{children:[r.stat&&t.jsx("pre",{className:"gm-diff-stat",children:r.stat}),t.jsx("pre",{className:"gm-diff-patch",children:r.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]})]},m.hash))}),u&&t.jsx("button",{className:"gm-load-more",onClick:c,children:"Load more commits"})]})}function TP({branches:e,branchSearch:n,setBranchSearch:s,newBranchName:i,setNewBranchName:r,branchBase:o,setBranchBase:l,onCreateBranch:c,onCheckoutBranch:u,onDeleteBranch:d,loading:m,allBranches:h,selectedBranch:f,branchCommits:p,loadingBranchCommits:g,expandedBranchCommit:b,branchCommitDiff:v,loadingBranchCommitDiff:x,onSelectBranch:y,onBranchCommitClick:j,onCloseBranchDetails:E}){return t.jsxs("div",{className:"gm-panel","data-testid":"branches-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Branches"}),t.jsxs("div",{className:"gm-search-box",children:[t.jsx(Ni,{size:14}),t.jsx("input",{type:"text",placeholder:"Filter branches...",value:n,onChange:C=>s(C.target.value)})]})]}),t.jsxs("form",{className:"gm-create-form",onSubmit:c,children:[t.jsx("input",{type:"text",placeholder:"New branch name",value:i,onChange:C=>r(C.target.value),disabled:m}),t.jsxs("select",{value:o,onChange:C=>l(C.target.value),disabled:m,className:"gm-branch-select",children:[t.jsx("option",{value:"",children:"Base: HEAD"}),h.map(C=>t.jsx("option",{value:C.name,children:C.name},C.name))]}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:m||!i.trim(),children:[t.jsx(dn,{size:14}),"Create"]})]}),t.jsx("div",{className:"gm-branches-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:n?"No matching branches":"No branches found"}):e.map(C=>t.jsxs("div",{children:[t.jsxs("div",{className:`gm-branch-item${C.isCurrent?" current":""}${f===C.name?" selected":""}`,onClick:()=>y(C.name),children:[t.jsxs("div",{className:"gm-branch-info",children:[t.jsxs("span",{className:"gm-branch-name",children:[C.isCurrent&&t.jsx(Jn,{size:14,className:"gm-current-icon"}),C.name]}),C.remote&&t.jsxs("span",{className:"gm-branch-remote",children:["→ ",C.remote]}),C.lastCommitDate&&t.jsx("span",{className:"gm-branch-date",children:Ca(C.lastCommitDate)})]}),t.jsx("div",{className:"gm-branch-actions",children:!C.isCurrent&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:w=>{w.stopPropagation(),u(C.name)},disabled:m,title:"Checkout",children:t.jsx(Ks,{size:14})}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:w=>{w.stopPropagation(),d(C.name)},disabled:m,title:"Delete",children:t.jsx(cn,{size:14})})]})})]}),f===C.name&&t.jsxs("div",{className:"gm-branch-details",children:[t.jsxs("div",{className:"gm-branch-details-header",children:[t.jsxs("span",{className:"gm-branch-details-title",children:[t.jsx(zr,{size:14}),"Commits on ",C.name]}),t.jsx("button",{className:"gm-icon-btn",onClick:E,title:"Close","data-testid":"close-branch-details",children:t.jsx(qt,{size:14})})]}),g?t.jsxs("div",{className:"gm-branch-details-loading",children:[t.jsx(lt,{size:16,className:"spin"}),"Loading commits..."]}):p.length===0?t.jsx("div",{className:"gm-empty",children:"No commits found"}):t.jsx("div",{className:"gm-branch-commits-list",children:p.map(w=>t.jsxs("div",{className:"gm-branch-commit",children:[t.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>j(w.hash),"data-testid":`branch-commit-${w.shortHash}`,children:[t.jsx("span",{className:"gm-commit-hash",children:w.shortHash}),t.jsx("span",{className:"gm-commit-message",title:w.message,children:w.message}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:w.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Ca(w.date)}),w.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),b===w.hash&&t.jsx("div",{className:"gm-commit-diff",children:x?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(lt,{size:16,className:"spin"}),"Loading diff..."]}):v?t.jsxs(t.Fragment,{children:[v.stat&&t.jsx("pre",{className:"gm-diff-stat",children:v.stat}),t.jsx("pre",{className:"gm-diff-patch",children:v.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},w.hash))})]})]},C.name))})]})}function PP({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:Sd(n.path)||n.path})]}),t.jsxs("div",{className:"gm-worktree-detail",children:[n.branch&&t.jsxs("span",{className:"gm-worktree-branch",children:[t.jsx(Ks,{size:12}),n.branch]}),n.taskId&&t.jsx("span",{className:"gm-worktree-task",children:n.taskId})]})]})},n.path))})]})}function IP({stashes:e,stashMessage:n,setStashMessage:s,onCreateStash:i,onApplyStash:r,onDropStash:o,stashLoading:l}){return t.jsxs("div",{className:"gm-panel","data-testid":"stashes-panel",children:[t.jsx("div",{className:"gm-panel-header",children:t.jsx("h4",{children:"Stashes"})}),t.jsxs("form",{className:"gm-create-form",onSubmit:i,children:[t.jsx("input",{type:"text",placeholder:"Stash message (optional)",value:n,onChange:c=>s(c.target.value),disabled:l!==null}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:l!==null,children:[l==="create"?t.jsx(lt,{size:14,className:"spin"}):t.jsx(Ir,{size:14}),"Stash"]})]}),t.jsx("div",{className:"gm-stash-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:"No stashes"}):e.map(c=>t.jsxs("div",{className:"gm-stash-item",children:[t.jsxs("div",{className:"gm-stash-info",children:[t.jsxs("span",{className:"gm-stash-ref",children:["stash@",`{${c.index}}`]}),t.jsx("span",{className:"gm-stash-message",children:c.message}),t.jsxs("div",{className:"gm-stash-meta",children:[c.branch&&t.jsxs("span",{className:"gm-stash-branch",children:[t.jsx(Ks,{size:12}),c.branch]}),t.jsx("span",{children:Ca(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(lt,{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(lt,{size:14,className:"spin"}):t.jsx(cn,{size:14})})]})]},c.index))})]})}function $P({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:i,onPull:r,onPush:o,addToast:l,projectId:c,copyToClipboard:u}){const d=ie=>{try{return new URL(ie).hostname}catch{return ie.replace(/^git@/,"").split(":")[0]||ie}},[m,h]=a.useState([]),[f,p]=a.useState(!1),[g,b]=a.useState(null),[v,x]=a.useState(""),[y,j]=a.useState(""),[E,C]=a.useState(null),[w,R]=a.useState(""),[S,O]=a.useState(""),[_,P]=a.useState(!1),[U,G]=a.useState([]),[M,T]=a.useState(!1),[D,K]=a.useState(null),[J,te]=a.useState([]),[N,z]=a.useState(!1),[I,k]=a.useState(null),H=m.find(ie=>ie.name===D),[Q,ue]=a.useState(null),[be,V]=a.useState(null),[ve,B]=a.useState(!1),[Y,X]=a.useState(null),[he,de]=a.useState(null),[me,se]=a.useState(!1);a.useEffect(()=>{_e()},[]),a.useEffect(()=>{e&&e.ahead>0?Fe():e&&e.ahead===0&&G([])},[e?.ahead]),a.useEffect(()=>{m.length>0&&!D&&K(m[0].name)},[m]),a.useEffect(()=>{D?Te(D):(te([]),k(null))},[D]),a.useEffect(()=>{D&&!m.find(ie=>ie.name===D)&&K(m.length>0?m[0].name:null)},[m,D]);const _e=async()=>{p(!0);try{const ie=await dw(c);h(ie)}catch(ie){l(ke(ie)||"Failed to load remotes","error")}finally{p(!1)}},Fe=async()=>{T(!0);try{const ie=await yw(c);G(ie)}catch{G([])}finally{T(!1)}},Te=async ie=>{z(!0),k(null);try{const Ae=await ww(ie,void 0,10,c);te(Ae)}catch(Ae){k(ke(Ae)||"Failed to load remote commits"),te([])}finally{z(!1)}},st=Gs(),nt=async ie=>{if(ie.preventDefault(),!(!v.trim()||!y.trim())){b("add");try{await uw(v.trim(),y.trim(),c),l(`Remote '${v}' added successfully`,"success"),x(""),j(""),P(!1),await _e()}catch(Ae){l(ke(Ae)||"Failed to add remote","error")}finally{b(null)}}},qe=async ie=>{if(await st.confirm({title:"Remove Remote",message:`Are you sure you want to remove remote '${ie}'?`,danger:!0})){b(`remove-${ie}`);try{await mw(ie,c),l(`Remote '${ie}' removed`,"success"),await _e()}catch(Le){l(ke(Le)||"Failed to remove remote","error")}finally{b(null)}}},Xe=async ie=>{if(S.trim()){b(`rename-${ie}`);try{await hw(ie,S.trim(),c),l(`Remote renamed to '${S.trim()}'`,"success"),C(null),O(""),await _e()}catch(Ae){l(ke(Ae)||"Failed to rename remote","error")}finally{b(null)}}},$e=async ie=>{if(w.trim()){b(`url-${ie}`);try{await pw(ie,w.trim(),c),l("Remote URL updated","success"),C(null),R(""),await _e()}catch(Ae){l(ke(Ae)||"Failed to update remote URL","error")}finally{b(null)}}},Ue=a.useCallback(async(ie,Ae)=>{if(Ae==="ahead"){if(Q===ie){ue(null),V(null);return}ue(ie),V(null),B(!0);try{const Le=await Uo(ie);V(Le)}catch{V(null)}finally{B(!1)}}else{if(Y===ie){X(null),de(null);return}X(ie),de(null),se(!0);try{const Le=await Uo(ie);de(Le)}catch{de(null)}finally{se(!1)}}},[Q,Y]),oe=ie=>{C(`url-${ie.name}`),R(ie.pushUrl||ie.fetchUrl)},je=ie=>{C(`name-${ie.name}`),O(ie.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:()=>P(!_),disabled:g!==null,title:_?"Cancel":"Add Remote",children:_?t.jsx(qt,{size:14}):t.jsx(dn,{size:14})})]}),_&&t.jsxs("form",{className:"gm-remote-form",onSubmit:nt,children:[t.jsx("input",{type:"text",placeholder:"Remote name",value:v,onChange:ie=>x(ie.target.value),disabled:g==="add",className:"gm-input"}),t.jsx("input",{type:"text",placeholder:"Repository URL",value:y,onChange:ie=>j(ie.target.value),disabled:g==="add",className:"gm-input gm-input-url"}),t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:!v.trim()||!y.trim()||g==="add",children:[g==="add"?t.jsx(lt,{size:12,className:"spin"}):t.jsx(dn,{size:12}),"Add"]})]}),f?t.jsxs("div",{className:"gm-loading",children:[t.jsx(lt,{size:16,className:"spin"}),"Loading..."]}):m.length===0?t.jsx("div",{className:"gm-empty",children:"No remotes"}):m.map(ie=>t.jsxs("div",{className:`gm-remote-selector-item${D===ie.name?" selected":""}`,onClick:()=>K(ie.name),role:"button",tabIndex:0,children:[t.jsxs("div",{className:"gm-remote-selector-info",children:[t.jsxs("span",{className:"gm-remote-selector-name",children:[ie.name,ie.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),t.jsx("span",{className:"gm-remote-selector-host",children:d(ie.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:Ae=>{Ae.stopPropagation(),qe(ie.name)},disabled:g!==null,title:"Remove remote",children:t.jsx(cn,{size:14})})]},ie.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[D&&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:D}),e&&(e.ahead>0||e.behind>0)&&t.jsxs("div",{className:"gm-remote-status",children:[e.ahead>0&&t.jsxs("div",{className:"gm-remote-indicator ahead",children:[t.jsx(Fi,{size:14}),e.ahead," to push"]}),e.behind>0&&t.jsxs("div",{className:"gm-remote-indicator behind",children:[t.jsx($r,{size:14}),e.behind," to pull"]})]})]}),t.jsxs("div",{className:"gm-remote-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:i,disabled:n!==null||f,children:[n==="fetch"?t.jsx(lt,{size:14,className:"spin"}):t.jsx(Fn,{size:14}),"Fetch"]}),t.jsxs("button",{className:"btn btn-primary",onClick:r,disabled:n!==null||f,children:[n==="pull"?t.jsx(lt,{size:14,className:"spin"}):t.jsx(Es,{size:14}),"Pull"]}),t.jsxs("button",{className:"btn btn-primary",onClick:o,disabled:n!==null||f,children:[n==="push"?t.jsx(lt,{size:14,className:"spin"}):t.jsx(Fi,{size:14}),"Push"]})]})]}),t.jsxs("div",{className:"gm-remote-detail-card","data-testid":"remote-detail-card",children:[t.jsxs("div",{className:"gm-remote-detail-urls",children:[t.jsxs("div",{className:"gm-remote-detail-url-row",children:[t.jsx("span",{className:"gm-url-label",children:"Fetch:"}),E===`url-${D}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:w,onChange:ie=>R(ie.target.value),className:"gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>$e(D),disabled:g===`url-${D}`,children:g===`url-${D}`?t.jsx(lt,{size:12,className:"spin"}):t.jsx(Jn,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{C(null),R("")},title:"Cancel",children:t.jsx(qt,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:H.fetchUrl,children:H.fetchUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>u(H.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:t.jsx(Bi,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>oe(H),disabled:g!==null,title:"Edit remote URL",children:t.jsx(hs,{size:14})})]})]}),H.pushUrl&&H.pushUrl!==H.fetchUrl&&t.jsxs("div",{className:"gm-remote-detail-url-row",children:[t.jsx("span",{className:"gm-url-label",children:"Push:"}),t.jsx("span",{className:"gm-url-value",title:H.pushUrl,children:H.pushUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>u(H.pushUrl,"push URL"),title:"Copy push URL",children:t.jsx(Bi,{size:14})})]})]}),t.jsx("div",{className:"gm-remote-detail-name-row",children:E===`name-${D}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:S,onChange:ie=>O(ie.target.value),className:"gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Xe(D),disabled:g===`rename-${D}`,children:g===`rename-${D}`?t.jsx(lt,{size:12,className:"spin"}):t.jsx(Jn,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{C(null),O("")},title:"Cancel",children:t.jsx(qt,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>je(H),disabled:g!==null,title:"Edit remote name",children:t.jsx(hs,{size:14})})})]}),e&&e.ahead>0&&t.jsxs("div",{className:"gm-remote-section","data-testid":"commits-to-push",children:[t.jsx("div",{className:"gm-section-subheader",children:t.jsxs("h5",{children:[t.jsx(Fi,{size:14}),"Commits to Push (",e.ahead,")"]})}),M?t.jsxs("div",{className:"gm-loading",children:[t.jsx(lt,{size:14,className:"spin"}),"Loading..."]}):U.length>0?t.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:U.map(ie=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>Ue(ie.hash,"ahead"),role:"button",tabIndex:0,title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:ie.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:ie.message,children:ie.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:ie.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Ca(ie.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:Q===ie.hash?t.jsx(Yt,{size:14}):t.jsx(gn,{size:14})})]}),Q===ie.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:ve?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(lt,{size:16,className:"spin"}),"Loading diff..."]}):be?t.jsxs(t.Fragment,{children:[ie.message&&t.jsx("div",{className:"gm-commit-message-full",children:ie.message}),be.stat&&t.jsx("pre",{className:"gm-diff-stat",children:be.stat}),t.jsx("pre",{className:"gm-diff-patch",children:be.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},ie.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(Mp,{size:14}),"Recent commits on ",D]})}),N?t.jsxs("div",{className:"gm-loading",children:[t.jsx(lt,{size:14,className:"spin"}),"Loading commits..."]}):I?t.jsxs("div",{className:"gm-error",children:[t.jsx(gs,{size:14}),I]}):J.length===0?t.jsxs("div",{className:"gm-empty",children:["No commits found on ",D,". Try fetching first."]}):t.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:J.map(ie=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>Ue(ie.hash,"remote"),role:"button",tabIndex:0,title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:ie.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:ie.message,children:ie.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:ie.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Ca(ie.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:Y===ie.hash?t.jsx(Yt,{size:14}):t.jsx(gn,{size:14})})]}),Y===ie.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:me?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(lt,{size:16,className:"spin"}),"Loading diff..."]}):he?t.jsxs(t.Fragment,{children:[ie.message&&t.jsx("div",{className:"gm-commit-message-full",children:ie.message}),he.stat&&t.jsx("pre",{className:"gm-diff-stat",children:he.stat}),t.jsx("pre",{className:"gm-diff-patch",children:he.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},ie.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 rr={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function DP(e,n){return e&&n?`${e}/${n}`:""}function LP(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 zP(e){switch(e){case"file-text":return Hi;case"check-circle":return Nn;case"shield":return Av;case"zap":return es;case"eye":return Ta;case"globe":return nl;case"layout-grid":return Vi;default:return Nn}}function OP(e){switch(e.toLowerCase()){case"quality":return"wfm-badge-category wfm-badge-category-quality";case"security":return"wfm-badge-category wfm-badge-category-security";default:return"wfm-badge-category"}}function FP({isOpen:e,onClose:n,addToast:s,projectId:i}){const[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState(!0),[m,h]=a.useState(!0),[f,p]=a.useState("my-steps"),[g,b]=a.useState(null),[v,x]=a.useState(!1),[y,j]=a.useState(rr),[E,C]=a.useState(!1),[w,R]=a.useState(!1),[S,O]=a.useState(null),[_,P]=a.useState(null),[U,G]=a.useState({}),[M,T]=a.useState([]),D=a.useRef(null);di(D,e,"fusion:workflow-steps-modal-size");const K=a.useCallback(async()=>{try{d(!0);const B=await Br(i);o(B)}catch(B){s(ke(B)||"Failed to load workflow steps","error")}finally{d(!1)}},[s,i]),J=a.useCallback(async()=>{try{const B=await _r(i);G(B||{})}catch{}},[i]),te=a.useCallback(async()=>{try{const B=await bs();T(B.models||[])}catch{}},[]),N=a.useCallback(async()=>{try{h(!0);const B=await xj();c(B.templates)}catch(B){s(ke(B)||"Failed to load templates","error")}finally{h(!1)}},[s]);a.useEffect(()=>{e&&(K(),N(),J(),te())},[e,K,N,J,te]);const z=a.useCallback(()=>{x(!0),b(null),j(rr)},[]),I=a.useCallback(B=>{b(B.id),x(!1),j({name:B.name,description:B.description,mode:B.mode||"prompt",phase:B.phase||"pre-merge",prompt:B.prompt,scriptName:B.scriptName||"",enabled:B.enabled,defaultOn:B.defaultOn||!1,modelProvider:B.modelProvider||"",modelId:B.modelId||""})},[]),k=a.useCallback(()=>{b(null),x(!1),j(rr)},[]),H=a.useCallback(async()=>{if(!y.name.trim()||!y.description.trim()){s("Name and description are required","error");return}C(!0);try{const B=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 Y={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,...B};await gu(Y,i),s("Workflow step created","success")}else g&&(await fj(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,...B},i),s("Workflow step updated","success"));x(!1),b(null),j(rr),await K()}catch(B){s(ke(B)||"Failed to save workflow step","error")}finally{C(!1)}},[y,v,g,s,K]),Q=a.useCallback(async B=>{try{await gj(B,i),s("Workflow step deleted","success"),O(null),g===B&&(b(null),j(rr)),await K()}catch(Y){s(ke(Y)||"Failed to delete workflow step","error")}},[g,s,K]),ue=a.useCallback(async()=>{if(!(!g&&!v)&&y.mode==="prompt"){if(v){if(!y.name.trim()||!y.description.trim()){s("Name and description are required before refining","error");return}C(!0);try{const B=y.modelProvider&&y.modelId?{modelProvider:y.modelProvider,modelId:y.modelId}:{},Y={name:y.name.trim(),description:y.description.trim(),mode:"prompt",prompt:y.prompt.trim()||void 0,enabled:y.enabled,defaultOn:y.defaultOn||void 0,...B},X=await gu(Y,i);x(!1),b(X.id),R(!0);const he=await bu(X.id,i);j(de=>({...de,prompt:he.prompt})),s("Prompt refined with AI","success"),await K()}catch(B){s(ke(B)||"Failed to refine prompt","error")}finally{C(!1),R(!1)}return}if(g){R(!0);try{const B=await bu(g,i);j(Y=>({...Y,prompt:B.prompt})),s("Prompt refined with AI","success"),await K()}catch(B){s(ke(B)||"Failed to refine prompt","error")}finally{R(!1)}}}},[g,v,y,s,K]),be=a.useCallback(async B=>{P(B.id);try{await vj(B.id,i),s(`Added ${B.name} workflow step`,"success"),await K(),p("my-steps")}catch(Y){const X=ke(Y);X?.includes("already exists")?s(`A workflow step named '${B.name}' already exists`,"error"):s(X||"Failed to add workflow step from template","error")}finally{P(null)}},[s,K]),V=Mi(n);if(!e)return null;const ve=v||g!==null;return t.jsx("div",{className:"modal-overlay open",...V,"data-testid":"workflow-step-manager",children:t.jsxs("div",{ref:D,className:"modal workflow-step-manager-modal",role:"dialog","aria-modal":"true","aria-label":"Workflow Steps",children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h2",{children:"Workflow Steps"}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]}),t.jsx("div",{className:"wfm-body",children:u?t.jsx("div",{className:"wfm-loading",children:"Loading..."}):t.jsxs(t.Fragment,{children:[!ve&&t.jsxs("div",{className:"wfm-tab-row",children:[t.jsxs("button",{className:`btn ${f==="my-steps"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>p("my-steps"),"data-testid":"tab-my-steps",children:[t.jsx(Sb,{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(Vi,{size:14}),"Templates (",l.length,")"]})]}),f==="my-steps"&&!ve&&t.jsxs(t.Fragment,{children:[r.length===0&&t.jsx("div",{className:"wfm-empty","data-testid":"empty-state",children:"No workflow steps defined. Create one to get started, or add one from the Templates tab."}),r.length>0&&t.jsx("div",{className:"wfm-step-list",children:r.map(B=>t.jsx("div",{className:"wfm-step-card","data-testid":`workflow-step-${B.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:B.name}),t.jsx("span",{className:`wfm-badge ${B.enabled?"wfm-badge-enabled":"wfm-badge-disabled"}`,children:B.enabled?"Enabled":"Disabled"}),t.jsx("span",{className:`wfm-badge ${(B.mode||"prompt")==="script"?"wfm-badge-script":"wfm-badge-prompt"}`,children:(B.mode||"prompt")==="script"?"Script":"AI Prompt"}),t.jsx("span",{className:`wfm-badge ${(B.phase||"pre-merge")==="post-merge"?"wfm-badge-post-merge":"wfm-badge-pre-merge"}`,children:(B.phase||"pre-merge")==="post-merge"?"Post-merge":"Pre-merge"}),B.defaultOn&&t.jsx("span",{className:"wfm-badge wfm-badge-default-on",children:"Default on"})]}),t.jsx("div",{className:"wfm-step-card-desc",children:B.description})]}),t.jsxs("div",{className:"wfm-step-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>I(B),title:"Edit","aria-label":`Edit ${B.name}`,children:t.jsx(hs,{size:14})}),S===B.id?t.jsxs("div",{className:"wfm-delete-confirm",children:[t.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>Q(B.id),title:"Confirm delete","aria-label":`Confirm delete ${B.name}`,children:t.jsx(Jn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>O(null),title:"Cancel delete","aria-label":"Cancel delete",children:t.jsx(qt,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>O(B.id),title:"Delete","aria-label":`Delete ${B.name}`,children:t.jsx(cn,{size:14})})]})]})},B.id))})]}),f==="templates"&&!ve&&t.jsx(t.Fragment,{children:m?t.jsxs("div",{className:"wfm-loading",children:[t.jsx(lt,{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(B=>{const Y=zP(B.icon),X=OP(B.category),he=_===B.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`template-${B.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(Y,{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:B.name}),t.jsx("span",{className:X,children:B.category})]}),t.jsx("div",{className:"wfm-template-desc",children:B.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>be(B),disabled:he,"data-testid":`add-template-${B.id}`,children:he?t.jsxs(t.Fragment,{children:[t.jsx(lt,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(dn,{size:12}),"Add"]})})]})]})},B.id)})})}),ve&&t.jsxs("div",{className:"wfm-form","data-testid":"workflow-step-form",children:[t.jsx("h3",{className:"wfm-form-title",children:v?"New Workflow Step":"Edit Workflow Step"}),t.jsxs("div",{className:"wfm-form-fields",children:[t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Name"}),t.jsx("input",{type:"text",value:y.name,onChange:B=>j(Y=>({...Y,name:B.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:B=>j(Y=>({...Y,description:B.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(B=>({...B,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[t.jsx(Si,{size:14}),"AI Prompt"]}),t.jsxs("button",{className:`btn ${y.mode==="script"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>j(B=>({...B,mode:"script",prompt:"",modelProvider:"",modelId:""})),"data-testid":"mode-script",children:[t.jsx(gi,{size:14}),"Run Script"]})]})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Execution Phase"}),t.jsxs("div",{className:"wfm-mode-selector","data-testid":"workflow-step-phase-selector",children:[t.jsx("button",{className:`btn ${y.phase==="pre-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>j(B=>({...B,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(B=>({...B,phase:"post-merge"})),"data-testid":"phase-post-merge",children:"Post-merge"})]}),t.jsx("div",{className:"wfm-field-hint",children:y.phase==="pre-merge"?"Runs before merge — can block merge on failure":"Runs after merge success — failures are logged but do not block"})]}),y.mode==="prompt"&&t.jsxs("div",{className:"wfm-field",children:[t.jsxs("div",{className:"wfm-prompt-header",children:[t.jsx("label",{children:"Agent Prompt"}),t.jsxs("button",{className:"btn-icon wfm-refine-btn",onClick:ue,disabled:!y.description.trim()||w,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[w?t.jsx(lt,{size:12,className:"spin"}):t.jsx(cs,{size:12}),t.jsx("span",{children:"Refine with AI"})]})]}),t.jsx("textarea",{value:y.prompt,onChange:B=>j(Y=>({...Y,prompt:B.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(B=>({...B,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[t.jsx(qt,{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(ns,{models:M,value:DP(y.modelProvider,y.modelId),onChange:B=>{const Y=LP(B);j(X=>({...X,modelProvider:Y.provider,modelId:Y.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(U).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:B=>j(Y=>({...Y,scriptName:B.target.value})),"data-testid":"workflow-step-script-select",children:[t.jsx("option",{value:"",children:"Select a script…"}),Object.entries(U).map(([B,Y])=>t.jsxs("option",{value:B,children:[B," (",Y,")"]},B))]})]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:y.enabled,onChange:B=>j(Y=>({...Y,enabled:B.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:B=>j(Y=>({...Y,defaultOn:B.target.checked})),"data-testid":"workflow-step-default-on"}),"Default on for new tasks"]}),t.jsxs("div",{className:"wfm-form-actions",children:[t.jsx("button",{className:"btn btn-secondary",onClick:k,disabled:E,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:H,disabled:E||!y.name.trim()||!y.description.trim()||y.mode==="script"&&!y.scriptName.trim(),"data-testid":"save-workflow-step",children:E?"Saving...":v?"Create":"Save"})]})]})]})]})}),!ve&&t.jsx("div",{className:"wfm-footer",children:t.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:z,"data-testid":"add-workflow-step",children:[t.jsx(dn,{size:14}),"Add Workflow Step"]})})]})})}const UP=36e5,BP=3e5,Sc=[{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 HP(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 qP(e){return typeof e!="number"||!Number.isFinite(e)?UP:Math.max(BP,Math.round(e))}function J3(e){if(Sc.some(s=>s.value===e))return[...Sc];const n={value:e,label:`${HP(e)} (custom)`};return[...Sc,n].sort((s,i)=>s.value-i.value)}const VP=4,WP=5*6e4;function KP(e){const n=qP(e?.heartbeatIntervalMs);return Math.max(n*VP,WP)}function GP(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 JP(e){const{state:n,lastHeartbeatAt:s,lastError:i,pauseReason:r,runtimeConfig:o}=e,l=GP(e),c=l||o?.enabled!==!1;if(n==="terminated")return{label:"Terminated",icon:t.jsx(Cs,{size:14}),color:"var(--state-error-text)",stateDerived:!0};if(n==="error")return{label:i??"Error",icon:t.jsx(Ds,{size:14}),color:"var(--state-error-text)",stateDerived:!i};if(n==="paused")return{label:r?`Paused: ${r}`:"Paused",icon:t.jsx(Vs,{size:14}),color:"var(--state-paused-text)",stateDerived:!r};if(n==="running"||l&&n==="active")return{label:"Running",icon:t.jsx(Ds,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!c)return{label:"Heartbeat Disabled",icon:t.jsx(Vs,{size:14}),color:"var(--state-paused-text)",stateDerived:!1};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:t.jsx(En,{size:14}),color:"var(--text-secondary)",stateDerived:!1};const u=new Date(s).getTime(),d=Date.now()-u,m=KP(o);return d>m?{label:"Unresponsive",icon:t.jsx(Ds,{size:14}),color:"var(--state-error-text)",stateDerived:!1}:{label:"Healthy",icon:t.jsx($x,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}const or=[{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 YP({isOpen:e,onClose:n,addToast:s,projectId:i}){const[r,o]=a.useState([]),[l,c]=a.useState(!1),[u,d]=a.useState(!1),[m,h]=a.useState(""),[f,p]=a.useState("custom"),[g,b]=a.useState("all"),[v,x]=a.useState(()=>{if(typeof window>"u")return"list";const I=Yn("fn-agent-view",i);return I==="board"||I==="list"?I:"list"});a.useEffect(()=>{const I=Yn("fn-agent-view",i);if(I==="board"||I==="list"){x(I);return}x("list")},[i]),a.useEffect(()=>{fs("fn-agent-view",v,i)},[i,v]);const[y,j]=a.useState(null),E=a.useRef(null),[C,w]=a.useState(new Set),[R,S]=a.useState(new Map),{confirm:O}=Gs(),_=a.useMemo(()=>R.size===0?r:r.map(I=>{const k=R.get(I.id);return k?{...I,state:k}:I}),[r,R]),P=a.useMemo(()=>g==="all"?_.filter(I=>I.state!=="terminated"):_,[_,g]),U=a.useCallback(async()=>{c(!0);try{const k=await Ia(g!=="all"?{state:g}:void 0,i);o(k)}catch(I){s(`Failed to load agents: ${ke(I)}`,"error")}finally{c(!1)}},[g,s,i]);a.useEffect(()=>{e&&U()},[e,U]),a.useEffect(()=>{if(!e)return;const I=setInterval(()=>{U()},3e4);return()=>{clearInterval(I)}},[e,U]);const G=async()=>{if(m.trim())try{await _j({name:m.trim(),role:f},i),s(`Agent "${m}" created`,"success"),h(""),d(!1),U()}catch(I){s(`Failed to create agent: ${ke(I)}`,"error")}},M=async(I,k)=>{if(!C.has(I)){w(H=>new Set(H).add(I)),S(H=>{const Q=new Map(H);return Q.set(I,k),Q});try{await Aj(I,k,i),s(`Agent state updated to ${k}`,"success"),await U(),S(H=>{const Q=new Map(H);return Q.delete(I),Q})}catch(H){S(Q=>{const ue=new Map(Q);return ue.delete(I),ue}),s(`Failed to update state: ${ke(H)}`,"error")}finally{w(H=>{const Q=new Set(H);return Q.delete(I),Q})}}},T=async(I,k)=>{if(await O({title:"Delete Agent",message:`Delete agent "${k}"? This cannot be undone.`,danger:!0}))try{await Rj(I,i),s(`Agent "${k}" deleted`,"success"),U()}catch(Q){s(`Failed to delete agent: ${ke(Q)}`,"error")}},D=async(I,k)=>{const H=r.find(Q=>Q.id===I);if(H){if(H.role===k){j(null);return}try{await Mj(I,{role:k},i),s(`Agent role updated to ${or.find(Q=>Q.value===k)?.label??k}`,"success"),j(null),U()}catch(Q){s(`Failed to update role: ${ke(Q)}`,"error")}}},K=(I,k)=>{I.key==="Escape"&&j(null)},J=I=>or.find(k=>k.value===I)?.label??I,te=I=>or.find(k=>k.value===I)?.icon??"◆",N=I=>JP(I),z=I=>I.color==="var(--state-active-text)"?"active":I.color==="var(--state-paused-text)"?"paused":I.color==="var(--state-error-text)"?"error":"muted";return e?t.jsx("div",{className:"modal-overlay open",onClick:I=>I.target===I.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(En,{size:20}),"Agents"]}),t.jsxs("div",{className:"modal-actions",children:[t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${v==="board"?" active":""}`,onClick:()=>x("board"),title:"Board view","aria-label":"Board view","aria-pressed":v==="board",children:t.jsx(Vi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${v==="list"?" active":""}`,onClick:()=>x("list"),title:"List view","aria-label":"List view","aria-pressed":v==="list",children:t.jsx(Lc,{size:16})})]}),t.jsx("button",{className:"btn-icon",onClick:()=>void U(),title:"Refresh",disabled:l,children:t.jsx(Fn,{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(Lo,{size:14}),t.jsxs("select",{className:"agent-state-filter-select",value:g,onChange:I=>b(I.target.value),"aria-label":"Filter agents by state",children:[t.jsx("option",{value:"all",children:"All States"}),t.jsx("option",{value:"idle",children:"Idle"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"running",children:"Running"}),t.jsx("option",{value:"paused",children:"Paused"}),t.jsx("option",{value:"error",children:"Error"}),t.jsx("option",{value:"terminated",children:"Terminated"})]})]}),t.jsxs("button",{className:"btn btn-task-create btn-sm",onClick:()=>d(!u),children:[t.jsx(dn,{size:16}),u?"Cancel":"New Agent"]})]}),u&&t.jsxs("div",{className:"agent-create-form",children:[t.jsx("input",{type:"text",placeholder:"Agent name...",value:m,onChange:I=>h(I.target.value),onKeyDown:I=>I.key==="Enter"&&G(),className:"input",autoFocus:!0}),t.jsx("select",{className:"select",value:f,onChange:I=>p(I.target.value),children:or.map(I=>t.jsxs("option",{value:I.value,children:[I.icon," ",I.label]},I.value))}),t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:()=>void G(),children:"Create"})]}),t.jsx("div",{className:v==="board"?"agent-board":"agent-list",children:P.length===0?t.jsxs("div",{className:"agent-empty",children:[t.jsx(En,{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"?P.map(I=>{const k=N(I),H=z(k);return t.jsxs("div",{className:"agent-board-card","data-state":I.state,children:[t.jsxs("div",{className:"agent-board-header",children:[t.jsx("span",{className:"agent-board-icon",children:te(I.role)}),t.jsx("span",{className:"agent-board-badge","data-state":I.state,children:I.state}),t.jsx("span",{className:"agent-board-health","data-health":H,title:k.label,children:k.icon})]}),t.jsx("div",{className:"agent-board-name",title:I.name,children:I.name}),t.jsx("div",{className:"agent-board-id",children:I.id}),t.jsxs("div",{className:"agent-board-actions",children:[I.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void M(I.id,"active"),disabled:C.has(I.id),title:"Activate",children:t.jsx(_n,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void T(I.id,I.name),title:"Delete",children:t.jsx(cn,{size:14})})]}),I.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void M(I.id,"paused"),disabled:C.has(I.id),title:"Pause",children:t.jsx(Vs,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void M(I.id,"terminated"),disabled:C.has(I.id),title:"Stop",children:t.jsx(Cs,{size:14})})]}),I.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void M(I.id,"active"),disabled:C.has(I.id),title:"Resume",children:t.jsx(_n,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void M(I.id,"terminated"),disabled:C.has(I.id),title:"Stop",children:t.jsx(Cs,{size:14})})]}),I.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void M(I.id,"paused"),disabled:C.has(I.id),title:"Pause",children:t.jsx(Vs,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void M(I.id,"terminated"),disabled:C.has(I.id),title:"Stop",children:t.jsx(Cs,{size:14})})]}),I.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void M(I.id,"active"),disabled:C.has(I.id),title:"Retry",children:t.jsx(_n,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void M(I.id,"terminated"),disabled:C.has(I.id),title:"Stop",children:t.jsx(Cs,{size:14})})]}),I.state==="terminated"&&t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void T(I.id,I.name),title:"Delete",children:t.jsx(cn,{size:14})})]})]},I.id)}):P.map(I=>{const k=N(I),H=z(k);return t.jsxs("div",{className:"agent-card","data-state":I.state,children:[t.jsxs("div",{className:"agent-card-header",children:[t.jsxs("div",{className:"agent-info",children:[y===I.id?t.jsx("select",{ref:E,className:"select agent-role-select",value:I.role,onChange:Q=>void D(I.id,Q.target.value),onKeyDown:Q=>K(Q,I.id),onBlur:()=>j(null),autoFocus:!0,children:or.map(Q=>t.jsxs("option",{value:Q.value,children:[Q.icon," ",Q.label]},Q.value))}):t.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>j(I.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:Q=>{(Q.key==="Enter"||Q.key===" ")&&j(I.id)},children:te(I.role)}),t.jsxs("div",{className:"agent-meta",children:[t.jsx("span",{className:"agent-name",children:I.name}),t.jsx("span",{className:"agent-id text-secondary",children:I.id})]})]}),t.jsxs("div",{className:"agent-badges",children:[t.jsx("span",{className:"badge agent-list-state-badge","data-state":I.state,children:I.state}),t.jsxs("span",{className:"badge agent-list-health-badge","data-health":H,title:k.label,children:[k.icon,!k.stateDerived&&` ${k.label}`]}),t.jsx("span",{className:"badge text-secondary",children:J(I.role)})]})]}),t.jsxs("div",{className:"agent-card-body",children:[I.taskId&&t.jsxs("div",{className:"agent-task",children:[t.jsx("span",{className:"text-secondary",children:"Working on:"}),t.jsx("span",{className:"badge",children:I.taskId})]}),I.lastHeartbeatAt&&t.jsxs("div",{className:"agent-heartbeat",children:[t.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),t.jsx("span",{children:new Date(I.lastHeartbeatAt).toLocaleString()})]})]}),t.jsxs("div",{className:"agent-card-actions",children:[I.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void M(I.id,"active"),disabled:C.has(I.id),title:"Activate",children:[t.jsx(_n,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void T(I.id,I.name),title:"Delete",children:[t.jsx(cn,{size:14})," Delete"]})]}),I.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void M(I.id,"paused"),disabled:C.has(I.id),title:"Pause",children:[t.jsx(Vs,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void M(I.id,"terminated"),disabled:C.has(I.id),title:"Stop",children:[t.jsx(Cs,{size:14})," Stop"]})]}),I.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void M(I.id,"active"),disabled:C.has(I.id),title:"Resume",children:[t.jsx(_n,{size:14})," Resume"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void M(I.id,"terminated"),disabled:C.has(I.id),title:"Stop",children:[t.jsx(Cs,{size:14})," Stop"]})]}),I.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void M(I.id,"paused"),disabled:C.has(I.id),title:"Pause",children:[t.jsx(Vs,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void M(I.id,"terminated"),disabled:C.has(I.id),title:"Stop",children:[t.jsx(Cs,{size:14})," Stop"]})]}),I.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void M(I.id,"active"),disabled:C.has(I.id),title:"Retry",children:[t.jsx(_n,{size:14})," Retry"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void M(I.id,"terminated"),disabled:C.has(I.id),title:"Stop",children:[t.jsx(Cs,{size:14})," Stop"]})]}),I.state==="terminated"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm btn-task-create",onClick:()=>void M(I.id,"active"),disabled:C.has(I.id),title:"Start",children:[t.jsx(_n,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void T(I.id,I.name),title:"Delete",children:[t.jsx(cn,{size:14})," Delete"]})]})]})]},I.id)})})]})]})}):null}function QP({authenticated:e,onToggled:n,compact:s=!1}){const[i,r]=a.useState(null),[o,l]=a.useState(null),[c,u]=a.useState(null),d=a.useRef(!0);a.useEffect(()=>(d.current=!0,()=>{d.current=!1}),[]);const m=a.useCallback(async()=>{try{const x=await Vy();return d.current&&r(x),x}catch(x){return d.current&&u({kind:"error",message:x instanceof Error?x.message:String(x)}),null}},[]);a.useEffect(()=>{m()},[m]);const h=a.useCallback(async()=>{l("testing"),u(null),await m(),d.current&&l(null)},[m]),f=a.useCallback(async x=>{l(x?"enabling":"disabling"),u(null);try{const y=await Jy(x);d.current&&u({kind:y.enabled?"enabled":"disabled",restartRequired:y.restartRequired}),n?.(y.enabled),await m()}catch(y){d.current&&u({kind:"error",message:y instanceof Error?y.message:String(y)})}finally{d.current&&l(null)}},[n,m]),p=i?.binary.available??!1,g=i?.enabled??e,b=t.jsxs("span",{className:"onboarding-provider-card__description",children:["Route AI calls through your locally-installed ",t.jsx("code",{children:"claude"})," CLI. Uses your existing Claude subscription / quota instead of an API key."]}),v=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(lt,{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(Rn,{provider:"claude-cli",size:"sm"}),t.jsx("strong",{children:"Anthropic — via Claude CLI"}),t.jsx(XP,{status:i,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:v})]}),t.jsxs("details",{className:"auth-provider-cli-details",children:[t.jsx("summary",{children:"Details"}),t.jsxs("div",{className:"auth-provider-cli-details-body",children:[b,t.jsx(qh,{status:i,authenticated:e}),c&&t.jsx(Vh,{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(Rn,{provider:"claude-cli",size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:"Anthropic — via Claude CLI"}),b,t.jsx(qh,{status:i,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(Vh,{action:c})]})}function XP({status:e,authenticated:n}){const s=e?.enabled??n,i=e?.binary.available??!1;return s?t.jsx("span",{className:"auth-status-badge authenticated",children:"✓ Active"}):!i&&e?t.jsx("span",{className:"auth-status-badge not-authenticated",children:"✗ Not installed"}):t.jsx("span",{className:"auth-status-badge not-authenticated",children:"✗ Not connected"})}function qh({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(lt,{size:10,className:"animate-spin"})," Probing local CLI…"]});const{binary:s,enabled:i,extension:r,ready:o}=e;return s.available?i?r&&r.status!=="ok"?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--warning",children:["⚠ Extension load failed: ",r.reason??r.status]}):o||n?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--connected",children:["✓ Connected",s.version?` — ${s.version}`:""]}):t.jsx("small",{className:"settings-muted",children:"Enabled. Validating…"}):t.jsxs("small",{className:"settings-muted",children:[t.jsx("code",{children:"claude"})," ",s.version?`(${s.version})`:""," detected",s.binaryPath?` at ${s.binaryPath}`:"",". Click Enable to route AI calls through it."]}):t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--error",children:["✗ ",s.reason??"`claude` not found on PATH"]})}function Vh({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 ZP({authenticated:e,onToggled:n,compact:s=!1}){const[i,r]=a.useState(null),[o,l]=a.useState(null),[c,u]=a.useState(null),d=a.useRef(!0);a.useEffect(()=>(d.current=!0,()=>{d.current=!1}),[]);const m=a.useCallback(async()=>{try{const x=await Gy();return d.current&&r(x),x}catch(x){return d.current&&u({kind:"error",message:x instanceof Error?x.message:String(x)}),null}},[]);a.useEffect(()=>{m()},[m]);const h=a.useCallback(async()=>{l("testing"),u(null),await m(),d.current&&l(null)},[m]),f=a.useCallback(async x=>{l(x?"enabling":"disabling"),u(null);try{const y=await Yy(x);d.current&&u({kind:y.enabled?"enabled":"disabled",restartRequired:y.restartRequired}),n?.(y.enabled),await m()}catch(y){d.current&&u({kind:"error",message:y instanceof Error?y.message:String(y)})}finally{d.current&&l(null)}},[n,m]),p=i?.binary.available??!1,g=i?.enabled??e,b=t.jsxs("span",{className:"onboarding-provider-card__description",children:["Route AI calls through your locally-installed ",t.jsx("code",{children:"droid"})," CLI. Uses your existing Factory AI subscription / quota instead of an API key."]}),v=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(lt,{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(Rn,{provider:"droid-cli",size:"sm"}),t.jsx("strong",{children:"Factory AI — via Droid CLI"}),t.jsx(eI,{status:i,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:v})]}),t.jsxs("details",{className:"auth-provider-cli-details",children:[t.jsx("summary",{children:"Details"}),t.jsxs("div",{className:"auth-provider-cli-details-body",children:[b,t.jsx(Wh,{status:i,authenticated:e}),c&&t.jsx(Kh,{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(Rn,{provider:"droid-cli",size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:"Factory AI — via Droid CLI"}),b,t.jsx(Wh,{status:i,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(Kh,{action:c})]})}function eI({status:e,authenticated:n}){const s=e?.enabled??n,i=e?.binary.available??!1;return s?t.jsx("span",{className:"auth-status-badge authenticated",children:"✓ Active"}):!i&&e?t.jsx("span",{className:"auth-status-badge not-authenticated",children:"✗ Not installed"}):t.jsx("span",{className:"auth-status-badge not-authenticated",children:"✗ Not connected"})}function Wh({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(lt,{size:10,className:"animate-spin"})," Probing local CLI…"]});const{binary:s,enabled:i,extension:r,ready:o}=e;return s.available?i?r&&r.status!=="ok"?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--warning",children:["⚠ Extension load failed: ",r.reason??r.status]}):o||n?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--connected",children:["✓ Connected",s.version?` — ${s.version}`:""]}):t.jsx("small",{className:"settings-muted",children:"Enabled. Validating…"}):t.jsxs("small",{className:"settings-muted",children:[t.jsx("code",{children:"droid"})," ",s.version?`(${s.version})`:""," detected",s.binaryPath?` at ${s.binaryPath}`:"",". Click Enable to route AI calls through it."]}):t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--error",children:["✗ ",s.reason??"`droid` not found on PATH"]})}function Kh({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 tI(e){const n="([A-Z0-9]{2,}(?:-[A-Z0-9]{2,})+|[A-Z0-9]{6,9})",s=new RegExp(`\\b(?:device\\s+code|your\\s+code|code)\\s*(?:is|:)?\\s*${n}\\b`,"i"),i=new RegExp(`\\b(?:enter|use)\\s+${n}\\b`,"i"),r=/\b([A-Z0-9]{2,}(?:-[A-Z0-9]{2,})+)\b/,o=e.match(s);if(o?.[1])return o[1];const l=e.match(i);if(l?.[1])return l[1];const c=e.match(r);return c?.[1]?c[1]:null}function Cc({instructions:e,"data-testid":n}){const[s,i]=a.useState(!1),r=tI(e),o=a.useRef(null),l=a.useCallback(()=>{i(!0),setTimeout(()=>i(!1),2e3)},[]),c=a.useCallback(async()=>{const u=r??e;try{await navigator.clipboard.writeText(u),l()}catch{}},[r,e,l]);return a.useEffect(()=>{const u=o.current===null&&r!==null;if(o.current=r,!u)return;(async()=>{try{await navigator.clipboard.writeText(r),l()}catch{}})()},[r,l]),t.jsx("p",{className:"auth-login-instructions","data-testid":n,children:r?t.jsx(t.Fragment,{children:e.split(r).map((u,d,m)=>t.jsxs("span",{children:[u,d<m.length-1&&t.jsxs("span",{className:"device-code-wrapper",children:[t.jsx("code",{className:"device-code",children:r}),t.jsx("button",{className:"device-code-copy-btn",onClick:c,title:s?"Copied!":"Copy code","aria-label":s?"Copied to clipboard":"Copy device code",type:"button",children:s?t.jsx(Jn,{size:12}):t.jsx(Bi,{size:12})})]})]},d))}):e})}const nI=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"]),sI=/^[a-z][a-z0-9-]*$/,Gh=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function Jh(){return{id:"",name:"",reasoning:!1}}function iI({initialConfig:e,onSave:n,onCancel:s,saving:i=!1,error:r}){const o=!!e,[l,c]=a.useState(e?.id??""),[u,d]=a.useState(e?.name??""),[m,h]=a.useState(e?.baseUrl??""),[f,p]=a.useState(e?.api??"openai-completions"),[g,b]=a.useState(e?.apiKey??""),[v,x]=a.useState(e?.models?.length?e.models:[Jh()]),[y,j]=a.useState(null),E=v.length>1,C=a.useMemo(()=>y??r??null,[y,r]);function w(_,P){x(U=>U.map((G,M)=>M===_?{...G,...P}:G))}function R(_){x(P=>P.length<=1?P:P.filter((U,G)=>G!==_))}function S(){if(!l.trim())return"Provider ID is required.";if(!sI.test(l.trim()))return"Provider ID must be kebab-case.";if(!o&&nI.has(l.trim()))return"Provider ID conflicts with a built-in provider.";if(!m.trim())return"Base URL is required.";try{const _=new URL(m.trim());if(_.protocol!=="http:"&&_.protocol!=="https:")return"Base URL must use http or https."}catch{return"Base URL must be a valid URL."}return Gh.includes(f)?v.length===0?"At least one model is required.":v.some(_=>!_.id?.trim())?"Each model must have a model ID.":null:"API type is required."}async function O(_){_.preventDefault();const P=S();j(P),!P&&await n({id:l.trim(),name:u.trim()||void 0,baseUrl:m.trim(),api:f,apiKey:g.trim()||void 0,models:v.map(U=>({id:U.id.trim(),name:U.name?.trim()||void 0,reasoning:!!U.reasoning,contextWindow:U.contextWindow,maxTokens:U.maxTokens}))})}return t.jsxs("form",{onSubmit:O,className:"custom-provider-form","aria-label":"custom-provider-form",children:[t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-id",children:"Provider ID"}),t.jsx("input",{id:"custom-provider-id",className:"input",value:l,onChange:_=>c(_.target.value),disabled:o||i})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-name",children:"Display Name"}),t.jsx("input",{id:"custom-provider-name",className:"input",value:u,onChange:_=>d(_.target.value),disabled:i})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-base-url",children:"Base URL"}),t.jsx("input",{id:"custom-provider-base-url",className:"input",value:m,onChange:_=>h(_.target.value),disabled:i})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-api",children:"API Type"}),t.jsx("select",{id:"custom-provider-api",className:"select",value:f,onChange:_=>p(_.target.value),disabled:i,children:Gh.map(_=>t.jsx("option",{value:_,children:_},_))})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-api-key",children:"API Key"}),t.jsx("input",{id:"custom-provider-api-key",className:"input",placeholder:"sk-..., MY_API_KEY, or !command",value:g,onChange:_=>b(_.target.value),disabled:i})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{children:"Models"}),t.jsx("div",{className:"custom-provider-form__models",children:v.map((_,P)=>t.jsxs("div",{className:"custom-provider-form__model-row",children:[t.jsx("input",{className:"input","aria-label":`Model ID ${P+1}`,placeholder:"Model ID",value:_.id,onChange:U=>w(P,{id:U.target.value}),disabled:i}),t.jsx("input",{className:"input","aria-label":`Model name ${P+1}`,placeholder:"Display name",value:_.name??"",onChange:U=>w(P,{name:U.target.value}),disabled:i}),t.jsxs("label",{className:"checkbox-label custom-provider-form__toggle",children:[t.jsx("input",{type:"checkbox",checked:!!_.reasoning,onChange:U=>w(P,{reasoning:U.target.checked}),disabled:i}),"Reasoning"]}),t.jsx("input",{className:"input","aria-label":`Context window ${P+1}`,placeholder:"Context window",type:"number",value:_.contextWindow??"",onChange:U=>w(P,{contextWindow:U.target.value?Number(U.target.value):void 0}),disabled:i}),t.jsx("input",{className:"input","aria-label":`Max tokens ${P+1}`,placeholder:"Max tokens",type:"number",value:_.maxTokens??"",onChange:U=>w(P,{maxTokens:U.target.value?Number(U.target.value):void 0}),disabled:i}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>R(P),disabled:i||!E,"aria-label":`Remove model ${P+1}`,children:"×"})]},`${P}-model`))}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>x(_=>[..._,Jh()]),disabled:i,children:"+ Add model"})]}),C?t.jsx("div",{className:"form-error",children:C}):null,t.jsxs("div",{className:"custom-provider-form__actions",children:[s?t.jsx("button",{type:"button",className:"btn",onClick:s,disabled:i,children:"Cancel"}):null,t.jsx("button",{type:"submit",className:"btn btn-primary",disabled:i,children:i?"Saving...":"Save Provider"})]})]})}const aI=new Set(["google-antigravity","antigravity","google-gemini-cli"]);function rI(e){return!aI.has(e)}function Yh(e){return e.filter(n=>rI(n.id))}const Ji="fusion_model_onboarding_state",Ea=[],_a=[],Qo=!1,Xo=!1,Ma={},oI=void 0,ki=["ai-setup","github","project-setup","first-task"],lI={"ai-setup":"AI Setup",github:"GitHub","project-setup":"Project","first-task":"First Task",complete:"Complete"};function As(){if(typeof window>"u")return null;try{const e=localStorage.getItem(Ji);if(!e)return null;const n=JSON.parse(e);return n&&typeof n=="object"&&"currentStep"in n&&typeof n.currentStep=="string"?cI(n):null}catch{return null}}function cI(e){const n=e.postOnboardingDismissedAt??oI;return{...e,completedSteps:e.completedSteps??Ea,skippedSteps:e.skippedSteps??_a,dismissed:e.dismissed??Qo,completed:e.completed??Xo,stepData:e.stepData??Ma,...n?{postOnboardingDismissedAt:n}:{}}}function Co(e,n){if(!(typeof window>"u")){if(!n){const s={currentStep:e,updatedAt:new Date().toISOString(),completedSteps:Ea,skippedSteps:_a,dismissed:Qo,completed:Xo,stepData:Ma};try{localStorage.setItem(Ji,JSON.stringify(s))}catch{}return}try{const s=As(),i=new Date().toISOString(),r=n.completed??Xo;let o=n.dismissed??Qo;r&&(o=!1);const l=n.completedSteps??s?.completedSteps??Ea,c=n.skippedSteps??s?.skippedSteps??_a,u={...s?.stepData??Ma};if(n.stepData)for(const[m,h]of Object.entries(n.stepData))h!==void 0&&(u[m]={...u[m]??{},...h});const d={currentStep:e,updatedAt:i,completedSteps:l,skippedSteps:c,dismissed:o,completed:r,stepData:u};localStorage.setItem(Ji,JSON.stringify(d))}catch{}}}function dI(e){if(!(typeof window>"u"))try{const n=As(),s=new Date().toISOString();if(!n){const o={currentStep:e,updatedAt:s,completedSteps:Ea,skippedSteps:[e],dismissed:Qo,completed:Xo,stepData:Ma};localStorage.setItem(Ji,JSON.stringify(o));return}const i=n.skippedSteps.includes(e)?n.skippedSteps:[...n.skippedSteps,e],r={...n,skippedSteps:i,completedSteps:n.completedSteps.filter(o=>o!==e),updatedAt:s};localStorage.setItem(Ji,JSON.stringify(r))}catch{}}function Qh(){if(!(typeof window>"u"))try{const e=As(),n=new Date().toISOString(),s=e?{...e,completedAt:n,completed:!0,dismissed:!1,updatedAt:n}:{currentStep:"complete",updatedAt:n,completedAt:n,completedSteps:Ea,skippedSteps:_a,dismissed:!1,completed:!0,stepData:Ma};localStorage.setItem(Ji,JSON.stringify(s))}catch{}}function Aa(){const e=As();return e?e.completed===!0?!0:typeof e.completedAt=="string"&&e.completedAt.length>0:!1}function uI(){if(!(typeof window>"u"))try{const e=As(),n=new Date().toISOString(),s=e?{...e,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:Ea,skippedSteps:_a,dismissed:!1,completed:!1,stepData:Ma,postOnboardingDismissedAt:n};localStorage.setItem(Ji,JSON.stringify(s))}catch{}}function Bg(){const e=As();return e?typeof e.postOnboardingDismissedAt=="string"&&e.postOnboardingDismissedAt.length>0:!1}function mI(){const e=As();return!e||Aa()?!1:e.currentStep!=="complete"}function hI(){const e=As();if(!e||Aa()||e.currentStep==="complete")return null;const n=e.currentStep,s=lI[n]??gI(e.currentStep);return{currentStep:e.currentStep,label:s,completedSteps:e.completedSteps}}function pI(){const e=As();return e?e.skippedSteps:_a}function fI(e){const n=As();return!n||!n.stepData?null:n.stepData[e]??null}function gI(e){return e.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const Hg="fusion_onboarding_events",Xh="fusion_onboarding_session_id",bI=200,xI=50;function Is(e,n={}){if(!(typeof window>"u"))try{const s=yI(),i=kI(n.step),r={type:e,timestamp:new Date().toISOString(),...i?{step:i}:{},metadata:n,sessionId:vI()},o=jI([...s,r]);wI(o)}catch{}}function vI(){if(typeof window>"u")return"server-session";try{const e=sessionStorage.getItem(Xh);if(e)return e;const n=Zh();return sessionStorage.setItem(Xh,n),n}catch{return Zh()}}function Zh(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function yI(){try{const e=localStorage.getItem(Hg);if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(NI):[]}catch{return[]}}function wI(e){try{localStorage.setItem(Hg,JSON.stringify(e))}catch{}}function jI(e){const n=[...e];for(;n.length>bI;)n.splice(0,xI);return n}function kI(e){if(e==="ai-setup"||e==="github"||e==="first-task"||e==="complete")return e}function NI(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 SI=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}))??[]}),CI={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"}}},qg={anthropic:{pattern:/^sk-ant-/,hint:"Starts with sk-ant-",example:"sk-ant-api03-..."},openai:{pattern:/^sk-/,hint:"Starts with sk-",example:"sk-..."},"openai-codex":{pattern:/^sk-/,hint:"Starts with sk-",example:"sk-..."},openrouter:{pattern:/^sk-or-/,hint:"Starts with sk-or-",example:"sk-or-v1-..."},google:{pattern:/^AIza/,hint:"Starts with AIza",example:"AIza..."},gemini:{pattern:/^AIza/,hint:"Starts with AIza",example:"AIza..."},minimax:{pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},ollama:{pattern:/^.+$/,hint:"Any non-empty value",example:"ollama"},zai:{pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},kimi:{pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},"kimi-coding":{pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},moonshot:{pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."}},EI={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},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 dd(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 Ec=["anthropic","openai","google","gemini","ollama"],_I=["anthropic","claude-cli","droid-cli","openai-codex","gemini","minimax","kimi","zai"],MI={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"},AI={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function ud(e){return MI[e]??e}function tp(e){const n=ud(e),s=_I.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function np(e,n){if(e.authenticated!==n.authenticated)return e.authenticated?-1:1;const s=tp(e.id),i=tp(n.id);if(s!==i)return s-i;const r=ud(e.id),o=ud(n.id);if(r!==o)return r.localeCompare(o);const l=AI[r];if(l){const u=l.indexOf(e.id),d=l.indexOf(n.id);if(u!==d)return(u===-1?Number.POSITIVE_INFINITY:u)-(d===-1?Number.POSITIVE_INFINITY:d)}const c=e.name.localeCompare(n.name);return c!==0?c:e.id.localeCompare(n.id)}function RI(e,n){const s=n.trim();if(!s)return"API key is required";const i=qg[e]??EI;return i.pattern.test(s)?null:`${dd(e)} keys should follow this format: ${i.hint} (e.g. ${i.example})`}const Vg={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"},TI={description:"AI provider — connect to start using AI models",apiKeyInfo:Vg};function md(e){return CI[e]??TI}function PI(e){return md(e.id).apiKeyInfo??Vg}function si({summary:e,children:n,className:s=""}){const[i,r]=a.useState(!1);return t.jsxs("div",{className:`onboarding-disclosure ${s}`,children:[t.jsxs("button",{className:"onboarding-disclosure-trigger",onClick:()=>r(!i),"aria-expanded":i,type:"button",children:[t.jsx(gn,{size:14,className:"onboarding-disclosure-chevron","aria-hidden":"true"}),t.jsx("span",{children:e})]}),i&&t.jsx("div",{className:"onboarding-disclosure-content",children:n})]})}function II({items:e}){return e.some(s=>s.status!=="connected")?t.jsxs("div",{className:"onboarding-readiness-summary","data-testid":"readiness-summary",role:"status",children:[t.jsx("p",{className:"onboarding-readiness-header",children:"Setup Summary"}),e.map(s=>{const i=s.status==="connected"?"✓":s.status==="missing"?"⚠":"○";return t.jsxs("div",{className:`onboarding-readiness-item onboarding-readiness-item--${s.status}`,"data-status":s.status,children:[t.jsx("span",{className:"onboarding-readiness-icon","aria-hidden":"true",children:i}),t.jsxs("span",{className:"onboarding-readiness-content",children:[t.jsx("span",{className:"onboarding-readiness-label",children:s.label}),s.detail&&t.jsx("span",{className:"onboarding-readiness-detail",children:s.detail})]})]},s.label)})]}):t.jsx("div",{className:"onboarding-readiness-summary","data-testid":"readiness-summary",role:"status",children:t.jsx("p",{className:"onboarding-readiness-all-connected",children:"✓ All integrations connected"})})}function $I({provider:e,apiKeyInfo:n,inputValue:s,isSaving:i,error:r,success:o,isConnected:l,onInputChange:c,onSave:u,onClear:d}){const m=`onboarding-apikey-input-${e.id}`,h=i||!s.trim(),f=qg[e.id],p=`input onboarding-apikey-input${r?" onboarding-apikey-input--error":""}${o?" onboarding-apikey-input--success":""}`,g=t.jsxs(t.Fragment,{children:[f&&t.jsxs("small",{className:"onboarding-apikey-hint",children:["Format: ",f.hint]}),t.jsx("p",{className:"onboarding-apikey-instructions",children:n.setupInstructions}),n.dashboardUrl&&t.jsx("a",{href:n.dashboardUrl,target:"_blank",rel:"noreferrer",className:"onboarding-apikey-dashboard-link",children:"Get your API key →"}),t.jsx("p",{className:"onboarding-apikey-usage",children:n.usageDescription})]});return l?t.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${e.id}`,children:[t.jsxs("div",{className:"onboarding-apikey-connected-header",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:n.fieldLabel}),t.jsx("span",{className:"auth-status-badge connected",children:"✓ API key saved"})]}),t.jsx("button",{className:"btn btn-sm",onClick:()=>d(e.id),disabled:i,children:i?"Removing…":"Remove Key"}),t.jsx(si,{summary:"Advanced setup details",children:g}),r&&t.jsx("small",{className:"field-error",children:r})]}):t.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${e.id}`,children:[t.jsx("label",{htmlFor:m,className:"onboarding-apikey-field-label",children:n.fieldLabel}),t.jsxs("div",{className:"onboarding-apikey-input-row",children:[t.jsx("input",{id:m,type:"password",className:p,placeholder:n.inputPlaceholder??"Enter API key",value:s,onChange:b=>c(e.id,b.target.value),onKeyDown:b=>{b.key==="Enter"&&u(e.id,s)},"data-testid":m}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>u(e.id,s),disabled:h,"data-testid":`onboarding-apikey-save-${e.id}`,children:i?"Saving…":"Save"})]}),r&&t.jsx("small",{className:"field-error",children:r}),o&&!r&&t.jsx("small",{className:"onboarding-apikey-success","data-testid":`onboarding-apikey-success-${e.id}`,children:o}),t.jsx(si,{summary:"Advanced setup details",children:g})]})}const DI=150;function LI({onComplete:e,addToast:n,projectId:s,onOpenSetupWizard:i,onOpenNewTask:r,onOpenGitHubImport:o,firstCreatedTask:l,onViewTask:c}){const u=As(),d=u?.currentStep,m=d==="complete"?"ai-setup":ki.includes(d)?d:"ai-setup",h=u?.completedSteps??[],f=u?.skippedSteps??pI(),[p,g]=a.useState(!0),[b,v]=a.useState(m),[x,y]=a.useState(h),[j,E]=a.useState(f),[C,w]=a.useState(!1),[R,S]=a.useState(""),[O,_]=a.useState(!1),[P,U]=a.useState(null),[G,M]=a.useState(null),[T,D]=a.useState([]),[K,J]=a.useState(void 0),[te,N]=a.useState(!0),[z,I]=a.useState(null),[k,H]=a.useState({}),[Q,ue]=a.useState([]),[be,V]=a.useState(""),[ve,B]=a.useState(!1),[Y,X]=a.useState({}),[he,de]=a.useState({}),[me,se]=a.useState({}),[_e,Fe]=a.useState([]),[Te,st]=a.useState(!1),[nt,qe]=a.useState(!1),[Xe,$e]=a.useState(),Ue=a.useRef({}),oe=a.useRef(null),je=a.useRef(null),ie=a.useRef(null),[Ae,Le]=a.useState({}),[we,Ee]=a.useState(()=>As()?.stepData?.github?.skipped===!0),Ve=a.useRef(0),rt=a.useRef(l),xe=a.useRef(!1),ce=u?.currentStep,Pe=!!u&&u.currentStep!=="complete";di(je,p,"fusion:model-onboarding-modal-size"),a.useEffect(()=>{const A=oe.current;A&&(A.scrollTop=0)},[b]);const[pe,Re]=a.useState(()=>As()?.stepData?.["ai-setup"]?.skippedProviders??{}),Qe=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"project-setup",label:"Project"},{key:"first-task",label:"First Task"}],Ie=Qe.findIndex(A=>A.key===b),bt=b==="complete"?Qe.length:Ie;a.useEffect(()=>{b!=="complete"&&Co(b,{completedSteps:x,skippedSteps:j})},[b,x,j]),a.useEffect(()=>{xe.current||(xe.current=!0,Is("onboarding:wizard-opened",{source:Pe?"resume":"initial",resumedFromStep:ce}))},[Pe,ce]),a.useEffect(()=>{const A=rt.current!=null,le=l!=null;!A&&le&&w(!0),le||w(!1),rt.current=l},[l]);const ee=a.useRef(m);a.useEffect(()=>{if(ee.current==="ai-setup"&&b!=="ai-setup"&&!T.some(le=>le.id!=="github"&&le.authenticated)){const le={};for(const ye of T)ye.id!=="github"&&!ye.authenticated&&!pe[ye.id]&&(le[ye.id]=!0);if(Object.keys(le).length>0){const ye={...pe,...le};Re(ye),Co(b,{stepData:{"ai-setup":{skippedProviders:ye}}})}}ee.current=b},[b,T,pe]);const re=a.useCallback(async()=>{try{const{providers:A,ghCli:le}=await Er(),ye=Yh(A);D(ye),J(le),H(Ye=>{const mt={};for(const[ht,Kt]of Object.entries(Ye)){const Jt=ye.find(zn=>zn.id===ht);Jt&&!Jt.authenticated&&Jt.loginInProgress&&(mt[ht]=Kt)}return Object.keys(mt).length===Object.keys(Ye).length?Ye:mt}),Le(Ye=>{let mt=!1;const ht={...Ye};for(const[Kt,Jt]of Object.entries(Ye)){if(Jt!=="pending")continue;ye.find(Hn=>Hn.id===Kt)?.loginInProgress||(delete ht[Kt],mt=!0)}return mt?ht:Ye}),Re(Ye=>{const mt={...Ye};for(const ht of ye)ht.authenticated&&mt[ht.id]&&delete mt[ht.id];return Object.keys(mt).length===Object.keys(Ye).length?Ye:mt})}catch{}},[]),Se=a.useCallback(async()=>{try{const A=await Qy();Fe((A.providers??[]).map(SI))}catch{}},[]),ot=a.useCallback(async A=>{qe(!0),$e(void 0);try{await Zy(A),await Se(),await bs().then(le=>ue(le.models??[])),st(!1)}catch(le){$e(ke(le)||"Failed to create custom provider")}finally{qe(!1)}},[Se]),ne=a.useRef(!1);a.useEffect(()=>{b==="ai-setup"&&Se(),ne.current&&re(),ne.current=b!=="ai-setup"},[b,re,Se]),a.useEffect(()=>{if(!T.some(ye=>ye.loginInProgress))return;const le=setInterval(()=>{re()},2e3);return()=>clearInterval(le)},[T,re]);const Ze=T.find(A=>A.id==="github"),ft=!!Ze,gt=Ze?.authenticated??!1,St=Ze?.loginInProgress??!1,Nt=K?.authenticated??!1,pt=gt||Nt,kt=!gt&&Nt,Ht=a.useCallback(A=>{if(A.authenticated)return"connected";const le=Ae?.[A.id];return le==="timeout"||le==="failed"?"retry":pe[A.id]?"skipped":"not-connected"},[Ae,pe]);function $t({status:A}){const le={connected:{text:"✓ Connected",className:"auth-status-badge connected"},"not-connected":{text:"Not connected",className:"auth-status-badge not-connected"},skipped:{text:"Skipped",className:"auth-status-badge skipped"},retry:{text:"Retry",className:"auth-status-badge retry"}},{text:ye,className:Ye}=le[A];return t.jsx("span",{"data-testid":"provider-status-badge",className:Ye,"data-status":A,children:ye})}const Tt=a.useCallback(()=>{if(pt)return"connected";const A=Ae.github;return A==="pending"?"pending":A==="failed"||A==="timeout"?"failed":we?"skipped":"not-connected"},[pt,Ae,we]);function Mt({status:A}){const le={connected:{text:"✓ Connected",className:"auth-status-badge connected"},pending:{text:"⏳ Connecting…",className:"auth-status-badge pending"},failed:{text:"✗ Connection failed",className:"auth-status-badge retry"},skipped:{text:"Skipped",className:"auth-status-badge skipped"},"not-connected":{text:"Not connected",className:"auth-status-badge not-connected"}},{text:ye,className:Ye}=le[A];return t.jsx("span",{"data-testid":"github-status-badge",className:Ye,"data-status":A,children:ye})}const Ot=a.useCallback(async()=>{try{const A=await bs();ue(A.models)}catch{}},[]),zt=a.useCallback(async()=>{try{const A=await Yi();if(A.defaultProvider&&A.defaultModelId){const le=`${A.defaultProvider}/${A.defaultModelId}`;V(le)}}catch{}},[]);a.useEffect(()=>{Promise.all([re(),Ot(),zt()]).finally(()=>N(!1))},[re,Ot,zt]),a.useEffect(()=>{const A=fI("ai-setup");if(A?.loginOutcomes){const le=A.loginOutcomes,ye={};for(const[Ye,mt]of Object.entries(le))mt!=="pending"&&(ye[Ye]=mt);Object.keys(ye).length>0&&Le(ye)}},[]);const Ft=a.useCallback((A,le)=>{Co(b,{completedSteps:x,stepData:{"ai-setup":{loginOutcomes:{[A]:le}}}})},[b,x]);a.useEffect(()=>{const A=Object.entries(Ae).filter(([le,ye])=>ye!=="pending");for(const[le,ye]of A)Ft(le,ye)},[Ae,Ft]),a.useEffect(()=>()=>{ie.current&&clearInterval(ie.current),Object.values(Ue.current).forEach(clearTimeout),Ue.current={}},[]);const Et=a.useCallback(A=>{Ee(A),Co(b,{completedSteps:x,stepData:{github:{skipped:A}}})},[b,x]),Pt=a.useCallback(A=>A==="complete"?-1:ki.indexOf(A),[]),Dt=a.useCallback(()=>{y(le=>[...new Set([...le,b])]),E(le=>le.filter(ye=>ye!==b)),Is("onboarding:step-completed",{step:b}),b==="github"&&!gt&&Et(!1);const A=Pt(b);A>=0&&A<ki.length-1&&v(ki[A+1])},[b,gt,Et,Pt]),Wt=a.useCallback(()=>{E(le=>[...new Set([...le,b])]),dI(b),Is("onboarding:step-skipped",{step:b}),b==="github"&&!gt&&Et(!0);const A=Pt(b);A>=0&&A<ki.length-1&&v(ki[A+1])},[b,gt,Et,Pt]),It=a.useCallback(()=>{const A=b;y(ye=>ye.filter(Ye=>Ye!==A)),E(ye=>ye.filter(Ye=>Ye!==A)),A==="github"&&!gt&&Et(!1);const le=Pt(b);le>0&&v(ki[le-1])},[b,gt,Et,Pt]),Rt=a.useCallback(()=>{Wt()},[Wt]),fe=a.useCallback(async A=>{Le(le=>{const ye=le[A];if(ye&&ye!=="pending"){const{[A]:Ye,...mt}=le;return mt}return le}),H(le=>{if(!(A in le))return le;const ye={...le};return delete ye[A],ye}),Le(le=>({...le,[A]:"pending"})),I(A),Ve.current=0;try{const{url:le,instructions:ye}=await ew(A);ye?.trim()&&H(Ye=>({...Ye,[A]:ye})),window.open(oi(le),"_blank"),ie.current=setInterval(async()=>{if(Ve.current++,Ve.current>=DI){ie.current&&(clearInterval(ie.current),ie.current=null),I(null),Le(Ye=>({...Ye,[A]:"timeout"})),H(Ye=>{if(!(A in Ye))return Ye;const mt={...Ye};return delete mt[A],mt}),n("Login timed out. Please try again.","warning");return}try{const{providers:Ye,ghCli:mt}=await Er(),ht=Yh(Ye);D(ht),J(mt),ht.find(Jt=>Jt.id===A)?.authenticated&&(ie.current&&(clearInterval(ie.current),ie.current=null),I(null),Le(Jt=>({...Jt,[A]:"success"})),H(Jt=>{if(!(A in Jt))return Jt;const zn={...Jt};return delete zn[A],zn}),A==="github"&&Et(!1),n("Login successful","success"))}catch{}},2e3)}catch(le){le instanceof Error&&le.message.includes("already in progress")||le&&typeof le=="object"&&"status"in le&&le.status===409?(n("Login already in progress. Cancel it to retry.","warning"),Le(Ye=>({...Ye,[A]:"pending"})),re()):(n(le instanceof Error?le.message:"Login failed","error"),Le(Ye=>({...Ye,[A]:"failed"}))),I(null),H(Ye=>{if(!(A in Ye))return Ye;const mt={...Ye};return delete mt[A],mt})}},[n,re,Et]),Oe=a.useCallback(async A=>{ie.current&&(clearInterval(ie.current),ie.current=null),I(A),Ve.current=0;try{await nw(A),await re(),Le(le=>({...le,[A]:"cancelled"})),n("Login cancelled","success")}catch(le){n(ke(le)||"Failed to cancel login","error")}finally{I(null),H(le=>{if(!(A in le))return le;const ye={...le};return delete ye[A],ye})}},[n,re]),ut=a.useCallback((A,le)=>{X(Ye=>({...Ye,[A]:le}));const ye=Ue.current[A];ye&&(clearTimeout(ye),delete Ue.current[A]),de(Ye=>{if(!Ye[A])return Ye;const mt={...Ye};return delete mt[A],mt}),se(Ye=>{if(!Ye[A])return Ye;const mt={...Ye};return delete mt[A],mt})},[]),L=a.useCallback(()=>{const A=oe.current;if(!A)return;const le=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof A.scrollTo=="function"){A.scrollTo({top:0,behavior:le?"auto":"smooth"});return}}catch{}A.scrollTop=0},[]),F=a.useCallback(async(A,le)=>{const ye=(le??Y[A]??"").trim(),Ye=RI(A,ye);if(Ye){de(ht=>({...ht,[A]:Ye}));return}const mt=Ue.current[A];mt&&(clearTimeout(mt),delete Ue.current[A]),I(A),de(ht=>{const Kt={...ht};return delete Kt[A],Kt}),se(ht=>{if(!ht[A])return ht;const Kt={...ht};return delete Kt[A],Kt});try{await sw(A,ye),await re(),L(),X(ht=>{const Kt={...ht};return delete Kt[A],Kt}),de(ht=>{if(!ht[A])return ht;const Kt={...ht};return delete Kt[A],Kt}),se(ht=>({...ht,[A]:"✓ Key saved"})),Ue.current[A]=setTimeout(()=>{se(ht=>{if(!ht[A])return ht;const Kt={...ht};return delete Kt[A],Kt}),delete Ue.current[A]},3e3),n("API key saved","success")}catch(ht){const Kt=ht instanceof TypeError&&ht.message.includes("Failed to fetch")?"Could not reach the server. Check your connection and try again.":ht instanceof Error?ht.message:"Failed to save API key";de(Jt=>({...Jt,[A]:Kt})),se(Jt=>{if(!Jt[A])return Jt;const zn={...Jt};return delete zn[A],zn}),n(Kt,"error")}finally{I(null)}},[Y,n,re,L]),ge=a.useCallback(async A=>{I(A);try{await iw(A),await re(),n("API key removed","success")}catch(le){n(le instanceof Error?le.message:"Failed to clear API key","error")}finally{I(null)}},[n,re]),ze=a.useCallback(async A=>{I(A);try{await tw(A),await re(),n("Logged out","success")}catch(le){n(le instanceof Error?le.message:"Logout failed","error")}finally{I(null)}},[n,re]),Be=a.useCallback(A=>{V(A)},[]),Ke=a.useCallback(async()=>{try{const A={modelOnboardingComplete:!0};if(be){const le=be.indexOf("/"),ye=le!==-1?be.slice(0,le):void 0,Ye=le!==-1?be.slice(le+1):be,mt=Q.find(ht=>ht.id===Ye);mt?(A.defaultProvider=mt.provider,A.defaultModelId=mt.id):ye&&Ye&&(A.defaultProvider=ye,A.defaultModelId=Ye)}await bn(A),Qh()}catch{}},[be,Q,bn,Qh]),dt=a.useCallback(async()=>{const A=[...new Set([...x,"first-task"])];B(!0);try{await Ke(),Is("onboarding:completed",{completedSteps:A,skippedSteps:j}),y(A),E(le=>le.filter(ye=>ye!=="first-task")),v("complete")}finally{B(!1)}},[Ke,x,j]),Xt=a.useCallback(async()=>{if(!s)return;const A=R.trim();if(!A){U("Please enter a task description.");return}U(null),_(!0);let le=!1;try{const ye=await Ip({description:A,source:{sourceType:"dashboard_ui"}},s);M(ye),w(!0),Is("onboarding:first-task-created",{taskId:ye?.id}),n("Task created","success"),le=!0}catch(ye){const Ye=ye instanceof Error?ye.message:"Something went wrong creating your task. Please try again.";U(Ye),n(Ye,"error")}finally{_(!1)}le&&Ke()},[s,R,n,Ke]),Cn=a.useCallback(async()=>{B(!0);try{await Ke()}finally{B(!1)}Is("onboarding:open-new-task",{}),r?.()},[Ke,r]),pn=a.useCallback(async()=>{if(pt){B(!0);try{await Ke()}finally{B(!1)}g(!1),e(),Is("onboarding:open-github-import",{}),o?.()}},[Ke,pt,e,o]),Kn=a.useCallback(async()=>{Is("onboarding:dismissed",{currentStep:b,completedSteps:x,skippedSteps:j}),B(!0);try{await bn({modelOnboardingComplete:!0})}catch{}g(!1),e()},[b,x,j,e]),Lt=a.useCallback(()=>{Is("onboarding:finished",{}),g(!1),e()},[e]),Zt=a.useCallback(()=>{const A=l??G;A&&(Ke(),c?.(A),e())},[l,G,Ke,c,e]),Ne=a.useCallback(()=>{Ke(),e()},[Ke,e]);if(!p)return null;const et=Tt(),ln=T.filter(A=>A.id!=="github"),wn=[...ln].sort(np),Gn=wn.some(A=>!A.type||A.type==="oauth"),Tn=wn.some(A=>A.type==="api_key"),Un=ln.filter(A=>A.authenticated),sn=Un.length>0,un=!!s,Bn=b==="github"&&!sn,Sn=(()=>{if(!be)return"";const A=be.indexOf("/"),le=A===-1?void 0:be.slice(0,A),ye=A===-1?be:be.slice(A+1),Ye=Q.find(mt=>mt.id===ye&&(!le||mt.provider===le));return Ye?.name?Ye.name:le?`${dd(le)} ${ye}`:be})(),an=[];if(un?an.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):an.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),sn){const A=dd(Un[0]?.id??"");an.push({label:"AI Provider",status:"connected",detail:`${A} connected — AI agents can work on tasks`})}else ln.length>0&&ln.some(A=>pe[A.id])?an.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):an.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});pt?an.push({label:"GitHub",status:"connected",detail:kt?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!ft||we?an.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):an.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),Sn&&an.push({label:"Default Model",status:"connected",detail:Sn});const Dn=l??G,Ln=Dn?.description?.split(`
|
|
662
|
-
`)[0]?.trim()||Dn?.title||"",ss=new Set(Ec),Pn=wn.filter(A=>ss.has(A.id)).sort((A,le)=>{const ye=Ec.indexOf(A.id),Ye=Ec.indexOf(le.id);return ye!==Ye?ye-Ye:np(A,le)}),nn=wn.filter(A=>A.authenticated&&!ss.has(A.id)),vt=wn.filter(A=>!A.authenticated&&!ss.has(A.id)),rn=A=>{if(A.id==="droid-cli"&&A.type==="cli")return t.jsx(ZP,{authenticated:A.authenticated,onToggled:()=>{re()}},A.id);if(A.id==="claude-cli"&&A.type==="cli")return t.jsx(QP,{authenticated:A.authenticated,onToggled:()=>{re()}},A.id);if(A.type==="api_key"){const le=md(A.id),ye=PI(A);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${A.id}`,className:`onboarding-provider-card${A.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${A.id}`,"aria-hidden":"true",children:t.jsx(Rn,{provider:A.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(Ep,{size:14,className:"onboarding-provider-key-icon"}),A.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:le.description}),t.jsx($t,{status:Ht(A)}),A.authenticated&&A.keyHint&&t.jsxs("span",{className:"auth-key-hint",children:["Key: ",A.keyHint]})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx($I,{provider:A,apiKeyInfo:ye,inputValue:Y[A.id]??"",isSaving:z===A.id,error:he[A.id],success:me[A.id],isConnected:A.authenticated,onInputChange:ut,onSave:F,onClear:ge})})]},A.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${A.id}`,className:`onboarding-provider-card${A.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${A.id}`,"aria-hidden":"true",children:t.jsx(Rn,{provider:A.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:A.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:md(A.id).description}),t.jsx($t,{status:Ht(A)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:z===A.id?A.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 Oe(A.id),children:"Cancel"})]}):A.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 Oe(A.id),children:"Cancel"})]}):A.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>ze(A.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>fe(A.id),children:"Login"})}),(z===A.id||A.loginInProgress)&&k[A.id]&&t.jsx(Cc,{instructions:k[A.id],"data-testid":`onboarding-login-instructions-${A.id}`}),Ae[A.id]==="timeout"&&z!==A.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),Ae[A.id]==="failed"&&z!==A.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},A.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:[b==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(es,{size:24})," Set Up AI ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),b==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(Es,{size:24})," Connect GitHub ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),b==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(Zd,{size:24})," Set Up Your Project"]}),b==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(Zd,{size:24})," Create Your First Task"]}),b==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx(Nn,{size:24})," All Set!"]})]}),b!=="complete"&&t.jsx("button",{className:"modal-close",onClick:Kn,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(qt,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:Qe.map((A,le)=>{const ye=bt>le,Ye=x.includes(A.key)&&ye,mt=j.includes(A.key)&&!x.includes(A.key)&&ye,ht=Ye||mt;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[le>0&&t.jsx("div",{className:`model-onboarding-step-connector ${le<=bt?"done":""}`}),ht?t.jsxs("button",{className:`model-onboarding-step-indicator ${b===A.key?"active":""} ${Ye?"done":""} ${mt?"skipped":""}`,onClick:()=>v(A.key),"aria-label":`Go back to ${A.label}`,title:`Review ${A.label}`,children:[t.jsx("span",{className:"step-number",children:Ye?t.jsx(Nn,{size:14}):mt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):le+1}),t.jsx("span",{className:"step-label",children:A.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${b===A.key?"active":""} ${Ye?"done":""} ${mt?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:Ye?t.jsx(Nn,{size:14}):mt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):le+1}),t.jsx("span",{className:"step-label",children:A.label})]})]},A.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:oe,children:[b==="ai-setup"&&t.jsxs("div",{className:"model-onboarding-ai-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Fusion uses AI models to plan, write, and review code for you. Connect an AI provider below to get started — you can use a hosted service or enter an API key."}),t.jsx("p",{className:"onboarding-helper-text model-onboarding-primary-helper",children:"You only need one provider to get started."}),!te&&T.length>0&&(()=>{const A=T.filter(ht=>ht.id!=="github"&&ht.authenticated).length,le=T.filter(ht=>ht.id!=="github").length,ye=Object.keys(pe).filter(ht=>!T.find(Kt=>Kt.id===ht)?.authenticated).length;if(le===0)return null;let Ye="onboarding-provider-summary",mt="";return A>0?(Ye+=" onboarding-provider-summary--connected",mt=`✓ ${A} of ${le} provider${le!==1?"s":""} connected`):ye>0?(Ye+=" onboarding-provider-summary--skipped",mt=`${ye} provider${ye!==1?"s":""} skipped`):(Ye+=" onboarding-provider-summary--none",mt="No providers connected yet"),t.jsx("div",{className:Ye,"data-testid":"provider-summary",children:mt})})(),t.jsx(si,{summary:"What are AI providers?",children:t.jsx("p",{className:"onboarding-helper-text",children:"AI providers like OpenAI and Anthropic power the AI capabilities in Fusion. Connecting a provider lets Fusion's agents use AI models to help with your tasks."})}),T.length>0&&!T.some(A=>A.authenticated)&&t.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),te?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(lt,{size:24,className:"animate-spin"}),t.jsx("span",{children:"Loading providers…"})]}):T.length===0?t.jsx("div",{className:"model-onboarding-empty",children:"No AI providers are configured. Please check your Fusion configuration."}):t.jsxs(t.Fragment,{children:[t.jsxs("section",{className:"onboarding-provider-section","data-testid":"onboarding-quick-start-providers",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Quick start providers"}),Pn.length>0?t.jsx("div",{className:"model-onboarding-providers",children:Pn.map(A=>rn(A))}):t.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),nn.length>0&&t.jsxs("section",{className:"onboarding-provider-section","data-testid":"onboarding-connected-providers",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Connected providers"}),t.jsx("div",{className:"model-onboarding-providers",children:nn.map(A=>rn(A))})]}),t.jsxs("div",{className:"onboarding-model-section",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Default Model (Optional)"}),t.jsx("p",{className:"model-onboarding-description",children:"Pick a default model for AI tasks, or leave this blank to choose later. Models vary in speed, capability, and cost."}),t.jsx(si,{summary:"How do I choose a model?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Models vary in speed, capability, and cost. A good default is usually the latest model from your connected provider. You can always change this later in Settings."})}),Q.length===0?t.jsx("div",{className:"model-onboarding-empty",children:"No models available yet. Connect a provider above to see model options."}):t.jsx("div",{className:"onboarding-model-selector",children:t.jsx(ns,{models:Q,value:be,onChange:Be,placeholder:"Select a default model…",label:"Default model"})}),be&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",Q.find(A=>A.id===be)?.name??be]})})]}),t.jsx(si,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:t.jsxs("div",{"data-testid":"onboarding-advanced-provider-settings",children:[vt.length>0?t.jsx("div",{className:"model-onboarding-providers",children:vt.map(A=>rn(A))}):t.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."}),_e.length>0?t.jsx("div",{className:"onboarding-custom-provider-list",children:_e.map(A=>t.jsxs("div",{className:"onboarding-custom-provider-item",children:[t.jsx(Rn,{provider:A.id,size:"sm"}),t.jsx("span",{children:A.name||A.id})]},A.id))}):null,Te?t.jsx(iI,{onSave:ot,onCancel:()=>{st(!1),$e(void 0)},saving:nt,error:Xe}):t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>st(!0),children:"Add custom provider"})]})}),Gn&&t.jsx(si,{summary:"How does login work?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Clicking Login opens the provider's website in a new tab where you sign in. Once you authorize Fusion, this page will automatically detect the connection. Your credentials are never stored in Fusion."})}),Tn&&t.jsx(si,{summary:"What is an API key?",children:t.jsx("p",{className:"onboarding-helper-text",children:"An API key is a secret token that authenticates Fusion with the provider. You can find your key in the provider's dashboard under API settings. Keys are stored securely on your machine."})})]})]}),b==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[pt?t.jsx("p",{className:"model-onboarding-description",children:kt?"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."}),!pt&&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"})]})}),Bn&&t.jsxs("div",{className:"onboarding-skip-banner",role:"status",children:[t.jsx("strong",{children:"No AI provider connected"}),t.jsx("p",{children:"AI features like task planning and code generation won't be available until you connect one. You can set this up later in Settings."})]}),t.jsx(si,{summary:"What does GitHub integration do?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Without GitHub, you can still create and manage tasks manually. GitHub integration adds the ability to import issues as tasks, track pull request status alongside your work, and automatically link commits to tasks. Connect anytime from Settings → Authentication."})}),ft?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"onboarding-provider-row",children:[t.jsxs("div",{className:"onboarding-provider-info",children:[t.jsxs("strong",{children:[t.jsx(Es,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(Mt,{status:et})})]}),gt&&(z==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>ze("github"),children:"Disconnect"}))]}),(et==="not-connected"||et==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[z==="github"||St?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 Oe("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>fe("github"),children:[t.jsx(Es,{size:16}),"Connect"]}),(z==="github"||St)&&k.github&&t.jsx(Cc,{instructions:k.github,"data-testid":"onboarding-login-instructions-github"})]}),et==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:kt?"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."}),et==="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:()=>fe("github"),children:"Retry"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Rt,children:"Skip for now"})]})]}),et==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),et==="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:()=>fe("github"),children:"Connect anyway"})})]}),et==="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(Rn,{provider:"github",size:"lg"})}),kt?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:kt?"Continue with gh CLI auth →":"Continue without GitHub →"}),kt&&(z==="github"||St?t.jsxs("button",{className:"btn btn-sm",disabled:!0,children:[t.jsx(lt,{size:14,className:"onboarding-spinner"}),"Waiting for OAuth login…"]}):t.jsxs("button",{className:"btn btn-sm",onClick:()=>fe("github"),children:[t.jsx(Rn,{provider:"github",size:"sm"}),"Connect OAuth (optional)"]}))]}),kt&&(z==="github"||St)&&k.github&&t.jsx(Cc,{instructions:k.github,"data-testid":"onboarding-login-instructions-github"})]})]}),b==="project-setup"&&t.jsxs("div",{className:"model-onboarding-project-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Choose your first project before creating or importing tasks. You can register an existing local directory or clone a GitHub repository URL through the setup wizard."}),un?t.jsx("div",{className:"onboarding-project-ready","data-testid":"onboarding-project-ready",role:"status",children:t.jsx("p",{children:"Project selected — task creation and imports are available."})}):t.jsxs("div",{className:"onboarding-project-prerequisite","data-testid":"onboarding-project-prerequisite",children:[t.jsx("p",{className:"onboarding-helper-text",children:"A project is required before first-task actions are available."}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:i,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"}),t.jsx("p",{className:"onboarding-helper-text",children:"In the setup wizard, pick an existing directory or paste a GitHub clone URL."})]}),t.jsx(si,{summary:"What does project setup do?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Project setup registers a workspace so Fusion knows where to read files, run commands, and track task changes."})})]}),b==="first-task"&&t.jsxs("div",{className:"model-onboarding-first-task",children:[t.jsx("p",{className:"model-onboarding-description",children:"Create your first task to start the board and launch AI execution."}),C&&Dn?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx(Nn,{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:Dn.id}),Ln&&t.jsx("p",{className:"onboarding-task-created__description",children:Ln}),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:Zt,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:Ne,children:"Go to Dashboard"})]})]}):t.jsxs(t.Fragment,{children:[un?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:R,onChange:A=>{S(A.target.value),U(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:Xt,disabled:O,"data-testid":"onboarding-first-task-submit",children:O?t.jsxs(t.Fragment,{children:[t.jsx(lt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),P&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:P}),t.jsx("p",{className:"onboarding-helper-text",children:"Your text has been preserved — fix the issue and try again."})]})]}):t.jsxs("div",{className:"onboarding-project-prerequisite","data-testid":"onboarding-project-prerequisite",children:[t.jsx("p",{className:"onboarding-helper-text",children:"A project must be selected before you can create tasks or import from GitHub."}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:i,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"})]}),t.jsx(II,{items:an}),un&&t.jsxs(t.Fragment,{children:[t.jsx(si,{summary:"What happens when I create a task?",children:t.jsx("p",{className:"onboarding-helper-text",children:"A task describes something you want done. Fusion's AI agents will read your description and work on implementing it. You can track progress on the board and review the results."})}),t.jsxs("div",{className:"onboarding-cta-options",children:[t.jsxs("button",{className:"onboarding-cta-card primary",onClick:Cn,disabled:ve,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(dn,{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${pt?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:pn,disabled:ve||!pt,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(Es,{size:24})}),t.jsxs("div",{className:"cta-content",children:[t.jsx("strong",{children:"Import from GitHub"}),t.jsx("span",{children:"Turn GitHub issues into tasks you can track here"}),!pt&&t.jsx("small",{className:"onboarding-cta-note",children:"Requires GitHub connection"})]})]})]}),t.jsxs("p",{className:"onboarding-skip-note",children:["You can create tasks anytime from the board, or use"," ",t.jsx("code",{children:"fn task create"})," in the terminal."]})]})]})]}),b==="complete"&&t.jsxs("div",{className:"model-onboarding-complete",children:[t.jsx(Nn,{size:48,className:"success-icon"}),t.jsx("p",{children:"Setup complete! Head to the board to create your first task, or explore the dashboard to see what's available."})]})]}),t.jsxs("div",{className:"model-onboarding-footer",children:[b==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Kn,disabled:ve,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Wt,children:"Skip setup →"}),t.jsx("button",{className:"btn btn-primary",onClick:Dt,children:"Next →"})]}),b==="github"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:It,children:"← Back"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Wt,children:"Skip GitHub →"}),t.jsx("button",{className:"btn btn-primary",onClick:Dt,children:"Next →"})]}),b==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:It,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:Dt,disabled:!un,children:"Next →"})]}),b==="first-task"&&!C&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:It,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:dt,disabled:ve,children:ve?t.jsxs(t.Fragment,{children:[t.jsx(lt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),b==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:Lt,children:[t.jsx(Nn,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function Wg({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 zI=a.lazy(()=>hn(()=>import("./SetupWizardModal-C_d9clJp.js"),__vite__mapDeps([12,1,13,14,15,6,7,16])).then(e=>({default:e.SetupWizardModal}))),OI=a.lazy(()=>hn(()=>import("./SettingsModal-C0DokcId.js"),__vite__mapDeps([17,1,18,19,20,2,6,7,21])).then(e=>({default:e.SettingsModal})));function FI(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{hn(()=>import("./SettingsModal-C0DokcId.js"),__vite__mapDeps([17,1,18,19,20,2,6,7,21]))},{timeout:1500})}function UI({projectId:e,tasks:n,projects:s,currentProject:i,addToast:r,toasts:o,removeToast:l,modalManager:c,projectActions:u,taskHandlers:d,taskOperations:m,deepLink:h,settings:f,onSettingsClose:p,onReopenOnboarding:g}){const[b,v]=a.useState(null),x=c.detailTask?(()=>{const R=n.find(S=>S.id===c.detailTask?.id);return R?"prompt"in c.detailTask?{...c.detailTask,...R,prompt:c.detailTask.prompt,log:c.detailTask.log}:R:c.detailTask})():null,y=p??c.closeSettings,j=a.useCallback(()=>{c.openNewTask()},[c]),E=a.useCallback(()=>{c.openGitHubImport()},[c]),C=a.useCallback(R=>{v(null),c.closeModelOnboarding(),c.openDetailTask(R)},[c]),w=a.useCallback(async R=>{const S=await d.handleModalCreate(R);return c.modelOnboardingOpen&&v(S),S},[d.handleModalCreate,c.modelOnboardingOpen]);return a.useEffect(()=>{!c.modelOnboardingOpen&&b&&v(null)},[c.modelOnboardingOpen,b]),a.useEffect(()=>{FI()},[]),t.jsxs(t.Fragment,{children:[x&&t.jsx($i,{children:t.jsx(_R,{task:x,projectId:e,tasks:n,onClose:h.handleDetailClose,onOpenDetail:c.openDetailTask,onMoveTask:m.moveTask,onDeleteTask:m.deleteTask,onMergeTask:m.mergeTask,onRetryTask:m.retryTask,onResetTask:m.resetTask,onDuplicateTask:m.duplicateTask,onTaskUpdated:c.updateDetailTask,addToast:r,prAuthAvailable:f.prAuthAvailable,initialTab:c.detailTaskInitialTab})}),c.settingsOpen&&t.jsx($i,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(OI,{onClose:y,addToast:r,initialSection:c.settingsInitialSection,projectId:e,themeMode:f.themeMode,colorTheme:f.colorTheme,onThemeModeChange:f.setThemeMode,onColorThemeChange:f.setColorTheme,dashboardFontScalePct:f.dashboardFontScalePct,onDashboardFontScaleChange:f.setDashboardFontScalePct,onReopenOnboarding:g})})}),t.jsx(AR,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:d.handleGitHubImport,tasks:n,projectId:e}),t.jsx($i,{children:t.jsx($R,{isOpen:c.isPlanningOpen,onClose:c.closePlanning,onTaskCreated:d.handlePlanningTaskCreated,onTasksCreated:d.handlePlanningTasksCreated,tasks:n,initialPlan:c.planningInitialPlan??void 0,projectId:e,resumeSessionId:c.planningResumeSessionId})}),t.jsx($i,{children:t.jsx(VR,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:d.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx(hT,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx(fT,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx(LT,{initialWorkspace:c.fileBrowserWorkspace,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),t.jsx(WT,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e,anchorRect:c.usageAnchorRect}),t.jsx(wP,{isOpen:c.systemStatsOpen,onClose:c.closeSystemStats,projectId:e}),c.schedulesOpen&&t.jsx(mP,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx($i,{children:t.jsx(gP,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:w,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan,onSubtaskBreakdown:c.openSubtaskBreakdown})}),t.jsx(CP,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:i,onOpenTaskDetail:R=>{const S=n.find(O=>O.id===R);S&&c.openDetailTask(S)}}),t.jsx($i,{children:t.jsx(_P,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx($i,{children:t.jsx(FP,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(YP,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(a.Suspense,{fallback:null,children:t.jsx(zI,{onProjectRegistered:u.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(LI,{onComplete:u.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:u.handleAddProject,onOpenNewTask:j,onOpenGitHubImport:E,firstCreatedTask:b,onViewTask:C}),t.jsx(Wg,{toasts:o,onRemove:l})]})}function BI({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 hd=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function HI(e,n){if(n==="ready")return"done";const s=hd.findIndex(r=>r.id===n),i=hd.findIndex(r=>r.id===e);return i<s?"done":i===s?"active":"pending"}function qI({stage:e}){const[n]=a.useState(()=>Yv());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:hd.map(s=>{const i=HI(s.id,e);return t.jsxs("li",{className:`dashboard-loader__step dashboard-loader__step--${i}`,"data-testid":`dashboard-loader-step-${s.id}`,children:[t.jsx("span",{className:"dashboard-loader__step-icon","aria-hidden":"true",children:i==="done"?"✓":i==="active"?t.jsx(lt,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:s.label})]},s.id)})})]})})}const VI=5e3;function WI(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function KI(e,n,s){let i=0,r=0,o=0,l=0,c=0;for(const u of e){switch(u.column){case"in-progress":i++,qo(u,n,s)&&o++;break;case"todo":l++;break;case"in-review":c++;break}u.blockedBy&&u.blockedBy.length>0&&r++}return{runningTaskCount:i,blockedTaskCount:r,stuckTaskCount:o,queuedTaskCount:l,inReviewCount:c}}function GI(e,n,s,i){const[r,o]=a.useState({globalPause:!1,enginePaused:!1,maxConcurrent:2}),[l,c]=a.useState(!0),[u,d]=a.useState(null),m=a.useRef(null),h=a.useRef(null),f=a.useCallback(async()=>{h.current&&h.current.abort(),h.current=new AbortController;try{c(!0),d(null);const v=await zj(n);o(v)}catch(v){if(v instanceof Error&&v.name==="AbortError")return;d(v instanceof Error?v.message:"Failed to fetch executor stats")}finally{c(!1)}},[n]);a.useEffect(()=>(f(),()=>{h.current&&h.current.abort()}),[f]),a.useEffect(()=>(m.current&&clearInterval(m.current),m.current=setInterval(()=>{f()},VI),()=>{m.current&&(clearInterval(m.current),m.current=null)}),[f]);const p=KI(e,s,i),g=WI(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:g,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:u,refresh:f}}const JI={planning:ri,subtask:qi,mission_interview:ks,milestone_interview:ks,slice_interview:ks},YI={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function QI({sessions:e,generating:n,needsInput:s,onOpenSession:i,onDismissSession:r}){const{confirm:o}=Gs(),[l,c]=a.useState(!1),[u,d]=a.useState(new Set),m=a.useRef(null),h=a.useRef(new Map),f=a.useRef(null),{activeTabMap:p}=La(),g=a.useMemo(()=>Qi(),[]);if(a.useEffect(()=>{if(!l)return;const x=y=>{m.current&&!m.current.contains(y.target)&&c(!1)};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[l]),a.useEffect(()=>{const x=new Set,y=new Map;for(const j of e){const E=p.get(j.id),C=[j.status,j.updatedAt,E?.tabId??j.lockedByTab??"",E?.stale?"stale":"fresh"].join("|"),w=h.current.get(j.id);w&&w!==C&&x.add(j.id),y.set(j.id,C)}if(h.current=y,x.size!==0)return d(x),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{d(new Set),f.current=null},500),()=>{f.current&&(clearTimeout(f.current),f.current=null)}},[p,e]),e.length===0)return null;const b=e.length,v=s>0;return t.jsxs("div",{ref:m,className:"background-tasks-indicator",children:[t.jsxs("button",{className:`background-tasks-indicator__pill${v?" background-tasks-indicator__pill--attention":""}`,onClick:()=>c(x=>!x),title:`${b} background AI task${b!==1?"s":""}${s>0?` (${s} need${s!==1?"":"s"} input)`:""}`,children:[n>0&&t.jsx(lt,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&t.jsx(Pc,{size:12}),t.jsxs("span",{children:["AI ",b]})]}),l&&t.jsxs("div",{className:"background-tasks-indicator__popover",children:[t.jsx("div",{className:"background-tasks-indicator__popover-header",children:"Background Tasks"}),t.jsx("div",{className:"background-tasks-indicator__popover-list",children:e.map(x=>{const y=JI[x.type],j=x.status==="generating",E=x.status==="awaiting_input",C=x.status==="error",w=p.get(x.id),R=w?.tabId??x.lockedByTab??null,S=!!(R&&R!==g&&!w?.stale),O=u.has(x.id);return t.jsxs("div",{className:`background-tasks-indicator__item${O?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:O?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:O?"translateY(-1px)":void 0},onClick:async()=>{S&&!await o({title:"Open Active Session",message:"This session is active in another tab. Open anyway?"})||(i(x),c(!1))},children:[C?t.jsx(gs,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--color-error)"}}):t.jsx(y,{size:14,className:"background-tasks-indicator__session-icon"}),t.jsxs("div",{className:"background-tasks-indicator__session-content",children:[t.jsx("div",{className:"background-tasks-indicator__session-title",children:x.title}),t.jsxs("div",{className:"background-tasks-indicator__session-meta",children:[C?"Failed":YI[x.type],j&&" — generating...",E&&!S&&" — needs input",E&&S&&" — active in another tab"]})]}),j&&t.jsx(lt,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),E&&!S&&t.jsx(Pc,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),E&&S&&t.jsx(il,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),t.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:_=>{_.stopPropagation(),r(x.id)},title:"Dismiss",children:t.jsx(qt,{size:12})})]},x.id)})})]})]})}function XI(e){if(!e)return"no activity";const n=Date.now(),s=new Date(e).getTime(),i=n-s,r=Math.floor(i/1e3),o=Math.floor(r/60),l=Math.floor(o/60),c=Math.floor(l/24);return c>0?`${c}d ago`:l>0?`${l}h ago`:o>0?`${o}m ago`:r>10?`${r}s ago`:"just now"}function ZI(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:_n};case"paused":return{label:"Paused",color:"var(--triage)",icon:Vs};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:es}}}function e4({tasks:e,projectId:n,taskStuckTimeoutMs:s,backgroundSessions:i,backgroundGenerating:r,backgroundNeedsInput:o,onOpenBackgroundSession:l,onDismissBackgroundSession:c,lastFetchTimeMs:u,currentProjectPath:d,onOpenProjectDirectory:m}){const{stats:h,loading:f,error:p}=GI(e,n,s,u),[g,b]=a.useState(!1),v=a.useMemo(()=>ZI(h.executorState),[h.executorState]),x=a.useMemo(()=>XI(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(rl,{size:14}),p]})}):f&&h.runningTaskCount===0?t.jsx("div",{className:"executor-status-bar executor-status-bar--loading",role:"status","aria-label":"Executor status",children:t.jsx("span",{className:"executor-status-bar__loading-text",children:"Loading..."})}):t.jsxs("div",{className:`executor-status-bar ${h.executorState==="running"?"executor-status-bar--running":""}`,role:"status","aria-label":"Executor status",children:[i&&i.length>0&&l&&c&&t.jsxs(t.Fragment,{children:[t.jsx(QI,{sessions:i,generating:r??0,needsInput:o??0,onOpenSession:l,onDismissSession:c}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--queued","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Queued"}),t.jsx("span",{className:"executor-status-bar__count",children:h.queuedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--running ${h.runningTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Running"}),t.jsx("span",{className:"executor-status-bar__count",children:h.runningTaskCount}),t.jsx("span",{className:"executor-status-bar__separator","aria-hidden":"true",children:"/"}),t.jsx("span",{className:"executor-status-bar__max",children:h.maxConcurrent})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),h.stuckTaskCount>0&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--stuck",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--stuck executor-status-bar__indicator--active","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Stuck"}),t.jsx("span",{className:"executor-status-bar__count executor-status-bar__count--error",children:h.stuckTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--blocked ${h.blockedTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Blocked"}),t.jsx("span",{className:`executor-status-bar__count ${h.blockedTaskCount>0?"executor-status-bar__count--warning":""}`,children:h.blockedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--review","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"In Review"}),t.jsx("span",{className:"executor-status-bar__count",children:h.inReviewCount})]}),d&&m&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--project-directory",children:[t.jsx("button",{className:`executor-status-bar__folder-toggle${g?" executor-status-bar__folder-toggle--active":""}`,onClick:()=>b(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(ts,{size:12,"aria-hidden":"true"})}),g&&t.jsx("button",{className:"executor-status-bar__project-path",onClick:m,title:d,"data-testid":"executor-project-path-link",children:d})]})]}),t.jsx("div",{className:"executor-status-bar__spacer"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--time",children:[t.jsx(Ei,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__time",children:x})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx(y,{size:12,style:{color:v.color},"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__state",style:{color:v.color},children:v.label})]})]})}const t4={planning:ri,subtask:qi,mission_interview:ks,milestone_interview:ks,slice_interview:ks},n4={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},Kg="fusion:session-banner-dismissed";function gr(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function s4(){if(typeof window>"u")return new Map;try{const e=window.localStorage.getItem(Kg);if(!e)return new Map;const n=JSON.parse(e),s=new Map;for(const[i,r]of Object.entries(n)){const o=typeof r=="number"?r:gr(r);s.set(i,o)}return s}catch{return new Map}}function i4(e){if(!(typeof window>"u"))try{const n={};for(const[s,i]of e)n[s]=i;window.localStorage.setItem(Kg,JSON.stringify(n))}catch{}}const fi=s4();function a4({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:i}){const[r,o]=a.useState(0),l=()=>{i4(fi),o(g=>g+1)};a.useEffect(()=>{if(fi.size===0)return;const g=new Map(e.map(v=>[v.id,v]));let b=!1;for(const[v,x]of fi){const y=g.get(v);if(!y)continue;if(!(y.status==="awaiting_input"||y.status==="error")){fi.delete(v),b=!0;continue}gr(y.updatedAt)>x&&(fi.delete(v),b=!0)}b&&l()},[e]);const c=a.useMemo(()=>e.filter(g=>{if(g.status!=="awaiting_input"&&g.status!=="error")return!1;const b=fi.get(g.id);return b===void 0?!0:gr(g.updatedAt)>b}),[e,r]);if(c.length===0)return null;const u=c.filter(g=>g.status==="awaiting_input").length,d=c.filter(g=>g.status==="error").length;let m="";u>0&&d>0?m=`${u} AI session${u===1?"":"s"} need${u===1?"s":""} your input, ${d} failed`:u>0?m=`${u} AI session${u===1?"":"s"} need${u===1?"s":""} your input`:d>0&&(m=`${d} AI session${d===1?"":"s"} failed`);const h=g=>{fi.set(g.id,Math.max(gr(g.updatedAt),Date.now())),l()},f=g=>{fi.delete(g.id),l(),n(g)},p=()=>{const g=Date.now();for(const b of c)fi.set(b.id,Math.max(gr(b.updatedAt),g));l(),i()};return t.jsxs("section",{className:"session-notification-banner",role:"region","aria-live":"polite","aria-label":"AI sessions needing input or failed",children:[t.jsxs("div",{className:"session-notification-banner__header",children:[t.jsxs("div",{className:"session-notification-banner__headline",children:[t.jsx(gs,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:m})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[t.jsx(qt,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Dismiss all"})]})]}),t.jsx("div",{className:"session-notification-banner__list",children:c.map(g=>{const b=t4[g.type],v=g.status==="error";return t.jsxs("article",{className:`session-notification-banner__item${v?" session-notification-banner__item--error":""}`,"data-session-type":g.type,"data-session-status":g.status,children:[t.jsxs("div",{className:"session-notification-banner__item-main",children:[v?t.jsx(gs,{size:16,className:"session-notification-banner__type-icon session-notification-banner__type-icon--error","aria-hidden":"true"}):t.jsx(b,{size:16,className:"session-notification-banner__type-icon","aria-hidden":"true"}),t.jsxs("div",{className:"session-notification-banner__text",children:[t.jsx("p",{className:"session-notification-banner__title",title:g.title,children:g.title}),t.jsx("p",{className:"session-notification-banner__meta",children:v?"Failed":n4[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(qt,{size:14,"aria-hidden":"true"})})]})]},g.id)})})]})}const Gg="fusion:cli-binary-banner-dismissed";function r4(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Gg)==="1"}catch{return!1}}function o4(){if(!(typeof window>"u"))try{window.localStorage.setItem(Gg,"1")}catch{}}function l4({onOpenSettings:e}){const[n,s]=a.useState(null),[i,r]=a.useState(()=>r4()),[o,l]=a.useState(!1),[c,u]=a.useState(null);a.useEffect(()=>{if(i)return;let h=!1;return Wy().then(f=>{h||s(f)}).catch(()=>{}),()=>{h=!0}},[i]);const d=a.useCallback(async()=>{l(!0),u(null);try{const h=await Ky();s({binary:h.binary,expectedVersion:h.expectedVersion,state:h.state,install:h.install}),h.installResult.success||u(h.installResult.permissionsHint||h.installResult.stderr||`Install failed (exit ${h.installResult.exitCode??"n/a"})`)}catch(h){u(h instanceof Error?h.message:String(h))}finally{l(!1)}},[]),m=a.useCallback(()=>{o4(),r(!0)},[]);return i||!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 d(),disabled:o,children:o?"Installing…":"Install with npm"}),t.jsx("button",{type:"button",className:"cli-binary-banner__secondary",onClick:e,children:"Open Settings"})]}),c&&t.jsx("div",{className:"cli-binary-banner__error",children:c})]}),t.jsx("button",{type:"button",className:"cli-binary-banner__dismiss","aria-label":"Dismiss",onClick:m,children:t.jsx(qt,{size:16})})]})}function c4({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(qt,{size:16,"aria-hidden":"true"})})]})}function d4({onResume:e}){const n=hI();if(!n)return null;const s=n.completedSteps.length,i=ki.length,r=s>0?`${s} of ${i} step${s!==1?"s":""} complete — You're on the `:"You're on the ";return t.jsxs("section",{className:"onboarding-resume-card",role:"region","aria-label":"Resume onboarding",children:[t.jsxs("div",{className:"onboarding-resume-card__main",children:[t.jsx("div",{className:"onboarding-resume-card__icon","aria-hidden":"true",children:t.jsx(cs,{size:20})}),t.jsxs("div",{className:"onboarding-resume-card__content",children:[t.jsx("h2",{className:"onboarding-resume-card__title",children:"Continue Setup"}),t.jsxs("p",{className:"onboarding-resume-card__description",children:[r,t.jsx("strong",{children:n.label})," step. Continue where you left off to complete your dashboard setup."]})]})]}),t.jsx("div",{className:"onboarding-resume-card__actions",children:t.jsxs("button",{className:"onboarding-resume-card__resume-btn btn btn-primary btn-sm",onClick:()=>{Is("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),e()},children:[t.jsx(_n,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function u4({onOpenSettings:e,onOpenModelOnboarding:n}){const s=Aa(),i=Bg(),[r,o]=a.useState(!0),[l,c]=a.useState(!1),[u,d]=a.useState(!1),[m,h]=a.useState({needsAiProvider:!1,needsDefaultModel:!1,needsGitHub:!1});a.useEffect(()=>{if(!s||i){o(!1);return}let x=!1;return(async()=>{try{o(!0),c(!1);const[j,E]=await Promise.all([Er(),Yi()]);if(x)return;const C=j.providers??[],w=C.find(P=>P.id==="github"),S=!C.some(P=>P.id!=="github"&&P.authenticated),O=!E.defaultProvider&&!E.defaultModelId,_=w?!w.authenticated:!1;h({needsAiProvider:S,needsDefaultModel:O,needsGitHub:_})}catch{x||c(!0)}finally{x||o(!1)}})(),()=>{x=!0}},[s,i]);const f=a.useCallback(()=>{uI(),d(!0)},[]),p=a.useCallback(()=>{n()},[n]),g=a.useCallback(()=>{e("global-models")},[e]),b=a.useCallback(()=>{e("authentication")},[e]),v=a.useMemo(()=>{const x=[];return m.needsAiProvider&&x.push({id:"ai-provider",title:"Connect AI Provider",description:"Connect an AI provider to enable AI agents for task planning and code generation",actionLabel:"Set Up AI",onAction:p,icon:es}),m.needsDefaultModel&&x.push({id:"default-model",title:"Select Default Model",description:"Choose a default AI model for task execution",actionLabel:"Choose Model",onAction:g,icon:Ep}),m.needsGitHub&&x.push({id:"github",title:"Connect GitHub",description:"Connect GitHub to import issues and track pull requests",actionLabel:"Connect GitHub",onAction:b,icon:Es}),x},[m.needsAiProvider,m.needsDefaultModel,m.needsGitHub,b,g,p]);return!s||i||u||r||l||v.length===0?null:t.jsxs("section",{className:"post-onboarding-recommendations",role:"region","aria-label":"Setup recommendations",children:[t.jsxs("div",{className:"post-onboarding-recommendations__main",children:[t.jsx("div",{className:"post-onboarding-recommendations__icon","aria-hidden":"true",children:t.jsx(ri,{size:18,"aria-hidden":!0})}),t.jsxs("div",{className:"post-onboarding-recommendations__content",children:[t.jsx("h2",{className:"post-onboarding-recommendations__title",children:"Recommended Next Steps"}),t.jsx("p",{className:"post-onboarding-recommendations__description",children:"Complete these setup items to get the most out of Fusion."}),t.jsx("ul",{className:"post-onboarding-recommendations__list",children:v.map(x=>{const y=x.icon;return t.jsxs("li",{className:"post-onboarding-recommendations__item",children:[t.jsxs("span",{className:"post-onboarding-recommendations__item-icon","aria-hidden":"true",children:[t.jsx(gs,{size:14,"aria-hidden":!0}),t.jsx(y,{size:14,"aria-hidden":!0})]}),t.jsxs("span",{className:"post-onboarding-recommendations__item-text",children:[t.jsx("strong",{children:x.title}),t.jsx("span",{children:x.description})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-primary",onClick:x.onAction,children:x.actionLabel})]},x.id)})})]})]}),t.jsx("button",{type:"button",className:"post-onboarding-recommendations__dismiss",onClick:f,"aria-label":"Dismiss recommendations",children:t.jsx(qt,{size:16,"aria-hidden":!0})})]})}function m4({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 _c(e){return e>99?"99+":String(e)}function h4({view:e,onChangeView:n,footerVisible:s,modalOpen:i=!1,keyboardOpen:r=!1,onOpenSettings:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:u,mailboxUnreadCount:d=0,onOpenGitManager:m,onOpenWorkflowSteps:h,onOpenSchedules:f,onOpenScripts:p,onToggleTerminal:g,onOpenFiles:b,onOpenGitHubImport:v,onOpenPlanning:x,onResumePlanning:y,activePlanningSessionCount:j=0,onOpenUsage:E,onRunScript:C,projectId:w,onViewAllProjects:R,showSkillsTab:S,experimentalFeatures:O,pluginDashboardViews:_=[]}){const P=$a(),[U,G]=a.useState(!1),[M,T]=a.useState(!1),[D,K]=a.useState({}),[J,te]=a.useState(!1),N=a.useMemo(()=>Object.entries(D).sort(([Y],[X])=>Y.localeCompare(X)),[D]);a.useEffect(()=>{if(!M)return;let Y=!1;return te(!0),_r(w).then(X=>{Y||K(X)}).catch(()=>{Y||K({})}).finally(()=>{Y||te(!1)}),()=>{Y=!0}},[M,w]);const z=a.useCallback(()=>G(!1),[]),I=a.useCallback(Y=>{z(),Y?.()},[z]);if(a.useEffect(()=>{if(!U)return;const Y=X=>{X.key==="Escape"&&G(!1)};return document.addEventListener("keydown",Y),()=>document.removeEventListener("keydown",Y)},[U]),P!=="mobile"||i||r)return null;const k=j>0&&y?y:x,H=!!O?.roadmap,Q=!!S,ue=!!O?.todoView,be=H&&(!Q||e==="roadmaps"),V=Q&&(!H||e!=="roadmaps"),ve=Q&&!V,B=e==="documents"||e==="research"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||e==="todos"&&ue||e==="roadmaps"&&!be||e==="skills"&&!V||e.startsWith("plugin:");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(Vi,{}),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(En,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Agents"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="missions"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-missions",role:"tab","aria-selected":e==="missions",onClick:()=>n("missions"),children:[t.jsx(ks,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Missions"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="chat"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-chat",role:"tab","aria-selected":e==="chat",onClick:()=>n("chat"),children:[t.jsx(Si,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Chat"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="mailbox"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-mailbox",role:"tab","aria-selected":e==="mailbox",onClick:()=>n("mailbox"),children:[t.jsx(ya,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),d>0&&t.jsx("span",{className:"mobile-nav-tab-badge",children:_c(d)})]}),V&&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(es,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),be&&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(zc,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Roadmaps"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${B?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>G(Y=>!Y),children:[t.jsx(Ic,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),U&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mobile-more-sheet-backdrop",onClick:z}),t.jsxs("div",{className:"mobile-more-sheet",children:[t.jsx("div",{className:"mobile-more-sheet-handle"}),t.jsx("div",{className:"mobile-more-sheet-title",children:"Navigate"}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-mailbox",onClick:()=>I(u),children:[t.jsx(ya,{}),t.jsx("span",{children:"Mailbox"}),d>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:_c(d)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>I(l),children:[t.jsx(Ds,{}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-system-stats",onClick:()=>I(c),children:[t.jsx(kr,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>I(m),children:[t.jsx(Ks,{}),t.jsx("span",{children:"Git Manager"})]}),t.jsxs("div",{className:"mobile-more-split-row",children:[t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-split-primary","data-testid":"mobile-more-item-terminal",onClick:()=>I(g),children:[t.jsx(gi,{}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>T(Y=>!Y),"aria-expanded":M,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(gn,{size:14,className:`mobile-more-chevron${M?" mobile-more-chevron--open":""}`})})]}),M&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:J?t.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[t.jsx(lt,{className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):N.length>0?t.jsxs(t.Fragment,{children:[N.map(([Y,X])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${Y}`,onClick:()=>{C&&C(Y,X),z(),T(!1)},children:[t.jsx(_n,{}),t.jsx("span",{children:Y})]},Y)),p&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{z(),T(!1),p()},children:[t.jsx(qs,{}),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:()=>{z(),T(!1),p()},children:[t.jsx(qs,{}),t.jsx("span",{children:"No scripts — add one…"})]})}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-files",onClick:()=>I(b),children:[t.jsx(ts,{}),t.jsx("span",{children:"Files"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>I(k),children:[t.jsx(ri,{}),t.jsx("span",{children:"Planning"}),j>0&&t.jsx("span",{className:"mobile-more-item-badge",children:_c(j)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>I(h),children:[t.jsx(Fc,{}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>I(f),children:[t.jsx(Ei,{}),t.jsx("span",{children:"Automation"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>I(v),children:[t.jsx(m4,{}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>I(E),children:[t.jsx(Ds,{}),t.jsx("span",{children:"Usage"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>I(R),children:[t.jsx(zo,{}),t.jsx("span",{children:"Projects"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>I(()=>n("documents")),children:[t.jsx(Hi,{}),t.jsx("span",{children:"Documents"})]}),ve&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>I(()=>n("skills")),children:[t.jsx(es,{}),t.jsx("span",{children:"Skills"})]}),H&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-roadmaps",onClick:()=>I(()=>n("roadmaps")),children:[t.jsx(zc,{}),t.jsx("span",{children:"Roadmaps"})]}),O?.researchView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-research",onClick:()=>I(()=>n("research")),children:[t.jsx(Ni,{}),t.jsx("span",{children:"Research"})]}),O?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>I(()=>n("insights")),children:[t.jsx(cs,{}),t.jsx("span",{children:"Insights"})]}),O?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>I(()=>n("memory")),children:[t.jsx(Do,{}),t.jsx("span",{children:"Memory"})]}),O?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{I(()=>n("dev-server"))},children:[t.jsx(kr,{}),t.jsx("span",{children:"Dev Server"})]}),ue&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-todos",onClick:()=>I(()=>n("todos")),children:[t.jsx(Rp,{}),t.jsx("span",{children:"Todos"})]}),_.filter(Y=>Y.view.placement!=="primary").sort((Y,X)=>(Y.view.order??Number.MAX_SAFE_INTEGER)-(X.view.order??Number.MAX_SAFE_INTEGER)).map(Y=>{const X=Qp(Y.pluginId,Y.view.viewId);return t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":`mobile-more-item-plugin-${Y.pluginId}-${Y.view.viewId}`,onClick:()=>I(()=>n(X)),children:[t.jsx(zo,{}),t.jsx("span",{children:Y.view.label})]},`${Y.pluginId}:${Y.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:()=>I(o),children:[t.jsx(br,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function p4({agents:e,filter:n,highlightedIndex:s,visible:i,onSelect:r,position:o="below"}){const l=a.useMemo(()=>{const c=n.trim().toLowerCase();return c?e.filter(u=>u.name.toLowerCase().includes(c)):e},[e,n]);return i?t.jsx("div",{className:`agent-mention-popup agent-mention-popup--${o}`,"data-testid":"agent-mention-popup",role:"listbox","aria-label":"Agent mention suggestions",children:l.length===0?t.jsx("div",{className:"agent-mention-empty",children:"No agents found"}):l.map((c,u)=>t.jsxs("button",{type:"button",className:`agent-mention-item${u===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${c.id}`,onMouseDown:d=>d.preventDefault(),onClick:()=>r(c),role:"option","aria-selected":u===s,children:[t.jsx(En,{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 ba="__fn_agent__";function Jg(e,n){const s=typeof e=="string"?e.trim():"",i=typeof n=="string"?n.trim():"";return!s||!i?{}:{modelProvider:s,modelId:i}}function Eo(e,n,s){const i=typeof e=="string"?e.trim():"",r=Jg(n,s),o=i||(r.modelProvider&&r.modelId?ba:"");return o?{agentId:o,...r}:null}function _o(e,n,s){const i=Jg(n,s),r=i.modelProvider??"",o=i.modelId??"";return`${e}::${r}/${o}`}function f4(e){const n=e?.toolCalls;if(!Array.isArray(n))return;const s=n.map(i=>{if(!i||typeof i!="object")return null;const r=i,o=typeof r.toolName=="string"?r.toolName:"";if(!o)return null;const l=r.args;return{toolName:o,...l&&typeof l=="object"?{args:l}:{},isError:!!r.isError,result:r.result,status:"completed"}}).filter(i=>i!==null);return s.length>0?s:void 0}function sp(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:f4(e.metadata),createdAt:e.createdAt}}function g4(e,n){const[s,i]=a.useState(null),[r,o]=a.useState([]),[l,c]=a.useState(!1),[u,d]=a.useState([]),[m,h]=a.useState(!1),[f,p]=a.useState(!1),[g,b]=a.useState(""),[v,x]=a.useState(""),[y,j]=a.useState([]),[E,C]=a.useState(""),w=a.useRef(null),R=a.useRef(!1),S=a.useRef(null),O=a.useRef(""),_=a.useRef(null),P=a.useRef(""),U=a.useRef(null);a.useEffect(()=>{O.current=E},[E]);const G=a.useCallback(async()=>{c(!0);try{const ue=await Nu(e);o(ue.sessions)}catch(ue){console.error("[useQuickChat] Failed to refresh sessions:",ue)}finally{c(!1)}},[e]),M=a.useCallback(async ue=>{const be={agentId:ue.agentId};return ue.modelProvider&&ue.modelId&&(be.modelProvider=ue.modelProvider,be.modelId=ue.modelId),(await tN(be,e)).session},[e]),T=a.useCallback(async(ue,be,V)=>{const ve=Eo(ue,be,V);if(!ve)return;const B=_o(ve.agentId,ve.modelProvider,ve.modelId);c(!0);try{const{session:Y}=await eN({agentId:ve.agentId,modelProvider:ve.modelProvider,modelId:ve.modelId},e);if(Y)i(Y),P.current=B;else{const X=await M(ve);i(X),P.current=B}}catch(Y){console.error("[useQuickChat] Failed to initialize session:",Y),n?.("Failed to initialize chat","error")}finally{c(!1)}},[e,n,M]),D=a.useCallback(async()=>{if(s){h(!0);try{const ue=await Su(s.id,{limit:50},e);d(ue.messages.map(sp))}catch(ue){console.error("[useQuickChat] Failed to load messages:",ue)}finally{h(!1)}}},[s,e]);a.useEffect(()=>{s?D():d([])},[s,D]);const K=a.useCallback(async()=>{if(s){h(!0);try{const ue=await Su(s.id,{limit:50},e);d(ue.messages.map(sp))}catch(ue){console.error("[useQuickChat] Failed to reload messages:",ue)}finally{h(!1)}}},[s,e]),J=a.useCallback(()=>{S.current?.(),S.current=null,O.current="",C(""),b(""),x(""),j([]),p(!1)},[]),te=a.useCallback(async(ue,be,V)=>{const ve=Eo(ue,be,V);if(!ve)return;const B=_o(ve.agentId,ve.modelProvider,ve.modelId);U.current=ve;const Y=B===P.current&&s;if(Y||(w.current&&(w.current.close(),w.current=null),J()),Y){await K();return}i(null),d([]),P.current=B,await T(ve.agentId,ve.modelProvider,ve.modelId)},[s,T,K,J]),N=a.useCallback(async ue=>{const be=Eo(ue.agentId,ue.modelProvider??void 0,ue.modelId??void 0);be&&(U.current=be,P.current=_o(be.agentId,be.modelProvider,be.modelId),w.current&&(w.current.close(),w.current=null),J(),i(ue))},[J]),z=a.useCallback(async(ue,be)=>{await te(ba,ue,be)},[te]),I=a.useCallback(async(ue,be,V)=>{const B=Eo(ue??"",be,V)??U.current;if(!B)return;U.current=B;const Y=_o(B.agentId,B.modelProvider,B.modelId);w.current&&(w.current.close(),w.current=null),J(),d([]),i(null),c(!0);try{const X=await M(B);i(X),P.current=Y;const he=await Nu(e);o(he.sessions)}catch(X){console.error("[useQuickChat] Failed to start a fresh session:",X),n?.("Failed to start a new chat","error")}finally{c(!1)}},[n,M,e,J]),k=a.useCallback(()=>{s&&(R.current=!0,S.current?.(),S.current=null,w.current?.close(),w.current=null,nN(s.id,e).catch(()=>{}),p(!1),b(""),x(""),j([]))},[s,e]),H=a.useCallback(()=>{O.current="",C("")},[]),Q=a.useCallback((ue,be)=>{if(!s||!ue.trim()&&(!be||be.length===0))return Promise.resolve();if(f)return be&&be.length>0?Promise.reject(new Error("Cannot send attachments while a response is streaming")):(O.current=ue,C(ue),Promise.resolve());const V=new Promise((ve,B)=>{_.current={resolve:ve,reject:B},R.current=!1,w.current&&(w.current.close(),w.current=null);const X={id:`temp-${Date.now()}`,sessionId:s.id,role:"user",content:ue,createdAt:new Date().toISOString()};d(qe=>[...qe,X]),b(""),x(""),j([]),p(!0);let he="",de="",me=[],se=null,_e=null;const Fe=()=>{se=null,b(he)},Te=()=>{_e=null,x(de)},st=()=>{se!==null&&(cancelAnimationFrame(se),se=null),_e!==null&&(cancelAnimationFrame(_e),_e=null)};S.current=st;const nt={onThinking:qe=>{de+=qe,_e===null&&(_e=requestAnimationFrame(Te))},onText:qe=>{he+=qe,se===null&&(se=requestAnimationFrame(Fe))},onToolStart:qe=>{me=[...me,{toolName:qe.toolName,args:qe.args,isError:!1,status:"running"}],j(me)},onToolEnd:qe=>{const Xe=[...me];for(let $e=Xe.length-1;$e>=0;$e--){const Ue=Xe[$e];if(Ue?.toolName===qe.toolName&&Ue.status==="running"){Xe[$e]={...Ue,status:"completed",isError:qe.isError,result:qe.result},me=Xe,j(Xe);return}}me=[...Xe,{toolName:qe.toolName,isError:qe.isError,result:qe.result,status:"completed"}],j(me)},onDone:qe=>{st();const Xe={id:qe.messageId||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:he,thinkingOutput:de||void 0,toolCalls:me.length>0?me:void 0,createdAt:new Date().toISOString()};d(Ue=>[...Ue,Xe]),b(""),x(""),j([]),p(!1),w.current=null,_.current?.resolve(),_.current=null;const $e=O.current.trim();$e&&(O.current="",C(""),Q($e))},onError:qe=>{if(st(),b(""),x(""),j([]),p(!1),w.current=null,console.error("[useQuickChat] Stream error:",qe),n?.("Failed to get response","error"),_.current?.reject(new Error(typeof qe=="string"?qe:"Failed to get response")),_.current=null,!R.current){const Xe=O.current.trim();Xe&&(O.current="",C(""),Q(Xe))}K()}};w.current=sN(s.id,ue,nt,be,e)});return V.catch(()=>{}),V},[s,f,e,n,K]);return a.useEffect(()=>()=>{w.current&&(w.current.close(),w.current=null)},[]),a.useMemo(()=>({activeSession:s,sessions:r,sessionsLoading:l,messages:u,messagesLoading:m,isStreaming:f,streamingText:g,streamingThinking:v,streamingToolCalls:y,pendingMessage:E,sendMessage:Q,stopStreaming:k,clearPendingMessage:H,switchSession:te,selectSession:N,startModelChat:z,startFreshSession:I,refreshSessions:G,loadMessages:D,reloadMessages:K}),[s,r,l,u,m,f,g,v,y,E,Q,k,H,te,N,z,I,G,D,K])}function b4(e,n){const[s,i]=a.useState([]),[r,o]=a.useState(null),[l,c]=a.useState(!1),u=a.useCallback(async f=>{c(!0);try{const p=n?.filterState,g=p&&p!=="all"?{state:p}:void 0,b=n?.showSystemAgents??!1,v=await Ia({...g,...f,includeEphemeral:f?.includeEphemeral??b},e),x=Array.from(new Map(v.map(y=>[y.id,y])).values());i(x)}catch(p){console.error("Failed to load agents:",p)}finally{c(!1)}},[e,n?.filterState,n?.showSystemAgents]),d=a.useCallback(async()=>{try{const f=await Tj(e);o(f)}catch(f){console.error("Failed to load agent stats:",f)}},[e]);a.useEffect(()=>{u(),d()},[u,d]),a.useEffect(()=>{const f=e?`?projectId=${encodeURIComponent(e)}`:"",p=()=>{u(),d()};return Js(`/api/events${f}`,{events:{"agent:created":p,"agent:updated":p,"agent:deleted":p,"agent:stateChanged":p}})},[e,u,d]);const m=n?.showSystemAgents??!1,h=s.filter(f=>f.state!=="active"&&f.state!=="running"?!1:m||!DN(f));return{agents:s,activeAgents:h,stats:r,isLoading:l,loadAgents:u,loadStats:d}}function x4({visible:e,position:n,files:s,selectedIndex:i,onSelect:r,loading:o}){return e?t.jsxs("div",{className:"file-mention-popup",style:{top:n.top,left:n.left},"data-testid":"file-mention-popup",onMouseDown:l=>{l.preventDefault()},children:[o&&t.jsx("div",{className:"file-mention-popup-loading","data-testid":"file-mention-loading",children:t.jsx("span",{className:"spinner"})}),!o&&s.length===0&&t.jsx("div",{className:"file-mention-popup-empty","data-testid":"file-mention-empty",children:"No files found"}),!o&&s.length>0&&t.jsx("ul",{className:"file-mention-popup-list",role:"listbox",children:s.map((l,c)=>{const u=cN(l.path),d=l.name;return t.jsxs("li",{className:`file-mention-popup-item${c===i?" file-mention-popup-item--selected":""}`,onClick:()=>r(l),onMouseEnter:()=>{},role:"option","aria-selected":c===i,"data-testid":`file-mention-item-${c}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(Sp,{size:14})}),t.jsxs("div",{className:"file-mention-popup-info",children:[t.jsx("span",{className:"file-mention-popup-item-name",children:d}),u&&t.jsx("span",{className:"file-mention-popup-item-path",children:u})]})]},l.path)})})]}):null}const v4=200;function y4(e={}){const{projectId:n,workspace:s="project"}=e,[i,r]=a.useState(!1),[o,l]=a.useState(""),[c,u]=a.useState(-1),[d,m]=a.useState([]),[h,f]=a.useState(!1),[p,g]=a.useState(0),b=a.useRef(null),v=a.useRef(null);a.useEffect(()=>()=>{b.current&&clearTimeout(b.current),v.current?.abort()},[]);const x=a.useCallback((w,R)=>{if(R<0||R>w.length){r(!1);return}const S=O=>/[a-zA-Z0-9/_.-]/.test(O);for(let O=R-1;O>=0;O--){if(w[O]==="#")if(O===0){const _=w.slice(O+1,R);u(O),l(_),g(0),r(!0);return}else{const _=w[O-1];if(/[\s,.;:!?'"()[\]{}]/.test(_)){const P=w.slice(O+1,R);u(O),l(P),g(0),r(!0);return}r(!1);return}if(!S(w[O])){r(!1);return}}r(!1)},[]),y=a.useCallback(()=>{r(!1),l(""),u(-1),m([]),g(0),f(!1)},[]),j=a.useCallback(async w=>{if(!w.trim()){m([]),f(!1);return}v.current?.abort(),v.current=new AbortController;try{f(!0);const R=await Ow(w,s,n);m(R.files),g(0)}catch(R){R.name!=="AbortError"&&m([])}finally{f(!1)}},[s,n]);a.useEffect(()=>{if(i)return b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{j(o)},v4),()=>{b.current&&clearTimeout(b.current)}},[o,i,j]);const E=a.useCallback((w,R)=>{if(!i||c<0)return R;const S=R.slice(0,c),O=R.slice(c+1),_=O.match(/[\s]|$/),P=_?_.index:O.length,U=O.slice(P);return`${S}#${w.path}${U}`},[i,c]),C=a.useCallback((w,R)=>{if(!i||d.length===0)return!1;switch(w.key){case"ArrowDown":return w.preventDefault(),g(S=>Math.min(S+1,d.length-1)),!0;case"ArrowUp":return w.preventDefault(),g(S=>Math.max(S-1,0)),!0;case"Enter":case"Tab":return d[p]?(w.preventDefault(),!0):!1;case"Escape":return w.preventDefault(),y(),!0;default:return!1}},[i,d,p,y]);return{mentionActive:i,files:d,loading:h,mentionQuery:o,selectedIndex:p,setSelectedIndex:g,detectMention:x,selectFile:E,dismissMention:y,handleKeyDown:C}}const w4=30,j4=16,k4=16;function N4(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let Po=null;function Yg(){return Po===null&&(Po=window.visualViewport?.height??window.innerHeight),Po}function S4(e){const n=Yg();e>n&&(Po=e)}function C4(e){return e?e instanceof HTMLTextAreaElement?!0:e instanceof HTMLInputElement?!new Set(["checkbox","radio","button","submit","reset","file","range","color","hidden"]).has(e.type):e instanceof HTMLElement&&e.isContentEditable:!1}function E4(){if(typeof window>"u"||!window.visualViewport)return{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0};const e=window.visualViewport,n=C4(document.activeElement),s=e.offsetTop;n||S4(e.height);const i=Math.max(0,window.innerHeight-e.offsetTop-e.height);if(i>0)return{overlap:i,open:!0,vvHeight:e.height,vvOffsetTop:s};const r=Yg(),o=Math.max(0,r-e.offsetTop-e.height);if(o>=w4)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};if(o>=j4&&n)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};const l=Math.max(0,r-e.height);return n&&l>=k4?{overlap:0,open:!0,vvHeight:e.height,vvOffsetTop:s}:{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0}}function Qg({enabled:e=!0}={}){const[n,s]=a.useState(0),[i,r]=a.useState(null),[o,l]=a.useState(0),[c,u]=a.useState(!1);return a.useEffect(()=>{if(!e||!N4()){s(0),r(null),l(0),u(!1);return}const d=window.visualViewport;if(!d){s(0),r(null),l(0),u(!1);return}const m=()=>{const h=E4();s(h.overlap),r(h.vvHeight),l(h.vvOffsetTop),u(h.open)};return m(),d.addEventListener("resize",m),d.addEventListener("scroll",m),document.addEventListener("focusin",m),document.addEventListener("focusout",m),()=>{d.removeEventListener("resize",m),d.removeEventListener("scroll",m),document.removeEventListener("focusin",m),document.removeEventListener("focusout",m),s(0),r(null),l(0),u(!1)}},[e]),{keyboardOverlap:n,viewportHeight:i,viewportOffsetTop:o,keyboardOpen:c}}function _4(e){return`${e.name?.trim()||e.id} (${e.role})`}function Mo(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 M4(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 Io(e,n){return e.length<=n?e:`${e.slice(0,n)}…`}function A4(e){if(!e)return null;const n=Object.entries(e);return n.length===0?null:n.map(([s,i])=>{const r=typeof i=="string"?i:(()=>{try{return JSON.stringify(i)}catch{return String(i)}})();return`${s}=${Io(r,50)}`}).join(", ")}function R4(e){if(e===void 0)return null;if(typeof e=="string")return Io(e,200);try{return Io(JSON.stringify(e),200)}catch{return Io(String(e),200)}}function Xg(e,n=!1){if(!e||e.length===0)return null;const s=(f,p)=>{const g=f.status==="running",b=f.status==="completed"&&f.isError,v=A4(f.args),x=R4(f.result),y=g?v:x?`result: ${x}`:v?`args: ${v}`:null,j=n?null:y,E=g?"running":b?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${g?" chat-tool-call--running":""}${b?" chat-tool-call--error":""}`,open:g,children:[t.jsxs("summary",{children:[t.jsx("span",{className:"chat-tool-call-status-dot","aria-hidden":"true"}),t.jsx("span",{className:"chat-tool-call-name",title:f.toolName,children:f.toolName}),j&&t.jsx("span",{className:"chat-tool-call-preview",title:j,children:j}),t.jsx("span",{className:"chat-tool-call-status-text",children:E})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[v&&t.jsxs("div",{className:"chat-tool-call-row",children:[t.jsx("span",{className:"chat-tool-call-label",children:"args"}),t.jsx("span",{className:"chat-tool-call-value",children:v})]}),x&&t.jsxs("div",{className:`chat-tool-call-row${b?" chat-tool-call-row--error":""}`,children:[t.jsx("span",{className:"chat-tool-call-label",children:"result"}),t.jsx("span",{className:"chat-tool-call-value",children:x})]})]})]},`${f.toolName}-${p}`)},i=`chat-tool-calls${n?" chat-tool-calls--compact":""}`;if(e.length===1)return t.jsxs("div",{className:i,"data-testid":"chat-tool-calls",children:[t.jsxs("div",{className:"chat-tool-calls-header",children:[t.jsx(tu,{size:12,"aria-hidden":"true"}),t.jsx("span",{children:"Tool calls"})]}),s(e[0],0)]});const r=e.filter(f=>f.status==="running").length,o=e.filter(f=>f.status==="completed"&&f.isError).length,l=r>0,c=Array.from(new Set(e.map(f=>f.toolName))),u=c.slice(0,5),d=Math.max(0,c.length-u.length),m=d>0?`${u.join(", ")}, +${d} more`:u.join(", "),h=l?`(${r} running)`:o>0?`(${o} ${o===1?"error":"errors"})`:null;return t.jsx("div",{className:i,"data-testid":"chat-tool-calls",children:t.jsxs("details",{className:`chat-tool-calls-group${n?" chat-tool-calls-group--compact":""}`,"data-testid":"chat-tool-calls-group",open:l,children:[t.jsxs("summary",{className:"chat-tool-calls-group-summary",children:[t.jsx(tu,{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 Zg={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 T4(e,n){const s=e.slice(0,n),i=/(^|[\s])@([\w-]*)$/.exec(s);if(!i)return null;const r=i[2]??"",o=s.length-r.length-1;return{filter:r,start:o,end:n}}const Ao={width:320,height:400},P4=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"]),I4=[".png",".jpg",".jpeg",".gif",".webp",".txt",".json",".yaml",".yml",".log",".csv",".xml",".md"];function $4(e){return e.type.startsWith("image/")}function D4(e){if(P4.has(e.type))return!0;const n=e.name.toLowerCase();return I4.some(s=>n.endsWith(s))}const ma={width:280,height:260},os=768,ha=8;function L4(e,n){const s=a.useCallback(()=>{if(typeof window>"u")return 0;const b=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return b&&parseFloat(b)||0},[]),i=a.useCallback(()=>typeof window<"u"&&window.innerWidth<=768?{x:4,y:4+s()}:{x:24,y:24+s()},[s]),[r,o]=a.useState(()=>{if(typeof window>"u")return i();const b=`fusion-quick-chat-position-${e||"default"}`;try{const v=localStorage.getItem(b);if(v){const x=JSON.parse(v);if(typeof x.x=="number"&&typeof x.y=="number"&&!isNaN(x.x)&&!isNaN(x.y))return x}}catch{}return i()}),[l,c]=a.useState(!1),u=a.useRef(null),d=n??a.useRef(!1),m=a.useCallback(b=>{if(typeof window>"u")return b;const v=48,x=window.innerWidth<=768?4:8,y=window.innerWidth<=768?44:0,j=window.innerWidth>768?s():0,E=window.innerWidth-v-x,C=window.innerHeight-v-x-y-j;return{x:Math.max(x,Math.min(E,b.x)),y:Math.max(x,Math.min(C,b.y))}},[s]),h=a.useCallback(b=>{if(typeof window>"u")return;const v=`fusion-quick-chat-position-${e||"default"}`;try{localStorage.setItem(v,JSON.stringify(b))}catch{}},[e]),f=a.useCallback(b=>{if(b.button!==0&&b.pointerType==="mouse")return;const x=b.target.closest(".quick-chat-fab");x&&(b.preventDefault(),typeof x.setPointerCapture=="function"&&x.setPointerCapture(b.pointerId),u.current={x:r.x,y:r.y,pointerX:b.clientX,pointerY:b.clientY},d.current=!1,c(!0),document.body.style.userSelect="none")},[r]),p=a.useCallback(b=>{if(!u.current||!l)return;const v=b.clientX-u.current.pointerX,x=b.clientY-u.current.pointerY;if((Math.abs(v)>=5||Math.abs(x)>=5)&&(d.current=!0),d.current){const y=u.current.x-v,j=u.current.y-x,E=m({x:y,y:j});o(E)}},[l,m]),g=a.useCallback(b=>{if(!u.current)return;const v=b.target.closest(".quick-chat-fab");if(v&&typeof v.releasePointerCapture=="function"&&v.releasePointerCapture(b.pointerId),c(!1),document.body.style.userSelect="",!d.current){u.current=null;return}h(r),u.current=null,d.current=!1},[r,h]);return{position:r,isDragging:l,handlePointerDown:f,handlePointerMove:p,handlePointerUp:g}}function z4(e,n,s){const i=`fusion:quick-chat-size-${e||"default"}`,r=a.useCallback(()=>typeof window<"u"&&window.innerWidth>os,[]),o=a.useCallback((f,p,g)=>{if(typeof window>"u")return f;const b=Math.max(ma.width,window.innerWidth-p-ha),v=Math.max(ma.height,window.innerHeight-g-ha);return{width:Math.max(ma.width,Math.min(b,f.width)),height:Math.max(ma.height,Math.min(v,f.height))}},[]),l=a.useCallback(()=>{if(typeof window>"u"||window.innerWidth<=os)return Ao;try{const f=localStorage.getItem(i);if(!f)return Ao;const p=JSON.parse(f);return typeof p.width!="number"||typeof p.height!="number"?Ao:{width:p.width,height:p.height}}catch{return Ao}},[i]),[c,u]=a.useState(l),[d,m]=a.useState({right:0,bottom:0});a.useEffect(()=>{if(!r())return;const f={right:n+d.right,bottom:s+d.bottom};u(p=>o(p,f.right,f.bottom))},[o,r,n,s,d]),a.useEffect(()=>{if(r())try{localStorage.setItem(i,JSON.stringify(c))}catch{}},[r,c,i]);const h=a.useCallback(f=>{if(!r())return;const p=f.currentTarget.dataset.resizeDirection;if(!p)return;f.preventDefault(),f.stopPropagation();const g=f.currentTarget;typeof g.setPointerCapture=="function"&&g.setPointerCapture(f.pointerId);const b={pointerX:f.clientX,pointerY:f.clientY,width:c.width,height:c.height,anchorRight:d.right,anchorBottom:d.bottom};document.body.style.userSelect="none";const v=y=>{const j=y.clientX-b.pointerX,E=y.clientY-b.pointerY;let C=b.width,w=b.height,R=b.anchorRight,S=b.anchorBottom;if(p.includes("w")&&(C=b.width-j),p.includes("e")){const M=j;C=b.width+M,R=b.anchorRight-M}if(p.includes("n")&&(w=b.height-E),p.includes("s")){const M=E;w=b.height+M,S=b.anchorBottom-M}const O=n+R,_=s+S,P=o({width:C,height:w},O,_),U=Math.max(ha-n,Math.min(window.innerWidth-n-ma.width-ha,R)),G=Math.max(ha-s,Math.min(window.innerHeight-s-ma.height-ha,S));u(P),m({right:U,bottom:G})},x=y=>{typeof g.releasePointerCapture=="function"&&g.releasePointerCapture(y.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",x);try{localStorage.setItem(i,JSON.stringify({width:c.width,height:c.height}))}catch{}};document.addEventListener("pointermove",v),document.addEventListener("pointerup",x)},[d.bottom,d.right,o,s,n,r,c.height,c.width,i]);return{panelSize:c,anchorOffset:d,handleResizeStart:h}}const ip=a.memo(function({message:n,forcePlain:s,mentionAgentsByName:i,onToggleRender:r}){const o=n.role==="user",l=a.useMemo(()=>{if(!o)return null;const u=n.content,d=/@([\w-]+)/g,m=[];let h=0,f=d.exec(u);for(;f;){const[p,g=""]=f,b=f.index;b>h&&m.push(u.slice(h,b));const v=g.replace(/_/g," ").toLowerCase(),x=i.get(v);x?m.push(t.jsxs("span",{className:"chat-mention-chip",children:["@",x.name.replace(/\s+/g,"_")]},`${x.id}-${b}`)):m.push(p),h=b+p.length,f=d.exec(u)}return h<u.length&&m.push(u.slice(h)),m.length===0?u:m},[o,n.content,i]),c=a.useMemo(()=>o?null:s?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:n.content}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(li,{remarkPlugins:[ci],components:Zg,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(bd,{size:14}):t.jsx(Ta,{size:14})})]}),Xg(n.toolCalls,!0)]})});function O4({projectId:e,addToast:n,showFAB:s=!0,open:i,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:c,onToggleModelFavorite:u}){const{agents:d}=b4(e),[m,h]=a.useState(!1),f=i!==void 0,p=f?i:m,g=f?A=>{r?.(typeof A=="function"?A(p):A)}:h;Qg({enabled:p});const b=$a(),[v,x]=a.useState("agent"),[y,j]=a.useState(""),[E,C]=a.useState(!1),[w,R]=a.useState("model"),[S,O]=a.useState(""),[_,P]=a.useState(""),[U,G]=a.useState([]),[M,T]=a.useState(!1),[D,K]=a.useState(""),[J,te]=a.useState(""),[N,z]=a.useState(""),[I,k]=a.useState(""),[H,Q]=a.useState(!1),[ue,be]=a.useState(0),[V,ve]=a.useState(-1),[B,Y]=a.useState(()=>new Set),[X,he]=a.useState([]),[de,me]=a.useState(!1),[,se]=a.useState(!1),[_e,Fe]=a.useState({top:0,left:0}),Te=y4({projectId:e}),st=a.useCallback(A=>{if(!A||!Te.mentionActive)return;const le=A.getBoundingClientRect();Fe({top:le.top-260,left:le.left+8})},[Te.mentionActive]),nt=a.useRef(!1),qe=a.useRef(!1),Xe=a.useRef(""),$e=a.useRef(0),Ue=a.useRef(null),oe=a.useRef(0),{position:je,isDragging:ie,handlePointerDown:Ae,handlePointerMove:Le,handlePointerUp:we}=L4(e,nt),Ee=je.y+60,{panelSize:Ve,anchorOffset:rt,handleResizeStart:xe}=z4(e,je.x,Ee),ce=typeof window<"u"&&window.innerWidth>os,{activeSession:Pe,messages:pe,isStreaming:Re,streamingText:Qe,streamingThinking:Ie,streamingToolCalls:bt,sessions:ee,sessionsLoading:re,messagesLoading:Se,sendMessage:ot,stopStreaming:ne,pendingMessage:Ze,clearPendingMessage:ft,switchSession:gt,selectSession:St,startModelChat:Nt,startFreshSession:pt,refreshSessions:kt}=g4(e,n),Ht=a.useRef(null),$t=a.useRef(null),Tt=a.useRef(null),Mt=a.useRef(null),Ot=a.useRef(null),zt=a.useRef([]),Ft=a.useRef(!1),Et=a.useRef(!1),Pt=a.useRef(!1),Dt=a.useRef(null),Wt=a.useRef(!1);a.useEffect(()=>{if(!p||typeof window>"u"||typeof document>"u"||window.innerWidth>os)return;const A=window.scrollY,le=document.documentElement,ye=document.body,Ye={htmlOverflow:le.style.overflow,bodyOverflow:ye.style.overflow};return window.scrollTo(0,0),le.style.overflow="hidden",ye.style.overflow="hidden",()=>{le.style.overflow=Ye.htmlOverflow,ye.style.overflow=Ye.bodyOverflow,window.scrollTo(0,A)}},[p]),a.useLayoutEffect(()=>{if(!p||typeof window>"u"||!window.visualViewport)return;const A=Ht.current;if(!A)return;const le=window.visualViewport,ye=()=>{Wt.current||(A.style.setProperty("--vv-height",`${le.height}px`),A.style.setProperty("--vv-offset-top",`${le.offsetTop||0}px`))};return ye(),le.addEventListener("resize",ye),le.addEventListener("scroll",ye),()=>{le.removeEventListener("resize",ye),le.removeEventListener("scroll",ye)}},[p]);const It=D||J,Rt=a.useMemo(()=>Mo(It),[It]),fe=a.useMemo(()=>U.find(A=>`${A.provider}/${A.id}`===It)??null,[U,It]),Oe=a.useMemo(()=>M4(fe,Rt),[fe,Rt]),ut=a.useMemo(()=>v==="model"?Rt?`${ba}::${Rt.modelProvider}/${Rt.modelId}`:"":y?`${y}::`:"",[v,Rt,y]),F=!(v==="agent"?!!y:!!Rt)||!Pe;a.useEffect(()=>{if(d.length===0){j(""),x("model");return}d.some(le=>le.id===y)||j(d[0]?.id??"")},[d,y]),a.useEffect(()=>{!p||qe.current||(qe.current=!0,T(!0),bs().then(A=>{const le=A.models??[];if(G(le),D||le.length===0)return;const ye=A.defaultProvider,Ye=A.defaultModelId;if(ye&&Ye){const ht=`${ye}/${Ye}`;if(le.some(Jt=>`${Jt.provider}/${Jt.id}`===ht)){te(ht),K(ht),x("model");return}}te("");const mt=le[0];mt&&K(`${mt.provider}/${mt.id}`)}).catch(A=>{console.error("[QuickChatFAB] Failed to load models:",A),G([]),te("")}).finally(()=>{T(!1)}))},[p,d.length,D]),a.useEffect(()=>{p&&kt()},[p,kt]),a.useEffect(()=>{if(!p){Xe.current="";return}if(!ut){Xe.current="";return}const A=ut===Xe.current&&!Pe&&!re;if(!(ut===Xe.current&&!A)){if(Xe.current=ut,v==="model"&&Rt){Nt(Rt.modelProvider,Rt.modelId);return}v==="agent"&&y&>(y)}},[p,v,Rt,y,ut,Pe,re,Nt,gt]),a.useEffect(()=>{p||(Q(!1),k(""),ve(-1),zt.current.forEach(A=>{A.previewUrl&&URL.revokeObjectURL(A.previewUrl)}),he([]))},[p]),a.useEffect(()=>{zt.current=X},[X]),a.useEffect(()=>{if(!p){Ft.current=!1;return}typeof window>"u"||(Ft.current=window.innerWidth<=os)},[p]),a.useEffect(()=>{if(!p||F||!Ft.current)return;const A=Mt.current;if(!A)return;const le=document.activeElement,ye=le?Ht.current?.contains(le):!1,Ye=le===document.body,mt=le===Dt.current;if(!ye&&!Ye&&!mt){Ft.current=!1;return}if(mt){A.focus({preventScroll:!0}),Ft.current=!1;return}const ht=requestAnimationFrame(()=>{A.focus(),Ft.current=!1});return()=>cancelAnimationFrame(ht)},[p,F]),a.useEffect(()=>()=>{zt.current.forEach(A=>{A.previewUrl&&URL.revokeObjectURL(A.previewUrl)})},[]);const ge=a.useCallback(()=>{C(!0),R("model"),O(d[0]?.id??""),P(D||J||"")},[d,J,D]),ze=a.useMemo(()=>d.find(A=>A.id===y)??null,[d,y]),Be=a.useMemo(()=>{const A=I.trim().toLowerCase();return A?d.filter(le=>le.name.toLowerCase().includes(A)):d},[d,I]),Ke=a.useMemo(()=>{const A=new Map;for(const le of d)A.set(le.name.toLowerCase(),le);return A},[d]);a.useEffect(()=>{be(0)},[I,H]),a.useEffect(()=>()=>{Ue.current!==null&&(window.clearTimeout(Ue.current),Ue.current=null)},[]),a.useEffect(()=>{if(!p)return;const A=ye=>{const Ye=ye.target;Ht.current?.contains(Ye)||$t.current?.contains(Ye)||Ye.closest(".model-combobox-dropdown--portal")||g(!1)},le=ye=>{ye.key==="Escape"&&g(!1)};return document.addEventListener("mousedown",A),document.addEventListener("keydown",le),()=>{document.removeEventListener("mousedown",A),document.removeEventListener("keydown",le)}},[p,g]),a.useEffect(()=>{if(!p)return;const A=Tt.current;A&&(A.scrollTop=A.scrollHeight)},[pe,Qe,Ie,Re,p]);const dt=a.useMemo(()=>{const A=new Map(d.map(ye=>[ye.id,ye.name?.trim()||ye.id])),le=new Map(U.map(ye=>[`${ye.provider}/${ye.id}`,ye.name?.trim()||""]));return ee.map((ye,Ye)=>{const mt=ye.title?.trim()||`Session ${Ye+1}`;let ht=null;if(ye.agentId&&ye.agentId!==ba)ht=A.get(ye.agentId)||ye.agentId;else if(ye.modelProvider&&ye.modelId){const Kt=`${ye.modelProvider}/${ye.modelId}`,Jt=le.get(Kt);ht=Jt?`${Jt} [${Kt}]`:Kt}return{id:ye.id,label:ht?`${mt} — ${ht}`:mt}})},[d,U,ee]),Xt=a.useMemo(()=>v==="agent"?ze?`Message ${ze.name||ze.id}`:"Select an agent to start chatting":Oe?`Message ${Oe}`:"Select a model to start chatting",[v,ze,Oe]),Cn=a.useCallback(A=>{const le=ee.find(ye=>ye.id===A);le&&(le.modelProvider&&le.modelId?(x("model"),K(`${le.modelProvider}/${le.modelId}`)):(x("agent"),j(le.agentId)),St(le))},[St,ee]),pn=a.useCallback(async()=>{if(!re){if(w==="agent"){if(!S)return;x("agent"),j(S),await pt(S)}else{const A=Mo(_||D||J);if(!A)return;x("model"),K(`${A.modelProvider}/${A.modelId}`),await pt(ba,A.modelProvider,A.modelId)}await kt(),C(!1),R("model")}},[J,S,w,_,kt,D,re,pt]),Kn=Ze.length>50?`${Ze.slice(0,50)}…`:Ze,Lt=a.useCallback(A=>{if(!A||A.length===0)return;const le=[];for(let ye=0;ye<A.length;ye+=1){const Ye=A[ye];D4(Ye)&&le.push({file:Ye,previewUrl:$4(Ye)?URL.createObjectURL(Ye):""})}le.length>0&&he(ye=>[...ye,...le])},[]),Zt=a.useCallback(A=>{he(le=>{const ye=le[A];return ye?.previewUrl&&URL.revokeObjectURL(ye.previewUrl),le.filter((Ye,mt)=>mt!==A)})},[]),Ne=a.useCallback(A=>{Lt(A.clipboardData?.files)},[Lt]),et=a.useCallback(()=>{if(typeof window>"u"||window.innerWidth>os)return;const A=Mt.current;!A||A.disabled||A.focus({preventScroll:!0})},[]),ln=a.useCallback(()=>{typeof window>"u"||window.innerWidth>os||(Pt.current=!0)},[]),wn=a.useCallback(async()=>{const A=N.trim(),le=zt.current;if(!(!A&&le.length===0)&&!F){if(z(""),Q(!1),k(""),ve(-1),A==="/clear"){ne(),ft(),le.forEach(ye=>{ye.previewUrl&&URL.revokeObjectURL(ye.previewUrl)}),he(ye=>ye.filter(Ye=>!le.includes(Ye)));try{if(v==="model"){const ye=Mo(It);if(!ye)return;await pt(ba,ye.modelProvider,ye.modelId)}else y&&await pt(y)}catch{n("Failed to clear conversation","error")}finally{et(),Pt.current=!1}return}try{await ot(A,le.map(ye=>ye.file)),le.forEach(ye=>{ye.previewUrl&&URL.revokeObjectURL(ye.previewUrl)}),he(ye=>ye.filter(Ye=>!le.includes(Ye)))}catch{}finally{et(),Pt.current=!1}}},[n,v,ft,et,F,N,It,y,ot,pt,ne]),Gn=a.useCallback(A=>{A.preventDefault(),oe.current+=1,me(!0)},[]),Tn=a.useCallback(A=>{A.preventDefault(),A.dataTransfer.dropEffect="copy",me(!0)},[]),Un=a.useCallback(A=>{A.preventDefault(),oe.current=Math.max(0,oe.current-1),oe.current===0&&me(!1)},[]),sn=a.useCallback(A=>{A.preventDefault(),oe.current=0,me(!1),Lt(A.dataTransfer?.files)},[Lt]),un=a.useCallback((A,le)=>{const ye=T4(A,le);if(ye){Q(!0),k(ye.filter),ve(ye.start);return}Q(!1),k(""),ve(-1)},[]),Bn=a.useCallback(A=>{const le=Mt.current;if(!le||V<0)return;const ye=le.selectionStart??$e.current,Ye=le.selectionEnd??ye,mt=Math.max(ye,Ye),ht=Math.min(V,mt),Jt=`${`@${A.name.replace(/\s+/g,"_")}`} `,zn=N.slice(0,ht)+Jt+N.slice(mt),Hn=ht+Jt.length;z(zn),Q(!1),k(""),be(0),ve(-1),window.requestAnimationFrame(()=>{Mt.current&&(Mt.current.focus(),Mt.current.setSelectionRange(Hn,Hn))})},[V,N]),Sn=a.useCallback(A=>{const le=A.target.value,ye=A.target.selectionStart??le.length;$e.current=ye,z(le),un(le,ye),Te.detectMention(le,ye),se(Te.mentionActive),Te.mentionActive&&st(A.target)},[un,Te,st]),an=a.useCallback(()=>{if(Pt.current){window.requestAnimationFrame(()=>{et()});return}typeof window<"u"&&window.innerWidth<=os&&Ht.current&&(Wt.current=!0,Ht.current.style.removeProperty("--vv-height"),Ht.current.style.removeProperty("--vv-offset-top"),window.setTimeout(()=>{Wt.current=!1},450)),Ue.current!==null&&window.clearTimeout(Ue.current),Ue.current=window.setTimeout(()=>{Q(!1),k(""),ve(-1),se(!1),Te.dismissMention(),Ue.current=null},120)},[Te,et]),Dn=a.useCallback(()=>{Wt.current=!1,Ue.current!==null&&(window.clearTimeout(Ue.current),Ue.current=null)},[]),Ln=a.useCallback(A=>{const le=A.currentTarget,ye=le.selectionStart??le.value.length;$e.current=ye,un(le.value,ye),Te.detectMention(le.value,ye),se(Te.mentionActive),Te.mentionActive&&st(le)},[un,Te,st]),ss=a.useCallback(A=>{A.key!=="Escape"&&Ln(A)},[Ln]),Pn=a.useCallback(A=>{Y(le=>{const ye=new Set(le);return ye.has(A)?ye.delete(A):ye.add(A),ye})},[]),nn=a.useCallback((A,le=!1)=>le?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:A}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(li,{remarkPlugins:[ci],components:Zg,children:A})}),[]),vt=a.useCallback(A=>{if($e.current=A.currentTarget.selectionStart??$e.current,Te.mentionActive&&Te.files.length>0){if(Te.handleKeyDown(A,N),A.key==="Enter"||A.key==="Tab"){const le=Te.files[Te.selectedIndex];if(le){const ye=Te.selectFile(le,N);z(ye),Te.dismissMention(),se(!1)}}return}if(H&&A.key==="ArrowDown"){A.preventDefault(),Be.length>0&&be(le=>(le+1)%Be.length);return}if(H&&A.key==="ArrowUp"){A.preventDefault(),Be.length>0&&be(le=>le===0?Be.length-1:le-1);return}if(H&&A.key==="Enter"){A.preventDefault();const le=Be[ue]??Be[0];le&&Bn(le);return}if(H&&A.key==="Escape"){A.preventDefault(),A.stopPropagation(),Q(!1),k(""),ve(-1);return}A.key!=="Enter"||A.shiftKey||(A.preventDefault(),wn())},[H,Be,ue,Bn,wn,Te,N]),rn=a.useCallback(()=>{if(nt.current){nt.current=!1;return}if(p){g(!1);return}typeof window<"u"&&window.innerWidth<=os&&Dt.current?.focus({preventScroll:!0}),g(!0)},[p,g]);return t.jsxs(t.Fragment,{children:[t.jsx("input",{ref:Dt,type:"text",className:"quick-chat-stealth-input","aria-hidden":"true",tabIndex:-1}),s&&t.jsx("button",{ref:$t,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":ie?"true":"false",style:{right:je.x,bottom:je.y},onPointerDown:Ae,onPointerMove:Le,onPointerUp:we,onClick:rn,children:t.jsx(Si,{size:24})}),p&&t.jsxs("div",{className:"quick-chat-panel",ref:Ht,"data-testid":"quick-chat-panel",style:{...ce?{right:je.x+rt.right,bottom:Ee+rt.bottom,width:Ve.width,height:Ve.height}:{}},children:[ce&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"n","data-testid":"quick-chat-resize-n",onPointerDown:xe,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:xe,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:xe,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:xe,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:xe,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:xe,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:xe,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:xe,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"&&Oe&&(()=>{const A=fe?.provider??Rt?.modelProvider??"";return b==="mobile"&&Oe.length>12&&A?t.jsx("span",{className:"quick-chat-model-tag quick-chat-model-tag--icon","data-testid":"quick-chat-model-tag",title:Oe,"aria-label":Oe,children:t.jsx(Rn,{provider:A,size:"sm"})}):t.jsx("span",{className:"quick-chat-model-tag","data-testid":"quick-chat-model-tag",title:Oe,children:Oe})})()]}),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:ge,disabled:re,children:t.jsx(dn,{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(qt,{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:Pe?.id??"",onChange:A=>Cn(A.target.value),"data-testid":"quick-chat-session-dropdown",children:[t.jsx("option",{value:"",disabled:!0,children:re?"Loading sessions…":"Select a session"}),dt.map(A=>t.jsx("option",{value:A.id,children:A.label},A.id))]})]}),E&&t.jsxs("div",{className:"quick-chat-new-session-chooser","data-testid":"quick-chat-new-session-chooser",children:[t.jsxs("div",{className:"quick-chat-inline-mode-toggle","data-testid":"quick-chat-inline-mode-toggle",children:[t.jsx("button",{type:"button",className:`quick-chat-mode-btn${w==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-model",onClick:()=>R("model"),children:"Model"}),t.jsx("button",{type:"button",className:`quick-chat-mode-btn${w==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-agent",onClick:()=>R("agent"),children:"Agent"})]}),w==="agent"?t.jsxs("div",{className:"quick-chat-panel-agent-select",children:[t.jsx("label",{htmlFor:"quick-chat-new-agent-select",className:"visually-hidden",children:"Select agent for new chat"}),t.jsx("select",{id:"quick-chat-new-agent-select",value:S,onChange:A=>O(A.target.value),"data-testid":"quick-chat-new-agent-select",children:d.map(A=>t.jsx("option",{value:A.id,children:_4(A)},A.id))})]}):t.jsx("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-new-model-select",children:t.jsx(ns,{id:"quick-chat-new-model-select",models:U,value:_,onChange:P,label:"Select model override",placeholder:M?"Loading models…":"Select a model",disabled:M||U.length===0,favoriteProviders:o,favoriteModels:l,onToggleFavorite:c,onToggleModelFavorite:u})}),t.jsxs("div",{className:"quick-chat-new-session-actions",children:[t.jsx("button",{type:"button",className:"btn","data-testid":"quick-chat-new-session-cancel",onClick:()=>{C(!1),R("model")},children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary","data-testid":"quick-chat-new-session-submit",onClick:()=>void pn(),disabled:re||(w==="agent"?!S:!Mo(_||D||J)),children:"Create"})]})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:Tt,"data-testid":"quick-chat-messages",children:re?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):Re?t.jsxs(t.Fragment,{children:[pe.map(A=>t.jsx(ip,{message:A,forcePlain:A.role!=="user"&&B.has(A.id),mentionAgentsByName:Ke,onToggleRender:Pn},A.id)),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:[Qe?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:nn(Qe,B.has("__streaming__"))}),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${B.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":B.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>Pn("__streaming__"),children:B.has("__streaming__")?t.jsx(bd,{size:14}):t.jsx(Ta,{size:14})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:Ie?"Thinking…":"Connecting…"}),Xg(bt,!0),Ie&&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:Ie})]})]})]}):Se?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):pe.length===0&&!Qe&&!Ie&&!Re?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsx(t.Fragment,{children:pe.map(A=>t.jsx(ip,{message:A,forcePlain:A.role!=="user"&&B.has(A.id),mentionAgentsByName:Ke,onToggleRender:Pn},A.id))})}),X.length>0&&t.jsx("div",{className:"quick-chat-attachment-previews","data-testid":"quick-chat-attachment-previews",children:X.map((A,le)=>t.jsxs("div",{className:"quick-chat-attachment-preview","data-testid":`quick-chat-attachment-preview-${le}`,children:[A.previewUrl?t.jsx("img",{src:A.previewUrl,alt:A.file.name}):t.jsx("span",{className:"quick-chat-attachment-preview-name",children:A.file.name}),t.jsx("button",{type:"button",className:"quick-chat-attachment-remove","data-testid":`quick-chat-attachment-remove-${le}`,"aria-label":`Remove ${A.file.name}`,onClick:()=>Zt(le),children:"×"})]},`${A.file.name}-${le}`))}),t.jsx("div",{className:"quick-chat-panel-input",children:t.jsxs("div",{className:`quick-chat-input-wrapper${de?" quick-chat-input-wrapper--dragover":""}`,onDragEnter:Gn,onDragOver:Tn,onDragLeave:Un,onDrop:sn,children:[t.jsx("input",{ref:Ot,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:A=>{Lt(A.target.files),A.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:()=>Ot.current?.click(),children:t.jsx(_p,{size:16})}),t.jsx("input",{ref:Mt,type:"text",value:N,onChange:Sn,onKeyDown:vt,onKeyUp:ss,onClick:Ln,onBlur:an,onFocus:Dn,onPaste:Ne,onTouchStart:A=>{typeof window>"u"||window.innerWidth>os||document.activeElement!==A.currentTarget&&(A.preventDefault(),A.currentTarget.focus({preventScroll:!0}))},placeholder:Xt,disabled:F,"data-testid":"quick-chat-input"}),Re?t.jsx("button",{type:"button",className:"chat-input-stop quick-chat-send-btn",onPointerDown:A=>{typeof window>"u"||window.innerWidth>os||(A.preventDefault(),A.pointerType&&A.pointerType!=="mouse"&&(Et.current=!0,ne()))},onTouchStart:A=>{typeof window>"u"||window.innerWidth>os||(A.preventDefault(),Et.current=!0,ne())},onMouseDown:A=>{typeof window>"u"||window.innerWidth>os||A.preventDefault()},onClick:()=>{if(Et.current){Et.current=!1;return}ne()},"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:t.jsx(Cs,{size:14})}):t.jsx("button",{type:"button",className:"quick-chat-send-btn",onPointerDown:A=>{typeof window>"u"||window.innerWidth>os||(A.preventDefault(),A.pointerType&&A.pointerType!=="mouse"&&(Et.current=!0,ln(),et(),wn()))},onTouchStart:A=>{typeof window>"u"||window.innerWidth>os||(A.preventDefault(),Et.current=!0,ln(),et(),wn())},onMouseDown:A=>{typeof window>"u"||window.innerWidth>os||A.preventDefault()},onClick:()=>{if(Et.current){Et.current=!1;return}wn()},disabled:F||N.trim().length===0&&X.length===0,"data-testid":"quick-chat-send",children:t.jsx(Oi,{size:16})})]}),t.jsx(p4,{agents:d,filter:I,highlightedIndex:ue,visible:H,onSelect:Bn,position:"above"}),t.jsx(x4,{visible:Te.mentionActive&&!H,position:_e,files:Te.files,selectedIndex:Te.selectedIndex,onSelect:A=>{const le=Te.selectFile(A,N);z(le),Te.dismissMention(),se(!1),Mt.current?.focus()},loading:Te.loading}),Ze&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${Kn}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:ft,children:"×"})]})]})})]})]})}function lr(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function ap(e){return e.status==="generating"||e.status==="awaiting_input"}function cr(e){return e==="complete"||e==="error"}function F4(e){const[n,s]=a.useState([]),i=a.useRef(new Map),r=a.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:c,requestSync:u}=La(),d=a.useCallback(()=>{jd(e).then(p=>{const g=p.filter(v=>{const x=lr(v.updatedAt),y=r.current.get(v.id);return y===void 0?!0:x<=y?!1:(r.current.delete(v.id),!0)}),b=new Map;for(const v of g)b.set(v.id,lr(v.updatedAt));i.current=b,s(g)}).catch(p=>{console.warn("[useBackgroundSessions] Failed to fetch AI sessions:",p)})},[e]);a.useEffect(()=>{u(),d()},[d,u]),a.useEffect(()=>{s(p=>{if(o.size===0)return p;let g=!1;const b=new Map(p.map(v=>[v.id,v]));for(const v of o.values()){if(e&&v.projectId&&v.projectId!==e)continue;const x=v.lastEventTimestamp,y=i.current.get(v.sessionId)??0;if(x<y)continue;const j=r.current.get(v.sessionId);if(j!==void 0&&x<=j)continue;if(j!==void 0&&x>j&&!cr(v.status)&&r.current.delete(v.sessionId),cr(v.status)){b.delete(v.sessionId)&&(g=!0),i.current.set(v.sessionId,x);continue}const E=b.get(v.sessionId),C=v.type??E?.type,w=v.title??E?.title;if(!E&&(!C||!w))continue;const R={id:v.sessionId,type:C??"planning",status:v.status,title:w??"AI Session",projectId:v.projectId??E?.projectId??e??null,lockedByTab:v.owningTabId??E?.lockedByTab??null,updatedAt:v.updatedAt??E?.updatedAt??new Date(x).toISOString()},S=b.get(v.sessionId);(!S||S.status!==R.status||S.title!==R.title||S.type!==R.type||S.projectId!==R.projectId||S.lockedByTab!==R.lockedByTab||S.updatedAt!==R.updatedAt)&&(b.set(v.sessionId,R),i.current.set(v.sessionId,x),g=!0)}return g?[...b.values()].sort((v,x)=>lr(x.updatedAt)-lr(v.updatedAt)):p})},[e,o]),a.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",g=v=>{try{const x=JSON.parse(v.data),y=lr(x.updatedAt)||Date.now();s(j=>{const E=i.current.get(x.id)??0;if(y<E)return j;const C=r.current.get(x.id);if(C!==void 0&&y<=C)return j;if(C!==void 0&&y>C&&!cr(x.status)&&r.current.delete(x.id),i.current.set(x.id,y),cr(x.status))return j.filter(R=>R.id!==x.id);const w=j.findIndex(R=>R.id===x.id);if(w>=0){const R=[...j];return R[w]=x,R}return ap(x)?[x,...j]:j}),l({sessionId:x.id,status:x.status,needsInput:x.status==="awaiting_input",type:x.type,title:x.title,projectId:x.projectId,owningTabId:x.lockedByTab,updatedAt:x.updatedAt,timestamp:y}),cr(x.status)&&c({sessionId:x.id,status:x.status,timestamp:y})}catch{}},b=v=>{try{const x=JSON.parse(v.data),y=Date.now();r.current.set(x,y),i.current.set(x,Math.max(i.current.get(x)??0,y)),c({sessionId:x,status:"complete",timestamp:y}),s(j=>j.filter(E=>E.id!==x))}catch{}};return Js(`/api/events${p}`,{events:{"ai_session:updated":g,"ai_session:deleted":b},onReconnect:()=>{d()}})},[c,l,e,d]);const m=a.useCallback(async p=>{const b=n.find(j=>j.id===p)?.type,v=Qi();let x=!1;if(b==="planning")try{await zp(p,e,v)}catch(j){x=!0,j instanceof Error&&j.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of planning session ${p} despite lock by another tab`)}else if(b==="subtask")try{await Up(p,e,v)}catch(j){x=!0,j instanceof Error&&j.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of subtask session ${p} despite lock by another tab`)}else if(b==="mission_interview")try{await Vp(p,e,v)}catch(j){x=!0,j instanceof Error&&j.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of mission interview session ${p} despite lock by another tab`)}x&&console.warn(`[useBackgroundSessions] Cancellation failed for session ${p}, attempting delete anyway`);const y=Date.now();r.current.set(p,y),i.current.set(p,Math.max(i.current.get(p)??0,y)),c({sessionId:p,status:"complete",timestamp:y});try{await Wp(p)}catch{}s(j=>j.filter(E=>E.id!==p))},[c,e,n]),h=a.useMemo(()=>n.filter(p=>ap(p)),[n]),f=a.useMemo(()=>h.filter(p=>p.type==="planning"),[h]);return{sessions:h,generating:h.filter(p=>p.status==="generating").length,needsInput:h.filter(p=>p.status==="awaiting_input").length,planningSessions:f,dismissSession:m,refresh:d}}const Zo="fusion:hide-session-banners",pd="fusion:session-banner-pref-changed";function U4(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Zo)==="1"}catch{return!1}}function B4(e){if(typeof window>"u")return()=>{};const n=i=>{i.key===Zo&&e()},s=()=>e();return window.addEventListener("storage",n),window.addEventListener(pd,s),()=>{window.removeEventListener("storage",n),window.removeEventListener(pd,s)}}function Y3(e){if(!(typeof window>"u"))try{e?window.localStorage.setItem(Zo,"1"):window.localStorage.removeItem(Zo),window.dispatchEvent(new Event(pd))}catch{}}function H4(){return a.useSyncExternalStore(B4,U4,()=>!1)}function Zn(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 rp(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function q4(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 Mc(e,n){if(rp(n.updatedAt,e.updatedAt)<0)return e;if(e.column===n.column)return q4(e,n);const i=rp(e.columnMovedAt,n.columnMovedAt);return e.columnMovedAt&&!n.columnMovedAt?{...n,column:e.column,columnMovedAt:e.columnMovedAt}:i>0?{...n,column:e.column,columnMovedAt:e.columnMovedAt}:n}function V4(e){const n=e?.projectId,s=e?.searchQuery,i=e?.sseEnabled??!0,[r,o]=a.useState([]),[l,c]=a.useState(!1),u=a.useRef(l);u.current=l;const d=a.useRef(r),m=a.useRef(0),h=a.useRef(0),f=a.useRef(s),p=a.useRef(null),g=a.useRef(void 0),b=a.useRef(0),v=a.useRef(n);d.current=r,f.current=s,v.current!==n&&(v.current=n,b.current++);const x=1e3,y=a.useCallback(async J=>{const te=++m.current,N=n,z=J?.searchQueryOverride??f.current,I=J?.includeArchivedOverride??u.current;try{const k=await xy(void 0,void 0,N,z,I);if(m.current!==te||n!==N)return;o(k.map(Zn)),g.current=Date.now()}catch{if(m.current!==te||n!==N)return;if(J?.clearOnError){o([]);return}o(k=>k)}},[n]);p.current=y;const j=a.useCallback(async()=>{u.current||(c(!0),u.current=!0,await p.current({includeArchivedOverride:!0}))},[]),E=a.useRef(s);a.useEffect(()=>{if(s===void 0&&E.current===void 0)return;E.current=s;const J=setTimeout(()=>{y({searchQueryOverride:s})},300);return()=>clearTimeout(J)},[s]),a.useEffect(()=>{y({clearOnError:!0});const J=()=>{if(document.visibilityState!=="visible")return;const te=Date.now();te-h.current<x||(h.current=te,y())};return document.addEventListener("visibilitychange",J),()=>{document.removeEventListener("visibilitychange",J)}},[y]),a.useEffect(()=>{if(i===!1)return;const J=b.current,te=n?`?projectId=${encodeURIComponent(n)}`:"",N=()=>b.current!==J;let z=!0;const I=V=>{if(N())return;const ve=Zn(JSON.parse(V.data));if(f.current){p.current({searchQueryOverride:f.current});return}o(B=>{const Y=B.findIndex(me=>me.id===ve.id);if(Y===-1)return[...B,ve];const X=B[Y],he=Mc(X,ve);if(he===X)return B;const de=[...B];return de[Y]=he,de}),g.current=Date.now()},k=V=>{if(N())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:ve,to:B}=JSON.parse(V.data),Y=Zn(ve);o(X=>X.map(he=>he.id===Y.id?{...Y,column:B}:he)),g.current=Date.now()},H=V=>{if(N())return;if(f.current){p.current({searchQueryOverride:f.current});return}const ve=Zn(JSON.parse(V.data));o(B=>B.map(Y=>Y.id!==ve.id?Y:Mc(Y,ve))),g.current=Date.now()},Q=V=>{if(N())return;if(f.current){p.current({searchQueryOverride:f.current});return}const ve=Zn(JSON.parse(V.data));o(B=>B.filter(Y=>Y.id!==ve.id))},ue=V=>{if(N())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:ve}=JSON.parse(V.data),B=Zn(ve);o(Y=>Y.map(X=>X.id===B.id?{...B,column:"done"}:X))},be=Js(`/api/events${te}`,{events:{"task:created":I,"task:moved":k,"task:updated":H,"task:deleted":Q,"task:merged":ue},onReconnect:()=>{z&&(N()||p.current())}});return()=>{z=!1,be()}},[n,i]);const C=a.useCallback(async J=>{const te=Zn(await Ip(J,n));return o(N=>N.some(z=>z.id===te.id)?N:[...N,te]),te},[n]),w=a.useCallback(async(J,te)=>Zn(await yy(J,te,n)),[n]),R=a.useCallback(async J=>Zn(await $p(J,n)),[n]),S=a.useCallback(async J=>Zn(await wy(J,n)),[n]),O=a.useCallback(async J=>jy(J,n),[n]),_=a.useCallback(async J=>Zn(await ky(J,n)),[n]),P=a.useCallback(async J=>Zn(await Ny(J,n)),[n]),U=a.useCallback(async J=>{const te=Zn(await Sy(J,n));return o(N=>N.some(z=>z.id===te.id)?N:[...N,te]),te},[n]),G=a.useCallback(async(J,te)=>{const N=d.current.find(I=>I.id===J),z=N?{...N,...te,updatedAt:new Date().toISOString()}:void 0;z&&o(I=>I.map(k=>k.id===J?z:k));try{const I=Zn(await ii(J,te,n));return o(k=>k.map(H=>H.id===J?I:H)),I}catch(I){throw N&&o(k=>k.map(H=>H.id===J?N:H)),I}},[n]),M=a.useCallback(async J=>{const te=Zn(await Ey(J,n));return o(N=>N.map(z=>z.id===J?te:z)),te},[n]),T=a.useCallback(async J=>{const te=Zn(await _y(J,n));return o(N=>N.map(z=>z.id===J?te:z)),te},[n]),D=a.useCallback(async()=>{const te=(await My(n)).map(Zn);return o(N=>N.map(z=>te.find(k=>k.id===z.id)||z)),te},[n]),K=a.useCallback(J=>{if(J.length===0)return;if(f.current){p.current({searchQueryOverride:f.current});return}const te=J.map(Zn);o(N=>{let z=N;for(const I of te){const k=z.findIndex(ue=>ue.id===I.id);if(k===-1){z===N&&(z=[...N]),z.push(I);continue}const H=z[k],Q=Mc(H,I);Q!==H&&(z===N&&(z=[...N]),z[k]=Q)}return z}),g.current=Date.now()},[]);return{tasks:r,createTask:C,moveTask:w,pauseTask:R,deleteTask:S,mergeTask:O,retryTask:_,resetTask:P,duplicateTask:U,updateTask:G,archiveTask:M,unarchiveTask:T,archiveAllDone:D,loadArchivedTasks:j,includeArchived:l,ingestCreatedTasks:K,lastFetchTimeMs:g.current}}const W4=5e3,K4=1e3;function G4(){const[e,n]=a.useState([]),[s,i]=a.useState(!0),[r,o]=a.useState(null),l=a.useRef(null),c=a.useRef(0),u=a.useCallback(async()=>{try{o(null);const f=await vu();n(f)}catch(f){o(f instanceof Error?f.message:"Failed to fetch projects")}},[]);a.useEffect(()=>{let f=!1;async function p(){i(!0);const b=performance.now();try{const v=await vu(),y=`initial fetchProjectsAcrossNodes took ${Math.round(performance.now()-b)}ms (${v.length} projects)`;console.log(`[useProjects] ${y}`),xr("[useProjects]",y),f||(n(v),o(null))}catch(v){const y=`initial fetch failed after ${Math.round(performance.now()-b)}ms: ${v instanceof Error?v.message:String(v)}`;console.warn(`[useProjects] ${y}`),xr("[useProjects]",y),f||o(v instanceof Error?v.message:"Failed to fetch projects")}finally{f||i(!1)}}p();const g=()=>{if(document.visibilityState!=="visible")return;const b=Date.now();b-c.current<K4||(c.current=b,u())};return document.addEventListener("visibilitychange",g),()=>{f=!0,document.removeEventListener("visibilitychange",g)}},[u]),a.useEffect(()=>{if(!s)return l.current=setInterval(()=>{u()},W4),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async f=>{const p=await Lj(f);return n(g=>[...g,p]),p},[]),m=a.useCallback(async(f,p)=>{const g=await Hj(f,p);return n(b=>b.map(v=>v.id===f?g:v)),g},[]),h=a.useCallback(async f=>{await Bp(f),n(p=>p.filter(g=>g.id!==f))},[]);return{projects:e,loading:s,error:r,refresh:u,register:d,update:m,unregister:h}}const J4="kb-dashboard-current-project";function Y4(e){return e??"local"}function Q4(e,n={}){const{nodeId:s=null}=n,[i,r]=a.useState(null),[o,l]=a.useState(!0),c=a.useRef(!1),u=a.useRef(!1),d=a.useRef(null),m=Y4(s);a.useEffect(()=>{let p=!1;async function g(){try{const b=await Yi();if(p)return;d.current=b.dashboardCurrentProjectIdByNode??{};const v=d.current[m];if(v){const x=e.find(y=>y.id===v);x&&(r(x),c.current=!0)}if(!v)try{const x=localStorage.getItem(J4);if(x){const y=JSON.parse(x);y?.id&&e.some(E=>E.id===y.id)&&(r(y),c.current=!0,d.current={...d.current,[m]:y.id},await bn({dashboardCurrentProjectIdByNode:d.current}).catch(()=>{}))}}catch{}}catch{}finally{p||l(!1)}}return g(),()=>{p=!0}},[m,e]),a.useEffect(()=>{if(!o){if(i){if(!e.some(b=>b.id===i.id)&&e.length>0){const b=e.find(v=>v.status==="active");r(b||e[0]||null);return}const g={...d.current,[m]:i.id};d.current=g,bn({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}else if(e.length>0&&!u.current){const p=e.find(g=>g.status==="active");p&&r(p)}}},[i,e,o,m]);const h=a.useCallback(p=>{if(u.current=!1,r(p),p){const g={...d.current,[m]:p.id};d.current=g,bn({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}},[m]),f=a.useCallback(()=>{u.current=!0,r(null);const p={...d.current};delete p[m],d.current=p,bn({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[m]);return{currentProject:i,setCurrentProject:h,clearCurrentProject:f,loading:o}}const eb=a.createContext(null);function X4({children:e}){const[n,s]=a.useState([]),i=a.useRef(0),r=a.useRef(new Map),o=a.useCallback(c=>{const u=r.current.get(c);u!==void 0&&(clearTimeout(u),r.current.delete(c)),s(d=>d.filter(m=>m.id!==c))},[]),l=a.useCallback((c,u="info")=>{const d=i.current++;s(h=>[...h,{id:d,message:c,type:u}]);const m=setTimeout(()=>o(d),4e3);r.current.set(d,m)},[o]);return a.useEffect(()=>()=>{r.current.forEach(c=>clearTimeout(c)),r.current.clear()},[]),$o.createElement(eb.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function Z4(){const e=a.useContext(eb);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const tb="kb-dashboard-theme-mode",nb="kb-dashboard-color-theme",sb="kb-dashboard-font-scale-pct",fd=100,e$=85,t$=125,ib=[...IN],gd="theme-data",Ac="theme-data.css";function n$(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.endsWith("/")?e.slice(0,-1)+`/${Ac}`:e.replace(/\/[^/]+$/,`/${Ac}`):`/${Ac}`}const js=typeof window<"u",s$=js?a.useLayoutEffect:a.useEffect;function ab(e){return e==="dark"||e==="light"||e==="system"}function op(){if(!js)return"dark";try{const e=localStorage.getItem(tb);if(ab(e))return e}catch{}return"dark"}function lp(){if(!js)return"default";try{const e=localStorage.getItem(nb);if(e&&ib.includes(e))return e}catch{}return"default"}function cp(e){if(js)try{localStorage.setItem(tb,e)}catch{}}function dp(e){if(js)try{localStorage.setItem(nb,e)}catch{}}function Pr(e){return typeof e!="number"||!Number.isFinite(e)?fd:Math.min(t$,Math.max(e$,Math.round(e)))}function up(){if(!js)return fd;try{const e=Number(localStorage.getItem(sb));return Pr(e)}catch{return fd}}function mp(e){if(js)try{localStorage.setItem(sb,String(Pr(e)))}catch{}}function i$(e,n){return e==="system"?n?"dark":"light":e}function a$(e,n,s,i){if(!js)return;const r=i$(e,i);document.documentElement.setAttribute("data-theme",r),document.documentElement.setAttribute("data-color-theme",n),document.documentElement.style.fontSize=`${Pr(s)}%`}function hp(){if(!js)return;const e=n$(),n=document.getElementById(gd);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=gd,document.head.appendChild(s)}function pp(){if(!js)return;const e=document.getElementById(gd);e&&e.remove()}function r$(){const[e,n]=a.useState(()=>op()),[s,i]=a.useState(()=>lp()),[r,o]=a.useState(()=>up()),[l,c]=a.useState(!0),[u,d]=a.useState(()=>js?window.matchMedia("(prefers-color-scheme: dark)").matches:!0),m=a.useRef(e),h=a.useRef(s),f=a.useRef(r),p=a.useRef(!1),g=a.useRef(!1),b=a.useRef(!1);a.useEffect(()=>{m.current=e},[e]),a.useEffect(()=>{h.current=s},[s]),a.useEffect(()=>{f.current=r},[r]),a.useEffect(()=>{if(!js||!l)return;let j=!1;return Yi().then(E=>{if(!j&&(ab(E.themeMode)&&!p.current&&(m.current!==E.themeMode&&(m.current=E.themeMode,n(E.themeMode)),op()!==E.themeMode&&cp(E.themeMode)),E.colorTheme&&ib.includes(E.colorTheme)&&!g.current&&(h.current!==E.colorTheme&&(h.current=E.colorTheme,i(E.colorTheme)),lp()!==E.colorTheme&&dp(E.colorTheme)),!b.current)){const C=Pr(E.dashboardFontScalePct);f.current!==C&&(f.current=C,o(C)),up()!==C&&mp(C)}}).catch(E=>{console.warn("[useTheme] Failed to hydrate theme from global settings",E)}).finally(()=>{j||c(!1)}),()=>{j=!0}},[l]),a.useEffect(()=>{if(!js)return;const j=window.matchMedia("(prefers-color-scheme: dark)"),E=C=>{d(C.matches)};return j.addEventListener("change",E),()=>j.removeEventListener("change",E)},[]),s$(()=>{a$(e,s,r,u)},[e,s,r,u]),a.useEffect(()=>{!js||l||(s!=="default"?hp():pp())},[s,l]);const v=a.useCallback(j=>{p.current=!0,m.current=j,n(j),cp(j),bn({themeMode:j}).catch(E=>{console.warn("[useTheme] Failed to persist themeMode to global settings",E)})},[]),x=a.useCallback(j=>{g.current=!0,h.current=j,i(j),dp(j),j!=="default"?hp():pp(),bn({colorTheme:j}).catch(E=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",E)})},[]),y=a.useCallback(j=>{const E=Pr(j);b.current=!0,f.current=E,o(E),mp(E),bn({dashboardFontScalePct:E}).catch(C=>{console.warn("[useTheme] Failed to persist dashboardFontScalePct to global settings",C)})},[]);return{themeMode:e,colorTheme:s,dashboardFontScalePct:r,setThemeMode:v,setColorTheme:x,setDashboardFontScalePct:y,isSystemDark:u}}function o$(e){const{planningSessions:n}=e,[s,i]=a.useState(!1),[r,o]=a.useState(!1),[l,c]=a.useState(null),[u,d]=a.useState(void 0),[m,h]=a.useState(!1),[f,p]=a.useState(null),[g,b]=a.useState(void 0),[v,x]=a.useState(null),[y,j]=a.useState("definition"),[E,C]=a.useState(!1),[w,R]=a.useState(void 0),[S,O]=a.useState(!1),[_,P]=a.useState(!1),[U,G]=a.useState(!1),[M,T]=a.useState(null),[D,K]=a.useState(!1),[J,te]=a.useState(!1),[N,z]=a.useState(void 0),[I,k]=a.useState(!1),[H,Q]=a.useState("project"),[ue,be]=a.useState(!1),[V,ve]=a.useState(!1),[B,Y]=a.useState(!1),[X,he]=a.useState(!1),[de,me]=a.useState(!1),[se,_e]=a.useState(!1),[Fe,Te]=a.useState(!1),st=!!(v||E||s||r||m||J||I||ue||V||B||de||X||U||D||S||_||se||Fe),nt=a.useCallback(()=>i(!0),[]),qe=a.useCallback(()=>i(!1),[]),Xe=a.useCallback(()=>o(!0),[]),$e=a.useCallback(fe=>{c(fe),o(!0)},[]),Ue=a.useCallback(()=>{const fe=n[0];fe&&(d(fe.id),o(!0))},[n]),oe=a.useCallback(fe=>{d(fe),o(!0)},[]),je=a.useCallback(()=>{o(!1),c(null),d(void 0)},[]),ie=a.useCallback(fe=>{p(fe),h(!0)},[]),Ae=a.useCallback(fe=>{b(fe),h(!0)},[]),Le=a.useCallback(()=>{h(!1),p(null),b(void 0)},[]),we=a.useCallback((fe,Oe="definition")=>{x(fe),j(Oe)},[]),Ee=a.useCallback(fe=>{x(fe),j("changes")},[]),Ve=a.useCallback(fe=>{x(Oe=>Oe&&{...Oe,...fe})},[]),rt=a.useCallback(()=>{x(null)},[]),xe=a.useCallback(fe=>{R(fe),C(!0)},[]),ce=a.useCallback(()=>{C(!1),R(void 0)},[]),Pe=a.useCallback(()=>O(!0),[]),pe=a.useCallback(()=>O(!1),[]),Re=a.useCallback(()=>P(!0),[]),Qe=a.useCallback(()=>P(!1),[]),Ie=a.useCallback(fe=>{T(fe??null),G(!0)},[]),bt=a.useCallback(()=>{G(!1),T(null)},[]),ee=a.useCallback(()=>K(!0),[]),re=a.useCallback(()=>K(!1),[]),Se=a.useCallback(()=>{te(fe=>!fe)},[]),ot=a.useCallback(()=>{te(!1),z(void 0)},[]),ne=a.useCallback(()=>k(!0),[]),Ze=a.useCallback(()=>k(!1),[]),ft=a.useCallback(fe=>{Q(fe)},[]),gt=a.useCallback(()=>be(!0),[]),St=a.useCallback(()=>be(!1),[]),Nt=a.useCallback(()=>ve(!0),[]),pt=a.useCallback(()=>ve(!1),[]),kt=a.useCallback(()=>Y(!0),[]),Ht=a.useCallback(()=>Y(!1),[]),$t=a.useCallback(()=>he(!0),[]),Tt=a.useCallback(()=>he(!1),[]),Mt=a.useCallback(()=>me(!0),[]),Ot=a.useCallback(()=>me(!1),[]),zt=a.useCallback(async(fe,Oe)=>{me(!1),z(Oe),te(!0)},[]),Ft=a.useCallback(()=>_e(!0),[]),Et=a.useCallback(()=>_e(!1),[]),Pt=a.useCallback(()=>Te(!0),[]),Dt=a.useCallback(()=>Te(!1),[]),Wt=a.useCallback((fe,Oe)=>{Oe(`Created ${fe.id} from planning mode`,"success"),o(!1),c(null)},[]),It=a.useCallback((fe,Oe)=>{const ut=fe.map(L=>L.id).join(", ");Oe(`Created ${ut} from planning mode`,"success"),o(!1),c(null)},[]),Rt=a.useCallback((fe,Oe)=>{const ut=fe.map(L=>L.id).join(", ");Oe(`Created ${ut} from subtask breakdown`,"success"),h(!1),p(null)},[]);return{newTaskModalOpen:s,isPlanningOpen:r,planningInitialPlan:l,planningResumeSessionId:u,isSubtaskOpen:m,subtaskInitialDescription:f,subtaskResumeSessionId:g,detailTask:v,detailTaskInitialTab:y,settingsOpen:E,settingsInitialSection:w,schedulesOpen:S,githubImportOpen:_,usageOpen:U,usageAnchorRect:M,systemStatsOpen:D,terminalOpen:J,terminalInitialCommand:N,filesOpen:I,fileBrowserWorkspace:H,activityLogOpen:ue,gitManagerOpen:V,workflowStepsOpen:B,agentsOpen:X,scriptsOpen:de,setupWizardOpen:se,modelOnboardingOpen:Fe,anyModalOpen:st,openNewTask:nt,closeNewTask:qe,openPlanning:Xe,openPlanningWithInitialPlan:$e,resumePlanning:Ue,openPlanningWithSession:oe,closePlanning:je,openSubtaskBreakdown:ie,openSubtaskWithSession:Ae,closeSubtask:Le,openDetailTask:we,openDetailWithChangesTab:Ee,updateDetailTask:Ve,closeDetailTask:rt,openSettings:xe,closeSettings:ce,openSchedules:Pe,closeSchedules:pe,openGitHubImport:Re,closeGitHubImport:Qe,openUsage:Ie,closeUsage:bt,openSystemStats:ee,closeSystemStats:re,toggleTerminal:Se,closeTerminal:ot,openFiles:ne,closeFiles:Ze,setFileWorkspace:ft,openActivityLog:gt,closeActivityLog:St,openGitManager:Nt,closeGitManager:pt,openWorkflowSteps:kt,closeWorkflowSteps:Ht,openAgents:$t,closeAgents:Tt,openScripts:Mt,closeScripts:Ot,runScript:zt,openSetupWizard:Ft,closeSetupWizard:Et,openModelOnboarding:Pt,closeModelOnboarding:Dt,onPlanningTaskCreated:Wt,onPlanningTasksCreated:It,onSubtaskTasksCreated:Rt}}function l$(e){const[n,s]=a.useState(2),[i,r]=a.useState("."),[o,l]=a.useState(!0),[c,u]=a.useState(!1),[d,m]=a.useState(!1),[h,f]=a.useState(void 0),[p,g]=a.useState(!1),[b,v]=a.useState(!1),[x,y]=a.useState(!1),[j,E]=a.useState({}),[C,w]=a.useState(!1),[R,S]=a.useState(!1),[O,_]=a.useState(!1),[P,U]=a.useState(!1),[G,M]=a.useState(!1),T=a.useCallback(async()=>{const[N,z]=await Promise.allSettled([Ty(e),ll(e)]);if(N.status==="fulfilled"&&(s(N.value.maxConcurrent),r(N.value.rootDir)),z.status==="fulfilled"){const I=z.value;l(!!I.autoMerge),u(!!I.globalPause),m(!!I.enginePaused),v(!!I.prAuthAvailable),f(I.taskStuckTimeoutMs),g(I.showQuickChatFAB===!0),E(I.experimentalFeatures??{});const k=I.experimentalFeatures??{};w(k.insights===!0),S(k.roadmap===!0),_(k.memoryView===!0),U(k.devServerView===!0||k.devServer===!0),M(k.todoView===!0)}y(!0)},[e]);a.useEffect(()=>{y(!1),E({}),w(!1),S(!1),_(!1),U(!1),M(!1),T()},[T]);const D=a.useCallback(async()=>{const N=!o;l(N);try{await so({autoMerge:N},e)}catch{l(!N)}},[o,e]),K=a.useCallback(async()=>{const N=!c;u(N);try{await so({globalPause:N,globalPauseReason:N?"manual":void 0},e)}catch{u(!N)}},[c,e]),J=a.useCallback(async()=>{const N=!d;m(N);try{await so({enginePaused:N},e)}catch{m(!N)}},[d,e]),te=a.useCallback(async()=>{const N=!p;g(N);try{await so({showQuickChatFAB:N},e)}catch{g(!N)}},[p,e]);return{maxConcurrent:n,rootDir:i,autoMerge:o,globalPaused:c,enginePaused:d,taskStuckTimeoutMs:h,showQuickChatFAB:p,prAuthAvailable:b,settingsLoaded:x,experimentalFeatures:j,insightsEnabled:C,roadmapEnabled:R,memoryEnabled:O,devServerEnabled:P,todosEnabled:G,toggleAutoMerge:D,toggleGlobalPause:K,toggleEnginePause:J,toggleShowQuickChatFAB:te,refresh:T}}function c$(e){const{projectId:n,projects:s,projectsLoading:i,currentProject:r,setCurrentProject:o,addToast:l,openTaskDetail:c,closeTaskDetail:u}=e,d=a.useRef(!1),m=a.useRef(null);return a.useEffect(()=>{const f=new URLSearchParams(window.location.search),p=f.get("project"),g=f.get("task");if(!g||i)return;if(p){const v=s.find(x=>x.id===p);if(!v){l(`Project '${p}' not found`,"error");return}r?.id!==v.id&&o(v)}if(d.current)return;d.current=!0,Sr(g,p??n).then(v=>{c(v),m.current=g}).catch(()=>{l(`Task ${g} not found`,"error")})},[n,s,i,r,o,l,c]),{handleDetailClose:a.useCallback(()=>{if(m.current){const f=new URLSearchParams(window.location.search);f.delete("task");const p=f.toString();window.history.replaceState(null,"",p?`${window.location.pathname}?${p}`:window.location.pathname),m.current=null}u()},[u])}}function d$(){const[e,n]=a.useState([]),[s,i]=a.useState([]),[r,o]=a.useState([]),l=a.useRef(s),c=a.useRef(r);a.useEffect(()=>{bs().then(m=>{n(m.models),l.current=m.favoriteProviders,c.current=m.favoriteModels,i(m.favoriteProviders),o(m.favoriteModels)}).catch(()=>{})},[]),a.useEffect(()=>{l.current=s},[s]),a.useEffect(()=>{c.current=r},[r]);const u=a.useCallback(async m=>{const h=l.current,p=h.includes(m)?h.filter(g=>g!==m):[m,...h];l.current=p,i(()=>p);try{await bn({favoriteProviders:p,favoriteModels:c.current})}catch(g){throw l.current=h,i(()=>h),g}},[]),d=a.useCallback(async m=>{const h=c.current,p=h.includes(m)?h.filter(g=>g!==m):[m,...h];c.current=p,o(()=>p);try{await bn({favoriteProviders:l.current,favoriteModels:p})}catch(g){throw c.current=h,o(()=>h),g}},[]);return{availableModels:e,favoriteProviders:s,favoriteModels:r,toggleFavoriteProvider:u,toggleFavoriteModel:d}}function u$({projectId:e,setupWizardOpen:n,openModelOnboarding:s,openSettings:i}){const r=a.useRef(!1),o=a.useRef(n);o.current=n,a.useEffect(()=>{if(n||!e||r.current)return;r.current=!0;let l=!1,c=!1;Er().then(({providers:u})=>{const d=u.some(h=>h.authenticated);if(u.length>0&&!d||u.length>0&&d)return Yi().then(h=>{const f=!!(h.defaultProvider&&h.defaultModelId);(h.modelOnboardingComplete===!1||h.modelOnboardingComplete===void 0)&&(!d||!f)&&!Aa()?l=!0:!d&&!Aa()&&(c=!0)})}).then(()=>{if(o.current){r.current=!1;return}l?(Is("onboarding:auto-triggered",{trigger:"first-run"}),s()):c&&(Is("onboarding:auto-triggered",{trigger:"missing-provider"}),i("authentication"))}).catch(()=>{})},[e,n,s,i])}const fp="kb-update-banner-dismissed";function m$(){const[e,n]=a.useState(!0),[s,i]=a.useState(!1),[r,o]=a.useState(null),[l,c]=a.useState(null),[u,d]=a.useState(!1);a.useEffect(()=>{const h=sessionStorage.getItem(fp)==="true";d(h);let f=!1;return Py().then(p=>{f||p.disabled||(i(p.updateAvailable===!0),o(typeof p.latestVersion=="string"?p.latestVersion:null),c(typeof p.currentVersion=="string"?p.currentVersion:null))}).catch(()=>{}).finally(()=>{f||n(!1)}),()=>{f=!0}},[]);const m=a.useCallback(()=>{d(!0),sessionStorage.setItem(fp,"true")},[]);return{updateAvailable:s,latestVersion:r,currentVersion:l,loading:e,dismissed:u,dismiss:m}}const h$=["board","list","agents","missions","chat","documents","research","roadmaps","skills","mailbox","insights","memory","devserver","dev-server","todos"];function p$(e){return e!==null&&h$.includes(e)}function f$(e){return e!==null&&/^plugin:[^:]+:.+$/u.test(e)}function gp(e){return p$(e)||f$(e)}function g$(e){return e==="devserver"?"dev-server":e}function b$(e){const{projectsLoading:n,projectsError:s,currentProjectLoading:i,currentProject:r,projectsLength:o,setupWizardOpen:l,openSetupWizard:c,themeMode:u,setThemeMode:d}=e,[m,h]=a.useState(()=>{if(typeof window<"u"){const x=window.localStorage.getItem("kb-dashboard-view-mode");if(x==="overview"||x==="project")return x}return"overview"}),[f,p]=a.useState(()=>{const x=Yn("kb-dashboard-task-view");return gp(x)?x:"board"}),g=a.useRef(!1);a.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",m)},[m]),a.useEffect(()=>{const x=Yn("kb-dashboard-task-view",r?.id);if(gp(x)){const y=!g.current&&x==="devserver";p(y?"devserver":g$(x))}else p("board");r?.id&&(g.current=!0)},[r?.id]),a.useEffect(()=>{fs("kb-dashboard-task-view",f,r?.id)},[r?.id,f]),a.useEffect(()=>{n||i||r&&m==="overview"&&h("project")},[n,i,r,m]),a.useEffect(()=>{if(n||i||l||s||o>0||r)return;const x=window.setTimeout(()=>{c()},500);return()=>window.clearTimeout(x)},[n,s,o,i,r,l,c]);const b=a.useCallback(x=>{p(x)},[]),v=a.useCallback(()=>{const x=["dark","light","system"],y=x.indexOf(u),j=x[(y+1)%x.length];d(j)},[u,d]);return{viewMode:m,setViewMode:h,taskView:f,setTaskView:p,handleChangeTaskView:b,handleToggleTheme:v}}const bp=new Map,x$=6e4;function v$(e){const[n,s]=a.useState([]),[i,r]=a.useState(!0),[o,l]=a.useState(null),c=a.useRef(!1);return a.useEffect(()=>{const u=e??"default";let d=!1;async function m(){const h=bp.get(u);if(h&&Date.now()<h.expiresAt){if(d)return;s(h.views),r(!1);return}c.current||r(!0),l(null);try{const f=await Zk(e);if(d)return;bp.set(u,{views:f,expiresAt:Date.now()+x$}),s(f)}catch(f){if(d)return;l(f instanceof Error?f.message:"Failed to fetch plugin dashboard views")}finally{d||(r(!1),c.current=!0)}}return m(),()=>{d=!0}},[e]),a.useMemo(()=>({views:n,loading:i,error:o}),[n,i,o])}function y$({taskView:e,context:n}){const s=wN(e);if(!s)return null;const i=jN(s.pluginId,s.viewId);return i?t.jsx(i,{context:n}):t.jsx(t.Fragment,{children:kN({pluginId:s.pluginId,viewId:s.viewId})})}function w$(e){const{setCurrentProject:n,clearCurrentProject:s,setViewMode:i,currentProject:r,refreshProjects:o,toggleFavoriteProvider:l,toggleFavoriteModel:c,addToast:u,openSettings:d,openSetupWizard:m,closeSetupWizard:h,closeModelOnboarding:f}=e,p=a.useCallback(S=>{n(S),i("project")},[n,i]),g=a.useCallback(()=>{s(),i("overview")},[s,i]),b=a.useCallback(()=>{d()},[d]),v=a.useCallback(()=>{m()},[m]),x=a.useCallback(S=>{h(),n(S),i("project"),u(`Project ${S.name} registered successfully`,"success"),o()},[h,n,i,u,o]),y=a.useCallback(()=>{f()},[f]),j=a.useCallback(async S=>{try{await Uj(S.id),u(`Project ${S.name} paused`,"success"),await o()}catch{u(`Failed to pause project ${S.name}`,"error")}},[u,o]),E=a.useCallback(async S=>{try{await Bj(S.id),u(`Project ${S.name} resumed`,"success"),await o()}catch{u(`Failed to resume project ${S.name}`,"error")}},[u,o]),C=a.useCallback(async S=>{try{await Bp(S.id),u(`Project ${S.name} removed`,"success"),r?.id===S.id&&(s(),i("overview")),await o()}catch{u(`Failed to remove project ${S.name}`,"error")}},[r,s,i,u,o]),w=a.useCallback(async S=>{try{await l(S)}catch{u("Failed to update favorites","error")}},[l,u]),R=a.useCallback(async S=>{try{await c(S)}catch{u("Failed to update model favorites","error")}},[c,u]);return{handleSelectProject:p,handleViewAllProjects:g,handleOpenSettings:b,handleAddProject:v,handleSetupComplete:x,handleModelOnboardingComplete:y,handlePauseProject:j,handleResumeProject:E,handleRemoveProject:C,handleToggleFavorite:w,handleToggleModelFavorite:R}}function j$(e){const{createTask:n,ingestCreatedTasks:s,onPlanningTaskCreated:i,onPlanningTasksCreated:r,onSubtaskTasksCreated:o,addToast:l}=e,c=a.useCallback(async p=>n({...p,column:"triage",source:{sourceType:"dashboard_ui"}}),[n]),u=a.useCallback(async p=>await n({...p,column:"triage",source:{sourceType:"dashboard_ui"}}),[n]),d=a.useCallback(p=>{s([p]),i(p,l)},[l,s,i]),m=a.useCallback(p=>{s(p),r(p,l)},[l,s,r]),h=a.useCallback(p=>{s(p),o(p,l)},[l,s,o]),f=a.useCallback(p=>{l(`Imported ${p.id} from GitHub`,"success")},[l]);return{handleBoardQuickCreate:c,handleModalCreate:u,handlePlanningTaskCreated:d,handlePlanningTasksCreated:m,handleSubtaskTasksCreated:h,handleGitHubImport:f}}async function k$(e){return cl("/health",{nodeId:e})}async function N$(e){return cl("/projects",{nodeId:e})}async function S$(e,n,s){const i=new URLSearchParams({projectId:n});return s&&s.trim()&&i.set("q",s.trim()),cl(`/tasks?${i.toString()}`,{nodeId:e})}async function C$(e,n){return cl(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:e})}async function Q3(e){return $(`/nodes/${encodeURIComponent(e)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function X3(e){return $(`/nodes/${encodeURIComponent(e)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function Z3(e){return $(`/nodes/${encodeURIComponent(e)}/settings/sync-status`)}async function ez(e){return $(`/nodes/${encodeURIComponent(e)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}function E$(e,n){const{projectId:s,searchQuery:i}=n??{},[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState(null),[m,h]=a.useState(!1),[f,p]=a.useState(null),g=a.useRef(null),b=a.useCallback(async()=>{if(!e){o([]),c([]),d(null),h(!1),p(null);return}g.current?.abort();const x=new AbortController;g.current=x,h(!0),p(null);try{const y=[k$(e),N$(e)];s&&(y.push(S$(e,s,i)),y.push(C$(e,s)));const j=await Promise.allSettled(y);if(x.signal.aborted)return;const E=j[0],C=j[1];if(E.status==="rejected"){p(`Failed to fetch node health: ${E.reason}`),h(!1);return}if(d(E.value),C.status==="rejected"){p(`Failed to fetch projects: ${C.reason}`),h(!1);return}if(o(C.value),s&&j[2]){const w=j[2];if(w.status==="rejected"){p(`Failed to fetch tasks: ${w.reason}`),h(!1);return}w.status==="fulfilled"&&c(w.value)}h(!1)}catch(y){x.signal.aborted||(p(y instanceof Error?y.message:"Unknown error"),h(!1))}},[e,s,i]);a.useEffect(()=>(b(),()=>{g.current?.abort()}),[b]);const v=a.useCallback(()=>{b()},[b]);return{projects:r,tasks:l,health:u,loading:m,error:f,refresh:v}}function _$(e){const[n,s]=a.useState(!1),[i,r]=a.useState(null);return a.useEffect(()=>{if(!e){s(!1),r(null);return}const o=`/api/proxy/${encodeURIComponent(e)}/events`;return Js(o,{events:{"task:created":l=>{r({type:"task:created",data:l.data})},"task:moved":l=>{r({type:"task:moved",data:l.data})},"task:updated":l=>{r({type:"task:updated",data:l.data})},"task:deleted":l=>{r({type:"task:deleted",data:l.data})},"task:merged":l=>{r({type:"task:merged",data:l.data})}},onOpen:()=>s(!0),onError:()=>s(!1)})},[e]),{isConnected:n,lastEvent:i}}const M$="fusion-dashboard-current-node",rb=a.createContext(null);function A$({children:e}){const[n,s]=a.useState(null),[i,r]=a.useState(!0),o=a.useRef(!1),l=a.useRef(void 0);a.useEffect(()=>{let m=!1;async function h(){try{const f=await Yi();if(m)return;l.current=f.dashboardCurrentNodeId;const p=f.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const g=localStorage.getItem(M$);if(g){const b=JSON.parse(g);b?.id&&b?.type==="remote"&&(l.current=b.id,await bn({dashboardCurrentNodeId:b.id}).catch(()=>{}))}}catch{}}catch{}finally{m||r(!1)}}return h(),()=>{m=!0}},[]),a.useEffect(()=>{if(!i)if(n&&n.type==="remote"&&n.id){const m=n.id;l.current!==m&&(l.current=m,bn({dashboardCurrentNodeId:m}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,bn({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,i]);const c=a.useCallback(m=>{s(m)},[]),u=a.useCallback(()=>{s(null),l.current=void 0,bn({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),d={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:u};return t.jsx(rb.Provider,{value:d,children:e})}function R$(){const e=a.useContext(rb);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}function T$({open:e}){const[n,s]=a.useState(""),i=a.useRef(null);a.useEffect(()=>{e&&i.current?.focus()},[e]);const r=a.useCallback(()=>{const l=n.trim();l&&(oy(l),window.location.reload())},[n]),o=a.useCallback(()=>{ly(),window.location.reload()},[]);return e?t.jsx("div",{className:"modal-overlay open auth-token-recovery-overlay",role:"presentation",onKeyDownCapture:l=>{l.key==="Escape"&&(l.preventDefault(),l.stopPropagation())},children:t.jsxs("div",{className:"modal modal-md",role:"dialog","aria-modal":"true","aria-labelledby":"auth-token-recovery-title","aria-describedby":"auth-token-recovery-description",children:[t.jsx("div",{className:"modal-header auth-token-recovery-header",children:t.jsx("h3",{id:"auth-token-recovery-title",children:"Authentication token required"})}),t.jsxs("div",{className:"auth-token-recovery-content",children:[t.jsx("p",{id:"auth-token-recovery-description",children:"This dashboard session can't authenticate with the daemon. Set a replacement token or clear the current token and retry."}),t.jsxs("div",{className:"auth-token-recovery-field",children:[t.jsx("label",{htmlFor:"auth-token-recovery-input",children:"Replacement token"}),t.jsx("input",{ref:i,id:"auth-token-recovery-input",className:"input",type:"password",value:n,onChange:l=>s(l.target.value),placeholder:"Paste token",autoComplete:"off",spellCheck:!1})]})]}),t.jsxs("div",{className:"modal-actions auth-token-recovery-actions",children:[t.jsx("button",{type:"button",className:"btn",onClick:o,children:"Clear token and retry"}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:r,disabled:n.trim().length===0,children:"Set token and reload"})]})]})}):null}const P$=200,I$=a.lazy(()=>hn(()=>import("./AgentsView-Bl9JH5C8.js"),__vite__mapDeps([22,1,3,4,23,14,6,7,24])).then(e=>({default:e.AgentsView}))),$$=a.lazy(()=>hn(()=>import("./DocumentsView-CESb6RI7.js"),__vite__mapDeps([25,1,6,7,26])).then(e=>({default:e.DocumentsView}))),D$=a.lazy(()=>hn(()=>import("./InsightsView-BKhvyEyQ.js"),__vite__mapDeps([27,1,20,6,7,28])).then(e=>({default:e.InsightsView}))),L$=a.lazy(()=>hn(()=>import("./ResearchView-CkVwRDVA.js"),__vite__mapDeps([29,1,6,7,30])).then(e=>({default:e.ResearchView}))),z$=a.lazy(()=>hn(()=>import("./NodesView-DgTXO8mm.js"),__vite__mapDeps([31,1,23,6,7,32])).then(e=>({default:e.NodesView}))),O$=a.lazy(()=>hn(()=>import("./ChatView-liNErE53.js"),__vite__mapDeps([33,1,6,7])).then(e=>({default:e.ChatView}))),F$=a.lazy(()=>hn(()=>import("./RoadmapsView-Cu85_XrQ.js"),__vite__mapDeps([34,1,6,7,35])).then(e=>({default:e.RoadmapsView}))),U$=a.lazy(()=>hn(()=>import("./SkillsView-C096TB7i.js"),__vite__mapDeps([36,1,6,7,37])).then(e=>({default:e.SkillsView}))),B$=a.lazy(()=>hn(()=>import("./MemoryView-DB-l2miV.js"),__vite__mapDeps([38,1,18,19,6,7,39])).then(e=>({default:e.MemoryView}))),H$=a.lazy(()=>hn(()=>import("./DevServerView-CV_PpbnZ.js"),__vite__mapDeps([40,1,6,7,41])).then(e=>({default:e.DevServerView}))),q$=a.lazy(()=>hn(()=>import("./TodoView-CUiAt2mR.js"),__vite__mapDeps([42,1,5,6,7,43])).then(e=>({default:e.TodoView})));function V$(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{hn(()=>import("./AgentsView-Bl9JH5C8.js"),__vite__mapDeps([22,1,3,4,23,14,6,7,24])),hn(()=>import("./DocumentsView-CESb6RI7.js"),__vite__mapDeps([25,1,6,7,26])),hn(()=>import("./InsightsView-BKhvyEyQ.js"),__vite__mapDeps([27,1,20,6,7,28])),hn(()=>import("./ResearchView-CkVwRDVA.js"),__vite__mapDeps([29,1,6,7,30])),hn(()=>import("./NodesView-DgTXO8mm.js"),__vite__mapDeps([31,1,23,6,7,32])),hn(()=>import("./ChatView-liNErE53.js"),__vite__mapDeps([33,1,6,7])),hn(()=>import("./RoadmapsView-Cu85_XrQ.js"),__vite__mapDeps([34,1,6,7,35])),hn(()=>import("./SkillsView-C096TB7i.js"),__vite__mapDeps([36,1,6,7,37])),hn(()=>import("./MemoryView-DB-l2miV.js"),__vite__mapDeps([38,1,18,19,6,7,39])),hn(()=>import("./DevServerView-CV_PpbnZ.js"),__vite__mapDeps([40,1,6,7,41])),hn(()=>import("./TodoView-CUiAt2mR.js"),__vite__mapDeps([42,1,5,6,7,43]))})}const Rc="kb-setup-warning-dismissed";function W$(){const{toasts:e,addToast:n,removeToast:s}=Z4(),i=typeof window<"u"&&!!window.electronAPI;a.useEffect(()=>{V$()},[]);const{projects:r,loading:o,error:l,refresh:c}=G4(),{nodes:u}=ml(),{currentNode:d,currentNodeId:m,isRemote:h,setCurrentNode:f,clearCurrentNode:p}=R$(),{currentProject:g,setCurrentProject:b,clearCurrentProject:v,loading:x}=Q4(r,{nodeId:m}),{hasAiProvider:y,hasGithub:j,loading:E,hasWarnings:C}=Fg(g?.id),{updateAvailable:w,latestVersion:R,currentVersion:S,dismissed:O,dismiss:_}=m$();a.useEffect(()=>{if(m&&!d&&u.length>0){const tt=u.find(At=>At.id===m);if(tt){f(tt);return}}m&&u.length>0&&(u.some(At=>At.id===m)||p())},[m,d,u,f,p]);const[P,U]=a.useState(""),G=E$(m,{projectId:g?.id,searchQuery:P||void 0});_$(m);const M=h&&G.projects.length>0?G.projects:r,{themeMode:T,colorTheme:D,dashboardFontScalePct:K,setThemeMode:J,setColorTheme:te,setDashboardFontScalePct:N}=r$(),{sessions:z,generating:I,needsInput:k,planningSessions:H,dismissSession:Q}=F4(g?.id),ue=z.filter(tt=>tt.status==="awaiting_input"||tt.status==="error"),be=H4(),V=o$({projectId:g?.id,planningSessions:H}),{viewMode:ve,setViewMode:B,taskView:Y,handleChangeTaskView:X}=b$({projectsLoading:o,projectsError:l,currentProjectLoading:x,currentProject:g,projectsLength:r.length,setupWizardOpen:V.setupWizardOpen,openSetupWizard:V.openSetupWizard,themeMode:T,setThemeMode:J}),{views:he}=v$(g?.id),de=a.useCallback(tt=>{tt==="missions"&&(Nt(void 0),kt(void 0),$t(void 0)),X(tt)},[X]),me=Y==="board"||Y==="list",{tasks:se,createTask:_e,moveTask:Fe,pauseTask:Te,deleteTask:st,mergeTask:nt,retryTask:qe,resetTask:Xe,updateTask:$e,duplicateTask:Ue,archiveTask:oe,unarchiveTask:je,archiveAllDone:ie,loadArchivedTasks:Ae,ingestCreatedTasks:Le,lastFetchTimeMs:we}=V4({...g?{projectId:g.id}:{},searchQuery:P||void 0,sseEnabled:me}),[Ee,Ve]=a.useState(!1),[rt,xe]=a.useState(0),ce=a.useRef(performance.now()),Pe=a.useRef(!1),pe=a.useRef(!1),Re=a.useMemo(()=>o?"projects":x?"project":"tasks",[o,x]);a.useEffect(()=>{if(!o&&!Pe.current){Pe.current=!0;const tt=`projects loaded at ${Math.round(performance.now()-ce.current)}ms from mount`;console.log(`[App] ${tt}`),xr("[App]",tt)}if(!x&&!pe.current){pe.current=!0;const tt=`current-project resolved at ${Math.round(performance.now()-ce.current)}ms from mount`;console.log(`[App] ${tt}`),xr("[App]",tt)}},[o,x]),a.useEffect(()=>{if(Ee||o||x)return;const tt=performance.now(),At=window.setTimeout(()=>{const Mn=`dashboard ready at ${Math.round(performance.now()-ce.current)}ms from mount (settle delay=${Math.round(performance.now()-tt)}ms)`;console.log(`[App] ${Mn}`),xr("[App]",Mn),Ve(!0)},P$);return()=>{window.clearTimeout(At)}},[Ee,o,x]);const Ie=$a()==="mobile",{keyboardOpen:bt}=Qg({enabled:Ie}),ee=Ie&&bt,[re,Se]=a.useState(0),ot=a.useCallback(()=>{Kp(g?.id).then(tt=>{Se(tt.unreadCount)}).catch(tt=>{console.warn("[App] Failed to fetch mailbox unread count:",tt)})},[g?.id]);a.useEffect(()=>{ot();const tt=new URLSearchParams;g?.id&&tt.set("projectId",g.id);const At=tt.size>0?`?${tt.toString()}`:"";return Js(`/api/events${At}`,{events:{"message:sent":ot,"message:received":ot,"message:read":ot,"message:deleted":ot}})},[g?.id,ot]);const[ne,Ze]=a.useState(!1),[ft,gt]=a.useState(!1),[St,Nt]=a.useState(void 0),[pt,kt]=a.useState(void 0),[Ht,$t]=a.useState(void 0),[Tt,Mt]=a.useState(!1),[Ot,zt]=a.useState(!1),[Ft,Et]=a.useState(()=>Yn(Rc,g?.id)==="true");a.useEffect(()=>{Et(Yn(Rc,g?.id)==="true")},[g?.id]),a.useEffect(()=>{const tt=()=>{zt(!0)};return window.addEventListener(Hc,tt),()=>{window.removeEventListener(Hc,tt)}},[]);const Pt=a.useCallback(()=>{fs(Rc,"true",g?.id),Et(!0)},[g?.id]),{maxConcurrent:Dt,autoMerge:Wt,globalPaused:It,enginePaused:Rt,taskStuckTimeoutMs:fe,showQuickChatFAB:Oe,prAuthAvailable:ut,settingsLoaded:L,experimentalFeatures:F,insightsEnabled:ge,roadmapEnabled:ze,memoryEnabled:Be,devServerEnabled:Ke,todosEnabled:dt,toggleAutoMerge:Xt,toggleGlobalPause:Cn,toggleEnginePause:pn,refresh:Kn}=l$(g?.id),Lt=F.skillsView===!0,Zt=F.nodesView===!0,Ne=F.researchView===!0,et=F.agentOnboarding===!0,ln=!0;a.useEffect(()=>{L&&(Y==="skills"&&!Lt&&X("board"),Y==="insights"&&!ge&&X("board"),Y==="roadmaps"&&!ze&&X("board"),Y==="memory"&&!Be&&X("board"),(Y==="devserver"||Y==="dev-server")&&!Ke&&X("board"),Y==="todos"&&!dt&&X("board"),Y==="research"&&!Ne&&X("board"))},[Y,L,Lt,ge,ze,X,ln,Be,Ke,dt,Ne]),a.useEffect(()=>{ne&&!Zt&&Ze(!1)},[ne,Zt]);const{availableModels:wn,favoriteProviders:Gn,favoriteModels:Tn,toggleFavoriteProvider:Un,toggleFavoriteModel:sn}=d$();u$({projectId:g?.id,setupWizardOpen:V.setupWizardOpen,openModelOnboarding:V.openModelOnboarding,openSettings:V.openSettings});const{handleSelectProject:un,handleViewAllProjects:Bn,handleOpenSettings:Sn,handleAddProject:an,handleSetupComplete:Dn,handleModelOnboardingComplete:Ln,handlePauseProject:ss,handleResumeProject:Pn,handleRemoveProject:nn,handleToggleFavorite:vt,handleToggleModelFavorite:rn}=w$({setCurrentProject:b,clearCurrentProject:v,setViewMode:B,currentProject:g,refreshProjects:c,toggleFavoriteProvider:Un,toggleFavoriteModel:sn,addToast:n,openSettings:V.openSettings,openSetupWizard:V.openSetupWizard,closeSetupWizard:V.closeSetupWizard,closeModelOnboarding:V.closeModelOnboarding}),{handleDetailClose:A}=c$({projectId:g?.id,projects:r,projectsLoading:o,currentProject:g,setCurrentProject:b,addToast:n,openTaskDetail:V.openDetailTask,closeTaskDetail:V.closeDetailTask}),{handleBoardQuickCreate:le,handleModalCreate:ye,handlePlanningTaskCreated:Ye,handlePlanningTasksCreated:mt,handleSubtaskTasksCreated:ht,handleGitHubImport:Kt}=j$({createTask:_e,ingestCreatedTasks:Le,onPlanningTaskCreated:V.onPlanningTaskCreated,onPlanningTasksCreated:V.onPlanningTasksCreated,onSubtaskTasksCreated:V.onSubtaskTasksCreated,addToast:n}),Jt=a.useCallback((tt,At)=>{if(At==="changes"){V.openDetailWithChangesTab(tt);return}V.openDetailTask(tt,At)},[V]),zn=a.useCallback(async tt=>{try{const At=await Sr(tt,g?.id);V.openDetailTask(At,"logs")}catch(At){n(`Failed to open task logs: ${At.message}`,"error")}},[V,g?.id,n]),[Hn,zs]=a.useState([]);a.useEffect(()=>{let tt=!1;return Br(g?.id).then(At=>{tt||zs(At)}).catch(()=>{tt||zs([])}),()=>{tt=!0}},[g?.id]);const ae=a.useMemo(()=>new Map(Hn.map(tt=>[tt.id,tt.name])),[Hn]),Me=a.useCallback(()=>{Zt&&Ze(tt=>!tt)},[Zt]),it=a.useCallback(()=>{V.setFileWorkspace("project"),V.openFiles()},[V]),wt=a.useCallback(async()=>{gt(!0);try{await c()}finally{gt(!1)}},[c]),jt=a.useCallback(tt=>{kt(tt),Nt(void 0),X("missions")},[X]),fn=a.useCallback(tt=>{tt.type==="planning"?V.openPlanningWithSession(tt.id):tt.type==="subtask"?V.openSubtaskWithSession(tt.id):tt.type==="mission_interview"?(kt(void 0),Nt(tt.id),$t(void 0),X("missions")):(tt.type==="milestone_interview"||tt.type==="slice_interview")&&(Nt(void 0),kt(void 0),$t(tt.id),X("missions"))},[X,V]),mn=a.useCallback(()=>{},[]),en=a.useCallback(()=>{},[]),on=!o&&!x&&r.length===0&&!g&&!!l,xn=()=>on?t.jsx(BI,{errorMessage:l??"Failed to fetch projects",isRetrying:ft,onRetry:wt}):ne?t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(rs,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(z$,{addToast:n,onClose:()=>Ze(!1)})})})}):ve==="overview"?t.jsx(rs,{children:t.jsx(mS,{projects:r,loading:o,onSelectProject:un,onAddProject:an,onPauseProject:ss,onResumeProject:Pn,onRemoveProject:nn,nodes:u})}):Y.startsWith("plugin:")?t.jsx(rs,{children:t.jsx(y$,{taskView:Y,context:{projectId:g?.id,tasks:h&&G.tasks.length>0?G.tasks:se,workflowSteps:Hn,openTaskDetail:(tt,At)=>V.openDetailTask(tt,At),renderTaskCard:tt=>t.jsx(Mr,{task:tt,projectId:g?.id,onOpenDetail:At=>V.openDetailTask(At),addToast:n,workflowStepNameLookup:ae})}})}):Y==="skills"?!L||!Lt?null:t.jsx(rs,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(U$,{addToast:n,projectId:g?.id,onClose:()=>X("board")})})}):Y==="chat"?t.jsx(rs,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(O$,{addToast:n,projectId:g?.id})})}):Y==="mailbox"?t.jsx(rs,{children:t.jsx(i0,{projectId:g?.id,addToast:n,onUnreadCountChange:Se})}):Y==="roadmaps"?!L||!ze?null:t.jsx(rs,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(F$,{addToast:n,projectId:g?.id})})}):Y==="missions"?t.jsx(rs,{children:t.jsx(e0,{isInline:!0,isOpen:!0,onClose:()=>{kt(void 0),Nt(void 0),$t(void 0),X("board")},addToast:n,projectId:g?.id,onSelectTask:tt=>{const At=se.find(Mn=>Mn.id===tt);At&&V.openDetailTask(At)},availableTasks:se.map(tt=>({id:tt.id,title:tt.title})),resumeSessionId:St,targetMissionId:pt,milestoneSliceResumeSessionId:Ht,onMilestoneSliceResumeFetchError:()=>$t(void 0)})}):Y==="agents"&&ln?t.jsx(rs,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(I$,{addToast:n,projectId:g?.id,onOpenTaskLogs:zn,agentOnboardingEnabled:et})})}):Y==="documents"?t.jsx(rs,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx($$,{projectId:g?.id,addToast:n,onOpenDetail:V.openDetailTask})})}):Y==="insights"?!L||!ge?null:t.jsx(rs,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(D$,{projectId:g?.id,addToast:n,onClose:()=>X("board")})})}):Y==="research"?!L||!Ne?null:t.jsx(rs,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(L$,{projectId:g?.id,addToast:n,onOpenSettings:tt=>V.openSettings(tt),readinessVersion:rt})})}):Y==="memory"?!L||!Be?null:t.jsx(rs,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(B$,{addToast:n,projectId:g?.id})})}):Y==="todos"?!L||!dt?null:t.jsx(rs,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(q$,{addToast:n,projectId:g?.id,onPlanningMode:V.openPlanningWithInitialPlan,onTaskCreated:tt=>Le([tt])})})}):Y==="devserver"||Y==="dev-server"?!L||!Ke?null:t.jsx(rs,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(H$,{addToast:n,projectId:g?.id})})}):Y==="board"?t.jsx(rs,{children:t.jsx(X1,{tasks:h&&G.tasks.length>0?G.tasks:se,projectId:g?.id,maxConcurrent:Dt,onMoveTask:Fe,onPauseTask:Te,onOpenDetail:V.openDetailTask,addToast:n,onQuickCreate:le,onNewTask:V.openNewTask,onPlanningMode:V.openPlanningWithInitialPlan,onSubtaskBreakdown:V.openSubtaskBreakdown,autoMerge:Wt,onToggleAutoMerge:Xt,globalPaused:It,onUpdateTask:$e,onRetryTask:qe,onArchiveTask:oe,onUnarchiveTask:je,onDeleteTask:st,onArchiveAllDone:ie,onLoadArchivedTasks:Ae,searchQuery:P,availableModels:wn,onOpenDetailWithTab:Jt,favoriteProviders:Gn,favoriteModels:Tn,onToggleFavorite:vt,onToggleModelFavorite:rn,taskStuckTimeoutMs:fe,onOpenMission:jt,lastFetchTimeMs:we})}):t.jsx(rs,{children:t.jsx(nS,{tasks:h&&G.tasks.length>0?G.tasks:se,projectId:g?.id,onMoveTask:Fe,onRetryTask:qe,onOpenDetail:V.openDetailTask,addToast:n,globalPaused:It,onNewTask:V.openNewTask,onQuickCreate:le,onPlanningMode:V.openPlanningWithInitialPlan,onSubtaskBreakdown:V.openSubtaskBreakdown,availableModels:wn,favoriteProviders:Gn,favoriteModels:Tn,onToggleFavorite:vt,onToggleModelFavorite:rn,taskStuckTimeoutMs:fe,searchQuery:P,lastFetchTimeMs:we})});if(!Ee)return t.jsxs(t.Fragment,{children:[t.jsx(qI,{stage:Re}),t.jsx(Wg,{toasts:e,onRemove:s})]});const qn=!V.modelOnboardingOpen&&mI(),On=!V.modelOnboardingOpen&&!qn&&Aa()&&!Bg();return t.jsxs(t.Fragment,{children:[t.jsx(SN,{isElectron:i,onOpenSettings:Sn,onOpenGitHubImport:V.openGitHubImport,onOpenPlanning:V.openPlanning,onResumePlanning:V.resumePlanning,activePlanningSessionCount:H.length,onOpenUsage:V.openUsage,onOpenActivityLog:V.openActivityLog,onOpenSystemStats:V.openSystemStats,onOpenMailbox:()=>de("mailbox"),mailboxUnreadCount:re,onOpenSchedules:V.openSchedules,onOpenGitManager:V.openGitManager,onOpenNodes:Me,showNodesButton:Zt,onOpenWorkflowSteps:V.openWorkflowSteps,onOpenScripts:V.openScripts,onRunScript:V.runScript,onToggleTerminal:V.toggleTerminal,onOpenFiles:V.openFiles,filesOpen:V.filesOpen,globalPaused:It,enginePaused:Rt,onToggleGlobalPause:Cn,onToggleEnginePause:pn,view:Y,onChangeView:ve==="project"&&g?de:void 0,showSkillsTab:Lt,showAgentsTab:ln,searchQuery:P,onSearchChange:U,projects:M,currentProject:g,onSelectProject:un,onViewAllProjects:Bn,projectId:g?.id,mobileNavEnabled:Ie,availableNodes:u,currentNode:d,onSelectNode:tt=>{tt===null?p():f(tt)},isRemote:h,experimentalFeatures:{insights:ge,roadmap:ze,memoryView:Be,devServer:Ke,devServerView:Ke,todoView:dt,researchView:Ne},pluginDashboardViews:he}),ve==="project"&&g&&!ne&&Y!=="missions"&&!V.isPlanningOpen&&!be&&t.jsx(a4,{sessions:ue,onResumeSession:fn,onDismissSession:mn,onDismissAll:en}),ve==="project"&&g&&t.jsx(l4,{onOpenSettings:()=>V.openSettings("general")}),ve==="project"&&g&&qn&&t.jsx(d4,{onResume:V.openModelOnboarding}),ve==="project"&&g&&On&&t.jsx(u4,{onOpenModelOnboarding:V.openModelOnboarding,onOpenSettings:tt=>V.openSettings(tt)}),ve==="project"&&g&&w&&R&&S&&!O&&t.jsx(c4,{latestVersion:R,currentVersion:S,onDismiss:_}),ve==="project"&&g&&!E&&C&&!Ft&&t.jsx(Ug,{hasAiProvider:y,hasGithub:j,onDismiss:Pt}),t.jsx("div",{className:`project-content${ve==="project"&&g?" project-content--with-footer":""}${Ie&&!ee?" project-content--with-mobile-nav":""}`,children:xn()}),ve==="project"&&g&&!ne&&t.jsx(e4,{tasks:h&&G.tasks.length>0?G.tasks:se,projectId:g.id,taskStuckTimeoutMs:fe,backgroundSessions:z,backgroundGenerating:I,backgroundNeedsInput:k,onOpenBackgroundSession:fn,onDismissBackgroundSession:Q,lastFetchTimeMs:we,currentProjectPath:g.path,onOpenProjectDirectory:it}),t.jsx(h4,{view:Y,onChangeView:ve==="project"&&g?de:()=>{},footerVisible:ve==="project"&&!!g,modalOpen:V.anyModalOpen,keyboardOpen:ee,onOpenSettings:Sn,onOpenActivityLog:V.openActivityLog,onOpenSystemStats:V.openSystemStats,onOpenMailbox:()=>de("mailbox"),mailboxUnreadCount:re,onOpenGitManager:V.openGitManager,onOpenWorkflowSteps:V.openWorkflowSteps,onOpenSchedules:V.openSchedules,onOpenScripts:V.openScripts,onToggleTerminal:V.toggleTerminal,onOpenFiles:V.openFiles,onOpenGitHubImport:V.openGitHubImport,onOpenPlanning:V.openPlanning,onResumePlanning:V.resumePlanning,activePlanningSessionCount:H.length,onOpenUsage:()=>V.openUsage(null),onViewAllProjects:Bn,onRunScript:V.runScript,projectId:g?.id,showSkillsTab:Lt,experimentalFeatures:{insights:ge,roadmap:ze,memoryView:Be,devServer:Ke,devServerView:Ke,todoView:dt,researchView:Ne},pluginDashboardViews:he}),ve==="project"&&g&&Y!=="chat"&&Y!=="mailbox"&&Y!=="insights"&&Y!=="devserver"&&Y!=="dev-server"&&!Y.startsWith("plugin:")&&t.jsx(O4,{projectId:g.id,addToast:n,showFAB:Oe,open:Tt,onOpenChange:Mt,favoriteProviders:Gn,favoriteModels:Tn,onToggleFavorite:vt,onToggleModelFavorite:rn}),t.jsx(UI,{projectId:g?.id,tasks:se,projects:r,currentProject:g,addToast:n,toasts:e,removeToast:s,modalManager:V,projectActions:{handleAddProject:an,handleSetupComplete:Dn,handleModelOnboardingComplete:Ln},taskHandlers:{handleModalCreate:ye,handlePlanningTaskCreated:Ye,handlePlanningTasksCreated:mt,handleSubtaskTasksCreated:ht,handleGitHubImport:Kt},taskOperations:{moveTask:Fe,deleteTask:st,mergeTask:nt,retryTask:qe,resetTask:Xe,duplicateTask:Ue},deepLink:{handleDetailClose:A},settings:{prAuthAvailable:ut,themeMode:T,colorTheme:D,dashboardFontScalePct:K,setThemeMode:J,setColorTheme:te,setDashboardFontScalePct:N},onSettingsClose:()=>{V.closeSettings(),xe(tt=>tt+1),Kn()},onReopenOnboarding:()=>{V.closeSettings(),V.openModelOnboarding()}}),t.jsx(T$,{open:Ot})]})}function K$(){return t.jsx(X4,{children:t.jsx(A$,{children:t.jsx(ON,{children:t.jsx(W$,{})})})})}function ob(e){e.postMessage({type:"SKIP_WAITING"})}function xp(e){e.addEventListener("statechange",()=>{e.state==="installed"&&navigator.serviceWorker.controller&&ob(e)})}function G$(){if(!("serviceWorker"in navigator))return;let e=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{e||(e=!0,vd("service worker activated new version"))}),navigator.serviceWorker.register("/sw.js").then(n=>{console.log("SW registered:",n.scope),n.waiting&&navigator.serviceWorker.controller&&ob(n.waiting),n.installing&&xp(n.installing),n.addEventListener("updatefound",()=>{const s=n.installing;s&&xp(s)})}).catch(n=>{console.log("SW registration failed:",n)})}fy();ey();lb.createRoot(document.getElementById("root")).render(t.jsx(a.StrictMode,{children:t.jsx(ty,{children:t.jsx(K$,{})})}));G$();export{BP as $,Ds as A,En as B,Nn as C,DN as D,wL as E,Hi as F,nl as G,Lc as H,Ks as I,dn as J,Lo as K,lt as L,J3 as M,gn as N,Sc as O,Rn as P,_n as Q,Fn as R,Ni as S,rl as T,Vs as U,cn as V,Yt as W,qt as X,JP as Y,es as Z,Mj as _,fs as a,Cs as a$,HP as a0,Aj as a1,xL as a2,Rj as a3,hn as a4,PD as a5,ID as a6,Lw as a7,bd as a8,Ta as a9,Q3 as aA,X3 as aB,ez as aC,Nr as aD,Av as aE,br as aF,ex as aG,hs as aH,Ap as aI,ml as aJ,G4 as aK,Nu as aL,Su as aM,Ar as aN,tN as aO,_3 as aP,M3 as aQ,nN as aR,sN as aS,y4 as aT,$a as aU,Qg as aV,N3 as aW,el as aX,_p as aY,p4 as aZ,x4 as a_,Ra as aa,li as ab,ci as ac,bi as ad,A3 as ae,P3 as af,T3 as ag,R3 as ah,I3 as ai,cs as aj,gs as ak,Uv as al,ri as am,ax as an,Ir as ao,Ei as ap,$3 as aq,L3 as ar,B3 as as,U3 as at,F3 as au,O3 as av,z3 as aw,D3 as ax,Er as ay,Z3 as az,EL as b,ZL as b$,Oi as b0,Sp as b1,tu as b2,Si as b3,$L as b4,LL as b5,DL as b6,zL as b7,OL as b8,FL as b9,vD as bA,gD as bB,fD as bC,dD as bD,wD as bE,AT as bF,eL as bG,ZD as bH,rL as bI,XD as bJ,tL as bK,nL as bL,sL as bM,iL as bN,rj as bO,aL as bP,wd as bQ,sj as bR,ij as bS,aj as bT,nj as bU,QD as bV,Or as bW,al as bX,_v as bY,kr as bZ,wv as b_,UL as ba,BL as bb,HL as bc,qL as bd,VL as be,WL as bf,KL as bg,GL as bh,YL as bi,QL as bj,JL as bk,Jn as bl,xd as bm,Bi as bn,C3 as bo,S3 as bp,E3 as bq,hD as br,mD as bs,uD as bt,pD as bu,kD as bv,ND as bw,yD as bx,bD as by,xD as bz,Je as c,ts as c$,e3 as c0,t3 as c1,n3 as c2,s3 as c3,i3 as c4,a3 as c5,XL as c6,Ip as c7,wa as c8,Lj as c9,SD as cA,PL as cB,Q$ as cC,X$ as cD,Yh as cE,_L as cF,Z$ as cG,tD as cH,cD as cI,lD as cJ,dw as cK,ew as cL,oi as cM,nw as cN,tw as cO,sw as cP,iw as cQ,_D as cR,ML as cS,AL as cT,RL as cU,Mi as cV,q3 as cW,V3 as cX,IL as cY,nD as cZ,Pc as c_,oy as ca,ly as cb,Wy as cc,Ky as cd,y3 as ce,DD as cf,$D as cg,w3 as ch,LD as ci,VD as cj,BD as ck,zD as cl,HD as cm,OD as cn,qD as co,FD as cp,UD as cq,Sb as cr,Qy as cs,WD as ct,Xy as cu,KD as cv,RR as cw,di as cx,H4 as cy,gT as cz,SL as d,CD as d$,_T as d0,QP as d1,ZP as d2,Cc as d3,dl as d4,iD as d5,eD as d6,aD as d7,sD as d8,rD as d9,kL as dA,jL as dB,Np as dC,hL as dD,mL as dE,UP as dF,vL as dG,Lr as dH,PA as dI,dL as dJ,cL as dK,zw as dL,uL as dM,pL as dN,p3 as dO,lL as dP,f3 as dQ,vv as dR,Oc as dS,j3 as dT,x3 as dU,b3 as dV,v3 as dW,g3 as dX,TL as dY,H3 as dZ,MD as d_,oD as da,Wi as db,Y3 as dc,TN as dd,ul as de,W3 as df,xh as dg,K3 as dh,G3 as di,jD as dj,r3 as dk,l3 as dl,u3 as dm,c3 as dn,o3 as dp,d3 as dq,m3 as dr,Vc as ds,ru as dt,fL as du,bL as dv,$x as dw,h3 as dx,yL as dy,gL as dz,CL as e,ED as e0,RD as e1,TD as e2,AD as e3,Sr as f,Yn as g,bs as h,Ia as i,k3 as j,ns as k,_j as l,oL as m,Ls as n,YD as o,GD as p,JD as q,qP as r,Js as s,NL as t,bn as u,b4 as v,Gs as w,ll as x,so as y,ke as z};
|