@runfusion/fusion 0.4.1 → 1.0.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 +34074 -34923
- package/dist/client/assets/{AgentDetailView-sy6Hg1Xr.js → AgentDetailView-dhJd4os0.js} +6 -11
- package/dist/client/assets/{AgentsView-DpEpW88a.js → AgentsView-CYVTv2_l.js} +3 -3
- package/dist/client/assets/{ChatView-BUt3C4cf.js → ChatView-ByPhfQZ6.js} +1 -1
- package/dist/client/assets/{DevServerView-BOyWtQJM.js → DevServerView-CD7mgC11.js} +1 -1
- package/dist/client/assets/{DirectoryPicker-BJyEEso5.js → DirectoryPicker-Cm0FCC9M.js} +1 -1
- package/dist/client/assets/{DocumentsView-Dx0M1YHw.js → DocumentsView-oB319uCj.js} +1 -1
- package/dist/client/assets/{InsightsView-BtXdAo7D.js → InsightsView-BHdMNnOa.js} +1 -1
- package/dist/client/assets/{MemoryView-kKPuqmwf.js → MemoryView-BDJMlzlM.js} +1 -1
- package/dist/client/assets/{NodesView-B_ZwUORz.js → NodesView-BfOlOj-Q.js} +1 -1
- package/dist/client/assets/{PiExtensionsManager-Db0EGr0Q.js → PiExtensionsManager-D-IznnkU.js} +2 -2
- package/dist/client/assets/{PluginManager-mOwWndfg.js → PluginManager-D40uAE-p.js} +1 -1
- package/dist/client/assets/{RoadmapsView-DbUzBLeF.js → RoadmapsView-DtgL8yl3.js} +1 -1
- package/dist/client/assets/{SettingsModal-TRJu_mTn.js → SettingsModal-0IyoaKEv.js} +1 -1
- package/dist/client/assets/SettingsModal-D1vZdAS4.js +31 -0
- package/dist/client/assets/{SetupWizardModal-D1bmCQrf.js → SetupWizardModal-BaQ8VkZm.js} +1 -1
- package/dist/client/assets/{SkillsView-Dzzpd5Md.js → SkillsView-DAvaRl37.js} +1 -1
- package/dist/client/assets/TodoView-BXRQSmSw.js +1 -0
- package/dist/client/assets/TodoView-DNi8blBB.css +1 -0
- package/dist/client/assets/{folder-open-BcuByk6U.js → folder-open-BJ4SvamV.js} +1 -1
- package/dist/client/assets/index-B7TDbn3p.css +1 -0
- package/dist/client/assets/index-CGW6tOaX.js +631 -0
- package/dist/client/assets/list-checks-CpGwz9gV.js +6 -0
- package/dist/client/assets/{upload-BzNbXYEj.js → upload-DJYyvab0.js} +1 -1
- package/dist/client/assets/{users-BvIqhSXp.js → users-ndAFpylb.js} +1 -1
- package/dist/client/index.html +2 -2
- package/dist/client/version.json +1 -1
- package/dist/extension.js +3262 -599
- package/dist/pi-claude-cli/package.json +1 -1
- package/dist/pi-claude-cli/src/__tests__/process-manager.test.ts +50 -17
- package/dist/pi-claude-cli/src/__tests__/setup-test-isolation.test.ts +30 -0
- package/dist/pi-claude-cli/src/__tests__/setup-test-isolation.ts +6 -0
- package/package.json +5 -5
- package/skill/fusion/references/extension-tools.md +5 -5
- package/skill/fusion/references/fusion-capabilities.md +5 -5
- package/dist/client/assets/SettingsModal-Bs_lNs5B.js +0 -31
- package/dist/client/assets/index-BipedNj4.css +0 -1
- package/dist/client/assets/index-k2c4LrUr.js +0 -616
|
@@ -1,616 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-xterm-DzcZoU0P.js","assets/vendor-react-K0fH_qHe.js","assets/vendor-xterm-LZoznX6r.css","assets/addon-fit-C7jRorKK.js","assets/addon-web-links-CkJwd4cQ.js","assets/addon-webgl-BjvOw43o.js","assets/SetupWizardModal-D1bmCQrf.js","assets/DirectoryPicker-BJyEEso5.js","assets/folder-open-BcuByk6U.js","assets/DirectoryPicker-DzKVmxOf.css","assets/SetupWizardModal-BMa6p24b.css","assets/SettingsModal-Bs_lNs5B.js","assets/SettingsModal-TRJu_mTn.js","assets/SettingsModal-G0ESQXRD.css","assets/users-BvIqhSXp.js","assets/SettingsModal-CDWvhvrd.css","assets/AgentsView-DpEpW88a.js","assets/upload-BzNbXYEj.js","assets/AgentsView-DETxUmHS.css","assets/DocumentsView-Dx0M1YHw.js","assets/DocumentsView-DV2DrCZb.css","assets/InsightsView-BtXdAo7D.js","assets/InsightsView-Egu71gmh.css","assets/NodesView-B_ZwUORz.js","assets/NodesView-BYVG2yY-.css","assets/ChatView-BUt3C4cf.js","assets/RoadmapsView-DbUzBLeF.js","assets/RoadmapsView-BOYnyMCh.css","assets/SkillsView-Dzzpd5Md.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-kKPuqmwf.js","assets/MemoryView-DiajLXby.css","assets/DevServerView-BOyWtQJM.js","assets/DevServerView-ZeBGQkLI.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as a,j as t,a as Ta,g as Km,R as Jm,c as Sf}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 Ym=(...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 Cf=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 Ef=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 Wc=e=>{const n=Ef(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 _o={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 Mf=e=>{for(const n in e)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},_f=a.createContext({}),Af=()=>a.useContext(_f),Tf=a.forwardRef(({color:e,size:n,strokeWidth:s,absoluteStrokeWidth:i,className:r="",children:o,iconNode:l,...c},u)=>{const{size:d=24,strokeWidth:m=2,absoluteStrokeWidth:h=!1,color:g="currentColor",className:p=""}=Af()??{},f=i??h?Number(s??m)*24/Number(n??d):s??m;return a.createElement("svg",{ref:u,..._o,width:n??d??_o.width,height:n??d??_o.height,stroke:e??g,strokeWidth:f,className:Ym("lucide",p,r),...!o&&!Mf(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 Ve=(e,n)=>{const s=a.forwardRef(({className:i,...r},o)=>a.createElement(Tf,{ref:o,iconNode:n,className:Ym(`lucide-${Cf(Wc(e))}`,`lucide-${e}`,i),...r}));return s.displayName=Wc(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 Rf=[["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"}]],Ss=Ve("activity",Rf);/**
|
|
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 If=[["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"}]],Zr=Ve("archive",If);/**
|
|
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 Pf=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],Wa=Ve("arrow-down",Pf);/**
|
|
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 $f=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],ia=Ve("arrow-left",$f);/**
|
|
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 Df=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],Ga=Ve("arrow-right",Df);/**
|
|
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 Lf=[["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"}]],Qm=Ve("arrow-up-down",Lf);/**
|
|
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 zf=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],yi=Ve("arrow-up",zf);/**
|
|
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 Ff=[["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"}]],Of=Ve("book-open",Ff);/**
|
|
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 Uf=[["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"}]],an=Ve("bot",Uf);/**
|
|
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 Bf=[["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"}]],Ml=Ve("box",Bf);/**
|
|
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 Hf=[["path",{d:"M12 18V5",key:"adv99a"}],["path",{d:"M15 13a4.17 4.17 0 0 1-3-4 4.17 4.17 0 0 1-3 4",key:"1e3is1"}],["path",{d:"M17.598 6.5A3 3 0 1 0 12 5a3 3 0 1 0-5.598 1.5",key:"1gqd8o"}],["path",{d:"M17.997 5.125a4 4 0 0 1 2.526 5.77",key:"iwvgf7"}],["path",{d:"M18 18a4 4 0 0 0 2-7.464",key:"efp6ie"}],["path",{d:"M19.967 17.483A4 4 0 1 1 12 18a4 4 0 1 1-7.967-.517",key:"1gq6am"}],["path",{d:"M6 18a4 4 0 0 1-2-7.464",key:"k1g0md"}],["path",{d:"M6.003 5.125a4 4 0 0 0-2.526 5.77",key:"q97ue3"}]],Pr=Ve("brain",Hf);/**
|
|
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 qf=[["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"}]],Xm=Ve("calendar",qf);/**
|
|
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 Vf=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],Wf=Ve("check-check",Vf);/**
|
|
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 Gf=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],xn=Ve("check",Gf);/**
|
|
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 Kf=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],zt=Ve("chevron-down",Kf);/**
|
|
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 Jf=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],rc=Ve("chevron-left",Jf);/**
|
|
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 Yf=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],en=Ve("chevron-right",Yf);/**
|
|
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 Qf=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],Ys=Ve("chevron-up",Qf);/**
|
|
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 Xf=[["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"}]],ss=Ve("circle-alert",Xf);/**
|
|
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 Zf=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],tn=Ve("circle-check-big",Zf);/**
|
|
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 eg=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],eo=Ve("circle-dot",eg);/**
|
|
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 tg=[["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"}]],Gc=Ve("circle-question-mark",tg);/**
|
|
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 ng=[["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"}]],Ka=Ve("circle-x",ng);/**
|
|
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 sg=[["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"}]],ig=Ve("clipboard-list",sg);/**
|
|
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 ag=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],ji=Ve("clock",ag);/**
|
|
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 rg=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Zm=Ve("code",rg);/**
|
|
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 og=[["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"}]],lg=Ve("columns-3",og);/**
|
|
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 cg=[["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"}]],wi=Ve("copy",cg);/**
|
|
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 dg=[["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"}]],ug=Ve("cpu",dg);/**
|
|
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 mg=[["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"}]],hg=Ve("download",mg);/**
|
|
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 pg=[["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"}]],fg=Ve("ellipsis-vertical",pg);/**
|
|
193
|
-
* @license lucide-react v1.7.0 - ISC
|
|
194
|
-
*
|
|
195
|
-
* This source code is licensed under the ISC license.
|
|
196
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
197
|
-
*/const gg=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],_l=Ve("ellipsis",gg);/**
|
|
198
|
-
* @license lucide-react v1.7.0 - ISC
|
|
199
|
-
*
|
|
200
|
-
* This source code is licensed under the ISC license.
|
|
201
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
202
|
-
*/const bg=[["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"}]],xg=Ve("external-link",bg);/**
|
|
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 vg=[["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"}]],$r=Ve("eye-off",vg);/**
|
|
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 yg=[["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"}]],Vi=Ve("eye",yg);/**
|
|
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 kg=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}]],Ts=Ve("file-code",kg);/**
|
|
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 jg=[["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"}]],eh=Ve("file-diff",jg);/**
|
|
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 wg=[["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"}]],Ng=Ve("file-minus",wg);/**
|
|
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 Sg=[["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"}]],th=Ve("file-pen",Sg);/**
|
|
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 Cg=[["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"}]],Eg=Ve("file-plus",Cg);/**
|
|
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 Mg=[["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"}]],_g=Ve("file-question-mark",Mg);/**
|
|
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 Ag=[["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"}]],Ni=Ve("file-text",Ag);/**
|
|
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 Tg=[["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"}]],Rg=Ve("file-type",Tg);/**
|
|
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 Ig=[["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"}]],nh=Ve("file",Ig);/**
|
|
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 Pg=[["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"}]],Al=Ve("folder-git-2",Pg);/**
|
|
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 $g=[["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"}]],Kc=Ve("folder-root",$g);/**
|
|
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 Dg=[["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"}]],jn=Ve("folder",Dg);/**
|
|
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 Lg=[["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"}]],Dr=Ve("funnel",Lg);/**
|
|
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 zg=[["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"}]],Os=Ve("git-branch",zg);/**
|
|
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 Fg=[["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"}]],za=Ve("git-commit-horizontal",Fg);/**
|
|
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 Og=[["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"}]],sh=Ve("git-merge",Og);/**
|
|
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 Ug=[["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=Ve("git-pull-request",Ug);/**
|
|
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 Bg=[["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"}]],to=Ve("globe",Bg);/**
|
|
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 Hg=[["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"}]],ih=Ve("grid-3x3",Hg);/**
|
|
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 qg=[["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"}]],oc=Ve("grip-vertical",qg);/**
|
|
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 Vg=[["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"}]],Wg=Ve("hard-drive",Vg);/**
|
|
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 Gg=[["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"}]],Kg=Ve("heart",Gg);/**
|
|
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 Jg=[["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"}]],Fa=Ve("history",Jg);/**
|
|
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 Yg=[["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"}]],Ra=Ve("inbox",Yg);/**
|
|
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 Qg=[["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"}]],ah=Ve("key",Qg);/**
|
|
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 Xg=[["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"}]],Si=Ve("layers",Xg);/**
|
|
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 Zg=[["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"}]],Ci=Ve("layout-grid",Zg);/**
|
|
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 eb=[["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"}]],Us=Ve("lightbulb",eb);/**
|
|
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 tb=[["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"}]],Wi=Ve("link",tb);/**
|
|
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 nb=[["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"}]],sb=Ve("list-plus",nb);/**
|
|
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 ib=[["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"}]],no=Ve("list-tree",ib);/**
|
|
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 ab=[["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"}]],Tl=Ve("list",ab);/**
|
|
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 rb=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],it=Ve("loader-circle",rb);/**
|
|
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 ob=[["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"}]],so=Ve("lock",ob);/**
|
|
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 lb=[["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"}]],Gi=Ve("mail",lb);/**
|
|
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 cb=[["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"}]],Rl=Ve("map",cb);/**
|
|
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 db=[["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"}]],io=Ve("maximize-2",db);/**
|
|
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 ub=[["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"}]],li=Ve("message-square",ub);/**
|
|
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 mb=[["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"}]],aa=Ve("minimize-2",mb);/**
|
|
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 hb=[["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"}]],rh=Ve("monitor",hb);/**
|
|
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 pb=[["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"}]],fb=Ve("move",pb);/**
|
|
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 gb=[["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"}]],Il=Ve("package",gb);/**
|
|
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 bb=[["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"}]],xb=Ve("paperclip",bb);/**
|
|
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 vb=[["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"}]],Fs=Ve("pause",vb);/**
|
|
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 yb=[["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"}]],Hn=Ve("pencil",yb);/**
|
|
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 kb=[["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"}]],rn=Ve("play",kb);/**
|
|
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 jb=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Vt=Ve("plus",jb);/**
|
|
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 wb=[["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"}]],oh=Ve("radio",wb);/**
|
|
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 Nb=[["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"}]],hn=Ve("refresh-cw",Nb);/**
|
|
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 Sb=[["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"}]],Jc=Ve("rocket",Sb);/**
|
|
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 Cb=[["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"}]],Eb=Ve("rotate-ccw",Cb);/**
|
|
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 Mb=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],lh=Ve("save",Mb);/**
|
|
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 _b=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Bi=Ve("search",_b);/**
|
|
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 Ab=[["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"}]],vi=Ve("send",Ab);/**
|
|
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 Tb=[["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"}]],Lr=Ve("server",Tb);/**
|
|
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 Rb=[["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"}]],Oa=Ve("settings",Rb);/**
|
|
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 Ib=[["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"}]],Pb=Ve("shield",Ib);/**
|
|
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 $b=[["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"}]],Dn=Ve("sparkles",$b);/**
|
|
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 Db=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],ls=Ve("square",Db);/**
|
|
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 Lb=[["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"}]],ns=Ve("target",Lb);/**
|
|
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 zb=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],Bs=Ve("terminal",zb);/**
|
|
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 Fb=[["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"}]],zr=Ve("text-wrap",Fb);/**
|
|
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 Ob=[["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"}]],Ht=Ve("trash-2",Ob);/**
|
|
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 Ub=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],Bb=Ve("trending-up",Ub);/**
|
|
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 Hb=[["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"}]],lc=Ve("triangle-alert",Hb);/**
|
|
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 qb=[["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"}]],Yc=Ve("unlink",qb);/**
|
|
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 Vb=[["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"}]],Pi=Ve("user",Vb);/**
|
|
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 Wb=[["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"}]],ch=Ve("webhook",Wb);/**
|
|
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 Gb=[["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"}]],Pl=Ve("workflow",Gb);/**
|
|
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 Kb=[["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"}]],Jb=Ve("wrench",Kb);/**
|
|
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 Yb=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Pt=Ve("x",Yb);/**
|
|
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 Qb=[["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"}]],vn=Ve("zap",Qb),$l="fusion:version-reload";function dh(e){if(sessionStorage.getItem($l)){console.warn("[versionCheck] reload already attempted, suppressing",e);return}sessionStorage.setItem($l,"1"),console.info("[versionCheck] reloading:",e),window.location.reload()}function Xb(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 Zb(e){return Xb(e)?(dh(`chunk load error: ${e?.message??e}`),!0):!1}async function ex(){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 Ao=!1;async function To(){if(!(Ao||document.visibilityState!=="visible")){Ao=!0;try{const e=await ex();e&&e!=="mog5pn44-24e04f4a"&&dh(`build version changed: mog5pn44-24e04f4a -> ${e}`)}finally{Ao=!1}}}function tx(){window.setTimeout(()=>sessionStorage.removeItem($l),5e3),document.addEventListener("visibilitychange",()=>{To()}),window.addEventListener("focus",()=>{To()}),window.setTimeout(()=>void To(),2e3)}class ao 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),!Zb(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(lc,{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 Xn({children:e,onError:n}){return t.jsx(ao,{level:"page",onError:n,children:e})}function fi({children:e,onError:n}){return t.jsx(ao,{level:"modal",onError:n,children:e})}function nx({children:e,onError:n}){return t.jsx(ao,{level:"root",onError:n,children:e})}const sx="modulepreload",ix=function(e){return"/"+e},Qc={},Zt=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=ix(d),d in Qc)return;Qc[d]=!0;const m=d.endsWith(".css"),h=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${h}`))return;const g=document.createElement("link");if(g.rel=m?"stylesheet":sx,m||(g.as="script"),g.crossOrigin="",g.href=d,u&&g.setAttribute("nonce",u),document.head.appendChild(g),m)return new Promise((p,f)=>{g.addEventListener("load",p),g.addEventListener("error",()=>f(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return r.then(l=>{for(const c of l||[])c.status==="rejected"&&o(c.reason);return n().catch(o)})},cc="fn.authToken",Xc="token",ax="fn_token";let Hi,Zc=!1,Fr=!1;const Dl="fn:auth-token-recovery-required";function rx(){try{const e=window.localStorage.getItem(cc);return e&&e.length>0?e:void 0}catch{return}}function uh(e){try{window.localStorage.setItem(cc,e)}catch{}}function ox(){if(!(Zc||typeof window>"u")){Zc=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(Xc);if(!n)return;uh(n),e.searchParams.delete(Xc);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function Ki(){if(Hi!==void 0)return Hi;const e=ox();if(e)return Hi=e,e;const n=rx();if(n)return Hi=n,n}function lx(e){Hi=e,Fr=!1,uh(e)}function cx(){Hi=void 0,Fr=!1;try{window.localStorage.removeItem(cc)}catch{}}function ed(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function dx(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function ux(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!dx(e.protocol))return!1;const s=e.hostname===n.hostname,i=e.port===n.port,r=ed(e.protocol)===ed(n.protocol);return s&&i&&r}function mx(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 Hs(e){const n=Ki();if(!n||typeof window>"u")return e;const s=mx(e);return!s||!ux(s.parsed)?e:(s.parsed.searchParams.set(ax,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function di(e){const n=Ki();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function hx(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function px(){typeof window>"u"||Fr||(Fr=!0,window.dispatchEvent(new CustomEvent(Dl)))}async function fx(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();hx(i)&&px()}catch{}}function gx(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,Ki();const e=window.fetch.bind(window);window.fetch=function(s,i){const r=Ki(),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=>(fx(u),u))}}class bx extends Error{status;details;constructor(n,s,i){super(n),this.name="ApiRequestError",this.status=s,this.details=i}}function xx(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function Vn(e){return`/api${e}`}async function D(e,n={}){const s=Vn(e),i=Ki(),r=(()=>{if(i){const g=new Headers(n.headers??{});return g.has("Content-Type")||g.set("Content-Type","application/json"),di(g)}if(!n.headers)return{"Content-Type":"application/json"};const h=new Headers(n.headers);return h.has("Content-Type")||h.set("Content-Type","application/json"),Object.fromEntries(h.entries())})(),o=await fetch(s,{...n,headers:r});if(o.status===204){if(!o.ok)throw new Error(`Request failed for ${s}: ${o.status} ${o.statusText}`);return}const l=o.headers.get("content-type")??"",c=await o.text(),u=l.includes("application/json");if(l.includes("text/html")||xx(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 bx(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return m}function YR(){return D("/health")}function vx(e,n,s,i,r){const o=new URLSearchParams;s&&o.set("projectId",s),i&&o.set("q",i),r&&o.set("includeArchived","1");const l=o.size>0?`?${o.toString()}`:"";return D(`/tasks${l}`)}async function Or(e,n){const i=Vn(V(`/tasks/${e}`,n));for(let r=1;r<=2;r++){const o=await fetch(i,{headers:di({"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 mh(e,n){const{title:s,description:i,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:u,modelPresetId:d,modelProvider:m,modelId:h,validatorModelProvider:g,validatorModelId:p,planningModelProvider:f,planningModelId:b,thinkingLevel:v,summarize:x,reviewLevel:k,executionMode:M,priority:y}=e;return D(V("/tasks",n),{method:"POST",body:JSON.stringify({title:s,description:i,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:u,modelPresetId:d,modelProvider:m,modelId:h,validatorModelProvider:g,validatorModelId:p,planningModelProvider:f,planningModelId:b,thinkingLevel:v,summarize:x,reviewLevel:k,executionMode:M,priority:y})})}function Ks(e,n,s){return D(V(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function yx(e,n,s,i,r,o,l,c){return D(V("/tasks/batch-update-models",c),{method:"POST",body:JSON.stringify({taskIds:e,modelProvider:n,modelId:s,validatorModelProvider:i,validatorModelId:r,planningModelProvider:o,planningModelId:l})})}function kx(e,n,s){return D(V(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n})})}function jx(e,n,s){const i=new URLSearchParams,r=i.size>0?`?${i.toString()}`:"";return D(V(`/tasks/${e}${r}`,n),{method:"DELETE"})}function wx(e,n){return D(V(`/tasks/${e}/merge`,n),{method:"POST"})}function Nx(e,n){return D(V(`/tasks/${e}/retry`,n),{method:"POST"})}function Sx(e,n){return D(V(`/tasks/${e}/duplicate`,n),{method:"POST"})}function hh(e,n){return D(V(`/tasks/${e}/pause`,n),{method:"POST"})}function Cx(e,n){return D(V(`/tasks/${e}/unpause`,n),{method:"POST"})}function Ex(e,n){return D(V(`/tasks/${e}/archive`,n),{method:"POST"})}function Mx(e,n){return D(V(`/tasks/${e}/unarchive`,n),{method:"POST"})}function _x(e){return D(V("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function Ax(e,n){return D(V(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function Tx(e,n){return D(V(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function Rx(e){return D(V("/config",e))}function ro(e){return D(V("/settings",e))}function dr(e,n){return D(V("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function QR(e){return D(V("/remote/settings",e))}function XR(e,n){return D(V("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function ZR(e){return D(V("/remote/status",e))}function e4(e,n){return D(V("/remote/provider/activate",n),{method:"POST",body:JSON.stringify({provider:e})})}function t4(e){return D(V("/remote/tunnel/start",e),{method:"POST"})}function n4(e){return D(V("/remote/tunnel/stop",e),{method:"POST"})}function s4(e){return D(V("/remote/token/persistent/regenerate",e),{method:"POST"})}function i4(e,n){return D(V("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function ph(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 a4(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:i}=e,r=ph(null,s,i);return D(V(`/remote/url${r}`,n))}function r4(e="text",n={}){const{projectId:s,tokenType:i="persistent",ttlMs:r}=n,o=ph(e,i,r);return D(V(`/remote/qr${o}`,s))}function o4(e){return D(V("/memory",e))}function l4(e,n){return D(V("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function c4(e){return D(V("/memory/files",e))}function d4(e,n){const s=`path=${encodeURIComponent(e)}`;return D(V(`/memory/file?${s}`,n))}function u4(e,n,s){return D(V("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function m4(e,n){let s,i=n;if(n!==void 0)s=e;else if(typeof e=="string"&&e.trim().length>0){const r=e.trim();r.includes("/")||r.endsWith(".md")||r.startsWith(".")?s=r:i=r}return D(V("/memory/compact",i),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function h4(e){return D(V("/memory/insights",e))}function p4(e,n){return D(V("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function f4(e){return D(V("/memory/extract",e),{method:"POST"})}function g4(e){return D(V("/memory/audit",e))}function b4(e){return D(V("/memory/stats",e))}function x4(e){return D(V("/memory/backend",e))}function v4(e){return D(V("/memory/install-qmd",e),{method:"POST"})}function y4(e,n){return D(V("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function ra(){return D("/settings/global")}function nn(e){return D("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function k4(e){return D(V("/settings/scopes",e))}function j4(e){return D(V("/settings/pi-extensions",e))}function w4(e,n){return D(V("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function N4(e,n){return D(V("/settings/test-ntfy",n),{method:"POST",body:e?JSON.stringify(e):void 0})}function S4(){return D("/pi-settings")}async function C4(e){return D("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function E4(e){return D("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function M4(e){return D(V("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function Ua(e,n,s){const i=new FormData;i.append("file",n);const r=await fetch(Vn(V(`/tasks/${e}/attachments`,s)),{method:"POST",headers:di(),body:i}),o=await r.json();if(!r.ok)throw new Error(o.error||"Upload failed");return o}async function Ix(e,n,s){return D(V(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function td(e,n,s){const i=new URLSearchParams;s?.limit!==void 0&&i.set("limit",String(s.limit)),s?.offset!==void 0&&i.set("offset",String(s.offset));const r=i.toString()?`?${i.toString()}`:"",o=V(`/tasks/${e}/logs${r}`,n),l=await fetch(Vn(o),{headers:di()});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 Px(e,n,s,i){return D(V(`/tasks/${e}/comments/${n}`,i),{method:"PATCH",body:JSON.stringify({text:s})})}function $x(e,n,s){return D(V(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function Dx(e,n){return D(V(`/tasks/${e}/documents`,n))}function Lx(e,n,s){return D(V(`/tasks/${e}/documents/${n}/revisions`,s))}async function _4(e,n){const s=new URLSearchParams;e?.q&&s.set("q",e.q),e?.limit!==void 0&&s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset));const i=s.toString(),r=`/documents${i?`?${i}`:""}`;return D(V(r,n))}function A4(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const i=s.toString(),r=`/files/markdown-list${i?`?${i}`:""}`;return D(V(r,e))}function nd(e,n,s,i,r){return D(V(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:i?.author,metadata:i?.metadata})})}function zx(e,n,s){return D(V(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function Fx(e,n,s){return D(V(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function Ox(e,n,s){return D(V(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Ux(e,n){return D(V(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function Bx(e,n,s){return D(V(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function is(){return D("/models")}function Hx(){return D("/usage")}function qx(){return D("/providers/claude-cli/status")}function Vx(e){return D("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function Ba(){return D("/auth/status")}function Wx(e){return D("/auth/login",{method:"POST",body:JSON.stringify({provider:e})})}function Gx(e){return D("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function Kx(e,n){return D("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function Jx(e){return D("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function Yx(e,n,s,i){return D("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:i})})}function Qx(e,n,s,i){return D(V("/github/issues/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function Xx(e,n,s){return D("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function Zx(e,n,s,i){return D(V("/github/pulls/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function ev(e){return D(V("/git/remotes",e))}function tv(e){return D(V("/git/remotes/detailed",e))}function nv(e,n,s){return D(V("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function sv(e,n){return D(V(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function iv(e,n,s){return D(V(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function av(e,n,s){return D(V(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function rv(e,n,s){return D(V(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function ov(e,n){return D(V(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}async function lv(e,n){return(await D(V("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:e})})).results}function ur(e,n,s,i){return D(V("/terminal/sessions",i),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function sd(e,n){return D(V(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function cv(e){return D(V("/terminal/sessions",e))}function As(e){return D(V("/git/status",e))}function dv(e,n){const s=e?`?limit=${e}`:"";return D(V(`/git/commits${s}`,n))}function Ur(e,n){return D(V(`/git/commits/${e}/diff`,n))}function uv(e){return D(V("/git/commits/ahead",e))}function mv(e,n,s,i){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return D(V(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,i))}function pa(e){return D(V("/git/branches",e))}function hv(e,n,s){const i=`?limit=${n}`;return D(V(`/git/branches/${encodeURIComponent(e)}/commits${i}`,s))}function pv(e){return D(V("/git/worktrees",e))}function fv(e,n,s){return D(V("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function gv(e,n){return D(V(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function id(e,n,s){const i=n?"?force=true":"";return D(V(`/git/branches/${encodeURIComponent(e)}${i}`,s),{method:"DELETE"})}function bv(e,n){return D(V("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function xv(e){return D(V("/git/pull",e),{method:"POST"})}function vv(e){return D(V("/git/push",e),{method:"POST"})}function mr(e){return D(V("/git/stashes",e))}function yv(e,n){return D(V("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function kv(e,n,s){return D(V(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function jv(e,n){return D(V(`/git/stashes/${e}`,n),{method:"DELETE"})}function wv(e,n,s){const i=new URLSearchParams;return i.set("path",e),i.set("staged",String(n)),D(V(`/git/diff/file?${i.toString()}`,s))}function $i(e){return D(V("/git/changes",e))}function ad(e,n){return D(V("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function Nv(e,n){return D(V("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function rd(e,n){return D(V("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function Sv(e,n){return D(V("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function Cv(e){return D(V("/workspaces",e))}function Ev(e,n,s){const i=new URLSearchParams({workspace:e});return n&&i.set("path",n),s&&i.set("projectId",s),D(`/files?${i.toString()}`)}function Mv(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),D(`/files/${encodeURIComponent(n)}?${i.toString()}`)}function _v(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),D(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function Av(e,n,s){const i=new URLSearchParams({q:e});return n&&i.set("workspace",n),s&&i.set("projectId",s),D(`/files/search?${i.toString()}`)}function Tv(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),D(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function Rv(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),D(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function Iv(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),D(`/files/${encodeURIComponent(n)}/delete?${i.toString()}`,{method:"POST"})}function Pv(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),D(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function fh(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${i.toString()}`}function $v(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${i.toString()}`}function Dv(e,n,s){return D(V("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function Lv(e,n,s,i){return D(V("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function zv(e,n,s){return D(V(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function gh(e,n,s){return D(V("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function Fv(e,n,s){return D(V("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Ov(e,n,s){return D(V("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Uv(e,n,s){return D(V("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const Ll=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(Ll))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function Bv(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function Ja(e,n,s={}){const i=s.maxReconnectAttempts??10;let r=null,o=!1,l=0,c=null,u=null,d=!1;const m=p=>{const f=p.lastEventId;if(!f)return!0;const b=Number.parseInt(f,10);return Number.isFinite(b)?u!==null&&b<=u?!1:(u=b,!0):!0},h=()=>{if(o)return;const p=Bv(e,u),f=new EventSource(Hs(p));r=f,f.onopen=()=>{l=0,d=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},f.onmessage=b=>{const v=b;m(v)&&n.onMessage?.(v)};for(const[b,v]of Object.entries(n.events??{}))f.addEventListener(b,x=>{const k=x;m(k)&&v(k)});f.onerror=()=>{if(o||r!==f)return;if(f.readyState===EventSource.CONNECTING){d||(d=!0,s.onConnectionStateChange?.("reconnecting"));return}if(f.close(),l>=i){s.onFatalError?.("Connection lost");return}d=!0,s.onConnectionStateChange?.("reconnecting"),l+=1;const v=Math.min(1e3*2**(l-1),3e4);c=setTimeout(()=>{c=null,h()},v)}};h();const g={close:()=>{o=!0,c&&(clearTimeout(c),c=null),r?.close(),Ll.delete(g)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return Ll.add(g),g}function od(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 Ji(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 Hv(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 qv(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((i,r)=>Hv(i,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function Vv(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 ld(e){return Array.isArray(e)?e.map(od):(e.candidates??[]).map(od)}async function Wv(e){try{const n=await D(V("/dev-server/candidates",e));return ld(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await D(V("/dev-server/detect",e));return ld(s)}throw n}}function dc(e){return D(V("/dev-server/status",e)).then(Ji)}async function T4(e={},n){const s=new URLSearchParams;typeof e.maxLines=="number"&&Number.isFinite(e.maxLines)&&s.set("maxLines",String(Math.max(1,Math.floor(e.maxLines)))),typeof e.offset=="number"&&Number.isFinite(e.offset)&&s.set("offset",String(Math.max(0,Math.floor(e.offset)))),typeof e.lastEventId=="number"&&Number.isFinite(e.lastEventId)&&s.set("lastEventId",String(Math.max(0,Math.floor(e.lastEventId))));const i=s.size>0?`?${s.toString()}`:"";try{const r=await D(V(`/dev-server/logs/history${i}`,n));return qv(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await dc(n);return Vv(o.logs,e)}throw r}}function Gv(e,n){const s=e.cwd??e.packagePath??".",i=e.scriptName;return D(V("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:i,scriptId:i,cwd:s,packagePath:e.packagePath})}).then(Ji)}function Kv(e){return D(V("/dev-server/stop",e),{method:"POST"}).then(Ji)}function Jv(e){return D(V("/dev-server/restart",e),{method:"POST"}).then(Ji)}async function Yv(e,n){const s=typeof e=="string"?{url:e}:e;try{const i=await D(V("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return Ji(i)}catch(i){if(i instanceof Error&&/\/dev-server\/preview-url/.test(i.message)){const r=await D(V("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return Ji(r)}throw i}}function R4(e){return Vn(V("/dev-server/logs/stream",e))}async function I4(e){try{return(await D(V("/devserver",e))).sessions??[]}catch{try{const n=await dc(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 P4(e,n){try{return await D(V(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await dc(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 $4(e,n){try{return await D(V(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await Gv({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 D4(e,n){try{return await D(V(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await Kv(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 L4(e,n){try{return await D(V(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await Jv(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 z4(e,n,s){try{const i=await D(V(`/devserver/${encodeURIComponent(e)}/preview`,s),{method:"POST",body:JSON.stringify({url:n})});return{url:i.url??null,source:i.source??null}}catch{const i=await Yv({url:n},s);return{url:i.previewUrl??i.manualUrl??null,source:"manual"}}}async function F4(e){try{return(await D(V("/devserver/detect",e))).candidates??[]}catch{try{return(await Wv(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function O4(e,n){return Vn(V(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function Ya(e,n,s=25e3){const i=setInterval(()=>{_k(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(i)}}}function Qv(e,n){return Vn(V(`/planning/${encodeURIComponent(e)}/stream`,n))}function Xv(e,n,s,i){const r=Qv(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Ja(r,{onOpen:()=>{c(),o=Ya(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 Qa(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 Zv(e){return D(Qa("/routines",e))}function ey(e,n){return D(Qa("/routines",n),{method:"POST",body:JSON.stringify(e)})}function cd(e,n,s){return D(Qa(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function ty(e,n){await D(Qa(`/routines/${e}`,n),{method:"DELETE"})}function ny(e,n){return D(Qa(`/routines/${e}/trigger`,n),{method:"POST"})}function dd(e){const n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e.limit)),e?.since!==void 0&&n.set("since",e.since),e?.type!==void 0&&n.set("type",e.type),e?.projectId&&n.set("projectId",e.projectId);const s=n.size>0?`?${n.toString()}`:"";return D(`/activity${s}`)}function sy(e){const n=V("/activity",e);return D(n,{method:"DELETE"})}function oo(e){return D(V("/workflow-steps",e))}function ud(e,n){return D(V("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function iy(e,n,s){return D(V(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function ay(e,n){return D(V(`/workflow-steps/${e}`,n),{method:"DELETE"})}function md(e,n){return D(V(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function ry(e,n){return D(V(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function oy(){return D("/workflow-step-templates")}function ly(e,n){return D(V(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function Xa(e){return D(V("/scripts",e))}function cy(e,n,s){return D(V("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function dy(e,n){return D(V(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function bh(e,n,s){return(await D(V("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const hr={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 xh(e){if(!(e instanceof Error))return hr.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?hr.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?hr.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:hr.NETWORK}function uy(e,n){return D(V("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function my(e,n,s){return D(V(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function hy(e,n){return Vn(V(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function py(e,n,s,i){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=Ja(hy(e,n),{onOpen:()=>{l(),r=Ya(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 fy(e,n,s,i){return D(V("/subtasks/create-tasks",i),{method:"POST",body:JSON.stringify({sessionId:e,parentTaskId:s,subtasks:n.map(r=>({tempId:r.id,title:r.title,description:r.description,size:r.suggestedSize,dependsOn:r.dependsOn}))})})}function vh(e,n,s){return D(V("/subtasks/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function V(e,n){if(!n)return e;const s=e.includes("?")?"&":"?";return`${e}${s}projectId=${encodeURIComponent(n)}`}function gy(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 lo(e,n){const{nodeId:s,localNodeId:i,...r}=n??{},o=gy(e,s,i);return D(o,r)}function oa(e,n){const s=new URLSearchParams;e?.state&&s.set("state",e.state),e?.role&&s.set("role",e.role),e?.includeEphemeral===!0&&s.set("includeEphemeral","true"),n&&s.set("projectId",n);const i=s.size>0?`?${s.toString()}`:"";return D(`/agents${i}`)}function yh(e,n){return D(V(`/agents/${encodeURIComponent(e)}`,n))}function by(e,n){return D(V("/agents",n),{method:"POST",body:JSON.stringify(e)})}function xy(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function U4(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function B4(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function H4(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function q4(e,n){return D(V(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function V4(e,n,s){const i=`path=${encodeURIComponent(n)}`;return D(V(`/agents/${encodeURIComponent(e)}/memory/file?${i}`,s))}function W4(e,n,s,i){return D(V(`/agents/${encodeURIComponent(e)}/memory/file`,i),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function vy(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function yy(e,n){return D(V(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function G4(e,n,s){const i=new URLSearchParams;i.set("limit",String(n)),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return D(`/agents/${encodeURIComponent(e)}/runs${r}`)}function K4(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function J4(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function Y4(e,n,s){const i=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return D(V(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:i,triggerDetail:r})})}function Q4(e,n){return D(V(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function ky(e){return D(V("/agents/stats",e))}function X4(e,n){return D(V(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function Z4(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeEphemeral&&s.set("includeEphemeral","true");const i=s.toString();return D(`/agents/org-tree${i?`?${i}`:""}`)}function eI(e,n){return D(V(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function hd(e,n,s){return D(V(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function tI(e,n){return D(V(`/agents/${encodeURIComponent(e)}/tasks`,n))}function nI(){return D("/agents/companies")}function sI(e,n){return D(V("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function iI(e,n){return D(V("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function aI(e,n){return D(V(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function rI(e){return D(V("/backups",e))}function oI(e){return D(V("/backups",e),{method:"POST"})}function lI(e,n){const s=V("/settings/export",n),i=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return D(i)}function cI(e,n,s){return D(V("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}function pd(){return D("/projects/across-nodes")}function Pa(e,n){D("/_perf/dashboard-load",{method:"POST",body:JSON.stringify({source:e,message:n})}).catch(()=>{})}function fd(){return D("/nodes")}function jy(e){return D("/nodes",{method:"POST",body:JSON.stringify(e)})}function wy(e,n){return D(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function Ny(e){return D(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Sy(e){const n=await D(`/nodes/${encodeURIComponent(e)}/health-check`,{method:"POST"});return{nodeId:n.nodeId??e,status:n.status,responseTimeMs:n.responseTimeMs,error:n.error,checkedAt:n.checkedAt??new Date().toISOString()}}function dI(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=Ki();l&&o.set("fn_token",l);const c=o.toString(),u=`/browse-directory${c?`?${c}`:""}`;return D(u)}function Cy(e){return D("/projects",{method:"POST",body:JSON.stringify(e)})}function kh(e){return D(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function gd(e){return D(`/projects/${encodeURIComponent(e)}/health`)}function Ey(e){return D(V("/executor/stats",e))}function bd(e){const n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e.limit)),e?.since&&n.set("since",e.since),e?.projectId&&n.set("projectId",e.projectId),e?.type&&n.set("type",e.type);const s=n.size>0?`?${n.toString()}`:"";return D(`/activity-feed${s}`)}function My(e){return D(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function _y(e){return D(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function uI(){return D("/global-concurrency")}function mI(e){return D("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function Ay(e,n){return D(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function jh(e,n,s){const i=new URLSearchParams;n&&i.set("worktree",n),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return D(`/tasks/${encodeURIComponent(e)}/diff${r}`)}function Ty(e){return D(V("/missions",e))}function Ry(e,n){return D(V("/missions",n),{method:"POST",body:JSON.stringify(e)})}function wh(e,n){return D(V(`/missions/${encodeURIComponent(e)}`,n))}function Iy(e,n,s){return D(V(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Py(e,n){return D(V(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function $y(e,n,s){const i=new URLSearchParams;i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset));const r=i.size>0?`?${i.toString()}`:"";return D(V(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function Dy(e){return D(V("/missions/health",e))}function Ly(e,n,s){return D(V(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function zy(e,n,s){return D(V(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Fy(e,n){return D(V(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Oy(e,n,s){return D(V(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function Uy(e,n,s){return D(V(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function By(e,n){return D(V(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Hy(e,n){return D(V(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function qy(e,n,s){return D(V(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function Vy(e,n,s){return D(V(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Wy(e,n){return D(V(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Gy(e,n,s){return D(V(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function Ky(e,n){return D(V(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function Jy(e,n,s,i){return D(V(`/missions/features/${encodeURIComponent(e)}/triage`,i),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s})})}function Yy(e,n){return D(V(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST"})}function Ro(e,n){return D(V(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function Qy(e,n,s){return D(V(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function Xy(e,n,s){return D(V(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Zy(e,n,s){return D(V(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function ek(e,n,s){return D(V(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function tk(e,n){return D(V(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function Io(e,n){return D(V(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function xd(e,n){return D(V(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function nk(e,n){return D(V(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function vd(e,n){return D(V(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function sk(e,n,s){const i=new URLSearchParams;i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset));const r=i.size>0?`?${i.toString()}`:"";return D(V(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function ik(e,n){return D(V(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function ak(e,n){return D(V(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function rk(e,n){return D(V(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function ok(e,n){return D(V(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function lk(e,n,s){return D(V(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function ck(e,n,s){return D(V("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function dk(e,n,s,i){return D(V("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function uk(e,n,s){return D(V(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Nh(e,n,s){return D(V("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function mk(e,n,s){return D(V("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function hk(e,n,s,i){const r=Vn(V(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Ja(r,{onOpen:()=>{c(),o=Ya(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 Za(e,n,s){return V(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function er(e,n,s){return V(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function pk(e,n){return D(Za(e,"/start",n),{method:"POST"})}function fk(e,n,s,i){return D(Za(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function gk(e,n,s,i){const r=Vn(Za(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Ja(r,{onOpen:()=>{c(),o=Ya(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 bk(e,n,s){return D(Za(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function xk(e,n){return D(Za(e,"/skip",n),{method:"POST"})}function vk(e,n){return D(er(e,"/start",n),{method:"POST"})}function yk(e,n,s,i){return D(er(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function kk(e,n,s,i){const r=Vn(er(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Ja(r,{onOpen:()=>{c(),o=Ya(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 jk(e,n,s){return D(er(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function wk(e,n){return D(er(e,"/skip",n),{method:"POST"})}async function Nk(e,n){try{return await D(V(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function hI(e){return D(V("/roadmaps",e))}function pI(e,n){return D(V("/roadmaps",n),{method:"POST",body:JSON.stringify(e)})}function fI(e,n){return D(V(`/roadmaps/${encodeURIComponent(e)}`,n))}function gI(e,n,s){return D(V(`/roadmaps/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function bI(e,n){return D(V(`/roadmaps/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function xI(e,n,s){return D(V(`/roadmaps/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function vI(e,n,s){return D(V(`/roadmaps/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function yI(e,n){return D(V(`/roadmaps/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function kI(e,n,s){return D(V(`/roadmaps/milestones/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function jI(e,n,s){return D(V(`/roadmaps/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function wI(e,n){return D(V(`/roadmaps/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function NI(e,n,s){return D(V(`/roadmaps/${encodeURIComponent(e)}/milestones/reorder`,s),{method:"POST",body:JSON.stringify({orderedMilestoneIds:n})})}function SI(e,n,s){return D(V(`/roadmaps/milestones/${encodeURIComponent(e)}/features/reorder`,s),{method:"POST",body:JSON.stringify({orderedFeatureIds:n})})}function CI(e,n,s,i){return D(V(`/roadmaps/features/${encodeURIComponent(e)}/move`,i),{method:"POST",body:JSON.stringify({targetMilestoneId:n,targetIndex:s})})}function EI(e,n){return D(V(`/roadmaps/${encodeURIComponent(e)}/handoff`,n))}function MI(e,n,s,i){return D(V(`/roadmaps/${encodeURIComponent(e)}/suggestions/milestones`,i),{method:"POST",body:JSON.stringify({goalPrompt:n.trim(),...s!==void 0?{count:s}:{}})})}function _I(e,n,s){return D(V(`/roadmaps/milestones/${encodeURIComponent(e)}/suggestions/features`,s),{method:"POST",body:JSON.stringify({...n?.prompt!==void 0?{prompt:n.prompt.trim()}:{},...n?.count!==void 0?{count:n.count}:{}})})}function Yi(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function Sh(e){const n=e?`?projectId=${encodeURIComponent(e)}`:"",s=await fetch(Vn(`/ai-sessions${n}`),{headers:di()});return s.ok?(await s.json()).sessions??[]:[]}async function Js(e){const n=await fetch(Vn(`/ai-sessions/${encodeURIComponent(e)}`),{headers:di()});return n.ok?n.json():null}async function Sk(e,n){const s=await D(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function Ck(e,n){return D(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function Ek(e,n){return D(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function Mk(e){await fetch(Vn(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:di()})}function _k(e,n){return D(V(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function Ak(e,n){const s=new URLSearchParams;s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),e?.unreadOnly&&s.set("unreadOnly","true"),e?.type&&s.set("type",e.type),n&&s.set("projectId",n);const i=s.size>0?`?${s.toString()}`:"";return D(`/messages/inbox${i}`)}function Tk(e,n){const s=new URLSearchParams;s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),e?.type&&s.set("type",e.type),n&&s.set("projectId",n);const i=s.size>0?`?${s.toString()}`:"";return D(`/messages/outbox${i}`)}function Ch(e){return D(V("/messages/unread-count",e))}function Rk(e,n){return D(V("/messages",n),{method:"POST",body:JSON.stringify(e)})}function Ik(e,n){return D(V(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function Pk(e){return D(V("/messages/read-all",e),{method:"POST"})}function $k(e,n){return D(V(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Dk(e,n,s){const i=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return D(V(i,s))}function Lk(e,n){return D(V(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function AI(e,n,s){const i=new URLSearchParams;i.set("limit",String(n)),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return D(`/agents/${encodeURIComponent(e)}/reflections${r}`)}function TI(e,n){return D(V(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function RI(e,n,s){const i=new URLSearchParams;s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return D(`/agents/${encodeURIComponent(e)}/performance${r}`)}function II(e,n,s){const i=new URLSearchParams;i.set("limit",String(n.limit)),n?.category&&i.set("category",n.category),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return D(`/agents/${encodeURIComponent(e)}/ratings${r}`)}function PI(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function $I(e,n){return D(V(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function DI(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function LI(e,n){return D(V(`/agents/${encodeURIComponent(e)}/budget`,n))}function zI(e,n){return D(V(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function FI(e){return D(V("/plugins",e))}async function OI(e,n){return D(V("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function UI(e,n){return D(V(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function BI(e,n){return D(V(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function HI(e,n){return D(V(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function qI(e,n){return D(V(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function VI(e,n,s){return D(V(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function WI(e,n){return D(V(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function zk(e){return D(V("/plugins/ui-slots",e))}async function GI(e){return(await D(V("/skills/discovered",e))).skills}async function KI(e,n,s){return D(V("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function JI(e,n,s){const i=new URLSearchParams;e&&i.set("q",e),i.set("limit",String(n));const r=i.size>0?`?${i.toString()}`:"";return D(V(`/skills/catalog${r}`,s))}async function YI(e,n){return(await D(V(`/skills/${encodeURIComponent(e)}/content`,n))).content}function QI(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const i=s.toString();return D(`/chat/sessions${i?`?${i}`:""}`)}async function Fk(e,n){const s=e.agentId.trim();if(!s)throw new Error("agentId is required");const i=e.modelProvider?.trim(),r=e.modelId?.trim();if(i&&!r||!i&&r)throw new Error("Both modelProvider and modelId must be provided together, or neither should be provided");const o=new URLSearchParams;return o.set("lookup","resume"),o.set("agentId",s),n&&o.set("projectId",n),i&&r&&(o.set("modelProvider",i),o.set("modelId",r)),{session:(await D(`/chat/sessions?${o.toString()}`)).sessions[0]??null}}function Ok(e,n){return D(V("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function XI(e,n,s){return D(V(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function ZI(e,n){return D(V(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function yd(e,n,s){const i=new URLSearchParams;n?.limit!==void 0&&i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset)),n?.before&&i.set("before",n.before);const r=i.toString();return D(V(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function Uk(e,n){return D(V(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function Bk(e,n,s,i,r){const o=Vn(V(`/chat/sessions/${encodeURIComponent(e)}/messages`,i)),l=new AbortController;let c=!1;const u=(d,m)=>{if(!(!d||!m))switch(d){case"thinking":try{s.onThinking?.(JSON.parse(m))}catch{s.onThinking?.(m)}break;case"text":try{s.onText?.(JSON.parse(m))}catch{s.onText?.(m)}break;case"tool_start":try{s.onToolStart?.(JSON.parse(m))}catch{}break;case"tool_end":try{s.onToolEnd?.(JSON.parse(m))}catch{}break;case"done":try{s.onDone?.(JSON.parse(m))}catch{s.onDone?.({messageId:""})}break;case"error":try{const h=JSON.parse(m);s.onError?.(h.message||h)}catch{s.onError?.(m||"Stream error")}break}};return(async()=>{try{const d=await fetch(o,{method:"POST",headers:di({"Content-Type":"application/json"}),body:JSON.stringify({content:n}),signal:l.signal});if(!d.ok){const v=await d.text();let x=`Request failed: ${d.status}`;try{x=JSON.parse(v).error||x}catch{}s.onError?.(x);return}if(!d.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected");const m=d.body.getReader(),h=new TextDecoder;let g="",p="",f=[];const b=(v,x=!1)=>{g+=v;const k=g.split(`
|
|
573
|
-
`);g=k.pop()||"",x&&g.length>0&&(k.push(g),g="");for(const M of k){const y=M.endsWith("\r")?M.slice(0,-1):M;if(y.startsWith("event:"))p=y.slice(6).trim();else if(y.startsWith("data:")){const R=y.slice(5);f.push(R.startsWith(" ")?R.slice(1):R)}else if(y===""){const R=f.join(`
|
|
574
|
-
`);u(p,R),p="",f=[]}}if(x&&p&&f.length>0){const M=f.join(`
|
|
575
|
-
`);u(p,M),p="",f=[]}};for(;;){const{done:v,value:x}=await m.read();if(v){b(h.decode(),!0);break}b(h.decode(x,{stream:!0}))}}catch(d){if(d instanceof DOMException&&d.name==="AbortError"){c||s.onError?.("Connection aborted");return}if(c)return;s.onError?.(d instanceof Error?d.message:"Connection error")}})(),{close:()=>{c=!0,l.abort()},isConnected:()=>!c}}function eP(e={},n){const s=new URLSearchParams;e.category&&s.set("category",e.category),e.status&&s.set("status",e.status),e.runId&&s.set("runId",e.runId),e.limit!==void 0&&s.set("limit",String(e.limit)),e.offset!==void 0&&s.set("offset",String(e.offset));const i=s.size>0?`?${s.toString()}`:"";return D(V(`/insights${i}`,n))}function tP(e,n){return D(V(`/insights/${encodeURIComponent(e)}/dismiss`,n),{method:"POST"})}function nP(e="manual",n,s){return D(V("/insights/run",s),{method:"POST",body:JSON.stringify({trigger:e,inputMetadata:n})})}function sP(e){return D(V("/insights/runs",e))}function iP(e,n){return D(V(`/insights/${encodeURIComponent(e)}/create-task`,n),{method:"POST"})}function Hk({onOpenScripts:e,onRunScript:n,projectId:s}){const[i,r]=a.useState(!1),[o,l]=a.useState({}),[c,u]=a.useState(!1),[d,m]=a.useState(-1),[h,g]=a.useState(null),p=a.useRef(null),f=a.useRef(null),b=a.useRef(null),v=a.useCallback(()=>{const P=window.visualViewport;return P&&P.width>0&&P.height>0?{width:P.width,height:P.height,offsetTop:P.offsetTop,offsetLeft:P.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),x=a.useCallback(()=>{const P=f.current;if(!P)return;const T=P.getBoundingClientRect(),_=b.current,{width:L,height:G,offsetTop:$,offsetLeft:I}=v(),w=16,q=16,W=6,B=_?.offsetWidth||Math.max(T.width,260),A=Math.min(B,Math.max(L-w*2,160)),z=_?.offsetHeight||280,X=Math.min(z,Math.max(G-q*2,160)),E=T.top-$,U=T.bottom-$,pe=T.left-I,ie=G-U,re=E,F=ie<X&&re>ie,ce=Math.min(Math.max(pe,w),L-w-A)+I,ae=F?Math.max(q+$,E-X-W+$):Math.min(U+W+$,G+$-q-X);g({top:ae,left:ce,width:A})},[v]),k=a.useMemo(()=>Object.entries(o).sort(([P],[T])=>P.localeCompare(T)),[o]),M=k.length>0,y=k.length+(M?1:0);a.useEffect(()=>{if(!i)return;let P=!1;return u(!0),Xa(s).then(T=>{P||l(T)}).catch(()=>{P||l({})}).finally(()=>{P||u(!1)}),()=>{P=!0}},[i,s]),a.useEffect(()=>{if(!i)return;const P=T=>{p.current&&!p.current.contains(T.target)&&f.current&&!f.current.contains(T.target)&&r(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[i]),a.useEffect(()=>{if(!i)return;const P=T=>{T.key==="Escape"&&(r(!1),f.current?.focus())};return document.addEventListener("keydown",P),()=>document.removeEventListener("keydown",P)},[i]),a.useEffect(()=>{if(i){m(-1);const P=window.setTimeout(()=>b.current?.focus(),0);return()=>window.clearTimeout(P)}g(null)},[i]),a.useEffect(()=>{if(!i)return;const P=requestAnimationFrame(()=>{x()});return()=>cancelAnimationFrame(P)},[i,c,k.length,M,x]),a.useEffect(()=>{if(!i)return;const P=()=>x();window.addEventListener("resize",P),window.addEventListener("scroll",P,!0);const T=window.visualViewport;return T&&(T.addEventListener("resize",P),T.addEventListener("scroll",P)),()=>{window.removeEventListener("resize",P),window.removeEventListener("scroll",P,!0),T&&(T.removeEventListener("resize",P),T.removeEventListener("scroll",P))}},[i,x]);const R=a.useCallback(P=>{switch(P.key){case"ArrowDown":P.preventDefault(),m(T=>T<y-1?T+1:0);break;case"ArrowUp":P.preventDefault(),m(T=>T>0?T-1:y-1);break;case"Enter":if(P.preventDefault(),d>=0)if(d<k.length){const[T,_]=k[d];C(T,_)}else M&&d===k.length&&S();break;case"Home":P.preventDefault(),m(0);break;case"End":P.preventDefault(),m(y-1);break}},[d,y,k,M]),j=a.useCallback(()=>{r(P=>!P)},[]),C=a.useCallback((P,T)=>{n(P,T),r(!1)},[n]),S=a.useCallback(()=>{e(),r(!1)},[e]);return t.jsxs("div",{className:"quick-scripts-dropdown",ref:p,children:[t.jsxs("button",{ref:f,className:`btn-icon quick-scripts-dropdown__trigger ${i?"open btn-icon--active":""}`,onClick:j,"aria-expanded":i,"aria-haspopup":"listbox","aria-label":"Quick scripts","data-testid":"scripts-btn",title:"Scripts",children:[t.jsx(Bs,{size:16}),t.jsx(zt,{size:14,className:`quick-scripts-dropdown__trigger-chevron ${i?"rotate":""}`})]}),i&&t.jsx("div",{ref:b,tabIndex:-1,className:"quick-scripts-dropdown__menu",role:"listbox","aria-label":"Scripts",onKeyDown:R,"data-testid":"quick-scripts-dropdown",style:h?{position:"fixed",top:`${h.top}px`,left:`${h.left}px`,width:`${h.width}px`,right:"auto"}:void 0,children:c?t.jsxs("div",{className:"quick-scripts-dropdown__loading","data-testid":"quick-scripts-loading",children:[t.jsx(it,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts..."})]}):k.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(Bs,{size:16})}),t.jsx("p",{children:"No scripts configured"}),t.jsx("button",{className:"quick-scripts-dropdown__empty-action btn",onClick:S,children:"Add your first script"})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-scripts-dropdown__list",children:k.map(([P,T],_)=>t.jsxs("button",{className:`quick-scripts-dropdown__item ${d===_?"highlighted":""}`,onClick:()=>C(P,T),role:"option","aria-selected":d===_,"data-testid":`quick-script-item-${P}`,children:[t.jsx(rn,{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:P}),t.jsx("span",{className:"quick-scripts-dropdown__item-command",title:T,children:T.length>50?`${T.slice(0,50)}...`:T})]})]},P))}),t.jsx("div",{className:"quick-scripts-dropdown__footer",children:t.jsxs("button",{className:`quick-scripts-dropdown__manage ${M&&d===k.length?"highlighted":""}`,onClick:S,"data-testid":"quick-scripts-manage",children:[t.jsx(Oa,{size:14}),t.jsx("span",{children:"Manage Scripts..."})]})})]})})]})}function qk(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 Vk({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}=qk(e.status),r=e.status==="connecting";return t.jsxs("div",{className:"node-status-indicator node-status-indicator--remote",children:[t.jsx("span",{className:`node-status-indicator__dot ${i}`,children:r&&t.jsx("span",{className:"node-status-indicator__spinner"})}),t.jsx("span",{className:"node-status-indicator__name",children:e.name}),n&&t.jsxs("span",{className:"node-status-indicator__details",children:[e.type," · ",s]})]})}const kd=new Map,Wk=6e4;function Eh(e){const[n,s]=a.useState([]),[i,r]=a.useState(!0),[o,l]=a.useState(null),c=a.useRef(!1),u=a.useRef(!1),d=a.useCallback(m=>n.filter(h=>h.slot.slotId===m),[n]);return a.useEffect(()=>{const m=e??"default";let h=!1;async function g(){const p=kd.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 zk(e);if(h||u.current)return;kd.set(m,{slots:b,expiresAt:Date.now()+Wk}),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 g(),()=>{h=!0}},[e]),a.useEffect(()=>{c.current=!1,u.current=!1},[e]),a.useEffect(()=>()=>{u.current=!0},[]),a.useMemo(()=>({slots:n,getSlotsForId:d,loading:i,error:o}),[n,d,i,o])}function co({slotId:e,projectId:n}){const{getSlotsForId:s,loading:i,error:r}=Eh(n);if(i||r||!e)return null;const o=s(e);return o.length===0?null:t.jsx(ao,{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 Gk(){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 tr(){const[e,n]=a.useState(Gk);return a.useEffect(()=>{if(typeof window>"u")return;const s=window.matchMedia("(max-width: 768px)"),i=window.matchMedia("(min-width: 769px) and (max-width: 1024px)"),r=()=>{s.matches?n("mobile"):i.matches?n("tablet"):n("desktop")};return s.addEventListener("change",r),i.addEventListener("change",r),()=>{s.removeEventListener("change",r),i.removeEventListener("change",r)}},[]),e}const Mh={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function Kk({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(zt,{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=Mh[u.status]?.color;return t.jsxs("button",{className:`project-selector-item${d?" project-selector-item--current":""}`,onClick:()=>c(u),role:"option","aria-selected":d,children:[t.jsx("span",{className:"project-selector-dot",style:{backgroundColor:m||"var(--text-muted)"}}),t.jsxs("div",{className:"project-selector-info",children:[t.jsx("span",{className:"project-selector-name",children:u.name}),t.jsx("span",{className:"project-selector-path",children:u.path.split("/").slice(-2).join("/")})]}),d&&t.jsx(xn,{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 jd({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 Jk({onOpenSettings:e,onOpenGitHubImport:n,onOpenPlanning:s,onResumePlanning:i,activePlanningSessionCount:r=0,onOpenUsage:o,onOpenActivityLog:l,onOpenMailbox:c,mailboxUnreadCount:u=0,onOpenSchedules:d,onOpenGitManager:m,onOpenNodes:h,showNodesButton:g,onOpenWorkflowSteps:p,onOpenScripts:f,onRunScript:b,onToggleTerminal:v,onOpenFiles:x,filesOpen:k,globalPaused:M,enginePaused:y,onToggleGlobalPause:R,onToggleEnginePause:j,view:C="board",onChangeView:S,showSkillsTab:P,showAgentsTab:T,searchQuery:_="",onSearchChange:L,projects:G=[],currentProject:$,onSelectProject:I,onViewAllProjects:w,projectId:q,isElectron:W=!1,mobileNavEnabled:B,availableNodes:A=[],currentNode:z,onSelectNode:X,isRemote:E=!1,experimentalFeatures:U}){const pe=tr(),ie=pe==="mobile",F=ie||pe==="tablet",ce=ie&&B,[ae,Q]=a.useState(!1),[de,Te]=a.useState(!1),[fe,Se]=a.useState(!1),[te,we]=a.useState(!1),[Pe,We]=a.useState(!1),[Ke,Ne]=a.useState(!1),[_e,Oe]=a.useState(!1),[ye,De]=a.useState(!1),[se,J]=a.useState(!1),[me,ee]=a.useState(!1),[he,le]=a.useState({}),[Ie,Ze]=a.useState(!1),at=a.useRef(null),oe=a.useRef(null),Z=a.useRef(null),ue=a.useRef(null),Ce=a.useRef(null),$e=a.useRef(null),ve=a.useRef(!1),Ge=a.useRef(null),je=a.useRef(null),Ue=a.useRef(null),He=a.useRef(null),ge=a.useRef(null),Fe=a.useMemo(()=>A.filter(Le=>Le.type==="remote"),[A]),be=Fe.length>0,Je=a.useMemo(()=>Object.entries(he).sort(([Le],[gt])=>Le.localeCompare(gt)),[he]),st=a.useMemo(()=>!!(U?.insights||U?.roadmap||P||U?.memoryView||U?.devServerView),[U,P]);a.useEffect(()=>{ve.current=Pe},[Pe]),a.useEffect(()=>{if(!Pe||!F)return;let Le=!1;return Ze(!0),Xa(q).then(gt=>{Le||le(gt)}).catch(()=>{Le||le({})}).finally(()=>{Le||Ze(!1)}),()=>{Le=!0}},[Pe,F,q]);const dt=ae||_.length>0,Tt=(de||_.length>0)&&!fe,$t=(C==="board"||C==="list")&&!ie&&L&&!fe&&_.length===0,Dt=(C==="board"||C==="list")&&!ie&&L;a.useEffect(()=>{_===""&&Se(!1)},[_]),a.useEffect(()=>{if(!te)return;const Le=gt=>{oe.current&&!oe.current.contains(gt.target)&&at.current&&!at.current.contains(gt.target)&&we(!1)};return document.addEventListener("mousedown",Le),()=>document.removeEventListener("mousedown",Le)},[te]),a.useEffect(()=>{if(!se)return;const Le=gt=>{ue.current&&!ue.current.contains(gt.target)&&Z.current&&!Z.current.contains(gt.target)&&J(!1)};return document.addEventListener("mousedown",Le),()=>document.removeEventListener("mousedown",Le)},[se]),a.useEffect(()=>{if(!Ke)return;const Le=gt=>{Ge.current&&!Ge.current.contains(gt.target)&&Ne(!1)};return document.addEventListener("mousedown",Le),()=>document.removeEventListener("mousedown",Le)},[Ke]),a.useEffect(()=>{const Le=gt=>{if(gt.key==="Escape"){if(De(!1),J(!1),ve.current){We(!1);return}we(!1),Q(!1),Ne(!1),Oe(!1)}};return document.addEventListener("keydown",Le),()=>document.removeEventListener("keydown",Le)},[]),a.useEffect(()=>{if(!_e)return;const Le=gt=>{je.current&&!je.current.contains(gt.target)&&Oe(!1)};return document.addEventListener("mousedown",Le),()=>document.removeEventListener("mousedown",Le)},[_e]),a.useEffect(()=>{if(!me)return;const Le=gt=>{ge.current&&!ge.current.contains(gt.target)&&ee(!1)};return document.addEventListener("mousedown",Le),()=>document.removeEventListener("mousedown",Le)},[me]),a.useEffect(()=>{if(!me)return;const Le=gt=>{gt.key==="Escape"&&ee(!1)};return document.addEventListener("keydown",Le),()=>document.removeEventListener("keydown",Le)},[me]),a.useEffect(()=>{if(!ye)return;const Le=gt=>{Ue.current&&!Ue.current.contains(gt.target)&&He.current&&!He.current.contains(gt.target)&&De(!1)};return document.addEventListener("mousedown",Le),()=>document.removeEventListener("mousedown",Le)},[ye]);const Bt=a.useCallback(()=>{Q(Le=>!Le)},[]),qt=a.useCallback(()=>{Te(!0),Se(!1)},[]),Lt=a.useCallback(()=>{Te(!1),Se(!0),L&&L("")},[L]),Ct=a.useCallback(()=>{we(Le=>!Le)},[]),xt=a.useCallback(Le=>{Le&&Le(),we(!1),We(!1)},[]),Et=a.useCallback(()=>{Q(!1),L&&L("")},[L]);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"})]}),ie&&G.length>=1&&I&&t.jsxs("div",{className:"mobile-project-switch",ref:je,children:[t.jsx("button",{className:`mobile-project-switch-trigger${_e?" mobile-project-switch-trigger--open":""}`,onClick:()=>Oe(Le=>!Le),title:"Switch project","aria-label":"Switch project","aria-expanded":_e,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:t.jsx(zt,{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:G.map(Le=>{const gt=$?.id===Le.id,ut=Mh[Le.status]?.color;return t.jsxs("button",{className:`mobile-project-switch-item${gt?" mobile-project-switch-item--current":""}`,onClick:()=>{I(Le),Oe(!1)},role:"option","aria-selected":gt,"data-testid":`mobile-project-switch-item-${Le.id}`,children:[t.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:ut||"var(--text-muted)"}}),t.jsxs("div",{className:"mobile-project-switch-info",children:[t.jsx("span",{className:"mobile-project-switch-name",children:Le.name}),t.jsx("span",{className:"mobile-project-switch-path",children:Le.path.split("/").slice(-2).join("/")})]}),gt&&t.jsx(xn,{size:14,className:"mobile-project-switch-check"})]},Le.id)})})]}),!F&&G.length>=1&&w&&t.jsx(Kk,{projects:G,currentProject:$??null,onViewAll:w,onSelectProject:I}),be&&t.jsxs("div",{className:`header-node-selector${ie?" header-node-selector--mobile":""}`,ref:ie?void 0:Ge,children:[t.jsx(Vk,{node:z??null,showDetails:!ie}),!ie&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:`btn-icon node-selector-trigger${Ke?" node-selector-trigger--open":""}`,onClick:()=>Ne(Le=>!Le),title:"Switch node","aria-label":"Switch node","aria-expanded":Ke,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:t.jsx(en,{size:12,className:`node-selector-chevron${Ke?" node-selector-chevron--open":""}`})}),Ke&&t.jsxs("div",{className:"node-selector-dropdown",role:"listbox","aria-label":"Select node",children:[t.jsxs("button",{className:`node-selector-option${E?"":" node-selector-option--active"}`,onClick:()=>{X?.(null),Ne(!1)},role:"option","aria-selected":!E,"data-testid":"node-option-local",children:[t.jsx("span",{className:"node-selector-option-dot node-selector-option-dot--local"}),t.jsx("span",{className:"node-selector-option-label",children:"Local"})]}),Fe.map(Le=>t.jsxs("button",{className:`node-selector-option${z?.id===Le.id?" node-selector-option--active":""}`,onClick:()=>{X?.(Le),Ne(!1)},role:"option","aria-selected":z?.id===Le.id,"data-testid":`node-option-${Le.id}`,children:[t.jsx("span",{className:`node-selector-option-dot node-selector-option-dot--${Le.status}`}),t.jsx("span",{className:"node-selector-option-label",children:Le.name}),t.jsx("span",{className:"node-selector-option-status",children:Le.status})]},Le.id))]})]})]})]}),t.jsxs("div",{className:"header-actions",children:[ce&&S&&(C==="board"||C==="list")&&t.jsxs("div",{className:"view-toggle","data-testid":"mobile-view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${C==="board"?" active":""}`,onClick:()=>S("board"),title:"Board view","aria-label":"Board view","aria-pressed":C==="board","data-testid":"mobile-view-toggle-board",children:t.jsx(Ci,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="list"?" active":""}`,onClick:()=>S("list"),title:"List view","aria-label":"List view","aria-pressed":C==="list","data-testid":"mobile-view-toggle-list",children:t.jsx(Tl,{size:16})})]}),L&&ie&&(ce||C==="board"||C==="list")&&!dt&&t.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:Bt,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:t.jsx(Bi,{size:16})}),$t&&t.jsx("button",{className:"btn-icon",onClick:qt,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:t.jsx(Bi,{size:16})}),ie&&ce&&o&&t.jsx("button",{className:"btn-icon",onClick:o,title:"View usage","data-testid":"mobile-header-usage-btn",children:t.jsx(Ss,{size:16})}),!ce&&S&&t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${C==="board"?" active":""}`,onClick:()=>S("board"),title:"Board view","aria-label":"Board view","aria-pressed":C==="board",children:t.jsx(Ci,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="list"?" active":""}`,onClick:()=>S("list"),title:"List view","aria-label":"List view","aria-pressed":C==="list",children:t.jsx(Tl,{size:16})}),T&&t.jsx("button",{className:`view-toggle-btn${C==="agents"?" active":""}`,onClick:()=>S("agents"),title:"Agents view","aria-label":"Agents view","aria-pressed":C==="agents",children:t.jsx(an,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="missions"?" active":""}`,onClick:()=>S("missions"),title:"Missions view","aria-label":"Missions view","aria-pressed":C==="missions",children:t.jsx(ns,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="chat"?" active":""}`,onClick:()=>S("chat"),title:"Chat view","aria-label":"Chat view","aria-pressed":C==="chat",children:t.jsx(li,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="documents"?" active":""}`,onClick:()=>S("documents"),title:"Documents view","aria-label":"Documents view","aria-pressed":C==="documents",children:t.jsx(Ni,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="mailbox"?" active":""}`,onClick:()=>S("mailbox"),title:"Mailbox view","aria-label":"Mailbox view","aria-pressed":C==="mailbox",children:t.jsx(Gi,{size:16})}),st&&t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:He,className:`view-toggle-btn${["skills","roadmaps","insights","memory","dev-server","devserver"].includes(C)?" active":""}`,onClick:()=>De(Le=>!Le),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":ye,"data-testid":"view-toggle-overflow-trigger",children:t.jsx(zt,{size:12})}),ye&&t.jsxs("div",{ref:Ue,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[U?.insights&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="insights"?" active":""}`,onClick:()=>{S("insights"),De(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[t.jsx(Dn,{size:14}),t.jsx("span",{children:"Insights"})]}),U?.roadmap&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="roadmaps"?" active":""}`,onClick:()=>{S("roadmaps"),De(!1)},role:"menuitem","data-testid":"view-overflow-roadmaps",children:[t.jsx(Rl,{size:14}),t.jsx("span",{children:"Roadmaps"})]}),P&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="skills"?" active":""}`,onClick:()=>{S("skills"),De(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[t.jsx(vn,{size:14}),t.jsx("span",{children:"Skills"})]}),U?.memoryView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="memory"?" active":""}`,onClick:()=>{S("memory"),De(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[t.jsx(Pr,{size:14}),t.jsx("span",{children:"Memory"})]}),U?.devServerView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="dev-server"||C==="devserver"?" active":""}`,onClick:()=>{S("devserver"),De(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[t.jsx(rh,{size:14}),t.jsx("span",{children:"Dev Server"}),t.jsx("span",{className:"visually-hidden","data-testid":"view-toggle-dev-server"})]})]})]})]}),!F&&o&&t.jsx("button",{className:"btn-icon",onClick:o,title:"View usage","data-testid":"desktop-header-usage-btn",children:t.jsx(Ss,{size:16})}),!F&&l&&t.jsx("button",{className:"btn-icon",onClick:l,title:"View Activity Log",children:t.jsx(Fa,{size:16})}),!F&&!W&&t.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:t.jsx(jd,{size:16})}),!F&&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(Us,{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})]}),!F&&t.jsx("button",{className:"btn-icon btn-icon--terminal",onClick:v,title:"Open Terminal","data-testid":"terminal-toggle-btn",children:t.jsx(Bs,{size:16})}),!F&&x&&t.jsx("button",{className:`btn-icon${k?" btn-icon--active":""}`,onClick:x,title:"Browse files","data-testid":"files-toggle-btn",children:t.jsx(jn,{size:16})}),!F&&m&&t.jsx("button",{className:"btn-icon",onClick:m,title:"Git Manager","data-testid":"git-manager-btn",children:t.jsx(Os,{size:16})}),!F&&p&&t.jsx("button",{className:"btn-icon",onClick:p,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:t.jsx(Pl,{size:16})}),!F&&f&&b&&t.jsx(Hk,{onOpenScripts:f,onRunScript:b,projectId:q}),!F&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{ref:Z,className:"btn-icon",onClick:()=>J(Le=>!Le),title:"More actions","aria-label":"More actions","aria-expanded":se,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:t.jsx(_l,{size:16})}),se&&t.jsxs("div",{ref:ue,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[h&&g!==!1&&t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{h(),J(!1)},role:"menuitem","data-testid":"desktop-overflow-nodes-btn",children:[t.jsx(Lr,{size:14}),t.jsx("span",{children:"Nodes"})]}),t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{xt(d),J(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[t.jsx(ji,{size:14}),t.jsx("span",{children:"Automation"})]})]})]}),t.jsxs("div",{className:"engine-control-split-btn",ref:ge,children:[t.jsx("button",{className:`btn-icon engine-control-split-btn__main${M?" btn-icon--stopped":""}`,onClick:R,title:M?"Start AI engine":"Stop AI engine","data-testid":"engine-control-main-btn",children:M?t.jsx(rn,{size:16}):t.jsx(ls,{size:16})}),t.jsx("span",{className:"engine-control-split-btn__divider"}),t.jsx("button",{className:`btn-icon engine-control-split-btn__chevron${me?" btn-icon--active":""}`,onClick:()=>ee(Le=>!Le),title:"Engine options","aria-haspopup":"menu","aria-expanded":me,"data-testid":"engine-control-chevron-btn",children:t.jsx(zt,{size:12})}),me&&t.jsx("div",{className:"engine-control-split-btn__menu",role:"menu",children:t.jsxs("button",{className:`engine-control-split-btn__menu-item${y?" engine-control-split-btn__menu-item--active":""}`,onClick:()=>{j?.(),ee(!1)},role:"menuitem",title:y?"Resume scheduling":"Pause triage",disabled:!!M,"data-testid":"engine-control-pause-triage-btn",children:[y?t.jsx(rn,{size:14}):t.jsx(Fs,{size:14}),t.jsx("span",{children:y?"Resume scheduling":"Pause triage"})]})})]}),!F&&t.jsx("button",{className:"btn-icon",onClick:e,title:"Settings",children:t.jsx(Oa,{size:16})}),t.jsx(co,{slotId:"header-action",projectId:q}),F&&!ce&&t.jsx("button",{ref:at,className:"btn-icon compact-overflow-trigger",onClick:Ct,title:"More header actions","aria-label":"More header actions","aria-expanded":te,"aria-haspopup":"menu",children:t.jsx(_l,{size:16})}),F&&!ce&&te&&t.jsxs("div",{ref:oe,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[G.length>=1&&w&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(w),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[t.jsx(ih,{size:16}),t.jsx("span",{children:"Projects"})]}),x&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(x),role:"menuitem","data-testid":"overflow-files-btn",children:[t.jsx(jn,{size:16}),t.jsx("span",{children:"Browse Files"})]}),t.jsxs("button",{className:`mobile-overflow-item${r>0?" mobile-overflow-item--has-indicator":""}`,onClick:()=>xt(r>0&&i?i:s),role:"menuitem","data-testid":"overflow-planning-btn",children:[t.jsxs("span",{className:"mobile-overflow-icon-wrapper",children:[t.jsx(Us,{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"})]}),m&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(m),role:"menuitem","data-testid":"overflow-git-btn",children:[t.jsx(Os,{size:16}),t.jsx("span",{children:"Git Manager"})]}),h&&g!==!1&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(h),role:"menuitem","data-testid":"overflow-nodes-btn",children:[t.jsx(Lr,{size:16}),t.jsx("span",{children:"Nodes"})]}),!W&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(n),role:"menuitem",children:[t.jsx(jd,{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:()=>xt(v),role:"menuitem","data-testid":"overflow-terminal-primary-btn",children:[t.jsx(Bs,{size:16}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{className:"mobile-overflow-split-toggle",onClick:()=>We(Le=>!Le),role:"menuitem","aria-expanded":Pe,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:t.jsx(en,{size:14,className:`mobile-overflow-chevron${Pe?" mobile-overflow-chevron--open":""}`})})]}),Pe&&t.jsx("div",{className:"mobile-overflow-submenu",role:"menu","aria-label":"Scripts submenu",children:Ie?t.jsxs("div",{className:"mobile-overflow-submenu-loading","data-testid":"overflow-scripts-loading",children:[t.jsx(it,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):Je.length>0?t.jsxs(t.Fragment,{children:[Je.map(([Le,gt])=>t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{b&&b(Le,gt),we(!1),We(!1)},role:"menuitem","data-testid":`overflow-script-item-${Le}`,children:[t.jsx(rn,{size:14}),t.jsx("span",{children:Le})]},Le)),f&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>xt(f),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(Ts,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):f&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>xt(f),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(Ts,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(d),role:"menuitem","data-testid":"overflow-schedules-btn",children:[t.jsx(ji,{size:16}),t.jsx("span",{children:"Automation"})]}),l&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(l),role:"menuitem","data-testid":"overflow-activity-log-btn",children:[t.jsx(Fa,{size:16}),t.jsx("span",{children:"View Activity Log"})]}),c&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(c),role:"menuitem","data-testid":"overflow-mailbox-btn",children:[t.jsx(Gi,{size:16}),t.jsxs("span",{children:["Mailbox",u>0?` (${u})`:""]})]}),o&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(o),role:"menuitem","data-testid":"overflow-usage-btn",children:[t.jsx(Ss,{size:16}),t.jsx("span",{children:"View Usage"})]}),p&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(p),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[t.jsx(Pl,{size:16}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(e),role:"menuitem",children:[t.jsx(Oa,{size:16}),t.jsx("span",{children:"Settings"})]})]})]})]}),Dt&&Tt&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{className:"header-search",children:[t.jsx(Bi,{size:14,className:"header-search-icon"}),t.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:_,onChange:Le=>L(Le.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:Lt,"aria-label":"Close search",children:t.jsx(Pt,{size:14})})]})}),L&&ie&&dt&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{ref:Ce,className:"header-search mobile-search-expanded",children:[t.jsx(Bi,{size:14,className:"header-search-icon"}),t.jsx("input",{ref:$e,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:_,onChange:Le=>L(Le.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:Et,"aria-label":"Close search",children:t.jsx(Pt,{size:14})})]})})]})}const Yk={themeMode:"dark",colorTheme:"default",defaultProvider:void 0,defaultModelId:void 0,fallbackProvider:void 0,fallbackModelId:void 0,defaultThinkingLevel:void 0,ntfyEnabled:!1,ntfyTopic:void 0,ntfyBaseUrl:void 0,ntfyEvents:["in-review","merged","failed","awaiting-approval","awaiting-user-review","planning-awaiting-input"],ntfyDashboardHost:void 0,defaultProjectId:void 0,setupComplete:void 0,favoriteProviders:void 0,favoriteModels:void 0,openrouterModelSync:!0,modelOnboardingComplete:void 0,useClaudeCli:void 0,executionGlobalProvider:void 0,executionGlobalModelId:void 0,planningGlobalProvider:void 0,planningGlobalModelId:void 0,validatorGlobalProvider:void 0,validatorGlobalModelId:void 0,titleSummarizerGlobalProvider:void 0,titleSummarizerGlobalModelId:void 0,daemonToken:void 0,daemonPort:4040,daemonHost:"127.0.0.1",settingsSyncEnabled:!1,settingsSyncAuth:!1,settingsSyncInterval:9e5,settingsSyncConflictResolution:"last-write-wins",dashboardCurrentNodeId:void 0,dashboardCurrentProjectIdByNode:void 0,vitestAutoKillEnabled:!0,vitestKillThresholdPct:90},Qk={globalPause:!1,globalPauseReason:void 0,enginePaused:!1,maxConcurrent:2,maxTriageConcurrent:2,globalMaxConcurrent:4,maxWorktrees:4,pollIntervalMs:15e3,heartbeatMultiplier:1,groupOverlappingFiles:!0,overlapIgnorePaths:[],autoMerge:!0,mergeStrategy:"direct",pushAfterMerge:!1,pushRemote:"origin",worktreeInitCommand:void 0,testCommand:void 0,buildCommand:void 0,recycleWorktrees:!1,worktreeNaming:"random",taskPrefix:"FN",includeTaskIdInCommit:!0,commitAuthorEnabled:!0,commitAuthorName:"Fusion",commitAuthorEmail:"noreply@runfusion.ai",planningProvider:void 0,planningModelId:void 0,planningFallbackProvider:void 0,planningFallbackModelId:void 0,defaultProviderOverride:void 0,defaultModelIdOverride:void 0,executionProvider:void 0,executionModelId:void 0,validatorProvider:void 0,validatorModelId:void 0,validatorFallbackProvider:void 0,validatorFallbackModelId:void 0,modelPresets:[],autoSelectModelPreset:!1,defaultPresetBySize:{},autoResolveConflicts:!0,smartConflictResolution:!0,worktreeRebaseBeforeMerge:!0,worktreeRebaseRemote:"",strictScopeEnforcement:!1,buildRetryCount:0,verificationFixRetries:3,buildTimeoutMs:3e5,requirePlanApproval:!1,specStalenessEnabled:!1,specStalenessMaxAgeMs:360*60*1e3,taskStuckTimeoutMs:void 0,aiSessionTtlMs:10080*60*1e3,aiSessionCleanupIntervalMs:3600*1e3,autoUnpauseEnabled:!0,autoUnpauseBaseDelayMs:3e5,autoUnpauseMaxDelayMs:36e5,maxStuckKills:6,maxPostReviewFixes:1,maxSpawnedAgentsPerParent:5,maxSpawnedAgentsGlobal:20,maintenanceIntervalMs:9e5,autoArchiveDoneTasksEnabled:!0,autoArchiveDoneAfterMs:2880*60*1e3,archiveAgentLogMode:"compact",autoUpdatePrStatus:!1,autoCreatePr:!1,autoBackupEnabled:!1,autoBackupSchedule:"0 2 * * *",autoBackupRetention:7,autoBackupDir:".fusion/backups",autoSummarizeTitles:!1,titleSummarizerProvider:void 0,titleSummarizerModelId:void 0,titleSummarizerFallbackProvider:void 0,titleSummarizerFallbackModelId:void 0,scripts:void 0,setupScript:void 0,insightExtractionEnabled:!1,insightExtractionSchedule:"0 2 * * *",insightExtractionMinIntervalMs:864e5,memoryEnabled:!0,memoryBackendType:"qmd",memoryAutoSummarizeEnabled:!1,memoryAutoSummarizeThresholdChars:5e4,memoryAutoSummarizeSchedule:"0 3 * * *",memoryDreamsEnabled:!1,memoryDreamsSchedule:"0 4 * * *",tokenCap:void 0,runStepsInNewSessions:!1,maxParallelSteps:2,missionStaleThresholdMs:6e5,missionMaxTaskRetries:3,missionHealthCheckIntervalMs:3e5,agentPrompts:void 0,promptOverrides:void 0,remoteAccess:{activeProvider:null,providers:{tailscale:{enabled:!1,hostname:"",targetPort:0,acceptRoutes:!1},cloudflare:{enabled:!1,quickTunnel:!1,tunnelName:"",tunnelToken:null,ingressUrl:""}},tokenStrategy:{persistent:{enabled:!0,token:null},shortLived:{enabled:!1,ttlMs:9e5,maxTtlMs:864e5}},lifecycle:{rememberLastRunning:!1,wasRunningOnShutdown:!1,lastRunningProvider:null}},reflectionEnabled:!1,reflectionIntervalMs:36e5,reflectionAfterTask:!0,reviewHandoffPolicy:"disabled",showQuickChatFAB:!1,experimentalFeatures:{}},Xk=Object.freeze(Object.keys(Yk)),Zk=Object.freeze(Object.keys(Qk));function aP(e){return Xk.includes(e)}function rP(e){return Zk.includes(e)}function xe(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}const oP=["off","minimal","low","medium","high"],ki=["triage","todo","in-progress","in-review","done","archived"],uc=["low","normal","high","urgent"],cs="normal",ej=["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"],Pn={triage:"Planning",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},tj={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"},zl={triage:["todo"],todo:["in-progress","triage"],"in-progress":["in-review","todo","triage","done"],"in-review":["done","in-progress","todo"],done:["todo","triage","archived"],archived:["done"]};function nj(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 sj(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 ij(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 _h({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 ${ij(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,onClick:r,children:[t.jsx(eo,{size:12}),t.jsxs("span",{children:["#",n.number]})]})]})}function pr(e,n){return`${e??"default"}:${n}`}class aj{ws=null;listeners=new Set;badgeUpdates=new Map;subscriptionsByTask=new Map;reconnectTimeout=null;reconnectDelayMs=1e3;shouldReconnect=!1;isConnected=!1;projectId=null;snapshot={badgeUpdates:new Map,isConnected:!1};previousProjectIdRef=null;projectContextVersionRef=0;contextVersionAtStart=0;subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}getSnapshot(){return this.snapshot}setProjectId(n){if(this.projectId===n)return;this.previousProjectIdRef=this.projectId,this.projectContextVersionRef++,this.contextVersionAtStart=this.projectContextVersionRef;const s=this.subscriptionsByTask.size>0,i=[];for(const[r,o]of this.subscriptionsByTask){const l=r.split(":").slice(1).join(":");for(const c of o)i.push({hookId:c,taskId:l})}if(this.projectId=n,this.reset(),s){for(const{hookId:r,taskId:o}of i){const l=pr(this.projectId,o);this.subscriptionsByTask.set(l,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const i=pr(this.projectId,s),r=this.subscriptionsByTask.get(i)??new Set,o=!r.has(n);r.add(n),this.subscriptionsByTask.set(i,r),this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect(),o&&this.send({type:"subscribe",taskId:s,projectId:this.projectId})}unsubscribeTask(n,s){const i=pr(this.projectId,s),r=this.subscriptionsByTask.get(i);r&&(r.delete(n),r.size===0&&(this.subscriptionsByTask.delete(i),this.badgeUpdates.delete(i),this.send({type:"unsubscribe",taskId:s,projectId:this.projectId}),this.emit()),this.shouldReconnect=this.subscriptionsByTask.size>0,this.shouldReconnect||this.disconnect())}cleanupHook(n){for(const s of[...this.subscriptionsByTask.keys()]){const i=s.split(":").slice(1).join(":");this.unsubscribeTask(n,i)}}reset(){this.disconnect(),this.badgeUpdates.clear(),this.subscriptionsByTask.clear(),this.shouldReconnect=!1,this.emit()}connect(){if(!this.shouldReconnect||typeof window>"u"||this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))return;const n=this.projectContextVersionRef;let i=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/ws`;this.projectId&&(i+=`?projectId=${encodeURIComponent(this.projectId)}`);const r=new WebSocket(Hs(i));this.ws=r,r.onopen=()=>{if(this.projectContextVersionRef!==n){r.close();return}this.isConnected=!0,this.reconnectDelayMs=1e3,this.emit();const o=new Set;for(const l of this.subscriptionsByTask.keys()){const c=l.split(":").slice(1).join(":");o.add(c)}for(const l of o)this.send({type:"subscribe",taskId:l,projectId:this.projectId})},r.onmessage=o=>{if(this.projectContextVersionRef===n)try{const l=JSON.parse(o.data);if(l.type!=="badge:updated"||l.projectId!==void 0&&l.projectId!==this.projectId)return;const c=pr(this.projectId,l.taskId),u=this.badgeUpdates.get(c);this.badgeUpdates.set(c,{prInfo:wd(l,"prInfo")?l.prInfo??null:u?.prInfo,issueInfo:wd(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 gi=new aj;let rj=0;function wd(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function Ah(e){const n=a.useRef(null);n.current===null&&(n.current=`badge-hook-${rj++}`);const s=a.useSyncExternalStore(o=>gi.subscribe(o),()=>gi.getSnapshot(),()=>gi.getSnapshot()),i=a.useCallback(o=>{gi.subscribeTask(n.current,o)},[]),r=a.useCallback(o=>{gi.unsubscribeTask(n.current,o)},[]);return a.useEffect(()=>{gi.setProjectId(e??null)},[e]),a.useEffect(()=>()=>{gi.cleanupHook(n.current)},[]),{badgeUpdates:s.badgeUpdates,isConnected:s.isConnected,subscribeToBadge:i,unsubscribeFromBadge:r}}function Br(e,n,s,i){return e===void 0||!n?s:!i||n>=i?e??void 0:s}function oj({taskId:e,prInfo:n,issueInfo:s,updatedAt:i,isInViewport:r,projectId:o}){const{badgeUpdates:l,subscribeToBadge:c,unsubscribeFromBadge:u}=Ah(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=Br(m?.prInfo,m?.timestamp,n,n?.lastCheckedAt??i),g=Br(m?.issueInfo,m?.timestamp,s,s?.lastCheckedAt??i);return!h&&!g?null:t.jsx(_h,{prInfo:h,issueInfo:g})}const lj=a.memo(oj);lj.displayName="TaskCardBadge";const cj={sm:16,md:20,lg:24};function dj({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 Nd({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 Sd({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 uj({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 mj({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 hj({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 Po({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 Cd({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 Ed({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 pj({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 fj({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 Md({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 _d({size:e,color:n,label:s="Anthropic — via Claude CLI"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"claude-cli-icon","aria-label":s,children:[t.jsx("g",{transform:"translate(-1 -1.5) scale(0.82)",children:t.jsx("path",{d:"M17.3041 3.541h-3.6718l6.696 16.918H24Zm-10.6082 0L0 20.459h3.7442l1.3693-3.5527h7.0052l1.3693 3.5528h3.7442L10.5363 3.5409Zm-.3712 10.2232 2.2914-5.9456 2.2914 5.9456Z",fill:n})}),t.jsx("rect",{x:"13",y:"13",width:"10",height:"9",rx:"1.5",fill:n}),t.jsx("path",{d:"M15.2 16.2l1.6 1.4-1.6 1.4M18.6 19.6h2.4",stroke:"var(--provider-icon-contrast)",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})]})}const gj={anthropic:{component:dj,color:"var(--provider-anthropic)"},"claude-cli":{component:_d,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"pi-claude-cli":{component:_d,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},openai:{component:Nd,color:"var(--provider-openai)"},"openai-codex":{component:Nd,color:"var(--provider-openai)",label:"OpenAI Codex"},google:{component:Sd,color:"var(--provider-gemini)"},gemini:{component:Sd,color:"var(--provider-gemini)"},ollama:{component:uj,color:"var(--text)"},github:{component:Md,color:"var(--text)"},"github-copilot":{component:Md,color:"var(--text)",label:"GitHub Copilot"},openrouter:{component:fj,color:"var(--provider-openrouter)"},minimax:{component:mj,color:"var(--provider-minimax)"},zai:{component:hj,color:"var(--provider-zai)"},kimi:{component:Po,color:"var(--provider-kimi)"},moonshot:{component:Po,color:"var(--provider-kimi)"},"kimi-coding":{component:Po,color:"var(--provider-kimi)",label:"Kimi"},bedrock:{component:Cd,color:"var(--provider-bedrock)"},"amazon-bedrock":{component:Cd,color:"var(--provider-bedrock)",label:"Amazon Bedrock"},xai:{component:Ed,color:"var(--text)"},grok:{component:Ed,color:"var(--text)",label:"xAI"},opencode:{component:pj,color:"var(--provider-opencode)"}};function Mn({provider:e,size:n="sm"}){const s=e.toLowerCase(),i=gj[s],r=i?.component,o=i?.color??"var(--text-muted)",l=i?.label,c=cj[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(ug,{size:c})})}const ks={data:new Map,pendingPromise:null,lastFetchTime:null},bj=5e3;function Tr(e,n){return n?`${n}::${e}`:e}function xj(e,n){const s=ks.data.get(Tr(e,n));if(!(!s||Date.now()-s.timestamp>bj))return s}function vj(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 lv(c,e)}catch(h){d=h instanceof Error?h:new Error(String(h));const g=xe(h);if(g?.includes("429")||g?.toLowerCase().includes("rate limit")){const p=Math.min(1e3*Math.pow(2,m),3e4);await new Promise(f=>setTimeout(f,p));continue}break}if(d)throw d;return{}},[e]),o=a.useCallback(async c=>{if(c.length===0)return;const d=Date.now()-5e3;if(c.every(g=>{const p=ks.data.get(Tr(g,e));return p&&p.timestamp>d})&&ks.lastFetchTime&&ks.lastFetchTime>d)return;if(i.current&&(clearTimeout(i.current),i.current=null),ks.pendingPromise){s(!0);try{await ks.pendingPromise}finally{s(!1)}return}s(!0);const h=r(c);ks.pendingPromise=h;try{const g=await h,p=Date.now();for(const[f,b]of Object.entries(g))ks.data.set(Tr(f,e),{result:b,timestamp:p});ks.lastFetchTime=p}catch{}finally{ks.pendingPromise=null,s(!1)}},[r,e]),l=a.useCallback(c=>ks.data.get(Tr(c,e)),[e]);return{fetchBatch:o,isLoading:n,lastFetchTime:ks.lastFetchTime,getBatchData:l}}const Fl=new Map,yj=3e4;function Th(e,n,s,i){return`${e}:${n??""}:${s??""}:${i??""}`}function kj(e,n,s,i){const r=Th(e,n,s,i),o=Fl.get(r);return o?Date.now()>o.expiresAt?(Fl.delete(r),null):o.stats:null}function jj(e,n,s,i,r){const o=Th(e,n,s,i);Fl.set(o,{stats:r,expiresAt:Date.now()+yj})}function wj(e,n,s,i,r={}){const o=r.enabled??!0,l=r.worktree,c=r.stepVersion,u=r.pollIntervalMs,[d,m]=a.useState(null),[h,g]=a.useState(!1);return a.useEffect(()=>{if(!o){m(null),g(!1);return}const p=n==="done"&&!!s,f=(n==="in-progress"||n==="in-review")&&!!l;if(!e||!p&&!f){m(null),g(!1);return}const b=f?l:void 0,v=c!==void 0?String(c):void 0;let x=!1;async function k(y=!1){if(!y){const R=kj(e,i,b,v);if(R){x||(m(R),g(!1));return}}g(!0);try{const R=await jh(e,b,i);x||(m(R.stats),jj(e,i,b,v,R.stats))}catch{x||m(null)}finally{x||g(!1)}}k();let M;return u&&f&&(M=setInterval(()=>{k(!0)},u)),()=>{x=!0,M&&clearInterval(M)}},[e,n,s,i,o,l,c,u]),{stats:d,loading:h}}const Nj=new Set(["failed","stuck-killed"]);function Hr(e,n,s){if(e.column!=="in-progress"||e.status&&Nj.has(e.status)||!n||n<=0)return!1;const i=new Date(e.updatedAt).getTime();return(s??Date.now())-i>n}function Sj(e){switch(e){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function Cj(e){return e==="done"||e==="skipped"}function Ej(e,n,s){const i=s?.get(e)?.trim();if(i)return i;const r=n?.workflowStepName?.trim();return r||e}function Rh(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:Ej(u,d,n),status:d?Sj(d.status):"pending",source:"workflow",phase:d?.phase??"pre-merge"}}),o=[...s,...r],l=o.length,c=o.filter(u=>Cj(u.status)).length;return{total:l,completed:c,items:o}}const Ol=new Map;async function Mj(e,n){const s=Ol.get(e);if(s)return s;try{const i=await wh(e,n);return Ol.set(e,i.title),i.title}catch{return e}}const Ad=12;function _j(e){return e.length<=Ad?e:e.slice(0,Ad-3)+"..."}const Ul=new Map;async function Aj(e,n){const s=Ul.get(e);if(s)return s;try{const i=await yh(e,n);return Ul.set(e,i.name),i.name}catch{return e}}function Tj(e){return typeof e=="string"&&uc.includes(e)?e:cs}function Rj(e,n){return e.length<=n?e:e.slice(0,n-3)+"..."}const Ij=new Set(["triage","todo"]),Td=new Set(["planning","researching","executing","finalizing","merging","specifying"]),Pj={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"},$j=new Set(["in-progress","done"]),Dj=3e4;function mc(e){if(!e)return null;const n=Date.parse(e);return Number.isFinite(n)?n:null}function Rd(e){const n=e.columnMovedAt??e.updatedAt??e.createdAt,s=mc(n);if(s==null)return null;const i=Date.now();return s>i?null:s}function Lj(e){const n=mc(e.columnMovedAt??e.updatedAt);if(n==null)return null;const s=Date.now();return n>s?null:n}function zj(e,n){return[e.createdAt].map(mc).filter(r=>r!=null).find(r=>r<=n)??null}function Id(e){if(!Number.isFinite(e)||e<0)return"";const n=Math.floor(e/6e4);if(n<1)return"<1m";if(n<60)return`${n}m`;const s=Math.floor(n/60);return s<24?`${s}h`:`${Math.floor(s/24)}d`}function Pd(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 Fj(e,n){return e.length!==n.length?!1:e.every((s,i)=>s.name===n[i]?.name&&s.status===n[i]?.status)}function Oj(e,n){return e.length!==n.length?!1:e.every((s,i)=>s===n[i])}function Uj(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>s===n[i])}function Bj(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 Hj(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 qj(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 Vj(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 Wj(e,n){const s=e.task,i=n.task;return e.queued===n.queued&&e.projectId===n.projectId&&e.globalPaused===n.globalPaused&&e.taskStuckTimeoutMs===n.taskStuckTimeoutMs&&e.onOpenDetail===n.onOpenDetail&&e.addToast===n.addToast&&e.onUpdateTask===n.onUpdateTask&&e.onArchiveTask===n.onArchiveTask&&e.onUnarchiveTask===n.onUnarchiveTask&&e.onDeleteTask===n.onDeleteTask&&e.onOpenDetailWithTab===n.onOpenDetailWithTab&&e.onOpenMission===n.onOpenMission&&e.onMoveTask===n.onMoveTask&&e.workflowStepNameLookup===n.workflowStepNameLookup&&s.id===i.id&&s.title===i.title&&s.description===i.description&&s.column===i.column&&s.columnMovedAt===i.columnMovedAt&&s.updatedAt===i.updatedAt&&s.createdAt===i.createdAt&&s.status===i.status&&s.priority===i.priority&&s.executionMode===i.executionMode&&s.paused===i.paused&&s.error===i.error&&s.size===i.size&&s.blockedBy===i.blockedBy&&s.worktree===i.worktree&&s.baseBranch===i.baseBranch&&s.breakIntoSubtasks===i.breakIntoSubtasks&&s.currentStep===i.currentStep&&s.modelProvider===i.modelProvider&&s.modelId===i.modelId&&s.validatorModelProvider===i.validatorModelProvider&&s.validatorModelId===i.validatorModelId&&s.planningModelProvider===i.planningModelProvider&&s.planningModelId===i.planningModelId&&s.reviewLevel===i.reviewLevel&&s.missionId===i.missionId&&s.assignedAgentId===i.assignedAgentId&&s.mergeRetries===i.mergeRetries&&qj(s.attachments,i.attachments)&&Vj(s.comments,i.comments)&&Oj(s.dependencies,i.dependencies)&&Fj(s.steps,i.steps)&&Uj(s.enabledWorkflowSteps,i.enabledWorkflowSteps)&&Hj(s.workflowStepResults,i.workflowStepResults)&&Pd(s.prInfo,i.prInfo)&&Pd(s.issueInfo,i.issueInfo)}function Gj({task:e,projectId:n,queued:s,onOpenDetail:i,addToast:r,globalPaused:o,onUpdateTask:l,onArchiveTask:c,onUnarchiveTask:u,onDeleteTask:d,onOpenDetailWithTab:m,taskStuckTimeoutMs:h,onOpenMission:g,onMoveTask:p,lastFetchTimeMs:f,workflowStepNameLookup:b}){const[v,x]=a.useState(!1),[k,M]=a.useState(!1),[y,R]=a.useState(!1),[j,C]=a.useState(e.description||""),[S,P]=a.useState(!1),[T,_]=a.useState(e.column==="in-progress"||e.column==="triage"&&e.steps.some(N=>N.status==="done"||N.status==="skipped")),[L,G]=a.useState(null),[$,I]=a.useState(null),[w,q]=a.useState(!1),[W,B]=a.useState(()=>Date.now()),A=a.useRef(null),z=a.useRef(!1),X=a.useRef(null),E=a.useRef(null),[U,pe]=a.useState(!1),{badgeUpdates:ie,subscribeToBadge:re,unsubscribeFromBadge:F}=Ah(n),ce=a.useRef(null),ae=a.useRef(!1),Q=a.useCallback(N=>N instanceof Element?!!N.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);a.useEffect(()=>{C(e.description||"")},[e.id,e.description]),a.useEffect(()=>{if(!w)return;const N=H=>{E.current&&!E.current.contains(H.target)&&q(!1)};return document.addEventListener("click",N),()=>document.removeEventListener("click",N)},[w]),a.useEffect(()=>{if(!e.missionId){G(null);return}const N=Ol.get(e.missionId);if(N){G(N);return}let H=!1;return Mj(e.missionId,n).then(Ae=>{H||G(Ae)}),()=>{H=!0}},[e.missionId,n]),a.useEffect(()=>{if(!e.assignedAgentId){I(null);return}const N=Ul.get(e.assignedAgentId);if(N){I(N);return}I(null);let H=!1;return Aj(e.assignedAgentId,n).then(Ae=>{H||I(Ae)}),()=>{H=!0}},[e.assignedAgentId,n]),a.useEffect(()=>{if(y&&A.current){const N=A.current;N.focus(),N.style.height="auto",N.style.height=N.scrollHeight+"px"}},[y]),a.useEffect(()=>{if(typeof IntersectionObserver>"u"){pe(!0);return}const N=X.current;if(!N)return;const H=new IntersectionObserver(([Ae])=>{pe(Ae?.isIntersecting??!0)},{rootMargin:"200px"});return H.observe(N),()=>H.disconnect()},[y,e.id]);const de=a.useCallback(N=>{N.dataTransfer.setData("text/plain",e.id),N.dataTransfer.effectAllowed="move",x(!0)},[e.id]),Te=a.useCallback(()=>{x(!1)},[]),fe=a.useCallback(N=>N.dataTransfer.types.includes("Files"),[]),Se=a.useCallback(N=>{fe(N)&&(N.preventDefault(),N.stopPropagation(),N.dataTransfer.dropEffect="copy",M(!0))},[fe]),te=a.useCallback(N=>{fe(N)&&(N.preventDefault(),N.stopPropagation(),M(!1))},[fe]),we=a.useCallback(async N=>{if(!fe(N))return;N.preventDefault(),N.stopPropagation(),M(!1);const H=Array.from(N.dataTransfer.files);for(const Ae of H)try{await Ua(e.id,Ae,n),r(`Attached ${Ae.name} to ${e.id}`,"success")}catch(ot){r(`Failed to attach ${Ae.name}: ${xe(ot)}`,"error")}},[e.id,fe,r]),Pe=a.useCallback(()=>{y||i(e)},[e,i,y]),We=a.useCallback(N=>{if(z.current){z.current=!1;return}Q(N.target)||Pe()},[Pe,Q]),Ke=a.useCallback(N=>{const H=N.touches[0];H&&(ce.current={x:H.clientX,y:H.clientY,time:Date.now()},ae.current=!1)},[]),Ne=a.useCallback(N=>{if(!ce.current)return;const H=N.touches[0];if(!H)return;const Ae=Math.abs(H.clientX-ce.current.x),ot=Math.abs(H.clientY-ce.current.y);(Ae>$d||ot>$d)&&(ae.current=!0)},[]),_e=a.useCallback(N=>{if(Q(N.target)||!ce.current)return;const Ae=Date.now()-ce.current.time<Kj,ot=!ae.current;Ae&&ot&&(z.current=!0,Pe()),ce.current=null,ae.current=!1},[Pe,Q]),Oe=a.useCallback(async(N,H)=>{N.stopPropagation();try{const Ae=await Or(H,n);i(Ae)}catch{r(`Failed to load dependency ${H}`,"error")}},[i,r]),ye=e.status==="failed",De=e.paused===!0,se=Tj(e.priority),J=se!==cs,me=Hr(e,h,f),ee=e.column==="triage"&&e.status==="awaiting-approval",he=e.column==="archived",le=!o&&!s&&!ye&&!De&&!me&&!ee&&(e.column==="in-progress"||Td.has(e.status)),Ie=!s&&!De&&!y&&!he,Ze=Ij.has(e.column)&&!le&&!De&&!s&&l,at=!!(e.prInfo||e.issueInfo),oe=!!(e.assignedAgentId&&$===null),Z=a.useMemo(()=>{const N=[];return e.modelProvider&&N.push(e.modelProvider),e.validatorModelProvider&&!N.includes(e.validatorModelProvider)&&N.push(e.validatorModelProvider),e.planningModelProvider&&!N.includes(e.planningModelProvider)&&N.push(e.planningModelProvider),N},[e.modelProvider,e.validatorModelProvider,e.planningModelProvider]),ue=a.useMemo(()=>Rh(e,b),[e.steps,e.enabledWorkflowSteps,e.workflowStepResults,b]),Ce=ue.total>0&&(e.status==="executing"||e.column==="in-progress");a.useEffect(()=>{if(e.column!=="in-progress"||Rd(e)==null)return;B(Date.now());const H=window.setInterval(()=>{B(Date.now())},Dj);return()=>window.clearInterval(H)},[e.column,e.columnMovedAt,e.updatedAt,e.createdAt]);const $e=a.useMemo(()=>{if(!$j.has(e.column))return null;if(e.column==="in-progress"){const kt=Rd(e);if(kt==null)return null;const Ot=Id(W-kt);return Ot?{label:Ot,title:`In progress since ${new Date(kt).toLocaleString()}`,ariaLabel:`Elapsed time ${Ot}. In progress since ${new Date(kt).toLocaleString()}`}:null}const N=Lj(e);if(N==null)return null;const H=zj(e,N);if(H==null)return null;const Ae=Id(N-H);if(!Ae)return null;const ot=new Date(N).toLocaleString();return{label:Ae,title:`Processing took ${Ae}. Completed ${ot}`,ariaLabel:`Completed processing duration ${Ae}. Completed ${ot}`}},[e.column,e.columnMovedAt,e.updatedAt,e.createdAt,W]);a.useEffect(()=>{if(!at||!U){F(e.id);return}return re(e.id),()=>{F(e.id)}},[at,U,re,e.id,F]);const ve=ie.get(`${n??"default"}:${e.id}`),Ge=e.column==="in-progress"||e.column==="in-review",je=a.useMemo(()=>e.steps.map(N=>`${N.name}:${N.status}`).join("|"),[e.steps]),{stats:Ue}=wj(e.id,e.column,e.mergeDetails?.commitSha,n,{enabled:U,worktree:e.worktree,stepVersion:Ge?je:void 0,pollIntervalMs:Ge?3e4:void 0}),He=a.useMemo(()=>xj(e.id,n),[e.id,n]),ge=a.useMemo(()=>{const N=ve?.prInfo,H=ve?.timestamp,Ae=He?.result?.prInfo,ot=He?.timestamp?new Date(He.timestamp).toISOString():void 0,kt=e.prInfo,Ot=e.prInfo?.lastCheckedAt??e.updatedAt;let sn=Br(N,H,kt,Ot);const Rt=H&&H>=Ot?H:Ot;return Ae&&ot&&(!Rt||ot>Rt)&&(sn=Ae),sn},[ve,He,e.prInfo,e.updatedAt]),Fe=a.useMemo(()=>{const N=ve?.issueInfo,H=ve?.timestamp,Ae=He?.result?.issueInfo,ot=He?.timestamp?new Date(He.timestamp).toISOString():void 0,kt=e.issueInfo,Ot=e.issueInfo?.lastCheckedAt??e.updatedAt;let sn=Br(N,H,kt,Ot);const Rt=H&&H>=Ot?H:Ot;return Ae&&ot&&(!Rt||ot>Rt)&&(sn=Ae),sn},[ve,He,e.issueInfo,e.updatedAt]),be=a.useCallback(N=>{N?.stopPropagation(),!(!Ze||S)&&(R(!0),C(e.description||""))},[Ze,S,e.description]),Je=a.useCallback(()=>{R(!1),C(e.description||"")},[e.description]),st=a.useCallback(()=>j!==(e.description||""),[j,e.description]),dt=a.useCallback(async()=>{if(!(!l||S)){if(!st()){Je();return}P(!0);try{await l(e.id,{description:j.trim()||void 0}),r(`Updated ${e.id}`,"success"),R(!1)}catch(N){r(`Failed to update ${e.id}: ${xe(N)}`,"error")}finally{P(!1)}}},[l,e.id,j,S,st,Je,r]),Tt=a.useCallback(N=>{N.key==="Enter"&&!N.shiftKey?(N.preventDefault(),dt()):N.key==="Escape"&&(N.preventDefault(),Je())},[dt,Je]),$t=a.useCallback(()=>{setTimeout(()=>{const N=document.activeElement;N===A.current||N?.closest(".card-editing-content")||(st()?dt():Je())},0)},[st,dt,Je]),Dt=a.useCallback(N=>{Ze&&(N.stopPropagation(),be(N))},[Ze,be]),Bt=a.useCallback(N=>{N.stopPropagation(),be(N)},[be]),qt=a.useCallback(N=>{C(N.target.value);const H=N.target;H.style.height="auto",H.style.height=H.scrollHeight+"px"},[]),Lt=a.useCallback(N=>{N.stopPropagation(),c&&c(e.id).then(()=>{r(`Archived ${e.id}`,"success")}).catch(H=>{r(`Failed to archive ${e.id}: ${xe(H)}`,"error")})},[r,c,e.id]),Ct=a.useCallback(N=>{N.stopPropagation(),u&&u(e.id).then(()=>{r(`Unarchived ${e.id}`,"success")}).catch(H=>{r(`Failed to unarchive ${e.id}: ${xe(H)}`,"error")})},[r,u,e.id]),xt=a.useCallback(N=>{N.stopPropagation(),d&&window.confirm(`Delete ${e.id}?`)&&d(e.id).then(()=>{r(`Deleted ${e.id}`,"success")}).catch(H=>{const Ae=Bj(H);if(!Ae||Ae.dependentIds.length===0){r(`Failed to delete ${e.id}: ${xe(H)}`,"error");return}const ot=Ae.dependentIds.join(", ");window.confirm(`${e.id} is a dependency of ${ot}.
|
|
576
|
-
|
|
577
|
-
Delete anyway by removing these dependency references first?`)&&d(e.id,{removeDependencyReferences:!0}).then(()=>{r(`Deleted ${e.id} after removing dependency references`,"success")}).catch(Ot=>{r(`Failed to delete ${e.id}: ${xe(Ot)}`,"error")})})},[r,d,e.id]),Et=a.useCallback(N=>{N.stopPropagation(),m?.(e,"changes")},[e,m]),Le=a.useCallback(N=>{N.stopPropagation(),_(H=>!H)},[]),gt=a.useCallback(N=>{N.stopPropagation(),e.missionId&&g&&g(e.missionId)},[e.missionId,g]),ut=a.useCallback(N=>{N.stopPropagation(),q(H=>!H)},[]),Me=a.useCallback((N,H)=>{N.stopPropagation(),q(!1),p&&p(e.id,H).then(()=>{r(`Moved ${e.id} to ${Pn[H]}`,"success")}).catch(Ae=>{r(`Failed to move ${e.id}: ${xe(Ae)}`,"error")})},[r,p,e.id]),Qe=`card${v?" dragging":""}${s?" queued":""}${le?" agent-active":""}${ye?" failed":""}${De?" paused":""}${me?" stuck":""}${ee?" awaiting-approval":""}${k?" file-drop-target":""}${y?" card-editing":""}${S?" card-saving":""}`,rt=(()=>{if(e.worktree&&e.column==="in-progress"){const N=Ue?.filesChanged;return N==null||N===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:Et,disabled:!m,children:[t.jsx(jn,{size:12}),t.jsxs("span",{children:[N," ",N===1?"file":"files"," changed"]})]})}if(e.column==="in-review"){const N=Ue?.filesChanged,H=N==null?e.modifiedFiles?.length:void 0,Ae=N??H;return Ae==null||Ae===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:Et,disabled:!m,children:[t.jsx(jn,{size:12}),t.jsxs("span",{children:[Ae," ",Ae===1?"file":"files"," changed"]})]})}if(e.column==="done"){const N=Ue?.filesChanged,H=e.mergeDetails?.filesChanged,Ae=N??H;if(Ae!=null&&Ae>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:Et,disabled:!m,children:[t.jsx(jn,{size:12}),t.jsxs("span",{children:[Ae," ",Ae===1?"file":"files"," changed"]})]});const ot=e.modifiedFiles?.length;if(ot!=null&&ot>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:Et,disabled:!m,children:[t.jsx(jn,{size:12}),t.jsxs("span",{children:[ot," ",ot===1?"file":"files"," changed"]})]})}return null})();return y?t.jsx("div",{ref:X,className:Qe,"data-id":e.id,onDoubleClick:Dt,children:t.jsxs("div",{className:"card-editing-content",children:[t.jsx("textarea",{ref:A,className:"card-edit-desc-textarea",placeholder:"Task description",value:j,onChange:qt,onKeyDown:Tt,onBlur:$t,disabled:S,rows:4}),S&&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:X,className:Qe,"data-id":e.id,draggable:Ie,onDragStart:Ie?de:void 0,onDragEnd:Ie?Te:void 0,onDragOver:Se,onDragLeave:te,onDrop:we,onClick:We,onTouchStart:Ke,onTouchMove:Ne,onTouchEnd:_e,onDoubleClick:Dt,children:[t.jsxs("div",{className:"card-header",children:[t.jsx("span",{className:"card-id",children:e.id}),De&&t.jsx("span",{className:"card-status-badge paused",children:"paused"}),!De&&e.status&&e.status!=="queued"&&t.jsx("span",{className:`card-status-badge card-status-badge--${e.column}${ee?" awaiting-approval":""}${Td.has(e.status)?" pulsing":""}${ye?" failed":""}${me?" stuck":""}`,children:me?"Stuck":ee?"Awaiting Approval":e.status}),me&&(De||!e.status||e.status==="queued")&&t.jsx("span",{className:"card-status-badge stuck",children:"Stuck"}),at&&t.jsx(_h,{prInfo:ge,issueInfo:Fe}),J&&t.jsx("span",{className:`card-priority-badge card-priority-badge--${se}`,children:se}),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:gt,title:`Mission: ${L??e.missionId}`,role:g?"button":void 0,tabIndex:g?0:void 0,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[t.jsx(ns,{size:11}),_j(L??e.missionId)]}),t.jsxs("div",{className:"card-header-actions",children:[Ze&&t.jsx("button",{className:"card-edit-btn",onClick:Bt,title:"Edit task","aria-label":"Edit task",children:t.jsx(Hn,{size:12})}),e.column==="triage"&&d&&t.jsx("button",{className:"card-delete-btn",onClick:xt,title:"Delete task","aria-label":"Delete task",children:t.jsx(Ht,{size:12})}),e.column==="done"&&c&&t.jsx("button",{className:"card-archive-btn",onClick:Lt,title:"Archive task","aria-label":"Archive task",children:"Archive"}),e.column==="archived"&&u&&t.jsx("button",{className:"card-unarchive-btn",onClick:Ct,title:"Unarchive task","aria-label":"Unarchive task",children:"Unarchive"}),e.column==="in-progress"&&p&&t.jsxs("div",{className:"card-send-back",ref:E,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:ut,title:"Send back","aria-label":"Send back","aria-haspopup":"menu","aria-expanded":w,children:["Send back",t.jsx(zt,{size:10})]}),w&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:zl["in-progress"].filter(N=>N!=="in-review").map(N=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:H=>Me(H,N),children:Pn[N]},N))})]}),e.column==="in-review"&&p&&t.jsxs("div",{className:"card-send-back",ref:E,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:ut,title:"Move task","aria-label":"Move task","aria-haspopup":"menu","aria-expanded":w,children:["Move",t.jsx(zt,{size:10})]}),w&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:zl["in-review"].map(N=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:H=>Me(H,N),children:N==="done"?"Done (no merge)":Pn[N]},N))})]}),e.size&&t.jsx("span",{className:`card-size-badge size-${e.size.toLowerCase()}`,children:e.size})]})]}),ye&&e.error&&t.jsxs("div",{className:"card-error",title:e.error,children:[t.jsx("span",{className:"card-error-icon",children:"⚠"}),t.jsx("span",{className:"card-error-text",children:e.error.length>60?e.error.slice(0,60)+"…":e.error})]}),t.jsx("div",{className:"card-title",title:e.title||e.description||void 0,children:Ld(e.title,Dd)||Ld(e.description,Dd)||e.id}),Ce&&(()=>{const N=ue.completed/ue.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:`${N}%`,backgroundColor:Pj[e.column]}})}),t.jsxs("span",{className:"card-progress-label",children:[ue.completed,"/",ue.total]})]}),t.jsxs("button",{type:"button",className:"card-steps-toggle",onClick:Le,"aria-expanded":T,"aria-label":T?"Hide steps":"Show steps",children:[t.jsxs("span",{children:[ue.total," step",ue.total===1?"":"s"]}),t.jsx(zt,{size:14,className:`card-steps-toggle-icon${T?" expanded":""}`})]}),T&&t.jsx("div",{className:"card-steps-list",children:ue.items.map(H=>{const Ae=H.source==="workflow"&&H.status==="failed";return t.jsxs("div",{className:"card-step-item",children:[t.jsx("span",{className:`card-step-dot card-step-dot--${H.status}${Ae?" card-step-dot--workflow-failed":""}`,"aria-hidden":"true"}),t.jsx("span",{className:`card-step-name${H.status==="done"?" completed":""}`,children:H.name}),H.source==="workflow"&&t.jsx("span",{className:`card-step-workflow-badge card-step-workflow-badge--${H.phase}`,title:"Workflow check",children:"workflow"})]},H.id)})})]})})(),(rt||$e)&&t.jsxs("div",{className:"card-footer-row",children:[rt,$e&&t.jsxs("span",{className:"card-time-indicator",title:$e.title,"aria-label":$e.ariaLabel,children:[t.jsx(ji,{size:12}),t.jsx("span",{children:$e.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(N=>t.jsxs("span",{className:"card-dep-badge clickable",onClick:H=>void Oe(H,N),title:`Click to view ${N}`,children:[t.jsx(Wi,{size:12,style:{verticalAlign:"middle"}})," ",N]},N))}),e.blockedBy&&t.jsxs("span",{className:"card-scope-badge","data-tooltip":`Blocked by ${e.blockedBy} (file overlap)`,children:[t.jsx(Si,{size:12,style:{verticalAlign:"middle"}})," ",e.blockedBy]}),(s||e.status==="queued")&&e.column!=="in-progress"&&t.jsxs("span",{className:"queued-badge",children:[t.jsx(ji,{size:12,style:{verticalAlign:"middle"}})," Queued"]})]}),(e.assignedAgentId||Z.length>0)&&t.jsxs("div",{className:"card-agent-row",children:[Z.length>0&&t.jsx("span",{className:"card-provider-icons","data-testid":"card-provider-icons",children:Z.map(N=>t.jsx(Mn,{provider:N,size:"sm"},N))}),e.assignedAgentId&&t.jsxs("span",{className:`card-agent-badge${oe?" card-agent-badge--loading":""}`,title:`Assigned to ${$??e.assignedAgentId}`,children:[t.jsx(an,{size:11}),t.jsx("span",{className:"card-agent-badge-text",children:Rj($??e.assignedAgentId,15)})]})]}),t.jsx(co,{slotId:"task-card-badge",projectId:n})]})}const $d=10,Kj=300,Dd=140;function Ld(e,n){return e?e.length>n?e.slice(0,n)+"…":e:""}const qr=a.memo(Gj,Wj);qr.displayName="TaskCard";function Jj({label:e,activeTasks:n,queuedTasks:s,projectId:i,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onOpenDetailWithTab:u,taskStuckTimeoutMs:d,onOpenMission:m,lastFetchTimeMs:h,workflowStepNameLookup:g}){return t.jsxs("div",{className:"worktree-group",children:[t.jsxs("div",{className:"worktree-group-header",children:[t.jsx("span",{className:"worktree-icon",children:e==="Up Next"||e==="Unassigned"?t.jsx(ig,{size:14}):t.jsx(Os,{size:14})}),t.jsx("span",{className:"worktree-label",children:e})]}),n.map(p=>t.jsx(qr,{task:p,projectId:i,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onOpenDetailWithTab:u,taskStuckTimeoutMs:d,onOpenMission:m,lastFetchTimeMs:h,workflowStepNameLookup:g},p.id)),s.map(p=>t.jsx(qr,{task:p,projectId:i,queued:!0,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onOpenDetailWithTab:u,taskStuckTimeoutMs:d,onOpenMission:m,lastFetchTimeMs:h,workflowStepNameLookup:g},p.id))]})}const Ih=a.memo(Jj);Ih.displayName="WorktreeGroup";function zd(e){return e.toLowerCase().replace(/[-_./]/g,"")}function Yj(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 Qj(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 Xj(e,n){const s=zd(e),i=zd(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&&Yj(s,o)||s.length>=4&&Qj(s,o,1))return!0;return!1}function Zj(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=>Xj(o,r))})}function wn({models:e,value:n,onChange:s,placeholder:i="Select a model…",disabled:r=!1,id:o,label:l,favoriteProviders:c=[],onToggleFavorite:u,favoriteModels:d=[],onToggleModelFavorite:m,noChangeValue:h,noChangeLabel:g="No change"}){const[p,f]=a.useState(!1),[b,v]=a.useState(""),[x,k]=a.useState(0),[M,y]=a.useState(null),[R,j]=a.useState(null),C=a.useRef(null),S=a.useRef(null),P=a.useRef(null),T=a.useRef(null),_=a.useRef(null),L=a.useMemo(()=>Zj(e,b),[e,b]),G=a.useMemo(()=>L.reduce((Q,de)=>((Q[de.provider]??=[]).push(de),Q),{}),[L]),$=a.useMemo(()=>{const Q=[];for(const de of d){const Te=de.indexOf("/");if(Te===-1)continue;const fe=de.slice(0,Te),Se=de.slice(Te+1),te=L.find(we=>we.provider===fe&&we.id===Se);te&&Q.push({model:te,fullId:de})}return Q},[d,L]),I=a.useMemo(()=>{const Q=Object.entries(G),de=new Set(c);return Q.sort(([Te],[fe])=>{const Se=de.has(Te),te=de.has(fe);if(Se&&!te)return-1;if(!Se&&te)return 1;if(Se&&te){const we=c.indexOf(Te),Pe=c.indexOf(fe);if(we!==Pe)return we-Pe}return Te.localeCompare(fe)})},[G,c]),w=typeof h=="string"&&h.length>0,q=a.useMemo(()=>{if(!n||w&&n===h)return null;const Q=n.indexOf("/");return Q===-1?null:n.slice(0,Q)},[w,h,n]),W=a.useMemo(()=>{const Q=[];return w&&Q.push({type:"no-change",value:h,label:g}),Q.push({type:"default",value:"",label:"Use default"}),Q},[w,g,h]),B=a.useMemo(()=>{const Q=[...W];for(const{model:de,fullId:Te}of $)Q.push({type:"favorite",value:Te,label:de.name,provider:de.provider});return I.forEach(([de,Te])=>{Q.push({type:"provider",value:`__group_${de}`,label:de,provider:de}),Te.forEach(fe=>{Q.push({type:"model",value:`${fe.provider}/${fe.id}`,label:fe.name,provider:fe.provider})})}),Q},[$,I,W]),A=a.useMemo(()=>{if(w&&n===h)return g;if(!n)return"Use default";const Q=n.indexOf("/");if(Q===-1)return n;const de=n.slice(0,Q),Te=n.slice(Q+1);return e.find(Se=>Se.provider===de&&Se.id===Te)?.name||n},[w,g,h,n,e]),z=a.useMemo(()=>B.findIndex(Q=>Q.value===n),[B,n]),X=a.useCallback(()=>{const Q=window.visualViewport;return Q&&Q.height>0&&Q.width>0?{width:Q.width,height:Q.height,offsetTop:Q.offsetTop,offsetLeft:Q.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),E=a.useCallback(()=>{const{height:Q}=X(),de=typeof window.matchMedia=="function",Te=de?window.matchMedia("(max-width: 640px)").matches:!1,fe=de?window.matchMedia("(max-width: 768px)").matches:!1;return Q<=0?320:Te?Math.min(Q*.6,360):fe?Math.min(Q*.7,420):320},[X]),U=a.useCallback(()=>{const Q=S.current;if(!Q)return;const de=Q.getBoundingClientRect(),{width:Te,height:fe,offsetTop:Se,offsetLeft:te}=X(),we=16,Pe=16,We=4,Ke=E(),Ne=de.bottom-Se,_e=de.top-Se,Oe=de.left-te,ye=fe-Ne,De=_e,se=Math.max(ye-Pe-We,160),J=Math.max(De-Pe-We,160),me=ye<Ke&&De>ye,ee=Math.max(Math.min(me?J:se,Ke),160),he=Math.min(de.width,Te-we*2),le=Math.min(Math.max(Oe,we),Te-we-he)+te,Ie=me?Math.max(Pe+Se,_e-ee-We+Se):Math.min(Ne+We+Se,fe+Se-Pe-ee);y({top:Ie,left:le,width:he,maxHeight:ee})},[X,E]);a.useEffect(()=>{j(document.body)},[]),a.useEffect(()=>{if(p){const Q=B.findIndex((de,Te)=>Te>=(z>=0?z:0)&&de.type!=="provider");k(Q>=0?Q:0)}},[p,B,z]),a.useEffect(()=>{if(!p)return;U();const Q=requestAnimationFrame(()=>T.current?.focus());return()=>cancelAnimationFrame(Q)},[p,U]),a.useEffect(()=>{if(!p)return;const Q=()=>U();window.addEventListener("resize",Q),window.addEventListener("scroll",Q,!0);const de=window.visualViewport;return de&&(de.addEventListener("resize",Q),de.addEventListener("scroll",Q)),()=>{window.removeEventListener("resize",Q),window.removeEventListener("scroll",Q,!0),de&&(de.removeEventListener("resize",Q),de.removeEventListener("scroll",Q))}},[p,U]),a.useEffect(()=>{if(!p)return;const Q=de=>{const Te=de.target,fe=C.current?.contains(Te),Se=P.current?.contains(Te);!fe&&!Se&&(f(!1),v(""))};return document.addEventListener("mousedown",Q),()=>document.removeEventListener("mousedown",Q)},[p]);const pe=a.useCallback(Q=>{switch(Q.key){case"ArrowDown":if(Q.preventDefault(),!p)f(!0);else{let de=x;for(let Te=1;Te<=B.length;Te++){const fe=(x+Te)%B.length;if(B[fe]?.type!=="provider"){de=fe;break}}k(de)}break;case"ArrowUp":if(Q.preventDefault(),p){let de=x;for(let Te=1;Te<=B.length;Te++){const fe=(x-Te+B.length)%B.length;if(B[fe]?.type!=="provider"){de=fe;break}}k(de)}break;case"Enter":if(Q.preventDefault(),p){const de=B[x];de&&de.type!=="provider"&&de.type!=="favorite"&&(s(de.value),f(!1),v(""))}else f(!0);break;case"Escape":Q.preventDefault(),f(!1),v("");break;case"Tab":p&&(f(!1),v(""));break}},[p,x,B,s]),ie=a.useCallback(Q=>{s(Q),f(!1),v("")},[s]),re=a.useCallback(()=>{v(""),T.current?.focus()},[]),F=a.useCallback(()=>{r||f(Q=>!Q)},[r]);a.useEffect(()=>{if(p&&_.current){const Q=_.current.querySelector(`[data-index="${x}"]`);Q&&typeof Q.scrollIntoView=="function"&&Q.scrollIntoView({block:"nearest"})}},[x,p]);const ce=b.length>0,ae=p&&M?t.jsxs("div",{ref:P,className:"model-combobox-dropdown model-combobox-dropdown--portal",role:"listbox","data-testid":"model-combobox-portal",onKeyDown:pe,style:{top:`${M.top}px`,left:`${M.left}px`,width:`${M.width}px`,maxHeight:`${M.maxHeight}px`},children:[t.jsxs("div",{className:"model-combobox-search-wrapper",children:[t.jsx("input",{ref:T,type:"text",className:"model-combobox-search",placeholder:"Filter models…",value:b,onChange:Q=>v(Q.target.value),onClick:Q=>Q.stopPropagation()}),ce&&t.jsx("button",{type:"button",className:"model-combobox-clear",onClick:re,"aria-label":"Clear filter",children:"×"})]}),t.jsxs("div",{className:"model-combobox-results-count",children:[L.length," model",L.length!==1?"s":""]}),t.jsxs("div",{ref:_,className:"model-combobox-list",children:[W.map((Q,de)=>t.jsx("div",{"data-index":de,className:`model-combobox-option ${x===de?"model-combobox-option--highlighted":""} ${n===Q.value?"model-combobox-option--selected":""}`,onClick:()=>ie(Q.value),onMouseEnter:()=>k(de),role:"option","aria-selected":n===Q.value,children:t.jsx("span",{className:"model-combobox-option-text model-combobox-option-text--default",children:Q.label})},`${Q.type}-${Q.value}`)),$.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"model-combobox-divider"}),$.map(({model:Q,fullId:de},Te)=>{const fe=Te+W.length,Se=x===fe,te=n===de;return t.jsxs("div",{"data-index":fe,className:`model-combobox-option model-combobox-option--favorite ${Se?"model-combobox-option--highlighted":""} ${te?"model-combobox-option--selected":""}`,onClick:()=>ie(de),onMouseEnter:()=>k(fe),role:"option","aria-selected":te,children:[t.jsxs("span",{className:"model-combobox-option-main",children:[t.jsx("span",{className:"model-combobox-option-icon",children:t.jsx(Mn,{provider:Q.provider,size:"sm"})}),t.jsx("span",{className:"model-combobox-option-text",children:Q.name})]}),t.jsx("span",{className:"model-combobox-option-id",children:Q.id}),m&&t.jsx("button",{type:"button",className:"model-combobox-option-favorite model-combobox-option-favorite--active",onClick:we=>{we.stopPropagation(),m(de)},title:"Remove from favorites","aria-label":`Remove ${Q.name} from favorites`,children:"★"})]},de)}),t.jsx("div",{className:"model-combobox-divider"})]}),I.map(([Q,de])=>{const Te=B.findIndex(te=>te.value===`__group_${Q}`),fe=c.includes(Q),Se=de.filter(te=>{const we=`${te.provider}/${te.id}`;return!d.includes(we)});return Se.length===0?null:t.jsxs("div",{className:"model-combobox-group",children:[t.jsxs("div",{className:"model-combobox-optgroup","data-index":Te,children:[t.jsx(Mn,{provider:Q,size:"sm"}),t.jsx("span",{className:"model-combobox-optgroup-text",children:Q}),u&&t.jsx("button",{type:"button",className:`model-combobox-optgroup-favorite ${fe?"model-combobox-optgroup-favorite--active":""}`,onClick:te=>{te.stopPropagation(),u(Q)},title:fe?"Remove from favorites":"Add to favorites","aria-label":fe?`Remove ${Q} from favorites`:`Add ${Q} to favorites`,children:"★"})]}),Se.map(te=>{const we=`${te.provider}/${te.id}`,Pe=B.findIndex(_e=>_e.value===we),We=x===Pe,Ke=n===we,Ne=d.includes(we);return t.jsxs("div",{"data-index":Pe,className:`model-combobox-option ${We?"model-combobox-option--highlighted":""} ${Ke?"model-combobox-option--selected":""}`,onClick:()=>ie(we),onMouseEnter:()=>k(Pe),role:"option","aria-selected":Ke,children:[t.jsx("span",{className:"model-combobox-option-text",children:te.name}),t.jsx("span",{className:"model-combobox-option-id",children:te.id}),m&&t.jsx("button",{type:"button",className:`model-combobox-option-favorite ${Ne?"model-combobox-option-favorite--active":""}`,onClick:_e=>{_e.stopPropagation(),m(we)},title:Ne?"Remove from favorites":"Add to favorites","aria-label":Ne?`Remove ${te.name} from favorites`:`Add ${te.name} to favorites`,children:Ne?"★":"☆"})]},we)})]},Q)}),L.length===0&&ce&&t.jsxs("div",{className:"model-combobox-no-results",children:["No models match '",b,"'"]})]})]}):null;return t.jsxs(t.Fragment,{children:[t.jsx("div",{ref:C,className:"model-combobox",onKeyDown:pe,children:t.jsxs("button",{ref:S,type:"button",id:o,className:"model-combobox-trigger",onClick:F,disabled:r,"aria-haspopup":"listbox","aria-expanded":p,"aria-label":l,children:[q&&t.jsx("span",{className:"model-combobox-trigger-icon",children:t.jsx(Mn,{provider:q,size:"sm"})}),t.jsx("span",{className:"model-combobox-trigger-text",children:A||i}),t.jsx("span",{className:"model-combobox-trigger-arrow",children:"▼"})]})}),R&&ae?Ta.createPortal(ae,R):null]})}function hc(e,n){return typeof n!="string"||n.length===0?e:`kb:${n}:${e}`}function Nn(e,n){return typeof window>"u"?null:window.localStorage.getItem(hc(e,n))}function ts(e,n,s){typeof window>"u"||window.localStorage.setItem(hc(e,s),n)}function Ha(e,n){typeof window>"u"||window.localStorage.removeItem(hc(e,n))}const fa="kb-quick-entry-text",ew=["image/png","image/jpeg","image/gif","image/webp"];function $o(e,n){return e&&n?`${e}/${n}`:""}function Do(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 Ph({onCreate:e,addToast:n,tasks:s=[],availableModels:i,onPlanningMode:r,onSubtaskBreakdown:o,projectId:l,autoExpand:c=!0,favoriteProviders:u,favoriteModels:d,onToggleFavorite:m,onToggleModelFavorite:h}){const[g,p]=a.useState(()=>typeof window<"u"&&Nn(fa,l)||""),[f,b]=a.useState(!1),[v,x]=a.useState(!1),[k,M]=a.useState(!1),y=a.useRef(null),R=a.useRef(null),j=a.useRef(!1),C=a.useRef(l),[S,P]=a.useState([]),T=a.useRef([]),[_,L]=a.useState([]),[G,$]=a.useState(!1),[I,w]=a.useState(""),[q,W]=a.useState(null),[B,A]=a.useState([]),[z,X]=a.useState(void 0),[E,U]=a.useState(!1),[pe,ie]=a.useState(!1),[re,F]=a.useState(!1),[ce,ae]=a.useState(null),[Q,de]=a.useState(void 0),[Te,fe]=a.useState(void 0),[Se,te]=a.useState(void 0),[we,Pe]=a.useState(void 0),[We,Ke]=a.useState(void 0),[Ne,_e]=a.useState(void 0),Oe=a.useRef(null),ye=a.useRef(null),De=a.useRef(null),se=a.useRef(null),[J,me]=a.useState(null),[ee,he]=a.useState(null),le=a.useRef(null),Ie=a.useRef(null),[Ze,at]=a.useState(null),[oe]=a.useState(()=>typeof document<"u"?document.body:null),[Z,ue]=a.useState(!1),[Ce,$e]=a.useState(null),[ve,Ge]=a.useState(i??[]),[je,Ue]=a.useState([]),[He,ge]=a.useState([]),[Fe,be]=a.useState(null),[Je,st]=a.useState(void 0),[dt,Tt]=a.useState(!1),[$t,Dt]=a.useState(!1),[Bt,qt]=a.useState(!1),Lt=a.useRef(null),Ct=a.useRef(null),[xt,Et]=a.useState(null),Le=u??je,gt=d??He,ut=!e;a.useEffect(()=>{if(i)Ge(i),ue(!1),$e(null);else{let ne=!1;return ue(!0),$e(null),is().then(Ee=>{ne||(Ge(Ee.models),u||Ue(Ee.favoriteProviders),d||ge(Ee.favoriteModels))}).catch(Ee=>{ne||$e(xe(Ee)||"Failed to load models")}).finally(()=>{ne||ue(!1)}),ro(l).then(Ee=>{ne||be(Ee)}).catch(()=>{}),()=>{ne=!0}}},[i,u,d,l]);const Me=$o(Q,Te),Qe=$o(Se,we),rt=$o(We,Ne),N=!!(Q&&Te),H=!!(Se&&we),Ae=!!(We&&Ne),ot=Number(N)+Number(H)+Number(Ae),kt=Je?Fe?.modelPresets?.find(ne=>ne.id===Je)?.name??"Models":ot>0?`${ot} model${ot===1?"":"s"}`:"Models",Ot=a.useCallback((ne,Ee)=>{if(!ne||!Ee)return"Using default";const nt=ve.find(ft=>ft.provider===ne&&ft.id===Ee);return nt?`${nt.provider}/${nt.id}`:`${ne}/${Ee}`},[ve]);a.useEffect(()=>{p(Nn(fa,l)||"")},[l]),a.useEffect(()=>{typeof window<"u"&&ts(fa,g,l)},[g,l]),a.useEffect(()=>{C.current!==l&&(C.current=l,A([]),X(void 0),W(null),U(!1),me(null))},[l]),a.useEffect(()=>{typeof window<"u"&&localStorage.removeItem("kb-quick-entry-expanded")},[]),a.useEffect(()=>{T.current=S},[S]),a.useEffect(()=>()=>{T.current.forEach(ne=>URL.revokeObjectURL(ne.previewUrl))},[]);const sn=a.useCallback(()=>{const ne=y.current;if(!ne)return;ne.style.height="auto";const Ee=Math.min(ne.scrollHeight,200);ne.style.height=`${Ee}px`},[]);a.useEffect(()=>{v&&sn()},[g,v,sn]),a.useEffect(()=>{if(!f&&g===""&&y.current){const ne=setTimeout(()=>{y.current?.focus()},0);return()=>clearTimeout(ne)}},[f,g]),a.useEffect(()=>{G||w("")},[G]),a.useEffect(()=>{if(!$t)return;const ne=Ee=>{const nt=Ee.target,ft=Lt.current?.contains(nt),bt=Ct.current?.contains(nt);!ft&&!bt&&Dt(!1)};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[$t]),a.useEffect(()=>{if(!re)return;const ne=Ee=>{const nt=Ee.target,ft=Oe.current?.contains(nt),bt=ye.current?.contains(nt),on=nt instanceof Element&&nt.closest?.(".model-combobox-dropdown--portal")!=null;!ft&&!bt&&!on&&(F(!1),ae(null))};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[re]),a.useEffect(()=>{if(!E)return;const ne=Ee=>{const nt=Ee.target;De.current?.contains(nt)||se.current?.contains(nt)||(U(!1),me(null))};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[E]);const Rt=a.useCallback(()=>{S.forEach(ne=>URL.revokeObjectURL(ne.previewUrl)),P([]),R.current&&(R.current.value=""),p(""),L([]),W(null),U(!1),me(null),de(void 0),fe(void 0),te(void 0),Pe(void 0),Ke(void 0),_e(void 0),st(void 0),Tt(!1),$(!1),F(!1),he(null),ae(null),Dt(!1),qt(!1),x(!1),M(!1),j.current=!0,y.current&&(y.current.style.height="auto"),typeof window<"u"&&Ha(fa,l)},[S,l]),zn=a.useCallback(ne=>{if(!ne||ne.length===0)return;const Ee=[];for(let nt=0;nt<ne.length;nt++){const ft=ne[nt];ew.includes(ft.type)&&Ee.push({file:ft,previewUrl:URL.createObjectURL(ft)})}Ee.length>0&&P(nt=>[...nt,...Ee])},[]),Wn=a.useCallback(ne=>{f||zn(ne.clipboardData?.files)},[zn,f]),ms=a.useCallback(ne=>{P(Ee=>{const nt=Ee[ne];return nt&&URL.revokeObjectURL(nt.previewUrl),Ee.filter((ft,bt)=>bt!==ne)})},[]),pn=a.useCallback(async()=>{const ne=g.trim();if(!(!ne||f||!e)){b(!0);try{const Ee=await e({description:ne,column:"triage",dependencies:_.length?_:void 0,...q?{assignedAgentId:q}:{},modelPresetId:Je,modelProvider:N?Q:void 0,modelId:N?Te:void 0,validatorModelProvider:H?Se:void 0,validatorModelId:H?we:void 0,planningModelProvider:Ae?We:void 0,planningModelId:Ae?Ne:void 0,...dt?{executionMode:"fast"}:{}});if(Ee&&S.length>0){const nt=[];for(const ft of S)try{await Ua(Ee.id,ft.file,l)}catch{nt.push(ft.file.name)}nt.length>0&&n(`Failed to upload: ${nt.join(", ")}`,"error")}Rt()}catch(Ee){n(xe(Ee)||"Failed to create task","error")}finally{b(!1)}}},[g,f,e,_,q,N,Q,Te,H,Se,we,Ae,We,Ne,S,l,n,Rt,dt]),Fn=a.useCallback(ne=>{if(ne.key==="Enter"){if(ne.shiftKey&&v)return;ne.preventDefault(),pn()}else if(ne.key==="Escape"){if(ne.preventDefault(),ce){ae(null);return}if(re){F(!1),he(null);return}if(G){$(!1);return}if($t){Dt(!1);return}if(E){U(!1),me(null);return}g.trim()&&(p(""),y.current&&(y.current.style.height="auto"),typeof window<"u"&&Ha(fa,l)),x(!1),M(!1),y.current?.blur()}},[pn,g,v,G,E,re,ce,$t,l,M]),Sn=a.useCallback(()=>{j.current&&(j.current=!1)},[]),fn=a.useCallback(()=>{c&&x(!0)},[c]),Gn=a.useCallback(ne=>{L(Ee=>Ee.includes(ne)?Ee.filter(nt=>nt!==ne):[...Ee,ne])},[]),dn=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}},[]),Mt=a.useCallback(()=>{const ne=Oe.current;if(!ne)return;const Ee=ne.getBoundingClientRect(),{width:nt,height:ft,offsetTop:bt,offsetLeft:on}=dn(),Xt=16,cn=16,Gt=4,bn=nt<=768,Cn=Math.min(bn?ft*.6:ft*.5,360),gs=bn?Math.min(nt-Xt*2,360):Math.max(Ee.width,240),Un=Math.min(gs,Math.max(nt-Xt*2,200)),Jn=Ee.top-bt,Bn=Ee.bottom-bt,Yn=Ee.left-on,un=ft-Bn,Qn=Jn,Es=Math.max(un-cn-Gt,160),Is=Math.max(Qn-cn-Gt,160),rs=un<Cn&&Qn>un,An=Math.max(Math.min(rs?Is:Es,Cn),160),bs=Math.min(Math.max(Yn,Xt),nt-Xt-Un)+on,Tn=rs?Math.max(cn+bt,Jn-An-Gt+bt):Math.min(Bn+Gt+bt,ft+bt-cn-An);he({top:Tn,left:bs,width:Un,maxHeight:An})},[dn]),yn=a.useCallback(()=>{const ne=Lt.current?.querySelector(".refine-button");if(!ne)return;const Ee=ne.getBoundingClientRect(),{width:nt,height:ft,offsetTop:bt,offsetLeft:on}=dn(),Xt=8,cn=12,Gt=4,bn=Math.min(200,Math.max(ft-cn*2,160)),Cn=Math.min(200,nt-Xt*2),gs=Ee.top-bt,Un=Ee.bottom-bt,Jn=Ee.left-on,Bn=ft-Un,Yn=gs,un=Bn<bn&&Yn>Bn,Qn=Math.min(Math.max(Jn,Xt),nt-Xt-Cn)+on,Es=un?Math.max(cn+bt,gs-bn-Gt+bt):Math.min(Un+Gt+bt,ft+bt-cn-bn);Et({top:Es,left:Qn})},[dn]),Kn=a.useCallback(()=>{const ne=le.current;if(!ne)return;const Ee=ne.getBoundingClientRect(),{width:nt,height:ft,offsetTop:bt,offsetLeft:on}=dn(),Xt=16,cn=16,Gt=4,bn=nt<=768,Cn=Math.min(bn?ft*.6:ft*.5,320),gs=bn?Math.min(nt-Xt*2,360):Math.max(Ee.width,280),Un=Math.min(gs,Math.max(nt-Xt*2,240)),Jn=Ee.top-bt,Bn=Ee.bottom-bt,Yn=Ee.left-on,un=ft-Bn,Qn=Jn,Es=Math.max(un-cn-Gt,200),Is=Math.max(Qn-cn-Gt,200),rs=un<Cn&&Qn>un,An=Math.max(Math.min(rs?Is:Es,Cn),200),bs=Math.min(Math.max(Yn,Xt),nt-Xt-Un)+on,Tn=rs?Math.max(cn+bt,Jn-An-Gt+bt):Math.min(Bn+Gt+bt,ft+bt-cn-An);at({top:Tn,left:bs,width:Un,maxHeight:An})},[dn]),kn=a.useCallback(()=>{const ne=De.current?.querySelector("button");if(!ne)return;const Ee=ne.getBoundingClientRect(),{width:nt,height:ft,offsetTop:bt,offsetLeft:on}=dn(),Xt=16,cn=16,Gt=4,bn=nt<=768,Cn=Math.min(bn?ft*.6:ft*.5,320),gs=bn?Math.min(nt-Xt*2,280):Math.max(Ee.width,240),Un=Math.min(gs,Math.max(nt-Xt*2,200)),Jn=Ee.top-bt,Bn=Ee.bottom-bt,Yn=Ee.left-on,un=ft-Bn,Qn=Jn,Es=Math.max(un-cn-Gt,160),Is=Math.max(Qn-cn-Gt,160),rs=un<Cn&&Qn>un,An=Math.max(Math.min(rs?Is:Es,Cn),160),bs=Math.min(Math.max(Yn,Xt),nt-Xt-Un)+on,Tn=rs?Math.max(cn+bt,Jn-An-Gt+bt):Math.min(Bn+Gt+bt,ft+bt-cn-An);me({top:Tn,left:bs,width:Un,maxHeight:An})},[dn]);a.useEffect(()=>{if(!re)return;const ne=()=>Mt();window.addEventListener("resize",ne),window.addEventListener("scroll",ne,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",ne),Ee.addEventListener("scroll",ne)),()=>{window.removeEventListener("resize",ne),window.removeEventListener("scroll",ne,!0),Ee&&(Ee.removeEventListener("resize",ne),Ee.removeEventListener("scroll",ne))}},[re,Mt]),a.useEffect(()=>{if(!$t)return;const ne=()=>yn();window.addEventListener("resize",ne),window.addEventListener("scroll",ne,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",ne),Ee.addEventListener("scroll",ne)),()=>{window.removeEventListener("resize",ne),window.removeEventListener("scroll",ne,!0),Ee&&(Ee.removeEventListener("resize",ne),Ee.removeEventListener("scroll",ne))}},[$t,yn]),a.useEffect(()=>{if(!G)return;const ne=()=>Kn();window.addEventListener("resize",ne),window.addEventListener("scroll",ne,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",ne),Ee.addEventListener("scroll",ne)),()=>{window.removeEventListener("resize",ne),window.removeEventListener("scroll",ne,!0),Ee&&(Ee.removeEventListener("resize",ne),Ee.removeEventListener("scroll",ne))}},[G,Kn]),a.useEffect(()=>{if(!E)return;const ne=()=>kn();window.addEventListener("resize",ne),window.addEventListener("scroll",ne,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",ne),Ee.addEventListener("scroll",ne)),()=>{window.removeEventListener("resize",ne),window.removeEventListener("scroll",ne,!0),Ee&&(Ee.removeEventListener("resize",ne),Ee.removeEventListener("scroll",ne))}},[E,kn]);const _n=a.useCallback(ne=>{const Ee=Do(ne);Ke(Ee.provider),_e(Ee.modelId)},[]),hs=a.useCallback(ne=>{const Ee=Do(ne);de(Ee.provider),fe(Ee.modelId)},[]),ps=a.useCallback(ne=>{const Ee=Do(ne);te(Ee.provider),Pe(Ee.modelId)},[]),On=a.useCallback(async ne=>{if(m){m(ne);return}const Ee=je,ft=Ee.includes(ne)?Ee.filter(bt=>bt!==ne):[ne,...Ee];Ue(ft);try{await nn({favoriteProviders:ft,favoriteModels:He})}catch{Ue(Ee)}},[je,He,m]),K=a.useCallback(async ne=>{if(h){h(ne);return}const Ee=He,ft=Ee.includes(ne)?Ee.filter(bt=>bt!==ne):[ne,...Ee];ge(ft);try{await nn({favoriteProviders:je,favoriteModels:ft})}catch{ge(Ee)}},[He,je,h]),ze=a.useCallback(()=>{const ne=g.trim();if(!ne){n("Enter a description first","error");return}r?.(ne),Rt()},[g,r,n,Rt]),tt=a.useCallback(()=>{const ne=g.trim();if(!ne){n("Enter a description first","error");return}o?.(ne),Rt()},[g,o,n,Rt]),et=a.useCallback(()=>{pn()},[pn]),mt=a.useCallback(async ne=>{const Ee=g.trim();if(!(!Ee||Bt)){Dt(!1),qt(!0);try{const nt=await bh(Ee,ne,l);p(nt),n("Description refined with AI","success"),y.current&&(y.current.style.height="auto",y.current.style.height=`${Math.min(y.current.scrollHeight,200)}px`)}catch(nt){const ft=xh(nt);n(ft,"error")}finally{qt(!1)}}},[g,Bt,n,l]),jt=(ne,Ee)=>ne.length>Ee?ne.slice(0,Ee)+"…":ne,_t=a.useCallback(async()=>{if(i){Ge(i),$e(null),ue(!1);return}ue(!0),$e(null);try{const ne=await is();Ge(ne.models),u||Ue(ne.favoriteProviders),d||ge(ne.favoriteModels)}catch(ne){$e(xe(ne)||"Failed to load models")}finally{ue(!1)}},[i,u,d]),gn=a.useCallback(async()=>{if(B.length>0&&z===l){U(!0),kn();return}ie(!0);try{const ne=await oa(void 0,l);A(ne),X(l),U(!0),kn()}catch(ne){const Ee=xe(ne);n(Ee?`Failed to load agents: ${Ee}`:"Failed to load agents","error"),U(!1)}finally{ie(!1)}},[B.length,z,l,n,kn]),Qt=(q?B.find(ne=>ne.id===q):void 0)?.name??q,vt=k,ct=a.useCallback(()=>{M(ne=>{const Ee=!ne;return x(Ee),Ee})},[]);return t.jsxs("div",{className:`quick-entry-box ${k?"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:y,className:`quick-entry-input ${v?"quick-entry-input--expanded":""}`,placeholder:f?"Creating...":"Add a task...",value:g,onChange:ne=>p(ne.target.value),onKeyDown:Fn,onPaste:Wn,onFocus:fn,onBlur:Sn,disabled:f||ut,"data-testid":"quick-entry-input",rows:2,"aria-controls":"quick-entry-controls","aria-expanded":k})}),t.jsx("button",{type:"button",className:"btn btn-sm quick-entry-toggle",onClick:ct,"aria-expanded":k,"aria-controls":"quick-entry-controls","data-testid":"quick-entry-toggle",title:k?"Collapse":"Expand",children:k?t.jsx(Ys,{size:14}):t.jsx(zt,{size:14})})]})}),t.jsxs("div",{id:"quick-entry-controls",className:"quick-entry-controls",hidden:!vt,"aria-hidden":!vt,children:[vt&&!f&&t.jsxs("div",{className:"quick-entry-actions","data-testid":"quick-entry-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:ze,onMouseDown:ne=>ne.preventDefault(),disabled:!g.trim(),"data-testid":"plan-button",title:"Open planning mode with current description",children:[t.jsx(Us,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Plan"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:tt,onMouseDown:ne=>ne.preventDefault(),disabled:!g.trim(),"data-testid":"subtask-button",title:"Break down into AI-generated subtasks",children:[t.jsx(no,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Subtask"]}),t.jsxs("div",{className:"refine-trigger-wrap",ref:Lt,children:[t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${Bt?"refine-button--loading":""}`,onClick:()=>{Dt(ne=>{const Ee=!ne;return Ee?yn():Et(null),Ee})},disabled:!g.trim()||Bt,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(Dn,{size:12,style:{verticalAlign:"middle"}}),Bt?"Refining...":"Refine"]}),$t&&oe&&xt&&Ta.createPortal(t.jsxs("div",{ref:Ct,className:"refine-menu refine-menu--portal",onMouseDown:ne=>ne.preventDefault(),style:{position:"fixed",top:`${xt.top}px`,left:`${xt.left}px`},children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>mt("clarify"),"data-testid":"refine-clarify",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Clarify"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Make the description clearer and more specific"})]}),t.jsxs("div",{className:"refine-menu-item",onClick:()=>mt("add-details"),"data-testid":"refine-add-details",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Add details"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Add implementation details and context"})]}),t.jsxs("div",{className:"refine-menu-item",onClick:()=>mt("expand"),"data-testid":"refine-expand",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Expand"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Expand into a more comprehensive description"})]}),t.jsxs("div",{className:"refine-menu-item",onClick:()=>mt("simplify"),"data-testid":"refine-simplify",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Simplify"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Simplify and make more concise"})]})]}),oe)]}),t.jsx("div",{className:"dep-trigger-wrap",children:t.jsxs("button",{ref:le,type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-deps",onClick:()=>{$(ne=>{const Ee=!ne;return Ee?(F(!1),he(null),ae(null),U(!1),Kn()):at(null),Ee})},children:[t.jsx(Wi,{size:12,style:{verticalAlign:"middle"}}),_.length>0?`${_.length} deps`:"Deps"]})}),G&&oe&&Ze&&(()=>{const ne=I.toLowerCase(),Ee=(ne?s.filter(nt=>nt.id.toLowerCase().includes(ne)||nt.title&&nt.title.toLowerCase().includes(ne)||nt.description&&nt.description.toLowerCase().includes(ne)):[...s]).sort((nt,ft)=>{const bt=ft.createdAt.localeCompare(nt.createdAt);if(bt!==0)return bt;const on=parseInt(nt.id.slice(nt.id.lastIndexOf("-")+1),10)||0;return(parseInt(ft.id.slice(ft.id.lastIndexOf("-")+1),10)||0)-on});return Ta.createPortal(t.jsxs("div",{ref:Ie,className:"dep-dropdown dep-dropdown--portal",onMouseDown:nt=>nt.preventDefault(),style:{position:"fixed",top:`${Ze.top}px`,left:`${Ze.left}px`,width:`${Ze.width}px`,maxHeight:Ze.maxHeight?`${Ze.maxHeight}px`:void 0,overflowY:Ze.maxHeight?"auto":void 0},children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:I,onChange:nt=>w(nt.target.value),onClick:nt=>nt.stopPropagation()}),Ee.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No existing tasks"}):Ee.map(nt=>t.jsxs("div",{className:`dep-dropdown-item${_.includes(nt.id)?" selected":""}`,onMouseDown:ft=>ft.preventDefault(),onClick:()=>Gn(nt.id),children:[t.jsx("span",{className:"dep-dropdown-id",children:nt.id}),t.jsx("span",{className:"dep-dropdown-title",children:jt(nt.title||nt.description||nt.id,60)})]},nt.id))]}),oe)})(),t.jsxs("button",{type:"button",className:"btn btn-sm","data-testid":"quick-entry-attach",onClick:()=>R.current?.click(),children:[t.jsx(xb,{size:12,style:{verticalAlign:"middle"}}),S.length>0?`Attach (${S.length})`:"Attach"]}),t.jsxs("button",{ref:Oe,type:"button",className:"btn btn-sm","data-testid":"quick-entry-models",onClick:()=>{$(!1),U(!1),ae(null),F(!0),Mt()},children:[t.jsx(Pr,{size:12,style:{verticalAlign:"middle"}}),kt]}),t.jsx("div",{className:"agent-trigger-wrap",ref:De,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{E?(U(!1),me(null)):gn()},"data-testid":"quick-entry-agent-button",children:[t.jsx(an,{size:12,style:{verticalAlign:"middle"}}),Qt?` ${Qt}`:" Agent"]})}),E&&oe&&J&&Ta.createPortal(t.jsxs("div",{ref:se,className:"dep-dropdown agent-picker-dropdown agent-picker-dropdown--portal",onMouseDown:ne=>ne.preventDefault(),style:{position:"fixed",top:`${J.top}px`,left:`${J.left}px`,width:`${J.width}px`,maxHeight:J.maxHeight?`${J.maxHeight}px`:void 0,overflowY:J.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),pe&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!pe&&B.filter(ne=>ne.state!=="terminated").map(ne=>t.jsxs("div",{className:`dep-dropdown-item${q===ne.id?" selected":""}`,onMouseDown:Ee=>Ee.preventDefault(),onClick:()=>{W(ne.id===q?null:ne.id),U(!1),me(null)},children:[t.jsx(an,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:ne.role}),t.jsx("span",{className:"dep-dropdown-title",children:ne.name})]},ne.id)),!pe&&B.filter(ne=>ne.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),q&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:ne=>ne.preventDefault(),onClick:()=>{W(null),U(!1),me(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]}),oe),t.jsx("button",{type:"button",className:`btn btn-sm ${dt?"btn-primary":""}`,onClick:()=>Tt(ne=>!ne),onMouseDown:ne=>ne.preventDefault(),"aria-pressed":dt,"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:et,onMouseDown:ne=>ne.preventDefault(),disabled:!g.trim()||f,"data-testid":"quick-entry-save",title:"Create task",children:[t.jsx(lh,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Save"]})]}),S.length>0&&t.jsx("div",{className:"inline-create-previews",children:S.map((ne,Ee)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:ne.previewUrl,alt:ne.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>ms(Ee),disabled:f,title:"Remove image","data-testid":`quick-entry-preview-remove-${Ee}`,children:"×"})]},ne.previewUrl))}),re&&oe&&ee&&Ta.createPortal(t.jsx("div",{ref:ye,className:"model-nested-menu model-nested-menu--portal",onMouseDown:ne=>ne.preventDefault(),"data-testid":"model-nested-menu",style:{position:"fixed",top:`${ee.top}px`,left:`${ee.left}px`,width:`${ee.width}px`,maxHeight:ee.maxHeight?`${ee.maxHeight}px`:void 0,overflowY:ee.maxHeight?"auto":void 0},children:ce===null?t.jsxs("div",{className:"model-menu-items",children:[t.jsxs("button",{type:"button",className:`model-menu-item ${Ae?"model-menu-item--active":""}`,onClick:()=>ae("plan"),"data-testid":"model-menu-plan",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(Us,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Plan"]}),t.jsx("span",{className:"model-menu-item-value",children:Ae?Ot(We,Ne):"Using default"}),t.jsx(en,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${N?"model-menu-item--active":""}`,onClick:()=>ae("executor"),"data-testid":"model-menu-executor",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(Dn,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Executor"]}),t.jsx("span",{className:"model-menu-item-value",children:N?Ot(Q,Te):"Using default"}),t.jsx(en,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${H?"model-menu-item--active":""}`,onClick:()=>ae("validator"),"data-testid":"model-menu-validator",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(Pr,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Validator"]}),t.jsx("span",{className:"model-menu-item-value",children:H?Ot(Se,we):"Using default"}),t.jsx(en,{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:()=>ae(null),"data-testid":"model-submenu-back",children:[t.jsx(zt,{size:12,style:{transform:"rotate(90deg)",marginRight:4}}),"Back"]}),t.jsxs("div",{className:"model-submenu-header",children:[ce==="plan"&&"Plan Model",ce==="executor"&&"Executor Model",ce==="validator"&&"Validator Model"]}),t.jsx(wn,{models:ve,value:ce==="plan"?rt:ce==="executor"?Me:Qe,onChange:ce==="plan"?_n:ce==="executor"?hs:ps,placeholder:"Using default",disabled:Z,id:`model-${ce}-select`,label:`${ce} model`,favoriteProviders:Le,onToggleFavorite:On,favoriteModels:gt,onToggleModelFavorite:K}),Ce&&t.jsxs("div",{className:"model-submenu-error",children:[t.jsx("span",{children:Ce}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:_t,children:"Retry"})]})]})}),oe)]}),t.jsx("input",{ref:R,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:ne=>{zn(ne.target.files),ne.currentTarget.value=""},"data-testid":"quick-entry-file-input"}),t.jsx("div",{className:"quick-entry-hint",children:"Enter to create · Esc to cancel"})]})}function tw(e){const n=e.replace(/\/+$/,"").split("/");return n[n.length-1]||e}function nw(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 sw(e,n,s){const i=e.filter(f=>f.worktree),r=e.filter(f=>!f.worktree),o=new Map;for(const f of i){const b=f.worktree,v=o.get(b)||[];v.push(f),o.set(b,v)}const l=new Map(n.map(f=>[f.id,f])),u=n.filter(f=>f.column==="todo").filter(f=>!f.paused&&(f.dependencies||[]).every(b=>{const v=l.get(b);return v&&(v.column==="done"||v.column==="in-review"||v.column==="archived")})),m=nw(u).map(f=>l.get(f)).filter(f=>f!==void 0&&u.includes(f)),h=[],g=Array.from(o.keys());for(const f of g)h.push({label:tw(f),activeTasks:o.get(f),queuedTasks:[]});r.length>0&&h.push({label:"Unassigned",activeTasks:r,queuedTasks:[]});const p=m.slice(0,s);return p.length>0&&h.push({label:"Up Next",activeTasks:[],queuedTasks:p}),h}const Fd=100,Lo=50,Od=25;function iw({column:e,tasks:n,projectId:s,maxConcurrent:i,onMoveTask:r,onPauseTask:o,onOpenDetail:l,addToast:c,onQuickCreate:u,onNewTask:d,autoMerge:m,onToggleAutoMerge:h,globalPaused:g,onUpdateTask:p,onArchiveTask:f,onUnarchiveTask:b,onDeleteTask:v,onArchiveAllDone:x,collapsed:k,onToggleCollapse:M,allTasks:y,availableModels:R,onPlanningMode:j,onSubtaskBreakdown:C,onOpenDetailWithTab:S,favoriteProviders:P,favoriteModels:T,onToggleFavorite:_,onToggleModelFavorite:L,isSearchActive:G,taskStuckTimeoutMs:$,onOpenMission:I,lastFetchTimeMs:w,workflowStepNameLookup:q}){const[W,B]=a.useState(!1),[A,z]=a.useState(Lo),[X,E]=a.useState(!1),[U,pe]=a.useState(!1),[ie,re]=a.useState(!1),[F,ce]=a.useState(!1),ae=a.useRef(null),Q=sj(n.length);a.useEffect(()=>{if(!X)return;function he(Ie){ae.current?.contains(Ie.target)||E(!1)}function le(Ie){Ie.key==="Escape"&&E(!1)}return document.addEventListener("mousedown",he),document.addEventListener("keydown",le),()=>{document.removeEventListener("mousedown",he),document.removeEventListener("keydown",le)}},[X]);const de=e==="archived",Te=de&&k,fe=!de&&!G&&e!=="in-progress"&&n.length>Fd;a.useEffect(()=>{z(he=>e==="in-progress"||de||n.length<=Fd?Lo:Math.min(Math.max(he,Lo),n.length))},[e,de,n.length]);const Se=a.useCallback(he=>{de||(he.preventDefault(),he.dataTransfer.dropEffect="move",B(!0))},[de]),te=a.useCallback(he=>{he.currentTarget.contains(he.relatedTarget)||B(!1)},[]),we=a.useCallback(async he=>{he.preventDefault(),B(!1);const le=he.dataTransfer.getData("text/plain");if(!le)return;const Ie=n.find(Ze=>Ze.id===le);if(!(Ie&&Ie.column===e))try{await r(le,e)}catch(Ze){c(xe(Ze),"error")}},[e,r,c,n]),Pe=a.useMemo(()=>e!=="in-progress"?[]:sw(n,n,i),[e,n,i]),We=a.useMemo(()=>fe?n.slice(0,A):n,[fe,n,A]),Ke=Math.max(0,n.length-We.length),Ne=a.useCallback(()=>{z(he=>Math.min(he+Od,n.length))},[n.length]),_e=a.useCallback(async()=>{if(E(!1),!(n.length===0||!window.confirm(`Move all ${n.length} todo task${n.length===1?"":"s"} back to triage to be respecified?`))){pe(!0);try{const le=await Promise.allSettled(n.map(at=>r(at.id,"triage"))),Ie=le.filter(at=>at.status==="rejected").length,Ze=le.length-Ie;Ie===0?c(`Moved ${Ze} task${Ze===1?"":"s"} to triage for respec`,"success"):c(`Moved ${Ze} of ${le.length} tasks; ${Ie} failed`,"error")}finally{pe(!1)}}},[n,r,c]),Oe=a.useMemo(()=>n.filter(he=>!he.paused),[n]),ye=Oe.length,De=e==="todo"||e==="in-progress"||e==="in-review",se=U||ie||F,J=a.useCallback(async()=>{if(!(!o||(E(!1),ye===0)||!window.confirm(`Stop all ${ye} ${Pn[e].toLowerCase()} task${ye===1?"":"s"}?`))){re(!0);try{const le=await Promise.allSettled(Oe.map(at=>o(at.id))),Ie=le.filter(at=>at.status==="rejected").length,Ze=le.length-Ie;Ie===0?c(`Stopped ${Ze} task${Ze===1?"":"s"}`,"success"):c(`Stopped ${Ze} of ${le.length} tasks; ${Ie} failed`,"error")}finally{re(!1)}}},[o,ye,e,Oe,c]),me=a.useCallback(async()=>{if(E(!1),!(n.length===0||!window.confirm(`Move all ${n.length} ${Pn[e].toLowerCase()} task${n.length===1?"":"s"} to Todo?`))){ce(!0);try{const le=await Promise.allSettled(n.map(at=>r(at.id,"todo"))),Ie=le.filter(at=>at.status==="rejected").length,Ze=le.length-Ie;Ie===0?c(`Moved ${Ze} task${Ze===1?"":"s"} to Todo`,"success"):c(`Moved ${Ze} of ${le.length} tasks to Todo; ${Ie} failed`,"error")}finally{ce(!1)}}},[n,e,r,c]),ee=a.useCallback(async()=>{if(!(!x||n.length===0||!window.confirm(`Archive all ${n.length} done tasks?`)))try{const le=await x();c(`Archived ${le.length} tasks`,"success")}catch(le){c(xe(le)||"Failed to archive tasks","error")}},[x,n.length,c]);return t.jsxs("div",{className:`column${W?" drag-over":""}${de?" column-archived":""}${Te?" column-collapsed":""}`,"data-column":e,onDragOver:Se,onDragLeave:te,onDrop:we,children:[t.jsxs("div",{className:"column-header",children:[t.jsx("div",{className:`column-dot dot-${e}`}),t.jsx("h2",{children:Pn[e]}),t.jsx("span",{className:`column-count${Q?" count-flash":""}`,children:n.length}),e==="in-review"&&h&&t.jsxs("label",{className:"auto-merge-toggle",title:m?"Auto-merge enabled":"Auto-merge disabled",children:[t.jsx("input",{type:"checkbox",checked:!!m,onChange:h}),t.jsx("span",{className:"toggle-slider"}),t.jsx("span",{className:"toggle-label",children:"Auto-merge"})]}),d&&t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:d,children:"+ New Task"}),e==="done"&&x&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:ee,disabled:n.length===0,title:"Archive all done tasks","aria-label":"Archive all done tasks",children:t.jsx(Zr,{size:16})}),de&&M&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:M,title:k?"Expand archived tasks":"Collapse archived tasks","aria-label":k?"Expand archived tasks":"Collapse archived tasks",children:k?t.jsx(zt,{size:16}):t.jsx(Ys,{size:16})}),De&&t.jsxs("div",{className:"column-menu",ref:ae,children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>E(he=>!he),"aria-haspopup":"menu","aria-expanded":X,"aria-label":`${Pn[e]} column actions`,title:"Column actions",disabled:se,children:t.jsx(fg,{size:16})}),X&&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||U,children:["Respecify All",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Triage"]})]}),(e==="in-progress"||e==="in-review")&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void J(),disabled:ye===0||ie||!o,children:["Stop All",t.jsx("span",{className:"column-menu-item-hint",children:n.length===0?"No tasks in this column":ye===0?"All tasks are already paused":`Pause ${ye} active task${ye===1?"":"s"}`})]}),t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void me(),disabled:n.length===0||F,children:["Move All to Todo",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Todo"]})]})]})]})]})]}),!Te&&t.jsx("p",{className:"column-desc",children:tj[e]}),!Te&&t.jsxs("div",{className:"column-body",children:[e==="triage"&&u&&t.jsx(Ph,{onCreate:u,addToast:c,tasks:y??[],availableModels:R,onPlanningMode:j,onSubtaskBreakdown:C,projectId:s,autoExpand:!1,favoriteProviders:P,favoriteModels:T,onToggleFavorite:_,onToggleModelFavorite:L}),e==="in-progress"?Pe.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):Pe.map(he=>t.jsx(Ih,{label:he.label,activeTasks:he.activeTasks,queuedTasks:he.queuedTasks,projectId:s,onOpenDetail:l,addToast:c,globalPaused:g,onUpdateTask:p,onOpenDetailWithTab:S,taskStuckTimeoutMs:$,onOpenMission:I,lastFetchTimeMs:w,workflowStepNameLookup:q},he.label)):n.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):t.jsxs(t.Fragment,{children:[We.map(he=>t.jsx(qr,{task:he,projectId:s,onOpenDetail:l,addToast:c,globalPaused:g,onUpdateTask:p,onArchiveTask:f,onUnarchiveTask:b,onDeleteTask:v,onOpenDetailWithTab:S,taskStuckTimeoutMs:$,onOpenMission:I,onMoveTask:r,lastFetchTimeMs:w,workflowStepNameLookup:q},he.id)),fe&&Ke>0&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ne,children:["Load ",Math.min(Od,Ke)," more (",Ke," remaining)"]})]}),t.jsx(co,{slotId:"board-column-footer",projectId:s})]})]})}const $h=a.memo(iw);$h.displayName="Column";function aw(e){return[...e].sort((n,s)=>n.columnMovedAt&&s.columnMovedAt?s.columnMovedAt.localeCompare(n.columnMovedAt):n.columnMovedAt&&!s.columnMovedAt?-1:!n.columnMovedAt&&s.columnMovedAt?1:n.createdAt.localeCompare(s.createdAt))}function rw(e,n){return e.length!==n.length?!1:e.every((s,i)=>s===n[i])}const Ud=new Map;function ow(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 lw({tasks:e,projectId:n,maxConcurrent:s,onMoveTask:i,onPauseTask:r,onOpenDetail:o,addToast:l,onQuickCreate:c,onNewTask:u,autoMerge:d,onToggleAutoMerge:m,globalPaused:h,onUpdateTask:g,onArchiveTask:p,onUnarchiveTask:f,onDeleteTask:b,onArchiveAllDone:v,onLoadArchivedTasks:x,searchQuery:k="",availableModels:M,onPlanningMode:y,onSubtaskBreakdown:R,onOpenDetailWithTab:j,favoriteProviders:C,favoriteModels:S,onToggleFavorite:P,onToggleModelFavorite:T,taskStuckTimeoutMs:_,onOpenMission:L,lastFetchTimeMs:G}){const[$,I]=a.useState(!0),w=a.useRef(!1),{fetchBatch:q}=vj(n),W=a.useRef(null),[B,A]=a.useState(Ud),z=k.trim()!=="",X=a.useRef({triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]}),E=a.useCallback(()=>{I(ie=>{const re=!ie;return!re&&!w.current&&x&&(w.current=!0,x()),re})},[x]),U=a.useMemo(()=>{const ie=Object.fromEntries(ki.map(ce=>[ce,[]]));for(const ce of e)ie[ce.column].push(ce);const re=X.current,F={};for(const ce of ki){const ae=aw(ie[ce]);F[ce]=rw(re[ce],ae)?re[ce]:ae}return X.current=F,F},[e]);a.useEffect(()=>{let ie=!1;return oo(n).then(re=>{if(ie)return;const F=new Map(re.map(ce=>[ce.id,ce.name]));A(ce=>ow(ce,F)?ce:F)}).catch(()=>{ie||A(re=>re.size===0?re:Ud)}),()=>{ie=!0}},[n]);const pe=a.useMemo(()=>e.filter(ie=>ie.prInfo||ie.issueInfo).map(ie=>ie.id),[e]);return a.useEffect(()=>{if(pe.length!==0)return W.current&&clearTimeout(W.current),W.current=setTimeout(()=>{const ie=[];for(let re=0;re<pe.length;re+=50)ie.push(pe.slice(re,re+50));ie.forEach(re=>{q(re)})},500),()=>{W.current&&clearTimeout(W.current)}},[pe,q]),t.jsx(t.Fragment,{children:t.jsx("main",{className:"board",id:"board",children:ki.map(ie=>t.jsx($h,{column:ie,tasks:U[ie],projectId:n,maxConcurrent:s,onMoveTask:i,onPauseTask:r,onOpenDetail:o,addToast:l,globalPaused:h,onUpdateTask:g,onArchiveTask:p,onUnarchiveTask:f,onDeleteTask:b,allTasks:e,availableModels:M,onOpenDetailWithTab:j,favoriteProviders:C,favoriteModels:S,onToggleFavorite:P,onToggleModelFavorite:T,isSearchActive:z,taskStuckTimeoutMs:_,onOpenMission:L,lastFetchTimeMs:G,workflowStepNameLookup:B,...ie==="triage"?{onQuickCreate:c,onNewTask:u,onPlanningMode:y,onSubtaskBreakdown:R}:{},...ie==="in-review"?{autoMerge:d,onToggleAutoMerge:m}:{},...ie==="done"?{onArchiveAllDone:v}:{},...ie==="archived"?{collapsed:$,onToggleCollapse:E}:{}},ie))})})}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)"},Bd=new Set(["planning","researching","executing","finalizing","merging","specifying"]),Bl=["id","title","status","column","dependencies","progress"];function Hd(e){try{const n=Nn("kb-dashboard-list-columns",e);if(n){const i=JSON.parse(n).filter(r=>Bl.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set(Bl)}function qd(e){try{const n=Nn("kb-dashboard-hide-done",e);if(n!==null)return n==="true"}catch{}return!1}function Vd(e){try{const n=Nn("kb-dashboard-list-collapsed",e);if(n){const i=JSON.parse(n).filter(r=>ki.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set}function Wd(e){try{const n=Nn("kb-dashboard-selected-tasks",e);if(n){const s=JSON.parse(n);return new Set(s)}}catch{}return new Set}function cw(e){return e.status==="executing"||e.column==="in-progress"}function Gd(e){const n=Rh(e);return n.total===0||!cw(e)?{label:"-",percent:0,hasProgress:!1}:{label:`${n.completed}/${n.total}`,percent:n.completed/n.total*100,hasProgress:!0}}function dw({tasks:e,onMoveTask:n,onOpenDetail:s,addToast:i,globalPaused:r,onNewTask:o,onQuickCreate:l,availableModels:c,favoriteProviders:u=[],favoriteModels:d=[],onToggleFavorite:m,onToggleModelFavorite:h,onPlanningMode:g,onSubtaskBreakdown:p,onTasksUpdated:f,projectId:b,projectName:v,taskStuckTimeoutMs:x,searchQuery:k="",lastFetchTimeMs:M}){const[y,R]=a.useState("id"),[j,C]=a.useState("desc"),[S,P]=a.useState(null),[T,_]=a.useState(null),[L,G]=a.useState(null),I=tr()==="mobile",[w,q]=a.useState(()=>Hd(b)),[W,B]=a.useState(()=>qd(b)),[A,z]=a.useState(()=>Vd(b));a.useEffect(()=>{typeof window<"u"&&ts("kb-dashboard-list-columns",JSON.stringify([...w]),b)},[b,w]),a.useEffect(()=>{typeof window<"u"&&ts("kb-dashboard-hide-done",W.toString(),b)},[W,b]),a.useEffect(()=>{typeof window<"u"&&ts("kb-dashboard-list-collapsed",JSON.stringify([...A]),b)},[A,b]);const[X,E]=a.useState(!1),U=a.useRef(null),[pe,ie]=a.useState(()=>Wd(b));a.useEffect(()=>{q(Hd(b)),B(qd(b)),z(Vd(b)),ie(Wd(b))},[b]),a.useEffect(()=>{typeof window<"u"&&ts("kb-dashboard-selected-tasks",JSON.stringify([...pe]),b)},[b,pe]);const re=a.useCallback(Z=>{ie(ue=>{const Ce=new Set(ue);return Ce.has(Z)?Ce.delete(Z):Ce.add(Z),Ce})},[]),F=a.useCallback(()=>{ie(new Set)},[]),ce=a.useCallback(Z=>{q(ue=>{const Ce=new Set(ue);return Ce.has(Z)?Ce.size>1&&Ce.delete(Z):Ce.add(Z),Ce})},[]);a.useEffect(()=>{if(!X)return;const Z=Ce=>{U.current&&!U.current.contains(Ce.target)&&E(!1)},ue=Ce=>{Ce.key==="Escape"&&E(!1)};return document.addEventListener("mousedown",Z),document.addEventListener("keydown",ue),()=>{document.removeEventListener("mousedown",Z),document.removeEventListener("keydown",ue)}},[X]);const ae={id:"ID",title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},Q=a.useCallback(Z=>{y===Z?C(ue=>ue==="asc"?"desc":"asc"):(R(Z),C("asc"))},[y]),de=a.useCallback(Z=>{G(ue=>ue===Z?null:Z)},[]),Te=a.useCallback(Z=>{z(ue=>{const Ce=new Set(ue);return Ce.has(Z)?Ce.delete(Z):Ce.add(Z),Ce})},[]),fe=a.useCallback(()=>{G(null)},[]),Se=a.useMemo(()=>{let Z=k?e.filter(ve=>ve.id.toLowerCase().includes(k.toLowerCase())||ve.title&&ve.title.toLowerCase().includes(k.toLowerCase())||ve.description.toLowerCase().includes(k.toLowerCase())):[...e];W&&!L&&(Z=Z.filter(ve=>ve.column!=="done"&&ve.column!=="archived"));const Ce=[...L?Z.filter(ve=>ve.column===L):Z].sort((ve,Ge)=>{let je=0;switch(y){case"id":je=ve.id.localeCompare(Ge.id);break;case"title":je=(ve.title||ve.description).localeCompare(Ge.title||Ge.description);break;case"status":je=(ve.status||"").localeCompare(Ge.status||"");break;case"column":je=ve.column.localeCompare(Ge.column);break}return j==="asc"?je:-je}),$e={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};return Ce.forEach(ve=>$e[ve.column].push(ve)),$e},[e,k,y,j,W,L]),te=a.useMemo(()=>Object.values(Se).reduce((Z,ue)=>Z+ue.length,0),[Se]),we=a.useMemo(()=>e.filter(Z=>Z.column==="done"||Z.column==="archived").length,[e]),Pe=a.useMemo(()=>W?we:0,[W,we]),We=a.useCallback(()=>{const Z=Object.values(Se).flat().filter(ue=>ue.column!=="archived").map(ue=>ue.id);ie(ue=>{if(Z.every($e=>ue.has($e))){const $e=new Set(ue);return Z.forEach(ve=>$e.delete(ve)),$e}else return new Set([...ue,...Z])})},[Se]),Ke=a.useMemo(()=>{const Z=Object.values(Se).flat().filter(ue=>ue.column!=="archived");return Z.length===0?!1:Z.every(ue=>pe.has(ue.id))},[Se,pe]),Ne=a.useMemo(()=>{const Z=Object.values(Se).flat().filter(Ce=>Ce.column!=="archived");if(Z.length===0)return!1;const ue=Z.filter(Ce=>pe.has(Ce.id)).length;return ue>0&&ue<Z.length},[Se,pe]),[_e,Oe]=a.useState("__no_change__"),[ye,De]=a.useState("__no_change__"),[se,J]=a.useState(!1),me=a.useCallback(async()=>{if(pe.size===0)return;const Z=Array.from(pe).filter(Ce=>{const $e=e.find(ve=>ve.id===Ce);return $e&&$e.column!=="archived"});if(Z.length===0){i("No valid tasks to update (archived tasks cannot be modified)","error");return}const ue={taskIds:Z};if(_e!=="__no_change__")if(_e==="")ue.modelProvider=null,ue.modelId=null;else{const Ce=_e.indexOf("/");Ce!==-1&&(ue.modelProvider=_e.slice(0,Ce),ue.modelId=_e.slice(Ce+1))}if(ye!=="__no_change__")if(ye==="")ue.validatorModelProvider=null,ue.validatorModelId=null;else{const Ce=ye.indexOf("/");Ce!==-1&&(ue.validatorModelProvider=ye.slice(0,Ce),ue.validatorModelId=ye.slice(Ce+1))}if(Object.keys(ue).length===1){i("No changes to apply","info");return}J(!0);try{const Ce=await yx(ue.taskIds,ue.modelProvider,ue.modelId,ue.validatorModelProvider,ue.validatorModelId,void 0,void 0,b);f&&Ce.updated.length>0&&f(Ce.updated),i(`Updated ${Ce.count} task${Ce.count===1?"":"s"}`,"success"),F(),Oe("__no_change__"),De("__no_change__")}catch(Ce){i(xe(Ce)||"Failed to update models","error")}finally{J(!1)}},[pe,e,_e,ye,b,i,F,f]),ee=a.useCallback(Z=>{s(Z)},[s]),he=a.useCallback((Z,ue)=>{if(ue.paused){Z.preventDefault();return}Z.dataTransfer.setData("text/plain",ue.id),Z.dataTransfer.effectAllowed="move",P(ue.id)},[]),le=a.useCallback(()=>{P(null),_(null)},[]),Ie=a.useCallback((Z,ue)=>{Z.preventDefault(),Z.dataTransfer.dropEffect="move",_(ue)},[]),Ze=a.useCallback(()=>{_(null)},[]),at=a.useCallback(async(Z,ue)=>{Z.preventDefault(),_(null);const Ce=Z.dataTransfer.getData("text/plain");if(Ce){if(ue==="archived"){i("Tasks can only be archived via the archive button","error");return}try{await n(Ce,ue)}catch($e){i(xe($e),"error")}}},[n,i]),oe=Z=>y!==Z?t.jsx(Qm,{size:14,className:"sort-icon"}):j==="asc"?t.jsx(yi,{size:14,className:"sort-icon active"}):t.jsx(Wa,{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:U,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>E(Z=>!Z),"aria-expanded":X,"aria-haspopup":"menu",children:[t.jsx(lg,{size:14}),"Columns"]}),X&&t.jsx("div",{className:"list-column-dropdown",role:"menu",children:Bl.map(Z=>{const ue=w.has(Z),Ce=ue&&w.size===1;return t.jsxs("label",{className:`list-column-dropdown-item${Ce?" disabled":""}`,role:"menuitem",title:Ce?"At least one column must be visible":"",children:[t.jsx("input",{type:"checkbox",checked:ue,onChange:()=>ce(Z),disabled:Ce}),t.jsx("span",{children:ae[Z]})]},Z)})})]}),t.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>B(Z=>!Z),"aria-pressed":W,title:W?"Show done tasks":"Hide done tasks",children:[W?t.jsx(Vi,{size:14}):t.jsx($r,{size:14}),W?"Show Done":"Hide Done"]}),t.jsxs("div",{className:"list-stats",children:[L?`${te} of ${e.length} tasks in ${Pn[L]}`:`${te} of ${e.length} tasks`,Pe>0&&!L&&t.jsxs("span",{className:"list-stats-hidden",children:[" (",Pe," hidden)"]}),L&&t.jsx("button",{className:"btn btn-sm",onClick:fe,"aria-label":"Clear column filter",style:{marginLeft:"8px"},children:"Clear"})]}),pe.size>0&&t.jsxs("div",{className:"list-selection-stats",children:[t.jsxs("span",{className:"selection-count",children:[pe.size," selected"]}),t.jsx("button",{className:"btn btn-sm btn-link",onClick:F,children:"Clear"})]}),pe.size>0&&c&&c.length>0&&t.jsxs("div",{className:"bulk-edit-toolbar",children:[t.jsx("span",{className:"bulk-edit-label",children:"Bulk Edit Models:"}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx(wn,{models:c,value:_e,onChange:Oe,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(wn,{models:c,value:ye,onChange:De,label:"Validator Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:u,onToggleFavorite:m,favoriteModels:d,onToggleModelFavorite:h})}),t.jsx("button",{className:"btn btn-primary btn-sm bulk-edit-apply-btn",onClick:me,disabled:se||_e==="__no_change__"&&ye==="__no_change__",children:se?"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:ki.map(Z=>{const ue=e.filter(Ge=>Ge.column===Z).length,Ce=Z==="done"||Z==="archived",$e=W&&Ce?0:ue,ve=W&&Ce&&ue>0;return t.jsxs("div",{className:`list-drop-zone${T===Z?" drag-over":""}${L===Z?" active":""}`,onClick:()=>de(Z),onDragOver:Ge=>Ie(Ge,Z),onDragLeave:Ze,onDrop:Ge=>at(Ge,Z),"data-column":Z,children:[t.jsx("span",{className:"drop-zone-dot",style:{background:ga[Z]}}),t.jsx("span",{className:"drop-zone-label",children:Pn[Z]}),t.jsx("span",{className:"drop-zone-count",children:ve?`${$e} of ${ue}`:ue})]},Z)})}),t.jsxs("div",{className:"list-table-container",children:[t.jsx("div",{className:"list-quick-entry-above-table",children:t.jsx(Ph,{onCreate:l??(async()=>i("Task creation not available","error")),addToast:i,tasks:e,availableModels:c,onPlanningMode:g,onSubtaskBreakdown:p,projectId:b,autoExpand:!1,favoriteProviders:u,favoriteModels:d,onToggleFavorite:m,onToggleModelFavorite:h})}),te===0?t.jsx("div",{className:"list-empty",children:k?"No tasks match your filter":"No tasks yet"}):I?t.jsx("div",{className:"list-cards",children:ki.map(Z=>{if(L&&Z!==L||W&&(Z==="done"||Z==="archived")&&!L)return null;const ue=Se[Z],Ce=ue.length===0;if(k&&Ce)return null;const $e=A.has(Z);return t.jsxs(a.Fragment,{children:[t.jsxs("div",{className:`list-card-section-header${$e?" list-section-header--collapsed":""}`,onClick:()=>Te(Z),"aria-expanded":!$e,role:"button",tabIndex:0,onKeyDown:ve=>{(ve.key==="Enter"||ve.key===" ")&&(ve.preventDefault(),Te(Z))},children:[t.jsx(en,{size:14,className:`list-section-chevron${$e?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${Z}`}),t.jsx("span",{className:"list-section-title",children:Pn[Z]}),t.jsx("span",{className:"list-section-count",children:ue.length})]}),!$e&&t.jsx(t.Fragment,{children:Ce?t.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):ue.map(ve=>{const Ge=ve.status==="failed",je=ve.paused===!0,Ue=Hr(ve,x,M),He=!r&&!Ge&&!je&&!Ue&&(ve.column==="in-progress"||Bd.has(ve.status)),ge=typeof ve.status=="string"&&ve.status.trim().length>0,Fe=!!(ve.dependencies&&ve.dependencies.length>0),be=Gd(ve),Je=be.hasProgress,st=pe.size>0;return t.jsxs("div",{className:`list-card${He?" agent-active":""}${st?" list-card--selectable":""}`,onClick:()=>ee(ve),"data-id":ve.id,children:[st&&t.jsx("label",{className:"list-card-checkbox",onClick:dt=>dt.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:pe.has(ve.id),onChange:dt=>{dt.stopPropagation(),re(ve.id)},onClick:dt=>dt.stopPropagation(),disabled:ve.column==="archived","aria-label":`Select ${ve.id}`})}),t.jsxs("div",{className:"list-card-row",children:[t.jsx("span",{className:"list-card-id",children:ve.id}),ve.executionMode==="fast"&&t.jsx("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",children:"Fast"}),t.jsx("span",{className:"list-card-spacer"}),Ue?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):ge?t.jsx("span",{className:`list-status-badge list-status-badge--${ve.column}${Ge?" failed":""}${He?" pulsing":""}`,children:ve.status}):null]}),t.jsx("div",{className:"list-card-row",children:t.jsx("div",{className:"list-card-title",children:ve.title||ve.description})}),(Fe||Je)&&t.jsxs("div",{className:"list-card-row list-card-meta",children:[Fe&&t.jsxs("span",{className:"list-dep-badge",title:ve.dependencies.join(", "),children:[t.jsx(Wi,{size:12})," ",ve.dependencies.length]}),Je&&t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${be.percent}%`,backgroundColor:ga[ve.column]}})}),t.jsx("span",{className:"list-progress-label",children:be.label})]})]})]},ve.id)})})]},Z)})}):t.jsxs("table",{className:"list-table",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{className:"list-header-cell list-header-checkbox",children:t.jsx("input",{type:"checkbox",checked:Ke,ref:Z=>{Z&&(Z.indeterminate=Ne)},onChange:We,"aria-label":"Select all visible tasks"})}),w.has("id")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Q("id"),children:["ID ",oe("id")]}),w.has("title")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Q("title"),children:["Title ",oe("title")]}),w.has("status")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Q("status"),children:["Status ",oe("status")]}),w.has("column")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Q("column"),children:["Column ",oe("column")]}),w.has("dependencies")&&t.jsx("th",{className:"list-header-cell",children:"Dependencies"}),w.has("progress")&&t.jsx("th",{className:"list-header-cell",children:"Progress"})]})}),t.jsx("tbody",{children:ki.map(Z=>{if(L&&Z!==L||W&&(Z==="done"||Z==="archived")&&!L)return null;const ue=Se[Z],Ce=ue.length===0;if(k&&Ce)return null;const $e=A.has(Z);return t.jsxs(a.Fragment,{children:[t.jsx("tr",{className:`list-section-header${$e?" list-section-header--collapsed":""}`,onClick:()=>Te(Z),"aria-expanded":!$e,children:t.jsxs("th",{colSpan:w.size+1,className:"list-section-cell",children:[t.jsx(en,{size:14,className:`list-section-chevron${$e?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${Z}`}),t.jsx("span",{className:"list-section-title",children:Pn[Z]}),t.jsx("span",{className:"list-section-count",children:ue.length})]})}),!$e&&t.jsx(t.Fragment,{children:Ce?t.jsx("tr",{className:"list-section-empty",children:t.jsx("td",{colSpan:w.size+1,className:"list-empty-cell",children:"No tasks"})}):ue.map(ve=>{const Ge=ve.status==="failed",je=ve.paused===!0,Ue=Hr(ve,x,M),He=!r&&!Ge&&!je&&!Ue&&(ve.column==="in-progress"||Bd.has(ve.status)),ge=S===ve.id;return t.jsxs("tr",{className:`list-row${Ge?" failed":""}${je?" paused":""}${Ue?" stuck":""}${He?" agent-active":""}${ge?" dragging":""}`,onClick:()=>ee(ve),draggable:!je,onDragStart:Fe=>he(Fe,ve),onDragEnd:le,"data-id":ve.id,children:[t.jsx("td",{className:"list-cell list-cell-checkbox",children:t.jsx("input",{type:"checkbox",checked:pe.has(ve.id),onChange:Fe=>{Fe.stopPropagation(),re(ve.id)},onClick:Fe=>Fe.stopPropagation(),disabled:ve.column==="archived","aria-label":`Select ${ve.id}`})}),w.has("id")&&t.jsx("td",{className:"list-cell list-cell-id",children:ve.id}),w.has("title")&&t.jsx("td",{className:"list-cell list-cell-title",children:t.jsxs("div",{className:"list-title-content",children:[ve.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:ve.title||ve.description})]})}),w.has("status")&&t.jsx("td",{className:"list-cell",children:Ue?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):ve.status?t.jsx("span",{className:`list-status-badge list-status-badge--${ve.column}${Ge?" failed":""}${He?" pulsing":""}`,children:ve.status}):t.jsx("span",{className:"list-status-badge",children:"-"})}),w.has("column")&&t.jsx("td",{className:"list-cell",children:t.jsx("span",{className:"list-column-badge",style:{background:`${ga[ve.column]}20`,color:ga[ve.column]},children:Pn[ve.column]})}),w.has("dependencies")&&t.jsx("td",{className:"list-cell list-cell-deps",children:ve.dependencies&&ve.dependencies.length>0?t.jsxs("span",{className:"list-dep-badge",title:ve.dependencies.join(", "),children:[t.jsx(Wi,{size:12})," ",ve.dependencies.length]}):"-"}),w.has("progress")&&t.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const Fe=Gd(ve);return Fe.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:`${Fe.percent}%`,backgroundColor:ga[ve.column]}})}),t.jsx("span",{className:"list-progress-label",children:Fe.label})]}):"-"})()})]},ve.id)})})]},Z)})})]})]})]})}const uw={active:{label:"Active",color:"var(--success)",icon:rn},paused:{label:"Paused",color:"var(--warning)",icon:Fs},errored:{label:"Error",color:"var(--color-error)",icon:ss},initializing:{label:"Initializing",color:"var(--info)",icon:it}};function mw(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 hw(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 pw(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 fw({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=uw[e.status],g=h.icon,p=a.useCallback(()=>{s(e)},[s,e]),f=a.useCallback(y=>{y.stopPropagation(),i(e)},[i,e]),b=a.useCallback(y=>{y.stopPropagation(),r(e)},[r,e]),v=a.useCallback(y=>{if(y.stopPropagation(),!d){m(!0);return}o(e),m(!1)},[d,o,e]),x=e.status==="paused",k=e.status==="errored",M=e.status==="initializing";return t.jsxs("div",{className:`project-card ${u?"project-card-loading":""} ${k?"project-card-errored":""}`,onClick:p,"data-project-id":e.id,role:"button",tabIndex:0,onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),p())},children:[t.jsxs("div",{className:"project-card-header",children:[t.jsx("div",{className:"project-card-icon",children:t.jsx(jn,{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:hw(e.path)})]}),t.jsxs("div",{className:"project-card-status-badge",style:{color:h.color,borderColor:h.color},children:[t.jsx(g,{size:12,className:M?"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:mw(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(rn,{size:14}),t.jsx("span",{children:"Resume"})]}):t.jsxs("button",{className:"project-card-action project-card-action-pause",onClick:f,disabled:u||M,title:M?"Cannot pause while initializing":"Pause project","aria-label":"Pause project",children:[t.jsx(Fs,{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(Ga,{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(Ht,{size:14}),t.jsx("span",{children:d?"Confirm":""})]})]})]})]})}const gw=a.memo(fw,pw);function bw(){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(jn,{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(Ss,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(tn,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(ss,{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 xw=1e4,Kd=5;function vw(e){const[n,s]=a.useState({}),[i,r]=a.useState(!0),[o,l]=a.useState(null),c=a.useRef(null),u=a.useRef(null),d=a.useRef(!1),m=a.useCallback(async()=>{if(e.length===0){s({}),d.current||(d.current=!0),r(!1);return}u.current&&u.current.abort(),u.current=new AbortController,!d.current&&r(!0),l(null);try{const p={};for(let f=0;f<e.length;f+=Kd){const b=e.slice(f,f+Kd),v=await Promise.allSettled(b.map(async x=>{try{return await gd(x)}catch{return null}}));if(b.forEach((x,k)=>{const M=v[k];p[x]=M.status==="fulfilled"?M.value:null}),u.current?.signal.aborted)return}s(p),d.current=!0}catch(p){if(p instanceof Error&&p.name==="AbortError")return;l(p instanceof Error?p.message:"Failed to fetch health data"),d.current=!0}finally{r(!1)}},[e]),h=a.useCallback(async g=>{try{const p=await gd(g);s(f=>({...f,[g]:p}))}catch(p){console.error(`Failed to fetch health for project ${g}:`,p)}},[]);return a.useEffect(()=>(d.current=!1,m(),()=>{u.current&&u.current.abort()}),[m]),a.useEffect(()=>{if(e.length!==0)return c.current&&clearInterval(c.current),c.current=setInterval(()=>{m()},xw),()=>{c.current&&(clearInterval(c.current),c.current=null)}},[m,e.length]),{healthMap:n,loading:i,error:o,refresh:m,refreshProject:h}}function yw({projects:e,loading:n=!1,onSelectProject:s,onAddProject:i,onPauseProject:r,onResumeProject:o,onRemoveProject:l,nodes:c=[]}){const[u,d]=a.useState("all"),[m,h]=a.useState(null),[g,p]=a.useState("activity"),[f,b]=a.useState("desc");a.useEffect(()=>{if(typeof window>"u")return;const G=localStorage.getItem("kb-dashboard-recent-projects");if(G)try{const $=JSON.parse(G);x($)}catch{}},[]);const[v,x]=a.useState([]),k=a.useMemo(()=>e.map(G=>G.id),[e]),{healthMap:M,loading:y}=vw(k),R=a.useMemo(()=>e.map(G=>({project:G,health:M[G.id]||null})),[e,M]),j=a.useMemo(()=>{let G=[...R];return u!=="all"&&(G=G.filter(({project:$})=>$.status===u)),m!==null&&(G=G.filter(({project:$})=>$.nodeId===m)),G},[R,u,m]),C=a.useMemo(()=>{const G=[...j];return G.sort(($,I)=>{let w=0;switch(g){case"name":w=$.project.name.localeCompare(I.project.name);break;case"activity":{const q=$.project.lastActivityAt||$.health?.lastActivityAt||$.project.updatedAt,W=I.project.lastActivityAt||I.health?.lastActivityAt||I.project.updatedAt;w=new Date(W).getTime()-new Date(q).getTime();break}case"status":{const q={errored:0,initializing:1,paused:2,active:3};w=q[$.project.status]-q[I.project.status];break}}return f==="asc"?w:-w}),G},[j,g,f]),S=a.useMemo(()=>{const G=e.length,$=e.filter(z=>z.status==="active").length,I=e.filter(z=>z.status==="errored").length,w=new Set;e.forEach(z=>{z.nodeId&&w.add(z.nodeId)});const q=w.size||(G>0?1:0);let W=0,B=0,A=0;return Object.values(M).forEach(z=>{z&&(W+=z.activeTaskCount,B+=z.totalTasksCompleted,A+=z.inFlightAgentCount)}),{totalProjects:G,activeProjects:$,erroredProjects:I,totalNodes:q,totalActiveTasks:W,totalCompletedTasks:B,totalInFlightAgents:A}},[e,M]),P=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]),T=a.useMemo(()=>{const G=new Map;return e.forEach($=>{const I=$.nodeId,w=G.get(I);if(w)w.count++;else{const W=c.find(B=>B.id===I)?.name??$._sourceNodeName??"Local";G.set(I,{name:W,count:1})}}),Array.from(G.entries()).map(([$,{name:I,count:w}])=>({nodeId:$??null,name:I,count:w}))},[e,c]),_=a.useCallback(G=>{const $=[G.id,...v.filter(I=>I!==G.id)].slice(0,3);x($),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify($)),s(G)},[s,v]);return n||y&&e.length>0&&Object.keys(M).length===0?t.jsx(bw,{}):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(Ra,{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(Vt,{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(Ci,{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(jn,{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(Ss,{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(tn,{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(ss,{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(Lr,{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(Vt,{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:P.all})]}),t.jsxs("button",{className:`project-filter-tab ${u==="active"?"active":""}`,onClick:()=>d("active"),children:["Active",t.jsx("span",{className:"project-filter-count",children:P.active})]}),t.jsxs("button",{className:`project-filter-tab ${u==="paused"?"active":""}`,onClick:()=>d("paused"),children:["Paused",t.jsx("span",{className:"project-filter-count",children:P.paused})]}),t.jsxs("button",{className:`project-filter-tab ${u==="errored"?"active":""} ${P.errored>0?"has-errors":""}`,onClick:()=>d("errored"),children:["Errored",t.jsx("span",{className:"project-filter-count",children:P.errored})]})]}),T.length>1&&t.jsxs("div",{className:"project-node-filter",children:[t.jsx(Lr,{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"}),T.map(({nodeId:G,name:$,count:I})=>t.jsxs("option",{value:G??"",children:[$," (",I,")"]},G??"local"))]})]}),t.jsxs("div",{className:"project-sort",children:[t.jsx(Dr,{size:14}),t.jsxs("select",{value:`${g}-${f}`,onChange:G=>{const[$,I]=G.target.value.split("-");p($),b(I)},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(Qm,{size:14})]})]}),t.jsx("div",{className:"project-grid",children:C.map(({project:G,health:$})=>{const I=c.find(q=>q.id===G.nodeId),w=I?void 0:G._sourceNodeName;return t.jsx(gw,{project:G,health:$,node:I,nodeNameFallback:w,onSelect:_,onPause:r,onResume:o,onRemove:l},G.id)})}),C.length===0&&t.jsxs("div",{className:"project-overview__no-results",children:[t.jsx(Dr,{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 kw=45e3,jw=3e3,ww=2e3,Nw=1500,Jd="fusion:sse-client-id";let Di=null;const ci=new Map;function Yd(){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 Dh(){if(!(typeof window>"u")){if(Di)return Di;try{const e=window.sessionStorage.getItem(Jd);if(e)return Di=e,e;const n=Yd();return window.sessionStorage.setItem(Jd,n),Di=n,n}catch{return Di=Yd(),Di}}}function Lh(e){if(!(typeof window>"u"))try{return{parsed:new URL(e,window.location.origin),preserveRelativePath:e.startsWith("/")}}catch{return}}function zh(e){return e.origin===window.location.origin&&e.pathname==="/api/events"}function Sw(e){const n=Dh();if(!n)return e;const s=Lh(e);return!s||!zh(s.parsed)?e:(s.parsed.searchParams.set("clientId",n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function pc(e,n){const s=Dh();if(!s)return;const i=Lh(e);if(!i||!zh(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),Hs(`${r.pathname}${r.search}${r.hash}`)}function Cw(e){if(typeof window>"u")return;const n=pc(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 uo(e){e.keepaliveTimer&&(clearInterval(e.keepaliveTimer),e.keepaliveTimer=null)}function Qd(e){if(typeof window>"u"||typeof window.fetch!="function")return;const n=pc(e.url,"keepalive");if(!n)return;const s=typeof AbortController<"u"?new AbortController:null,i=s?window.setTimeout(()=>s.abort(),Nw):null;window.fetch(n,{method:"POST",cache:"no-store",signal:s?.signal}).catch(()=>{}).finally(()=>{i!==null&&window.clearTimeout(i)})}function Ew(e){uo(e),pc(e.url,"keepalive")&&(Qd(e),e.keepaliveTimer=window.setInterval(()=>{Qd(e)},ww))}if(typeof window<"u"){const e=()=>{for(const s of Array.from(ci.values()))if(!s.closed){if(uo(s),Cw(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,fc(i))};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e),window.addEventListener("pageshow",n)}function Ia(e){e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),e.heartbeatTimer=setTimeout(()=>{Fh(e)},kw)}function Fh(e){if(e.heartbeatTimer&&(clearTimeout(e.heartbeatTimer),e.heartbeatTimer=null),e.es&&(e.es.close(),e.es=null),uo(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&&fc(e)},jw)}}function fc(e){if(e.es||e.closed)return;e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=null);const n=new EventSource(Hs(Sw(e.url)));e.es=n,Ew(e),n.addEventListener("open",()=>{Ia(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);Fh(e)}),n.addEventListener("message",()=>Ia(e)),n.addEventListener("heartbeat",()=>Ia(e)),Oh(e),Ia(e)}function Oh(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=>{Ia(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 Mw(e){e.closed=!0,e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),uo(e),e.reconnectTimer&&clearTimeout(e.reconnectTimer),e.es&&e.es.close(),e.es=null,e.nativeListeners.clear(),ci.delete(e.url)}function qs(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[o,l]of Object.entries(n.events)){let c=i.events.get(o);c||(c=new Set,i.events.set(o,c)),c.add(l)}s.subscribers.add(i),fc(s),Oh(s);let r=!0;return()=>{if(!r)return;r=!1;const o=ci.get(e);o&&(o.subscribers.delete(i),o.subscribers.size===0&&Mw(o))}}const gc="kb-planning-last-description",bc="kb-subtask-last-description",xc="kb-mission-last-goal";function _w(e,n){ts(gc,e,n)}function Aw(e){return Nn(gc,e)||""}function Li(e){Ha(gc,e)}function Tw(e,n){ts(bc,e,n)}function Rw(e){return Nn(bc,e)||""}function zo(e){Ha(bc,e)}function Iw(e,n){ts(xc,e,n)}function Pw(e){return Nn(xc,e)||""}function ai(e){Ha(xc,e)}function $w(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 Dw(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 Lw(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 Cs({entries:e,defaultShowThinking:n=!1}){const[s,i]=a.useState({}),r=Lw(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?$w(o):void 0,h=o.question&&m!==void 0?Dw(o.question,m):"";return t.jsxs("div",{className:"conversation-entry",children:[c?t.jsxs("div",{className:"conversation-entry-question",children:[t.jsxs("span",{className:"conversation-entry-question-label",children:["Q",o.questionNumber]}),t.jsx("p",{children:o.question?.question})]}):t.jsx("div",{className:"conversation-entry-question",children:t.jsx("span",{className:"conversation-entry-question-label",children:"AI Reasoning"})}),c&&t.jsxs("div",{className:"conversation-entry-response",children:[t.jsx("strong",{children:"Your response"}),t.jsx("p",{children:h||"—"})]}),u&&t.jsxs("div",{className:"conversation-entry-thinking",children:[t.jsxs("button",{type:"button",className:"conversation-thinking-toggle",onClick:()=>{i(g=>({...g,[l]:!d}))},"aria-expanded":d,children:[t.jsx("span",{"aria-hidden":"true",children:d?"▾":"▸"}),d?`Hide ${c?"AI thinking":"AI reasoning"}`:`Show ${c?"AI thinking":"AI reasoning"}`]}),d&&t.jsx("pre",{children:o.thinkingOutput})]})]},`${o.question?.id??"thinking"}-${l}`)})})}const Xd="fusion-tab-id";function zw(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function _i(){if(typeof window>"u")return"server-tab";const e=window.sessionStorage.getItem(Xd);if(e)return e;const n=zw();return window.sessionStorage.setItem(Xd,n),n}function mo(e){const n=a.useMemo(()=>_i(),[]),[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(Sk(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=Ck(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=Hs(`/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:qs("/api/events",{events:{"ai_session:updated":m=>{try{const h=JSON.parse(m.data);if(h.id!==e)return;const g=h.lockedByTab??null;o(g),i(!!(g&&g!==n))}catch{}}}}),[e,n]);const u=a.useCallback(async()=>{if(e){c(!0);try{await Promise.resolve(Ek(e,n)),i(!1),o(null)}finally{c(!1)}}},[e,n]);return{isLockedByOther:s,currentHolder:r,takeControl:u,isLoading:l}}const Fw="fusion:ai-session-sync",Zd="fusion:ai-session-sync",Ow=3e4,Uw=6e4;function $s(){return Date.now()}function Bw(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function eu(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 Hw{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=Bw(),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:$s()})}broadcastUpdate(n){const s=n.timestamp??$s();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??$s();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=$s();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=$s();this.releaseTabOwnership(n,s,i),this.ownedSessions.delete(n),this.publish({type:"tab:inactive",tabId:s,sessionId:n,timestamp:i})}broadcastHeartbeat(n){const s=$s();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(Fw),this.channel.onmessage=s=>{const i=eu(s.data);i&&this.handleIncomingMessage(i)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==Zd||!s.newValue))try{const i=JSON.parse(s.newValue),r=eu(i.message);r&&this.handleIncomingMessage(r)}catch{}};window.addEventListener("storage",n),this.cleanupStorageListener=()=>{window.removeEventListener("storage",n)}}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{const n=$s();this.updateHeartbeat(this.tabId,n),this.publish({type:"tab:heartbeat",tabId:this.tabId,timestamp:n})},Ow)}startStaleSweep(){this.staleSweepInterval=setInterval(()=>{this.emit()},1e4)}setupBeforeUnloadCleanup(){const n=()=>{for(const[s,i]of this.ownedSessions.entries()){const r=$s();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(Zd,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:$s()});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=$s(),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>Uw;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 Ds=new Hw;function la(){const e=a.useSyncExternalStore(c=>Ds.subscribe(c),()=>Ds.getSnapshot(),()=>Ds.getSnapshot());a.useEffect(()=>{Ds.requestSync()},[]);const n=a.useCallback(c=>{Ds.broadcastUpdate(c)},[]),s=a.useCallback(c=>{Ds.broadcastCompleted(c)},[]),i=a.useCallback((c,u)=>{Ds.broadcastLock(c,u)},[]),r=a.useCallback((c,u)=>{Ds.broadcastUnlock(c,u)},[]),o=a.useCallback(c=>{Ds.broadcastHeartbeat(c)},[]),l=a.useCallback(()=>{Ds.requestSync()},[]);return{tabId:e.tabId,sessions:e.sessions,activeTabMap:e.activeTabMap,broadcastUpdate:n,broadcastCompleted:s,broadcastLock:i,broadcastUnlock:r,broadcastHeartbeat:o,requestSync:l}}function qw(e,n){return e&&n?`${e}/${n}`:""}function Vw(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 Ww=["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 Gw({isOpen:e,onClose:n,onMissionCreated:s,projectId:i,initialGoal:r,resumeSessionId:o}){const[l,c]=a.useState(""),[u,d]=a.useState({type:"initial"}),[m,h]=a.useState(null),[g,p]=a.useState([]),[f,b]=a.useState([]),[v,x]=a.useState(null),[k,M]=a.useState(!1),y=a.useRef(!1),[R,j]=a.useState(""),[C,S]=a.useState(!0),[P,T]=a.useState(!1),[_,L]=a.useState(!1),[G,$]=a.useState(!1),I=a.useRef(null),w=a.useRef(null),q=a.useRef(null),W=a.useRef(null),[B,A]=a.useState(o??null),z=a.useMemo(()=>_i(),[]),{isLockedByOther:X,takeControl:E,isLoading:U}=mo(e?B:null),{activeTabMap:pe,broadcastUpdate:ie,broadcastCompleted:re,broadcastLock:F,broadcastUnlock:ce,broadcastHeartbeat:ae}=la(),[Q,de]=a.useState(void 0),[Te,fe]=a.useState(void 0),[Se,te]=a.useState([]),[we,Pe]=a.useState(!0),[We,Ke]=a.useState(null),[Ne,_e]=a.useState([]),[Oe,ye]=a.useState([]),De=qw(Q,Te);a.useEffect(()=>{(async()=>{try{Pe(!0);const Ue=await is();te(Ue.models),_e(Ue.favoriteProviders),ye(Ue.favoriteModels)}catch(Ue){Ke(xe(Ue)||"Failed to load models")}finally{Pe(!1)}})()},[]);const se=a.useCallback(je=>{_e(Ue=>{const He=Ue,Fe=He.includes(je)?He.filter(be=>be!==je):[je,...He];return nn({favoriteProviders:Fe,favoriteModels:Oe}).catch(()=>{_e(He)}),Fe})},[Oe]),J=a.useCallback(je=>{ye(Ue=>{const He=Ue,Fe=He.includes(je)?He.filter(be=>be!==je):[je,...He];return nn({favoriteProviders:Ne,favoriteModels:Fe}).catch(()=>{ye(He)}),Fe})},[Ne]),me=a.useCallback((je,Ue)=>{if(!je||!Ue)return"Using default";const He=Se.find(ge=>ge.provider===je&&ge.id===Ue);return He?`${He.provider}/${He.id}`:`${je}/${Ue}`},[Se]),ee=a.useCallback(je=>{w.current?.close();const Ue=hk(je,i,{onThinking:He=>{j(ge=>ge+He),ie({sessionId:je,status:"generating",needsInput:!1,owningTabId:z,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onQuestion:He=>{T(!1),L(!1),ai(i),d({type:"question",sessionId:je,question:He}),j(""),M(!0),ie({sessionId:je,status:"awaiting_input",needsInput:!0,owningTabId:z,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onSummary:He=>{T(!1),L(!1),ai(i),d({type:"summary",sessionId:je,summary:He}),x(He),j(""),M(!0),ie({sessionId:je,status:"complete",needsInput:!1,owningTabId:z,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onError:He=>{const ge=He||"Session failed while contacting the AI.";T(!1),L(!1),h(null),d({type:"error",sessionId:je,errorMessage:ge}),j(""),M(!0),q.current=je,ie({sessionId:je,status:"error",needsInput:!1,owningTabId:z,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null}),re({sessionId:je,status:"error"})},onComplete:()=>{T(!1),L(!1),q.current=null,re({sessionId:je,status:"complete"})},onConnectionStateChange:He=>{T(He==="reconnecting")}});w.current=Ue},[re,ie,l,i,z]),he=a.useCallback(async je=>{const Ue=je??l;if(Ue.trim()){h(null),j(""),p([]),b([]),T(!1),d({type:"loading"});try{const{sessionId:He}=await ck(Ue.trim(),i,Q&&Te?{modelProvider:Q,modelId:Te}:void 0);q.current=He,A(He),ai(i),ee(He),p([])}catch(He){T(!1),h(xe(He)||"Failed to start interview session"),d({type:"initial"}),q.current=null,A(null)}}},[ee,l,Q,Te,i]);a.useEffect(()=>{e&&u.type==="initial"&&I.current?.focus()},[e,u.type]),a.useEffect(()=>{if(e&&r&&!y.current&&u.type==="initial"){c(r);const je=setTimeout(()=>{y.current=!0,he(r)},0);return()=>clearTimeout(je)}else if(e&&!r&&!y.current&&u.type==="initial"){const je=Pw(i);je&&c(je)}},[e,r,u.type,he]),a.useEffect(()=>{e||(y.current=!1,T(!1),L(!1),A(null))},[e]),a.useEffect(()=>{if(!e||!o||u.type!=="initial")return;let je=!1;return Js(o).then(Ue=>{if(je||!Ue)return;const He=Yi(Ue.conversationHistory);if(b(He),A(Ue.id),p(He.map(ge=>ge.response).filter(ge=>!!(ge&&typeof ge=="object"&&!Array.isArray(ge)))),Ue.status==="awaiting_input"&&Ue.currentQuestion)try{ai(i);const ge=JSON.parse(Ue.currentQuestion);q.current=Ue.id,M(!0),d({type:"question",sessionId:Ue.id,question:ge})}catch{h("Failed to restore session question.")}else if(Ue.status==="complete"&&Ue.result)try{ai(i);const ge=JSON.parse(Ue.result);q.current=Ue.id,M(!0),x(ge),d({type:"summary",sessionId:Ue.id,summary:ge})}catch{h("Failed to restore session result.")}else Ue.status==="generating"?(q.current=Ue.id,M(!0),Ue.thinkingOutput&&j(Ue.thinkingOutput),d({type:"loading"}),ee(Ue.id)):Ue.status==="error"&&(q.current=Ue.id,M(!0),h(null),d({type:"error",sessionId:Ue.id,errorMessage:Ue.error??"The session encountered an error."}))}).catch(()=>{je||h("Failed to resume session.")}),()=>{je=!0}},[ee,e,o,u.type,i]),a.useEffect(()=>{if(!e){W.current&&(ce(W.current,z),W.current=null);return}if(B&&W.current!==B){W.current&&ce(W.current,z),F(B,z),W.current=B;return}!B&&W.current&&(ce(W.current,z),W.current=null)},[F,ce,e,B,z]),a.useEffect(()=>{if(!e||!B||W.current!==B)return;ae(z);const je=setInterval(()=>{ae(z)},3e4);return()=>{clearInterval(je)}},[ae,e,B,z]),a.useEffect(()=>()=>{w.current?.close(),w.current=null,W.current&&(ce(W.current,z),W.current=null)},[ce,z]),a.useEffect(()=>{if(!e)return;const je=Ue=>{(u.type==="question"||u.type==="summary")&&(Ue.preventDefault(),Ue.returnValue=""),w.current?.close()};return window.addEventListener("beforeunload",je),()=>window.removeEventListener("beforeunload",je)},[e,u]);const le=a.useCallback(()=>{w.current?.close(),w.current=null,n()},[n]),Ie=a.useCallback(async()=>{if(l&&Iw(l,i),!(k&&!confirm("Are you sure you want to close? Your interview progress will be lost."))){if(w.current?.close(),w.current=null,u.type==="question"||u.type==="summary"||u.type==="error")try{await Nh(u.sessionId,i,z)}catch{}c(""),d({type:"initial"}),h(null),p([]),b([]),x(null),j(""),T(!1),L(!1),M(!1),$(!1),de(void 0),fe(void 0),q.current=null,A(null),n()}},[l,k,u,n,i,z]);a.useEffect(()=>{if(!e)return;const je=Ue=>{Ue.key==="Escape"&&(k?confirm("Are you sure you want to close? Your interview progress will be lost.")&&Ie():Ie())};return document.addEventListener("keydown",je),()=>document.removeEventListener("keydown",je)},[e,k,Ie]);const Ze=a.useCallback(async je=>{if(u.type!=="question")return;const{sessionId:Ue}=u;h(null),p(He=>[...He,je]),b(He=>[...He,{question:u.question,response:je}]),d({type:"loading"}),j("");try{ee(Ue),await dk(Ue,je,i,z),M(!0)}catch(He){w.current?.close(),w.current=null,h(xe(He)||"Failed to submit response"),d({type:"question",sessionId:Ue,question:u.question})}},[u,i,z,ee]),at=a.useCallback(async()=>{if(u.type!=="error")return;const je=u.sessionId;h(null),L(!0),j(""),d({type:"loading"}),ee(je);try{q.current=je,A(je),await uk(je,i,z)}catch(Ue){let He=Ue;if((xe(Ue)||"").includes("not in an error state"))try{const Fe=await Js(je);if(!Fe)throw new Error("Failed to refresh interview session.");const be=Yi(Fe.conversationHistory);if(b(be),p(be.map(Je=>Je.response).filter(Je=>!!(Je&&typeof Je=="object"&&!Array.isArray(Je)))),q.current=Fe.id,A(Fe.id),M(!0),Fe.status==="generating")j(Fe.thinkingOutput??""),d({type:"loading"}),w.current?.isConnected()||ee(Fe.id);else if(Fe.status==="awaiting_input"){if(!Fe.currentQuestion)throw new Error("Interview session is awaiting input but has no current question.");ai(i);const Je=JSON.parse(Fe.currentQuestion);d({type:"question",sessionId:Fe.id,question:Je}),w.current?.isConnected()||ee(Fe.id)}else if(Fe.status==="complete"){if(!Fe.result)throw new Error("Interview session is complete but has no result.");ai(i);const Je=JSON.parse(Fe.result);x(Je),d({type:"summary",sessionId:Fe.id,summary:Je})}else Fe.status==="error"&&d({type:"error",sessionId:Fe.id,errorMessage:Fe.error??"Retry failed. Please try again."});T(!1);return}catch(Fe){He=Fe}w.current?.close(),w.current=null,d({type:"error",sessionId:je,errorMessage:xe(He)||"Retry failed. Please try again."}),T(!1)}finally{L(!1)}},[ee,i,z,u]),oe=a.useCallback(async()=>{if(u.type==="summary"){h(null),$(!0);try{const je=await mk(u.sessionId,v||void 0,i);s(je),ai(i),w.current?.close(),w.current=null,c(""),d({type:"initial"}),h(null),p([]),b([]),x(null),j(""),T(!1),L(!1),M(!1),$(!1),q.current=null,A(null),n()}catch(je){h(xe(je)||"Failed to create mission"),$(!1)}}},[u,v,s,n,i]),Z=()=>u.type==="question"?Math.min(g.length+1,6):6,ue=u.type==="loading"||u.type==="question"||u.type==="summary"||u.type==="error",Ce=B?pe.get(B):null,$e=Ce&&Ce.tabId!==z,ve=!!($e&&!Ce.stale),Ge=X&&(!$e||Ce.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:je=>je.target===je.currentTarget&&Ie(),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(ns,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Plan Mission with AI"})]}),t.jsxs("div",{className:"modal-header-actions",children:[ue&&t.jsx("button",{className:"modal-send-to-background",onClick:le,title:"Send to background","aria-label":"Send to background",children:t.jsx(aa,{size:16})}),t.jsx("button",{className:"modal-close",onClick:Ie,"aria-label":"Close",children:t.jsx(Pt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[m&&t.jsx("div",{className:"form-error planning-error",children:m}),P&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),ve&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),u.type==="initial"&&t.jsxs("div",{className:"planning-initial",children:[t.jsxs("div",{className:"planning-view-scroll",children:[t.jsxs("div",{className:"planning-intro",children:[t.jsx(Dn,{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:I,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:je=>c(je.target.value),onKeyDown:je=>{je.key==="Enter"&&!je.shiftKey&&l.trim()&&(je.preventDefault(),he())}})]}),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:Ww.map((je,Ue)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>c(je),children:je.length>45?je.slice(0,45)+"...":je},Ue))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"mission-interview-modal-model",className:"form-label",children:["Planning Model",we&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(wn,{id:"mission-interview-modal-model",label:"Planning Model",value:De,onChange:je=>{const{provider:Ue,modelId:He}=Vw(je);de(Ue),fe(He)},models:Se,disabled:we,favoriteProviders:Ne,onToggleFavorite:se,favoriteModels:Oe,onToggleModelFavorite:J}),We&&t.jsxs("div",{className:"form-hint form-hint-error",children:[We," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{Pe(!0);const je=await is();te(je.models),_e(je.favoriteProviders),ye(je.favoriteModels),Ke(null)}catch(je){Ke(xe(je)||"Failed to load models")}finally{Pe(!1)}})()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${Q&&Te?"model-badge-custom":"model-badge-default"}`,children:me(Q,Te)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>he(),disabled:!l.trim(),children:[t.jsx(ns,{size:16,className:"icon-mr-8"}),"Start Interview"]})})]}),u.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(it,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:R?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>S(!C),type:"button",children:C?"Hide thinking":"Show thinking"}),C&&R&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:R})})]})]}),u.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[f.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Cs,{entries:f}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:u.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void at(),disabled:_,children:[_?t.jsx(it,{size:14,className:"spin"}):t.jsx(hn,{size:14}),t.jsx("span",{className:"icon-ml-6",children:_?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Ie,disabled:_,children:"Cancel"})]})]})]})}),u.type==="question"&&t.jsx(Kw,{question:u.question,progress:Z(),historyEntries:f,onSubmit:Ze}),u.type==="summary"&&v&&t.jsx(Jw,{summary:v,historyEntries:f,onSummaryChange:x,onApprove:oe,onStartOver:()=>{d({type:"initial"}),M(!1),x(null),p([]),b([]),A(null),w.current?.close(),w.current=null},isCreating:G}),X&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(so,{size:16}),t.jsx("span",{children:Ge?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),Ge&&t.jsx("button",{type:"button",onClick:()=>{E()},disabled:U,className:"btn btn-primary session-lock-take-control",children:U?"Taking control...":"Take Control"})]})})]})]})}):null}function Kw({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(Cs,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3,4,5,6].map(m=>t.jsx("div",{className:`planning-progress-step ${m<=n?"active":""}`},m))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~6"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:l,onChange:m=>c(m.target.value),onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&l.trim()&&(m.preventDefault(),u())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(m=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:m.id,checked:r[e.id]===m.id,onChange:()=>o({[e.id]:m.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(m=>{const h=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:m.id,checked:h.includes(m.id),onChange:g=>{const p=g.target.checked?[...h,m.id]:h.filter(f=>f!==m.id);o({[e.id]:p})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!0?"selected":""}`,onClick:()=>o({[e.id]:!0}),children:[t.jsx(tn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(Pt,{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(Ga,{size:16,className:"icon-ml-4"})]})})]})}function Jw({summary:e,historyEntries:n,onSummaryChange:s,onApprove:i,onStartOver:r,isCreating:o}){const[l,c]=a.useState(()=>new Set(e.milestones.map((y,R)=>R))),[u,d]=a.useState(()=>{const y=new Set;return e.milestones.forEach((R,j)=>{R.slices.forEach((C,S)=>y.add(`${j}-${S}`))}),y}),m=y=>{c(R=>{const j=new Set(R);return j.has(y)?j.delete(y):j.add(y),j})},h=y=>{d(R=>{const j=new Set(R);return j.has(y)?j.delete(y):j.add(y),j})},g=(y,R)=>{const j=[...e.milestones];j[y]={...j[y],...R},s({...e,milestones:j})},p=(y,R,j)=>{const C=[...e.milestones],S=[...C[y].slices];S[R]={...S[R],...j},C[y]={...C[y],slices:S},s({...e,milestones:C})},f=(y,R,j,C)=>{const S=[...e.milestones],P=[...S[y].slices],T=[...P[R].features];T[j]={...T[j],...C},P[R]={...P[R],features:T},S[y]={...S[y],slices:P},s({...e,milestones:S})},b=y=>{const R=e.milestones.filter((j,C)=>C!==y);s({...e,milestones:R})},v=(y,R)=>{const j=[...e.milestones];j[y]={...j[y],slices:j[y].slices.filter((C,S)=>S!==R)},s({...e,milestones:j})},x=(y,R,j)=>{const C=[...e.milestones],S=[...C[y].slices];S[R]={...S[R],features:S[R].features.filter((P,T)=>T!==j)},C[y]={...C[y],slices:S},s({...e,milestones:C})},k=(y,R)=>{const j=[...e.milestones],C=[...j[y].slices];C[R]={...C[R],features:[...C[R].features,{title:"New feature",description:""}]},j[y]={...j[y],slices:C},s({...e,milestones:j})},M=e.milestones.reduce((y,R)=>y+R.slices.reduce((j,C)=>j+C.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(Cs,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(tn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Mission Plan Ready"}),t.jsxs("p",{className:"text-muted",children:[e.milestones.length," milestones, ",M," 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:y=>s({...e,missionTitle:y.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:y=>s({...e,missionDescription:y.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Roadmap"}),t.jsx("div",{className:"roadmap-list",children:e.milestones.map((y,R)=>t.jsxs("div",{className:"roadmap-card",children:[t.jsxs("div",{className:"roadmap-card-header",onClick:()=>m(R),children:[l.has(R)?t.jsx(zt,{size:16,className:"icon-text-secondary"}):t.jsx(en,{size:16,className:"icon-text-secondary"}),t.jsx(Si,{size:16,className:"icon-milestone"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-title",value:y.title,onChange:j=>g(R,{title:j.target.value}),onClick:j=>j.stopPropagation()}),e.milestones.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:j=>{j.stopPropagation(),b(R)},title:"Remove milestone",children:t.jsx(Ht,{size:14,className:"icon-text-secondary"})})]}),l.has(R)&&t.jsxs("div",{className:"roadmap-card-body",children:[t.jsx("textarea",{className:"planning-textarea roadmap-textarea-md",rows:2,placeholder:"Milestone description...",value:y.description||"",onChange:j=>g(R,{description:j.target.value})}),t.jsxs("div",{className:"roadmap-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Verification Criteria"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-sm",rows:2,placeholder:"How to confirm this milestone is complete...",value:y.verification||"",onChange:j=>g(R,{verification:j.target.value})})]}),y.slices.map((j,C)=>{const S=`${R}-${C}`;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(zt,{size:14,className:"icon-text-secondary"}):t.jsx(en,{size:14,className:"icon-text-secondary"}),t.jsx(Il,{size:14,className:"icon-slice"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:j.title,onChange:P=>p(R,C,{title:P.target.value}),onClick:P=>P.stopPropagation()}),y.slices.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:P=>{P.stopPropagation(),v(R,C)},title:"Remove slice",children:t.jsx(Ht,{size:12,className:"icon-text-secondary"})})]}),u.has(S)&&t.jsxs("div",{className:"roadmap-slice-body",children:[t.jsxs("div",{className:"roadmap-slice-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Slice Verification"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-xs",rows:1,placeholder:"How to confirm this slice is done...",value:j.verification||"",onChange:P=>p(R,C,{verification:P.target.value})})]}),j.features.map((P,T)=>t.jsxs("div",{className:"roadmap-feature-row",children:[t.jsx(Ml,{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:P.title,onChange:_=>f(R,C,T,{title:_.target.value})}),P.description&&t.jsx("p",{className:"roadmap-feature-text",children:P.description}),P.acceptanceCriteria&&t.jsxs("p",{className:"roadmap-feature-text--italic",children:["AC: ",P.acceptanceCriteria]})]}),t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:()=>x(R,C,T),title:"Remove feature",children:t.jsx(Ht,{size:12,className:"icon-text-secondary"})})]},T)),t.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>k(R,C),children:[t.jsx(Vt,{size:12}),"Add Feature"]})]})]},C)})]})]},R))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:r,disabled:o,children:[t.jsx(ia,{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(it,{size:16,className:"spin icon-mr-8"}),"Creating Mission..."]}):t.jsxs(t.Fragment,{children:[t.jsx(tn,{size:16,className:"icon-mr-8"}),"Approve Plan"]})})]})]})}function Yw({isOpen:e,onClose:n,onApplied:s,targetType:i,targetId:r,targetTitle:o,missionContext:l,projectId:c,resumeSessionId:u}){const[d,m]=a.useState({type:"initial"}),[h,g]=a.useState(null),[p,f]=a.useState([]),[b,v]=a.useState([]),[x,k]=a.useState(null),[M,y]=a.useState(""),[R,j]=a.useState(!0),[C,S]=a.useState(!1),[P,T]=a.useState(!1),_=a.useRef(null),L=a.useRef(null),G=a.useRef(null),$=a.useRef(null),[I,w]=a.useState(null),q=a.useMemo(()=>_i(),[]);mo(e?I:null);const{activeTabMap:W,broadcastUpdate:B,broadcastCompleted:A,broadcastLock:z,broadcastUnlock:X,broadcastHeartbeat:E}=la(),U=i==="milestone"?pk:vk,pe=i==="milestone"?fk:yk,ie=i==="milestone"?gk:kk,re=i==="milestone"?bk:jk,F=i==="milestone"?xk:wk,ce=i==="milestone"?"Milestone":"Slice",ae=i==="milestone"?"milestone_interview":"slice_interview",Q=a.useCallback(ye=>{L.current?.close();const De=ie(ye,c,{onThinking:se=>{y(J=>J+se),B({sessionId:ye,status:"generating",needsInput:!1,owningTabId:q,type:ae,title:o,projectId:c??null})},onQuestion:se=>{S(!1),de(),m({type:"question",sessionId:ye,question:se}),y(""),B({sessionId:ye,status:"awaiting_input",needsInput:!0,owningTabId:q,type:ae,title:o,projectId:c??null})},onSummary:se=>{S(!1),de(),m({type:"summary",sessionId:ye,summary:se}),k(se),y(""),B({sessionId:ye,status:"complete",needsInput:!1,owningTabId:q,type:ae,title:o,projectId:c??null})},onError:se=>{const J=se||"Session failed while contacting the AI.";S(!1),g(null),m({type:"error",sessionId:ye,errorMessage:J}),y(""),G.current=ye,B({sessionId:ye,status:"error",needsInput:!1,owningTabId:q,type:ae,title:o,projectId:c??null}),A({sessionId:ye,status:"error"})},onComplete:()=>{S(!1),G.current=null,A({sessionId:ye,status:"complete"})},onConnectionStateChange:se=>{S(se==="reconnecting")}});L.current=De},[A,B,ie,ae,c,q,o]),de=()=>{k(null),f([]),v([]),y("")},Te=a.useCallback(async()=>{g(null),de(),S(!1),m({type:"loading"});try{const{sessionId:ye}=await U(r,c);G.current=ye,w(ye),Q(ye)}catch(ye){S(!1),g(xe(ye)||`Failed to start ${ce.toLowerCase()} interview`),m({type:"initial"}),G.current=null,w(null)}},[Q,c,U,r,ce]),fe=a.useCallback(async()=>{g(null),T(!0);try{await F(r,c),s(),m({type:"applied"})}catch(ye){g(xe(ye)||`Failed to skip ${ce.toLowerCase()} interview`),T(!1)}},[s,c,F,r,ce]);a.useEffect(()=>{e&&d.type==="initial"&&_.current?.focus()},[e,d.type]),a.useEffect(()=>{if(!e||!u||d.type!=="initial")return;let ye=!1;return Js(u).then(De=>{if(ye||!De)return;const se=Yi(De.conversationHistory);if(v(se),w(De.id),f(se.map(J=>J.response).filter(J=>!!(J&&typeof J=="object"&&!Array.isArray(J)))),De.status==="awaiting_input"&&De.currentQuestion)try{const J=JSON.parse(De.currentQuestion);G.current=De.id,m({type:"question",sessionId:De.id,question:J})}catch{g("Failed to restore session question.")}else if(De.status==="complete"&&De.result)try{const J=JSON.parse(De.result);G.current=De.id,k(J),m({type:"summary",sessionId:De.id,summary:J})}catch{g("Failed to restore session result.")}else De.status==="generating"?(G.current=De.id,De.thinkingOutput&&y(De.thinkingOutput),m({type:"loading"}),Q(De.id)):De.status==="error"&&(G.current=De.id,g(null),m({type:"error",sessionId:De.id,errorMessage:De.error??"The session encountered an error."}))}).catch(()=>{ye||g("Failed to resume session.")}),()=>{ye=!0}},[Q,e,u,d.type]),a.useEffect(()=>{e||(S(!1),w(null))},[e]),a.useEffect(()=>{if(!(!e||!I)){if($.current!==I){$.current&&X($.current,q),z(I,q),$.current=I;return}!I&&$.current&&(X($.current,q),$.current=null)}},[z,X,e,I,q]),a.useEffect(()=>{if(!e||!I||$.current!==I)return;E(q);const ye=setInterval(()=>{E(q)},3e4);return()=>{clearInterval(ye)}},[E,e,I,q]),a.useEffect(()=>()=>{L.current?.close(),L.current=null,$.current&&(X($.current,q),$.current=null)},[X,q]);const Se=a.useCallback(()=>{L.current?.close(),L.current=null,n()},[n]),te=a.useCallback(async()=>{L.current?.close(),L.current=null,de(),m({type:"initial"}),g(null),G.current=null,w(null),n()},[n]),we=a.useCallback(async ye=>{if(d.type!=="question")return;const{sessionId:De}=d;g(null),f(se=>[...se,ye]),v(se=>[...se,{question:d.question,response:ye}]),m({type:"loading"}),y("");try{Q(De),await pe(De,ye,c,q)}catch(se){L.current?.close(),L.current=null,g(xe(se)||"Failed to submit response"),m({type:"question",sessionId:De,question:d.question})}},[Q,c,pe,q,d]),Pe=a.useCallback(async()=>{if(d.type==="summary"){g(null),T(!0);try{await re(d.sessionId,x||void 0,c),s(),m({type:"applied"})}catch(ye){g(xe(ye)||"Failed to apply interview results"),T(!1)}}},[re,x,s,c,d]),We=()=>d.type==="question"?Math.min(p.length+1,6):6,Ke=d.type==="loading"||d.type==="question"||d.type==="summary"||d.type==="error",Ne=I?W.get(I):null,Oe=!!(Ne&&Ne.tabId!==q&&!Ne.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:ye=>ye.target===ye.currentTarget&&te(),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(Dn,{size:20,className:"icon-triage"}),t.jsxs("h3",{children:["Plan ",ce,": ",o]})]}),t.jsxs("div",{className:"modal-header-actions",children:[Ke&&t.jsx("button",{className:"modal-send-to-background",onClick:Se,title:"Send to background","aria-label":"Send to background",children:t.jsx(aa,{size:16})}),t.jsx("button",{className:"modal-close",onClick:te,"aria-label":"Close",children:t.jsx(Pt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[h&&t.jsx("div",{className:"form-error planning-error",children:h}),C&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Oe&&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(Dn,{size:32,className:"icon-triage-lg"}),t.jsxs("h4",{children:["Refine ",ce," 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 Te(),children:[t.jsx(Dn,{size:16,className:"icon-mr-8"}),"Start Interview"]}),t.jsxs("button",{className:"btn planning-use-context-btn",onClick:()=>void fe(),disabled:P,children:[P?t.jsx(it,{size:16,className:"spin"}):null,"Use Mission Context"]}),t.jsx("button",{className:"btn",onClick:te,children:"Cancel"})]})]}),d.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(it,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:M?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>j(!R),type:"button",children:R?"Hide thinking":"Show thinking"}),R&&M&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:M})})]})]}),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(Cs,{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:te,children:"Cancel"})})]})]})}),d.type==="question"&&t.jsx(Qw,{question:d.question,progress:We(),historyEntries:b,onSubmit:we}),d.type==="summary"&&x&&t.jsx(Xw,{summary:x,historyEntries:b,onSummaryChange:k,onApply:Pe,onCancel:te,isApplying:P}),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(tn,{size:48,className:"icon-success"}),t.jsxs("h4",{children:[ce," 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 Qw({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(Cs,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3,4,5,6].map(m=>t.jsx("div",{className:`planning-progress-step ${m<=n?"active":""}`},m))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~6"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:l,onChange:m=>c(m.target.value),onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&l.trim()&&(m.preventDefault(),u())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(m=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:m.id,checked:r[e.id]===m.id,onChange:()=>o({[e.id]:m.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(m=>{const h=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:m.id,checked:h.includes(m.id),onChange:g=>{const p=g.target.checked?[...h,m.id]:h.filter(f=>f!==m.id);o({[e.id]:p})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!0?"selected":""}`,onClick:()=>o({[e.id]:!0}),children:[t.jsx(tn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(Pt,{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(Ga,{size:16,className:"icon-ml-4"})]})})]})}function Xw({summary:e,historyEntries:n,onSummaryChange:s,onApply:i,onCancel:r,isApplying:o}){const[l,c]=a.useState(e),[u,d]=a.useState(!0),m=(h,g)=>{const p={...l,[h]:g};c(p),s(p)};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Cs,{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(zt,{size:16}):t.jsx(en,{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(it,{size:16,className:"spin"}):null,"Apply"]}),t.jsx("button",{className:"btn",onClick:r,disabled:o,children:"Cancel"})]})]})}const ba={planning:{bg:"var(--mission-planning-bg)",text:"var(--mission-planning-text)"},active:{bg:"var(--mission-active-bg)",text:"var(--mission-active-text)"},blocked:{bg:"var(--mission-blocked-bg)",text:"var(--mission-blocked-text)"},complete:{bg:"var(--mission-complete-bg)",text:"var(--mission-complete-text)"},archived:{bg:"var(--mission-archived-bg)",text:"var(--mission-archived-text)"}},tu={planning:{bg:"var(--mission-planning-bg)",text:"var(--mission-planning-text)"},active:{bg:"var(--mission-active-bg)",text:"var(--mission-active-text)"},blocked:{bg:"var(--mission-blocked-bg)",text:"var(--mission-blocked-text)"},complete:{bg:"var(--mission-complete-bg)",text:"var(--mission-complete-text)"}},nu={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)"}},fr={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)"}},gr={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)"}},br={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)"}},su={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)"}},Zw=3;function eN(e){return e==="completed"?"planned":e==="needs_update"?"needs_update":"not_started"}function iu({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 au(e){return e?e.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const Fo={title:"",description:"",status:"planning",autopilotEnabled:!1},Oo={title:"",description:"",status:"planning",dependencies:[]},Uo={title:"",description:"",status:"pending"},Bo={title:"",description:"",acceptanceCriteria:"",status:"defined"},tN=3600*1e3;function Vr(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 nN(e){if(!e)return"healthy";const n=typeof e.lastErrorAt=="string"&&Date.now()-new Date(e.lastErrorAt).getTime()<=tN,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 sN(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 iN(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 Ho(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 Uh=["feature_triaged","feature_completed"],Bh=["slice_activated","slice_completed","milestone_completed"],Hh=["mission_started","mission_paused","mission_resumed","mission_completed"],qh=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function ru(e,n){switch(n){case"errors":return e==="error"||e==="warning";case"state_changes":return Hh.includes(e);case"tasks":return Uh.includes(e);case"slices":return Bh.includes(e);case"autopilot":return qh.includes(e);default:return!0}}function aN(e){return e==="error"||e==="warning"?"mission-event__type--error":Hh.includes(e)?"mission-event__type--state":Uh.includes(e)?"mission-event__type--task":Bh.includes(e)?"mission-event__type--slice":qh.includes(e)?"mission-event__type--autopilot":"mission-event__type--default"}function rN(e){return e.replace(/_/g," ")}function oN(e,n){return n?e==="watching"?`Watching since ${Vr(n)}`:`Last activation ${Vr(n)}`:null}function lN({isOpen:e,isInline:n=!1,onClose:s,addToast:i,projectId:r,onSelectTask:o,availableTasks:l=[],resumeSessionId:c,targetMissionId:u,milestoneSliceResumeSessionId:d,onMilestoneSliceResumeFetchError:m}){const h=n||e,[g,p]=a.useState([]),[f,b]=a.useState(null),[v,x]=a.useState(!0),[k,M]=a.useState(!1),[y,R]=a.useState(!1),[j,C]=a.useState(null),[S,P]=a.useState(Fo),[T,_]=a.useState(!1),[L,G]=a.useState(new Set),[$,I]=a.useState(new Set),[w,q]=a.useState(null),[W,B]=a.useState(Oo),[A,z]=a.useState(!1),[X,E]=a.useState(null),[U,pe]=a.useState(Uo),[ie,re]=a.useState(!1),[F,ce]=a.useState(null),[ae,Q]=a.useState(null),[de,Te]=a.useState(Bo),[fe,Se]=a.useState(!1),[te,we]=a.useState(null),[Pe,We]=a.useState(null),[Ke,Ne]=a.useState(""),[_e,Oe]=a.useState(!1),[ye,De]=a.useState([]),[se,J]=a.useState(void 0),me=se??c,[ee,he]=a.useState(null),[le,Ie]=a.useState(null),[Ze,at]=a.useState(null);a.useEffect(()=>{h&&me&&Oe(!0)},[h,me]),a.useEffect(()=>{if(!h||me)return;let O=!1;return Sh(r).then(ke=>{if(O)return;const Re=ke.filter(ht=>ht.type==="mission_interview"&&(ht.status==="awaiting_input"||ht.status==="error"));De(Re)}).catch(ke=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",ke)}),()=>{O=!0}},[h,r,me]),a.useEffect(()=>{if(!h||!d)return;let O=!1;return Js(d).then(ke=>{if(!(O||!ke))try{const Re=JSON.parse(ke.inputPayload||"{}");Re.targetId&&Re.targetType&&he({type:Re.targetType,id:Re.targetId,title:Re.targetTitle||ke.title,resumeSessionId:d})}catch{he({type:"milestone",id:"",title:ke.title,resumeSessionId:d})}}).catch(ke=>{O||(console.warn("[MissionManager] Failed to fetch session for milestone/slice resume:",ke),m?.())}),()=>{O=!0}},[h,d,m]);const[oe,Z]=a.useState(null),[ue,Ce]=a.useState(new Map),[$e,ve]=a.useState(null),[Ge,je]=a.useState({title:"",assertion:"",status:"pending"}),[Ue,He]=a.useState(!1),[ge,Fe]=a.useState(null),[be,Je]=a.useState(new Map),[st,dt]=a.useState(new Set),[Tt,$t]=a.useState(new Set),[Dt,Bt]=a.useState(null),[qt,Lt]=a.useState(new Map),[Ct,xt]=a.useState(null),[Et,Le]=a.useState(null),[gt,ut]=a.useState(!0),[Me,Qe]=a.useState(new Set),[rt,N]=a.useState(new Map),[H,Ae]=a.useState(null),[ot,kt]=a.useState(new Map),[Ot,sn]=a.useState(null),[Rt,zn]=a.useState(new Map),[Wn,ms]=a.useState(new Map),[pn,Fn]=a.useState("structure"),[Sn,fn]=a.useState([]),Gn=a.useRef([]),dn=a.useRef([]),Mt=a.useRef(null),yn=a.useRef(null),Kn=a.useRef("structure"),kn=a.useRef("all"),[_n,hs]=a.useState(!1),[ps,On]=a.useState(0),[K,ze]=a.useState("all"),[tt,et]=a.useState(new Set),mt=a.useRef(null),jt=a.useRef(null);dn.current=g,Mt.current=f,yn.current=Ct,Kn.current=pn,kn.current=K;const _t=a.useCallback((O="auto")=>{const ke=jt.current;if(ke&&typeof ke.scrollIntoView=="function"){ke.scrollIntoView({block:"end",behavior:O});return}const Re=mt.current;Re&&(Re.scrollTop=Re.scrollHeight)},[]),gn=a.useCallback(()=>{const O=mt.current;return O?O.scrollHeight-O.scrollTop-O.clientHeight<=100:!0},[]),fs=a.useCallback(async O=>{if(O.length===0){ms(new Map);return}const ke=await Dy(r);ms(Re=>{const ht=new Map(Re);for(const[Kt,Nt]of Object.entries(ke))sN(Nt)&&ht.set(Kt,Nt);return ht})},[r]),Qt=a.useCallback(async()=>{try{x(!0);const O=await Ty(r);p(O),fs(O)}catch(O){i(xe(O)||"Failed to load missions","error")}finally{x(!1)}},[i,r,fs]),vt=a.useCallback(async O=>{try{M(!0);const ke=await wh(O,r);if(b(ke),ke.milestones.length>0){const Re=ke.milestones[0].id;xt(Re),ut(!0),G(new Set([Re])),Ro(Re,r).then(ht=>{Ce(Kt=>{const Nt=new Map(Kt);return Nt.set(Re,ht),Nt})}).catch(()=>{}),Io(Re,r).then(ht=>{Lt(Kt=>{const Nt=new Map(Kt);return Nt.set(Re,ht),Nt})}).catch(()=>{}),ke.milestones[0].slices.length>0&&I(new Set([ke.milestones[0].slices[0].id]))}else xt(null),Le(null)}catch(ke){i(xe(ke)||"Failed to load mission details","error")}finally{M(!1)}},[i,r]);a.useEffect(()=>{if(!h||!Ct){Le(null);return}let O=!1;return Le(null),xd(Ct,r).then(ke=>{if(!O){if(!Ho(ke)){Le(null);return}Le(ke),Lt(Re=>{const ht=new Map(Re);return ht.set(Ct,ke.rollup),ht})}}).catch(()=>{O||Le(null)}),()=>{O=!0}},[h,Ct,r]),a.useEffect(()=>{ut(!0)},[Ct]);const ct=a.useCallback(O=>{!O||O!==yn.current||xd(O,r).then(ke=>{yn.current!==O||!Ho(ke)||(Le(ke),Lt(Re=>{const ht=new Map(Re);return ht.set(O,ke.rollup),ht}))}).catch(()=>{})},[r]),ne=a.useCallback(async(O,ke)=>{const Re=ke?.append??!1,ht=Re?Gn.current.length:0;Re||(hs(!0),et(new Set));try{const Kt=await $y(O,{limit:50,offset:ht,eventType:void 0},r),Nt=Kt.events.filter(Ut=>ru(Ut.eventType,K));fn(Ut=>{if(!Re)return Nt;const Be=new Set(Ut.map(pt=>pt.id)),qe=[...Ut];for(const pt of Nt)Be.has(pt.id)||qe.push(pt);return qe}),On(Kt.total),Re||requestAnimationFrame(()=>{_t("auto")})}catch(Kt){i(xe(Kt)||"Failed to load mission activity","error")}finally{Re||hs(!1)}},[i,K,r,_t]);a.useEffect(()=>{Gn.current=Sn},[Sn]),a.useEffect(()=>{h&&(Qt(),b(null),xt(null),Le(null),fn([]),On(0),Fn("structure"),ze("all"),et(new Set))},[h,Qt]);const Ee=a.useRef(null);a.useEffect(()=>{h&&u&&Ee.current!==u&&g.length>0&&(Ee.current=u,vt(u))},[h,u,g,vt]),a.useEffect(()=>{h||(Ee.current=null)},[h]),a.useEffect(()=>{!h||!f||pn!=="activity"||ne(f.id)},[pn,h,ne,f,K]),a.useEffect(()=>{if(!h||typeof EventSource>"u")return;const O=new URLSearchParams;r&&O.set("projectId",r);const ke=`/api/events${O.size>0?`?${O.toString()}`:""}`,Re=()=>{fs(dn.current)},ht=En=>{Re();const ln=En;if(ln.data)try{const At=JSON.parse(ln.data);At?.id&&p(pi=>pi.map(ys=>ys.id===At.id?{...ys,...At}:ys))}catch{}Mt.current&&vt(Mt.current.id)},Kt=En=>{Re(),Mt.current&&vt(Mt.current.id)},Nt=()=>{Re(),Mt.current&&vt(Mt.current.id)},Ut=En=>{Re(),Mt.current&&vt(Mt.current.id)},Be=En=>{const ln=En;if(ln.data)try{const At=JSON.parse(ln.data);At&&At.featureId&&(Ws(At.featureId),ni(At.featureId),At.milestoneId&&ct(At.milestoneId))}catch{}},qe=En=>{const ln=En;if(ln.data)try{const At=JSON.parse(ln.data);At&&At.featureId&&(Ws(At.featureId),ni(At.featureId),At.milestoneId&&ct(At.milestoneId),Mt.current&&vt(Mt.current.id))}catch{}},pt=En=>{const ln=En;if(ln.data)try{const At=JSON.parse(ln.data);At&&At.milestoneId&&(Y(At.milestoneId),ct(At.milestoneId))}catch{}},Jt=En=>{const ln=En;if(ln.data)try{const At=JSON.parse(ln.data);At&&At.milestoneId&&(ti(At.milestoneId),Y(At.milestoneId),ct(At.milestoneId))}catch{}};return qs(ke,{events:{"mission:updated":ht,"slice:updated":Kt,"feature:updated":Nt,"milestone:updated":Ut,"mission:event":En=>{Re();const ln=Mt.current;if(!ln||Kn.current!=="activity")return;const At=gn(),pi=En;if(pi.data)try{const ys=JSON.parse(pi.data);if(!iN(ys)||ys.missionId!==ln.id||!ru(ys.eventType,kn.current))return;fn(Gs=>{const Eo=Gs.filter(Mo=>Mo.id!==ys.id);return[ys,...Eo].slice(0,100)}),On(Gs=>Gs+1),At&&requestAnimationFrame(()=>{const Gs=mt.current;Gs&&(Gs.scrollTop=0)})}catch{}},"validator-run:started":Be,"validator-run:completed":qe,"milestone:validation:updated":pt,"assertion:created":Jt,"assertion:updated":Jt,"assertion:deleted":Jt,"assertion:linked":Jt,"assertion:unlinked":Jt,"fix-feature:created":En=>{const ln=En;if(ln.data)try{const At=JSON.parse(ln.data);if(At&&At.sourceFeatureId){Ws(At.sourceFeatureId);const pi=At?.feature?.sliceId,ys=Mt.current;if(pi&&ys){const Gs=ys.milestones.find(Eo=>Eo.slices.some(Mo=>Mo.id===pi));Gs&&ct(Gs.id)}Mt.current&&vt(Mt.current.id)}}catch{}}}})},[h,gn,vt,fs,r,ct]);const nt=a.useCallback(()=>{R(!0),C(null),P(Fo)},[]),ft=a.useCallback(O=>{C(O.id),R(!1),P({title:O.title,description:O.description||"",status:O.status,autopilotEnabled:O.autopilotEnabled??!1})},[]),bt=a.useCallback(()=>{C(null),R(!1),P(Fo)},[]),on=a.useCallback(async()=>{if(!S.title.trim()){i("Mission title is required","error");return}try{if(_(!0),y)await Ry({title:S.title.trim(),description:S.description.trim()||void 0,autopilotEnabled:S.autopilotEnabled},r),i("Mission created","success");else if(j){const O={title:S.title.trim(),description:S.description.trim()||void 0,status:S.status,autopilotEnabled:S.autopilotEnabled};S.autopilotEnabled&&(O.autoAdvance=!0),await Iy(j,O,r),i("Mission updated","success"),f?.id===j&&await vt(j)}await Qt(),bt()}catch(O){i(xe(O)||"Failed to save mission","error")}finally{_(!1)}},[S,y,j,i,Qt,vt,f,bt,r]),Xt=a.useCallback(async O=>{try{await Py(O,r),i("Mission deleted","success"),f?.id===O&&b(null),await Qt(),Z(null)}catch(ke){i(xe(ke)||"Failed to delete mission","error")}},[i,Qt,f,r]),cn=a.useCallback(()=>{z(!0),q(null),B(Oo)},[]),Gt=a.useCallback(O=>{q(O.id),z(!1),B({title:O.title,description:O.description||"",status:O.status,dependencies:O.dependencies})},[]),bn=a.useCallback(()=>{q(null),z(!1),B(Oo)},[]),Cn=a.useCallback(async()=>{if(!W.title.trim()){i("Milestone title is required","error");return}try{_(!0),A&&f?(await Ly(f.id,{title:W.title.trim(),description:W.description.trim()||void 0,dependencies:W.dependencies},r),i("Milestone created","success")):w&&(await zy(w,{title:W.title.trim(),description:W.description.trim()||void 0,status:W.status,dependencies:W.dependencies},r),i("Milestone updated","success")),await vt(f.id),bn()}catch(O){i(xe(O)||"Failed to save milestone","error")}finally{_(!1)}},[W,A,w,f,i,vt,bn,S.title,r]),gs=a.useCallback(async O=>{try{await Fy(O,r),i("Milestone deleted","success"),await vt(f.id),Z(null)}catch(ke){i(xe(ke)||"Failed to delete milestone","error")}},[i,vt,f,r]),Un=a.useCallback(O=>{xt(O),ut(!0),G(ke=>{const Re=new Set(ke);return!Re.has(O)?(Re.add(O),Ro(O,r).then(Kt=>{Ce(Nt=>{const Ut=new Map(Nt);return Ut.set(O,Kt),Ut})}).catch(()=>{}),Io(O,r).then(Kt=>{Lt(Nt=>{const Ut=new Map(Nt);return Ut.set(O,Kt),Ut})}).catch(()=>{})):Re.delete(O),Re})},[r]),Jn=a.useCallback(O=>{ce(O),re(!0),E(null),pe(Uo)},[]),Bn=a.useCallback(O=>{E(O.id),re(!1),pe({title:O.title,description:O.description||"",status:O.status})},[]),Yn=a.useCallback(()=>{E(null),re(!1),ce(null),pe(Uo)},[]),un=a.useCallback(async()=>{if(!U.title.trim()){i("Slice title is required","error");return}try{_(!0),ie&&F?(await Oy(F,{title:U.title.trim(),description:U.description.trim()||void 0},r),i("Slice created","success")):X&&(await Uy(X,{title:U.title.trim(),description:U.description.trim()||void 0,status:U.status},r),i("Slice updated","success")),await vt(f.id),Yn()}catch(O){i(xe(O)||"Failed to save slice","error")}finally{_(!1)}},[U,ie,X,F,f,i,vt,Yn,r]),Qn=a.useCallback(async O=>{try{await By(O,r),i("Slice deleted","success"),await vt(f.id),Z(null)}catch(ke){i(xe(ke)||"Failed to delete slice","error")}},[i,vt,f,r]),Es=a.useCallback(async O=>{try{await Hy(O,r),i("Slice activated","success"),await vt(f.id)}catch(ke){i(xe(ke)||"Failed to activate slice","error")}},[i,vt,f,r]),Is=a.useCallback(O=>{I(ke=>{const Re=new Set(ke);return Re.has(O)?Re.delete(O):Re.add(O),Re})},[]),rs=a.useCallback(O=>{we(O),Se(!0),Q(null),Te(Bo)},[]),An=a.useCallback(O=>{Q(O.id),Se(!1),Te({title:O.title,description:O.description||"",acceptanceCriteria:O.acceptanceCriteria||"",status:O.status})},[]),bs=a.useCallback(()=>{Q(null),Se(!1),we(null),Te(Bo)},[]),Tn=a.useCallback(async()=>{if(!de.title.trim()){i("Feature title is required","error");return}try{_(!0),fe&&te?(await qy(te,{title:de.title.trim(),description:de.description.trim()||void 0,acceptanceCriteria:de.acceptanceCriteria.trim()||void 0},r),i("Feature created","success")):ae&&(await Vy(ae,{title:de.title.trim(),description:de.description.trim()||void 0,acceptanceCriteria:de.acceptanceCriteria.trim()||void 0,status:de.status},r),i("Feature updated","success")),await vt(f.id),bs()}catch(O){i(xe(O)||"Failed to save feature","error")}finally{_(!1)}},[de,fe,ae,te,f,i,vt,bs,r]),ua=a.useCallback(async O=>{try{await Wy(O,r),i("Feature deleted","success"),await vt(f.id),Z(null)}catch(ke){i(xe(ke)||"Failed to delete feature","error")}},[i,vt,f,r]),xo=a.useCallback(async()=>{if(!Pe||!Ke.trim()){i("Task ID is required","error");return}try{await Gy(Pe,Ke.trim(),r),i("Feature linked to task","success"),await vt(f.id),We(null),Ne("")}catch(O){i(xe(O)||"Failed to link feature to task","error")}},[Pe,Ke,i,vt,f,r]),vo=a.useCallback(async O=>{try{await Ky(O,r),i("Feature unlinked from task","success"),await vt(f.id)}catch(ke){i(xe(ke)||"Failed to unlink feature","error")}},[i,vt,f,r]),mi=a.useCallback(async O=>{try{_(!0),await Jy(O,void 0,void 0,r),i("Feature triaged — task created","success"),await vt(f.id)}catch(ke){i(xe(ke)||"Failed to triage feature","error")}finally{_(!1)}},[i,vt,f,r]),ar=a.useCallback(async O=>{at(O);try{const ke=await Nk(O,r);Ie({featureId:O,enrichedDescription:ke.description})}catch{await mi(O)}finally{at(null)}},[mi,r]),rr=a.useCallback(async()=>{le&&(Ie(null),await mi(le.featureId))},[mi,le]),ei=a.useCallback(()=>{Ie(null)},[]),yo=a.useCallback(async O=>{try{_(!0);const ke=await Yy(O,r);i(`Triaged ${ke.count} feature${ke.count!==1?"s":""}`,"success"),await vt(f.id)}catch(ke){i(xe(ke)||"Failed to triage slice features","error")}finally{_(!1)}},[i,vt,f,r]),ti=a.useCallback(async O=>{try{const ke=await Ro(O,r);Ce(Re=>{const ht=new Map(Re);return ht.set(O,ke),ht})}catch{}},[r]),Y=a.useCallback(async O=>{try{const ke=await Io(O,r);Lt(Re=>{const ht=new Map(Re);return ht.set(O,ke),ht})}catch{}},[r]),Ye=a.useCallback(async O=>{if(!Ge.title.trim()||!Ge.assertion.trim()){i("Title and assertion text are required","error");return}try{_(!0),await Qy(O,{title:Ge.title.trim(),assertion:Ge.assertion.trim(),status:Ge.status},r),i("Assertion created","success"),await ti(O),await Y(O),He(!1),je({title:"",assertion:"",status:"pending"})}catch(ke){i(xe(ke)||"Failed to create assertion","error")}finally{_(!1)}},[Ge,i,ti,Y,r]),lt=a.useCallback(O=>{ve(O.id),je({title:O.title,assertion:O.assertion,status:O.status})},[]),wt=a.useCallback(()=>{ve(null),He(!1),je({title:"",assertion:"",status:"pending"})},[]),Ms=a.useCallback(async(O,ke)=>{if(!Ge.title.trim()||!Ge.assertion.trim()){i("Title and assertion text are required","error");return}try{_(!0),await Xy(O,{title:Ge.title.trim(),assertion:Ge.assertion.trim(),status:Ge.status},r),i("Assertion updated","success"),await ti(ke),await Y(ke),wt()}catch(Re){i(xe(Re)||"Failed to update assertion","error")}finally{_(!1)}},[Ge,i,ti,Y,wt,r]),Rn=a.useCallback(async O=>{try{const ke=await tk(O,r);Je(Re=>{const ht=new Map(Re);return ht.set(O,ke),ht})}catch{}},[r]),or=a.useCallback(async O=>{const ke=ge!==O;Fe(Re=>Re===O?null:O),ke&&await Rn(O)},[ge,Rn]),ma=a.useCallback(O=>{Fe(O),Rn(O),requestAnimationFrame(()=>{const ke=document.querySelector(`[data-mission-assertion-id="${O}"]`);ke instanceof HTMLElement&&typeof ke.scrollIntoView=="function"&&ke.scrollIntoView({behavior:"smooth",block:"center"})})},[Rn]),ko=a.useCallback(async(O,ke)=>{try{dt(Re=>new Set(Re).add(ke)),await Zy(O,ke,r),i("Feature linked to assertion","success"),await Rn(ke),Bt(null)}catch(Re){i(xe(Re)||"Failed to link feature","error")}finally{dt(Re=>{const ht=new Set(Re);return ht.delete(ke),ht})}},[i,Rn,r]),jo=a.useCallback(async(O,ke)=>{const Re=`${O}-${ke}`;try{$t(ht=>new Set(ht).add(Re)),await ek(O,ke,r),i("Feature unlinked from assertion","success"),await Rn(ke)}catch(ht){i(xe(ht)||"Failed to unlink feature","error")}finally{$t(ht=>{const Kt=new Set(ht);return Kt.delete(Re),Kt})}},[i,Rn,r]),wo=a.useCallback(async O=>{try{Qe(Re=>new Set(Re).add(O)),await nk(O,r),i("Validation triggered","success");const ke=await vd(O,r);N(Re=>{const ht=new Map(Re);return ht.set(O,ke),ht})}catch(ke){i(xe(ke)||"Failed to trigger validation","error")}finally{Qe(ke=>{const Re=new Set(ke);return Re.delete(O),Re})}},[i,r]),Ws=a.useCallback(async O=>{try{const ke=await vd(O,r);N(Re=>{const ht=new Map(Re);return ht.set(O,ke),ht})}catch{}},[r]),ni=a.useCallback(async O=>{try{const ke=await sk(O,{limit:10},r);kt(Re=>{const ht=new Map(Re);return ht.set(O,ke),ht})}catch{}},[r]),si=a.useCallback(O=>{const ke=Mt.current;if(ke){for(const Re of ke.milestones)for(const ht of Re.slices)if(ht.features.find(Nt=>Nt.id===O)){G(Nt=>{const Ut=new Set(Nt);return Ut.add(Re.id),Ut}),I(Nt=>{const Ut=new Set(Nt);return Ut.add(ht.id),Ut}),Ae(O),xt(Re.id),Ws(O),ni(O),requestAnimationFrame(()=>{const Nt=document.querySelector(`[data-mission-feature-id="${O}"]`);Nt instanceof HTMLElement&&typeof Nt.scrollIntoView=="function"&&Nt.scrollIntoView({behavior:"smooth",block:"center"})});return}}},[Ws,ni]),Ti=a.useCallback(async O=>{try{const ke=await ik(O,r);zn(Re=>{const ht=new Map(Re);return ht.set(O,ke),ht})}catch{}},[r]),Ri=a.useCallback(async O=>{H===O?Ae(null):(Ae(O),await Ws(O),await ni(O))},[H,Ws,ni]),ha=a.useCallback(async O=>{Ot===O?sn(null):(sn(O),await Ti(O))},[Ot,Ti]),No=a.useCallback(async O=>{try{await ak(O,r),i("Mission resumed","success"),await vt(O),Qt()}catch(ke){i(xe(ke)||"Failed to resume mission","error")}},[i,vt,Qt,r]),So=a.useCallback(async O=>{try{const Re=(await rk(O,r)).pausedTaskIds?.length??0;i(`Mission stopped (${Re} task${Re!==1?"s":""} paused)`,"success"),await vt(O),Qt()}catch(ke){i(xe(ke)||"Failed to stop mission","error")}},[i,vt,Qt,r]),xs=a.useCallback(async O=>{try{await ok(O,r),i("Mission started — first slice activated","success"),await vt(O),Qt()}catch(ke){i(xe(ke)||"Failed to start mission","error")}},[i,vt,Qt,r]),ii=a.useCallback(async(O,ke)=>{try{await lk(O,{enabled:ke},r),i(ke?"Autopilot enabled":"Autopilot disabled","success"),await vt(O),Qt()}catch(Re){i(xe(Re)||"Failed to update autopilot","error")}},[i,vt,Qt,r]),_s=a.useCallback(O=>{Fn("structure"),xt(null),Le(null),fn([]),On(0),ze("all"),et(new Set),vt(O.id)},[vt]),Ps=a.useCallback(()=>{b(null),xt(null),Le(null),Fn("structure"),fn([]),On(0),ze("all"),et(new Set),Qt()},[Qt]),lr=Sn.length<ps,Ii=f?.autopilotState??"inactive",zc=Ii==="watching"||Ii==="activating",Fc=oN(Ii,f?.lastAutopilotActivityAt),cr=a.useMemo(()=>!Et||!Ct||!Ho(Et)?null:Et.rollup.milestoneId===Ct?Et:null,[Ct,Et]),kf=a.useMemo(()=>{const O=new Map;for(const ke of cr?.validationTelemetry.validationRounds??[]){const Re=O.get(ke.featureId);(!Re||ke.startedAt>Re.startedAt)&&O.set(ke.featureId,ke)}return O},[cr]),jf=a.useCallback(()=>{!f||_n||!lr||ne(f.id,{append:!0})},[_n,lr,ne,f]),wf=a.useCallback(O=>{et(ke=>{const Re=new Set(ke);return Re.has(O)?Re.delete(O):Re.add(O),Re})},[]),Co=a.useCallback(O=>{O.key==="Enter"&&!O.shiftKey&&(O.preventDefault(),on())},[on]),Oc=a.useCallback(O=>{O.key==="Enter"&&!O.shiftKey&&(O.preventDefault(),Cn())},[Cn]),Uc=a.useCallback(O=>{O.key==="Enter"&&!O.shiftKey&&(O.preventDefault(),un())},[un]),Bc=a.useCallback(O=>{O.key==="Enter"&&!O.shiftKey&&(O.preventDefault(),Tn())},[Tn]),Nf=a.useRef(null);if(a.useEffect(()=>{if(!h)return;const O=ke=>{ke.key==="Escape"&&s()};return document.addEventListener("keydown",O),()=>document.removeEventListener("keydown",O)},[h,s]),!h)return null;const Hc=t.jsxs("div",{ref:Nf,className:`mission-manager${n?" mission-manager--inline":""}`,role:n?void 0:"dialog","aria-modal":n?void 0:!0,"aria-label":n?void 0:"Mission Manager","data-testid":"mission-manager-dialog",children:[t.jsxs("div",{className:`mission-manager__header${n?" mission-manager__header--inline":""}`,children:[t.jsxs("div",{className:"mission-manager__header-title",children:[f?t.jsx("button",{className:"mission-manager__back-btn",onClick:Ps,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:t.jsx(rc,{size:18})}):null,t.jsx(ns,{size:18,className:"mission-manager__header-icon"}),t.jsx("h2",{className:"mission-manager__title",children:f?f.title:"Missions"})]}),!n&&t.jsx("button",{className:"modal-close",onClick:s,title:"Close","aria-label":"Close Mission Manager","data-testid":"mission-close-btn",children:t.jsx(Pt,{size:18})})]}),t.jsx("div",{className:"mission-manager__body",children:v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(it,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):k?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(it,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):f?t.jsxs("div",{className:"mission-detail",children:[t.jsxs("div",{className:"mission-detail__header",children:[t.jsxs("div",{className:"mission-detail__title-row",children:[t.jsxs("div",{className:"mission-detail__title-text",children:[zc&&t.jsx("span",{className:"mission-detail__autopilot-dot",title:"Autopilot watching"}),t.jsx("h3",{className:"mission-detail__title",children:f.title})]}),t.jsx("span",{className:"mission-status-badge",style:{backgroundColor:(ba[f.status]||ba.planning).bg,color:(ba[f.status]||ba.planning).text},children:f.status})]}),f.description&&t.jsx("p",{className:"mission-detail__description",children:f.description}),t.jsx("div",{className:"mission-detail__meta",children:t.jsxs("span",{className:"mission-detail__meta-info",children:[f.milestones.length," milestones"]})}),t.jsxs("div",{className:"mission-detail__autopilot",children:[t.jsxs("div",{className:"mission-detail__autopilot-toggle",children:[t.jsxs("label",{className:"mission-toggle","data-testid":"mission-autopilot-toggle",children:[t.jsx("input",{type:"checkbox",checked:f.autopilotEnabled??!1,onChange:O=>ii(f.id,O.target.checked),"aria-label":"Autopilot"}),t.jsx("span",{className:"mission-toggle__track","aria-hidden":"true",children:t.jsx("span",{className:"mission-toggle__thumb"})}),t.jsxs("span",{className:"mission-toggle__label",children:[t.jsx(vn,{size:14,className:"mission-detail__autopilot-icon"}),"Autopilot"]})]}),t.jsxs("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(gr[Ii]||gr.inactive).bg,color:(gr[Ii]||gr.inactive).text},"data-testid":"autopilot-state-badge",children:[zc&&t.jsx("span",{className:"mission-detail__autopilot-pulse"}),Ii]})]}),Fc&&t.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:Fc})]}),t.jsxs("div",{className:"mission-detail__actions",children:[f.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>So(f.id),title:"Stop mission","aria-label":"Stop mission",children:t.jsx(ls,{size:14})}),f.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>No(f.id),title:"Resume mission","aria-label":"Resume mission",children:t.jsx(rn,{size:14})}),f.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>xs(f.id),title:"Start mission","aria-label":"Start mission",children:t.jsx(rn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>ft(f),title:"Edit mission","aria-label":"Edit mission",children:t.jsx(Hn,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Z({type:"mission",id:f.id}),title:"Delete mission","aria-label":"Delete mission",children:t.jsx(Ht,{size:14})})]})]}),j===f.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:S.title,onChange:O=>P({...S,title:O.target.value}),onKeyDown:Co,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:S.description,onChange:O=>P({...S,description:O.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:S.status,onChange:O=>P({...S,status:O.target.value}),children:[t.jsx("option",{value:"planning",children:"Planning"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"blocked",children:"Blocked"}),t.jsx("option",{value:"complete",children:"Complete"}),t.jsx("option",{value:"archived",children:"Archived"})]}),t.jsxs("label",{className:"mission-checkbox",children:[t.jsx("input",{type:"checkbox",checked:S.autopilotEnabled,onChange:O=>P({...S,autopilotEnabled:O.target.checked})}),t.jsx(vn,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:on,disabled:T,children:[T?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bt,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-detail__tabs",role:"tablist","aria-label":"Mission detail tabs",children:[t.jsx("button",{className:`mission-btn ${pn==="structure"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Fn("structure"),role:"tab","aria-selected":pn==="structure","data-testid":"mission-tab-structure",children:"Structure"}),t.jsxs("button",{className:`mission-btn ${pn==="activity"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Fn("activity"),role:"tab","aria-selected":pn==="activity","data-testid":"mission-tab-activity",children:["Activity (",ps,")"]})]}),pn==="structure"?t.jsxs("div",{className:"mission-detail__milestones",children:[f.milestones.map(O=>{const ke=cr?.rollup.milestoneId===O.id?cr:null,Re=ke?.rollup??qt.get(O.id),ht=ke?.validationTelemetry.validationRounds??[],Kt=ke?.fixFeatures??[],Nt=su[Re?.state??"not_started"]??su.not_started,Ut=Re&&(Re.state==="blocked"||Re.state==="failed")?ke?.validationTelemetry.validationRounds.find(Be=>Be.blockedReason)?.blockedReason:void 0;return t.jsxs("div",{className:"mission-milestone",children:[t.jsxs("div",{className:"mission-milestone__header",onClick:()=>Un(O.id),children:[t.jsx("button",{className:"mission-milestone__expand",children:L.has(O.id)?t.jsx(zt,{size:16}):t.jsx(en,{size:16})}),t.jsx(Si,{size:16,className:"mission-milestone__icon"}),t.jsx("span",{className:"mission-milestone__title",children:O.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:tu[O.status].bg,color:tu[O.status].text},children:O.status}),t.jsxs("span",{className:"mission-milestone__count",children:[O.slices.length," slices"]}),t.jsx(iu,{state:eN(O.interviewState)}),Re&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Nt.bg,color:Nt.text},title:"Validation state",children:au(Re.state)}),Re.totalAssertions>0&&t.jsx("div",{className:"mission-milestone__coverage-bar",title:`${Re.passedAssertions??0} of ${Re.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-milestone__coverage-bar-fill",style:{width:`${(Re.passedAssertions??0)/Re.totalAssertions*100}%`,backgroundColor:(Re.passedAssertions??0)===Re.totalAssertions?"var(--color-success)":"var(--color-warning)"}})})]}),O.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>he({type:"milestone",id:O.id,title:O.title}),title:"Plan milestone","aria-label":"Plan milestone",children:t.jsx(Ni,{size:14})}),t.jsxs("div",{className:"mission-milestone__actions",onClick:Be=>Be.stopPropagation(),children:[t.jsx("button",{className:"mission-icon-btn",onClick:()=>Jn(O.id),title:"Add slice",children:t.jsx(Vt,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Gt(O),title:"Edit milestone",children:t.jsx(Hn,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Z({type:"milestone",id:O.id}),title:"Delete milestone",children:t.jsx(Ht,{size:14})})]})]}),L.has(O.id)&&t.jsxs("div",{className:"mission-milestone__body",children:[(A||w===O.id)&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:W.title,onChange:Be=>B({...W,title:Be.target.value}),onKeyDown:Oc,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:W.description,onChange:Be=>B({...W,description:Be.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Cn,disabled:T,children:[T?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),w?"Update":"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bn,children:"Cancel"})]})]}),ke&&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:[ke.validationTelemetry.totalRuns," rounds",ke.validationTelemetry.lastValidatorStatus?` · Last ${ke.validationTelemetry.lastValidatorStatus}`:""]})]}),Ut&&t.jsxs("div",{className:"mission-blocked-reason",children:[t.jsx("strong",{children:"Blocked reason:"})," ",Ut]}),ht.length>0&&t.jsxs("div",{className:"mission-validation-rounds",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm mission-validation-rounds__toggle",onClick:()=>ut(Be=>!Be),title:gt?"Hide validation rounds":"Show validation rounds",children:[gt?t.jsx(zt,{size:12}):t.jsx(en,{size:12}),"Validation rounds (",ht.length,")"]}),gt&&t.jsx("div",{className:"mission-validation-rounds__list",children:ht.map(Be=>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--${Be.validatorStatus}`,children:Be.validatorStatus}),t.jsx("span",{className:"mission-validation-round__feature",children:Be.featureTitle}),t.jsxs("span",{className:"mission-validation-round__attempts",children:["impl #",Be.implementationAttempt," · validator #",Be.validatorAttempt]})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),Be.failedAssertionIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Be.failedAssertionIds.map(qe=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>ma(qe),title:`Jump to assertion ${qe}`,children:qe},`${Be.roundId}-${qe}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Generated fix features:"}),Be.generatedFixFeatureIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Be.generatedFixFeatureIds.map(qe=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>si(qe),title:`Jump to fix feature ${qe}`,children:qe},`${Be.roundId}-${qe}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),Be.blockedReason&&t.jsx("div",{className:"mission-validation-round__blocked-reason",children:Be.blockedReason})]},Be.roundId))})]}),Kt.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:Kt.map(Be=>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:()=>si(Be.id),title:`Jump to feature ${Be.id}`,children:Be.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:fr[Be.status].bg,color:fr[Be.status].text},children:Be.status}),Be.loopState&&t.jsx("span",{className:`mission-loop-state mission-loop-state--${Be.loopState}`,children:Be.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:()=>si(Be.sourceFeatureId),title:`Jump to source feature ${Be.sourceFeatureId}`,children:Be.sourceFeatureId}),t.jsx("span",{children:"Run:"}),t.jsx("span",{className:"mission-fix-feature__run",children:Be.runId})]}),Be.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:Be.failedAssertionIds.map(qe=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>ma(qe),title:`Jump to assertion ${qe}`,children:qe},`${Be.id}-${qe}`))})]})]},Be.id))})]})]}),t.jsxs("div",{className:"mission-slices",children:[O.slices.map(Be=>t.jsxs("div",{className:"mission-slice",children:[t.jsxs("div",{className:"mission-slice__header",onClick:()=>Is(Be.id),children:[t.jsx("button",{className:"mission-slice__expand",children:$.has(Be.id)?t.jsx(zt,{size:16}):t.jsx(en,{size:16})}),t.jsx(Il,{size:16,className:"mission-slice__icon"}),t.jsx("span",{className:"mission-slice__title",children:Be.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:nu[Be.status].bg,color:nu[Be.status].text},children:Be.status}),t.jsxs("span",{className:"mission-slice__count",children:[Be.features?.length||0," features"]}),t.jsx(iu,{state:Be.planState??"not_started"}),Be.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>he({type:"slice",id:Be.id,title:Be.title}),title:"Plan slice","aria-label":"Plan slice",children:t.jsx(Ni,{size:14})}),t.jsxs("div",{className:"mission-slice__actions",onClick:qe=>qe.stopPropagation(),children:[Be.status==="pending"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Es(Be.id),title:"Activate slice",children:t.jsx(rn,{size:14})}),Be.status==="active"&&Be.features?.some(qe=>qe.status==="defined")&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>yo(Be.id),title:"Triage all features",disabled:T,children:T?t.jsx(it,{size:14,className:"spinner"}):t.jsx(vn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>rs(Be.id),title:"Add feature",children:t.jsx(Vt,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Bn(Be),title:"Edit slice",children:t.jsx(Hn,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Z({type:"slice",id:Be.id}),title:"Delete slice",children:t.jsx(Ht,{size:14})})]})]}),$.has(Be.id)&&t.jsxs("div",{className:"mission-slice__body",children:[ie&&F===O.id&&!X&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:U.title,onChange:qe=>pe({...U,title:qe.target.value}),onKeyDown:Uc,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:U.description,onChange:qe=>pe({...U,description:qe.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:un,disabled:T,children:[T?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Yn,children:"Cancel"})]})]}),X===Be.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:U.title,onChange:qe=>pe({...U,title:qe.target.value}),onKeyDown:Uc,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:U.description,onChange:qe=>pe({...U,description:qe.target.value}),rows:2}),t.jsxs("select",{value:U.status,onChange:qe=>pe({...U,status:qe.target.value}),children:[t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"complete",children:"Complete"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:un,disabled:T,children:[T?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Yn,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-features",children:[Be.features?.map(qe=>t.jsxs("div",{className:"mission-feature","data-mission-feature-id":qe.id,children:[t.jsxs("div",{className:"mission-feature__header",children:[t.jsx("button",{className:"mission-feature__expand",onClick:()=>Ri(qe.id),title:H===qe.id?"Collapse details":"Expand to show run history",children:H===qe.id?t.jsx(zt,{size:14}):t.jsx(en,{size:14})}),t.jsx(Ml,{size:14,className:"mission-feature__icon"}),t.jsx("span",{className:"mission-feature__title",children:qe.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:fr[qe.status].bg,color:fr[qe.status].text},children:qe.status}),qe.loopState&&qe.loopState!=="idle"&&t.jsxs("span",{className:`mission-loop-state mission-loop-state--${qe.loopState}`,title:`Loop state: ${qe.loopState}`,children:[qe.loopState==="implementing"&&"⏳",qe.loopState==="validating"&&"🔄",qe.loopState==="needs_fix"&&"🔧",qe.loopState==="passed"&&"✅",qe.loopState==="blocked"&&"🚫"]}),qe.generatedFromFeatureId&&t.jsx("button",{className:"mission-feature__lineage",onClick:()=>si(qe.generatedFromFeatureId),title:`Generated from feature: ${qe.generatedFromFeatureId}`,children:"🔗 Fix"}),(qe.loopState==="validating"||qe.loopState==="needs_fix")&&(()=>{const pt=rt.get(qe.id),Jt=kf.get(qe.id),vs=pt?.implementationAttemptCount??Jt?.implementationAttempt??qe.implementationAttemptCount??0,hi=pt?.retryBudgetRemaining??Math.max(0,Zw-vs);return t.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",vs," · ",hi," ",hi===1?"retry":"retries"," left"]})})(),qe.loopState==="implementing"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>wo(qe.id),title:"Validate feature",disabled:Me.has(qe.id),children:Me.has(qe.id)?t.jsx(it,{size:14,className:"spinner"}):t.jsx(Dn,{size:14})}),qe.taskId&&t.jsx("span",{className:"mission-feature__task-link",onClick:()=>o?.(qe.taskId),title:"Click to view task",children:qe.taskId}),t.jsxs("div",{className:"mission-feature__actions",children:[qe.status==="defined"&&!qe.taskId&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>ar(qe.id),title:"Triage — create task",disabled:T||Ze===qe.id,children:Ze===qe.id?t.jsx(it,{size:14,className:"spinner"}):t.jsx(vn,{size:14})}),qe.taskId?t.jsx("button",{className:"mission-icon-btn",onClick:()=>vo(qe.id),title:"Unlink task",children:t.jsx(Yc,{size:14})}):qe.status!=="defined"?t.jsx("button",{className:"mission-icon-btn",onClick:()=>We(qe.id),title:"Link to task",children:t.jsx(Wi,{size:14})}):null,t.jsx("button",{className:"mission-icon-btn",onClick:()=>An(qe),title:"Edit feature",children:t.jsx(Hn,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Z({type:"feature",id:qe.id}),title:"Delete feature",children:t.jsx(Ht,{size:14})})]})]}),qe.description&&t.jsx("p",{className:"mission-feature__description",children:qe.description}),qe.acceptanceCriteria&&t.jsxs("p",{className:"mission-feature__criteria",children:[t.jsx("strong",{children:"Acceptance:"})," ",qe.acceptanceCriteria]}),le?.featureId===qe.id&&t.jsxs("div",{className:"mission-triage-preview",children:[t.jsx("div",{className:"mission-triage-preview__header",children:"Enriched Description Preview"}),t.jsx("div",{className:"mission-triage-preview__content",children:le.enrichedDescription}),t.jsxs("div",{className:"mission-triage-preview__actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:rr,disabled:T,children:[T?t.jsx(it,{size:14,className:"spinner"}):null,"Create Task"]}),t.jsx("button",{className:"btn",onClick:ei,disabled:T,children:"Cancel"})]})]}),ae===qe.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:de.title,onChange:pt=>Te({...de,title:pt.target.value}),onKeyDown:Bc,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:de.description,onChange:pt=>Te({...de,description:pt.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:de.acceptanceCriteria,onChange:pt=>Te({...de,acceptanceCriteria:pt.target.value}),rows:2}),t.jsxs("select",{value:de.status,onChange:pt=>Te({...de,status:pt.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:Tn,disabled:T,children:[T?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bs,children:"Cancel"})]})]}),H===qe.id&&t.jsxs("div",{className:"mission-feature__run-history",children:[t.jsx("div",{className:"mission-feature__run-history-header",children:t.jsx("span",{className:"mission-feature__run-history-title",children:"Validation Runs"})}),(ot.get(qe.id)??[]).map(pt=>t.jsxs("div",{className:"mission-run",children:[t.jsxs("div",{className:"mission-run__header",onClick:()=>ha(pt.id),children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-run__status mission-run__status--${pt.status}`,title:pt.status,children:pt.status}),t.jsx("span",{className:"mission-run__time",children:new Date(pt.startedAt).toLocaleString()}),pt.completedAt&&t.jsxs("span",{className:"mission-run__duration",children:[Math.round((new Date(pt.completedAt).getTime()-new Date(pt.startedAt).getTime())/1e3),"s"]}),pt.triggerType&&t.jsx("span",{className:"mission-run__trigger",children:pt.triggerType}),t.jsx("button",{className:"mission-icon-btn",title:Ot===pt.id?"Hide details":"Show details",children:Ot===pt.id?t.jsx(zt,{size:12}):t.jsx(en,{size:12})})]}),Ot===pt.id&&Rt.get(pt.id)&&t.jsxs("div",{className:"mission-run__details",children:[pt.summary&&t.jsx("p",{className:"mission-run__summary",children:pt.summary}),pt.blockedReason&&t.jsxs("p",{className:"mission-run__blocked-reason",children:[t.jsx("strong",{children:"Blocked:"})," ",pt.blockedReason]}),Rt.get(pt.id)?.failures&&Rt.get(pt.id).failures.length>0&&t.jsxs("div",{className:"mission-run__failures",children:[t.jsx("span",{className:"mission-run__failures-title",children:"Failed Assertions:"}),Rt.get(pt.id).failures.map(Jt=>t.jsxs("div",{className:"mission-run__failure",children:[t.jsx("span",{className:"mission-run__failure-message",children:Jt.message}),Jt.expected&&t.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",Jt.expected]}),Jt.actual&&t.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",Jt.actual]})]},Jt.id))]}),(!Rt.get(pt.id)?.failures||Rt.get(pt.id).failures.length===0)&&t.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},pt.id)),(!ot.get(qe.id)||ot.get(qe.id).length===0)&&t.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},qe.id)),fe&&te===Be.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:de.title,onChange:qe=>Te({...de,title:qe.target.value}),onKeyDown:Bc,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:de.description,onChange:qe=>Te({...de,description:qe.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:de.acceptanceCriteria,onChange:qe=>Te({...de,acceptanceCriteria:qe.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Tn,disabled:T,children:[T?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bs,children:"Cancel"})]})]}),!fe&&(!Be.features||Be.features.length===0)&&t.jsxs("div",{className:"mission-manager__empty mission-features__empty",children:[t.jsx(Ml,{size:16}),t.jsx("span",{children:"No fix features generated."})]})]})]})]},Be.id)),O.slices.length===0&&!ie&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Il,{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"}),Re&&t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Nt.bg,color:Nt.text},children:au(Re.state)}),Re&&Re.totalAssertions>0&&t.jsx("div",{className:"mission-assertions__coverage-bar",title:`${Re.passedAssertions??0} of ${Re.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-assertions__coverage-bar-fill",style:{width:`${(Re.passedAssertions??0)/Re.totalAssertions*100}%`,backgroundColor:(Re.passedAssertions??0)===Re.totalAssertions?"var(--color-success)":"var(--color-warning)"}})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>{He(!0),ve(null),je({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:t.jsx(Vt,{size:14})})]}),Ue&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:Ge.title,onChange:Be=>je({...Ge,title:Be.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:Ge.assertion,onChange:Be=>je({...Ge,assertion:Be.target.value}),rows:2}),t.jsxs("select",{value:Ge.status,onChange:Be=>je({...Ge,status:Be.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:()=>Ye(O.id),disabled:T,children:[T?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:wt,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-assertions__list",children:[(Array.isArray(ue.get(O.id))?ue.get(O.id):[]).map(Be=>t.jsxs("div",{className:"mission-assertion","data-mission-assertion-id":Be.id,children:[t.jsx("div",{className:"mission-assertion__header",children:$e===Be.id?t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:Ge.title,onChange:qe=>je({...Ge,title:qe.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text",value:Ge.assertion,onChange:qe=>je({...Ge,assertion:qe.target.value}),rows:2}),t.jsxs("select",{value:Ge.status,onChange:qe=>je({...Ge,status:qe.target.value}),children:[t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"passed",children:"Passed"}),t.jsx("option",{value:"failed",children:"Failed"}),t.jsx("option",{value:"blocked",children:"Blocked"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:()=>Ms(Be.id,O.id),disabled:T,children:[T?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),"Save"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:wt,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(br[Be.status]??br.pending).bg,color:(br[Be.status]??br.pending).text},children:Be.status}),t.jsx("span",{className:"mission-assertion__title",children:Be.title}),(()=>{const pt=be.get(Be.id)?.length??0;return pt>0?t.jsxs("span",{className:"mission-assertion__linked-count",title:`${pt} linked feature${pt!==1?"s":""}`,children:["(",pt," linked)"]}):null})(),t.jsx("button",{className:"mission-icon-btn",onClick:()=>or(Be.id),title:"Toggle details",children:ge===Be.id?t.jsx(zt,{size:14}):t.jsx(en,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>lt(Be),title:"Edit assertion",children:t.jsx(Hn,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Z({type:"assertion",id:Be.id}),title:"Delete assertion",children:t.jsx(Ht,{size:14})})]})}),ge===Be.id&&t.jsxs("div",{className:"mission-assertion__body",children:[t.jsx("p",{className:"mission-assertion__text",children:Be.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()=>{ge!==Be.id&&await or(Be.id),Bt(Dt===Be.id?null:Be.id)},title:"Link a feature",children:[t.jsx(Wi,{size:12}),"Link Feature"]})]}),Dt===Be.id&&t.jsx("div",{className:"mission-assertion__feature-picker",children:t.jsx("div",{className:"mission-assertion__feature-picker-dropdown",children:(()=>{const qe=new Set((be.get(Be.id)??[]).map(Jt=>Jt.id)),pt=[];return f?.milestones.forEach(Jt=>Jt.slices.forEach(vs=>pt.push(...vs.features.filter(hi=>!qe.has(hi.id))))),pt.length===0?t.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):pt.map(Jt=>t.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>ko(Jt.id,Be.id),disabled:st.has(Be.id),children:[t.jsx("span",{className:"mission-assertion__feature-picker-title",children:Jt.title}),st.has(Be.id)&&t.jsx(it,{size:12,className:"spinner"})]},Jt.id))})()})}),(()=>{const qe=be.get(Be.id)??[];return qe.length===0?t.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):qe.map(pt=>{const Jt=`${pt.id}-${Be.id}`,vs=Tt.has(Jt);return t.jsxs("div",{className:"mission-assertion__linked-feature",children:[t.jsx("span",{className:"mission-assertion__linked-feature-title",children:pt.title}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>jo(pt.id,Be.id),disabled:vs,title:"Unlink feature",children:vs?t.jsx(it,{size:12,className:"spinner"}):t.jsx(Yc,{size:12})})]},pt.id)})})()]})]})]},Be.id)),(!ue.get(O.id)||ue.get(O.id)?.length===0)&&!Ue&&t.jsx("div",{className:"mission-manager__empty mission-assertions__empty",children:t.jsx("span",{children:"No assertions defined. Add one to define completion criteria."})})]})]})]})]})]},O.id)}),f&&!A&&w===null&&t.jsxs("button",{className:"mission-add-btn",onClick:cn,children:[t.jsx(Vt,{size:16}),"Add Milestone"]}),A&&w===null&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:W.title,onChange:O=>B({...W,title:O.target.value}),onKeyDown:Oc,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:W.description,onChange:O=>B({...W,description:O.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Cn,disabled:T,children:[T?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bn,children:"Cancel"})]})]}),f.milestones.length===0&&!A&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Si,{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:K,onChange:O=>ze(O.target.value),"data-testid":"mission-activity-filter",children:[t.jsx("option",{value:"all",children:"All events"}),t.jsx("option",{value:"errors",children:"Errors & warnings"}),t.jsx("option",{value:"state_changes",children:"State changes"}),t.jsx("option",{value:"tasks",children:"Task events"}),t.jsx("option",{value:"slices",children:"Slice & milestone events"}),t.jsx("option",{value:"autopilot",children:"Autopilot events"})]})]}),t.jsxs("span",{className:"mission-detail__activity-count",children:[Sn.length," of ",ps]})]}),!_n&&lr&&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:jf,"data-testid":"mission-activity-load-more",children:"Load more"})}),_n?t.jsxs("div",{className:"mission-manager__loading mission-detail__activity-loading",children:[t.jsx(it,{size:18,className:"spinner"}),t.jsx("span",{children:"Loading mission activity..."})]}):Sn.length===0?t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Ss,{size:18}),t.jsx("span",{children:"No events yet."})]}):t.jsxs("div",{ref:mt,className:"mission-events","data-testid":"mission-activity-events",children:[Sn.map(O=>{const ke=!!(O.metadata&&Object.keys(O.metadata).length>0),Re=tt.has(O.id);return t.jsxs("div",{className:"mission-event",children:[t.jsxs("div",{className:"mission-event__header",children:[t.jsx("span",{className:`mission-event__type ${aN(O.eventType)}`,children:rN(O.eventType)}),t.jsx("span",{className:"mission-event__time",children:Vr(O.timestamp)})]}),t.jsx("p",{className:"mission-event__description",children:O.description}),t.jsx("span",{className:"mission-event__timestamp",children:new Date(O.timestamp).toLocaleString()}),ke&&t.jsxs("div",{className:"mission-event__metadata",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>wf(O.id),"data-testid":`mission-event-metadata-${O.id}`,children:[Re?"Hide":"Show"," metadata"]}),Re&&t.jsx("pre",{className:"mission-event__metadata-content",children:JSON.stringify(O.metadata,null,2)})]})]},O.id)}),t.jsx("div",{ref:jt})]})]})]}):t.jsxs("div",{className:"mission-list",children:[y&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:S.title,onChange:O=>P({...S,title:O.target.value}),onKeyDown:Co,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:S.description,onChange:O=>P({...S,description:O.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:on,disabled:T,children:[T?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bt,children:"Cancel"})]})]}),g.map(O=>{const ke=O,Re=f,ht=Re&&Re.id===ke.id,Kt=ba[ke.status]||{bg:"",text:""},Nt=ke.summary,Ut=Wn.get(ke.id),Be=nN(Ut),qe=!!(Nt&&(Nt.totalMilestones>0||Nt.totalFeatures>0)),pt=Ut?.totalTasks??0,Jt=Ut?.tasksCompleted??0,vs=Ut?.tasksFailed??0,hi=Ut?.estimatedCompletionPercent??Nt?.progressPercent??0,En=qe||pt>0||vs>0||!!Ut?.lastActivityAt,ln=ke.status==="active"&&(Ut?.currentMilestoneId||Ut?.currentSliceId)?"Current milestone/slice in progress":null;return t.jsxs("div",{className:`mission-list__item ${ht?"mission-list__item--selected":""}`,onClick:()=>_s(O),children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(ns,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{className:"mission-list__item-title",children:ke.title}),O.autopilotEnabled&&t.jsx("span",{title:"Autopilot enabled",children:t.jsx(vn,{size:12,className:"mission-list__item-autopilot-icon"})}),t.jsx("span",{className:`mission-health-badge mission-health-badge--${Be}`,"data-testid":`mission-health-badge-${ke.id}`,"aria-label":`Mission health: ${Be}`}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Kt.bg,color:Kt.text},children:ke.status})]}),ke.description&&t.jsx("p",{className:"mission-list__item-description",children:ke.description}),ln&&t.jsxs("p",{className:"mission-list__item-active-slice",children:["Active: ",ln]}),En&&t.jsxs("div",{className:"mission-list__item-summary",children:[qe&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"mission-list__item-stat",children:[Nt.completedMilestones,"/",Nt.totalMilestones," milestones"]}),t.jsxs("span",{className:"mission-list__item-stat",children:[Nt.completedFeatures,"/",Nt.totalFeatures," features"]})]}),t.jsxs("span",{className:"mission-list__item-stat","data-testid":`mission-task-stats-${ke.id}`,children:[Jt,"/",pt," tasks"]}),vs>0&&t.jsxs("button",{className:"mission-list__item-failed",onClick:At=>{At.stopPropagation(),_s(O)},"data-testid":`mission-failed-${ke.id}`,title:"View mission failures",children:[vs," failed"]}),t.jsxs("span",{className:"mission-relative-time","data-testid":`mission-last-activity-${ke.id}`,children:["Activity ",Vr(Ut?.lastActivityAt)]}),t.jsx("div",{className:`mission-list__item-progress mission-list__item-progress--${Be}`,children:t.jsx("div",{className:"mission-list__item-progress-bar",style:{width:`${hi}%`}})})]})]}),t.jsxs("div",{className:"mission-list__item-actions",onClick:At=>At.stopPropagation(),children:[ke.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>So(ke.id),title:"Stop mission",children:t.jsx(ls,{size:14})}),ke.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>No(ke.id),title:"Resume mission",children:t.jsx(rn,{size:14})}),ke.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>xs(ke.id),title:"Start mission",children:t.jsx(rn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>ft(O),title:"Edit mission",children:t.jsx(Hn,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Z({type:"mission",id:ke.id}),title:"Delete mission",children:t.jsx(Ht,{size:14})})]})]},ke.id)}),j&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:S.title,onChange:O=>P({...S,title:O.target.value}),onKeyDown:Co,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:S.description,onChange:O=>P({...S,description:O.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:S.status,onChange:O=>P({...S,status:O.target.value}),children:[t.jsx("option",{value:"planning",children:"Planning"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"blocked",children:"Blocked"}),t.jsx("option",{value:"complete",children:"Complete"}),t.jsx("option",{value:"archived",children:"Archived"})]}),t.jsxs("label",{className:"mission-checkbox",children:[t.jsx("input",{type:"checkbox",checked:S.autopilotEnabled,onChange:O=>P({...S,autopilotEnabled:O.target.checked})}),t.jsx(vn,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:on,disabled:T,children:[T?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bt,children:"Cancel"})]})]}),g.length===0&&!y&&t.jsxs("div",{className:"mission-manager__empty mission-manager__empty--large",children:[t.jsx(ns,{size:32}),t.jsx("span",{children:"No missions yet. Create one to start planning."})]}),!y&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[ye.length>0&&t.jsxs("div",{className:"mission-resume-prompt",children:[t.jsx(ss,{size:16}),t.jsx("span",{children:ye.length===1?`Resume "${ye[0].title}"?`:`${ye.length} interview sessions pending`}),t.jsx("div",{style:{display:"flex",gap:"4px",marginLeft:"auto"},children:ye.map(O=>t.jsxs("button",{className:"mission-add-btn",onClick:()=>{J(O.id),Oe(!0),De([])},children:[O.status==="error"?t.jsx(hn,{size:14}):t.jsx(Dn,{size:14}),O.status==="error"?"Retry":"Resume"]},O.id))})]}),t.jsxs("div",{style:{display:"flex",gap:"8px"},children:[t.jsxs("button",{className:"mission-add-btn",onClick:()=>Oe(!0),children:[t.jsx(Dn,{size:16}),"Plan with AI"]}),t.jsxs("button",{className:"mission-add-btn",onClick:nt,children:[t.jsx(Vt,{size:16}),"New Mission"]})]})]})]})}),oe&&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 ",oe.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()=>{oe.type==="mission"?await Xt(oe.id):oe.type==="milestone"?await gs(oe.id):oe.type==="slice"?await Qn(oe.id):oe.type==="feature"&&await ua(oe.id)},children:"Delete"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>Z(null),children:"Cancel"})]})]})}),Pe&&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:Ke,onChange:O=>Ne(O.target.value),autoFocus:!0}),l.length>0&&t.jsxs("div",{className:"mission-task-suggestions",children:[t.jsx("small",{children:"Or select:"}),t.jsx("div",{className:"mission-task-suggestions__list",children:l.slice(0,5).map(O=>t.jsxs("button",{className:"mission-task-suggestions__item",onClick:()=>Ne(O.id),children:[O.id,": ",O.title||"Untitled"]},O.id))})]}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--primary",onClick:xo,children:"Link"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>{We(null),Ne("")},children:"Cancel"})]})]})})]}),qc=t.jsx(Gw,{isOpen:_e,onClose:()=>Oe(!1),onMissionCreated:()=>{Qt(),i("Mission created from AI interview","success")},projectId:r,resumeSessionId:me}),Vc=ee?t.jsx(Yw,{isOpen:!0,onClose:()=>he(null),onApplied:()=>{he(null),f&&vt(f.id)},targetType:ee.type,targetId:ee.id,targetTitle:ee.title,missionContext:f?.title,projectId:r,resumeSessionId:ee.resumeSessionId}):null;return n?t.jsxs(t.Fragment,{children:[Hc,qc,Vc]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mission-manager-overlay open",onClick:O=>O.target===O.currentTarget&&s(),"data-testid":"mission-manager-overlay",role:"dialog","aria-modal":"true",children:Hc}),qc,Vc]})}const xr=2e3;function ou({recipient:e,replyContext:n,agents:s=[],projectId:i,onSend:r,onCancel:o,addToast:l,isLoadingAgents:c=!1}){const[u,d]=a.useState(e?.id??""),[m,h]=a.useState(e?.type??"agent"),[g,p]=a.useState(""),[f,b]=a.useState(!1),[v,x]=a.useState(null),k=u.trim()!==""&&g.trim().length>0&&g.length<=xr,M=a.useCallback(async()=>{if(!(!k||f)){b(!0),x(null);try{const R=m==="agent"?"user-to-agent":"system";await Rk({toId:u.trim(),toType:m,content:g.trim(),type:R,...n?{metadata:{replyTo:{messageId:n.messageId}}}:{}},i),r()}catch(R){const j=xe(R)||"Failed to send message";x(j),l?.(j,"error")}finally{b(!1)}}},[k,f,u,m,g,n,i,r,l]),y=a.useCallback(R=>{d(R),h("agent")},[]);return t.jsxs("div",{className:"message-composer","data-testid":"message-composer",children:[t.jsxs("div",{className:"message-composer-header",children:[t.jsx("span",{children:n?"Reply":"New Message"}),t.jsx("button",{className:"btn-icon",onClick:o,"aria-label":"Cancel","data-testid":"message-composer-cancel",children:t.jsx(Pt,{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:R=>y(R.target.value),disabled:c||s.length===0,"data-testid":"message-composer-recipient",children:[t.jsx("option",{value:"",children:c?"Loading agents…":s.length===0?"No agents available":"Select agent…"}),s.map(R=>t.jsx("option",{value:R.id,children:R.name||R.id},R.id))]})]}),e&&t.jsxs("div",{className:"message-composer-field",children:[t.jsx("span",{className:"message-composer-label",children:"To:"}),t.jsxs("span",{className:"message-composer-recipient-fixed",children:[t.jsx(an,{size:14}),e.id]})]}),n&&t.jsxs("div",{className:"message-composer-field","data-testid":"message-composer-reply-context",children:[t.jsx("span",{className:"message-composer-label",children:"Replying to:"}),t.jsx("span",{className:"message-composer-recipient-fixed",children:n.preview?.trim()?n.preview:`Message ${n.messageId}`})]}),t.jsxs("div",{className:"message-composer-field message-composer-field--content",children:[t.jsx("label",{className:"message-composer-label",htmlFor:"message-content",children:"Message:"}),t.jsx("textarea",{id:"message-content",className:"message-composer-textarea",placeholder:"Type your message…",value:g,onChange:R=>p(R.target.value),maxLength:xr,rows:4,"data-testid":"message-composer-content"}),t.jsx("div",{className:"message-composer-charcount","data-testid":"message-composer-charcount",children:t.jsxs("span",{className:g.length>xr?"over-limit":"",children:[g.length,"/",xr]})})]}),v&&t.jsxs("div",{className:"message-composer-error","data-testid":"message-composer-error",children:[t.jsx(ss,{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:M,disabled:!k||f,"data-testid":"message-composer-send",children:f?t.jsxs(t.Fragment,{children:[t.jsx(it,{size:14,className:"spin"}),t.jsx("span",{children:"Sending…"})]}):t.jsxs(t.Fragment,{children:[t.jsx(vi,{size:14}),t.jsx("span",{children:"Send"})]})})]})]})}function zi(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 cN(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 dN(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 lu(e,n=80){return e.length<=n?e:`${e.slice(0,n)}…`}function uN(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 mN({projectId:e,addToast:n,onUnreadCountChange:s}){const[i,r]=a.useState("inbox"),[o,l]=a.useState(null),[c,u]=a.useState(null),[d,m]=a.useState(0),[h,g]=a.useState(!1),[p,f]=a.useState(null),[b,v]=a.useState([]),[x,k]=a.useState(!1),[M,y]=a.useState(null),[R,j]=a.useState(null),[C,S]=a.useState(null),[P,T]=a.useState("inbox"),[_,L]=a.useState(null),[G,$]=a.useState([]),I=a.useMemo(()=>new Map(G.map(te=>[te.id,te.name??""])),[G]),w=a.useCallback((te,we)=>cN(te,we,I),[I]),W=tr()==="mobile",B=!W,A=a.useCallback(async()=>{g(!0);try{const te=await Ak({limit:50},e);l(te),m(te.unreadCount),s?.(te.unreadCount)}catch{}finally{g(!1)}},[e,s]),z=a.useCallback(async()=>{g(!0);try{const te=await Tk({limit:50},e);u(te)}catch{}finally{g(!1)}},[e]),X=a.useCallback(async te=>{g(!0);try{const we=await Lk(te,e);L(we)}catch{}finally{g(!1)}},[e]),E=a.useCallback(async()=>{try{const te=await oa(void 0,e);$(te)}catch{}},[e]),U=a.useCallback(async()=>{try{const te=await Ch(e);m(te.unreadCount),s?.(te.unreadCount)}catch{}},[e,s]);a.useEffect(()=>{i==="inbox"?A():i==="outbox"?z():i==="agents"&&E()},[i,A,z,E]),a.useEffect(()=>{C&&X(C)},[C,X]),a.useEffect(()=>{U()},[U]),a.useEffect(()=>{E()},[E]),a.useEffect(()=>{if(typeof EventSource>"u")return;const te=e?`?projectId=${encodeURIComponent(e)}`:"",we=()=>{U(),i==="inbox"?A():i==="outbox"&&z(),C&&X(C)};return qs(`/api/events${te}`,{events:{"message:sent":we,"message:received":we,"message:read":we,"message:deleted":we}})},[e,i,C,U,A,z,X]);const pe=a.useCallback(async te=>{if(f(te),!te.read)try{const we=await Ik(te.id,e);we&&l(We=>We&&{...We,messages:We.messages.map(Ke=>Ke.id===we.id?we:Ke),unreadCount:Math.max(0,We.unreadCount-1)});const Pe=Math.max(0,d-1);m(Pe),s?.(Pe)}catch{}try{const we=await Dk(te.fromId,te.fromType,e);v(we)}catch{v([te])}},[e,d,s]),ie=a.useCallback(()=>{f(null),v([])},[]),re=a.useCallback(async()=>{try{const te=await Pk(e);m(0),s?.(0),l(we=>we&&{...we,messages:we.messages.map(Pe=>({...Pe,read:!0})),unreadCount:0}),n?.(`Marked ${te.markedAsRead} messages as read`,"success")}catch{n?.("Failed to mark messages as read","error")}},[e,n,s]),F=a.useCallback(async te=>{try{await $k(te,e),f(null),v([]),i==="inbox"?A():i==="outbox"?z():C&&X(C),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[e,i,C,A,z,X,n]),ce=a.useCallback(te=>{y({id:te.fromId,type:te.fromType}),j({messageId:te.id,preview:lu(te.content,120)}),k(!0)},[]),ae=a.useCallback(()=>{k(!1),y(null),j(null),n?.("Message sent","success"),i==="outbox"?z():i==="agents"&&C&&X(C),U()},[i,z,C,X,n,U]),Q=a.useCallback(()=>{y(i==="agents"&&C?{id:C,type:"agent"}:null),j(null),k(!0)},[i,C]),de=a.useCallback(()=>{k(!1),y(null),j(null)},[]),Te=()=>!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:[W&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:ie,"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:dN(p.type)}),t.jsx("span",{className:"mailbox-message-time",children:zi(p.createdAt)})]}),t.jsxs("div",{className:"mailbox-message-detail-actions",children:[p.fromType==="agent"&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>ce(p),"data-testid":"mailbox-reply",children:[t.jsx(li,{size:14}),t.jsx("span",{children:"Reply"})]}),t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>F(p.id),"data-testid":"mailbox-delete",children:[t.jsx(Ht,{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(an,{size:14}):t.jsx(Pi,{size:14}),w(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(an,{size:14}):t.jsx(Pi,{size:14}),w(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(te=>{const we=te.metadata?.replyTo?.messageId,Pe=we?b.find(We=>We.id===we):void 0;return t.jsxs("div",{className:`mailbox-conversation-msg ${te.id===p.id?"current":""}`,children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:w(te.fromId,te.fromType)}),t.jsx("span",{className:"mailbox-message-time",children:zi(te.createdAt)})]}),we&&t.jsxs("div",{className:"mailbox-reply-context","data-testid":`mailbox-reply-context-${te.id}`,children:["↪ Replying to ",Pe?lu(Pe.content,60):`message ${we}`]}),t.jsx("div",{className:"mailbox-conversation-msg-body",children:te.content})]},te.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})]})]}),fe=()=>t.jsxs(t.Fragment,{children:[i==="inbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[h&&!o&&t.jsx(qo,{}),o&&o.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-inbox-empty",children:[t.jsx(Ra,{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:uN(o.messages).map(te=>t.jsxs("div",{className:`mailbox-conversation-group ${te.unreadCount>0?"unread":""}`,onClick:()=>pe(te.latestMessage),"data-testid":`mailbox-conversation-${te.key}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:te.fromType==="agent"?t.jsx(an,{size:16}):t.jsx(Pi,{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:w(te.fromId,te.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:zi(te.latestMessage.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[te.latestMessage.content.slice(0,80),te.latestMessage.content.length>80?"…":""]})]}),te.unreadCount>0&&t.jsx("div",{className:"mailbox-group-unread-badge","data-testid":`mailbox-unread-badge-${te.key}`,children:te.unreadCount>9?"9+":te.unreadCount})]},te.key))})]}),i==="outbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-outbox-list",children:[h&&!c&&t.jsx(qo,{}),c&&c.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-outbox-empty",children:[t.jsx(vi,{size:32}),t.jsx("p",{children:"No sent messages"})]}),c?.messages.map(te=>t.jsxs("div",{className:"mailbox-item",onClick:()=>pe(te),"data-testid":`mailbox-item-${te.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:te.toType==="agent"?t.jsx(an,{size:16}):t.jsx(Pi,{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: ",w(te.toId,te.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:zi(te.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[te.content.slice(0,80),te.content.length>80?"…":""]})]})]},te.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(an,{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:C??"",onChange:te=>{S(te.target.value||null),T("inbox")},"data-testid":"mailbox-agent-select",children:[t.jsx("option",{value:"",children:"Select an agent…"}),G.map(te=>t.jsx("option",{value:te.id,children:te.name||te.id},te.id))]})}),t.jsxs("button",{className:"btn btn-sm btn-secondary mailbox-compose-btn",onClick:Q,"data-testid":"mailbox-compose-btn",children:[t.jsx(li,{size:14}),t.jsx("span",{children:"Compose"})]})]}),C&&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 ${P==="inbox"?"active":""}`,onClick:()=>T("inbox"),"data-testid":"mailbox-agent-subtab-inbox",children:[t.jsx(Ra,{size:12}),t.jsx("span",{children:"Inbox"}),_&&_.unreadCount>0&&t.jsx("span",{className:"mailbox-tab-badge",children:_.unreadCount})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${P==="outbox"?"active":""}`,onClick:()=>T("outbox"),"data-testid":"mailbox-agent-subtab-outbox",children:[t.jsx(vi,{size:12}),t.jsx("span",{children:"Outbox"})]})]}),t.jsxs("div",{className:"mailbox-agents-content",children:[!C&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(an,{size:32}),t.jsx("p",{children:"Select an agent to view their mailbox"})]}),C&&h&&!_&&t.jsx(qo,{}),C&&_&&P==="inbox"&&_.inbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Ra,{size:32}),t.jsx("p",{children:"No received messages for this agent"})]}),C&&_&&P==="outbox"&&_.outbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(vi,{size:32}),t.jsx("p",{children:"No sent messages for this agent"})]}),C&&_&&P==="inbox"&&_.inbox.map(te=>t.jsxs("div",{className:`mailbox-item ${te.read?"":"unread"}`,onClick:()=>pe(te),"data-testid":`mailbox-item-${te.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:te.fromType==="agent"?t.jsx(an,{size:16}):t.jsx(Pi,{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:w(te.fromId,te.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:zi(te.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[te.content.slice(0,80),te.content.length>80?"…":""]})]})]},te.id)),C&&_&&P==="outbox"&&_.outbox.map(te=>t.jsxs("div",{className:"mailbox-item",onClick:()=>pe(te),"data-testid":`mailbox-item-${te.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:te.toType==="agent"?t.jsx(an,{size:16}):t.jsx(Pi,{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: ",w(te.toId,te.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:zi(te.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[te.content.slice(0,80),te.content.length>80?"…":""]})]})]},te.id))]})]})})]}),Se=()=>x?t.jsx(ou,{recipient:M,replyContext:R,agents:G,projectId:e,onSend:ae,onCancel:de,addToast:n}):p?Te():t.jsxs("div",{className:"mailbox-split-empty","data-testid":"mailbox-split-empty",children:[t.jsx(Gi,{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(Gi,{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:Q,title:"Compose message","data-testid":"mailbox-header-compose",children:[t.jsx(li,{size:14}),t.jsx("span",{children:"Compose"})]}),i==="inbox"&&d>0&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:re,title:"Mark all as read","data-testid":"mailbox-mark-all-read",children:[t.jsx(Wf,{size:14}),t.jsx("span",{children:"Mark all read"})]}),t.jsx("button",{className:"btn-icon",onClick:()=>{i==="inbox"?A():i==="outbox"?z():C&&X(C)},disabled:h,title:"Refresh","data-testid":"mailbox-refresh",children:h?t.jsx(it,{size:14,className:"spin"}):t.jsx(hn,{size:14})})]})]}),t.jsxs("div",{className:"mailbox-tabs","data-testid":"mailbox-tabs",children:[t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="inbox"?"active":""}`,onClick:()=>{r("inbox"),f(null)},"data-testid":"mailbox-tab-inbox",children:[t.jsx(Ra,{size:14}),t.jsx("span",{children:"Inbox"}),d>0&&t.jsx("span",{className:"mailbox-tab-badge",children:d})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="outbox"?"active":""}`,onClick:()=>{r("outbox"),f(null)},"data-testid":"mailbox-tab-outbox",children:[t.jsx(vi,{size:14}),t.jsx("span",{children:"Outbox"})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="agents"?"active":""}`,onClick:()=>{r("agents"),f(null)},"data-testid":"mailbox-tab-agents",children:[t.jsx(an,{size:14}),t.jsx("span",{children:"Agents"})]})]}),t.jsx("div",{className:"mailbox-content","data-testid":"mailbox-content",children:B?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:fe()}),t.jsx("div",{className:"mailbox-split-detail-pane","data-testid":"mailbox-split-detail-pane",children:Se()})]}):t.jsxs(t.Fragment,{children:[Te(),x&&t.jsx(ou,{recipient:M,replyContext:R,agents:G,projectId:e,onSend:ae,onCancel:de,addToast:n}),!p&&!x&&fe()]})})]})}function qo(){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 hN(e,n){const s={};return(e[e.length-1]===""?[...e,""]:e).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const pN=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,fN=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,gN={};function cu(e,n){return(gN.jsx?fN:pN).test(e)}const bN=/[ \t\n\f\r]/g;function xN(e){return typeof e=="object"?e.type==="text"?du(e.value):!1:du(e)}function du(e){return e.replace(bN,"")===""}class nr{constructor(n,s,i){this.normal=s,this.property=n,i&&(this.space=i)}}nr.prototype.normal={};nr.prototype.property={};nr.prototype.space=void 0;function Vh(e,n){const s={},i={};for(const r of e)Object.assign(s,r.property),Object.assign(i,r.normal);return new nr(s,i,n)}function Hl(e){return e.toLowerCase()}class as{constructor(n,s){this.attribute=s,this.property=n}}as.prototype.attribute="";as.prototype.booleanish=!1;as.prototype.boolean=!1;as.prototype.commaOrSpaceSeparated=!1;as.prototype.commaSeparated=!1;as.prototype.defined=!1;as.prototype.mustUseProperty=!1;as.prototype.number=!1;as.prototype.overloadedBoolean=!1;as.prototype.property="";as.prototype.spaceSeparated=!1;as.prototype.space=void 0;let vN=0;const St=Ai(),mn=Ai(),ql=Ai(),Xe=Ai(),Yt=Ai(),qi=Ai(),os=Ai();function Ai(){return 2**++vN}const Vl=Object.freeze(Object.defineProperty({__proto__:null,boolean:St,booleanish:mn,commaOrSpaceSeparated:os,commaSeparated:qi,number:Xe,overloadedBoolean:ql,spaceSeparated:Yt},Symbol.toStringTag,{value:"Module"})),Vo=Object.keys(Vl);class vc extends as{constructor(n,s,i,r){let o=-1;if(super(n,s),uu(this,"space",r),typeof i=="number")for(;++o<Vo.length;){const l=Vo[o];uu(this,Vo[o],(i&Vl[l])===Vl[l])}}}vc.prototype.defined=!0;function uu(e,n,s){s&&(e[n]=s)}function ca(e){const n={},s={};for(const[i,r]of Object.entries(e.properties)){const o=new vc(i,e.transform(e.attributes||{},i),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(i)&&(o.mustUseProperty=!0),n[i]=o,s[Hl(i)]=i,s[Hl(o.attribute)]=i}return new nr(n,s,e.space)}const Wh=ca({properties:{ariaActiveDescendant:null,ariaAtomic:mn,ariaAutoComplete:null,ariaBusy:mn,ariaChecked:mn,ariaColCount:Xe,ariaColIndex:Xe,ariaColSpan:Xe,ariaControls:Yt,ariaCurrent:null,ariaDescribedBy:Yt,ariaDetails:null,ariaDisabled:mn,ariaDropEffect:Yt,ariaErrorMessage:null,ariaExpanded:mn,ariaFlowTo:Yt,ariaGrabbed:mn,ariaHasPopup:null,ariaHidden:mn,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Yt,ariaLevel:Xe,ariaLive:null,ariaModal:mn,ariaMultiLine:mn,ariaMultiSelectable:mn,ariaOrientation:null,ariaOwns:Yt,ariaPlaceholder:null,ariaPosInSet:Xe,ariaPressed:mn,ariaReadOnly:mn,ariaRelevant:null,ariaRequired:mn,ariaRoleDescription:Yt,ariaRowCount:Xe,ariaRowIndex:Xe,ariaRowSpan:Xe,ariaSelected:mn,ariaSetSize:Xe,ariaSort:null,ariaValueMax:Xe,ariaValueMin:Xe,ariaValueNow:Xe,ariaValueText:null,role:null},transform(e,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function Gh(e,n){return n in e?e[n]:n}function Kh(e,n){return Gh(e,n.toLowerCase())}const yN=ca({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:qi,acceptCharset:Yt,accessKey:Yt,action:null,allow:null,allowFullScreen:St,allowPaymentRequest:St,allowUserMedia:St,alt:null,as:null,async:St,autoCapitalize:null,autoComplete:Yt,autoFocus:St,autoPlay:St,blocking:Yt,capture:null,charSet:null,checked:St,cite:null,className:Yt,cols:Xe,colSpan:null,content:null,contentEditable:mn,controls:St,controlsList:Yt,coords:Xe|qi,crossOrigin:null,data:null,dateTime:null,decoding:null,default:St,defer:St,dir:null,dirName:null,disabled:St,download:ql,draggable:mn,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:St,formTarget:null,headers:Yt,height:Xe,hidden:ql,high:Xe,href:null,hrefLang:null,htmlFor:Yt,httpEquiv:Yt,id:null,imageSizes:null,imageSrcSet:null,inert:St,inputMode:null,integrity:null,is:null,isMap:St,itemId:null,itemProp:Yt,itemRef:Yt,itemScope:St,itemType:Yt,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:St,low:Xe,manifest:null,max:null,maxLength:Xe,media:null,method:null,min:null,minLength:Xe,multiple:St,muted:St,name:null,nonce:null,noModule:St,noValidate:St,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:St,optimum:Xe,pattern:null,ping:Yt,placeholder:null,playsInline:St,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:St,referrerPolicy:null,rel:Yt,required:St,reversed:St,rows:Xe,rowSpan:Xe,sandbox:Yt,scope:null,scoped:St,seamless:St,selected:St,shadowRootClonable:St,shadowRootDelegatesFocus:St,shadowRootMode:null,shape:null,size:Xe,sizes:null,slot:null,span:Xe,spellCheck:mn,src:null,srcDoc:null,srcLang:null,srcSet:null,start:Xe,step:null,style:null,tabIndex:Xe,target:null,title:null,translate:null,type:null,typeMustMatch:St,useMap:null,value:mn,width:Xe,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Yt,axis:null,background:null,bgColor:null,border:Xe,borderColor:null,bottomMargin:Xe,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:St,declare:St,event:null,face:null,frame:null,frameBorder:null,hSpace:Xe,leftMargin:Xe,link:null,longDesc:null,lowSrc:null,marginHeight:Xe,marginWidth:Xe,noResize:St,noHref:St,noShade:St,noWrap:St,object:null,profile:null,prompt:null,rev:null,rightMargin:Xe,rules:null,scheme:null,scrolling:mn,standby:null,summary:null,text:null,topMargin:Xe,valueType:null,version:null,vAlign:null,vLink:null,vSpace:Xe,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:St,disableRemotePlayback:St,prefix:null,property:null,results:Xe,security:null,unselectable:null},space:"html",transform:Kh}),kN=ca({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:os,accentHeight:Xe,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:Xe,amplitude:Xe,arabicForm:null,ascent:Xe,attributeName:null,attributeType:null,azimuth:Xe,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:Xe,by:null,calcMode:null,capHeight:Xe,className:Yt,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:Xe,diffuseConstant:Xe,direction:null,display:null,dur:null,divisor:Xe,dominantBaseline:null,download:St,dx:null,dy:null,edgeMode:null,editable:null,elevation:Xe,enableBackground:null,end:null,event:null,exponent:Xe,externalResourcesRequired:null,fill:null,fillOpacity:Xe,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:qi,g2:qi,glyphName:qi,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:Xe,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:Xe,horizOriginX:Xe,horizOriginY:Xe,id:null,ideographic:Xe,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:Xe,k:Xe,k1:Xe,k2:Xe,k3:Xe,k4:Xe,kernelMatrix:os,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:Xe,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:Xe,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:Xe,overlineThickness:Xe,paintOrder:null,panose1:null,path:null,pathLength:Xe,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Yt,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:Xe,pointsAtY:Xe,pointsAtZ:Xe,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:os,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:os,rev:os,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:os,requiredFeatures:os,requiredFonts:os,requiredFormats:os,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:Xe,specularExponent:Xe,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:Xe,strikethroughThickness:Xe,string:null,stroke:null,strokeDashArray:os,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:Xe,strokeOpacity:Xe,strokeWidth:null,style:null,surfaceScale:Xe,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:os,tabIndex:Xe,tableValues:null,target:null,targetX:Xe,targetY:Xe,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:os,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:Xe,underlineThickness:Xe,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:Xe,values:null,vAlphabetic:Xe,vMathematical:Xe,vectorEffect:null,vHanging:Xe,vIdeographic:Xe,version:null,vertAdvY:Xe,vertOriginX:Xe,vertOriginY:Xe,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:Xe,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Gh}),Jh=ca({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()}}),Yh=ca({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Kh}),Qh=ca({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,n){return"xml:"+n.slice(3).toLowerCase()}}),jN={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"},wN=/[A-Z]/g,mu=/-[a-z]/g,NN=/^data[-\w.:]+$/i;function SN(e,n){const s=Hl(n);let i=n,r=as;if(s in e.normal)return e.property[e.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&NN.test(n)){if(n.charAt(4)==="-"){const o=n.slice(5).replace(mu,EN);i="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=n.slice(4);if(!mu.test(o)){let l=o.replace(wN,CN);l.charAt(0)!=="-"&&(l="-"+l),n="data"+l}}r=vc}return new r(i,n)}function CN(e){return"-"+e.toLowerCase()}function EN(e){return e.charAt(1).toUpperCase()}const MN=Vh([Wh,yN,Jh,Yh,Qh],"html"),yc=Vh([Wh,kN,Jh,Yh,Qh],"svg");function _N(e){return e.join(" ").trim()}var Fi={},Wo,hu;function AN(){if(hu)return Wo;hu=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=`
|
|
578
|
-
`,d="/",m="*",h="",g="comment",p="declaration";function f(v,x){if(typeof v!="string")throw new TypeError("First argument must be a string");if(!v)return[];x=x||{};var k=1,M=1;function y($){var I=$.match(n);I&&(k+=I.length);var w=$.lastIndexOf(u);M=~w?$.length-w:M+$.length}function R(){var $={line:k,column:M};return function(I){return I.position=new j($),P(),I}}function j($){this.start=$,this.end={line:k,column:M},this.source=x.source}j.prototype.content=v;function C($){var I=new Error(x.source+":"+k+":"+M+": "+$);if(I.reason=$,I.filename=x.source,I.line=k,I.column=M,I.source=v,!x.silent)throw I}function S($){var I=$.exec(v);if(I){var w=I[0];return y(w),v=v.slice(w.length),I}}function P(){S(s)}function T($){var I;for($=$||[];I=_();)I!==!1&&$.push(I);return $}function _(){var $=R();if(!(d!=v.charAt(0)||m!=v.charAt(1))){for(var I=2;h!=v.charAt(I)&&(m!=v.charAt(I)||d!=v.charAt(I+1));)++I;if(I+=2,h===v.charAt(I-1))return C("End of comment missing");var w=v.slice(2,I-2);return M+=2,y(w),v=v.slice(I),M+=2,$({type:g,comment:w})}}function L(){var $=R(),I=S(i);if(I){if(_(),!S(r))return C("property missing ':'");var w=S(o),q=$({type:p,property:b(I[0].replace(e,h)),value:w?b(w[0].replace(e,h)):h});return S(l),q}}function G(){var $=[];T($);for(var I;I=L();)I!==!1&&($.push(I),T($));return $}return P(),G()}function b(v){return v?v.replace(c,h):h}return Wo=f,Wo}var pu;function TN(){if(pu)return Fi;pu=1;var e=Fi&&Fi.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Fi,"__esModule",{value:!0}),Fi.default=s;const n=e(AN());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 Fi}var xa={},fu;function RN(){if(fu)return xa;fu=1,Object.defineProperty(xa,"__esModule",{value:!0}),xa.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 xa.camelCase=u,xa}var va,gu;function IN(){if(gu)return va;gu=1;var e=va&&va.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},n=e(TN()),s=RN();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,va=i,va}var PN=IN();const $N=Km(PN),Xh=Zh("end"),kc=Zh("start");function Zh(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 DN(e){const n=kc(e),s=Xh(e);if(n&&s)return{start:n,end:s}}function $a(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?bu(e.position):"start"in e||"end"in e?bu(e):"line"in e||"column"in e?Wl(e):""}function Wl(e){return xu(e&&e.line)+":"+xu(e&&e.column)}function bu(e){return Wl(e&&e.start)+"-"+Wl(e&&e.end)}function xu(e){return e&&typeof e=="number"?e:1}class Ln 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=$a(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}}Ln.prototype.file="";Ln.prototype.name="";Ln.prototype.reason="";Ln.prototype.message="";Ln.prototype.stack="";Ln.prototype.column=void 0;Ln.prototype.line=void 0;Ln.prototype.ancestors=void 0;Ln.prototype.cause=void 0;Ln.prototype.fatal=void 0;Ln.prototype.place=void 0;Ln.prototype.ruleId=void 0;Ln.prototype.source=void 0;const jc={}.hasOwnProperty,LN=new Map,zN=/[A-Z]/g,FN=new Set(["table","tbody","thead","tfoot","tr"]),ON=new Set(["td","th"]),ep="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function UN(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=JN(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=KN(s,n.jsx,n.jsxs)}const r={Fragment:n.Fragment,ancestors:[],components:n.components||{},create:i,elementAttributeNameCase:n.elementAttributeNameCase||"react",evaluater:n.createEvaluater?n.createEvaluater():void 0,filePath:s,ignoreInvalidStyle:n.ignoreInvalidStyle||!1,passKeys:n.passKeys!==!1,passNode:n.passNode||!1,schema:n.space==="svg"?yc:MN,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},o=tp(r,e,void 0);return o&&typeof o!="string"?o:r.create(e,r.Fragment,{children:o||void 0},void 0)}function tp(e,n,s){if(n.type==="element")return BN(e,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return HN(e,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return VN(e,n,s);if(n.type==="mdxjsEsm")return qN(e,n);if(n.type==="root")return WN(e,n,s);if(n.type==="text")return GN(e,n)}function BN(e,n,s){const i=e.schema;let r=i;n.tagName.toLowerCase()==="svg"&&i.space==="html"&&(r=yc,e.schema=r),e.ancestors.push(n);const o=sp(e,n.tagName,!1),l=YN(e,n);let c=Nc(e,n);return FN.has(n.tagName)&&(c=c.filter(function(u){return typeof u=="string"?!xN(u):!0})),np(e,l,o,n),wc(l,c),e.ancestors.pop(),e.schema=i,e.create(n,o,l,s)}function HN(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)}qa(e,n.position)}function qN(e,n){if(n.data&&n.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(n.data.estree);qa(e,n.position)}function VN(e,n,s){const i=e.schema;let r=i;n.name==="svg"&&i.space==="html"&&(r=yc,e.schema=r),e.ancestors.push(n);const o=n.name===null?e.Fragment:sp(e,n.name,!0),l=QN(e,n),c=Nc(e,n);return np(e,l,o,n),wc(l,c),e.ancestors.pop(),e.schema=i,e.create(n,o,l,s)}function WN(e,n,s){const i={};return wc(i,Nc(e,n)),e.create(n,e.Fragment,i,s)}function GN(e,n){return n.value}function np(e,n,s,i){typeof s!="string"&&s!==e.Fragment&&e.passNode&&(n.node=i)}function wc(e,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(e.children=s)}}function KN(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 JN(e,n){return s;function s(i,r,o,l){const c=Array.isArray(o.children),u=kc(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 YN(e,n){const s={};let i,r;for(r in n.properties)if(r!=="children"&&jc.call(n.properties,r)){const o=XN(e,r,n.properties[r]);if(o){const[l,c]=o;e.tableCellAlignToStyle&&l==="align"&&typeof c=="string"&&ON.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 QN(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 qa(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 qa(e,n.position);else o=i.value===null?!0:i.value;s[r]=o}return s}function Nc(e,n){const s=[];let i=-1;const r=e.passKeys?new Map:LN;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=tp(e,o,l);c!==void 0&&s.push(c)}return s}function XN(e,n,s){const i=SN(e.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=i.commaSeparated?hN(s):_N(s)),i.property==="style"){let r=typeof s=="object"?s:ZN(e,String(s));return e.stylePropertyNameCase==="css"&&(r=e1(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&i.space?jN[i.property]||i.property:i.attribute,s]}}function ZN(e,n){try{return $N(n,{reactCompat:!0})}catch(s){if(e.ignoreInvalidStyle)return{};const i=s,r=new Ln("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=ep+"#cannot-parse-style-attribute",r}}function sp(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=cu(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=cu(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(i.type==="Literal"){const r=i.value;return jc.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(i);qa(e)}function qa(e,n){const s=new Ln("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=ep+"#cannot-handle-mdx-estrees-without-createevaluater",s}function e1(e){const n={};let s;for(s in e)jc.call(e,s)&&(n[t1(s)]=e[s]);return n}function t1(e){let n=e.replace(zN,n1);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function n1(e){return"-"+e.toLowerCase()}const Go={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"]},s1={};function Sc(e,n){const s=s1,i=typeof s.includeImageAlt=="boolean"?s.includeImageAlt:!0,r=typeof s.includeHtml=="boolean"?s.includeHtml:!0;return ip(e,i,r)}function ip(e,n,s){if(i1(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 vu(e.children,n,s)}return Array.isArray(e)?vu(e,n,s):""}function vu(e,n,s){const i=[];let r=-1;for(;++r<e.length;)i[r]=ip(e[r],n,s);return i.join("")}function i1(e){return!!(e&&typeof e=="object")}const yu=document.createElement("i");function Cc(e){const n="&"+e+";";yu.innerHTML=n;const s=yu.textContent;return s.charCodeAt(s.length-1)===59&&e!=="semi"||s===n?!1:s}function ds(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 ws(e,n){return e.length>0?(ds(e,e.length,0,n),e):n}const ku={}.hasOwnProperty;function ap(e){const n={};let s=-1;for(;++s<e.length;)a1(n,e[s]);return n}function a1(e,n){let s;for(s in n){const r=(ku.call(e,s)?e[s]:void 0)||(e[s]={}),o=n[s];let l;if(o)for(l in o){ku.call(r,l)||(r[l]=[]);const c=o[l];r1(r[l],Array.isArray(c)?c:c?[c]:[])}}}function r1(e,n){let s=-1;const i=[];for(;++s<n.length;)(n[s].add==="after"?e:i).push(n[s]);ds(e,0,0,i)}function rp(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 Rs(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const qn=ui(/[A-Za-z]/),$n=ui(/[\dA-Za-z]/),o1=ui(/[#-'*+\--9=?A-Z^-~]/);function Wr(e){return e!==null&&(e<32||e===127)}const Gl=ui(/\d/),l1=ui(/[\dA-Fa-f]/),c1=ui(/[!-/:-@[-`{-~]/);function yt(e){return e!==null&&e<-2}function Wt(e){return e!==null&&(e<0||e===32)}function It(e){return e===-2||e===-1||e===32}const ho=ui(/\p{P}|\p{S}/u),Ei=ui(/\s/);function ui(e){return n;function n(s){return s!==null&&s>-1&&e.test(String.fromCharCode(s))}}function da(e){const n=[];let s=-1,i=0,r=0;for(;++s<e.length;){const o=e.charCodeAt(s);let l="";if(o===37&&$n(e.charCodeAt(s+1))&&$n(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 Ft(e,n,s,i){const r=i?i-1:Number.POSITIVE_INFINITY;let o=0;return l;function l(u){return It(u)?(e.enter(s),c(u)):n(u)}function c(u){return It(u)&&o++<r?(e.consume(u),c):(e.exit(s),n(u))}}const d1={tokenize:u1};function u1(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"),Ft(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 yt(c)?(e.consume(c),e.exit("chunkText"),o):(e.consume(c),l)}}const m1={tokenize:h1},ju={tokenize:p1};function h1(e){const n=this,s=[];let i=0,r,o,l;return c;function c(M){if(i<s.length){const y=s[i];return n.containerState=y[1],e.attempt(y[0].continuation,u,d)(M)}return d(M)}function u(M){if(i++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,r&&k();const y=n.events.length;let R=y,j;for(;R--;)if(n.events[R][0]==="exit"&&n.events[R][1].type==="chunkFlow"){j=n.events[R][1].end;break}x(i);let C=y;for(;C<n.events.length;)n.events[C][1].end={...j},C++;return ds(n.events,R+1,0,n.events.slice(y)),n.events.length=C,d(M)}return c(M)}function d(M){if(i===s.length){if(!r)return g(M);if(r.currentConstruct&&r.currentConstruct.concrete)return f(M);n.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return n.containerState={},e.check(ju,m,h)(M)}function m(M){return r&&k(),x(i),g(M)}function h(M){return n.parser.lazy[n.now().line]=i!==s.length,l=n.now().offset,f(M)}function g(M){return n.containerState={},e.attempt(ju,p,f)(M)}function p(M){return i++,s.push([n.currentConstruct,n.containerState]),g(M)}function f(M){if(M===null){r&&k(),x(0),e.consume(M);return}return r=r||n.parser.flow(n.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:o}),b(M)}function b(M){if(M===null){v(e.exit("chunkFlow"),!0),x(0),e.consume(M);return}return yt(M)?(e.consume(M),v(e.exit("chunkFlow")),i=0,n.interrupt=void 0,c):(e.consume(M),b)}function v(M,y){const R=n.sliceStream(M);if(y&&R.push(null),M.previous=o,o&&(o.next=M),o=M,r.defineSkip(M.start),r.write(R),n.parser.lazy[M.start.line]){let j=r.events.length;for(;j--;)if(r.events[j][1].start.offset<l&&(!r.events[j][1].end||r.events[j][1].end.offset>l))return;const C=n.events.length;let S=C,P,T;for(;S--;)if(n.events[S][0]==="exit"&&n.events[S][1].type==="chunkFlow"){if(P){T=n.events[S][1].end;break}P=!0}for(x(i),j=C;j<n.events.length;)n.events[j][1].end={...T},j++;ds(n.events,S+1,0,n.events.slice(C)),n.events.length=j}}function x(M){let y=s.length;for(;y-- >M;){const R=s[y];n.containerState=R[1],R[0].exit.call(n,e)}s.length=M}function k(){r.write([null]),o=void 0,r=void 0,n.containerState._closeFlow=void 0}}function p1(e,n,s){return Ft(e,e.attempt(this.parser.constructs.document,n,s),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Qi(e){if(e===null||Wt(e)||Ei(e))return 1;if(ho(e))return 2}function po(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 Kl={name:"attention",resolveAll:f1,tokenize:g1};function f1(e,n){let s=-1,i,r,o,l,c,u,d,m;for(;++s<e.length;)if(e[s][0]==="enter"&&e[s][1].type==="attentionSequence"&&e[s][1]._close){for(i=s;i--;)if(e[i][0]==="exit"&&e[i][1].type==="attentionSequence"&&e[i][1]._open&&n.sliceSerialize(e[i][1]).charCodeAt(0)===n.sliceSerialize(e[s][1]).charCodeAt(0)){if((e[i][1]._close||e[s][1]._open)&&(e[s][1].end.offset-e[s][1].start.offset)%3&&!((e[i][1].end.offset-e[i][1].start.offset+e[s][1].end.offset-e[s][1].start.offset)%3))continue;u=e[i][1].end.offset-e[i][1].start.offset>1&&e[s][1].end.offset-e[s][1].start.offset>1?2:1;const h={...e[i][1].end},g={...e[s][1].start};wu(h,-u),wu(g,u),l={type:u>1?"strongSequence":"emphasisSequence",start:h,end:{...e[i][1].end}},c={type:u>1?"strongSequence":"emphasisSequence",start:{...e[s][1].start},end:g},o={type:u>1?"strongText":"emphasisText",start:{...e[i][1].end},end:{...e[s][1].start}},r={type:u>1?"strong":"emphasis",start:{...l.start},end:{...c.end}},e[i][1].end={...l.start},e[s][1].start={...c.end},d=[],e[i][1].end.offset-e[i][1].start.offset&&(d=ws(d,[["enter",e[i][1],n],["exit",e[i][1],n]])),d=ws(d,[["enter",r,n],["enter",l,n],["exit",l,n],["enter",o,n]]),d=ws(d,po(n.parser.constructs.insideSpan.null,e.slice(i+1,s),n)),d=ws(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=ws(d,[["enter",e[s][1],n],["exit",e[s][1],n]])):m=0,ds(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 g1(e,n){const s=this.parser.constructs.attentionMarkers.null,i=this.previous,r=Qi(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=Qi(u),h=!m||m===2&&r||s.includes(u),g=!r||r===2&&m||s.includes(i);return d._open=!!(o===42?h:h&&(r||!g)),d._close=!!(o===42?g:g&&(m||!h)),n(u)}}function wu(e,n){e.column+=n,e.offset+=n,e._bufferIndex+=n}const b1={name:"autolink",tokenize:x1};function x1(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 qn(p)?(e.consume(p),l):p===64?s(p):d(p)}function l(p){return p===43||p===45||p===46||$n(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||$n(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||Wr(p)?s(p):(e.consume(p),u)}function d(p){return p===64?(e.consume(p),m):o1(p)?(e.consume(p),d):s(p)}function m(p){return $n(p)?h(p):s(p)}function h(p){return p===46?(e.consume(p),i=0,m):p===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.exit("autolink"),n):g(p)}function g(p){if((p===45||$n(p))&&i++<63){const f=p===45?g:h;return e.consume(p),f}return s(p)}}const sr={partial:!0,tokenize:v1};function v1(e,n,s){return i;function i(o){return It(o)?Ft(e,r,"linePrefix")(o):r(o)}function r(o){return o===null||yt(o)?n(o):s(o)}}const op={continuation:{tokenize:k1},exit:j1,name:"blockQuote",tokenize:y1};function y1(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 It(l)?(e.enter("blockQuotePrefixWhitespace"),e.consume(l),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),n):(e.exit("blockQuotePrefix"),n(l))}}function k1(e,n,s){const i=this;return r;function r(l){return It(l)?Ft(e,o,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l):o(l)}function o(l){return e.attempt(op,n,s)(l)}}function j1(e){e.exit("blockQuote")}const lp={name:"characterEscape",tokenize:w1};function w1(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 c1(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),n):s(o)}}const cp={name:"characterReference",tokenize:N1};function N1(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=$n,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=l1,m):(e.enter("characterReferenceValue"),o=7,l=Gl,m(h))}function m(h){if(h===59&&r){const g=e.exit("characterReferenceValue");return l===$n&&!Cc(i.sliceSerialize(g))?s(h):(e.enter("characterReferenceMarker"),e.consume(h),e.exit("characterReferenceMarker"),e.exit("characterReference"),n)}return l(h)&&r++<o?(e.consume(h),m):s(h)}}const Nu={partial:!0,tokenize:C1},Su={concrete:!0,name:"codeFenced",tokenize:S1};function S1(e,n,s){const i=this,r={partial:!0,tokenize:R};let o=0,l=0,c;return u;function u(j){return d(j)}function d(j){const C=i.events[i.events.length-1];return o=C&&C[1].type==="linePrefix"?C[2].sliceSerialize(C[1],!0).length:0,c=j,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),m(j)}function m(j){return j===c?(l++,e.consume(j),m):l<3?s(j):(e.exit("codeFencedFenceSequence"),It(j)?Ft(e,h,"whitespace")(j):h(j))}function h(j){return j===null||yt(j)?(e.exit("codeFencedFence"),i.interrupt?n(j):e.check(Nu,b,y)(j)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),g(j))}function g(j){return j===null||yt(j)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),h(j)):It(j)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),Ft(e,p,"whitespace")(j)):j===96&&j===c?s(j):(e.consume(j),g)}function p(j){return j===null||yt(j)?h(j):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),f(j))}function f(j){return j===null||yt(j)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),h(j)):j===96&&j===c?s(j):(e.consume(j),f)}function b(j){return e.attempt(r,y,v)(j)}function v(j){return e.enter("lineEnding"),e.consume(j),e.exit("lineEnding"),x}function x(j){return o>0&&It(j)?Ft(e,k,"linePrefix",o+1)(j):k(j)}function k(j){return j===null||yt(j)?e.check(Nu,b,y)(j):(e.enter("codeFlowValue"),M(j))}function M(j){return j===null||yt(j)?(e.exit("codeFlowValue"),k(j)):(e.consume(j),M)}function y(j){return e.exit("codeFenced"),n(j)}function R(j,C,S){let P=0;return T;function T(I){return j.enter("lineEnding"),j.consume(I),j.exit("lineEnding"),_}function _(I){return j.enter("codeFencedFence"),It(I)?Ft(j,L,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(I):L(I)}function L(I){return I===c?(j.enter("codeFencedFenceSequence"),G(I)):S(I)}function G(I){return I===c?(P++,j.consume(I),G):P>=l?(j.exit("codeFencedFenceSequence"),It(I)?Ft(j,$,"whitespace")(I):$(I)):S(I)}function $(I){return I===null||yt(I)?(j.exit("codeFencedFence"),C(I)):S(I)}}}function C1(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 Ko={name:"codeIndented",tokenize:M1},E1={partial:!0,tokenize:_1};function M1(e,n,s){const i=this;return r;function r(d){return e.enter("codeIndented"),Ft(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):yt(d)?e.attempt(E1,l,u)(d):(e.enter("codeFlowValue"),c(d))}function c(d){return d===null||yt(d)?(e.exit("codeFlowValue"),l(d)):(e.consume(d),c)}function u(d){return e.exit("codeIndented"),n(d)}}function _1(e,n,s){const i=this;return r;function r(l){return i.parser.lazy[i.now().line]?s(l):yt(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),r):Ft(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):yt(l)?r(l):s(l)}}const A1={name:"codeText",previous:R1,resolve:T1,tokenize:I1};function T1(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 R1(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function I1(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)):yt(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||yt(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 P1{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&&ya(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),ya(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),ya(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);ya(this.right,s.reverse())}else{const s=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);ya(this.left,s.reverse())}}}function ya(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 dp(e){const n={};let s=-1,i,r,o,l,c,u,d;const m=new P1(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,$1(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 ds(e,0,Number.POSITIVE_INFINITY,m.slice(0)),!d}function $1(e,n){const s=e.get(n)[1],i=e.get(n)[2];let r=n-1;const o=[];let l=s._tokenizer;l||(l=i.parser[s.contentType](s.start),s._contentTypeTextTrailing&&(l._contentTypeTextTrailing=!0));const c=l.events,u=[],d={};let m,h,g=-1,p=s,f=0,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;++g<c.length;)c[g][0]==="exit"&&c[g-1][0]==="enter"&&c[g][1].type===c[g-1][1].type&&c[g][1].start.line!==c[g][1].end.line&&(b=g+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(),g=v.length;g--;){const x=c.slice(v[g],v[g+1]),k=o.pop();u.push([k,k+x.length-1]),e.splice(k,2,x)}for(u.reverse(),g=-1;++g<u.length;)d[f+u[g][0]]=f+u[g][1],f+=u[g][1]-u[g][0]-1;return d}const D1={resolve:z1,tokenize:F1},L1={partial:!0,tokenize:O1};function z1(e){return dp(e),e}function F1(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):yt(c)?e.check(L1,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 O1(e,n,s){const i=this;return r;function r(l){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),Ft(e,o,"linePrefix")}function o(l){if(l===null||yt(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 up(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),g):x===null||x===32||x===41||Wr(x)?s(x):(e.enter(i),e.enter(l),e.enter(c),e.enter("chunkString",{contentType:"string"}),b(x))}function g(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),g(x)):x===null||x===60||yt(x)?s(x):(e.consume(x),x===92?f:p)}function f(x){return x===60||x===62||x===92?(e.consume(x),p):p(x)}function b(x){return!m&&(x===null||x===41||Wt(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||Wr(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 mp(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):yt(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||yt(p)||c++>999?(e.exit("chunkString"),m(p)):(e.consume(p),u||(u=!It(p)),p===92?g:h)}function g(p){return p===91||p===92||p===93?(e.consume(p),c++,h):h(p)}}function hp(e,n,s,i,r,o){let l;return c;function c(g){return g===34||g===39||g===40?(e.enter(i),e.enter(r),e.consume(g),e.exit(r),l=g===40?41:g,u):s(g)}function u(g){return g===l?(e.enter(r),e.consume(g),e.exit(r),e.exit(i),n):(e.enter(o),d(g))}function d(g){return g===l?(e.exit(o),u(l)):g===null?s(g):yt(g)?(e.enter("lineEnding"),e.consume(g),e.exit("lineEnding"),Ft(e,d,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),m(g))}function m(g){return g===l||g===null||yt(g)?(e.exit("chunkString"),d(g)):(e.consume(g),g===92?h:m)}function h(g){return g===l||g===92?(e.consume(g),m):m(g)}}function Da(e,n){let s;return i;function i(r){return yt(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),s=!0,i):It(r)?Ft(e,i,s?"linePrefix":"lineSuffix")(r):n(r)}}const U1={name:"definition",tokenize:H1},B1={partial:!0,tokenize:q1};function H1(e,n,s){const i=this;let r;return o;function o(p){return e.enter("definition"),l(p)}function l(p){return mp.call(i,e,c,s,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function c(p){return r=Rs(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 Wt(p)?Da(e,d)(p):d(p)}function d(p){return up(e,m,s,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function m(p){return e.attempt(B1,h,h)(p)}function h(p){return It(p)?Ft(e,g,"whitespace")(p):g(p)}function g(p){return p===null||yt(p)?(e.exit("definition"),i.parser.defined.push(r),n(p)):s(p)}}function q1(e,n,s){return i;function i(c){return Wt(c)?Da(e,r)(c):s(c)}function r(c){return hp(e,o,s,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function o(c){return It(c)?Ft(e,l,"whitespace")(c):l(c)}function l(c){return c===null||yt(c)?n(c):s(c)}}const V1={name:"hardBreakEscape",tokenize:W1};function W1(e,n,s){return i;function i(o){return e.enter("hardBreakEscape"),e.consume(o),r}function r(o){return yt(o)?(e.exit("hardBreakEscape"),n(o)):s(o)}}const G1={name:"headingAtx",resolve:K1,tokenize:J1};function K1(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"},ds(e,i,s-i+1,[["enter",r,n],["enter",o,n],["exit",o,n],["exit",r,n]])),e}function J1(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||Wt(m)?(e.exit("atxHeadingSequence"),c(m)):s(m)}function c(m){return m===35?(e.enter("atxHeadingSequence"),u(m)):m===null||yt(m)?(e.exit("atxHeading"),n(m)):It(m)?Ft(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||Wt(m)?(e.exit("atxHeadingText"),c(m)):(e.consume(m),d)}}const Y1=["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"],Cu=["pre","script","style","textarea"],Q1={concrete:!0,name:"htmlFlow",resolveTo:e0,tokenize:t0},X1={partial:!0,tokenize:s0},Z1={partial:!0,tokenize:n0};function e0(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 t0(e,n,s){const i=this;let r,o,l,c,u;return d;function d(E){return m(E)}function m(E){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(E),h}function h(E){return E===33?(e.consume(E),g):E===47?(e.consume(E),o=!0,b):E===63?(e.consume(E),r=3,i.interrupt?n:A):qn(E)?(e.consume(E),l=String.fromCharCode(E),v):s(E)}function g(E){return E===45?(e.consume(E),r=2,p):E===91?(e.consume(E),r=5,c=0,f):qn(E)?(e.consume(E),r=4,i.interrupt?n:A):s(E)}function p(E){return E===45?(e.consume(E),i.interrupt?n:A):s(E)}function f(E){const U="CDATA[";return E===U.charCodeAt(c++)?(e.consume(E),c===U.length?i.interrupt?n:L:f):s(E)}function b(E){return qn(E)?(e.consume(E),l=String.fromCharCode(E),v):s(E)}function v(E){if(E===null||E===47||E===62||Wt(E)){const U=E===47,pe=l.toLowerCase();return!U&&!o&&Cu.includes(pe)?(r=1,i.interrupt?n(E):L(E)):Y1.includes(l.toLowerCase())?(r=6,U?(e.consume(E),x):i.interrupt?n(E):L(E)):(r=7,i.interrupt&&!i.parser.lazy[i.now().line]?s(E):o?k(E):M(E))}return E===45||$n(E)?(e.consume(E),l+=String.fromCharCode(E),v):s(E)}function x(E){return E===62?(e.consume(E),i.interrupt?n:L):s(E)}function k(E){return It(E)?(e.consume(E),k):T(E)}function M(E){return E===47?(e.consume(E),T):E===58||E===95||qn(E)?(e.consume(E),y):It(E)?(e.consume(E),M):T(E)}function y(E){return E===45||E===46||E===58||E===95||$n(E)?(e.consume(E),y):R(E)}function R(E){return E===61?(e.consume(E),j):It(E)?(e.consume(E),R):M(E)}function j(E){return E===null||E===60||E===61||E===62||E===96?s(E):E===34||E===39?(e.consume(E),u=E,C):It(E)?(e.consume(E),j):S(E)}function C(E){return E===u?(e.consume(E),u=null,P):E===null||yt(E)?s(E):(e.consume(E),C)}function S(E){return E===null||E===34||E===39||E===47||E===60||E===61||E===62||E===96||Wt(E)?R(E):(e.consume(E),S)}function P(E){return E===47||E===62||It(E)?M(E):s(E)}function T(E){return E===62?(e.consume(E),_):s(E)}function _(E){return E===null||yt(E)?L(E):It(E)?(e.consume(E),_):s(E)}function L(E){return E===45&&r===2?(e.consume(E),w):E===60&&r===1?(e.consume(E),q):E===62&&r===4?(e.consume(E),z):E===63&&r===3?(e.consume(E),A):E===93&&r===5?(e.consume(E),B):yt(E)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(X1,X,G)(E)):E===null||yt(E)?(e.exit("htmlFlowData"),G(E)):(e.consume(E),L)}function G(E){return e.check(Z1,$,X)(E)}function $(E){return e.enter("lineEnding"),e.consume(E),e.exit("lineEnding"),I}function I(E){return E===null||yt(E)?G(E):(e.enter("htmlFlowData"),L(E))}function w(E){return E===45?(e.consume(E),A):L(E)}function q(E){return E===47?(e.consume(E),l="",W):L(E)}function W(E){if(E===62){const U=l.toLowerCase();return Cu.includes(U)?(e.consume(E),z):L(E)}return qn(E)&&l.length<8?(e.consume(E),l+=String.fromCharCode(E),W):L(E)}function B(E){return E===93?(e.consume(E),A):L(E)}function A(E){return E===62?(e.consume(E),z):E===45&&r===2?(e.consume(E),A):L(E)}function z(E){return E===null||yt(E)?(e.exit("htmlFlowData"),X(E)):(e.consume(E),z)}function X(E){return e.exit("htmlFlow"),n(E)}}function n0(e,n,s){const i=this;return r;function r(l){return yt(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 s0(e,n,s){return i;function i(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(sr,n,s)}}const i0={name:"htmlText",tokenize:a0};function a0(e,n,s){const i=this;let r,o,l;return c;function c(A){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(A),u}function u(A){return A===33?(e.consume(A),d):A===47?(e.consume(A),R):A===63?(e.consume(A),M):qn(A)?(e.consume(A),S):s(A)}function d(A){return A===45?(e.consume(A),m):A===91?(e.consume(A),o=0,f):qn(A)?(e.consume(A),k):s(A)}function m(A){return A===45?(e.consume(A),p):s(A)}function h(A){return A===null?s(A):A===45?(e.consume(A),g):yt(A)?(l=h,q(A)):(e.consume(A),h)}function g(A){return A===45?(e.consume(A),p):h(A)}function p(A){return A===62?w(A):A===45?g(A):h(A)}function f(A){const z="CDATA[";return A===z.charCodeAt(o++)?(e.consume(A),o===z.length?b:f):s(A)}function b(A){return A===null?s(A):A===93?(e.consume(A),v):yt(A)?(l=b,q(A)):(e.consume(A),b)}function v(A){return A===93?(e.consume(A),x):b(A)}function x(A){return A===62?w(A):A===93?(e.consume(A),x):b(A)}function k(A){return A===null||A===62?w(A):yt(A)?(l=k,q(A)):(e.consume(A),k)}function M(A){return A===null?s(A):A===63?(e.consume(A),y):yt(A)?(l=M,q(A)):(e.consume(A),M)}function y(A){return A===62?w(A):M(A)}function R(A){return qn(A)?(e.consume(A),j):s(A)}function j(A){return A===45||$n(A)?(e.consume(A),j):C(A)}function C(A){return yt(A)?(l=C,q(A)):It(A)?(e.consume(A),C):w(A)}function S(A){return A===45||$n(A)?(e.consume(A),S):A===47||A===62||Wt(A)?P(A):s(A)}function P(A){return A===47?(e.consume(A),w):A===58||A===95||qn(A)?(e.consume(A),T):yt(A)?(l=P,q(A)):It(A)?(e.consume(A),P):w(A)}function T(A){return A===45||A===46||A===58||A===95||$n(A)?(e.consume(A),T):_(A)}function _(A){return A===61?(e.consume(A),L):yt(A)?(l=_,q(A)):It(A)?(e.consume(A),_):P(A)}function L(A){return A===null||A===60||A===61||A===62||A===96?s(A):A===34||A===39?(e.consume(A),r=A,G):yt(A)?(l=L,q(A)):It(A)?(e.consume(A),L):(e.consume(A),$)}function G(A){return A===r?(e.consume(A),r=void 0,I):A===null?s(A):yt(A)?(l=G,q(A)):(e.consume(A),G)}function $(A){return A===null||A===34||A===39||A===60||A===61||A===96?s(A):A===47||A===62||Wt(A)?P(A):(e.consume(A),$)}function I(A){return A===47||A===62||Wt(A)?P(A):s(A)}function w(A){return A===62?(e.consume(A),e.exit("htmlTextData"),e.exit("htmlText"),n):s(A)}function q(A){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(A),e.exit("lineEnding"),W}function W(A){return It(A)?Ft(e,B,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(A):B(A)}function B(A){return e.enter("htmlTextData"),l(A)}}const Ec={name:"labelEnd",resolveAll:c0,resolveTo:d0,tokenize:u0},r0={tokenize:m0},o0={tokenize:h0},l0={tokenize:p0};function c0(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&&ds(e,0,e.length,s),e}function d0(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=ws(c,e.slice(o+1,o+i+3)),c=ws(c,[["enter",m,n]]),c=ws(c,po(n.parser.constructs.insideSpan.null,e.slice(o+i+4,l-3),n)),c=ws(c,[["exit",m,n],e[l-2],e[l-1],["exit",d,n]]),c=ws(c,e.slice(l+1)),c=ws(c,[["exit",u,n]]),ds(e,o,e.length,c),e}function u0(e,n,s){const i=this;let r=i.events.length,o,l;for(;r--;)if((i.events[r][1].type==="labelImage"||i.events[r][1].type==="labelLink")&&!i.events[r][1]._balanced){o=i.events[r][1];break}return c;function c(g){return o?o._inactive?h(g):(l=i.parser.defined.includes(Rs(i.sliceSerialize({start:o.end,end:i.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(g),e.exit("labelMarker"),e.exit("labelEnd"),u):s(g)}function u(g){return g===40?e.attempt(r0,m,l?m:h)(g):g===91?e.attempt(o0,m,l?d:h)(g):l?m(g):h(g)}function d(g){return e.attempt(l0,m,h)(g)}function m(g){return n(g)}function h(g){return o._balanced=!0,s(g)}}function m0(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 Wt(h)?Da(e,o)(h):o(h)}function o(h){return h===41?m(h):up(e,l,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function l(h){return Wt(h)?Da(e,u)(h):m(h)}function c(h){return s(h)}function u(h){return h===34||h===39||h===40?hp(e,d,s,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):m(h)}function d(h){return Wt(h)?Da(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 h0(e,n,s){const i=this;return r;function r(c){return mp.call(i,e,o,l,"reference","referenceMarker","referenceString")(c)}function o(c){return i.parser.defined.includes(Rs(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)))?n(c):s(c)}function l(c){return s(c)}}function p0(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 f0={name:"labelStartImage",resolveAll:Ec.resolveAll,tokenize:g0};function g0(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 b0={name:"labelStartLink",resolveAll:Ec.resolveAll,tokenize:x0};function x0(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 Jo={name:"lineEnding",tokenize:v0};function v0(e,n){return s;function s(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),Ft(e,n,"linePrefix")}}const Rr={name:"thematicBreak",tokenize:y0};function y0(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||yt(d))?(e.exit("thematicBreak"),n(d)):s(d)}function u(d){return d===r?(e.consume(d),i++,u):(e.exit("thematicBreakSequence"),It(d)?Ft(e,c,"whitespace")(d):c(d))}}const Zn={continuation:{tokenize:N0},exit:C0,name:"list",tokenize:w0},k0={partial:!0,tokenize:E0},j0={partial:!0,tokenize:S0};function w0(e,n,s){const i=this,r=i.events[i.events.length-1];let o=r&&r[1].type==="linePrefix"?r[2].sliceSerialize(r[1],!0).length:0,l=0;return c;function c(p){const f=i.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(f==="listUnordered"?!i.containerState.marker||p===i.containerState.marker:Gl(p)){if(i.containerState.type||(i.containerState.type=f,e.enter(f,{_container:!0})),f==="listUnordered")return e.enter("listItemPrefix"),p===42||p===45?e.check(Rr,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 Gl(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(sr,i.interrupt?s:m,e.attempt(k0,g,h))}function m(p){return i.containerState.initialBlankLine=!0,o++,g(p)}function h(p){return It(p)?(e.enter("listItemPrefixWhitespace"),e.consume(p),e.exit("listItemPrefixWhitespace"),g):s(p)}function g(p){return i.containerState.size=o+i.sliceSerialize(e.exit("listItemPrefix"),!0).length,n(p)}}function N0(e,n,s){const i=this;return i.containerState._closeFlow=void 0,e.check(sr,r,o);function r(c){return i.containerState.furtherBlankLines=i.containerState.furtherBlankLines||i.containerState.initialBlankLine,Ft(e,n,"listItemIndent",i.containerState.size+1)(c)}function o(c){return i.containerState.furtherBlankLines||!It(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(j0,n,l)(c))}function l(c){return i.containerState._closeFlow=!0,i.interrupt=void 0,Ft(e,e.attempt(Zn,n,s),"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function S0(e,n,s){const i=this;return Ft(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 C0(e){e.exit(this.containerState.type)}function E0(e,n,s){const i=this;return Ft(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!It(o)&&l&&l[1].type==="listItemPrefixWhitespace"?n(o):s(o)}}const Eu={name:"setextUnderline",resolveTo:M0,tokenize:_0};function M0(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 _0(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"),It(d)?Ft(e,u,"lineSuffix")(d):u(d))}function u(d){return d===null||yt(d)?(e.exit("setextHeadingLine"),n(d)):s(d)}}const A0={tokenize:T0};function T0(e){const n=this,s=e.attempt(sr,i,e.attempt(this.parser.constructs.flowInitial,r,Ft(e,e.attempt(this.parser.constructs.flow,r,e.attempt(D1,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 R0={resolveAll:fp()},I0=pp("string"),P0=pp("text");function pp(e){return{resolveAll:fp(e==="text"?$0:void 0),tokenize:n};function n(s){const i=this,r=this.parser.constructs[e],o=s.attempt(r,l,c);return l;function l(m){return d(m)?o(m):c(m)}function c(m){if(m===null){s.consume(m);return}return s.enter("data"),s.consume(m),u}function u(m){return d(m)?(s.exit("data"),o(m)):(s.consume(m),u)}function d(m){if(m===null)return!0;const h=r[m];let g=-1;if(h)for(;++g<h.length;){const p=h[g];if(!p.previous||p.previous.call(i,i.previous))return!0}return!1}}}function fp(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 $0(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 D0={42:Zn,43:Zn,45:Zn,48:Zn,49:Zn,50:Zn,51:Zn,52:Zn,53:Zn,54:Zn,55:Zn,56:Zn,57:Zn,62:op},L0={91:U1},z0={[-2]:Ko,[-1]:Ko,32:Ko},F0={35:G1,42:Rr,45:[Eu,Rr],60:Q1,61:Eu,95:Rr,96:Su,126:Su},O0={38:cp,92:lp},U0={[-5]:Jo,[-4]:Jo,[-3]:Jo,33:f0,38:cp,42:Kl,60:[b1,i0],91:b0,92:[V1,lp],93:Ec,95:Kl,96:A1},B0={null:[Kl,R0]},H0={null:[42,95]},q0={null:[]},V0=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:H0,contentInitial:L0,disable:q0,document:D0,flow:F0,flowInitial:z0,insideSpan:B0,string:O0,text:U0},Symbol.toStringTag,{value:"Module"}));function W0(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:C(R),check:C(j),consume:k,enter:M,exit:y,interrupt:C(j,{interrupt:!0})},d={code:null,containerState:{},defineSkip:b,events:[],now:f,parser:e,previous:null,sliceSerialize:g,sliceStream:p,write:h};let m=n.tokenize.call(d,u);return n.resolveAll&&o.push(n),d;function h(_){return l=ws(l,_),v(),l[l.length-1]!==null?[]:(S(n,0),d.events=po(o,d.events,d),d.events)}function g(_,L){return K0(p(_),L)}function p(_){return G0(l,_)}function f(){const{_bufferIndex:_,_index:L,line:G,column:$,offset:I}=i;return{_bufferIndex:_,_index:L,line:G,column:$,offset:I}}function b(_){r[_.line]=_.column,T()}function v(){let _;for(;i._index<l.length;){const L=l[i._index];if(typeof L=="string")for(_=i._index,i._bufferIndex<0&&(i._bufferIndex=0);i._index===_&&i._bufferIndex<L.length;)x(L.charCodeAt(i._bufferIndex));else x(L)}}function x(_){m=m(_)}function k(_){yt(_)?(i.line++,i.column=1,i.offset+=_===-3?2:1,T()):_!==-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=_}function M(_,L){const G=L||{};return G.type=_,G.start=f(),d.events.push(["enter",G,d]),c.push(G),G}function y(_){const L=c.pop();return L.end=f(),d.events.push(["exit",L,d]),L}function R(_,L){S(_,L.from)}function j(_,L){L.restore()}function C(_,L){return G;function G($,I,w){let q,W,B,A;return Array.isArray($)?X($):"tokenize"in $?X([$]):z($);function z(ie){return re;function re(F){const ce=F!==null&&ie[F],ae=F!==null&&ie.null,Q=[...Array.isArray(ce)?ce:ce?[ce]:[],...Array.isArray(ae)?ae:ae?[ae]:[]];return X(Q)(F)}}function X(ie){return q=ie,W=0,ie.length===0?w:E(ie[W])}function E(ie){return re;function re(F){return A=P(),B=ie,ie.partial||(d.currentConstruct=ie),ie.name&&d.parser.constructs.disable.null.includes(ie.name)?pe():ie.tokenize.call(L?Object.assign(Object.create(d),L):d,u,U,pe)(F)}}function U(ie){return _(B,A),I}function pe(ie){return A.restore(),++W<q.length?E(q[W]):w}}}function S(_,L){_.resolveAll&&!o.includes(_)&&o.push(_),_.resolve&&ds(d.events,L,d.events.length-L,_.resolve(d.events.slice(L),d)),_.resolveTo&&(d.events=_.resolveTo(d.events,d))}function P(){const _=f(),L=d.previous,G=d.currentConstruct,$=d.events.length,I=Array.from(c);return{from:$,restore:w};function w(){i=_,d.previous=L,d.currentConstruct=G,d.events.length=$,c=I,T()}}function T(){i.line in r&&i.column<2&&(i.column=r[i.line],i.offset+=r[i.line]-1)}}function G0(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 K0(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=`
|
|
579
|
-
`;break}case-3:{l=`\r
|
|
580
|
-
`;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 J0(e){const i={constructs:ap([V0,...(e||{}).extensions||[]]),content:r(d1),defined:[],document:r(m1),flow:r(A0),lazy:{},string:r(I0),text:r(P0)};return i;function r(o){return l;function l(c){return W0(i,o,c)}}}function Y0(e){for(;!dp(e););return e}const Mu=/[\0\t\n\r]/g;function Q0(){let e=1,n="",s=!0,i;return r;function r(o,l,c){const u=[];let d,m,h,g,p;for(o=n+(typeof o=="string"?o.toString():new TextDecoder(l||void 0).decode(o)),h=0,n="",s&&(o.charCodeAt(0)===65279&&h++,s=void 0);h<o.length;){if(Mu.lastIndex=h,d=Mu.exec(o),g=d&&d.index!==void 0?d.index:o.length,p=o.charCodeAt(g),!d){n=o.slice(h);break}if(p===10&&h===g&&i)u.push(-3),i=void 0;else switch(i&&(u.push(-5),i=void 0),h<g&&(u.push(o.slice(h,g)),e+=g-h),p){case 0:{u.push(65533),e++;break}case 9:{for(m=Math.ceil(e/4)*4,u.push(-2);e++<m;)u.push(-1);break}case 10:{u.push(-4),e=1;break}default:i=!0,e=1}h=g+1}return c&&(i&&u.push(-5),n&&u.push(n),u.push(null)),u}}const X0=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function Z0(e){return e.replace(X0,eS)}function eS(e,n,s){if(n)return n;if(s.charCodeAt(0)===35){const r=s.charCodeAt(1),o=r===120||r===88;return rp(s.slice(o?2:1),o?16:10)}return Cc(s)||e}const gp={}.hasOwnProperty;function tS(e,n,s){return n&&typeof n=="object"&&(s=n,n=void 0),nS(s)(Y0(J0(s).document().write(Q0()(e,n,!0))))}function nS(e){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(We),autolinkProtocol:P,autolinkEmail:P,atxHeading:o(Se),blockQuote:o(ae),characterEscape:P,characterReference:P,codeFenced:o(Q),codeFencedFenceInfo:l,codeFencedFenceMeta:l,codeIndented:o(Q,l),codeText:o(de,l),codeTextData:P,data:P,codeFlowValue:P,definition:o(Te),definitionDestinationString:l,definitionLabelString:l,definitionTitleString:l,emphasis:o(fe),hardBreakEscape:o(te),hardBreakTrailing:o(te),htmlFlow:o(we,l),htmlFlowData:P,htmlText:o(we,l),htmlTextData:P,image:o(Pe),label:l,link:o(We),listItem:o(Ne),listItemValue:g,listOrdered:o(Ke,h),listUnordered:o(Ke),paragraph:o(_e),reference:E,referenceString:l,resourceDestinationString:l,resourceTitleString:l,setextHeading:o(Se),strong:o(Oe),thematicBreak:o(De)},exit:{atxHeading:u(),atxHeadingSequence:R,autolink:u(),autolinkEmail:ce,autolinkProtocol:F,blockQuote:u(),characterEscapeValue:T,characterReferenceMarkerHexadecimal:pe,characterReferenceMarkerNumeric:pe,characterReferenceValue:ie,characterReference:re,codeFenced:u(v),codeFencedFence:b,codeFencedFenceInfo:p,codeFencedFenceMeta:f,codeFlowValue:T,codeIndented:u(x),codeText:u(I),codeTextData:T,data:T,definition:u(),definitionDestinationString:y,definitionLabelString:k,definitionTitleString:M,emphasis:u(),hardBreakEscape:u(L),hardBreakTrailing:u(L),htmlFlow:u(G),htmlFlowData:T,htmlText:u($),htmlTextData:T,image:u(q),label:B,labelText:W,lineEnding:_,link:u(w),listItem:u(),listOrdered:u(),listUnordered:u(),paragraph:u(),referenceString:U,resourceDestinationString:A,resourceTitleString:z,resource:X,setextHeading:u(S),setextHeadingLineSequence:C,setextHeadingText:j,strong:u(),thematicBreak:u()}};bp(n,(e||{}).mdastExtensions||[]);const s={};return i;function i(se){let J={type:"root",children:[]};const me={stack:[J],tokenStack:[],config:n,enter:c,exit:d,buffer:l,resume:m,data:s},ee=[];let he=-1;for(;++he<se.length;)if(se[he][1].type==="listOrdered"||se[he][1].type==="listUnordered")if(se[he][0]==="enter")ee.push(he);else{const le=ee.pop();he=r(se,le,he)}for(he=-1;++he<se.length;){const le=n[se[he][0]];gp.call(le,se[he][1].type)&&le[se[he][1].type].call(Object.assign({sliceSerialize:se[he][2].sliceSerialize},me),se[he][1])}if(me.tokenStack.length>0){const le=me.tokenStack[me.tokenStack.length-1];(le[1]||_u).call(me,void 0,le[0])}for(J.position={start:ri(se.length>0?se[0][1].start:{line:1,column:1,offset:0}),end:ri(se.length>0?se[se.length-2][1].end:{line:1,column:1,offset:0})},he=-1;++he<n.transforms.length;)J=n.transforms[he](J)||J;return J}function r(se,J,me){let ee=J-1,he=-1,le=!1,Ie,Ze,at,oe;for(;++ee<=me;){const Z=se[ee];switch(Z[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{Z[0]==="enter"?he++:he--,oe=void 0;break}case"lineEndingBlank":{Z[0]==="enter"&&(Ie&&!oe&&!he&&!at&&(at=ee),oe=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:oe=void 0}if(!he&&Z[0]==="enter"&&Z[1].type==="listItemPrefix"||he===-1&&Z[0]==="exit"&&(Z[1].type==="listUnordered"||Z[1].type==="listOrdered")){if(Ie){let ue=ee;for(Ze=void 0;ue--;){const Ce=se[ue];if(Ce[1].type==="lineEnding"||Ce[1].type==="lineEndingBlank"){if(Ce[0]==="exit")continue;Ze&&(se[Ze][1].type="lineEndingBlank",le=!0),Ce[1].type="lineEnding",Ze=ue}else if(!(Ce[1].type==="linePrefix"||Ce[1].type==="blockQuotePrefix"||Ce[1].type==="blockQuotePrefixWhitespace"||Ce[1].type==="blockQuoteMarker"||Ce[1].type==="listItemIndent"))break}at&&(!Ze||at<Ze)&&(Ie._spread=!0),Ie.end=Object.assign({},Ze?se[Ze][1].start:Z[1].end),se.splice(Ze||ee,0,["exit",Ie,Z[2]]),ee++,me++}if(Z[1].type==="listItemPrefix"){const ue={type:"listItem",_spread:!1,start:Object.assign({},Z[1].start),end:void 0};Ie=ue,se.splice(ee,0,["enter",ue,Z[2]]),ee++,me++,at=void 0,oe=!0}}}return se[J][1]._spread=le,me}function o(se,J){return me;function me(ee){c.call(this,se(ee),ee),J&&J.call(this,ee)}}function l(){this.stack.push({type:"fragment",children:[]})}function c(se,J,me){this.stack[this.stack.length-1].children.push(se),this.stack.push(se),this.tokenStack.push([J,me||void 0]),se.position={start:ri(J.start),end:void 0}}function u(se){return J;function J(me){se&&se.call(this,me),d.call(this,me)}}function d(se,J){const me=this.stack.pop(),ee=this.tokenStack.pop();if(ee)ee[0].type!==se.type&&(J?J.call(this,se,ee[0]):(ee[1]||_u).call(this,se,ee[0]));else throw new Error("Cannot close `"+se.type+"` ("+$a({start:se.start,end:se.end})+"): it’s not open");me.position.end=ri(se.end)}function m(){return Sc(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function g(se){if(this.data.expectingFirstListItemValue){const J=this.stack[this.stack.length-2];J.start=Number.parseInt(this.sliceSerialize(se),10),this.data.expectingFirstListItemValue=void 0}}function p(){const se=this.resume(),J=this.stack[this.stack.length-1];J.lang=se}function f(){const se=this.resume(),J=this.stack[this.stack.length-1];J.meta=se}function b(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function v(){const se=this.resume(),J=this.stack[this.stack.length-1];J.value=se.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function x(){const se=this.resume(),J=this.stack[this.stack.length-1];J.value=se.replace(/(\r?\n|\r)$/g,"")}function k(se){const J=this.resume(),me=this.stack[this.stack.length-1];me.label=J,me.identifier=Rs(this.sliceSerialize(se)).toLowerCase()}function M(){const se=this.resume(),J=this.stack[this.stack.length-1];J.title=se}function y(){const se=this.resume(),J=this.stack[this.stack.length-1];J.url=se}function R(se){const J=this.stack[this.stack.length-1];if(!J.depth){const me=this.sliceSerialize(se).length;J.depth=me}}function j(){this.data.setextHeadingSlurpLineEnding=!0}function C(se){const J=this.stack[this.stack.length-1];J.depth=this.sliceSerialize(se).codePointAt(0)===61?1:2}function S(){this.data.setextHeadingSlurpLineEnding=void 0}function P(se){const me=this.stack[this.stack.length-1].children;let ee=me[me.length-1];(!ee||ee.type!=="text")&&(ee=ye(),ee.position={start:ri(se.start),end:void 0},me.push(ee)),this.stack.push(ee)}function T(se){const J=this.stack.pop();J.value+=this.sliceSerialize(se),J.position.end=ri(se.end)}function _(se){const J=this.stack[this.stack.length-1];if(this.data.atHardBreak){const me=J.children[J.children.length-1];me.position.end=ri(se.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(J.type)&&(P.call(this,se),T.call(this,se))}function L(){this.data.atHardBreak=!0}function G(){const se=this.resume(),J=this.stack[this.stack.length-1];J.value=se}function $(){const se=this.resume(),J=this.stack[this.stack.length-1];J.value=se}function I(){const se=this.resume(),J=this.stack[this.stack.length-1];J.value=se}function w(){const se=this.stack[this.stack.length-1];if(this.data.inReference){const J=this.data.referenceType||"shortcut";se.type+="Reference",se.referenceType=J,delete se.url,delete se.title}else delete se.identifier,delete se.label;this.data.referenceType=void 0}function q(){const se=this.stack[this.stack.length-1];if(this.data.inReference){const J=this.data.referenceType||"shortcut";se.type+="Reference",se.referenceType=J,delete se.url,delete se.title}else delete se.identifier,delete se.label;this.data.referenceType=void 0}function W(se){const J=this.sliceSerialize(se),me=this.stack[this.stack.length-2];me.label=Z0(J),me.identifier=Rs(J).toLowerCase()}function B(){const se=this.stack[this.stack.length-1],J=this.resume(),me=this.stack[this.stack.length-1];if(this.data.inReference=!0,me.type==="link"){const ee=se.children;me.children=ee}else me.alt=J}function A(){const se=this.resume(),J=this.stack[this.stack.length-1];J.url=se}function z(){const se=this.resume(),J=this.stack[this.stack.length-1];J.title=se}function X(){this.data.inReference=void 0}function E(){this.data.referenceType="collapsed"}function U(se){const J=this.resume(),me=this.stack[this.stack.length-1];me.label=J,me.identifier=Rs(this.sliceSerialize(se)).toLowerCase(),this.data.referenceType="full"}function pe(se){this.data.characterReferenceType=se.type}function ie(se){const J=this.sliceSerialize(se),me=this.data.characterReferenceType;let ee;me?(ee=rp(J,me==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):ee=Cc(J);const he=this.stack[this.stack.length-1];he.value+=ee}function re(se){const J=this.stack.pop();J.position.end=ri(se.end)}function F(se){T.call(this,se);const J=this.stack[this.stack.length-1];J.url=this.sliceSerialize(se)}function ce(se){T.call(this,se);const J=this.stack[this.stack.length-1];J.url="mailto:"+this.sliceSerialize(se)}function ae(){return{type:"blockquote",children:[]}}function Q(){return{type:"code",lang:null,meta:null,value:""}}function de(){return{type:"inlineCode",value:""}}function Te(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function fe(){return{type:"emphasis",children:[]}}function Se(){return{type:"heading",depth:0,children:[]}}function te(){return{type:"break"}}function we(){return{type:"html",value:""}}function Pe(){return{type:"image",title:null,url:"",alt:null}}function We(){return{type:"link",title:null,url:"",children:[]}}function Ke(se){return{type:"list",ordered:se.type==="listOrdered",start:null,spread:se._spread,children:[]}}function Ne(se){return{type:"listItem",spread:se._spread,checked:null,children:[]}}function _e(){return{type:"paragraph",children:[]}}function Oe(){return{type:"strong",children:[]}}function ye(){return{type:"text",value:""}}function De(){return{type:"thematicBreak"}}}function ri(e){return{line:e.line,column:e.column,offset:e.offset}}function bp(e,n){let s=-1;for(;++s<n.length;){const i=n[s];Array.isArray(i)?bp(e,i):sS(e,i)}}function sS(e,n){let s;for(s in n)if(gp.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 _u(e,n){throw e?new Error("Cannot close `"+e.type+"` ("+$a({start:e.start,end:e.end})+"): a different token (`"+n.type+"`, "+$a({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+$a({start:n.start,end:n.end})+") is still open")}function iS(e){const n=this;n.parser=s;function s(i){return tS(i,{...n.data("settings"),...e,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function aS(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 rS(e,n){const s={type:"element",tagName:"br",properties:{},children:[]};return e.patch(n,s),[e.applyData(n,s),{type:"text",value:`
|
|
581
|
-
`}]}function oS(e,n){const s=n.value?n.value+`
|
|
582
|
-
`:"",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 lS(e,n){const s={type:"element",tagName:"del",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function cS(e,n){const s={type:"element",tagName:"em",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function dS(e,n){const s=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=String(n.identifier).toUpperCase(),r=da(i.toLowerCase()),o=e.footnoteOrder.indexOf(i);let l,c=e.footnoteCounts.get(i);c===void 0?(c=0,e.footnoteOrder.push(i),l=e.footnoteOrder.length):l=o+1,c+=1,e.footnoteCounts.set(i,c);const u={type:"element",tagName:"a",properties:{href:"#"+s+"fn-"+r,id:s+"fnref-"+r+(c>1?"-"+c:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(l)}]};e.patch(n,u);const d={type:"element",tagName:"sup",properties:{},children:[u]};return e.patch(n,d),e.applyData(n,d)}function uS(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 mS(e,n){if(e.options.allowDangerousHtml){const s={type:"raw",value:n.value};return e.patch(n,s),e.applyData(n,s)}}function xp(e,n){const s=n.referenceType;let i="]";if(s==="collapsed"?i+="[]":s==="full"&&(i+="["+(n.label||n.identifier)+"]"),n.type==="imageReference")return[{type:"text",value:"!["+n.alt+i}];const r=e.all(n),o=r[0];o&&o.type==="text"?o.value="["+o.value:r.unshift({type:"text",value:"["});const l=r[r.length-1];return l&&l.type==="text"?l.value+=i:r.push({type:"text",value:i}),r}function hS(e,n){const s=String(n.identifier).toUpperCase(),i=e.definitionById.get(s);if(!i)return xp(e,n);const r={src:da(i.url||""),alt:n.alt};i.title!==null&&i.title!==void 0&&(r.title=i.title);const o={type:"element",tagName:"img",properties:r,children:[]};return e.patch(n,o),e.applyData(n,o)}function pS(e,n){const s={src:da(n.url)};n.alt!==null&&n.alt!==void 0&&(s.alt=n.alt),n.title!==null&&n.title!==void 0&&(s.title=n.title);const i={type:"element",tagName:"img",properties:s,children:[]};return e.patch(n,i),e.applyData(n,i)}function fS(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 gS(e,n){const s=String(n.identifier).toUpperCase(),i=e.definitionById.get(s);if(!i)return xp(e,n);const r={href:da(i.url||"")};i.title!==null&&i.title!==void 0&&(r.title=i.title);const o={type:"element",tagName:"a",properties:r,children:e.all(n)};return e.patch(n,o),e.applyData(n,o)}function bS(e,n){const s={href:da(n.url)};n.title!==null&&n.title!==void 0&&(s.title=n.title);const i={type:"element",tagName:"a",properties:s,children:e.all(n)};return e.patch(n,i),e.applyData(n,i)}function xS(e,n,s){const i=e.all(n),r=s?vS(s):vp(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:`
|
|
583
|
-
`}),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:`
|
|
584
|
-
`});const d={type:"element",tagName:"li",properties:o,children:l};return e.patch(n,d),e.applyData(n,d)}function vS(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=vp(s[i])}return n}function vp(e){const n=e.spread;return n??e.children.length>1}function yS(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 kS(e,n){const s={type:"element",tagName:"p",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function jS(e,n){const s={type:"root",children:e.wrap(e.all(n))};return e.patch(n,s),e.applyData(n,s)}function wS(e,n){const s={type:"element",tagName:"strong",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function NS(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=kc(n.children[1]),u=Xh(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 SS(e,n,s){const i=s?s.children:void 0,o=(i?i.indexOf(n):1)===0?"th":"td",l=s&&s.type==="table"?s.align:void 0,c=l?l.length:n.children.length;let u=-1;const d=[];for(;++u<c;){const h=n.children[u],g={},p=l?l[u]:void 0;p&&(g.align=p);let f={type:"element",tagName:o,properties:g,children:[]};h&&(f.children=e.all(h),e.patch(h,f),f=e.applyData(h,f)),d.push(f)}const m={type:"element",tagName:"tr",properties:{},children:e.wrap(d,!0)};return e.patch(n,m),e.applyData(n,m)}function CS(e,n){const s={type:"element",tagName:"td",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}const Au=9,Tu=32;function ES(e){const n=String(e),s=/\r?\n|\r/g;let i=s.exec(n),r=0;const o=[];for(;i;)o.push(Ru(n.slice(r,i.index),r>0,!0),i[0]),r=i.index+i[0].length,i=s.exec(n);return o.push(Ru(n.slice(r),r>0,!1)),o.join("")}function Ru(e,n,s){let i=0,r=e.length;if(n){let o=e.codePointAt(i);for(;o===Au||o===Tu;)i++,o=e.codePointAt(i)}if(s){let o=e.codePointAt(r-1);for(;o===Au||o===Tu;)r--,o=e.codePointAt(r-1)}return r>i?e.slice(i,r):""}function MS(e,n){const s={type:"text",value:ES(String(n.value))};return e.patch(n,s),e.applyData(n,s)}function _S(e,n){const s={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(n,s),e.applyData(n,s)}const AS={blockquote:aS,break:rS,code:oS,delete:lS,emphasis:cS,footnoteReference:dS,heading:uS,html:mS,imageReference:hS,image:pS,inlineCode:fS,linkReference:gS,link:bS,listItem:xS,list:yS,paragraph:kS,root:jS,strong:wS,table:NS,tableCell:CS,tableRow:SS,text:MS,thematicBreak:_S,toml:vr,yaml:vr,definition:vr,footnoteDefinition:vr};function vr(){}const yp=-1,fo=0,La=1,Gr=2,Mc=3,_c=4,Ac=5,Tc=6,kp=7,jp=8,Iu=typeof self=="object"?self:globalThis,TS=(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 fo:case yp:return s(l,r);case La:{const c=s([],r);for(const u of l)c.push(i(u));return c}case Gr:{const c=s({},r);for(const[u,d]of l)c[i(u)]=i(d);return c}case Mc:return s(new Date(l),r);case _c:{const{source:c,flags:u}=l;return s(new RegExp(c,u),r)}case Ac:{const c=s(new Map,r);for(const[u,d]of l)c.set(i(u),i(d));return c}case Tc:{const c=s(new Set,r);for(const u of l)c.add(i(u));return c}case kp:{const{name:c,message:u}=l;return s(new Iu[c](u),r)}case jp: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 Iu[o](l),r)};return i},Pu=e=>TS(new Map,e)(0),Oi="",{toString:RS}={},{keys:IS}=Object,ka=e=>{const n=typeof e;if(n!=="object"||!e)return[fo,n];const s=RS.call(e).slice(8,-1);switch(s){case"Array":return[La,Oi];case"Object":return[Gr,Oi];case"Date":return[Mc,Oi];case"RegExp":return[_c,Oi];case"Map":return[Ac,Oi];case"Set":return[Tc,Oi];case"DataView":return[La,s]}return s.includes("Array")?[La,s]:s.includes("Error")?[kp,s]:[Gr,s]},yr=([e,n])=>e===fo&&(n==="function"||n==="symbol"),PS=(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]=ka(l);switch(c){case fo:{let m=l;switch(u){case"bigint":c=jp,m=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+u);m=null;break;case"undefined":return r([yp],l)}return r([c,m],l)}case La:{if(u){let g=l;return u==="DataView"?g=new Uint8Array(l.buffer):u==="ArrayBuffer"&&(g=new Uint8Array(l)),r([u,[...g]],l)}const m=[],h=r([c,m],l);for(const g of l)m.push(o(g));return h}case Gr:{if(u)switch(u){case"BigInt":return r([u,l.toString()],l);case"Boolean":case"Number":case"String":return r([u,l.valueOf()],l)}if(n&&"toJSON"in l)return o(l.toJSON());const m=[],h=r([c,m],l);for(const g of IS(l))(e||!yr(ka(l[g])))&&m.push([o(g),o(l[g])]);return h}case Mc:return r([c,l.toISOString()],l);case _c:{const{source:m,flags:h}=l;return r([c,{source:m,flags:h}],l)}case Ac:{const m=[],h=r([c,m],l);for(const[g,p]of l)(e||!(yr(ka(g))||yr(ka(p))))&&m.push([o(g),o(p)]);return h}case Tc:{const m=[],h=r([c,m],l);for(const g of l)(e||!yr(ka(g)))&&m.push(o(g));return h}}const{message:d}=l;return r([c,{name:u,message:d}],l)};return o},$u=(e,{json:n,lossy:s}={})=>{const i=[];return PS(!(n||s),!!n,new Map,i)(e),i},Kr=typeof structuredClone=="function"?(e,n)=>n&&("json"in n||"lossy"in n)?Pu($u(e,n)):structuredClone(e):(e,n)=>Pu($u(e,n));function $S(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 DS(e,n){return"Back to reference "+(e+1)+(n>1?"-"+n:"")}function LS(e){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=e.options.footnoteBackContent||$S,i=e.options.footnoteBackLabel||DS,r=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",l=e.options.footnoteLabelProperties||{className:["sr-only"]},c=[];let u=-1;for(;++u<e.footnoteOrder.length;){const d=e.footnoteById.get(e.footnoteOrder[u]);if(!d)continue;const m=e.all(d),h=String(d.identifier).toUpperCase(),g=da(h.toLowerCase());let p=0;const f=[],b=e.footnoteCounts.get(h);for(;b!==void 0&&++p<=b;){f.length>0&&f.push({type:"text",value:" "});let k=typeof s=="string"?s:s(u,p);typeof k=="string"&&(k={type:"text",value:k}),f.push({type:"element",tagName:"a",properties:{href:"#"+n+"fnref-"+g+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof i=="string"?i:i(u,p),className:["data-footnote-backref"]},children:Array.isArray(k)?k:[k]})}const v=m[m.length-1];if(v&&v.type==="element"&&v.tagName==="p"){const k=v.children[v.children.length-1];k&&k.type==="text"?k.value+=" ":v.children.push({type:"text",value:" "}),v.children.push(...f)}else m.push(...f);const x={type:"element",tagName:"li",properties:{id:n+"fn-"+g},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:{...Kr(l),id:"footnote-label"},children:[{type:"text",value:r}]},{type:"text",value:`
|
|
585
|
-
`},{type:"element",tagName:"ol",properties:{},children:e.wrap(c,!0)},{type:"text",value:`
|
|
586
|
-
`}]}}const go=(function(e){if(e==null)return US;if(typeof e=="function")return bo(e);if(typeof e=="object")return Array.isArray(e)?zS(e):FS(e);if(typeof e=="string")return OS(e);throw new Error("Expected function, string, or object as test")});function zS(e){const n=[];let s=-1;for(;++s<e.length;)n[s]=go(e[s]);return bo(i);function i(...r){let o=-1;for(;++o<n.length;)if(n[o].apply(this,r))return!0;return!1}}function FS(e){const n=e;return bo(s);function s(i){const r=i;let o;for(o in e)if(r[o]!==n[o])return!1;return!0}}function OS(e){return bo(n);function n(s){return s&&s.type===e}}function bo(e){return n;function n(s,i,r){return!!(BS(s)&&e.call(this,s,typeof i=="number"?i:void 0,r||void 0))}}function US(){return!0}function BS(e){return e!==null&&typeof e=="object"&&"type"in e}const wp=[],HS=!0,Jl=!1,qS="skip";function Np(e,n,s,i){let r;typeof n=="function"&&typeof s!="function"?(i=s,s=n):r=n;const o=go(r),l=i?-1:1;c(e,void 0,[])();function c(u,d,m){const h=u&&typeof u=="object"?u:{};if(typeof h.type=="string"){const p=typeof h.tagName=="string"?h.tagName:typeof h.name=="string"?h.name:void 0;Object.defineProperty(g,"name",{value:"node ("+(u.type+(p?"<"+p+">":""))+")"})}return g;function g(){let p=wp,f,b,v;if((!n||o(u,d,m[m.length-1]||void 0))&&(p=VS(s(u,m)),p[0]===Jl))return p;if("children"in u&&u.children){const x=u;if(x.children&&p[0]!==qS)for(b=(i?x.children.length:-1)+l,v=m.concat(x);b>-1&&b<x.children.length;){const k=x.children[b];if(f=c(k,b,v)(),f[0]===Jl)return f;b=typeof f[1]=="number"?f[1]:b+l}}return p}}}function VS(e){return Array.isArray(e)?e:typeof e=="number"?[HS,e]:e==null?wp:[e]}function Rc(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),Np(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 Yl={}.hasOwnProperty,WS={};function GS(e,n){const s=n||WS,i=new Map,r=new Map,o=new Map,l={...AS,...s.handlers},c={all:d,applyData:JS,definitionById:i,footnoteById:r,footnoteCounts:o,footnoteOrder:[],handlers:l,one:u,options:s,patch:KS,wrap:QS};return Rc(e,function(m){if(m.type==="definition"||m.type==="footnoteDefinition"){const h=m.type==="definition"?i:r,g=String(m.identifier).toUpperCase();h.has(g)||h.set(g,m)}}),c;function u(m,h){const g=m.type,p=c.handlers[g];if(Yl.call(c.handlers,g)&&p)return p(c,m,h);if(c.options.passThrough&&c.options.passThrough.includes(g)){if("children"in m){const{children:b,...v}=m,x=Kr(v);return x.children=c.all(m),x}return Kr(m)}return(c.options.unknownHandler||YS)(c,m,h)}function d(m){const h=[];if("children"in m){const g=m.children;let p=-1;for(;++p<g.length;){const f=c.one(g[p],m);if(f){if(p&&g[p-1].type==="break"&&(!Array.isArray(f)&&f.type==="text"&&(f.value=Du(f.value)),!Array.isArray(f)&&f.type==="element")){const b=f.children[0];b&&b.type==="text"&&(b.value=Du(b.value))}Array.isArray(f)?h.push(...f):h.push(f)}}}return h}}function KS(e,n){e.position&&(n.position=DN(e))}function JS(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,Kr(o)),"children"in s&&s.children&&r!==null&&r!==void 0&&(s.children=r)}return s}function YS(e,n){const s=n.data||{},i="value"in n&&!(Yl.call(s,"hProperties")||Yl.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 QS(e,n){const s=[];let i=-1;for(n&&s.push({type:"text",value:`
|
|
587
|
-
`});++i<e.length;)i&&s.push({type:"text",value:`
|
|
588
|
-
`}),s.push(e[i]);return n&&e.length>0&&s.push({type:"text",value:`
|
|
589
|
-
`}),s}function Du(e){let n=0,s=e.charCodeAt(n);for(;s===9||s===32;)n++,s=e.charCodeAt(n);return e.slice(n)}function Lu(e,n){const s=GS(e,n),i=s.one(e,void 0),r=LS(s),o=Array.isArray(i)?{type:"root",children:i}:i||{type:"root",children:[]};return r&&o.children.push({type:"text",value:`
|
|
590
|
-
`},r),o}function XS(e,n){return e&&"run"in e?async function(s,i){const r=Lu(s,{file:i,...n});await e.run(r,i)}:function(s,i){return Lu(s,{file:i,...e||n})}}function zu(e){if(e)throw e}var Yo,Fu;function ZS(){if(Fu)return Yo;Fu=1;var e=Object.prototype.hasOwnProperty,n=Object.prototype.toString,s=Object.defineProperty,i=Object.getOwnPropertyDescriptor,r=function(d){return typeof Array.isArray=="function"?Array.isArray(d):n.call(d)==="[object Array]"},o=function(d){if(!d||n.call(d)!=="[object Object]")return!1;var m=e.call(d,"constructor"),h=d.constructor&&d.constructor.prototype&&e.call(d.constructor.prototype,"isPrototypeOf");if(d.constructor&&!m&&!h)return!1;var g;for(g in d);return typeof g>"u"||e.call(d,g)},l=function(d,m){s&&m.name==="__proto__"?s(d,m.name,{enumerable:!0,configurable:!0,value:m.newValue,writable:!0}):d[m.name]=m.newValue},c=function(d,m){if(m==="__proto__")if(e.call(d,m)){if(i)return i(d,m).value}else return;return d[m]};return Yo=function u(){var d,m,h,g,p,f,b=arguments[0],v=1,x=arguments.length,k=!1;for(typeof b=="boolean"&&(k=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),g=c(d,m),b!==g&&(k&&g&&(o(g)||(p=r(g)))?(p?(p=!1,f=h&&r(h)?h:[]):f=h&&o(h)?h:{},l(b,{name:m,newValue:u(k,f,g)})):typeof g<"u"&&l(b,{name:m,newValue:g}));return b},Yo}var eC=ZS();const Qo=Km(eC);function Ql(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 tC(){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?nC(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 nC(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 Ls={basename:sC,dirname:iC,extname:aC,join:rC,sep:"/"};function sC(e,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');ir(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 iC(e){if(ir(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 aC(e){ir(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 rC(...e){let n=-1,s;for(;++n<e.length;)ir(e[n]),e[n]&&(s=s===void 0?e[n]:s+"/"+e[n]);return s===void 0?".":oC(s)}function oC(e){ir(e);const n=e.codePointAt(0)===47;let s=lC(e,!n);return s.length===0&&!n&&(s="."),s.length>0&&e.codePointAt(e.length-1)===47&&(s+="/"),n?"/"+s:s}function lC(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 ir(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const cC={cwd:dC};function dC(){return"/"}function Xl(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function uC(e){if(typeof e=="string")e=new URL(e);else if(!Xl(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 mC(e)}function mC(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 Xo=["history","path","basename","stem","extname","dirname"];class Sp{constructor(n){let s;n?Xl(n)?s={path:n}:typeof n=="string"||hC(n)?s={value:n}:s=n:s={},this.cwd="cwd"in s?"":cC.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let i=-1;for(;++i<Xo.length;){const o=Xo[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)Xo.includes(r)||(this[r]=s[r])}get basename(){return typeof this.path=="string"?Ls.basename(this.path):void 0}set basename(n){el(n,"basename"),Zo(n,"basename"),this.path=Ls.join(this.dirname||"",n)}get dirname(){return typeof this.path=="string"?Ls.dirname(this.path):void 0}set dirname(n){Ou(this.basename,"dirname"),this.path=Ls.join(n||"",this.basename)}get extname(){return typeof this.path=="string"?Ls.extname(this.path):void 0}set extname(n){if(Zo(n,"extname"),Ou(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=Ls.join(this.dirname,this.stem+(n||""))}get path(){return this.history[this.history.length-1]}set path(n){Xl(n)&&(n=uC(n)),el(n,"path"),this.path!==n&&this.history.push(n)}get stem(){return typeof this.path=="string"?Ls.basename(this.path,this.extname):void 0}set stem(n){el(n,"stem"),Zo(n,"stem"),this.path=Ls.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 Ln(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 Zo(e,n){if(e&&e.includes(Ls.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+Ls.sep+"`")}function el(e,n){if(!e)throw new Error("`"+n+"` cannot be empty")}function Ou(e,n){if(!e)throw new Error("Setting `"+n+"` requires `path` to be set too")}function hC(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const pC=(function(e){const i=this.constructor.prototype,r=i[e],o=function(){return r.apply(o,arguments)};return Object.setPrototypeOf(o,i),o}),fC={}.hasOwnProperty;class Ic extends pC{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=tC()}copy(){const n=new Ic;let s=-1;for(;++s<this.attachers.length;){const i=this.attachers[s];n.use(...i)}return n.data(Qo(!0,{},this.namespace)),n}data(n,s){return typeof n=="string"?arguments.length===2?(sl("data",this.frozen),this.namespace[n]=s,this):fC.call(this.namespace,n)&&this.namespace[n]||void 0:n?(sl("data",this.frozen),this.namespace=n,this):this.namespace}freeze(){if(this.frozen)return this;const n=this;for(;++this.freezeIndex<this.attachers.length;){const[s,...i]=this.attachers[this.freezeIndex];if(i[0]===!1)continue;i[0]===!0&&(i[0]=void 0);const r=s.call(n,...i);typeof r=="function"&&this.transformers.use(r)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(n){this.freeze();const s=kr(n),i=this.parser||this.Parser;return tl("parse",i),i(String(s),s)}process(n,s){const i=this;return this.freeze(),tl("process",this.parser||this.Parser),nl("process",this.compiler||this.Compiler),s?r(void 0,s):new Promise(r);function r(o,l){const c=kr(n),u=i.parse(c);i.run(u,c,function(m,h,g){if(m||!h||!g)return d(m);const p=h,f=i.stringify(p,g);xC(f)?g.value=f:g.result=f,d(m,g)});function d(m,h){m||!h?l(m):o?o(h):s(void 0,h)}}}processSync(n){let s=!1,i;return this.freeze(),tl("processSync",this.parser||this.Parser),nl("processSync",this.compiler||this.Compiler),this.process(n,r),Bu("processSync","process",s),i;function r(o,l){s=!0,zu(o),i=l}}run(n,s,i){Uu(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=kr(s);r.run(n,u,d);function d(m,h,g){const p=h||n;m?c(m):l?l(p):i(void 0,p,g)}}}runSync(n,s){let i=!1,r;return this.run(n,s,o),Bu("runSync","run",i),r;function o(l,c){zu(l),r=c,i=!0}}stringify(n,s){this.freeze();const i=kr(s),r=this.compiler||this.Compiler;return nl("stringify",r),Uu(n),r(n,i)}use(n,...s){const i=this.attachers,r=this.namespace;if(sl("use",this.frozen),n!=null)if(typeof n=="function")u(n,s);else if(typeof n=="object")Array.isArray(n)?c(n):l(n);else throw new TypeError("Expected usable value, not `"+n+"`");return this;function o(d){if(typeof d=="function")u(d,[]);else if(typeof d=="object")if(Array.isArray(d)){const[m,...h]=d;u(m,h)}else l(d);else throw new TypeError("Expected usable value, not `"+d+"`")}function l(d){if(!("plugins"in d)&&!("settings"in d))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");c(d.plugins),d.settings&&(r.settings=Qo(!0,r.settings,d.settings))}function c(d){let m=-1;if(d!=null)if(Array.isArray(d))for(;++m<d.length;){const h=d[m];o(h)}else throw new TypeError("Expected a list of plugins, not `"+d+"`")}function u(d,m){let h=-1,g=-1;for(;++h<i.length;)if(i[h][0]===d){g=h;break}if(g===-1)i.push([d,...m]);else if(m.length>0){let[p,...f]=m;const b=i[g][1];Ql(b)&&Ql(p)&&(p=Qo(!0,b,p)),i[g]=[d,p,...f]}}}}const gC=new Ic().freeze();function tl(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function nl(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function sl(e,n){if(n)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Uu(e){if(!Ql(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Bu(e,n,s){if(!s)throw new Error("`"+e+"` finished async. Use `"+n+"` instead")}function kr(e){return bC(e)?e:new Sp(e)}function bC(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function xC(e){return typeof e=="string"||vC(e)}function vC(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const yC="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Hu=[],qu={allowDangerousHtml:!0},kC=/^(https?|ircs?|mailto|xmpp)$/i,jC=[{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 Qs(e){const n=wC(e),s=NC(e);return SC(n.runSync(n.parse(s),s),e)}function wC(e){const n=e.rehypePlugins||Hu,s=e.remarkPlugins||Hu,i=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...qu}:qu;return gC().use(iS).use(s).use(XS,i).use(n)}function NC(e){const n=e.children||"",s=new Sp;return typeof n=="string"&&(s.value=n),s}function SC(e,n){const s=n.allowedElements,i=n.allowElement,r=n.components,o=n.disallowedElements,l=n.skipHtml,c=n.unwrapDisallowed,u=n.urlTransform||CC;for(const m of jC)Object.hasOwn(n,m.from)&&(""+m.from+(m.to?"use `"+m.to+"` instead":"remove it")+yC+m.id,void 0);return Rc(e,d),UN(e,{Fragment:t.Fragment,components:r,ignoreInvalidStyle:!0,jsx:t.jsx,jsxs:t.jsxs,passKeys:!0,passNode:!0});function d(m,h,g){if(m.type==="raw"&&g&&typeof h=="number")return l?g.children.splice(h,1):g.children[h]={type:"text",value:m.value},h;if(m.type==="element"){let p;for(p in Go)if(Object.hasOwn(Go,p)&&Object.hasOwn(m.properties,p)){const f=m.properties[p],b=Go[p];(b===null||b.includes(m.tagName))&&(m.properties[p]=u(String(f||""),p,m))}}if(m.type==="element"){let p=s?!s.includes(m.tagName):o?o.includes(m.tagName):!1;if(!p&&i&&typeof h=="number"&&(p=!i(m,h,g)),p&&g&&typeof h=="number")return c&&m.children?g.children.splice(h,1,...m.children):g.children.splice(h,1),h}}}function CC(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||kC.test(e.slice(0,n))?e:""}function Vu(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 EC(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function MC(e,n,s){const r=go((s||{}).ignore||[]),o=_C(n);let l=-1;for(;++l<o.length;)Np(e,"text",c);function c(d,m){let h=-1,g;for(;++h<m.length;){const p=m[h],f=g?g.children:void 0;if(r(p,f?f.indexOf(p):void 0,g))return;g=p}if(g)return u(d,m)}function u(d,m){const h=m[m.length-1],g=o[l][0],p=o[l][1];let f=0;const v=h.children.indexOf(d);let x=!1,k=[];g.lastIndex=0;let M=g.exec(d.value);for(;M;){const y=M.index,R={index:M.index,input:M.input,stack:[...m,d]};let j=p(...M,R);if(typeof j=="string"&&(j=j.length>0?{type:"text",value:j}:void 0),j===!1?g.lastIndex=y+1:(f!==y&&k.push({type:"text",value:d.value.slice(f,y)}),Array.isArray(j)?k.push(...j):j&&k.push(j),f=y+M[0].length,x=!0),!g.global)break;M=g.exec(d.value)}return x?(f<d.value.length&&k.push({type:"text",value:d.value.slice(f)}),h.children.splice(v,1,...k)):k=[d],v+k.length}}function _C(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([AC(r[0]),TC(r[1])])}return n}function AC(e){return typeof e=="string"?new RegExp(EC(e),"g"):e}function TC(e){return typeof e=="function"?e:function(){return e}}const il="phrasing",al=["autolink","link","image","label"];function RC(){return{transforms:[FC],enter:{literalAutolink:PC,literalAutolinkEmail:rl,literalAutolinkHttp:rl,literalAutolinkWww:rl},exit:{literalAutolink:zC,literalAutolinkEmail:LC,literalAutolinkHttp:$C,literalAutolinkWww:DC}}}function IC(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:il,notInConstruct:al},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:il,notInConstruct:al},{character:":",before:"[ps]",after:"\\/",inConstruct:il,notInConstruct:al}]}}function PC(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function rl(e){this.config.enter.autolinkProtocol.call(this,e)}function $C(e){this.config.exit.autolinkProtocol.call(this,e)}function DC(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 LC(e){this.config.exit.autolinkEmail.call(this,e)}function zC(e){this.exit(e)}function FC(e){MC(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,OC],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,UC]],{ignore:["link","linkReference"]})}function OC(e,n,s,i,r){let o="";if(!Cp(r)||(/^w/i.test(n)&&(s=n+s,n="",o="http://"),!BC(s)))return!1;const l=HC(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 UC(e,n,s,i){return!Cp(i,!0)||/[-\d_]$/.test(s)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+s,children:[{type:"text",value:n+"@"+s}]}}function BC(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 HC(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=Vu(e,"(");let o=Vu(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 Cp(e,n){const s=e.input.charCodeAt(e.index-1);return(e.index===0||Ei(s)||ho(s))&&(!n||s!==47)}Ep.peek=XC;function qC(){this.buffer()}function VC(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function WC(){this.buffer()}function GC(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function KC(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=Rs(this.sliceSerialize(e)).toLowerCase(),s.label=n}function JC(e){this.exit(e)}function YC(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=Rs(this.sliceSerialize(e)).toLowerCase(),s.label=n}function QC(e){this.exit(e)}function XC(){return"["}function Ep(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 ZC(){return{enter:{gfmFootnoteCallString:qC,gfmFootnoteCall:VC,gfmFootnoteDefinitionLabelString:WC,gfmFootnoteDefinition:GC},exit:{gfmFootnoteCallString:KC,gfmFootnoteCall:JC,gfmFootnoteDefinitionLabelString:YC,gfmFootnoteDefinition:QC}}}function e2(e){let n=!1;return e&&e.firstLineBlank&&(n=!0),{handlers:{footnoteDefinition:s,footnoteReference:Ep},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?`
|
|
591
|
-
`:" ")+o.indentLines(o.containerFlow(i,c.current()),n?Mp:t2))),d(),u}}function t2(e,n,s){return n===0?e:Mp(e,n,s)}function Mp(e,n,s){return(s?"":" ")+e}const n2=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];_p.peek=o2;function s2(){return{canContainEols:["delete"],enter:{strikethrough:a2},exit:{strikethrough:r2}}}function i2(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:n2}],handlers:{delete:_p}}}function a2(e){this.enter({type:"delete",children:[]},e)}function r2(e){this.exit(e)}function _p(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 o2(){return"~"}function l2(e){return e.length}function c2(e,n){const s=n||{},i=(s.align||[]).concat(),r=s.stringLength||l2,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 k=d2(e[m][x]);if(s.alignDelimiters!==!1){const M=r(k);v[x]=M,(u[x]===void 0||M>u[x])&&(u[x]=M)}b.push(k)}l[m]=b,c[m]=v}let h=-1;if(typeof i=="object"&&"length"in i)for(;++h<d;)o[h]=Wu(i[h]);else{const b=Wu(i);for(;++h<d;)o[h]=b}h=-1;const g=[],p=[];for(;++h<d;){const b=o[h];let v="",x="";b===99?(v=":",x=":"):b===108?v=":":b===114&&(x=":");let k=s.alignDelimiters===!1?1:Math.max(1,u[h]-v.length-x.length);const M=v+"-".repeat(k)+x;s.alignDelimiters!==!1&&(k=v.length+k+x.length,k>u[h]&&(u[h]=k),p[h]=k),g[h]=M}l.splice(1,0,g),c.splice(1,0,p),m=-1;const f=[];for(;++m<l.length;){const b=l[m],v=c[m];h=-1;const x=[];for(;++h<d;){const k=b[h]||"";let M="",y="";if(s.alignDelimiters!==!1){const R=u[h]-(v[h]||0),j=o[h];j===114?M=" ".repeat(R):j===99?R%2?(M=" ".repeat(R/2+.5),y=" ".repeat(R/2-.5)):(M=" ".repeat(R/2),y=M):y=" ".repeat(R)}s.delimiterStart!==!1&&!h&&x.push("|"),s.padding!==!1&&!(s.alignDelimiters===!1&&k==="")&&(s.delimiterStart!==!1||h)&&x.push(" "),s.alignDelimiters!==!1&&x.push(M),x.push(k),s.alignDelimiters!==!1&&x.push(y),s.padding!==!1&&x.push(" "),(s.delimiterEnd!==!1||h!==d-1)&&x.push("|")}f.push(s.delimiterEnd===!1?x.join("").replace(/ +$/,""):x.join(""))}return f.join(`
|
|
592
|
-
`)}function d2(e){return e==null?"":String(e)}function Wu(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 u2(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()),m2);return r(),l}function m2(e,n,s){return">"+(s?"":" ")+e}function h2(e,n){return Gu(e,n.inConstruct,!0)&&!Gu(e,n.notInConstruct,!1)}function Gu(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 Ku(e,n,s,i){let r=-1;for(;++r<s.unsafe.length;)if(s.unsafe[r].character===`
|
|
593
|
-
`&&h2(s.stack,s.unsafe[r]))return/[ \t]/.test(i.before)?"":" ";return`\\
|
|
594
|
-
`}function p2(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 f2(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 g2(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 b2(e,n,s,i){const r=g2(s),o=e.value||"",l=r==="`"?"GraveAccent":"Tilde";if(f2(e,s)){const h=s.enter("codeIndented"),g=s.indentLines(o,x2);return h(),g}const c=s.createTracker(i),u=r.repeat(Math.max(p2(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:`
|
|
595
|
-
`,encode:["`"],...c.current()})),h()}return m+=c.move(`
|
|
596
|
-
`),o&&(m+=c.move(o+`
|
|
597
|
-
`)),m+=c.move(u),d(),m}function x2(e,n,s){return(s?"":" ")+e}function Pc(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 v2(e,n,s,i){const r=Pc(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?" ":`
|
|
598
|
-
`,...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 y2(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 Va(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Jr(e,n,s){const i=Qi(e),r=Qi(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}}Ap.peek=k2;function Ap(e,n,s,i){const r=y2(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=Jr(i.before.charCodeAt(i.before.length-1),d,r);m.inside&&(u=Va(d)+u.slice(1));const h=u.charCodeAt(u.length-1),g=Jr(i.after.charCodeAt(0),h,r);g.inside&&(u=u.slice(0,-1)+Va(h));const p=l.move(r);return o(),s.attentionEncodeSurroundingInfo={after:g.outside,before:m.outside},c+u+p}function k2(e,n,s){return s.options.emphasis||"*"}function j2(e,n){let s=!1;return Rc(e,function(i){if("value"in i&&/\r?\n|\r/.test(i.value)||i.type==="break")return s=!0,Jl}),!!((!e.depth||e.depth<3)&&Sc(e)&&(n.options.setext||s))}function w2(e,n,s,i){const r=Math.max(Math.min(6,e.depth||1),1),o=s.createTracker(i);if(j2(e,s)){const m=s.enter("headingSetext"),h=s.enter("phrasing"),g=s.containerPhrasing(e,{...o.current(),before:`
|
|
599
|
-
`,after:`
|
|
600
|
-
`});return h(),m(),g+`
|
|
601
|
-
`+(r===1?"=":"-").repeat(g.length-(Math.max(g.lastIndexOf("\r"),g.lastIndexOf(`
|
|
602
|
-
`))+1))}const l="#".repeat(r),c=s.enter("headingAtx"),u=s.enter("phrasing");o.move(l+" ");let d=s.containerPhrasing(e,{before:"# ",after:`
|
|
603
|
-
`,...o.current()});return/^[\t ]/.test(d)&&(d=Va(d.charCodeAt(0))+d.slice(1)),d=d?l+" "+d:l,s.options.closeAtx&&(d+=" "+l),u(),c(),d}Tp.peek=N2;function Tp(e){return e.value||""}function N2(){return"<"}Rp.peek=S2;function Rp(e,n,s,i){const r=Pc(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 S2(){return"!"}Ip.peek=C2;function Ip(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 C2(){return"!"}Pp.peek=E2;function Pp(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 E2(){return"`"}function $p(e,n){const s=Sc(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))}Dp.peek=M2;function Dp(e,n,s,i){const r=Pc(s),o=r==='"'?"Quote":"Apostrophe",l=s.createTracker(i);let c,u;if($p(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 M2(e,n,s){return $p(e,s)?"<":"["}Lp.peek=_2;function Lp(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 _2(){return"["}function $c(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 A2(e){const n=$c(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 T2(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 zp(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 R2(e,n,s,i){const r=s.enter("list"),o=s.bulletCurrent;let l=e.ordered?T2(s):$c(s);const c=e.ordered?l==="."?")":".":A2(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),zp(s)===l&&m){let h=-1;for(;++h<e.children.length;){const g=e.children[h];if(g&&g.type==="listItem"&&g.children&&g.children[0]&&g.children[0].type==="thematicBreak"){u=!0;break}}}}u&&(l=c),s.bulletCurrent=l;const d=s.containerFlow(e,i);return s.bulletLastUsed=l,s.bulletCurrent=o,r(),d}function I2(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 P2(e,n,s,i){const r=I2(s);let o=s.bulletCurrent||$c(s);n&&n.type==="list"&&n.ordered&&(o=(typeof n.start=="number"&&n.start>-1?n.start:1)+(s.options.incrementListMarker===!1?0:n.children.indexOf(e))+o);let l=o.length+1;(r==="tab"||r==="mixed"&&(n&&n.type==="list"&&n.spread||e.spread))&&(l=Math.ceil(l/4)*4);const c=s.createTracker(i);c.move(o+" ".repeat(l-o.length)),c.shift(l);const u=s.enter("listItem"),d=s.indentLines(s.containerFlow(e,c.current()),m);return u(),d;function m(h,g,p){return g?(p?"":" ".repeat(l))+h:(p?o:o+" ".repeat(l-o.length))+h}}function $2(e,n,s,i){const r=s.enter("paragraph"),o=s.enter("phrasing"),l=s.containerPhrasing(e,i);return o(),r(),l}const D2=go(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function L2(e,n,s,i){return(e.children.some(function(l){return D2(l)})?s.containerPhrasing:s.containerFlow).call(s,e,i)}function z2(e){const n=e.options.strong||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize strong with `"+n+"` for `options.strong`, expected `*`, or `_`");return n}Fp.peek=F2;function Fp(e,n,s,i){const r=z2(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=Jr(i.before.charCodeAt(i.before.length-1),d,r);m.inside&&(u=Va(d)+u.slice(1));const h=u.charCodeAt(u.length-1),g=Jr(i.after.charCodeAt(0),h,r);g.inside&&(u=u.slice(0,-1)+Va(h));const p=l.move(r+r);return o(),s.attentionEncodeSurroundingInfo={after:g.outside,before:m.outside},c+u+p}function F2(e,n,s){return s.options.strong||"*"}function O2(e,n,s,i){return s.safe(e.value,i)}function U2(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 B2(e,n,s){const i=(zp(s)+(s.options.ruleSpaces?" ":"")).repeat(U2(s));return s.options.ruleSpaces?i.slice(0,-1):i}const Op={blockquote:u2,break:Ku,code:b2,definition:v2,emphasis:Ap,hardBreak:Ku,heading:w2,html:Tp,image:Rp,imageReference:Ip,inlineCode:Pp,link:Dp,linkReference:Lp,list:R2,listItem:P2,paragraph:$2,root:L2,strong:Fp,text:O2,thematicBreak:B2};function H2(){return{enter:{table:q2,tableData:Ju,tableHeader:Ju,tableRow:W2},exit:{codeText:G2,table:V2,tableData:ol,tableHeader:ol,tableRow:ol}}}function q2(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 V2(e){this.exit(e),this.data.inTable=void 0}function W2(e){this.enter({type:"tableRow",children:[]},e)}function ol(e){this.exit(e)}function Ju(e){this.enter({type:"tableCell",children:[]},e)}function G2(e){let n=this.resume();this.data.inTable&&(n=n.replace(/\\([\\|])/g,K2));const s=this.stack[this.stack.length-1];s.type,s.value=n,this.exit(e)}function K2(e,n){return n==="|"?n:e}function J2(e){const n=e||{},s=n.tableCellPadding,i=n.tablePipeAlign,r=n.stringLength,o=s?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
|
|
604
|
-
`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:g,table:l,tableCell:u,tableRow:c}};function l(p,f,b,v){return d(m(p,b,v),p.align)}function c(p,f,b,v){const x=h(p,b,v),k=d([x]);return k.slice(0,k.indexOf(`
|
|
605
|
-
`))}function u(p,f,b,v){const x=b.enter("tableCell"),k=b.enter("phrasing"),M=b.containerPhrasing(p,{...v,before:o,after:o});return k(),x(),M}function d(p,f){return c2(p,{align:f,alignDelimiters:i,padding:s,stringLength:r})}function m(p,f,b){const v=p.children;let x=-1;const k=[],M=f.enter("table");for(;++x<v.length;)k[x]=h(v[x],f,b);return M(),k}function h(p,f,b){const v=p.children;let x=-1;const k=[],M=f.enter("tableRow");for(;++x<v.length;)k[x]=u(v[x],p,f,b);return M(),k}function g(p,f,b){let v=Op.inlineCode(p,f,b);return b.stack.includes("tableCell")&&(v=v.replace(/\|/g,"\\$&")),v}}function Y2(){return{exit:{taskListCheckValueChecked:Yu,taskListCheckValueUnchecked:Yu,paragraph:X2}}}function Q2(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:Z2}}}function Yu(e){const n=this.stack[this.stack.length-2];n.type,n.checked=e.type==="taskListCheckValueChecked"}function X2(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 Z2(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=Op.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 eE(){return[RC(),ZC(),s2(),H2(),Y2()]}function tE(e){return{extensions:[IC(),e2(e),i2(),J2(e),Q2()]}}const nE={tokenize:lE,partial:!0},Up={tokenize:cE,partial:!0},Bp={tokenize:dE,partial:!0},Hp={tokenize:uE,partial:!0},sE={tokenize:mE,partial:!0},qp={name:"wwwAutolink",tokenize:rE,previous:Wp},Vp={name:"protocolAutolink",tokenize:oE,previous:Gp},Zs={name:"emailAutolink",tokenize:aE,previous:Kp},Vs={};function iE(){return{text:Vs}}let bi=48;for(;bi<123;)Vs[bi]=Zs,bi++,bi===58?bi=65:bi===91&&(bi=97);Vs[43]=Zs;Vs[45]=Zs;Vs[46]=Zs;Vs[95]=Zs;Vs[72]=[Zs,Vp];Vs[104]=[Zs,Vp];Vs[87]=[Zs,qp];Vs[119]=[Zs,qp];function aE(e,n,s){const i=this;let r,o;return l;function l(h){return!Zl(h)||!Kp.call(i,i.previous)||Dc(i.events)?s(h):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(h))}function c(h){return Zl(h)?(e.consume(h),c):h===64?(e.consume(h),u):s(h)}function u(h){return h===46?e.check(sE,m,d)(h):h===45||h===95||$n(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&&qn(i.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),n(h)):s(h)}}function rE(e,n,s){const i=this;return r;function r(l){return l!==87&&l!==119||!Wp.call(i,i.previous)||Dc(i.events)?s(l):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(nE,e.attempt(Up,e.attempt(Bp,o),s),s)(l))}function o(l){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),n(l)}}function oE(e,n,s){const i=this;let r="",o=!1;return l;function l(h){return(h===72||h===104)&&Gp.call(i,i.previous)&&!Dc(i.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),r+=String.fromCodePoint(h),e.consume(h),c):s(h)}function c(h){if(qn(h)&&r.length<5)return r+=String.fromCodePoint(h),e.consume(h),c;if(h===58){const g=r.toLowerCase();if(g==="http"||g==="https")return e.consume(h),u}return s(h)}function u(h){return h===47?(e.consume(h),o?d:(o=!0,u)):s(h)}function d(h){return h===null||Wr(h)||Wt(h)||Ei(h)||ho(h)?s(h):e.attempt(Up,e.attempt(Bp,m),s)(h)}function m(h){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),n(h)}}function lE(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 cE(e,n,s){let i,r,o;return l;function l(d){return d===46||d===95?e.check(Hp,u,c)(d):d===null||Wt(d)||Ei(d)||d!==45&&ho(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 dE(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(Hp,n,o)(l):l===null||Wt(l)||Ei(l)?n(l):(e.consume(l),r)}function o(l){return l===41&&i++,e.consume(l),r}}function uE(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||Wt(c)||Ei(c)?n(c):s(c)}function r(c){return c===null||c===40||c===91||Wt(c)||Ei(c)?n(c):i(c)}function o(c){return qn(c)?l(c):s(c)}function l(c){return c===59?(e.consume(c),i):qn(c)?(e.consume(c),l):s(c)}}function mE(e,n,s){return i;function i(o){return e.consume(o),r}function r(o){return $n(o)?s(o):n(o)}}function Wp(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||Wt(e)}function Gp(e){return!qn(e)}function Kp(e){return!(e===47||Zl(e))}function Zl(e){return e===43||e===45||e===46||e===95||$n(e)}function Dc(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 hE={tokenize:kE,partial:!0};function pE(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:xE,continuation:{tokenize:vE},exit:yE}},text:{91:{name:"gfmFootnoteCall",tokenize:bE},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:fE,resolveTo:gE}}}}function fE(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=Rs(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 gE(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 bE(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||Wt(h))return s(h);if(h===93){e.exit("chunkString");const g=e.exit("gfmFootnoteCallString");return r.includes(Rs(i.sliceSerialize(g)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),n):s(h)}return Wt(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 xE(e,n,s){const i=this,r=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);let o,l=0,c;return u;function u(f){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionLabelMarker"),d}function d(f){return f===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",m):s(f)}function m(f){if(l>999||f===93&&!c||f===null||f===91||Wt(f))return s(f);if(f===93){e.exit("chunkString");const b=e.exit("gfmFootnoteDefinitionLabelString");return o=Rs(i.sliceSerialize(b)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),g}return Wt(f)||(c=!0),l++,e.consume(f),f===92?h:m}function h(f){return f===91||f===92||f===93?(e.consume(f),l++,m):m(f)}function g(f){return f===58?(e.enter("definitionMarker"),e.consume(f),e.exit("definitionMarker"),r.includes(o)||r.push(o),Ft(e,p,"gfmFootnoteDefinitionWhitespace")):s(f)}function p(f){return n(f)}}function vE(e,n,s){return e.check(sr,n,e.attempt(hE,n,s))}function yE(e){e.exit("gfmFootnoteDefinition")}function kE(e,n,s){const i=this;return Ft(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 jE(e){let s=(e||{}).singleTilde;const i={name:"strikethrough",tokenize:o,resolveAll:r};return s==null&&(s=!0),{text:{126:i},insideSpan:{null:[i]},attentionMarkers:{null:[126]}};function r(l,c){let u=-1;for(;++u<l.length;)if(l[u][0]==="enter"&&l[u][1].type==="strikethroughSequenceTemporary"&&l[u][1]._close){let d=u;for(;d--;)if(l[d][0]==="exit"&&l[d][1].type==="strikethroughSequenceTemporary"&&l[d][1]._open&&l[u][1].end.offset-l[u][1].start.offset===l[d][1].end.offset-l[d][1].start.offset){l[u][1].type="strikethroughSequence",l[d][1].type="strikethroughSequence";const m={type:"strikethrough",start:Object.assign({},l[d][1].start),end:Object.assign({},l[u][1].end)},h={type:"strikethroughText",start:Object.assign({},l[d][1].end),end:Object.assign({},l[u][1].start)},g=[["enter",m,c],["enter",l[d][1],c],["exit",l[d][1],c],["enter",h,c]],p=c.parser.constructs.insideSpan.null;p&&ds(g,g.length,0,po(p,l.slice(d+1,u),c)),ds(g,g.length,0,[["exit",h,c],["enter",l[u][1],c],["exit",l[u][1],c],["exit",m,c]]),ds(l,d-1,u-d+3,g),u=d+g.length-2;break}}for(u=-1;++u<l.length;)l[u][1].type==="strikethroughSequenceTemporary"&&(l[u][1].type="data");return l}function o(l,c,u){const d=this.previous,m=this.events;let h=0;return g;function g(f){return d===126&&m[m.length-1][1].type!=="characterEscape"?u(f):(l.enter("strikethroughSequenceTemporary"),p(f))}function p(f){const b=Qi(d);if(f===126)return h>1?u(f):(l.consume(f),h++,p);if(h<2&&!s)return u(f);const v=l.exit("strikethroughSequenceTemporary"),x=Qi(f);return v._open=!x||x===2&&!!b,v._close=!b||b===2&&!!x,c(f)}}}class wE{constructor(){this.map=[]}add(n,s,i){NE(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 NE(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 SE(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 CE(){return{flow:{null:{name:"table",tokenize:EE,resolveAll:ME}}}}function EE(e,n,s){const i=this;let r=0,o=0,l;return c;function c(T){let _=i.events.length-1;for(;_>-1;){const $=i.events[_][1].type;if($==="lineEnding"||$==="linePrefix")_--;else break}const L=_>-1?i.events[_][1].type:null,G=L==="tableHead"||L==="tableRow"?j:u;return G===j&&i.parser.lazy[i.now().line]?s(T):G(T)}function u(T){return e.enter("tableHead"),e.enter("tableRow"),d(T)}function d(T){return T===124||(l=!0,o+=1),m(T)}function m(T){return T===null?s(T):yt(T)?o>1?(o=0,i.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(T),e.exit("lineEnding"),p):s(T):It(T)?Ft(e,m,"whitespace")(T):(o+=1,l&&(l=!1,r+=1),T===124?(e.enter("tableCellDivider"),e.consume(T),e.exit("tableCellDivider"),l=!0,m):(e.enter("data"),h(T)))}function h(T){return T===null||T===124||Wt(T)?(e.exit("data"),m(T)):(e.consume(T),T===92?g:h)}function g(T){return T===92||T===124?(e.consume(T),h):h(T)}function p(T){return i.interrupt=!1,i.parser.lazy[i.now().line]?s(T):(e.enter("tableDelimiterRow"),l=!1,It(T)?Ft(e,f,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(T):f(T))}function f(T){return T===45||T===58?v(T):T===124?(l=!0,e.enter("tableCellDivider"),e.consume(T),e.exit("tableCellDivider"),b):R(T)}function b(T){return It(T)?Ft(e,v,"whitespace")(T):v(T)}function v(T){return T===58?(o+=1,l=!0,e.enter("tableDelimiterMarker"),e.consume(T),e.exit("tableDelimiterMarker"),x):T===45?(o+=1,x(T)):T===null||yt(T)?y(T):R(T)}function x(T){return T===45?(e.enter("tableDelimiterFiller"),k(T)):R(T)}function k(T){return T===45?(e.consume(T),k):T===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(T),e.exit("tableDelimiterMarker"),M):(e.exit("tableDelimiterFiller"),M(T))}function M(T){return It(T)?Ft(e,y,"whitespace")(T):y(T)}function y(T){return T===124?f(T):T===null||yt(T)?!l||r!==o?R(T):(e.exit("tableDelimiterRow"),e.exit("tableHead"),n(T)):R(T)}function R(T){return s(T)}function j(T){return e.enter("tableRow"),C(T)}function C(T){return T===124?(e.enter("tableCellDivider"),e.consume(T),e.exit("tableCellDivider"),C):T===null||yt(T)?(e.exit("tableRow"),n(T)):It(T)?Ft(e,C,"whitespace")(T):(e.enter("data"),S(T))}function S(T){return T===null||T===124||Wt(T)?(e.exit("data"),C(T)):(e.consume(T),T===92?P:S)}function P(T){return T===92||T===124?(e.consume(T),S):S(T)}}function ME(e,n){let s=-1,i=!0,r=0,o=[0,0,0,0],l=[0,0,0,0],c=!1,u=0,d,m,h;const g=new wE;for(;++s<e.length;){const p=e[s],f=p[1];p[0]==="enter"?f.type==="tableHead"?(c=!1,u!==0&&(Qu(g,n,u,d,m),m=void 0,u=0),d={type:"table",start:Object.assign({},f.start),end:Object.assign({},f.end)},g.add(s,0,[["enter",d,n]])):f.type==="tableRow"||f.type==="tableDelimiterRow"?(i=!0,h=void 0,o=[0,0,0,0],l=[0,s+1,0,0],c&&(c=!1,m={type:"tableBody",start:Object.assign({},f.start),end:Object.assign({},f.end)},g.add(s,0,[["enter",m,n]])),r=f.type==="tableDelimiterRow"?2:m?3:1):r&&(f.type==="data"||f.type==="tableDelimiterMarker"||f.type==="tableDelimiterFiller")?(i=!1,l[2]===0&&(o[1]!==0&&(l[0]=l[1],h=jr(g,n,o,r,void 0,h),o=[0,0,0,0]),l[2]=s)):f.type==="tableCellDivider"&&(i?i=!1:(o[1]!==0&&(l[0]=l[1],h=jr(g,n,o,r,void 0,h)),o=l,l=[o[1],s,0,0])):f.type==="tableHead"?(c=!0,u=s):f.type==="tableRow"||f.type==="tableDelimiterRow"?(u=s,o[1]!==0?(l[0]=l[1],h=jr(g,n,o,r,s,h)):l[1]!==0&&(h=jr(g,n,l,r,s,h)),r=0):r&&(f.type==="data"||f.type==="tableDelimiterMarker"||f.type==="tableDelimiterFiller")&&(l[3]=s)}for(u!==0&&Qu(g,n,u,d,m),g.consume(n.events),s=-1;++s<n.events.length;){const p=n.events[s];p[0]==="enter"&&p[1].type==="table"&&(p[1]._align=SE(n.events,s))}return e}function jr(e,n,s,i,r,o){const l=i===1?"tableHeader":i===2?"tableDelimiter":"tableData",c="tableContent";s[0]!==0&&(o.end=Object.assign({},Ui(n.events,s[0])),e.add(s[0],0,[["exit",o,n]]));const u=Ui(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=Ui(n.events,s[2]),m=Ui(n.events,s[3]),h={type:c,start:Object.assign({},d),end:Object.assign({},m)};if(e.add(s[2],0,[["enter",h,n]]),i!==2){const g=n.events[s[2]],p=n.events[s[3]];if(g[1].end=Object.assign({},p[1].end),g[1].type="chunkText",g[1].contentType="text",s[3]>s[2]+1){const f=s[2]+1,b=s[3]-s[2]-1;e.add(f,b,[])}}e.add(s[3]+1,0,[["exit",h,n]])}return r!==void 0&&(o.end=Object.assign({},Ui(n.events,r)),e.add(r,0,[["exit",o,n]]),o=void 0),o}function Qu(e,n,s,i,r){const o=[],l=Ui(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 Ui(e,n){const s=e[n],i=s[0]==="enter"?"start":"end";return s[1][i]}const _E={name:"tasklistCheck",tokenize:TE};function AE(){return{text:{91:_E}}}function TE(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 Wt(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 yt(u)?n(u):It(u)?e.check({tokenize:RE},n,s)(u):s(u)}}function RE(e,n,s){return Ft(e,i,"whitespace");function i(r){return r===null?s(r):n(r)}}function IE(e){return ap([iE(),pE(),jE(e),CE(),AE()])}const PE={};function Xs(e){const n=this,s=e||PE,i=n.data(),r=i.micromarkExtensions||(i.micromarkExtensions=[]),o=i.fromMarkdownExtensions||(i.fromMarkdownExtensions=[]),l=i.toMarkdownExtensions||(i.toMarkdownExtensions=[]);r.push(IE(s)),o.push(eE()),l.push(tE(s))}const Xu=500,Zu=100;function ll(e){return e.length>Xu?e.slice(-Xu):e}function Jp(e,n,s){const[i,r]=a.useState([]),[o,l]=a.useState(!1),[c,u]=a.useState(!1),[d,m]=a.useState(null),[h,g]=a.useState(!1),p=a.useRef(null),f=a.useRef(!1),b=a.useRef(0),v=a.useRef(e),x=a.useRef(s),k=a.useRef(n),M=a.useRef(0);(v.current!==e||x.current!==s||k.current!==n)&&(v.current=e,x.current=s,k.current=n,b.current++,f.current=!0,r([]),l(!1),u(!1),m(null),g(!1),p.current&&(p.current(),p.current=null)),a.useEffect(()=>{if(!e||!n){p.current&&(p.current(),p.current=null);return}const C=b.current,S=++M.current;f.current=!1;const P=e,T=s;async function _(){if(!P)return;l(!0),g(!1);try{const G=await td(P,T,{limit:Zu});if(f.current||b.current!==C||M.current!==S)return;r(ll(G.entries)),u(G.hasMore),m(G.total)}catch{if(f.current||b.current!==C||M.current!==S)return;r([]),u(!1),m(null)}finally{!f.current&&b.current===C&&M.current===S&&l(!1)}const L=T?`?projectId=${encodeURIComponent(T)}`:"";p.current=qs(`/api/tasks/${P}/logs/stream${L}`,{events:{"agent:log":G=>{if(!(f.current||b.current!==C))try{const $=JSON.parse(G.data);r(I=>ll([...I,$])),m(I=>I!==null?I+1:null)}catch{}}}})}return _(),()=>{f.current=!0,p.current&&(p.current(),p.current=null)}},[e,n,s]);const R=a.useCallback(async()=>{if(!e||h)return;const C=b.current,S=i.length,P=e;g(!0);try{const T=await td(P,s,{limit:Zu,offset:S});if(f.current||b.current!==C)return;r(_=>{const L=[...T.entries,..._];return ll(L)}),u(T.hasMore),m(T.total)}catch{}finally{g(!1)}},[e,s,i.length,h]),j=a.useCallback(()=>r([]),[]);return{entries:i,loading:o,clear:j,loadMore:R,hasMore:c,total:d,loadingMore:h}}function $E(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 em={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})},DE=50;function Yp(e){return[e.taskId,e.timestamp,e.agent??"",e.type,e.text,e.detail??""].join("|")}function LE(e){const n=new Map;return e.map(s=>{const i=Yp(s),r=n.get(i)??0;return n.set(i,r+1),`${i}|${r}`})}function zE({entries:e,loading:n,executorModel:s,validatorModel:i,planningModel:r,hasMore:o=!1,onLoadMore:l,loadingMore:c=!1,totalCount:u=null}){const d=a.useRef(null),m=a.useRef(0),h=a.useRef(0),g=a.useRef(null),[p,f]=a.useState(!0),[b,v]=a.useState(!1),[x,k]=a.useState(!1),M=a.useMemo(()=>LE(e),[e]);a.useLayoutEffect(()=>{const _=d.current;if(!_)return;const L=e.length,G=m.current,$=h.current,I=M[M.length-1]??null,w=g.current!==I;if(L>G){const q=_.scrollTop<=DE;if(w)if(q)_.scrollTop=0;else{const W=_.scrollHeight-$;W>0&&(_.scrollTop+=W)}}m.current=L,h.current=_.scrollHeight,g.current=I},[e,M]);const y=a.useCallback(_=>{_.key==="Escape"&&b&&v(!1)},[b]);a.useEffect(()=>{if(b)return document.addEventListener("keydown",y),()=>{document.removeEventListener("keydown",y)}},[b,y]);const R=s?.provider&&s?.modelId,j=i?.provider&&i?.modelId,C=r?.provider&&r?.modelId,S=a.useMemo(()=>{const _=[];return R&&_.push({role:"Executor",provider:s.provider,modelId:s.modelId}),j&&_.push({role:"Validator",provider:i.provider,modelId:i.modelId}),C&&_.push({role:"Planning",provider:r.provider,modelId:r.modelId}),_},[R,s,j,i,C,r]);if(n&&e.length===0)return t.jsx("div",{className:"agent-log-viewer","data-testid":"agent-log-viewer",children:t.jsx("div",{className:"agent-log-loading",children:"Loading agent logs…"})});if(e.length===0)return 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."})});const P=[...e].reverse(),T=[...M].reverse();return t.jsxs("div",{ref:d,className:`agent-log-viewer agent-log-viewer--streaming${b?" 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:[S.map(_=>t.jsx(Mn,{provider:_.provider,size:"sm"},`${_.role}-${_.provider}-${_.modelId??"default"}`)),t.jsx("button",{className:"agent-log-model-expand-btn",onClick:()=>k(_=>!_),"aria-label":x?"Collapse model details":"Expand model details","aria-expanded":x,"aria-controls":"agent-log-model-details","data-testid":"agent-log-model-expand",children:x?t.jsx(zt,{size:14}):t.jsx(en,{size:14})})]}),t.jsxs("div",{className:"agent-log-model-header-toggle",children:[t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>f(_=>!_),"aria-label":p?"Switch to plain text mode":"Switch to markdown mode","aria-pressed":p,"data-testid":"agent-log-mode-toggle",title:p?"Show raw text":"Show formatted markdown",children:p?"Markdown":"Plain"}),t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>v(_=>!_),"aria-label":b?"Exit full screen":"Expand agent log to full screen","data-testid":"agent-log-fullscreen-toggle",title:b?"Exit full screen":"Expand agent log to full screen",children:b?t.jsx(aa,{size:14}):t.jsx(io,{size:14})})]}),x&&t.jsxs("div",{id:"agent-log-model-details",className:"agent-log-model-details",children:[t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Executor:"}),R?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Mn,{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:"Validator:"}),j?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Mn,{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/Triage:"}),C?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Mn,{provider:r.provider,size:"sm"}),t.jsxs("span",{children:[r.provider,"/",r.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]})]})]}),u!==null&&t.jsxs("div",{className:"agent-log-summary","data-testid":"agent-log-summary",children:["Showing ",e.length," of ",u," entries"]}),P.map((_,L)=>{const G=T[L]??`${Yp(_)}|fallback`,$=P[L-1],I=_.type==="tool"||_.type==="tool_result"||_.type==="tool_error",w=_.agent?I||L===0||$&&($.agent!==_.agent||$.type!==_.type):!1,q=w?t.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:$E(_.timestamp)}):null,W=w?t.jsxs("span",{className:"agent-log-badge-row",children:[t.jsxs("span",{className:"agent-log-agent-badge",children:["[",_.agent,"]"]}),q]}):null;return _.type==="tool"?t.jsxs("div",{className:"agent-log-tool",children:[W,"⚡ ",_.text,_.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",_.detail]})]},G):_.type==="thinking"?t.jsxs("div",{className:"agent-log-thinking",children:[W,p?t.jsx("div",{className:"markdown-body",children:t.jsx(Qs,{remarkPlugins:[Xs],components:em,children:_.text})}):_.text]},G):_.type==="tool_result"?t.jsxs("div",{className:"agent-log-tool-result",children:[W,"✓ ",_.text,_.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",_.detail]})]},G):_.type==="tool_error"?t.jsxs("div",{className:"agent-log-tool-error",children:[W,"✗ ",_.text,_.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",_.detail]})]},G):t.jsxs("div",{className:"agent-log-text",children:[W,p?t.jsx("div",{className:"markdown-body",children:t.jsx(Qs,{remarkPlugins:[Xs],components:em,children:_.text})}):_.text]},G)}),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(it,{size:14,className:"animate-spin"}),"Loading…"]}):"Load More"})})]})}function Xi(e){return e??void 0}function wr(e){return{provider:Xi(e.modelProvider),modelId:Xi(e.modelId)}}function Nr(e){return{provider:Xi(e.validatorModelProvider),modelId:Xi(e.validatorModelId)}}function Sr(e){return{provider:Xi(e.planningModelProvider),modelId:Xi(e.planningModelId)}}function FE(e,n){return e.modelProvider&&e.modelId?{provider:e.modelProvider,modelId:e.modelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function OE(e,n){return e.validatorModelProvider&&e.validatorModelId?{provider:e.validatorModelProvider,modelId:e.validatorModelId}:n?.validatorProvider&&n.validatorModelId?{provider:n.validatorProvider,modelId:n.validatorModelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function UE(e,n){return e.planningModelProvider&&e.planningModelId?{provider:e.planningModelProvider,modelId:e.planningModelId}:n?.planningProvider&&n.planningModelId?{provider:n.planningProvider,modelId:n.planningModelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function cl(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 dl(e){return e.provider&&e.modelId?`${e.provider}/${e.modelId}`:""}function ul(e,n){return e.provider===n.provider&&e.modelId===n.modelId}function BE(e,n){const i={executor:"Executor",validator:"Validator",planning:"Planning"}[e]||e;return!n.provider||!n.modelId?`${i} model set to default`:`${i} model set to ${n.provider}/${n.modelId}`}function HE({task:e,addToast:n,onTaskUpdated:s,settings:i}){const[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState([]),[m,h]=a.useState(!1),[g,p]=a.useState(null),[f,b]=a.useState(()=>wr(e)),[v,x]=a.useState(()=>wr(e)),[k,M]=a.useState(()=>Nr(e)),[y,R]=a.useState(()=>Nr(e)),[j,C]=a.useState(()=>Sr(e)),[S,P]=a.useState(()=>Sr(e)),[T,_]=a.useState(()=>e.thinkingLevel??null),[L,G]=a.useState(()=>e.thinkingLevel??null),[$,I]=a.useState(null),w=a.useRef(e.id);a.useEffect(()=>{h(!0),p(null),is().then(fe=>{o(fe.models),c(fe.favoriteProviders),d(fe.favoriteModels)}).catch(fe=>{p(fe.message||"Failed to load models")}).finally(()=>{h(!1)})},[]);const q=a.useCallback(async fe=>{const Se=l,we=Se.includes(fe)?Se.filter(Pe=>Pe!==fe):[fe,...Se];c(we);try{await nn({favoriteProviders:we,favoriteModels:u})}catch{c(Se),n("Failed to update favorites","error")}},[l,u,n]),W=a.useCallback(async fe=>{const Se=u,we=Se.includes(fe)?Se.filter(Pe=>Pe!==fe):[fe,...Se];d(we);try{await nn({favoriteProviders:l,favoriteModels:we})}catch{d(Se),n("Failed to update model favorites","error")}},[u,l,n]);a.useEffect(()=>{w.current=e.id;const fe=wr(e),Se=Nr(e),te=Sr(e);b(fe),x(fe),M(Se),R(Se),C(te),P(te);const we=e.thinkingLevel??null;_(we),G(we),I(null)},[e.id,e.modelProvider,e.modelId,e.validatorModelProvider,e.validatorModelId,e.planningModelProvider,e.planningModelId,e.thinkingLevel]);const B=a.useMemo(()=>dl(f),[f]),A=a.useMemo(()=>dl(k),[k]),z=a.useMemo(()=>dl(j),[j]),X=a.useMemo(()=>FE(e,i),[e,i]),E=a.useMemo(()=>OE(e,i),[e,i]),U=a.useMemo(()=>UE(e,i),[e,i]),pe=$!==null,ie=a.useCallback(async(fe,Se)=>{const te=e.id,we=v,Pe=y,We=S;I(fe);try{const Ke=s?fe==="executor"?{modelProvider:Se.provider??null,modelId:Se.modelId??null}:fe==="validator"?{validatorModelProvider:Se.provider??null,validatorModelId:Se.modelId??null}:{planningModelProvider:Se.provider??null,planningModelId:Se.modelId??null}:{modelProvider:(fe==="executor"?Se:v).provider??null,modelId:(fe==="executor"?Se:v).modelId??null,validatorModelProvider:(fe==="validator"?Se:y).provider??null,validatorModelId:(fe==="validator"?Se:y).modelId??null,planningModelProvider:(fe==="planning"?Se:S).provider??null,planningModelId:(fe==="planning"?Se:S).modelId??null},Ne=await Ks(te,Ke);if(w.current!==te)return;const _e=wr(Ne),Oe=Nr(Ne),ye=Sr(Ne);x(_e),b(_e),R(Oe),M(Oe),P(ye),C(ye),s?.(Ne),n(BE(fe,{executor:_e,validator:Oe,planning:ye}[fe]),"success")}catch(Ke){if(w.current!==te)return;fe==="executor"?b(we):fe==="validator"?M(Pe):C(We),n(xe(Ke)||"Failed to save model settings","error")}finally{w.current===te&&I(null)}},[e.id,v,y,S,n,s]),re=a.useCallback(fe=>{const Se=cl(fe);b(Se),!ul(Se,v)&&ie("executor",Se)},[v,ie]),F=a.useCallback(fe=>{const Se=cl(fe);M(Se),!ul(Se,y)&&ie("validator",Se)},[y,ie]),ce=a.useCallback(fe=>{const Se=cl(fe);C(Se),!ul(Se,S)&&ie("planning",Se)},[S,ie]),ae=a.useCallback(async fe=>{const Se=e.id,te=L,we=fe===""?null:fe;_(we),I("thinking");try{const Pe=await Ks(Se,{thinkingLevel:we});if(w.current!==Se)return;const We=Pe.thinkingLevel??null;G(We),_(We),s?.(Pe);const Ke=i?.defaultThinkingLevel??"off";n(We===null?`Thinking level set to default (${Ke})`:`Thinking level set to ${We}`,"success")}catch(Pe){if(w.current!==Se)return;_(te),n(xe(Pe)||"Failed to save thinking level","error")}finally{w.current===Se&&I(null)}},[e.id,L,i,n,s]),Q=!v.provider&&!v.modelId,de=!y.provider&&!y.modelId,Te=!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…"}):g?t.jsxs("div",{className:"model-selector-error",children:["Error loading models: ",g,t.jsx("button",{className:"btn btn-sm",onClick:()=>{h(!0),p(null),is().then(fe=>{o(fe.models),c(fe.favoriteProviders),d(fe.favoriteModels)}).catch(fe=>p(fe.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:Q?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",X.provider&&X.modelId?` (${X.provider}/${X.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[v.provider&&t.jsx(Mn,{provider:v.provider,size:"sm"}),v.provider,"/",v.modelId]})}),t.jsx(wn,{id:"executorModel",label:"Executor Model",value:B,onChange:re,models:r,disabled:pe,placeholder:"Select executor model…",favoriteProviders:l,onToggleFavorite:q,favoriteModels:u,onToggleModelFavorite:W}),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:"Validator Model"}),t.jsx("div",{className:"model-selector-current",children:de?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",E.provider&&E.modelId?` (${E.provider}/${E.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[y.provider&&t.jsx(Mn,{provider:y.provider,size:"sm"}),y.provider,"/",y.modelId]})}),t.jsx(wn,{id:"validatorModel",label:"Validator Model",value:A,onChange:F,models:r,disabled:pe,placeholder:"Select validator model…",favoriteProviders:l,onToggleFavorite:q,favoriteModels:u,onToggleModelFavorite:W}),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:Te?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",U.provider&&U.modelId?` (${U.provider}/${U.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[S.provider&&t.jsx(Mn,{provider:S.provider,size:"sm"}),S.provider,"/",S.modelId]})}),t.jsx(wn,{id:"planningModel",label:"Planning Model",value:z,onChange:ce,models:r,disabled:pe,placeholder:"Select planning model…",favoriteProviders:l,onToggleFavorite:q,favoriteModels:u,onToggleModelFavorite:W}),t.jsx("small",{children:"The AI model used for task specification (triage phase)."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"thinkingLevel",children:"Thinking Level"}),t.jsx("div",{className:"model-selector-current",children:L===null?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default (",i?.defaultThinkingLevel??"off",")"]}):t.jsx("span",{className:"model-badge model-badge-custom",children:L})}),t.jsxs("select",{id:"thinkingLevel",value:T??"",onChange:fe=>ae(fe.target.value),disabled:pe,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:Q&&de&&Te&&L===null?"Using project or global default models.":"Model settings are up to date."})]})]})}const qE={open:t.jsx(eo,{size:16}),closed:t.jsx(Ka,{size:16}),merged:t.jsx(sh,{size:16})};function VE({taskId:e,projectId:n,prInfo:s,automationStatus:i,autoMerge:r=!1,prAuthAvailable:o,onPrCreated:l,onPrUpdated:c,addToast:u}){const[d,m]=a.useState(!1),[h,g]=a.useState(""),[p,f]=a.useState(""),[b,v]=a.useState(!1),[x,k]=a.useState(!1),[M,y]=a.useState(null),R=a.useCallback(async()=>{if(h.trim()){v(!0);try{const P=await rv(e,{title:h.trim(),body:p.trim()||void 0},n);l(P),m(!1),g(""),f(""),u(`Created PR #${P.number}`,"success")}catch(P){u(xe(P)||"Failed to create PR","error")}finally{v(!1)}}},[e,h,p,n,l,u]),j=a.useCallback(async()=>{if(s){k(!0);try{const P=await ov(e,n);y(P),c(P.prInfo),u("PR status refreshed","success")}catch(P){u(xe(P)||"Failed to refresh PR","error")}finally{k(!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:P=>g(P.target.value),disabled:b,className:"pr-input"}),t.jsx("textarea",{placeholder:"PR description (optional)",value:p,onChange:P=>f(P.target.value),disabled:b,className:"pr-textarea",rows:3}),t.jsxs("div",{className:"pr-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>m(!1),disabled:b,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:R,disabled:!h.trim()||b,children:b?"Creating…":"Create PR"})]})]})]}):t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(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(Vt,{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 C=qE[s.status]??t.jsx(eo,{size:16}),S=M?.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:C}),t.jsx("span",{className:`pr-status-badge pr-status-badge--${s.status}`,children:s.status}),t.jsxs("span",{className:"pr-number",children:["#",s.number]}),t.jsx("div",{className:"pr-spacer"}),t.jsx("button",{className:"btn btn-sm pr-refresh-btn",onClick:j,disabled:x,title:"Refresh PR status",children:t.jsx(hn,{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(li,{size:14}),s.commentCount]}),t.jsxs("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"pr-link",children:[t.jsx(xg,{size:14}),"View on GitHub"]})]})]})]})}const tm=2e3;function WE(e){const n=e.updatedAt||e.createdAt,s=new Date(n).toLocaleString();return e.updatedAt?`${s} (edited)`:s}function GE(e){return e==="agent"||e==="system"}function KE({task:e,onTaskUpdated:n,addToast:s,currentAuthor:i="user",projectId:r}){const[o,l]=a.useState(""),[c,u]=a.useState(null),[d,m]=a.useState(""),[h,g]=a.useState(!1),[p,f]=a.useState(null),b=a.useMemo(()=>[...e.comments||[]].sort((C,S)=>new Date(S.createdAt).getTime()-new Date(C.createdAt).getTime()),[e.comments]),v=o.length>tm;async function x(){const C=o.trim();if(C){g(!0);try{const S=await Fx(e.id,C,r);l(""),n?.(S),s("Comment added","success")}catch(S){s(xe(S)||"Failed to add comment","error")}finally{g(!1)}}}async function k(C){const S=d.trim();if(S){g(!0);try{const P=await Px(e.id,C,S,r);u(null),m(""),n?.(P),s("Comment updated","success")}catch(P){s(xe(P)||"Failed to update comment","error")}finally{g(!1)}}}async function M(C){f(C);try{const S=await $x(e.id,C,r);n?.(S),s("Comment deleted","success")}catch(S){s(xe(S)||"Failed to delete comment","error")}finally{f(null)}}function y(C){C.key==="Enter"&&(C.ctrlKey||C.metaKey)&&(C.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(C=>{const S=C.author===i,P=c===C.id,T=GE(C.author);return t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header comments-header-row",children:[t.jsxs("div",{className:"comments-author-row",children:[T?t.jsx("span",{className:"ai-guidance-badge","data-testid":"ai-guidance-badge",children:"AI Guidance"}):t.jsx("strong",{children:C.author}),t.jsx("span",{className:"detail-log-timestamp",children:WE(C)})]}),S&&!P?t.jsxs("div",{className:"comments-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{u(C.id),m(C.text)},children:"Edit"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void M(C.id),disabled:p===C.id,children:p===C.id?"Deleting…":"Delete"})]}):null]}),P?t.jsxs("div",{className:"comments-edit-form",children:[t.jsx("textarea",{value:d,onChange:_=>m(_.target.value),rows:3,className:"spec-editor-feedback"}),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 k(C.id),disabled:h||!d.trim(),children:"Save"})]})]}):t.jsx("div",{className:"detail-log-outcome comments-outcome-text",children:C.text})]},C.id)})}),t.jsxs("div",{className:"comments-compose-form",children:[t.jsx("textarea",{value:o,onChange:C=>l(C.target.value),onKeyDown:y,rows:3,placeholder:"Add a comment",className:"spec-editor-feedback"}),t.jsxs("div",{className:"comments-footer-row",children:[t.jsxs("span",{className:`comments-char-count${v?" comments-char-count--over":""}`,children:[o.length," / ",tm]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void x(),disabled:h||!o.trim()||v,children:h?"Posting…":"Add Comment"})]})]})]})}function JE(e){return e?e.slice(0,7):"Unknown"}function YE({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:JE(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 Qp(e){return e.split(`
|
|
606
|
-
`).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}
|
|
607
|
-
`},i):t.jsx(Jm.Fragment,{children:`${s}
|
|
608
|
-
`},i)})}function nm(e,n=60){if(!e||e.length<=n)return e;if(n<4)return e.slice(0,n);const s="...",i=e.lastIndexOf("/");if(i===-1){const m=Math.max(1,n-s.length);return e.slice(0,m)+s}const r=[];for(let m=1;m<e.length;m++)e[m]==="/"&&r.push(m);const o=n-s.length;let l=null,c=-1;for(let m=r.length-1;m>=0;m--){const h=r[m],g=e.slice(h);if(g.length>o)continue;const p=o-g.length;for(let f=0;f<r.length;f++){const b=r[f],v=e.slice(0,b);v.length<=p&&v.length+s.length+g.length<=n&&v.length+g.length>c&&(c=v.length+g.length,l=v+s+g)}}if(l)return l;const u=e.slice(i);if(s.length+u.length<=n)return s+u;const d=n-s.length;return s+e.slice(e.length-d)}function QE(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function XE({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);a.useEffect(()=>{s.length>0&&u===null&&d(0)},[s,u]);const g=a.useCallback(()=>{d(v=>v!==null&&v>0?v-1:v)},[]),p=a.useCallback(()=>{d(v=>v!==null&&v<s.length-1?v+1:v)},[]);if(a.useEffect(()=>{if(!e)return;const v=x=>{if(x.key==="Escape"){l();return}x.key==="ArrowUp"&&(x.metaKey||x.ctrlKey)&&(x.preventDefault(),g()),x.key==="ArrowDown"&&(x.metaKey||x.ctrlKey)&&(x.preventDefault(),p())};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[e,l,g,p]),!e)return null;const f=u!==null?s[u]:null,b=o==="done";return t.jsx("div",{className:"modal-overlay open",onClick:l,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal changes-diff-modal",onClick:v=>v.stopPropagation(),children:[t.jsxs("div",{className:"modal-header changes-diff-modal-header",children:[t.jsxs("div",{className:"changes-diff-header-title",children:[t.jsx(Ts,{size:18}),t.jsxs("span",{children:["Changes — ",n]}),t.jsxs("span",{className:"changes-stat-summary",children:[t.jsxs("span",{className:"diff-add",children:["+",i.additions]})," ",t.jsxs("span",{className:"diff-del",children:["-",i.deletions]})]})]}),t.jsxs("div",{className:"changes-diff-header-actions",children:[s.length>0&&t.jsxs("div",{className:"changes-nav",children:[t.jsx("button",{className:"btn btn-sm btn-icon",onClick:g,disabled:u===null||u<=0,title:"Previous file (Ctrl+↑)","aria-label":"Previous file",children:t.jsx(rc,{size:14})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:u!==null?`${u+1}/${s.length}`:`—/${s.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:p,disabled:u===null||u>=s.length-1,title:"Next file (Ctrl+↓)","aria-label":"Next file",children:t.jsx(en,{size:14})})]}),t.jsx("button",{className:`btn btn-sm ${m?"btn-primary":""}`,onClick:()=>h(v=>!v),title:m?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(zr,{size:14})}),c&&t.jsxs("button",{className:"btn btn-sm",onClick:c,children:[t.jsx(hn,{size:14}),"Refresh"]}),t.jsx("button",{className:"modal-close",onClick:l,"aria-label":"Close",children:t.jsx(Pt,{size:20})})]})]}),t.jsxs("div",{className:"changes-diff-body",children:[t.jsxs("div",{className:"changes-diff-sidebar",children:[b&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(za,{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((v,x)=>t.jsxs("button",{className:`changes-diff-file-item ${u===x?"selected":""}`,onClick:()=>d(x),title:v.path,children:[t.jsx("span",{className:`changes-file-status changes-file-status--${v.status}`,children:QE(v.status)}),t.jsx("span",{className:"changes-diff-file-path",children:v.path}),t.jsxs("span",{className:"changes-diff-file-stat",children:["+",v.additions," -",v.deletions]})]},v.path))})]}),t.jsx("div",{className:"changes-diff-content",children:f?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:f.path}),t.jsxs("span",{className:"changes-diff-file-header-stats",children:["+",f.additions," -",f.deletions]})]}),f.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:Qp(f.patch)})})}):t.jsx("div",{className:"changes-diff-empty",children:"No diff available for this file."})]}):t.jsxs("div",{className:"changes-diff-empty",children:[t.jsx(Ts,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to view its diff"})]})})]})]})})}function sm(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function ZE({taskId:e,worktree:n,projectId:s,column:i,mergeDetails:r,modifiedFiles:o}){const[l,c]=a.useState([]),[u,d]=a.useState({filesChanged:0,additions:0,deletions:0}),[m,h]=a.useState(!0),[g,p]=a.useState(null),[f,b]=a.useState(new Set),[v,x]=a.useState(null),[k,M]=a.useState(!0),[y,R]=a.useState(!1),j=i==="done",C=j&&!!r?.commitSha,S=i==="in-progress"||i==="in-review"||C,P=a.useCallback(async()=>{if(!S){h(!1);return}try{h(!0),p(null);const $=await jh(e,void 0,s),I=$.files.map(w=>({path:w.path,status:w.status,additions:w.additions,deletions:w.deletions,patch:w.patch}));c(I),d($.stats),I.length>0&&(b(new Set([I[0].path])),x(0))}catch($){p(xe($)||"Failed to load diff")}finally{h(!1)}},[e,s,S]);a.useEffect(()=>{P()},[P]);const T=$=>{b(I=>{const w=new Set(I);if(w.has($))w.delete($);else{w.add($);const q=l.findIndex(W=>W.path===$);q!==-1&&x(q)}return w})},_=$=>{if($<0||$>=l.length)return;const I=l[$].path;b(new Set([I])),x($)},L=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(g)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--error",children:[t.jsx(ss,{size:16}),t.jsxs("span",{children:["Error loading changes: ",g]})]})});if(!j&&!n)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Ts,{size:24}),t.jsx("p",{children:"No worktree available for this task."}),t.jsx("span",{className:"task-changes-state-hint",children:"Changes will be shown once the task is in progress."})]})});if(j&&!C){const $=r?.filesChanged,I=r?.insertions,w=r?.deletions,q=$!=null||I!=null||w!=null;return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Ts,{size:24}),t.jsx("p",{children:"Detailed file changes unavailable."}),t.jsx("span",{className:"task-changes-state-hint",children:q?`Merge summary: ${$??0} file${($??0)===1?"":"s"} changed, +${I??0} additions, -${w??0} deletions.`:"No merge commit was recorded for this task."})]})})}return l.length===0?j&&o&&o.length>0?t.jsxs("div",{className:"detail-section task-changes-tab",children:[j&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(za,{size:14}),t.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Ts,{size:24}),t.jsxs("p",{children:[o.length," file",o.length===1?"":"s"," modified during execution."]}),t.jsx("span",{className:"task-changes-state-hint",children:"The recorded merge commit has no diff (likely collapsed into a squash on main). Showing file paths only — patches unavailable."})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:o.map($=>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:sm("unknown")}),t.jsx("span",{className:"changes-file-path",title:$,children:nm($)})]})},$))})]}):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Ts,{size:24}),t.jsx("p",{children:"No files modified."}),t.jsx("span",{className:"task-changes-state-hint",children:j?"No file changes were recorded in the merge commit.":"The agent did not modify any files during execution."})]})}):t.jsxs("div",{className:"detail-section task-changes-tab",children:[j&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(za,{size:14}),t.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergeCommitMessage&&t.jsx("div",{className:"commit-diff-message",children:r.mergeCommitMessage}),r.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),t.jsxs("div",{className:"changes-header",children:[t.jsxs("div",{className:"task-changes-header-title",children:[t.jsxs("h4",{children:[t.jsx(Ts,{size:16}),"Files Changed (",u.filesChanged,")"]}),t.jsxs("span",{className:"task-changes-stats changes-stat-summary",children:[t.jsxs("span",{className:"diff-add",children:["+",u.additions]})," ",t.jsxs("span",{className:"diff-del",children:["-",u.deletions]})]})]}),t.jsxs("div",{className:"changes-header-actions-wrapper",children:[t.jsxs("div",{className:"changes-header-actions",children:[l.length>0&&t.jsxs("div",{className:"changes-nav",children:[t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>L&&_(v-1),disabled:!L,title:"Previous file","aria-label":"Previous file",children:t.jsx(rc,{size:14})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:v!==null?`${v+1}/${l.length}`:`—/${l.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>G&&_(v+1),disabled:!G,title:"Next file","aria-label":"Next file",children:t.jsx(en,{size:14})})]}),t.jsx("button",{className:`btn btn-sm ${k?"btn-primary":""}`,onClick:()=>M($=>!$),title:k?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(zr,{size:14})})]}),t.jsxs("div",{className:"changes-header-actions-secondary",children:[t.jsx("button",{className:"btn btn-sm",onClick:P,disabled:m,children:"Refresh"}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>R(!0),title:"Expand to full-screen diff view","aria-label":"Expand diff view",children:t.jsx(io,{size:14})})]})]})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:l.map($=>{const I=f.has($.path);return t.jsxs("div",{className:`changes-file-item ${I?"expanded":""}`,children:[t.jsxs("button",{className:"changes-file-header",onClick:()=>T($.path),children:[t.jsx("span",{className:"changes-file-toggle",children:I?t.jsx(zt,{size:14}):t.jsx(en,{size:14})}),t.jsx("span",{className:`changes-file-status changes-file-status--${$.status}`,title:$.status,children:sm($.status)}),t.jsx("span",{className:"changes-file-path",title:$.path,children:nm($.path)}),t.jsxs("span",{className:"changes-file-stat",title:`+${$.additions} -${$.deletions}`,children:["+",$.additions," -",$.deletions]})]}),I&&$.patch&&t.jsx("div",{className:"changes-file-content",children:t.jsx("pre",{className:`changes-diff-patch ${k?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:t.jsx("code",{children:Qp($.patch)})})})]},$.path)})}),t.jsx(XE,{isOpen:y,taskId:e,files:l,stats:u,mergeDetails:r,column:i,onClose:()=>R(!1),onRefresh:P})]})}function im(e){return{executorValue:e?.executorProvider&&e?.executorModelId?`${e.executorProvider}/${e.executorModelId}`:"",validatorValue:e?.validatorProvider&&e?.validatorModelId?`${e.validatorProvider}/${e.validatorModelId}`:""}}function eM(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function lP(e,n){const s=eM(e),i=new Set(n.map(c=>c.id));if(!i.has(s))return s;const r=30;let o=s,l=1;for(;i.has(o)&&l<100;){const c=`-${l}`;o=`${s.slice(0,r-c.length)}${c}`,l++}return o}const am=["image/png","image/jpeg","image/gif","image/webp"];function tM(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 Xp({mode:e,description:n,onDescriptionChange:s,title:i,onTitleChange:r,dependencies:o,onDependenciesChange:l,priority:c,onPriorityChange:u,executorModel:d,onExecutorModelChange:m,validatorModel:h,onValidatorModelChange:g,planningModel:p,onPlanningModelChange:f,thinkingLevel:b,onThinkingLevelChange:v,presetMode:x,onPresetModeChange:k,selectedPresetId:M,onSelectedPresetIdChange:y,selectedWorkflowSteps:R,onWorkflowStepsChange:j,onDefaultOnApplied:C,pendingImages:S,onImagesChange:P,tasks:T,projectId:_,disabled:L=!1,addToast:G,isActive:$=!0,onAutoSaveDescription:I,onPlanningMode:w,onSubtaskBreakdown:q,onClose:W,renderBelowPrimary:B,renderBelowModelConfiguration:A,hideDependencies:z,autoExpandMoreOptionsOnSelection:X=!0,reviewLevel:E,onReviewLevelChange:U,executionMode:pe,onExecutionModeChange:ie}){const re=(z?!1:o.length>0)||S.length>0||R.length>0||x!=="default"||(c??cs)!==cs||d!==""||h!==""||(p||"")!==""||(b||"")!==""||E!==void 0||pe==="fast",[F,ce]=a.useState(!1),[ae,Q]=a.useState(X?re:!1),[de,Te]=a.useState(""),[fe,Se]=a.useState([]),[te,we]=a.useState([]),[Pe,We]=a.useState([]),[Ke,Ne]=a.useState(!1),[_e,Oe]=a.useState(null),[ye,De]=a.useState([]),[se,J]=a.useState("idle"),[me,ee]=a.useState(!1),[he,le]=a.useState(!1),[Ie,Ze]=a.useState(!1),at=a.useRef(null),oe=a.useRef(null),Z=a.useRef(null),ue=a.useRef(null),Ce=a.useRef(null),$e=a.useRef(null),ve=a.useRef(null),Ge=a.useRef(!1),je=a.useRef(re),Ue=a.useRef(n.trim()),He=a.useRef(n.trim());a.useEffect(()=>{$&&(Ne(!0),is().then(N=>{Se(N.models),we(N.favoriteProviders),We(N.favoriteModels)}).catch(()=>{}).finally(()=>Ne(!1)),ro(_).then(N=>Oe(N)).catch(()=>Oe(null)),oo(_).then(N=>De(N.filter(H=>H.enabled))).catch(()=>De([])))},[$,_]);const ge=_e?.modelPresets||[],Fe=ge.find(N=>N.id===M),be=(z?!1:o.length>0)||S.length>0||R.length>0||x!=="default"||(c??cs)!==cs||d!==""||h!==""||(p||"")!==""||(b||"")!==""||E!==void 0||pe==="fast";a.useEffect(()=>{if(e!=="create"||!$||!_e?.autoSelectModelPreset)return;const N=(_e.defaultPresetBySize,void 0);if(N){const H=im(N);y(N.id),k("preset"),m(H.executorValue),g(H.validatorValue)}},[$,_e,ge,e]);const Je=a.useRef(!1);a.useEffect(()=>{if(e!=="create"||!$||Je.current||ye.length===0)return;const N=ye.filter(Ae=>Ae.defaultOn);if(N.length===0)return;Je.current=!0;const H=N.map(Ae=>Ae.id);j(H),C?.(H)},[e,$,ye]),a.useEffect(()=>{$||(Je.current=!1)},[$]),a.useEffect(()=>{if(!X){je.current=be;return}be&&!je.current&&Q(!0),je.current=be},[be,X]),a.useEffect(()=>{ae||(ce(!1),Te(""))},[ae]),a.useEffect(()=>{e!=="edit"||!$||ue.current&&(ue.current.focus(),ue.current.select())},[e,$]),a.useEffect(()=>{if(!F)return;const N=H=>{oe.current&&!oe.current.contains(H.target)&&ce(!1)};return document.addEventListener("mousedown",N),()=>document.removeEventListener("mousedown",N)},[F]),a.useEffect(()=>{(e!=="edit"||L)&&Ze(!1)},[e,L]),a.useEffect(()=>{if(e!=="edit"){J("idle");return}const N=n.trim();Ue.current=N,He.current=N,J("idle")},[e]),a.useEffect(()=>{if(e!=="edit"||!I||!$)return;const N=n.trim(),H=Ue.current;if(N===H||N===He.current){$e.current&&(clearTimeout($e.current),$e.current=null),Ge.current||J("idle");return}return $e.current&&clearTimeout($e.current),$e.current=setTimeout(async()=>{if(!Ge.current){Ge.current=!0,J("saving");try{await I(N),He.current=N,J("saved"),ve.current&&clearTimeout(ve.current),ve.current=setTimeout(()=>{J("idle"),ve.current=null},2e3)}catch{J("idle")}finally{Ge.current=!1,$e.current=null}}},1500),()=>{$e.current&&(clearTimeout($e.current),$e.current=null)}},[e,n,I,$]),a.useEffect(()=>()=>{$e.current&&clearTimeout($e.current),ve.current&&clearTimeout(ve.current)},[]),a.useEffect(()=>{if(!me)return;const N=H=>{at.current&&!at.current.contains(H.target)&&ee(!1)};return document.addEventListener("mousedown",N),()=>document.removeEventListener("mousedown",N)},[me]);const st=a.useCallback(N=>{const H=N.clipboardData?.items;if(H)for(let Ae=0;Ae<H.length;Ae++){const ot=H[Ae];if(ot.type.startsWith("image/")){const kt=ot.getAsFile();if(kt&&am.includes(kt.type)){N.preventDefault(),P([...S,{file:kt,previewUrl:URL.createObjectURL(kt)}]);return}}}},[S,P]),dt=a.useCallback(N=>{N.preventDefault();const H=N.dataTransfer.files;for(let Ae=0;Ae<H.length;Ae++){const ot=H[Ae];if(am.includes(ot.type)){P([...S,{file:ot,previewUrl:URL.createObjectURL(ot)}]);return}}},[S,P]),Tt=a.useCallback(N=>{const H=S[N];H&&URL.revokeObjectURL(H.previewUrl),P(S.filter((Ae,ot)=>ot!==N))},[S,P]),$t=a.useCallback(N=>{l(o.includes(N)?o.filter(H=>H!==N):[...o,N])},[o,l]),Dt=(N,H)=>N.length>H?N.slice(0,H)+"…":N,Bt=a.useCallback(N=>{s(N.target.value);const H=N.target;H.style.height="auto",H.style.height=H.scrollHeight+"px"},[s]),qt=a.useCallback(()=>{Ze(N=>!N)},[]),Lt=a.useCallback(N=>{!Ie||N.key!=="Escape"||(N.preventDefault(),N.stopPropagation(),Ze(!1))},[Ie]),Ct=a.useCallback(async N=>{const H=n.trim();if(!(!H||he)){le(!0);try{const Ae=await bh(H,N,_);s(Ae),ee(!1),G("Description refined with AI","success"),Z.current&&(Z.current.style.height="auto",Z.current.style.height=Z.current.scrollHeight+"px")}catch(Ae){const ot=xh(Ae);G(ot,"error")}finally{le(!1)}}},[n,he,G,s,_]),xt=a.useCallback(async N=>{const H=te,ot=H.includes(N)?H.filter(kt=>kt!==N):[N,...H];we(ot);try{await nn({favoriteProviders:ot,favoriteModels:Pe})}catch{we(H)}},[te,Pe]),Et=a.useCallback(async N=>{const H=Pe,ot=H.includes(N)?H.filter(kt=>kt!==N):[N,...H];We(ot);try{await nn({favoriteProviders:te,favoriteModels:ot})}catch{We(H)}},[Pe,te]),Le=a.useCallback(N=>{if(N<=0)return;const H=[...R];[H[N-1],H[N]]=[H[N],H[N-1]],j(H)},[R,j]),gt=a.useCallback(N=>{if(N>=R.length-1)return;const H=[...R];[H[N],H[N+1]]=[H[N+1],H[N]],j(H)},[R,j]),ut=a.useCallback(N=>{j(R.filter(H=>H!==N))},[R,j]),Me=new Map;for(const N of ye)Me.set(N.id,{name:N.name,description:N.description});const Qe=T.filter(N=>!o.includes(N.id)).sort((N,H)=>{const Ae=H.createdAt.localeCompare(N.createdAt);if(Ae!==0)return Ae;const ot=parseInt(N.id.slice(N.id.lastIndexOf("-")+1),10)||0;return(parseInt(H.id.slice(H.id.lastIndexOf("-")+1),10)||0)-ot}),rt=de?Qe.filter(N=>N.id.toLowerCase().includes(de.toLowerCase())||N.title&&N.title.toLowerCase().includes(de.toLowerCase())||N.description&&N.description.toLowerCase().includes(de.toLowerCase())):Qe;return t.jsxs("div",{className:"task-form",onDrop:dt,onDragOver:N=>N.preventDefault(),onPaste:st,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:ue,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:"Task title",value:i||"",onChange:N=>r(N.target.value),disabled:L})]}),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${se==="idle"?"":" is-visible"}`,"aria-live":"polite",children:se==="saving"?"Saving...":se==="saved"?"Saved":""})]}),t.jsxs("div",{className:`description-with-refine${Ie?" description--fullscreen":""}`,ref:at,onKeyDown:Lt,children:[Ie&&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:qt,"aria-label":"Collapse description",title:"Collapse description",children:t.jsx(aa,{size:14})})]}),t.jsx("textarea",{ref:Z,autoFocus:e==="create",id:"task-form-description",value:n,onChange:Bt,placeholder:"What needs to be done?",rows:e==="edit"?8:5,disabled:L||he}),(()=>{const N=!!n.trim()&&!L;return t.jsxs(t.Fragment,{children:[!Ie&&t.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${N?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:qt,"aria-label":"Expand description",title:"Expand description",children:t.jsx(io,{size:14})}),N&&t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${he?"refine-button--loading":""}`,onClick:()=>ee(H=>!H),disabled:he,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(Dn,{size:12,style:{verticalAlign:"middle"}}),he?"Refining...":"Refine"]})]})})(),me&&t.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:N=>N.preventDefault(),children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>Ct("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:()=>Ct("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:()=>Ct("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:()=>Ct("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"&&(w||q)&&t.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[w&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const N=n.trim();if(!N){G("Enter a description first","error");return}W?.(),w(N)},disabled:L||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),q&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const N=n.trim();if(!N){G("Enter a description first","error");return}W?.(),q(N)},disabled:L||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),B,t.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>Q(N=>!N),"aria-expanded":ae,"aria-controls":"task-form-more-options",disabled:L,"data-testid":"task-form-more-options-toggle",children:[t.jsx("span",{children:"More options"}),ae?t.jsx(Ys,{size:14}):t.jsx(zt,{size:14})]}),t.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${ae?"":" collapsed"}`,"aria-hidden":!ae,hidden:!ae,"data-testid":"task-form-more-options",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Attachments"}),S.length>0&&t.jsx("div",{className:"inline-create-previews",children:S.map((N,H)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:N.previewUrl,alt:N.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>Tt(H),disabled:L,title:"Remove image",children:"×"})]},N.previewUrl))}),t.jsx("input",{ref:Ce,type:"file",accept:"image/*",onChange:N=>{const H=N.target.files?.[0];H&&(P([...S,{file:H,previewUrl:URL.createObjectURL(H)}]),N.target.value="")},style:{display:"none"}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>Ce.current?.click(),disabled:L,children:"Attach Screenshot"}),t.jsx("small",{children:"You can also paste images or drag & drop"})]}),!z&&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:oe,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>ce(N=>!N),disabled:L,children:o.length>0?`${o.length} selected`:"Add dependencies"}),F&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:de,onChange:N=>Te(N.target.value),onClick:N=>N.stopPropagation()}),rt.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):rt.map(N=>t.jsxs("div",{className:`dep-dropdown-item${o.includes(N.id)?" selected":""}`,onClick:()=>$t(N.id),onMouseDown:H=>H.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:N.id}),t.jsx("span",{className:"dep-dropdown-title",children:Dt(N.title||N.description||N.id,30)})]},N.id))]})]}),o.length>0&&t.jsx("div",{className:"selected-deps",children:o.map(N=>t.jsxs("span",{className:"dep-chip",children:[N,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>$t(N),disabled:L,children:"×"})]},N))})]})}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Model Configuration"}),u&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"task-priority",className:"model-select-label",children:"Priority"}),t.jsx("select",{id:"task-priority","data-testid":"task-priority-select",value:c??cs,onChange:N=>u(N.target.value),disabled:L,children:uc.map(N=>t.jsx("option",{value:N,children:N[0].toUpperCase()+N.slice(1)},N))})]}),ie&&pe!==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:pe,onChange:N=>ie(N.target.value),disabled:L,children:[t.jsx("option",{value:"standard",children:"Standard"}),t.jsx("option",{value:"fast",children:"Fast"})]})]}),Ke?t.jsx("div",{className:"model-selector-loading",children:"Loading models…"}):fe.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:x==="preset"?M:x,onChange:N=>{const H=N.target.value;if(H==="default"){k("default"),y(""),m(""),g("");return}if(H==="custom"){k("custom"),y("");return}const Ae=ge.find(kt=>kt.id===H),ot=im(Ae);k("preset"),y(H),m(ot.executorValue),g(ot.validatorValue)},disabled:L,children:[t.jsx("option",{value:"default",children:"Use default"}),ge.length>0?t.jsx("option",{disabled:!0,children:"──────────"}):null,ge.map(N=>t.jsx("option",{value:N.id,children:N.name},N.id)),t.jsx("option",{value:"custom",children:"Custom"})]})]}),x==="preset"&&Fe?t.jsxs("small",{children:["Using preset: ",Fe.name]}):null,x==="preset"?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>k("custom"),disabled:L,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(wn,{id:"executor-model",label:"Executor Model",value:d,onChange:N=>{k("custom"),y(""),m(N)},models:fe,disabled:L||x==="preset",favoriteProviders:te,onToggleFavorite:xt,favoriteModels:Pe,onToggleModelFavorite:Et})]}),t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"validator-model",className:"model-select-label",children:"Validator"}),t.jsx(wn,{id:"validator-model",label:"Validator Model",value:h,onChange:N=>{k("custom"),y(""),g(N)},models:fe,disabled:L||x==="preset",favoriteProviders:te,onToggleFavorite:xt,favoriteModels:Pe,onToggleModelFavorite:Et})]}),f&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"planning-model",className:"model-select-label",children:"Planning"}),t.jsx(wn,{id:"planning-model",label:"Planning Model",value:p||"",onChange:N=>{k("custom"),y(""),f(N)},models:fe,disabled:L||x==="preset",favoriteProviders:te,onToggleFavorite:xt,favoriteModels:Pe,onToggleModelFavorite:Et})]}),v&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"thinking-level",className:"model-select-label",children:"Thinking"}),t.jsxs("select",{id:"thinking-level",value:b||"",onChange:N=>v(N.target.value),disabled:L||x==="preset",children:[t.jsxs("option",{value:"",children:["Default (",_e?.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"})]})]}),U&&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:E??"",onChange:N=>U(N.target.value===""?0:parseInt(N.target.value,10)),disabled:L,children:[t.jsx("option",{value:"",children:"Default (None)"}),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"})]})]})]})]}),A,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:ye.length>0&&ye.map(N=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${N.id}`,children:[t.jsx("input",{type:"checkbox",checked:R.includes(N.id),onChange:H=>{j(H.target.checked?[...R,N.id]:R.filter(Ae=>Ae!==N.id))},disabled:L}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[N.name,tM(N.phase||"pre-merge",N.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:N.description})]})]},N.id))})]}),R.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:"}),R.map((N,H)=>{const Ae=Me.get(N);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${N}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:H+1}),t.jsx("span",{className:"workflow-step-order-name",children:Ae?.name||N}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Le(H),disabled:L||H===0,"data-testid":`workflow-step-move-up-${N}`,title:"Move up",children:t.jsx(Ys,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>gt(H),disabled:L||H===R.length-1,"data-testid":`workflow-step-move-down-${N}`,title:"Move down",children:t.jsx(zt,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>ut(N),disabled:L,"data-testid":`workflow-step-remove-${N}`,title:"Remove",children:t.jsx(Pt,{size:14})})]})]},N)})]})]})]})]})}const rm={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 nM(e){switch(e){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return e}}function sM(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 iM(e){return e?new Date(e).toLocaleString():null}function aM(e){const n=e.split(`
|
|
609
|
-
`);return n.length<=1?e:`${n.length} lines`}function Cr(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 rM({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 oM({taskId:e,results:n,loading:s,enabledWorkflowSteps:i,canEdit:r,projectId:o,isTaskInProgress:l,onWorkflowStepsChange:c}){const[u,d]=a.useState({}),[m,h]=a.useState({}),[g,p]=a.useState(null),[f,b]=a.useState([]),[v,x]=a.useState(!1),k=n.some(E=>E.status==="pending"),{entries:M}=Jp(e,!!l&&k,o);a.useEffect(()=>{let E=!1;return oo(o).then(U=>{E||b(U.filter(pe=>pe.enabled))}).catch(()=>{E||b([])}),()=>{E=!0}},[o]);const y=i??[],R=a.useMemo(()=>f.map(E=>({id:E.id,name:E.name,description:E.description,phase:E.phase||"pre-merge"})),[f]),j=a.useMemo(()=>new Map(R.map(E=>[E.id,E])),[R]),C=E=>{d(U=>({...U,[E]:!U[E]}))},S=E=>{h(U=>{const pe=U[E]??"markdown";return{...U,[E]:pe==="markdown"?"plain":"markdown"}})},P=E=>{p(E)},T=()=>{p(null)};a.useEffect(()=>{if(!g)return;const E=U=>{U.key==="Escape"&&T()};return document.addEventListener("keydown",E),()=>{document.removeEventListener("keydown",E)}},[g]);const _=a.useCallback((E,U)=>{if(c){if(U){if(y.includes(E)){c(y);return}c([...y,E]);return}c(y.filter(pe=>pe!==E))}},[c,y]),L=a.useCallback(E=>{if(!c||E<=0)return;const U=[...y];[U[E-1],U[E]]=[U[E],U[E-1]],c(U)},[c,y]),G=a.useCallback(E=>{if(!c||E>=y.length-1)return;const U=[...y];[U[E],U[E+1]]=[U[E+1],U[E]],c(U)},[c,y]),$=a.useCallback(E=>{c&&c(y.filter(U=>U!==E))},[c,y]),I=n.length>0,w=y.length>0;a.useEffect(()=>{r||x(!1)},[r]);const q=a.useMemo(()=>y.map(E=>{const U=j.get(E);return{id:E,name:U?.name||E,description:U?.description||"Step definition not found.",phase:U?.phase||"pre-merge"}}),[y,j]),W=()=>!r||!v||s?null:t.jsxs("div",{className:"workflow-results-editor","data-testid":"workflow-steps-editor",children:[t.jsxs("div",{className:"workflow-steps-section",children:[t.jsx("small",{className:"workflow-steps-description",children:"Select steps to run after task implementation completes"}),t.jsx("div",{className:"workflow-steps-list",children:R.map(E=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${E.id}`,children:[t.jsx("input",{type:"checkbox",checked:y.includes(E.id),onChange:U=>_(E.id,U.target.checked)}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[E.name,Cr(E.phase,E.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:E.description})]})]},E.id))})]}),y.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:"}),y.map((E,U)=>{const pe=j.get(E);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${E}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:U+1}),t.jsx("span",{className:"workflow-step-order-name",children:pe?.name||E}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>L(U),disabled:U===0,"data-testid":`workflow-step-move-up-${E}`,title:"Move up",children:t.jsx(Ys,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>G(U),disabled:U===y.length-1,"data-testid":`workflow-step-move-down-${E}`,title:"Move down",children:t.jsx(zt,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>$(E),"data-testid":`workflow-step-remove-${E}`,title:"Remove",children:t.jsx(Pt,{size:14})})]})]},E)})]})]}),B=()=>{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(!I)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 E=n.filter(F=>F.status==="passed").length,U=n.filter(F=>F.status==="failed").length,pe=n.filter(F=>F.status==="skipped").length,ie=n.filter(F=>F.status==="pending").length,re=[`${n.length} step${n.length!==1?"s":""}`];return E>0&&re.push(`${E} passed`),U>0&&re.push(`${U} failed`),pe>0&&re.push(`${pe} skipped`),ie>0&&re.push(`${ie} 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:re.join(" · ")}),n.map((F,ce)=>{const ae=F.phase||"pre-merge",Q=u[F.workflowStepId]??!1;return t.jsxs("div",{className:`workflow-result-item workflow-result-item--${F.status}`,"data-testid":`workflow-result-item-${F.workflowStepId}`,children:[t.jsxs("div",{className:"workflow-result-header",children:[t.jsxs("div",{className:"workflow-result-name",children:[F.workflowStepName,Cr(ae,F.workflowStepId,"workflow-result-phase")]}),t.jsx("span",{className:`workflow-result-badge workflow-result-badge--${F.status}`,"data-testid":`workflow-result-badge-${F.workflowStepId}`,children:nM(F.status)})]}),t.jsxs("div",{className:"workflow-result-meta",children:[F.startedAt&&t.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",iM(F.startedAt)]}),F.completedAt&&t.jsx("span",{className:"workflow-result-duration",children:sM(F.startedAt,F.completedAt)})]}),F.status==="pending"&&F.startedAt?t.jsx(rM,{entries:M,startedAt:F.startedAt,stepId:F.workflowStepId}):F.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:()=>C(F.workflowStepId),"data-testid":`workflow-result-toggle-${F.workflowStepId}`,children:Q?"Hide output":"Show output"}),!Q&&t.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${F.workflowStepId}`,children:aM(F.output)}),Q&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>S(F.workflowStepId),"data-testid":`workflow-result-mode-toggle-${F.workflowStepId}`,title:(m[F.workflowStepId]??"markdown")==="markdown"?"Switch to plain text":"Switch to markdown",children:(m[F.workflowStepId]??"markdown")==="markdown"?"Markdown":"Plain"}),t.jsx("button",{className:"workflow-result-expand-toggle",onClick:()=>P(F.workflowStepId),"data-testid":`workflow-result-expand-${F.workflowStepId}`,title:"Expand output",children:t.jsx(io,{size:12})})]})]}),Q&&t.jsx("div",{className:`workflow-result-output${(m[F.workflowStepId]??"markdown")==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":`workflow-result-output-${F.workflowStepId}`,children:(m[F.workflowStepId]??"markdown")==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(Qs,{remarkPlugins:[Xs],components:rm,children:F.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:F.output})})]}):null]},`${F.workflowStepId}-${ce}`)})]})},A=r?t.jsx("button",{type:"button",className:"modal-edit-btn workflow-results-edit-toggle",onClick:()=>x(E=>!E),"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(xn,{size:14}),"Done"]}):t.jsxs(t.Fragment,{children:[t.jsx(Hn,{size:14}),"Edit"]})}):null,z=!s&&!I&&w,X=r&&I;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:[q.length," step",q.length===1?"":"s"]})]}),A]}),t.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:q.map(E=>t.jsxs("div",{className:"workflow-configured-item","data-testid":`workflow-configured-step-${E.id}`,children:[t.jsxs("div",{className:"workflow-configured-name",children:[E.name,Cr(E.phase,E.id,"workflow-configured-phase")]}),t.jsx("p",{className:"workflow-configured-description",children:E.description})]},E.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."}),W()]}):t.jsxs(t.Fragment,{children:[X&&t.jsxs("div",{className:"workflow-results-edit-header","data-testid":"workflow-results-edit-header",children:[t.jsx("h4",{children:"Workflow Steps"}),A]}),B(),W()]}),g&&(()=>{const E=n.find(ie=>ie.workflowStepId===g);if(!E)return null;const U=m[E.workflowStepId]??"markdown",pe=E.phase||"pre-merge";return t.jsx("div",{className:"workflow-output-modal-overlay",onClick:ie=>{ie.target===ie.currentTarget&&T()},"data-testid":"workflow-output-modal",children:t.jsxs("div",{className:"workflow-output-modal",role:"dialog","aria-modal":"true",children:[t.jsxs("div",{className:"workflow-output-modal-header",children:[t.jsxs("div",{className:"workflow-output-modal-title",children:[t.jsx("span",{className:"workflow-output-modal-name",children:E.workflowStepName}),Cr(pe,E.workflowStepId,"workflow-output-modal-phase")]}),t.jsxs("div",{className:"workflow-output-modal-controls",children:[t.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>S(E.workflowStepId),"data-testid":"workflow-output-modal-mode-toggle",title:U==="markdown"?"Switch to plain text":"Switch to markdown",children:U==="markdown"?"Markdown":"Plain"}),t.jsx("button",{className:"workflow-output-modal-close",onClick:T,"data-testid":"workflow-output-modal-close","aria-label":"Close",children:t.jsx(Pt,{size:16})})]})]}),t.jsx("div",{className:"workflow-output-modal-body",children:t.jsx("div",{className:`workflow-result-output workflow-result-output--expanded${U==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":"workflow-output-modal-content",children:U==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(Qs,{remarkPlugins:[Xs],components:rm,children:E.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:E.output})})})]})})})()]})}const lM=/^[a-zA-Z0-9_-]{1,64}$/,cM=200;function om(e){return e?new Date(e).toLocaleString():""}function dM(e,n=cM){return e.length<=n?e:e.substring(0,n)+"…"}function uM({taskId:e,addToast:n,onTaskUpdated:s,projectId:i,canEdit:r=!1}){const[o,l]=a.useState([]),[c,u]=a.useState(!0),[d,m]=a.useState(null),[h,g]=a.useState(""),[p,f]=a.useState(null),[b,v]=a.useState(""),[x,k]=a.useState(null),[M,y]=a.useState([]),[R,j]=a.useState(!1),[C,S]=a.useState(!1),[P,T]=a.useState(""),[_,L]=a.useState(""),[G,$]=a.useState(!1),[I,w]=a.useState(null),[q,W]=a.useState(null),[B,A]=a.useState(!1),z=a.useCallback(async()=>{try{const ae=await Dx(e,i);l(ae)}catch(ae){n(xe(ae)||"Failed to load documents","error")}finally{u(!1)}},[e,i,n]);a.useEffect(()=>{z()},[z]);async function X(ae){d===ae.key?(m(null),g(""),f(null),v(""),k(null),y([]),A(!1)):(m(ae.key),g(ae.content),f(null),v(""),k(null),y([]),A(!1))}async function E(ae){if(x===ae)k(null),y([]);else{k(ae),j(!0);try{const Q=await Lx(e,ae,i);y(Q)}catch(Q){n(xe(Q)||"Failed to load revisions","error")}finally{j(!1)}}}function U(){d&&(f(d),v(h))}function pe(){f(null),v("")}async function ie(){if(!(!p||!b.trim())){$(!0);try{await nd(e,p,b,{},i),f(null),v(""),await z();const ae=o.find(Q=>Q.key===p);ae&&g(ae.content),n("Document saved","success")}catch(ae){n(xe(ae)||"Failed to save document","error")}finally{$(!1)}}}async function re(){const ae=P.trim(),Q=_.trim();if(!ae){n("Document key is required","error");return}if(!lM.test(ae)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!Q){n("Content is required","error");return}$(!0);try{await nd(e,ae,Q,{},i),S(!1),T(""),L(""),await z(),n("Document created","success")}catch(de){n(xe(de)||"Failed to create document","error")}finally{$(!1)}}async function F(ae){w(ae);try{await zx(e,ae,i),W(null),w(null),d===ae&&(m(null),g("")),x===ae&&(k(null),y([])),await z(),n("Document deleted","success")}catch(Q){n(xe(Q)||"Failed to delete document","error")}finally{w(null)}}function ce(ae){g(ae.content),f(null),v("")}return c?t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),t.jsx("div",{className:"detail-log-empty",children:"Loading documents…"})]}):t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),C&&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:P,onChange:ae=>T(ae.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:_,onChange:ae=>L(ae.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),T(""),L("")},disabled:G,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void re(),disabled:G||!P.trim()||!_.trim(),children:G?"Creating…":"Create"})]})]}),o.length===0&&!C?t.jsx("div",{className:"detail-log-empty",children:"No documents yet."}):t.jsx("div",{className:"task-documents-list",children:o.map(ae=>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(Ni,{size:14}),t.jsx("span",{className:"task-document-key",children:ae.key}),t.jsxs("span",{className:"task-document-revision-badge",children:["v",ae.revision]})]}),t.jsxs("div",{className:"task-document-meta",children:[t.jsx("span",{className:"task-document-author",children:ae.author}),t.jsx("span",{className:"task-document-timestamp",children:om(ae.updatedAt||ae.createdAt)})]})]}),d===ae.key&&p!==ae.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:()=>A(Q=>!Q),"aria-label":B?"Switch to plain text":"Switch to markdown","aria-pressed":B,title:B?"Switch to plain text":"Switch to markdown",children:B?"Markdown":"Plain"})}),t.jsx("div",{className:"task-document-content",children:B?t.jsx("div",{className:"task-document-content-markdown",children:t.jsx("div",{className:"markdown-body",children:t.jsx(Qs,{remarkPlugins:[Xs],children:h})})}):t.jsx("pre",{className:"task-document-content-text",children:h})}),x===ae.key&&t.jsxs("div",{className:"task-document-revisions",children:[t.jsx("h5",{children:"Revision History"}),R?t.jsx("div",{className:"detail-log-empty",children:"Loading…"}):M.length<=1?t.jsx("div",{className:"detail-log-empty",children:"No previous revisions."}):t.jsx("div",{className:"task-document-revision-list",children:M.filter(Q=>Q.revision<ae.revision).sort((Q,de)=>de.revision-Q.revision).map(Q=>t.jsxs("div",{className:"task-document-revision-item",onClick:()=>ce(Q),children:[t.jsxs("div",{className:"revision-header",children:[t.jsxs("span",{className:"revision-badge",children:["v",Q.revision]}),t.jsx("span",{className:"revision-author",children:Q.author}),t.jsx("span",{className:"revision-timestamp",children:om(Q.createdAt)})]}),t.jsx("div",{className:"revision-preview",children:dM(Q.content,100)})]},Q.id))})]})]}),p===ae.key&&t.jsxs("div",{className:"task-document-edit-form",children:[t.jsx("textarea",{value:b,onChange:Q=>v(Q.target.value),rows:10,disabled:G}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:pe,disabled:G,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void ie(),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 X(ae),children:d===ae.key?t.jsxs(t.Fragment,{children:[t.jsx(Ys,{size:14})," Collapse"]}):t.jsxs(t.Fragment,{children:[t.jsx(zt,{size:14})," Expand"]})}),d===ae.key&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>void E(ae.key),children:[t.jsx(Fa,{size:14})," History"]}),r&&p!==ae.key&&t.jsx("button",{className:"btn btn-sm",onClick:U,children:"Edit"}),r&&(q===ae.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 F(ae.key),disabled:I===ae.key,children:I===ae.key?"…":"Yes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>W(null),disabled:I===ae.key,children:"No"})]}):t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>W(ae.key),children:t.jsx(Ht,{size:14})}))]})]})]},ae.key))}),r&&!C&&t.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>S(!0),children:[t.jsx(Vt,{size:14})," New Document"]})]})}function Er(e){return e.toLocaleString()}function ml(e){const n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString()}function Mr(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 mM(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 hM(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??""}
|
|
610
|
-
${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:mM(n)}})}function pM(e){const n=e.map(r=>{if(!r.startedAt||!r.completedAt)return null;const o=new Date(r.startedAt).getTime(),l=new Date(r.completedAt).getTime();return Number.isNaN(o)||Number.isNaN(l)||l<o?null:{name:r.workflowStepName||r.workflowStepId,durationMs:l-o}}).filter(r=>r!==null),s=n.reduce((r,o)=>r+o.durationMs,0),i=n.reduce((r,o)=>!r||o.durationMs>r.durationMs?o:r,void 0);return{timedStepCount:n.length,totalDurationMs:s,longestStep:i}}function fM({tokenUsage:e,loading:n,task:s}){const i=hM(s?.log??[]),r=i.filter(d=>typeof d.durationMs=="number"),o=r.reduce((d,m)=>d+(m.durationMs??0),0),l=r.reduce((d,m)=>!d||(m.durationMs??0)>(d.durationMs??0)?m:d,void 0),c=pM(s?.workflowStepResults??[]),u=s?.steps?.length??0;return t.jsxs("section",{className:"task-token-stats-panel","aria-label":"Task execution statistics",children:[t.jsx("h4",{children:"Execution & Token Stats"}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Execution Timing"}),t.jsxs("div",{className:"task-token-stats-panel__grid",role:"list","aria-label":"Execution timing metrics",children:[t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Timing events"}),t.jsx("span",{className:"task-token-stats-panel__value",children:i.length.toLocaleString()})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Timed duration"}),t.jsx("span",{className:"task-token-stats-panel__value",children:Mr(o)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Workflow timed steps"}),t.jsx("span",{className:"task-token-stats-panel__value",children:c.timedStepCount.toLocaleString()})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Workflow runtime"}),t.jsx("span",{className:"task-token-stats-panel__value",children:Mr(c.totalDurationMs)})]})]}),t.jsxs("dl",{className:"task-token-stats-panel__timestamps",children:[t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Longest timing event"}),t.jsx("dd",{children:l?.durationMs?`${l.summary} (${Mr(l.durationMs)})`:"No timed events recorded yet."})]}),t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Longest workflow step"}),t.jsx("dd",{children:c.longestStep?`${c.longestStep.name} (${Mr(c.longestStep.durationMs)})`:"No completed workflow step timings yet."})]})]})]}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Execution Details"}),t.jsxs("dl",{className:"task-token-stats-panel__details",children:[t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Execution mode"}),t.jsx("dd",{children:s?.executionMode==="fast"?"Fast":"Standard"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Runtime status"}),t.jsx("dd",{children:s?.status??"Not set"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Paused"}),t.jsx("dd",{children:s?.paused?"Yes":"No"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Step progress"}),t.jsx("dd",{children:u>0?`${Math.min((s?.currentStep??0)+1,u)} / ${u}`:"No steps"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Retries (recovery / workflow / merge / task_done)"}),t.jsx("dd",{children:`${s?.recoveryRetryCount??0} / ${s?.workflowStepRetries??0} / ${s?.mergeRetries??0} / ${s?.taskDoneRetryCount??0}`})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Recovery state"}),t.jsx("dd",{children:s?.nextRecoveryAt?`Next recovery at ${ml(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:Er(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:Er(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:Er(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:Er(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:ml(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:ml(e.lastUsedAt)})})]})]})]}):t.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:"No token usage recorded for this task yet."})]})]})}function gM(e,n){return e.modelProvider&&e.modelId?{provider:e.modelProvider,modelId:e.modelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function bM(e,n){return e.validatorModelProvider&&e.validatorModelId?{provider:e.validatorModelProvider,modelId:e.validatorModelId}:n?.validatorProvider&&n.validatorModelId?{provider:n.validatorProvider,modelId:n.validatorModelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function xM(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 vM(e,n,s){if(e.planningModelProvider&&e.planningModelId)return{provider:e.planningModelProvider,modelId:e.planningModelId};const i=xM(n);return i||(s?.planningProvider&&s.planningModelId?{provider:s.planningProvider,modelId:s.planningModelId}:s?.defaultProvider&&s.defaultModelId?{provider:s.defaultProvider,modelId:s.defaultModelId}:{})}function yM(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 kM(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 jM(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function wM(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 lm(e,n){return e.length>n?e.slice(0,n)+"…":e}function cm(e=[],n=[]){return e.length===n.length&&e.every((s,i)=>s===n[i])}function hl(e){const n=e.indexOf("/");return!e||n===-1?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function pl(e){return e.trim()}function NM(e){const n=e.trim();return n.length>0?n:void 0}function ja(e){return typeof e=="string"&&uc.includes(e)?e:cs}function wa(e){return e==="fast"?"fast":"standard"}const fl=200,SM=new Set(["triage","todo"]);function CM({task:e,projectId:n,tasks:s=[],onClose:i,onOpenDetail:r,onMoveTask:o,onDeleteTask:l,onMergeTask:c,onRetryTask:u,onDuplicateTask:d,onTaskUpdated:m,addToast:h,prAuthAvailable:g,initialTab:p="definition"}){const[f,b]=a.useState(p),[v,x]=a.useState(()=>"prompt"in e?e:null),[k,M]=a.useState(()=>!("prompt"in e));a.useEffect(()=>{if("prompt"in e){x(e),M(!1);return}let Y=!1;return M(!0),x(null),Or(e.id,n).then(Ye=>{Y||(x(Ye),M(!1))}).catch(()=>{Y||M(!1)}),()=>{Y=!0}},[e.id,n]);const y=v??{...e,prompt:""},R=e.status==="failed"||e.status==="stuck-killed"||e.status==="specifying"||e.status==="needs-respecify"||(e.stuckKillCount??0)>0||(e.recoveryRetryCount??0)>0||!!e.nextRecoveryAt;a.useEffect(()=>{b(p)},[p]),a.useEffect(()=>{P(!1)},[e.id]);const[j,C]=a.useState("activity"),[S,P]=a.useState(!1),[T,_]=a.useState(e.attachments||[]),[L,G]=a.useState(!1),[$,I]=a.useState(e.dependencies||[]),[w,q]=a.useState(!1),[W,B]=a.useState(""),[A,z]=a.useState(null),[X,E]=a.useState([]),[U,pe]=a.useState(!1),[ie,re]=a.useState(!1),[F,ce]=a.useState(!1),[ae,Q]=a.useState(!1),[de,Te]=a.useState(!1),[fe,Se]=a.useState(y.prompt||""),[te,we]=a.useState(""),[Pe,We]=a.useState(!1),[Ke,Ne]=a.useState(""),[_e,Oe]=a.useState(!1),[ye,De]=a.useState(!1),[se,J]=a.useState(e.title||""),[me,ee]=a.useState(e.description||""),[he,le]=a.useState(e.dependencies||[]),[Ie,Ze]=a.useState(""),[at,oe]=a.useState(""),[Z,ue]=a.useState(""),[Ce,$e]=a.useState(""),[ve,Ge]=a.useState("default"),[je,Ue]=a.useState(void 0),[He,ge]=a.useState(cs),[Fe,be]=a.useState(wa(e.executionMode)),[Je,st]=a.useState(""),[dt,Tt]=a.useState(e.enabledWorkflowSteps||[]),[$t,Dt]=a.useState(e.sourceIssue?.provider??""),[Bt,qt]=a.useState(e.sourceIssue?.repository??""),[Lt,Ct]=a.useState(e.sourceIssue?.externalIssueId??""),[xt,Et]=a.useState(e.sourceIssue?.url??""),[Le,gt]=a.useState([]),[ut,Me]=a.useState(!1),Qe=a.useRef(!1),[rt,N]=a.useState(!1),[H,Ae]=a.useState(!1),ot=a.useRef(null),kt=a.useRef(null),{getSlotsForId:Ot}=Eh(n),sn=Ot("task-detail-tab");a.useEffect(()=>(Qe.current=!0,()=>{Qe.current=!1}),[]);const[Rt,zn]=a.useState(void 0),[Wn,ms]=a.useState([]),[pn,Fn]=a.useState(!1),[Sn,fn]=a.useState(e.enabledWorkflowSteps||[]);a.useEffect(()=>{J(e.title||""),ee(e.description||""),Dt(e.sourceIssue?.provider??""),qt(e.sourceIssue?.repository??""),Ct(e.sourceIssue?.externalIssueId??""),Et(e.sourceIssue?.url??""),be(wa(e.executionMode)),De(!1)},[e.id,e.title,e.description,e.sourceIssue,e.executionMode]),a.useEffect(()=>{fn(e.enabledWorkflowSteps||[])},[e.id,e.enabledWorkflowSteps]),a.useEffect(()=>{let Y=!1;return ro(n).then(Ye=>{Y||zn(Ye)}).catch(()=>{}),()=>{Y=!0}},[n]),a.useEffect(()=>{if(f!=="workflow")return;let Y=!1;return Fn(!0),ry(e.id,n).then(Ye=>{Y||ms(Ye)}).catch(Ye=>{Y||h(`Failed to load workflow results: ${xe(Ye)}`,"error")}).finally(()=>{Y||Fn(!1)}),()=>{Y=!0}},[f,e.id,n,h]),a.useEffect(()=>{if(f!=="workflow")return;const Y=n?`?projectId=${encodeURIComponent(n)}`:"",Ye=lt=>{try{const wt=JSON.parse(lt.data);wt.id===e.id&&Array.isArray(wt.workflowStepResults)&&ms(wt.workflowStepResults)}catch{}};return qs(`/api/events${Y}`,{events:{"task:updated":Ye}})},[f,e.id,n]),a.useEffect(()=>{w||B("")},[w]),a.useEffect(()=>{if(!e.assignedAgentId){z(null);return}const Y=X.find(lt=>lt.id===e.assignedAgentId);if(Y){z(Y);return}let Ye=!1;return yh(e.assignedAgentId,n).then(lt=>{Ye||z(lt)}).catch(()=>{Ye||z(null)}),()=>{Ye=!0}},[e.assignedAgentId,n,X]),a.useEffect(()=>{pe(!1)},[e.id]),a.useEffect(()=>{if(!(rt||H))return;const Ye=lt=>{const wt=lt.target,Ms=ot.current?.contains(wt),Rn=kt.current?.contains(wt);!Ms&&rt&&N(!1),!Rn&&H&&Ae(!1)};return document.addEventListener("mousedown",Ye),()=>document.removeEventListener("mousedown",Ye)},[rt,H]),a.useEffect(()=>{if(!(rt||H))return;const Ye=lt=>{lt.key==="Escape"&&(lt.stopPropagation(),rt&&N(!1),H&&Ae(!1))};return document.addEventListener("keydown",Ye),()=>document.removeEventListener("keydown",Ye)},[rt,H]),a.useEffect(()=>{Te(!1),Se(y.prompt||""),we("")},[e.id,y.prompt]);const Gn=SM.has(e.column)&&!ut,dn=a.useCallback(()=>{if(!Gn)return;De(!0),J(e.title||""),ee(e.description||""),le(e.dependencies||[]);const Y=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"",Ye=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"",lt=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";Ze(Y),oe(Ye),ue(lt),$e(e.thinkingLevel??""),Ge(Y||Ye||lt?"custom":"default"),st(""),Tt(e.enabledWorkflowSteps||[]),be(wa(e.executionMode)),Dt(e.sourceIssue?.provider??""),qt(e.sourceIssue?.repository??""),Ct(e.sourceIssue?.externalIssueId??""),Et(e.sourceIssue?.url??""),gt([]),Ue(e.reviewLevel),ge(ja(e.priority))},[Gn,e]),Mt=a.useCallback(()=>{De(!1),J(e.title||""),ee(e.description||""),le(e.dependencies||[]),Dt(e.sourceIssue?.provider??""),qt(e.sourceIssue?.repository??""),Ct(e.sourceIssue?.externalIssueId??""),Et(e.sourceIssue?.url??""),ge(ja(e.priority)),be(wa(e.executionMode)),Le.forEach(Y=>URL.revokeObjectURL(Y.previewUrl)),gt([])},[e.title,e.description,e.dependencies,e.priority,e.executionMode,Le]),yn=a.useCallback(async()=>{Me(!0);try{const Y={},Ye=se.trim(),lt=me.trim();Ye&&Ye!==(e.title??"")&&(Y.title=Ye),lt&<!==(e.description??"")&&(Y.description=lt),cm(he,e.dependencies??[])||(Y.dependencies=he),cm(dt,e.enabledWorkflowSteps??[])||(Y.enabledWorkflowSteps=dt);const wt=hl(Ie),Ms=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"";Ie!==Ms&&(Y.modelProvider=wt?.provider??null,Y.modelId=wt?.modelId??null);const Rn=hl(at),or=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"";at!==or&&(Y.validatorModelProvider=Rn?.provider??null,Y.validatorModelId=Rn?.modelId??null);const ma=hl(Z),ko=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";Z!==ko&&(Y.planningModelProvider=ma?.provider??null,Y.planningModelId=ma?.modelId??null);const jo=e.thinkingLevel??"";Ce!==jo&&(Y.thinkingLevel=Ce!==""?Ce:null);const wo=e.reviewLevel;je!==wo&&(Y.reviewLevel=je);const Ws=ja(e.priority);He!==Ws&&(Y.priority=He);const ni=wa(e.executionMode);Fe!==ni&&(Y.executionMode=Fe==="fast"?"fast":null);const si=pl($t),Ti=pl(Bt),Ri=pl(Lt),ha=NM(xt);if(si.length===0&&Ti.length===0&&Ri.length===0&&!ha)e.sourceIssue&&(Y.sourceIssue=null);else{if(!si||!Ti||!Ri){h("Source issue provider, repository, and issue identifier are required","error"),Me(!1);return}const xs=Number.parseInt(Ri,10),ii=e.sourceIssue?.issueNumber??xs;if(!Number.isFinite(ii)||ii<=0){h("Source issue identifier must be numeric for new metadata","error"),Me(!1);return}const _s={provider:si,repository:Ti,externalIssueId:Ri,issueNumber:ii,...ha?{url:ha}:{}},Ps=e.sourceIssue;(!Ps||Ps.provider!==_s.provider||Ps.repository!==_s.repository||Ps.externalIssueId!==_s.externalIssueId||Ps.issueNumber!==_s.issueNumber||(Ps.url??void 0)!==_s.url)&&(Y.sourceIssue=_s)}if(Object.keys(Y).length>0){const xs=await Ks(e.id,Y,n);m?.(xs)}if(Le.length>0){const xs=[];for(const ii of Le)try{const _s=await Ua(e.id,ii.file,n);_(Ps=>[...Ps,_s])}catch{xs.push(ii.file.name)}xs.length>0&&h(`Failed to upload: ${xs.join(", ")}`,"error")}Le.forEach(xs=>URL.revokeObjectURL(xs.previewUrl)),gt([]),h(`Updated ${e.id}`,"success"),De(!1)}catch(Y){h(`Failed to update ${e.id}: ${xe(Y)}`,"error")}finally{Qe.current&&Me(!1)}},[e,se,me,he,Ie,at,Z,Ce,je,He,Fe,dt,$t,Bt,Lt,xt,Le,h,n,m]),Kn=a.useCallback(async Y=>{try{await Ks(e.id,{description:Y},n),h("Description saved","success")}catch(Ye){h(`Failed to save: ${xe(Ye)}`,"error")}},[e.id,h,n]),kn=a.useCallback(Y=>{ye&&(Y.key==="Escape"?(Y.preventDefault(),Mt()):Y.key==="Enter"&&(Y.ctrlKey||Y.metaKey)&&(Y.preventDefault(),yn()))},[ye,Mt,yn]);a.useEffect(()=>{if(ye)return document.addEventListener("keydown",kn),()=>document.removeEventListener("keydown",kn)},[ye,kn]);const _n=a.useRef(null),{entries:hs,loading:ps,loadMore:On,hasMore:K,total:ze,loadingMore:tt}=Jp(e.id,f==="logs"&&j==="agent-log",n);a.useEffect(()=>{const Y=Ye=>{Ye.key==="Escape"&&!ye&&i()};return document.addEventListener("keydown",Y),()=>document.removeEventListener("keydown",Y)},[i,ye]);const et=a.useCallback(Y=>{Y.target===Y.currentTarget&&i()},[i]),mt=a.useCallback(async Y=>{try{await o(e.id,Y),i(),h(`Moved to ${Pn[Y]}`,"success")}catch(Ye){h(xe(Ye),"error")}},[e.id,o,i,h]),jt=a.useCallback(async()=>{if(confirm(`Delete ${e.id}?`))try{await l(e.id),i(),h(`Deleted ${e.id}`,"info")}catch(Y){const Ye=wM(Y);if(!Ye||Ye.dependentIds.length===0){h(xe(Y),"error");return}const lt=Ye.dependentIds.join(", ");if(!confirm(`${e.id} is a dependency of ${lt}.
|
|
611
|
-
|
|
612
|
-
Delete anyway by removing these dependency references first?`))return;try{await l(e.id,{removeDependencyReferences:!0}),i(),h(`Deleted ${e.id} after removing dependency references`,"info")}catch(Ms){h(xe(Ms),"error")}}},[e.id,l,i,h]),_t=a.useCallback(()=>{confirm(`Merge ${e.id} into the current branch?`)&&(i(),h(`Merging ${e.id}...`,"info"),c(e.id).then(Y=>{const Ye=Y.merged?`Merged ${e.id} (branch: ${Y.branch})`:`Closed ${e.id} (${Y.error||"no branch to merge"})`;h(Ye,"success")}).catch(Y=>{h(xe(Y),"error")}))},[e.id,c,i,h]),gn=a.useCallback(()=>{u&&(i(),u(e.id).then(()=>{h(`Retried ${e.id}`,"success")}).catch(Y=>{h(xe(Y),"error")}))},[e.id,u,i,h]),fs=a.useCallback(async()=>{if(d&&confirm(`Duplicate ${e.id}? This will create a new task in Triage with the same description and prompt.`))try{const Y=await d(e.id);i(),h(`Duplicated ${e.id} → ${Y.id}`,"success")}catch(Y){h(xe(Y),"error")}},[e.id,d,i,h]),Qt=a.useCallback(async()=>{try{e.paused?(await Cx(e.id,n),h(`Unpaused ${e.id}`,"success")):(await hh(e.id,n),h(`Paused ${e.id}`,"success")),i()}catch(Y){h(xe(Y),"error")}},[e.id,e.paused,i,h]),vt=a.useCallback(async()=>{try{await Ax(e.id,n),h(`Plan approved — ${e.id} moved to Todo`,"success"),i()}catch(Y){h(xe(Y),"error")}},[e.id,i,h]),ct=a.useCallback(async()=>{if(confirm("Reject this plan? The specification will be discarded and regenerated."))try{await Tx(e.id,n),h(`Plan rejected — ${e.id} returned to Triage for re-specification`,"info"),i()}catch(Y){h(xe(Y),"error")}},[e.id,i,h]),ne=a.useCallback(async()=>{if(confirm("Rebuild the specification for this task? The task will move to triage for re-specification."))try{await Ux(e.id,n),i(),h(`Respecifying ${e.id}...`,"info")}catch(Y){h(xe(Y),"error")}},[e.id,n,i,h]),Ee=a.useCallback(()=>{We(!0),Ne("")},[]),nt=a.useCallback(()=>{N(!1),Ae(!1)},[]),ft=a.useCallback(Y=>{nt(),mt(Y)},[nt]),bt=a.useCallback(Y=>{nt(),Y()},[nt]),on=a.useCallback(()=>{nt(),_t()},[nt]),Xt=a.useCallback(()=>{We(!1),Ne(""),Oe(!1)},[]),cn=a.useCallback(async()=>{if(!Ke.trim()){h("Please enter feedback describing what needs refinement","error");return}if(Ke.length>2e3){h("Feedback must be 2000 characters or less","error");return}Oe(!0);try{const Y=await Bx(e.id,Ke.trim(),n);h(`Refinement task created: ${Y.id}`,"success"),i()}catch(Y){h(xe(Y),"error")}finally{Oe(!1)}},[e.id,Ke,h,i]),Gt=a.useCallback(async Y=>{G(!0);try{const Ye=await Ua(e.id,Y,n);_(lt=>[...lt,Ye]),h("Screenshot attached","success")}catch(Ye){h(xe(Ye),"error")}finally{G(!1)}},[e.id,h]),bn=a.useCallback(async Y=>{const Ye=Y.target.files?.[0];Ye&&(await Gt(Ye),_n.current&&(_n.current.value=""))},[Gt]);a.useEffect(()=>{const Y=Ye=>{const lt=Ye.clipboardData?.items;if(lt)for(let wt=0;wt<lt.length;wt++){const Ms=lt[wt];if(Ms.type.startsWith("image/")){const Rn=Ms.getAsFile();if(Rn){Ye.preventDefault(),Gt(Rn);return}}}};return document.addEventListener("paste",Y),()=>document.removeEventListener("paste",Y)},[Gt]);const Cn=a.useCallback(Y=>{Y.preventDefault()},[]),gs=a.useCallback(Y=>{Y.preventDefault();const Ye=Y.dataTransfer.files;for(let lt=0;lt<Ye.length;lt++){const wt=Ye[lt];if(wt.type.startsWith("image/")){Gt(wt);return}}},[Gt]),Un=a.useCallback(async Y=>{try{await Ix(e.id,Y,n),_(Ye=>Ye.filter(lt=>lt.filename!==Y)),h("Attachment deleted","info")}catch(Ye){h(xe(Ye),"error")}},[e.id,h]),Jn=a.useCallback(async Y=>{const Ye=Sn;fn(Y);try{const lt=await Ks(e.id,{enabledWorkflowSteps:Y},n);h("Workflow steps updated","success"),m?.(lt)}catch(lt){fn(Ye),h(`Failed to update workflow steps: ${xe(lt)}`,"error")}},[e.id,n,Sn,m,h]),Bn=a.useCallback(async()=>{re(!0);try{const Y=await oa(void 0,n);E(Y),pe(!0)}catch(Y){h(`Failed to load agents: ${xe(Y)}`,"error"),pe(!1)}finally{re(!1)}},[n,h]),Yn=a.useCallback(async Y=>{try{const Ye=await hd(e.id,Y,n),lt=X.find(wt=>wt.id===Y)??null;z(lt||(wt=>wt?.id===Y?wt:null)),pe(!1),m?.(Ye),h("Assigned agent updated","success")}catch(Ye){h(`Failed to assign agent: ${xe(Ye)}`,"error")}},[e.id,n,X,m,h]),un=a.useCallback(async()=>{try{const Y=await hd(e.id,null,n);z(null),pe(!1),m?.(Y),h("Agent unassigned","success")}catch(Y){h(`Failed to unassign agent: ${xe(Y)}`,"error")}},[e.id,n,m,h]),Qn=a.useCallback(async Y=>{const Ye=[...$,Y];I(Ye);try{await Ks(e.id,{dependencies:Ye},n)}catch(lt){I($),h(xe(lt),"error")}},[e.id,$,h]),Es=a.useCallback(async(Y,Ye)=>{Y.stopPropagation();const lt=$.filter(wt=>wt!==Ye);I(lt);try{await Ks(e.id,{dependencies:lt},n)}catch(wt){I($),h(xe(wt),"error")}},[e.id,$,h]),Is=a.useCallback(async Y=>{try{const Ye=await Or(Y,n);r(Ye)}catch{h(`Failed to load dependency ${Y}`,"error")}},[r,h]),rs=a.useCallback(async Y=>{ce(!0);try{await Ks(y.id,{prompt:Y},n),h("Spec updated","success"),v&&(v.prompt=Y)}catch(Ye){throw h(xe(Ye),"error"),Ye}finally{ce(!1)}},[y,v,h]),An=a.useCallback(async Y=>{Q(!0);try{await Ox(e.id,Y,n),h("AI revision requested. Task moved to triage.","success"),i()}catch(Ye){const lt=xe(Ye);lt.includes("in-review")||lt.includes("done")?h("Cannot request revision: Task must be in 'todo' or 'in-progress' column.","error"):h(lt,"error")}finally{Q(!1)}},[e.id,h,i]),bs=a.useCallback(()=>{Te(!0),Se(y.prompt||""),we("")},[y.prompt]),Tn=a.useCallback(()=>{Te(!1),Se(y.prompt||""),we("")},[y.prompt]),ua=a.useCallback(async()=>{if(fe===(y.prompt||"")){Tn();return}await rs(fe),Te(!1)},[fe,y.prompt,rs,Tn]),xo=a.useCallback(async()=>{te.trim()&&await An(te.trim())},[te,An]),vo=a.useCallback(Y=>{Y.key==="Escape"?(Y.preventDefault(),Tn()):Y.key==="Enter"&&(Y.ctrlKey||Y.metaKey)&&(Y.preventDefault(),ua())},[Tn,ua]),mi=s.filter(Y=>Y.id!==e.id&&!$.includes(Y.id)).sort((Y,Ye)=>{const lt=Ye.createdAt.localeCompare(Y.createdAt);if(lt!==0)return lt;const wt=parseInt(Y.id.slice(Y.id.lastIndexOf("-")+1),10)||0;return(parseInt(Ye.id.slice(Ye.id.lastIndexOf("-")+1),10)||0)-wt}),ar=A?.name??e.assignedAgentId??null,rr=a.useMemo(()=>{const Y=[];return y.modelProvider&&Y.push(y.modelProvider),y.validatorModelProvider&&!Y.includes(y.validatorModelProvider)&&Y.push(y.validatorModelProvider),y.planningModelProvider&&!Y.includes(y.planningModelProvider)&&Y.push(y.planningModelProvider),Y},[y.modelProvider,y.validatorModelProvider,y.planningModelProvider]),ei=zl[e.column]||[],yo={"creating-pr":"Creating PR…","awaiting-pr-checks":"Awaiting PR checks","merging-pr":"Merging PR…"},ti=e.status?yo[e.status]:void 0;return t.jsx("div",{className:"modal-overlay open",onClick:et,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg",onDragOver:Cn,onDrop:gs,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:Pn[e.column]})]}),t.jsxs("div",{className:"modal-header-actions",children:[!ye&&Gn&&t.jsx("button",{className:"modal-edit-btn",onClick:dn,title:"Edit task","aria-label":"Edit task",children:t.jsx(Hn,{size:14})}),t.jsx("button",{className:"modal-close",onClick:i,"aria-label":"Close",children:"×"})]})]}),t.jsxs("div",{className:`detail-body${f==="logs"&&j==="agent-log"&&!ye?" detail-body--agent-log":""}`,children:[ye?t.jsx("div",{className:"modal-edit-form",children:t.jsx(Xp,{mode:"edit",title:se,onTitleChange:J,description:me,onDescriptionChange:ee,dependencies:he,onDependenciesChange:le,executorModel:Ie,onExecutorModelChange:Ze,validatorModel:at,onValidatorModelChange:oe,planningModel:Z,onPlanningModelChange:ue,thinkingLevel:Ce,onThinkingLevelChange:$e,presetMode:ve,onPresetModeChange:Ge,selectedPresetId:Je,onSelectedPresetIdChange:st,selectedWorkflowSteps:dt,onWorkflowStepsChange:Tt,pendingImages:Le,onImagesChange:gt,tasks:s.filter(Y=>Y.id!==e.id),projectId:n,disabled:ut,addToast:h,isActive:ye,onAutoSaveDescription:Kn,reviewLevel:je,onReviewLevelChange:Ue,priority:He,onPriorityChange:ge,executionMode:Fe,onExecutionModeChange:be,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:$t,onChange:Y=>Dt(Y.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:Bt,onChange:Y=>qt(Y.target.value),disabled:ut,"data-testid":"task-source-repository-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Issue identifier",value:Lt,onChange:Y=>Ct(Y.target.value),disabled:ut,"data-testid":"task-source-external-id-input"}),t.jsx("input",{type:"url",className:"modal-edit-input",placeholder:"Issue URL",value:xt,onChange:Y=>Et(Y.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 Y=e.title||e.description||e.id,Ye=!S&&Y.length>fl;return t.jsxs(t.Fragment,{children:[t.jsx("h2",{className:"detail-title",children:Ye?Y.slice(0,fl)+"…":Y}),Y.length>fl&&t.jsx("button",{className:"detail-description-toggle",onClick:()=>P(!S),children:S?"Show less":"Show more"})]})})(),t.jsxs("div",{className:"detail-meta",children:["Created ",new Date(e.createdAt).toLocaleDateString()," · Updated"," ",new Date(e.updatedAt).toLocaleDateString()," ·",t.jsxs("span",{className:`detail-priority-chip detail-priority-chip--${ja(e.priority)}`,children:["Priority: ",ja(e.priority)]})]})]}),e.status==="failed"&&e.error&&t.jsxs("div",{className:"detail-error-alert",children:[t.jsx("span",{className:"detail-error-icon",children:"⚠"}),t.jsxs("div",{className:"detail-error-content",children:[t.jsx("div",{className:"detail-error-title",children:"Task Failed"}),t.jsx("div",{className:"detail-error-message",children:e.error})]})]}),!ye&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"detail-tabs",children:[t.jsx("button",{className:`detail-tab${f==="definition"?" detail-tab-active":""}`,onClick:()=>b("definition"),children:"Definition"}),t.jsx("button",{className:`detail-tab${f==="logs"?" detail-tab-active":""}`,onClick:()=>b("logs"),children:"Logs"}),(e.column==="in-progress"||e.column==="in-review"||e.column==="done")&&t.jsx("button",{className:`detail-tab${f==="changes"?" detail-tab-active":""}`,onClick:()=>b("changes"),children:"Changes"}),t.jsx("button",{className:`detail-tab${f==="comments"?" detail-tab-active":""}`,onClick:()=>b("comments"),children:"Comments"}),t.jsx("button",{className:`detail-tab${f==="documents"?" detail-tab-active":""}`,onClick:()=>b("documents"),children:"Documents"}),t.jsx("button",{className:`detail-tab${f==="model"?" detail-tab-active":""}`,onClick:()=>b("model"),children:"Model"}),t.jsx("button",{className:`detail-tab${f==="workflow"?" detail-tab-active":""}`,onClick:()=>b("workflow"),children:"Workflow"}),t.jsx("button",{className:`detail-tab${f==="stats"?" detail-tab-active":""}`,onClick:()=>b("stats"),children:"Stats"}),sn.map((Y,Ye)=>{const lt=`plugin-${Ye}`;return t.jsx("button",{className:`detail-tab${f===lt?" detail-tab-active":""}`,onClick:()=>b(lt),children:Y.slot.label},`plugin-tab-${Y.pluginId}`)})]}),f==="workflow"?t.jsx("div",{className:"detail-section",children:t.jsx(oM,{taskId:e.id,results:Wn,loading:pn,enabledWorkflowSteps:Sn,canEdit:Gn,projectId:n,isTaskInProgress:e.column==="in-progress"&&e.status!=="paused",onWorkflowStepsChange:Jn})}):f==="model"?t.jsx("div",{className:"detail-section",children:t.jsx(HE,{task:e,addToast:h,onTaskUpdated:m,settings:Rt})}):f==="logs"?t.jsxs("div",{className:`detail-section${j==="agent-log"?" detail-section--agent-log":""}`,children:[t.jsxs("div",{className:"log-subview-toggle",children:[t.jsx("button",{className:`log-subview-btn${j==="activity"?" log-subview-btn-active":""}`,onClick:()=>C("activity"),children:"Activity"}),t.jsx("button",{className:`log-subview-btn${j==="agent-log"?" log-subview-btn-active":""}`,onClick:()=>C("agent-log"),children:"Agent Log"})]}),j==="agent-log"?t.jsx(zE,{entries:hs,loading:ps,executorModel:gM(e,Rt),validatorModel:bM(e,Rt),planningModel:vM(e,hs,Rt),hasMore:K,onLoadMore:On,loadingMore:tt,totalCount:ze}):t.jsxs("div",{className:"detail-activity",children:[t.jsx("h4",{children:"Activity"}),y.activityLogTruncatedCount?t.jsxs("div",{className:"detail-log-truncated",children:["Showing the most recent ",y.log.length," activity entries."]}):null,y.log&&y.log.length>0?t.jsx("div",{className:"detail-activity-list",children:[...y.log].reverse().map((Y,Ye)=>t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-timestamp",children:kM(Y.timestamp)}),t.jsx("span",{className:"detail-log-action",children:Y.action})]}),Y.outcome&&t.jsx("div",{className:"detail-log-outcome",children:Y.outcome})]},Ye))}):t.jsx("div",{className:"detail-log-empty",children:"(no activity)"})]})]}):f==="changes"?t.jsx(ZE,{taskId:e.id,worktree:e.worktree,projectId:n,column:e.column,mergeDetails:e.mergeDetails,modifiedFiles:e.modifiedFiles}):f==="comments"?t.jsx(KE,{task:e,addToast:h,projectId:n,onTaskUpdated:m}):f==="documents"?t.jsx(uM,{taskId:e.id,addToast:h,projectId:n,onTaskUpdated:m,canEdit:Gn}):typeof f=="string"&&f.startsWith("plugin-")?t.jsx("div",{className:"detail-section",children:t.jsx(co,{slotId:"task-detail-tab",projectId:n})}):f==="stats"?t.jsx("div",{className:"detail-section",children:t.jsx(fM,{tokenUsage:y.tokenUsage,loading:k,task:y})}):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(Qs,{remarkPlugins:[Xs],children:e.summary})})]}),t.jsx(YE,{task:e}),e.sourceIssue&&t.jsxs("div",{className:"detail-section detail-source-section",children:[t.jsx("h4",{children:"Source Issue"}),t.jsxs("dl",{className:"detail-source-grid",children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Provider"}),t.jsx("dd",{children:e.sourceIssue.provider})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Repository"}),t.jsx("dd",{children:e.sourceIssue.repository})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Issue Identifier"}),t.jsx("dd",{children:e.sourceIssue.externalIssueId})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"URL"}),t.jsx("dd",{children:e.sourceIssue.url?t.jsx("a",{className:"detail-source-link",href:e.sourceIssue.url,target:"_blank",rel:"noopener noreferrer",children:e.sourceIssue.url}):t.jsx("span",{className:"detail-source-empty",children:"(none)"})})]})]})]}),t.jsx("div",{className:"detail-section detail-agent-section",children:t.jsxs("div",{className:"detail-meta-row",children:[t.jsxs("div",{className:"detail-meta-left",children:[rr.length>0&&t.jsx("span",{className:"detail-provider-icons","data-testid":"detail-provider-icons",children:rr.map(Y=>t.jsx(Mn,{provider:Y,size:"sm"},Y))}),t.jsxs("span",{className:"detail-meta-label",children:[t.jsx(an,{size:14,style:{verticalAlign:"middle",marginRight:6}}),"Agent"]})]}),t.jsxs("div",{className:"detail-agent-actions",children:[ar?t.jsxs("span",{className:"detail-agent-chip",children:[t.jsx(an,{size:14}),ar,t.jsx("button",{className:"detail-agent-clear",onClick:()=>void un(),title:"Unassign agent",children:t.jsx(Pt,{size:12})})]}):t.jsx("button",{className:"btn btn-sm",onClick:()=>{U?pe(!1):Bn()},children:"Assign Agent"}),U&&t.jsxs("div",{className:"agent-picker-dropdown",children:[ie&&t.jsx("div",{className:"agent-picker-loading",children:"Loading agents..."}),!ie&&X.filter(Y=>Y.state!=="terminated").map(Y=>t.jsxs("button",{className:`agent-picker-item${e.assignedAgentId===Y.id?" selected":""}`,onClick:()=>void Yn(Y.id),children:[t.jsx(an,{size:14}),t.jsx("span",{className:"agent-picker-name",children:Y.name}),t.jsx("span",{className:"agent-picker-role",children:Y.role})]},Y.id)),!ie&&X.filter(Y=>Y.state!=="terminated").length===0&&t.jsx("div",{className:"agent-picker-empty",children:"No agents available"})]})]})]})}),t.jsxs("div",{className:"detail-section detail-step-progress",children:[t.jsx("h4",{children:"Progress"}),y.steps&&y.steps.length>0?t.jsxs("div",{className:"step-progress-wrapper",children:[t.jsx("div",{className:"step-progress-bar",children:y.steps.map((Y,Ye)=>t.jsx("div",{className:`step-progress-segment step-progress-segment--${Y.status}`,"data-tooltip":`${Y.name} (${Y.status})`,style:{backgroundColor:yM(Y.status)}},Ye))}),t.jsxs("span",{className:"step-progress-label",children:[y.steps.filter(Y=>Y.status==="done").length,"/",y.steps.length," step",y.steps.length===1?"":"s"]})]}):t.jsx("div",{className:"step-progress-empty",children:"(no steps defined)"})]}),t.jsxs("div",{className:"detail-section",children:[!de&&t.jsx("div",{className:"detail-spec-edit-trigger",children:t.jsx("button",{className:"btn btn-sm",onClick:bs,children:"Edit"})}),de?t.jsxs("div",{className:"spec-editor-edit-mode",children:[t.jsx("textarea",{className:"spec-editor-textarea",value:fe,onChange:Y=>Se(Y.target.value),onKeyDown:vo,disabled:F,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:Tn,disabled:F,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void ua(),disabled:fe===(y.prompt||"")||F,children:F?"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 triage for re-specification."}),t.jsx("textarea",{className:"spec-editor-feedback",value:te,onChange:Y=>we(Y.target.value),placeholder:"e.g., 'Add more details about error handling', 'Split this into smaller steps', 'Include tests for the API endpoints'...",disabled:ae,rows:4,maxLength:2e3}),t.jsxs("div",{className:"spec-editor-revision-actions",children:[t.jsxs("span",{className:"spec-editor-char-count",children:[te.length,"/2000"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void xo(),disabled:!te.trim()||ae,children:ae?"Requesting…":"Request AI Revision"})]})]})]}):k?t.jsx("div",{className:"spec-loading",children:"Loading specification…"}):y.prompt?t.jsx("div",{className:"markdown-body",children:t.jsx(Qs,{remarkPlugins:[Xs],children:y.prompt.replace(/^#\s+[^\n]*\n+/,"")})}):t.jsx("div",{className:"detail-prompt",children:"(no prompt)"})]}),t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Attachments"}),T.length>0?t.jsx("div",{className:"detail-attachments-grid",children:T.map(Y=>{const Ye=Hs(`/api/tasks/${e.id}/attachments/${Y.filename}`);return t.jsxs("div",{className:"detail-attachment-card",children:[t.jsx("a",{className:"detail-attachment-link",href:Ye,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{src:Ye,alt:Y.originalName,className:"detail-attachment-image"})}),t.jsxs("div",{className:"detail-attachment-meta",children:[Y.originalName," (",jM(Y.size),")"]}),t.jsx("button",{className:"detail-attachment-delete",onClick:()=>Un(Y.filename),title:"Delete attachment",children:"×"})]},Y.filename)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no attachments)"}),t.jsx("input",{className:"detail-hidden-file-input",ref:_n,type:"file",accept:"image/*",onChange:bn}),t.jsx("button",{className:"btn btn-sm",onClick:()=>_n.current?.click(),disabled:L,children:L?"Uploading…":"Attach Screenshot"})]}),t.jsxs("div",{className:"detail-deps",children:[t.jsx("h4",{children:"Dependencies"}),$.length>0?t.jsx("ul",{className:"detail-dep-list",children:$.map(Y=>{const Ye=s.find(wt=>wt.id===Y),lt=Ye?.title||Ye?.description||Y;return t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>Is(Y),onKeyDown:wt=>{(wt.key==="Enter"||wt.key===" ")&&(wt.preventDefault(),Is(Y))},role:"link",tabIndex:0,title:`Click to view ${Y}`,children:[t.jsx("span",{className:"detail-dep-id",children:Y}),t.jsx("span",{className:"detail-dep-label",children:lm(lt,40)})]}),t.jsx("button",{className:"dep-remove-btn",onClick:wt=>Es(wt,Y),title:`Remove dependency ${Y}`,children:"×"})]},Y)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no dependencies)"}),t.jsxs("div",{className:"dep-trigger-wrap",children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{w&&B(""),q(Y=>!Y)},children:"Add Dependency"}),w&&(()=>{const Y=W.toLowerCase(),Ye=Y?mi.filter(lt=>lt.id.toLowerCase().includes(Y)||lt.title&<.title.toLowerCase().includes(Y)||lt.description&<.description.toLowerCase().includes(Y)):mi;return t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:W,onChange:lt=>B(lt.target.value),onClick:lt=>lt.stopPropagation()}),Ye.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Ye.map(lt=>t.jsxs("div",{className:"dep-dropdown-item",onClick:()=>{Qn(lt.id),q(!1)},children:[t.jsx("span",{className:"dep-dropdown-id",children:lt.id}),t.jsx("span",{className:"dep-dropdown-title",children:lm(lt.title||lt.description||lt.id,30)})]},lt.id))]})})()]})]}),e.column==="in-review"&&t.jsx(VE,{taskId:e.id,projectId:n,prInfo:e.prInfo,automationStatus:e.status??null,autoMerge:Rt?.autoMerge??!1,prAuthAvailable:g??!1,onPrCreated:Y=>{e.prInfo=Y,h(`PR #${Y.number} created`,"success")},onPrUpdated:Y=>{e.prInfo=Y},addToast:h})]})]})]}),t.jsx("div",{className:"modal-actions",children:ye?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:Mt,disabled:ut,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:yn,disabled:ut,children:ut?"Saving…":"Save"})]}):t.jsxs(t.Fragment,{children:[e.column==="triage"&&e.status==="awaiting-approval"&&y.prompt&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:vt,children:"Approve Plan"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:ct,children:"Reject Plan"})]}),e.column==="triage"&&e.status!=="awaiting-approval"&&!R&&t.jsx("button",{className:"btn btn-sm btn-danger",onClick:jt,"aria-label":"Delete task",title:"Delete task",children:"Delete"}),(e.column!=="triage"||e.status==="awaiting-approval"||R)&&t.jsxs("div",{className:"detail-actions-dropdown",ref:kt,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>{Ae(Y=>!Y),N(!1)},"aria-haspopup":"menu","aria-expanded":H,children:["Actions",t.jsx(zt,{size:12})]}),H&&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:()=>bt(jt),children:"Delete"}),d&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>bt(fs),children:"Duplicate"}),(e.column==="done"||e.column==="in-review")&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>bt(Ee),children:"Refine"}),t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>bt(ne),children:"Respecify"}),R&&u&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>bt(gn),children:"Retry"}),e.column!=="done"&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>bt(Qt),children:e.paused?"Unpause":"Pause"})]})]}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("div",{className:"detail-move-dropdown",ref:ot,children:e.column==="in-review"?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"detail-move-actions-in-review",children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>{N(Y=>!Y),Ae(!1)},"aria-haspopup":"menu","aria-expanded":rt,children:["Move",t.jsx(zt,{size:12})]}),ti?t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!0,children:ti}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:on,children:"Merge & Close"})]}),rt&&t.jsxs("div",{className:"detail-move-menu",role:"menu",children:[t.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>ft("todo"),children:"Move to Todo"}),t.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>ft("in-progress"),children:"Back to In Progress"})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>ft(ei[0]),disabled:ei.length===0,children:["Move to ",ei.length>0?Pn[ei[0]]:""]}),ei.length>1&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{N(Y=>!Y),Ae(!1)},"aria-haspopup":"menu","aria-expanded":rt,children:t.jsx(zt,{size:12})}),rt&&t.jsx("div",{className:"detail-move-menu",role:"menu",children:ei.map(Y=>t.jsxs("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>ft(Y),children:["Move to ",Pn[Y]]},Y))})]})]})})]})}),Pe&&t.jsx("div",{className:"modal-overlay open detail-refine-overlay",onClick:Xt,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal detail-refine-modal",onClick:Y=>Y.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{className:"detail-refine-title",children:"Refine"}),t.jsx("button",{className:"modal-close",onClick:Xt,"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:Ke,onChange:Y=>Ne(Y.target.value),placeholder:"Enter your feedback here...",rows:6,maxLength:2e3,autoFocus:!0}),t.jsxs("div",{className:"detail-refine-input-group",children:[t.jsxs("div",{className:"detail-refine-char-count",children:[Ke.length,"/2000 characters"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:cn,disabled:!Ke.trim()||_e,children:_e?"Creating...":"Create Refinement Task"})]})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:Xt,disabled:_e,children:"Cancel"})})]})})]})})}const EM=640;function MM({isOpen:e,onClose:n,onImport:s,tasks:i,projectId:r}){const[o,l]=a.useState(""),[c,u]=a.useState(""),[d,m]=a.useState(""),[h,g]=a.useState(!1),[p,f]=a.useState("issues"),[b,v]=a.useState([]),[x,k]=a.useState(null),[M,y]=a.useState([]),[R,j]=a.useState(null),[C,S]=a.useState(null),[P,T]=a.useState(!1),[_,L]=a.useState([]),[G,$]=a.useState(!1),[I,w]=a.useState(""),q=a.useRef(!1),[W,B]=a.useState(!1),[A,z]=a.useState("list"),X=a.useRef(null),E=new Set;for(const ee of i){const he=ee.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);he&&E.add(he[1]);const le=ee.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);le&&E.add(le[1])}a.useEffect(()=>{if(e)return l(""),u(""),m(""),v([]),k(null),y([]),j(null),f("issues"),S(null),T(!1),L([]),$(!0),w(""),X.current=null,q.current=!0,ev().then(ee=>{if(q.current)if(L(ee),$(!1),ee.length===1){const he=ee[0];l(he.owner),u(he.repo),w(he.name)}else ee.length>1&&(l(""),u(""),w(""))}).catch(()=>{q.current&&$(!1)}),()=>{q.current=!1}},[e]);const U=a.useCallback(ee=>{if(w(ee),ee==="")l(""),u("");else{const he=_.find(le=>le.name===ee);he&&(l(he.owner),u(he.repo))}},[_]),pe=a.useCallback(async()=>{if(!o.trim()||!c.trim()){S("Repository must be selected");return}g(!0),S(null),v([]),k(null);try{const ee=d.split(",").map(le=>le.trim()).filter(Boolean),he=await Yx(o.trim(),c.trim(),30,ee.length>0?ee:void 0);v(he),he.length===0&&S("No open issues found")}catch(ee){S(xe(ee)||"Failed to fetch issues")}finally{g(!1)}},[o,c,d]),ie=a.useCallback(async()=>{if(!o.trim()||!c.trim()){S("Repository must be selected");return}g(!0),S(null),y([]),j(null);try{const ee=await Xx(o.trim(),c.trim(),30);y(ee),ee.length===0&&S("No open pull requests found")}catch(ee){S(xe(ee)||"Failed to fetch pull requests")}finally{g(!1)}},[o,c]);a.useEffect(()=>{if(!e||!o.trim()||!c.trim()||h||P)return;const ee={owner:o.trim(),repo:c.trim(),labels:d.trim(),tab:p};X.current?.owner===ee.owner&&X.current?.repo===ee.repo&&X.current?.labels===ee.labels&&X.current?.tab===ee.tab||(X.current=ee,p==="issues"?pe():ie())},[o,c,d,p,e,h,P,pe,ie]),a.useEffect(()=>{if(!e)return;const ee=he=>{he.key==="Escape"&&n()};return document.addEventListener("keydown",ee),()=>document.removeEventListener("keydown",ee)},[e,n]),a.useEffect(()=>{if(!e)return;const ee=()=>{B(window.innerWidth<=EM)};return ee(),window.addEventListener("resize",ee),()=>window.removeEventListener("resize",ee)},[e]);const re=a.useCallback(ee=>{k(ee),W&&z("preview")},[W]),F=a.useCallback(ee=>{j(ee),W&&z("preview")},[W]),ce=a.useCallback(()=>{z("list")},[]),ae=a.useCallback(async()=>{if(p==="issues"){if(x===null)return;T(!0),S(null);try{const ee=await Qx(o.trim(),c.trim(),x,r);s(ee),n()}catch(ee){const he=xe(ee);he?.includes("already imported")?S(he):S(he||"Failed to import issue")}finally{T(!1)}}else{if(R===null)return;T(!0),S(null);try{const ee=await Zx(o.trim(),c.trim(),R,r);s(ee),n()}catch(ee){const he=xe(ee);he?.includes("already imported")?S(he):S(he||"Failed to import pull request")}finally{T(!1)}}},[p,x,R,o,c,s,n]),Q=b.find(ee=>ee.number===x),de=M.find(ee=>ee.number===R);if(!e)return null;const Te=_.length>0,fe=_.length===1,Se=b.filter(ee=>E.has(ee.html_url)).length,te=M.filter(ee=>E.has(ee.html_url)).length,we=C==="No open issues found",Pe=C==="No open pull requests found",We=p==="issues"?we:Pe,Ke=!!C&&!we&&b.length===0&&!h,Ne=!!C&&!Pe&&M.length===0&&!h,_e=p==="issues"?Ke:Ne,Oe=h||b.length>0||we||Ke,ye=h||M.length>0||Pe||Ne,De=p==="issues"?Oe:ye,se=!!C&&b.length>0&&!we,J=!!C&&M.length>0&&!Pe,me=p==="issues"?se:J;return t.jsx("div",{className:"modal-overlay open",onClick:ee=>ee.target===ee.currentTarget&&n(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg github-import-modal",children:[t.jsxs("div",{className:"modal-header github-import-modal__header",children:[t.jsxs("div",{children:[t.jsx("h3",{children:"Import from GitHub"}),t.jsx("p",{className:"github-import-modal__subtitle",children:"Choose a detected remote, load open issues or pull requests, and import one into the board."})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close import modal",children:"×"})]}),t.jsxs("div",{className:"modal-body github-import-modal__body",children:[t.jsxs("div",{className:"github-import-tabs",role:"tablist","aria-label":"Import type",children:[t.jsxs("button",{role:"tab","aria-selected":p==="issues","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="issues"?"active":""}`,onClick:()=>{f("issues"),j(null)},disabled:h||P,children:[t.jsx(eo,{size:16}),t.jsx("span",{children:"Issues"})]}),t.jsxs("button",{role:"tab","aria-selected":p==="pulls","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="pulls"?"active":""}`,onClick:()=>{f("pulls"),k(null)},disabled:h||P,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(it,{size:16,className:"spin"}),t.jsx("span",{children:"Detecting…"})]}):Te?fe?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:_[0].name}),t.jsxs("span",{className:"github-import-remote-pill__repo",children:[_[0].owner,"/",_[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:I,onChange:ee=>U(ee.target.value),disabled:h||P,"aria-label":"Select Git remote",children:[t.jsx("option",{value:"",children:"Select remote…"}),_.map(ee=>t.jsxs("option",{value:ee.name,children:[ee.name," (",ee.owner,"/",ee.repo,")"]},ee.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:ee=>m(ee.target.value),onKeyDown:ee=>ee.key==="Enter"&&pe(),disabled:h||P||!Te,"aria-label":"Filter issues by labels"})]}):t.jsxs("span",{className:"github-import-filter-hint",children:["Open pull requests from ",o||"selected remote"]})}),t.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--action",children:t.jsxs("button",{id:"gh-load",className:"btn btn-primary github-import-load-button",onClick:p==="issues"?pe:ie,disabled:h||P||!o.trim()||!c.trim(),"aria-label":h?`Loading ${p}`:`Load ${p} from repository`,title:h?"Loading…":`Load ${p}`,children:[h?t.jsx(it,{size:14,className:"spin"}):t.jsx(hn,{size:14}),t.jsx("span",{children:h?"Loading…":"Load"})]})})]}),!G&&!Te&&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"})]}),me&&t.jsx("div",{className:"form-error github-import-banner",role:"alert",children:C}),t.jsxs("div",{className:"github-import-workspace",children:[t.jsxs("section",{className:`github-import-list-pane ${W?"mobile":""} ${A==="list"?"active":""}`,"data-testid":"github-import-list-pane","aria-labelledby":"github-import-results-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[t.jsx("h4",{id:"github-import-results-heading",children:p==="issues"?"Issues":"Pull Requests"}),p==="issues"&&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:[Se," imported"]})]}),p==="pulls"&&M.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[M.length," pull request",M.length===1?"":"s"]}),t.jsxs("span",{children:[te," imported"]})]})]}),t.jsxs("div",{className:"github-import-pane-content",children:[!De&&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(it,{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:C})]})}),We&&t.jsx("div",{className:"github-import-state github-import-state--empty",role:"status",children:t.jsxs("div",{children:[t.jsxs("strong",{children:["No open ",p==="issues"?"issues":"pull requests"," found"]}),t.jsx("span",{children:p==="issues"?"Try a different label filter or choose another repository.":"Choose another repository."})]})}),p==="issues"&&b.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:b.map(ee=>{const he=E.has(ee.html_url);return t.jsxs("div",{className:`issue-item ${x===ee.number?"selected":""} ${he?"imported":""}`,onClick:()=>!he&&re(ee.number),children:[t.jsx("input",{type:"radio",name:"issue",checked:x===ee.number,onChange:()=>re(ee.number),disabled:he,"aria-label":`Select issue #${ee.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",ee.number]}),t.jsx("span",{className:"issue-title",children:ee.title})]}),ee.labels.length>0&&t.jsx("span",{className:"issue-labels",children:ee.labels.map(le=>t.jsx("span",{className:"label-chip",children:le.name},le.name))})]}),he&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},ee.number)})}),p==="pulls"&&M.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:M.map(ee=>{const he=E.has(ee.html_url);return t.jsxs("div",{className:`issue-item ${R===ee.number?"selected":""} ${he?"imported":""}`,onClick:()=>!he&&F(ee.number),children:[t.jsx("input",{type:"radio",name:"pull",checked:R===ee.number,onChange:()=>F(ee.number),disabled:he,"aria-label":`Select pull request #${ee.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",ee.number]}),t.jsx("span",{className:"issue-title",children:ee.title})]}),t.jsxs("span",{className:"pull-branch-info",children:[ee.headBranch," → ",ee.baseBranch]})]}),he&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},ee.number)})})]})]}),t.jsxs("section",{className:`github-import-preview-pane ${W?"mobile":""} ${A==="preview"?"active":""}`,"data-testid":"github-import-preview-pane","aria-labelledby":"github-import-preview-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[W&&t.jsxs("button",{className:"github-import-back-button",onClick:ce,"data-testid":"github-import-back-button","aria-label":`Back to ${p==="issues"?"issues":"pull requests"} list`,children:[t.jsx(ia,{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"&&Q?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Issue #",Q.number]}),t.jsx("div",{className:"preview-title",children:Q.title}),t.jsx("div",{className:"preview-body",children:Q.body?Q.body.slice(0,200)+(Q.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:P,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:ae,disabled:(p==="issues"?x===null:R===null)||P,children:P?t.jsx(it,{size:14,className:"spin"}):"Import"})]})]})})}const _M=["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 AM(e,n){return e&&n?`${e}/${n}`:""}function TM(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 RM({isOpen:e,onClose:n,onTaskCreated:s,onTasksCreated:i,tasks:r,initialPlan:o,projectId:l,resumeSessionId:c}){const[u,d]=a.useState(""),[m,h]=a.useState({type:"initial"}),[g,p]=a.useState(null),[f,b]=a.useState([]),[v,x]=a.useState([]),[k,M]=a.useState(null),y=a.useRef(!1),R=a.useRef(!1),[j,C]=a.useState(""),[S,P]=a.useState(!0),[T,_]=a.useState(!1),[L,G]=a.useState(!1),$=a.useRef(null),I=a.useRef(null),w=a.useRef(null),[q,W]=a.useState(c??null),B=a.useMemo(()=>_i(),[]),{isLockedByOther:A,takeControl:z,isLoading:X}=mo(e?q:null),{activeTabMap:E,broadcastUpdate:U,broadcastCompleted:pe,broadcastLock:ie,broadcastUnlock:re,broadcastHeartbeat:F}=la(),[ce,ae]=a.useState(void 0),[Q,de]=a.useState(void 0),[Te,fe]=a.useState([]),[Se,te]=a.useState(!1),[we,Pe]=a.useState(null),[We,Ke]=a.useState([]),[Ne,_e]=a.useState([]),Oe=a.useRef(null),ye=AM(ce,Q),De=a.useCallback((ge,Fe)=>{if(!ge||!Fe)return"Using default";const be=Te.find(Je=>Je.provider===ge&&Je.id===Fe);return be?`${be.provider}/${be.id}`:`${ge}/${Fe}`},[Te]),se=a.useCallback(async()=>{te(!0),Pe(null);try{const ge=await is();fe(ge.models),Ke(ge.favoriteProviders),_e(ge.favoriteModels)}catch(ge){Pe(xe(ge)||"Failed to load models")}finally{te(!1)}},[]),J=a.useCallback(ge=>{Ke(Fe=>{const be=Fe,st=be.includes(ge)?be.filter(dt=>dt!==ge):[ge,...be];return nn({favoriteProviders:st,favoriteModels:Ne}).catch(()=>{Ke(be)}),st})},[Ne]),me=a.useCallback(ge=>{_e(Fe=>{const be=Fe,st=be.includes(ge)?be.filter(dt=>dt!==ge):[ge,...be];return nn({favoriteProviders:We,favoriteModels:st}).catch(()=>{_e(be)}),st})},[We]),ee=a.useCallback(ge=>{I.current?.close();const Fe=Xv(ge,l,{onThinking:be=>{C(Je=>Je+be),U({sessionId:ge,status:"generating",needsInput:!1,owningTabId:B,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onQuestion:be=>{_(!1),G(!1),Li(l),h({type:"question",session:{sessionId:ge,currentQuestion:be,summary:null}}),C(""),U({sessionId:ge,status:"awaiting_input",needsInput:!0,owningTabId:B,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onSummary:be=>{_(!1),G(!1),Li(l),h({type:"summary",session:{sessionId:ge,currentQuestion:null,summary:be},summary:be}),M(be),C(""),U({sessionId:ge,status:"complete",needsInput:!1,owningTabId:B,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onError:be=>{const Je=be||"Session failed while contacting the AI.";_(!0),(async()=>{try{const st=await Js(ge);if(st&&(st.status==="generating"||st.status==="awaiting_input")){ee(ge);return}}catch{}_(!1),G(!1),p(null),h(st=>st.type==="question"||st.type==="summary"||st.type==="error"?{type:"error",session:st.session,errorMessage:Je}:{type:"error",session:{sessionId:ge,currentQuestion:null,summary:null},errorMessage:Je}),C(""),w.current=ge,U({sessionId:ge,status:"error",needsInput:!1,owningTabId:B,type:"planning",title:u.trim()||"Planning session",projectId:l??null}),pe({sessionId:ge,status:"error"})})()},onComplete:()=>{_(!1),G(!1),w.current=null,pe({sessionId:ge,status:"complete"})},onConnectionStateChange:be=>{_(be==="reconnecting")}});I.current=Fe},[pe,U,u,l,B]),he=a.useCallback(async ge=>{const Fe=ge??u;if(Fe.trim()){p(null),C(""),x([]),b([]),_(!1),h({type:"loading"});try{const be=ce&&Q?{planningModelProvider:ce,planningModelId:Q}:void 0,{sessionId:Je}=await Dv(Fe.trim(),l,be);w.current=Je,W(Je),ee(Je),b([])}catch(be){_(!1),p(xe(be)||"Failed to start planning session"),h({type:"initial"}),w.current=null,W(null)}}},[ee,u,Q,ce,l]);a.useEffect(()=>{e&&m.type==="initial"&&$.current?.focus()},[e,m.type]),a.useEffect(()=>{e&&se()},[e,se]),a.useEffect(()=>{if(e&&o&&!y.current&&m.type==="initial"){d(o);const ge=setTimeout(()=>{y.current=!0,he(o)},0);return()=>clearTimeout(ge)}else if(e&&!o&&!y.current&&!R.current&&m.type==="initial"){R.current=!0;const ge=Aw(l);ge&&d(ge)}},[e,o,m.type,he,l]),a.useEffect(()=>{if(!e||!c||m.type!=="initial")return;let ge=!1;return(async()=>{try{const Fe=await Js(c);if(ge||!Fe)return;w.current=c,W(c);const be=Yi(Fe.conversationHistory);if(x(be),b(be.map(Je=>Je.response).filter(Je=>!!(Je&&typeof Je=="object"&&!Array.isArray(Je)))),Fe.status==="awaiting_input"&&Fe.currentQuestion){Li(l);const Je=JSON.parse(Fe.currentQuestion);h({type:"question",session:{sessionId:c,currentQuestion:Je,summary:null}}),Fe.thinkingOutput&&C(Fe.thinkingOutput),ee(c)}else if(Fe.status==="complete"&&Fe.result){Li(l);const Je=JSON.parse(Fe.result);h({type:"summary",session:{sessionId:c,currentQuestion:null,summary:Je},summary:Je}),M(Je)}else Fe.status==="generating"?(h({type:"loading"}),Fe.thinkingOutput&&C(Fe.thinkingOutput),ee(c)):Fe.status==="error"&&(p(null),h({type:"error",session:{sessionId:c,currentQuestion:null,summary:null},errorMessage:Fe.error||"Session failed"}))}catch{p("Failed to resume session")}})(),()=>{ge=!0}},[ee,e,c,m.type,l]),a.useEffect(()=>{e||(y.current=!1,R.current=!1,_(!1),G(!1),W(null))},[e]),a.useEffect(()=>{if(!e){Oe.current&&(re(Oe.current,B),Oe.current=null);return}if(q&&Oe.current!==q){Oe.current&&re(Oe.current,B),ie(q,B),Oe.current=q;return}!q&&Oe.current&&(re(Oe.current,B),Oe.current=null)},[ie,re,e,q,B]),a.useEffect(()=>{if(!e||!q||Oe.current!==q)return;F(B);const ge=setInterval(()=>{F(B)},3e4);return()=>{clearInterval(ge)}},[F,e,q,B]),a.useEffect(()=>()=>{I.current?.close(),I.current=null,Oe.current&&(re(Oe.current,B),Oe.current=null)},[re,B]),a.useEffect(()=>{if(!e)return;const ge=()=>{I.current?.close(),I.current=null};return window.addEventListener("beforeunload",ge),()=>window.removeEventListener("beforeunload",ge)},[e]);const le=a.useCallback(()=>{I.current?.close(),I.current=null,n()},[n]),Ie=a.useCallback(()=>{let ge=null;m.type==="question"||m.type==="summary"||m.type==="error"?ge=m.session.sessionId:m.type==="breakdown"?ge=m.sessionId:m.type==="loading"&&(ge=w.current),u&&_w(u,l),I.current?.close(),I.current=null,ge&&gh(ge,l,B).catch(()=>{}),d(""),h({type:"initial"}),p(null),b([]),x([]),M(null),C(""),_(!1),G(!1),ae(void 0),de(void 0),w.current=null,W(null),n()},[u,n,l,B,m]);a.useEffect(()=>{if(!e)return;const ge=Fe=>{Fe.key==="Escape"&&Ie()};return document.addEventListener("keydown",ge),()=>document.removeEventListener("keydown",ge)},[e,Ie]);const Ze=a.useCallback(async ge=>{if(m.type!=="question")return;const{session:Fe}=m,be=Fe.sessionId,Je=Fe.currentQuestion;if(!Je){p("No active question in session");return}p(null),b(st=>[...st,ge]),x(st=>[...st,{question:Je,response:ge}]),h({type:"loading"}),C("");try{await Lv(be,ge,l,B)}catch(st){p(xe(st)||"Failed to submit response"),h({type:"question",session:Fe})}},[l,B,m]),at=a.useCallback(async()=>{if(m.type!=="error")return;const ge=m.session;p(null),G(!0),C(""),h({type:"loading"}),ee(ge.sessionId);try{w.current=ge.sessionId,W(ge.sessionId),await zv(ge.sessionId,l,B)}catch(Fe){let be=Fe;if((xe(Fe)||"").includes("not in an error state"))try{const st=await Js(ge.sessionId);if(!st)throw new Error("Failed to refresh planning session.");if(w.current=st.id,W(st.id),st.status==="generating")C(st.thinkingOutput??""),h({type:"loading"});else if(st.status==="awaiting_input"){if(!st.currentQuestion)throw new Error("Planning session is awaiting input but has no current question.");const dt=JSON.parse(st.currentQuestion);Li(l),h({type:"question",session:{sessionId:st.id,currentQuestion:dt,summary:null}}),I.current?.isConnected()||ee(st.id)}else if(st.status==="complete"){if(!st.result)throw new Error("Planning session is complete but has no result.");const dt=JSON.parse(st.result);Li(l),h({type:"summary",session:{sessionId:st.id,currentQuestion:null,summary:dt},summary:dt}),M(dt)}else st.status==="error"&&h({type:"error",session:{sessionId:st.id,currentQuestion:null,summary:null},errorMessage:st.error||"Retry failed. Please try again."});_(!1);return}catch(st){be=st}I.current?.close(),I.current=null,h({type:"error",session:ge,errorMessage:xe(be)||"Retry failed. Please try again."}),_(!1)}finally{G(!1)}},[ee,l,B,m]),oe=a.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const ge=await Fv(m.session.sessionId,k??void 0,l);s(ge),Ie()}catch(ge){p(xe(ge)||"Failed to create task"),h({type:"summary",session:m.session,summary:m.summary})}}},[k,m,l,s,Ie]),Z=a.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const ge=await Ov(m.session.sessionId,k??void 0,l);W(ge.sessionId),h({type:"breakdown",sessionId:ge.sessionId,subtasks:ge.subtasks,dirty:!1})}catch(ge){p(xe(ge)||"Failed to start breakdown"),h({type:"summary",session:m.session,summary:m.summary})}}},[k,m,l]),ue=a.useCallback(async()=>{if(m.type==="breakdown"){p(null),h({type:"creating"});try{const ge=await Uv(m.sessionId,m.subtasks,l);i(ge.tasks),d(""),h({type:"initial"}),p(null),b([]),x([]),M(null),C(""),ae(void 0),de(void 0),w.current=null,W(null),n()}catch(ge){p(xe(ge)||"Failed to create tasks"),h({type:"breakdown",sessionId:m.sessionId,subtasks:m.subtasks,dirty:m.dirty})}}},[m,i,n,l]),Ce=a.useCallback(()=>{if(m.type==="question"&&f.length>0){const ge=f.slice(0,-1);b(ge),h({type:"question",session:m.session})}},[m,f]),$e=()=>m.type==="question"?Math.min(f.length+1,3):3,ve=m.type==="loading"||m.type==="question"||m.type==="summary"||m.type==="error",Ge=q?E.get(q):null,je=Ge&&Ge.tabId!==B,Ue=!!(je&&!Ge.stale),He=A&&(!je||Ge.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:ge=>ge.target===ge.currentTarget&&Ie(),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(Us,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Planning Mode"})]}),t.jsxs("div",{className:"modal-header-actions",children:[ve&&t.jsx("button",{className:"modal-send-to-background",onClick:le,title:"Send to background","aria-label":"Send to background",children:t.jsx(aa,{size:16})}),t.jsx("button",{className:"modal-close",onClick:Ie,"aria-label":"Close",children:t.jsx(Pt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[g&&t.jsx("div",{className:"form-error planning-error",children:g}),T&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Ue&&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(Dn,{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:$,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:ge=>d(ge.target.value),onKeyDown:ge=>{ge.key==="Enter"&&!ge.shiftKey&&u.trim()&&(ge.preventDefault(),he())}})]}),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:_M.map((ge,Fe)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>d(ge),children:ge.length>40?ge.slice(0,40)+"...":ge},Fe))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"planning-modal-model",className:"form-label",children:["Planning Model",Se&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(wn,{id:"planning-modal-model",label:"Planning Model",value:ye,onChange:ge=>{const{provider:Fe,modelId:be}=TM(ge);ae(Fe),de(be)},models:Te,disabled:Se,favoriteProviders:We,onToggleFavorite:J,favoriteModels:Ne,onToggleModelFavorite:me}),we&&t.jsxs("div",{className:"form-hint form-hint-error",children:[we," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{se()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${ce&&Q?"model-badge-custom":"model-badge-default"}`,children:De(ce,Q)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>he(),disabled:!u.trim(),children:[t.jsx(Us,{size:16,className:"icon-mr-8"}),"Start Planning"]})})]}),m.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(it,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:j?"AI is thinking...":"Generating next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>P(!S),type:"button",children:S?"Hide thinking":"Show thinking"}),S&&j&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:j})})]})]}),m.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[v.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Cs,{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 at(),disabled:L,children:[L?t.jsx(it,{size:14,className:"spin"}):t.jsx(hn,{size:14}),t.jsx("span",{className:"icon-ml-6",children:L?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Ie,disabled:L,children:"Dismiss"})]})]})]})}),m.type==="creating"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(it,{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(IM,{question:m.session.currentQuestion,progress:$e(),historyEntries:v,onSubmit:Ze,onBack:f.length>0?Ce:void 0})}),m.type==="summary"&&k&&t.jsx(PM,{summary:k,historyEntries:v,onSummaryChange:M,tasks:r,onCreateTask:oe,onBreakIntoTasks:Z,onRefine:()=>{h({type:"question",session:m.session})},isLoading:!1}),m.type==="breakdown"&&t.jsx(DM,{subtasks:m.subtasks,dirty:m.dirty,isLoading:!1,onUpdateSubtasks:ge=>h({...m,subtasks:ge,dirty:!0}),onCreateTasks:ue,onBack:()=>{const Fe={sessionId:m.sessionId,currentQuestion:null,summary:k??null};k&&h({type:"summary",session:Fe,summary:k})}}),A&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(so,{size:16}),t.jsx("span",{children:He?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),He&&t.jsx("button",{type:"button",onClick:()=>{z()},disabled:X,className:"btn btn-primary session-lock-take-control",children:X?"Taking control...":"Take Control"})]})})]})]})}):null}function IM({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(Cs,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3].map(h=>t.jsx("div",{className:`planning-progress-step ${h<=n?"active":""}`},h))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~3"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:c,onChange:h=>u(h.target.value),onKeyDown:h=>{h.key==="Enter"&&!h.shiftKey&&c.trim()&&(h.preventDefault(),d())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(h=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:h.id,checked:o[e.id]===h.id,onChange:()=>l({[e.id]:h.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:h.label}),h.description&&t.jsx("span",{className:"planning-option-desc",children:h.description})]})]},h.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(h=>{const g=o[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:h.id,checked:g.includes(h.id),onChange:p=>{const f=p.target.checked?[...g,h.id]:g.filter(b=>b!==h.id);l({[e.id]:f})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:h.label}),h.description&&t.jsx("span",{className:"planning-option-desc",children:h.description})]})]},h.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!0?"selected":""}`,onClick:()=>l({[e.id]:!0}),children:[t.jsx(tn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!1?"selected":""}`,onClick:()=>l({[e.id]:!1}),children:[t.jsx(Pt,{size:18}),"No"]})]})]})]})]})]}),t.jsxs("div",{className:"planning-actions",children:[r&&t.jsxs("button",{className:"btn",onClick:r,children:[t.jsx(ia,{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(Ga,{size:16,className:"icon-ml-4"})]})]})]})}function PM({summary:e,historyEntries:n,onSummaryChange:s,tasks:i,onCreateTask:r,onBreakIntoTasks:o,onRefine:l,isLoading:c}){const[u,d]=a.useState(!1),[m,h]=a.useState(e.suggestedDependencies),g=p=>{const f=m.includes(p)?m.filter(b=>b!==p):[...m,p];h(f),s({...e,suggestedDependencies:f})};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Cs,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(tn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Planning Complete!"}),t.jsx("p",{className:"text-muted",children:"Review and refine your task before creating it."})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{children:["Description",t.jsx("button",{type:"button",className:"planning-expand-btn",onClick:()=>d(!u),children:u?"Collapse":"Expand"})]}),t.jsx("textarea",{className:`planning-textarea ${u?"expanded":""}`,rows:u?10:4,value:e.description,onChange:p=>s({...e,description:p.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Suggested Size"}),t.jsxs("select",{className:"planning-size-select",value:e.suggestedSize,onChange:p=>s({...e,suggestedSize:p.target.value}),disabled:c,children:[t.jsx("option",{value:"S",children:"S (Small)"}),t.jsx("option",{value:"M",children:"M (Medium)"}),t.jsx("option",{value:"L",children:"L (Large)"})]})]}),i.length>0&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Suggested Dependencies"}),t.jsx("div",{className:"planning-deps-list",children:i.map(p=>t.jsxs("label",{className:`planning-dep-chip ${m.includes(p.id)?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:m.includes(p.id),onChange:()=>g(p.id)}),t.jsx("span",{className:"planning-dep-id",children:p.id}),t.jsx("span",{className:"planning-dep-title",children:p.title||p.description.slice(0,30)})]},p.id))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Key Deliverables"}),t.jsx("ul",{className:"planning-deliverables",children:e.keyDeliverables.map((p,f)=>t.jsx("li",{children:p},f))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:l,disabled:c,children:[t.jsx(ia,{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(it,{size:16,className:"spin icon-mr-8"}),"Breaking down..."]}):t.jsxs(t.Fragment,{children:[t.jsx(no,{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(it,{size:16,className:"spin icon-mr-8"}),"Creating..."]}):t.jsxs(t.Fragment,{children:[t.jsx(tn,{size:16,className:"icon-mr-8"}),"Create Task"]})})]})]})]})}function dm(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 $M(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function DM({subtasks:e,dirty:n,isLoading:s,onUpdateSubtasks:i,onCreateTasks:r,onBack:o}){const[l,c]=a.useState(null),[u,d]=a.useState(null),[m,h]=a.useState(null),g=a.useRef([]),p=a.useMemo(()=>e.length===0||e.some(C=>!C.title.trim())?!0:dm(e),[e]),f=a.useCallback((C,S)=>{i(e.map(P=>P.id===C?{...P,...S}:P))},[e,i]),b=a.useCallback(()=>{i([...e,$M(e.length+1)])},[e,i]),v=a.useCallback(C=>{i(e.filter(S=>S.id!==C).map(S=>({...S,dependsOn:S.dependsOn.filter(P=>P!==C)})))},[e,i]),x=a.useCallback((C,S)=>{if(S<0||S>=e.length)return;const P=[...e],[T]=P.splice(C,1);P.splice(S,0,T),i(P)},[e,i]),k=a.useCallback(C=>S=>{c(C),S.dataTransfer.setData("text/plain",C),S.dataTransfer.effectAllowed="move"},[]),M=a.useCallback(()=>{c(null),d(null),h(null)},[]),y=a.useCallback(C=>S=>{if(S.preventDefault(),C===l)return;const P=S.currentTarget.getBoundingClientRect(),T=P.top+P.height/2,_=S.clientY<T?"before":"after";d(C),h(_)},[l]),R=a.useCallback(C=>S=>{S.preventDefault();const P=S.dataTransfer.getData("text/plain");if(!P||P===C){M();return}const T=e.findIndex(I=>I.id===P),_=e.findIndex(I=>I.id===C);if(T===-1||_===-1){M();return}const L=[...e],[G]=L.splice(T,1);let $=_;m==="after"&&T<_&&$--,m==="after"&&$++,L.splice($,0,G),i(L),M()},[e,m,i,M]),j=a.useCallback(C=>{const S=C.currentTarget.getBoundingClientRect(),P=C.clientX,T=C.clientY;(P<S.left||P>S.right||T<S.top||T>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(no,{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((C,S)=>{const P=l===C.id,T=u===C.id,_=["task-detail-section","subtask-item",P?"subtask-item-dragging":"",T?"subtask-item-drop-target":"",T&&m==="before"?"subtask-item-drop-before":"",T&&m==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:_,"data-testid":`subtask-item-${S}`,draggable:!s,onDragStart:k(C.id),onDragEnd:M,onDragOver:y(C.id),onDrop:R(C.id),onDragLeave:j,children:[t.jsxs("div",{className:"detail-title-row subtask-item-header subtask-item-header--between",children:[t.jsxs("div",{className:"subtask-drag-handle",title:"Drag to reorder",children:[t.jsx(oc,{size:16}),t.jsx("strong",{children:C.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(yi,{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(Wa,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>v(C.id),disabled:s,children:[t.jsx(Ht,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:L=>{g.current[S]=L},value:C.title,onChange:L=>f(C.id,{title:L.target.value}),onKeyDown:L=>{L.key==="Enter"&&(L.preventDefault(),S<e.length-1&&g.current[S+1]?.focus())},disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:C.description,onChange:L=>f(C.id,{description:L.target.value}),disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Size"}),t.jsxs("select",{className:"planning-size-select",value:C.suggestedSize,onChange:L=>f(C.id,{suggestedSize:L.target.value}),disabled:s,children:[t.jsx("option",{value:"S",children:"S"}),t.jsx("option",{value:"M",children:"M"}),t.jsx("option",{value:"L",children:"L"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"planning-deps-list",children:[e.slice(0,S).filter(L=>L.id!==C.id).map(L=>{const G=C.dependsOn.includes(L.id);return t.jsxs("label",{className:`planning-dep-chip ${G?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:G,onChange:()=>{const $=G?C.dependsOn.filter(I=>I!==L.id):[...C.dependsOn,L.id];f(C.id,{dependsOn:$})},disabled:s}),t.jsx("span",{className:"planning-dep-id",children:L.id}),t.jsx("span",{className:"planning-dep-title",children:L.title||"Untitled"})]},L.id)}),S===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),S>0&&e.slice(0,S).filter(L=>L.id!==C.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},C.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:b,disabled:s,children:[t.jsx(Vt,{size:16,className:"icon-mr-6"})," Add subtask"]}),dm(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(ia,{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(it,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]})}function LM(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function um(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 zM({isOpen:e,onClose:n,initialDescription:s,onTasksCreated:i,parentTaskId:r,projectId:o,resumeSessionId:l}){const[c,u]=a.useState({type:"initial"}),[d,m]=a.useState([]),[h,g]=a.useState([]),[p,f]=a.useState(""),[b,v]=a.useState(!0),[x,k]=a.useState(!1),[M,y]=a.useState(!1),[R,j]=a.useState(s),[C,S]=a.useState(null),[P,T]=a.useState(!1),[_,L]=a.useState(null),[G,$]=a.useState(null),[I,w]=a.useState(null),q=a.useRef(null),W=a.useRef([]),B=a.useRef(!1),A=a.useRef(null),z=c.type==="generating"||c.type==="editing"||c.type==="creating"||c.type==="error"?c.sessionId:null,X=a.useMemo(()=>_i(),[]),{isLockedByOther:E,takeControl:U,isLoading:pe}=mo(e?z:null),{activeTabMap:ie,broadcastUpdate:re,broadcastCompleted:F,broadcastLock:ce,broadcastUnlock:ae,broadcastHeartbeat:Q}=la(),de=a.useMemo(()=>d.length===0||d.some(oe=>!oe.title.trim())?!0:um(d),[d]),Te=c.type==="generating"||c.type==="editing"||c.type==="error",fe=z?ie.get(z):null,Se=fe&&fe.tabId!==X,te=!!(Se&&!fe.stale),we=E&&(!Se||fe.stale),Pe=a.useCallback(()=>{R&&Tw(R,o),q.current?.close(),q.current=null,u({type:"initial"}),m([]),g([]),f(""),v(!0),k(!1),y(!1),S(null),T(!1),B.current=!1},[R,o]),We=a.useCallback(()=>{q.current?.close(),q.current=null,n()},[n]),Ke=a.useCallback(async()=>{if(!((P||c.type==="editing"||c.type==="creating")&&!confirm("Close subtask breakdown? Unsaved changes will be lost."))){if(z)try{await vh(z,o,X)}catch{}Pe(),n()}},[P,n,Pe,z,X,c.type,o]),Ne=a.useCallback(oe=>{q.current?.close(),q.current=py(oe,o,{onThinking:Z=>{f(ue=>ue+Z),re({sessionId:oe,status:"generating",needsInput:!1,owningTabId:X,type:"subtask",title:R.trim()||"Subtask breakdown",projectId:o??null})},onSubtasks:Z=>{k(!1),y(!1),zo(o),m(Z),u({type:"editing",sessionId:oe}),T(!1),re({sessionId:oe,status:"awaiting_input",needsInput:!0,owningTabId:X,type:"subtask",title:R.trim()||"Subtask breakdown",projectId:o??null})},onError:Z=>{const ue=Z||"Session failed while contacting the AI.";k(!1),y(!1),S(null),u({type:"error",sessionId:oe,errorMessage:ue}),re({sessionId:oe,status:"error",needsInput:!1,owningTabId:X,type:"subtask",title:R.trim()||"Subtask breakdown",projectId:o??null}),F({sessionId:oe,status:"error"})},onComplete:()=>{F({sessionId:oe,status:"complete"})},onConnectionStateChange:Z=>{k(Z==="reconnecting")}})},[F,re,R,o,X]),_e=a.useCallback(async()=>{if(R.trim()){S(null),g([]),f(""),k(!1);try{const{sessionId:oe}=await uy(R.trim(),o);u({type:"generating",sessionId:oe}),Ne(oe)}catch(oe){S(xe(oe)||"Failed to start subtask breakdown"),u({type:"initial"})}}},[Ne,R,o]);a.useEffect(()=>{if(!e){Pe();return}if(e&&s&&!B.current)j(s),B.current=!0,_e();else if(e&&!s&&!B.current){const oe=Rw(o);oe&&j(oe)}},[e,s,_e,Pe]),a.useEffect(()=>{!e||!l||c.type!=="initial"||(async()=>{try{const oe=await Js(l);if(!oe)return;const Z=Yi(oe.conversationHistory);if(g(Z),oe.status==="generating"||oe.status==="awaiting_input")f(oe.thinkingOutput??""),u({type:"generating",sessionId:l}),Ne(l);else if(oe.status==="complete"&&oe.result){zo(o);const ue=JSON.parse(oe.result);m(ue),u({type:"editing",sessionId:l})}else oe.status==="error"&&(S(null),u({type:"error",sessionId:l,errorMessage:oe.error??"Session encountered an error"}))}catch(oe){S(xe(oe)||"Failed to resume session")}})()},[Ne,e,l,c.type,o]),a.useEffect(()=>{if(!e){A.current&&(ae(A.current,X),A.current=null);return}if(z&&A.current!==z){A.current&&ae(A.current,X),ce(z,X),A.current=z;return}!z&&A.current&&(ae(A.current,X),A.current=null)},[ce,ae,e,z,X]),a.useEffect(()=>{if(!e||!z||A.current!==z)return;Q(X);const oe=setInterval(()=>{Q(X)},3e4);return()=>{clearInterval(oe)}},[Q,e,z,X]),a.useEffect(()=>()=>{q.current?.close(),A.current&&(ae(A.current,X),A.current=null)},[ae,X]),a.useEffect(()=>{if(!e)return;const oe=Z=>{Z.key==="Escape"&&(Z.preventDefault(),Ke())};return document.addEventListener("keydown",oe),()=>document.removeEventListener("keydown",oe)},[e,Ke]);const Oe=a.useCallback((oe,Z)=>{m(ue=>ue.map(Ce=>Ce.id===oe?{...Ce,...Z}:Ce)),T(!0)},[]),ye=a.useCallback(()=>{m(oe=>[...oe,LM(oe.length+1)]),T(!0)},[]),De=a.useCallback(oe=>{m(Z=>Z.filter(ue=>ue.id!==oe).map(ue=>({...ue,dependsOn:ue.dependsOn.filter(Ce=>Ce!==oe)}))),T(!0)},[]),se=a.useCallback(oe=>Z=>{L(oe),Z.dataTransfer.setData("text/plain",oe),Z.dataTransfer.effectAllowed="move"},[]),J=a.useCallback(()=>{L(null),$(null),w(null)},[]),me=a.useCallback(oe=>Z=>{if(Z.preventDefault(),oe===_)return;const ue=Z.currentTarget.getBoundingClientRect(),Ce=ue.top+ue.height/2,$e=Z.clientY<Ce?"before":"after";$(oe),w($e)},[_]),ee=a.useCallback(oe=>Z=>{Z.preventDefault();const ue=Z.dataTransfer.getData("text/plain");if(!ue||ue===oe){L(null),$(null),w(null);return}m(Ce=>{const $e=Ce.findIndex(He=>He.id===ue),ve=Ce.findIndex(He=>He.id===oe);if($e===-1||ve===-1)return Ce;const Ge=[...Ce],[je]=Ge.splice($e,1);let Ue=ve;return I==="after"&&$e<ve&&Ue--,I==="after"&&Ue++,Ge.splice(Ue,0,je),Ge}),T(!0),L(null),$(null),w(null)},[I]),he=a.useCallback(oe=>{const Z=oe.currentTarget.getBoundingClientRect(),ue=oe.clientX,Ce=oe.clientY;(ue<Z.left||ue>Z.right||Ce<Z.top||Ce>Z.bottom)&&($(null),w(null))},[]),le=a.useCallback((oe,Z)=>{Z<0||Z>=d.length||(m(ue=>{const Ce=[...ue],[$e]=Ce.splice(oe,1);return Ce.splice(Z,0,$e),Ce}),T(!0))},[d.length]),Ie=a.useCallback(oe=>{W.current[oe+1]?.focus()},[]),Ze=a.useCallback(async()=>{if(!(!z||de)){S(null),u({type:"creating",sessionId:z});try{const oe=await fy(z,d,r,o);i(oe.tasks),Pe(),n()}catch(oe){S(xe(oe)||"Failed to create tasks"),u({type:"editing",sessionId:z})}}},[de,n,i,r,o,Pe,z,d]),at=a.useCallback(async()=>{if(c.type!=="error")return;const oe=c.sessionId;S(null),y(!0),f(""),u({type:"generating",sessionId:oe}),Ne(oe);try{await my(oe,o,X)}catch(Z){let ue=Z;if((xe(Z)||"").includes("not in an error state"))try{const $e=await Js(oe);if(!$e)throw new Error("Failed to refresh subtask session.");if(g(Yi($e.conversationHistory)),$e.status==="generating"||$e.status==="awaiting_input")f($e.thinkingOutput??""),u({type:"generating",sessionId:$e.id}),q.current?.isConnected()||Ne($e.id);else if($e.status==="complete"){if(!$e.result)throw new Error("Subtask session is complete but has no result.");zo(o);const ve=JSON.parse($e.result);m(ve),u({type:"editing",sessionId:$e.id}),T(!1)}else $e.status==="error"&&u({type:"error",sessionId:$e.id,errorMessage:$e.error??"Retry failed. Please try again."});k(!1);return}catch($e){ue=$e}q.current?.close(),q.current=null,u({type:"error",sessionId:oe,errorMessage:xe(ue)||"Retry failed. Please try again."}),k(!1)}finally{y(!1)}},[Ne,o,X,c]);return e?t.jsx("div",{className:"modal-overlay open",onClick:oe=>oe.target===oe.currentTarget&&void Ke(),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(no,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Subtask Breakdown"})]}),t.jsxs("div",{className:"modal-header-actions",children:[Te&&t.jsx("button",{className:"modal-send-to-background",onClick:We,title:"Send to background","aria-label":"Send to background",children:t.jsx(aa,{size:16})}),t.jsx("button",{className:"modal-close",onClick:()=>void Ke(),"aria-label":"Close",children:t.jsx(Pt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[C&&t.jsx("div",{className:"form-error planning-error",children:C}),x&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),te&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),c.type==="initial"&&t.jsx("div",{className:"planning-initial",children:t.jsxs("div",{className:"planning-view-scroll",children:[t.jsx("p",{className:"text-muted",children:"Preparing to break this task into subtasks."}),t.jsx("pre",{className:"planning-thinking-output",children:R})]})}),c.type==="generating"&&t.jsxs("div",{className:"planning-loading",children:[h.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Cs,{entries:h,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsx(it,{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(Cs,{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 at(),disabled:M,children:[M?t.jsx(it,{size:14,className:"spin"}):t.jsx(hn,{size:14}),t.jsx("span",{className:"icon-ml-6",children:M?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:()=>void Ke(),disabled:M,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(Cs,{entries:h}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(tn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Review your subtasks"}),t.jsx("p",{className:"text-muted",children:"Edit titles, descriptions, sizes, and dependencies before creating all tasks at once."})]}),t.jsxs("div",{className:"planning-summary-form",children:[d.map((oe,Z)=>{const ue=_===oe.id,Ce=G===oe.id,$e=["task-detail-section","subtask-item",ue?"subtask-item-dragging":"",Ce?"subtask-item-drop-target":"",Ce&&I==="before"?"subtask-item-drop-before":"",Ce&&I==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:$e,"data-testid":`subtask-item-${Z}`,draggable:c.type!=="creating",onDragStart:se(oe.id),onDragEnd:J,onDragOver:me(oe.id),onDrop:ee(oe.id),onDragLeave:he,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(oc,{size:16}),t.jsx("strong",{children:oe.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>le(Z,Z-1),disabled:c.type==="creating"||Z===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(yi,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>le(Z,Z+1),disabled:c.type==="creating"||Z===d.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(Wa,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>De(oe.id),disabled:c.type==="creating",children:[t.jsx(Ht,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:ve=>{W.current[Z]=ve},value:oe.title,onChange:ve=>Oe(oe.id,{title:ve.target.value}),onKeyDown:ve=>{ve.key==="Enter"&&(ve.preventDefault(),Ie(Z))},disabled:c.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:8,value:oe.description,onChange:ve=>Oe(oe.id,{description:ve.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:oe.suggestedSize,onChange:ve=>Oe(oe.id,{suggestedSize:ve.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,Z).filter(ve=>ve.id!==oe.id).map(ve=>{const Ge=oe.dependsOn.includes(ve.id);return t.jsxs("label",{className:`planning-dep-chip ${Ge?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:Ge,onChange:()=>{const je=Ge?oe.dependsOn.filter(Ue=>Ue!==ve.id):[...oe.dependsOn,ve.id];Oe(oe.id,{dependsOn:je})},disabled:c.type==="creating"}),t.jsx("span",{className:"planning-dep-id",children:ve.id}),t.jsx("span",{className:"planning-dep-title",children:ve.title||"Untitled"})]},ve.id)}),Z===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),Z>0&&d.slice(0,Z).filter(ve=>ve.id!==oe.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},oe.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:ye,disabled:c.type==="creating",children:[t.jsx(Vt,{size:16,className:"icon-mr-6"})," Add subtask"]}),um(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 Ke(),disabled:c.type==="creating",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:()=>void Ze(),disabled:c.type==="creating"||de,children:c.type==="creating"?t.jsxs(t.Fragment,{children:[t.jsx(it,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]}),E&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(so,{size:16}),t.jsx("span",{children:we?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),we&&t.jsx("button",{type:"button",onClick:()=>{U()},disabled:pe,className:"btn btn-primary session-lock-take-control",children:pe?"Taking control...":"Take Control"})]})})]})]})}):null}const FM=5,OM=1e3,UM=45e3;function _r(){return{scrollback:null,connected:null,data:[]}}function BM(e,n){const[s,i]=a.useState("disconnected"),r=a.useRef(0),o=a.useRef(e),l=a.useRef(n),c=o.current!==e||l.current!==n;c&&(o.current=e,l.current=n,r.current++);const u=a.useRef(null),d=a.useRef(0),m=a.useRef(null),h=a.useRef(null),g=a.useRef(!1),p=a.useRef(new Set),f=a.useRef(new Set),b=a.useRef(new Set),v=a.useRef(new Set),x=a.useRef(new Set),k=a.useRef(_r()),M=a.useCallback($=>{p.current.add($);const I=k.current;return I.data.length>0&&(I.data.forEach(w=>$(w)),I.data=[]),()=>p.current.delete($)},[]),y=a.useCallback($=>(f.current.add($),()=>f.current.delete($)),[]),R=a.useCallback($=>{b.current.add($);const I=k.current;return I.connected&&($(I.connected),I.connected=null),()=>b.current.delete($)},[]),j=a.useCallback($=>{v.current.add($);const I=k.current;return I.scrollback&&($(I.scrollback),I.scrollback=null),()=>v.current.delete($)},[]),C=a.useCallback($=>(x.current.add($),()=>x.current.delete($)),[]),S=a.useCallback($=>{const I=u.current;I?.readyState===WebSocket.OPEN&&I.send(JSON.stringify({type:"input",data:$}))},[]),P=a.useCallback(($,I)=>{const w=u.current;w?.readyState===WebSocket.OPEN&&w.send(JSON.stringify({type:"resize",cols:$,rows:I}))},[]),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),k.current=_r()},[]),_=a.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.current=null),u.current&&(g.current=!0,u.current.close(),u.current=null),k.current=_r()},[]),L=a.useCallback(()=>{if(!e){i("disconnected");return}if(u.current?.readyState===WebSocket.OPEN)return;u.current&&(g.current=!0,u.current.close()),g.current=!1,i("connecting");const $=r.current;let w=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/terminal/ws?sessionId=${encodeURIComponent(e)}`;n&&(w+=`&projectId=${encodeURIComponent(n)}`);const q=new WebSocket(Hs(w));u.current=q,q.onopen=()=>{if(r.current!==$){q.close();return}k.current=_r(),i("connected"),d.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{r.current===$&&q.readyState===WebSocket.OPEN&&q.send(JSON.stringify({type:"ping"}))},UM)},q.onmessage=W=>{if(r.current===$)try{const B=JSON.parse(W.data),A=k.current;switch(B.type){case"data":B.data&&(p.current.size===0&&A.data.push(B.data),p.current.forEach(z=>z(B.data)));break;case"scrollback":B.data&&(A.scrollback=B.data,v.current.forEach(z=>z(B.data)));break;case"connected":B.shell&&B.cwd&&(A.connected={shell:B.shell,cwd:B.cwd},b.current.forEach(z=>z({shell:B.shell,cwd:B.cwd})));break;case"exit":B.exitCode!==void 0&&f.current.forEach(z=>z(B.exitCode));break;case"ping":q.readyState===WebSocket.OPEN&&q.send(JSON.stringify({type:"pong"}));break;case"pong":break}}catch{}},q.onclose=W=>{if(r.current!==$)return;if(u.current=null,h.current&&(clearInterval(h.current),h.current=null),g.current){i("disconnected");return}if(W.code===4e3||W.code===4004){i("disconnected"),W.code===4004&&x.current.forEach(z=>z());return}if(d.current++,d.current>FM){i("disconnected");return}const B=OM*Math.pow(2,d.current-1);i("reconnecting");const A=r.current;m.current=setTimeout(()=>{r.current===A&&(g.current||L())},Math.min(B,16e3))},q.onerror=()=>{}},[e,n]),G=a.useCallback(()=>{d.current=0,_(),L()},[_,L]);return a.useEffect(()=>(c&&(T(),d.current=0,i("disconnected")),e?L():i("disconnected"),_),[e,n,c,L,_,T]),{connectionStatus:s,sendInput:S,resize:P,onData:M,onExit:y,onConnect:R,onScrollback:j,reconnect:G,onSessionInvalid:C}}const Zp="kb-terminal-tabs",HM=15e3,qM=15e3;function mm(){return`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function hm(e){if(typeof window>"u")return[];try{const n=Nn(Zp,e);if(n)return JSON.parse(n)}catch{}return[]}function gl(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return n.includes("Failed to parse URL")||n.includes("Invalid URL")}function pm(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 VM(e){const[n,s]=a.useState(()=>hm(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(hm(e)),r(!1),l(!0),u(null)},[e]),a.useEffect(()=>{try{ts(Zp,JSON.stringify(n),e)}catch{}},[e,n]),a.useEffect(()=>{let R=!1;const j=h.current;return(async()=>{if(!R)try{const S=await pm(cv(e),HM,"listTerminalSessions");if(R||j!==h.current)return;const P=new Set(S.map(T=>T.id));l(!0),s(T=>{if(R||j!==h.current)return T;const L=T.map(I=>({...I,_verified:P.has(I.sessionId)})).filter(I=>I._verified);if(L.length===0)return[];const G=L.map(({_verified:I,...w})=>w);return G.find(I=>I.isActive)?G:G.map((I,w)=>({...I,isActive:w===0}))}),r(!0)}catch(S){if(R||j!==h.current)return;const P=gl(S);P||console.warn("Failed to validate terminal sessions with server:",S),l(!P),r(!0)}})(),()=>{R=!0}},[e]),a.useEffect(()=>{if(n.length===0&&i&&o){const R=h.current,j=setTimeout(()=>{pm(ur(void 0,void 0,void 0,e),qM,"createTerminalSession").then(C=>{if(R!==h.current)return;const S={id:mm(),sessionId:C.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};s(P=>P.length>0?P:[...P.map(_=>({..._,isActive:!1})),S]),u(null)}).catch(C=>{if(R!==h.current)return;gl(C)||console.error(C);const S=C instanceof Error?C.message:typeof C=="string"?C:"Failed to create terminal session";u(S)})},0);return()=>clearTimeout(j)}},[i,o,n.length,d]);const g=a.useCallback(async()=>{const R=await ur(void 0,void 0,void 0,e),j={id:mm(),sessionId:R.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};return s(C=>[...C.map(P=>({...P,isActive:!1})),j]),j},[n.length]),p=a.useCallback(async()=>g(),[g]),f=a.useCallback(R=>{s(j=>{const C=j.find(_=>_.id===R);if(!C)return j;sd(C.sessionId,e).catch(_=>{console.warn(`Failed to kill terminal session ${C.sessionId}:`,_)});const S=j.findIndex(_=>_.id===R),P=C.isActive,T=j.filter(_=>_.id!==R);if(T.length===0)return[];if(P){const _=Math.min(S,T.length-1);return T.map((L,G)=>({...L,isActive:G===_}))}return T})},[]),b=a.useCallback(R=>{s(j=>{let C=!1;const S=j.map(P=>P.id===R?(C=!0,{...P,isActive:!0}):{...P,isActive:!1});return C?S:j})},[]),v=a.useCallback((R,j)=>{s(C=>C.map(S=>S.id===R?{...S,title:j}:S))},[]),x=a.useCallback(async()=>{s(C=>{const S=C.find(P=>P.isActive);return S&&sd(S.sessionId,e).catch(P=>{console.warn(`Failed to kill old session ${S.sessionId}:`,P)}),C});const R=n.find(C=>C.isActive);if(!R)return;const j=await ur(void 0,void 0,void 0,e);s(C=>C.map(S=>S.id===R.id?{...S,sessionId:j.sessionId}:S))},[n]),k=a.useCallback(async()=>{const R=n.find(j=>j.isActive);if(R)try{const j=await ur(void 0,void 0,void 0,e);s(C=>C.map(S=>S.id===R.id?{...S,sessionId:j.sessionId}:S)),u(null)}catch(j){gl(j)||console.error(j);const C=j instanceof Error?j.message:typeof j=="string"?j:"Failed to create terminal session";u(C)}},[n]),M=n.find(R=>R.isActive)??null,y=a.useCallback(()=>{u(null),h.current+=1,m(R=>R+1)},[]);return{tabs:n,activeTab:M,isReady:i,bootstrapError:c,createTab:p,closeTab:f,setActiveTab:b,updateTabTitle:v,restartActiveTab:x,retryBootstrap:y,replaceActiveTabSession:k}}const WM=1e4,GM=[500,1500,3e3];function KM(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 JM(e){return new Promise(n=>setTimeout(n,e))}async function YM(e,n=GM){let s;for(let i=0;i<=n.length;i+=1)try{return await e()}catch(r){if(!KM(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 JM(o)}throw s??new Error("Dynamic import failed")}function fm(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}function QM(){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=XM()-e.offsetTop-e.height;return i>=30&&i>80?i:0}let bl=null;function XM(){return bl===null&&(bl=window.innerHeight),bl}function ZM({isOpen:e,onClose:n,initialCommand:s,projectId:i}){const[r,o]=a.useState(null),[l,c]=a.useState(null),[u,d]=a.useState(!1),[m,h]=a.useState(null),[g,p]=a.useState(0),[f,b]=a.useState(0),[v,x]=a.useState(null),k=a.useRef(null),M=a.useRef(null),y=a.useRef(null),R=a.useRef(null),j=a.useRef(!1),C=a.useRef(!1),S=a.useRef(null),P=a.useRef(0),T=a.useRef(null),_=a.useRef(i);P.current=f;const L=a.useCallback(Ne=>{if(Ne&&C.current!==Ne)return;const _e=R.current,Oe=y.current,ye=S.current;if(!(!_e||!Oe)&&!(Ne&&C.current!==Ne))try{_e.fit(),ye&&ye(Oe.cols,Oe.rows)}catch{}},[]);a.useEffect(()=>{e&&p(Ne=>Ne+1)},[e]),a.useEffect(()=>{if(!e||!fm())return;const Ne=window.visualViewport;if(!Ne)return;const _e=()=>{const Oe=QM();b(Oe),x(Ne.height),Oe>0&&M.current?.scrollIntoView&&M.current.scrollIntoView({block:"end",behavior:"smooth"}),T.current!==null&&(cancelAnimationFrame(T.current),T.current=null);const ye=typeof C.current=="string"?C.current:void 0;T.current=requestAnimationFrame(()=>{T.current=null,L(ye)})};return _e(),Ne.addEventListener("resize",_e),Ne.addEventListener("scroll",_e),()=>{Ne.removeEventListener("resize",_e),Ne.removeEventListener("scroll",_e),T.current!==null&&(cancelAnimationFrame(T.current),T.current=null),b(0),x(null)}},[L,e]);const{tabs:G,activeTab:$,isReady:I,bootstrapError:w,createTab:q,closeTab:W,setActiveTab:B,updateTabTitle:A,restartActiveTab:z,retryBootstrap:X,replaceActiveTabSession:E}=VM(i),{connectionStatus:U,sendInput:pe,resize:ie,onData:re,onConnect:F,onExit:ce,onScrollback:ae,reconnect:Q,onSessionInvalid:de}=BM($?.sessionId??null,i);S.current=ie,a.useEffect(()=>{if(!e||!I)return;const Ne=$?.sessionId;if(!Ne)return;const _e=_.current!==i;if(_e&&(_.current=i),C.current===Ne&&y.current&&!_e)return;y.current&&(C.current!==Ne||_e)&&(y.current.dispose(),y.current=null,R.current=null,C.current=!1,d(!1),h(null));let Oe=!0,ye;return(async()=>{const se=YM(()=>Promise.all([Zt(()=>import("./vendor-xterm-DzcZoU0P.js").then(he=>he.x),__vite__mapDeps([0,1,2])),Zt(()=>import("./addon-fit-C7jRorKK.js").then(he=>he.a),__vite__mapDeps([3,1])),Zt(()=>import("./addon-web-links-CkJwd4cQ.js").then(he=>he.a),__vite__mapDeps([4,1]))])),J=new Promise((he,le)=>{ye=setTimeout(()=>{le(new Error("xterm initialization timed out"))},WM)});let me,ee;try{const[{Terminal:he},{FitAddon:le},{WebLinksAddon:Ie}]=await Promise.race([se,J]);if(!Oe||!k.current||y.current)return;me=new he({cursorBlink:!0,cursorStyle:"block",fontSize:14,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',theme:{background:"#1e1e1e",foreground:"#d4d4d4",cursor:"#d4d4d4",selectionBackground:"#264f78",black:"#1e1e1e",red:"#f48771",green:"#4ec9b0",yellow:"#dcdcaa",blue:"#569cd6",magenta:"#c586c0",cyan:"#9cdcfe",white:"#d4d4d4"},allowProposedApi:!0,scrollback:5e3}),ee=new le,me.loadAddon(ee);const Ze=new Ie;if(me.loadAddon(Ze),!fm())try{const{WebglAddon:oe}=await Zt(async()=>{const{WebglAddon:ue}=await import("./addon-webgl-BjvOw43o.js").then(Ce=>Ce.a);return{WebglAddon:ue}},__vite__mapDeps([5,1])),Z=new oe;Z.onContextLoss(()=>{Z.dispose()}),me.loadAddon(Z)}catch{}me.open(k.current),ye&&clearTimeout(ye);const at=k.current?.querySelector(".xterm-helper-textarea");if(at&&at.focus(),k.current)try{k.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}setTimeout(()=>{ee.fit();const oe=k.current?.querySelector(".xterm-helper-textarea");oe&&oe.focus()},50),y.current=me,R.current=ee,C.current=Ne,P.current>0&&(T.current!==null&&(cancelAnimationFrame(T.current),T.current=null),T.current=requestAnimationFrame(()=>{T.current=null,L(Ne)})),d(!0),h(null)}catch(he){if(ye&&clearTimeout(ye),!Oe)return;const le=he instanceof Error?he.message:"xterm initialization failed";h(le)}})(),()=>{Oe=!1,ye&&clearTimeout(ye)}},[L,e,I,$?.sessionId,i]),a.useEffect(()=>{if(!e||!u||!$?.sessionId||!y.current)return;const Ne=$.sessionId,Oe=y.current.onData(De=>{C.current===Ne&&pe(De)}),ye=()=>{if(C.current===Ne&&R.current&&y.current)try{R.current.fit();const{cols:De,rows:se}=y.current;ie(De,se)}catch{}};return window.addEventListener("resize",ye),()=>{Oe.dispose(),window.removeEventListener("resize",ye)}},[e,u,$?.sessionId,pe,ie]),a.useEffect(()=>{e||(y.current&&(y.current.dispose(),y.current=null),R.current=null,C.current=!1,d(!1),h(null),j.current=!1,o(null),c(null))},[e]),a.useEffect(()=>{if(!u||!y.current||!$)return;const Ne=$.sessionId,_e=J=>{C.current===Ne&&y.current?.write(J)},Oe=re(J=>{_e(J)}),ye=ae(J=>{_e(J)}),De=F(J=>{A($.id,J.shell.split("/").pop()||J.shell)}),se=ce(J=>{C.current===Ne&&(c(J),y.current?.write(`\r
|
|
613
|
-
\x1B[33m[Process exited with code ${J}]\x1B[0m\r
|
|
614
|
-
`))});return()=>{Oe(),ye(),De(),se()}},[u,$?.sessionId,$?.id,$,U,re,ae,F,ce,A]),a.useEffect(()=>{U==="connected"&&s&&j.current!==s&&$&&(j.current=s,setTimeout(()=>{pe(s+`
|
|
615
|
-
`)},500))},[U,s,pe,$,g]),a.useEffect(()=>{if(!e)return;const Ne=_e=>{if(!(!_e.ctrlKey&&!_e.metaKey)){if(_e.code==="Equal"||_e.code==="NumpadAdd"){if(_e.preventDefault(),y.current){const Oe=y.current.options.fontSize||14;y.current.options.fontSize=Math.min(Oe+1,32),R.current?.fit()}return}if(_e.code==="Minus"||_e.code==="NumpadSubtract"){if(_e.preventDefault(),y.current){const Oe=y.current.options.fontSize||14;y.current.options.fontSize=Math.max(Oe-1,8),R.current?.fit()}return}if(_e.code==="Digit0"||_e.code==="Numpad0"){_e.preventDefault(),y.current&&(y.current.options.fontSize=14,R.current?.fit());return}}};return window.addEventListener("keydown",Ne),()=>window.removeEventListener("keydown",Ne)},[e]),a.useEffect(()=>{if(!e)return;const Ne=_e=>{_e.key==="Escape"&&n()};return document.addEventListener("keydown",Ne),()=>document.removeEventListener("keydown",Ne)},[e,n]),a.useEffect(()=>{U==="connected"&&y.current&&setTimeout(()=>{if(!y.current||!k.current)return;const Ne=k.current.querySelector(".xterm-helper-textarea");Ne&&Ne.focus();try{k.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[U]);const Te=a.useCallback(()=>{if(!k.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;y.current?.focus();const _e=k.current.querySelector(".xterm-helper-textarea");if(!_e)return;_e.autocapitalize="off",_e.autocomplete="off",_e.autocorrect="off",_e.spellcheck=!1,_e.setAttribute("inputmode","text");try{_e.focus({preventScroll:!0})}catch{_e.focus()}const Oe=_e.value.length;_e.setSelectionRange(Oe,Oe)},[]);a.useEffect(()=>de(()=>{y.current?.clear(),c(null),j.current=!1,y.current&&(y.current.dispose(),y.current=null),R.current=null,C.current=!1,d(!1),h(null),E().catch(_e=>{console.error("Failed to replace invalid terminal session:",_e)})}),[de,E]);const fe=a.useCallback(Ne=>{Ne.target===Ne.currentTarget&&n()},[n]),Se=a.useCallback(()=>{y.current?.clear()},[]),te=a.useCallback(async()=>{y.current?.clear(),c(null),j.current=!1;try{await z()}catch(Ne){o(xe(Ne)||"Failed to restart terminal session")}},[z]),we=a.useCallback(()=>{y.current&&(y.current.dispose(),y.current=null),R.current=null,C.current=!1,h(null),d(!1)},[]),Pe=a.useCallback(()=>{window.location.reload()},[]);if(!e)return null;const We=()=>{switch(U){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}},Ke=!I||!$&&!w||!u&&!m;return t.jsx("div",{className:"modal-overlay open",onClick:fe,role:"dialog","aria-modal":"true","data-testid":"terminal-modal-overlay",style:f>0?{"--overlay-padding-top":"0px"}:void 0,children:t.jsxs("div",{ref:M,className:"modal terminal-modal","data-testid":"terminal-modal",style:f>0?{"--keyboard-overlap":`${f}px`,"--vv-height":v?`${v}px`:void 0}:void 0,children:[t.jsxs("div",{className:"terminal-header",children:[t.jsxs("div",{className:"terminal-tabs","data-testid":"terminal-tabs",children:[G.map(Ne=>t.jsxs("div",{className:`terminal-tab ${Ne.isActive?"terminal-tab--active":""}`,onClick:()=>B(Ne.id),title:Ne.title,role:"tab","aria-selected":Ne.isActive,children:[t.jsx("span",{className:"terminal-tab-label",children:Ne.title}),G.length>1&&t.jsx("button",{className:"terminal-tab-close",onClick:_e=>{_e.stopPropagation(),W(Ne.id)},title:"Close tab",children:"×"})]},Ne.id)),t.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:q,title:"New terminal",children:"+"})]}),t.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[t.jsx(Bs,{size:16}),We()]}),t.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[U==="disconnected"&&$&&t.jsxs("button",{className:"terminal-reconnect-btn",onClick:Q,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[t.jsx(hn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),l!==null&&t.jsxs("button",{className:"terminal-restart-btn",onClick:te,title:"New Session","data-testid":"terminal-restart-btn",children:[t.jsx(hn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:Se,"data-testid":"terminal-clear-btn",title:"Clear terminal",children:[t.jsx(Ht,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Clear"})]}),t.jsx("button",{className:"terminal-close",onClick:n,"data-testid":"terminal-close-btn",title:"Close terminal",children:t.jsx(Pt,{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:[Ke&&!w&&t.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[t.jsx("div",{className:"terminal-spinner"}),t.jsx("span",{children:"Starting terminal..."})]}),w&&!$&&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: ",w]}),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(hn,{size:14}),"Retry"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Pe,"data-testid":"terminal-bootstrap-refresh-btn",children:[t.jsx(hn,{size:14}),"Refresh page"]})]})]})}),m&&$&&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:we,"data-testid":"terminal-reinit-btn",children:[t.jsx(hn,{size:14}),"Reinitialize"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Pe,"data-testid":"terminal-xterm-refresh-btn",children:[t.jsx(hn,{size:14}),"Refresh page"]})]})]})}),t.jsx("div",{ref:k,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:Te,onTouchStart:Te},$?.sessionId)]}),t.jsxs("div",{className:"terminal-status-bar","data-testid":"terminal-status-bar",children:[t.jsxs("span",{className:`terminal-connection-status ${U}`,children:[U==="connected"&&"Connected",U==="connecting"&&"Connecting...",U==="reconnecting"&&"Reconnecting...",U==="disconnected"&&"Disconnected"]}),l!==null&&t.jsxs("span",{className:"terminal-exit-code","data-testid":"terminal-exit-code",children:["Exit: ",l]}),t.jsx("span",{className:"terminal-shortcuts",children:"Ctrl++/- zoom • Ctrl+L clear • Esc close"})]})]})})}const Na={name:"",command:""};function gm(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function e_(e,n=60){return e.length<=n?e:e.slice(0,n-3)+"..."}function t_({isOpen:e,onClose:n,addToast:s,projectId:i,onRunScript:r}){const[o,l]=a.useState({}),[c,u]=a.useState(!0),[d,m]=a.useState(!1),[h,g]=a.useState(null),[p,f]=a.useState(Na),[b,v]=a.useState(!1),[x,k]=a.useState(null),[M,y]=a.useState(null),R=a.useCallback(async()=>{try{u(!0);const I=await Xa(i);l(I)}catch(I){s(xe(I)||"Failed to load scripts","error")}finally{u(!1)}},[s,i]);a.useEffect(()=>{e&&R()},[e,R]);const j=a.useCallback(()=>{m(!0),g(null),f(Na),y(null)},[]),C=a.useCallback((I,w)=>{g(I),m(!1),f({name:I,command:w}),y(null)},[]),S=a.useCallback(()=>{g(null),m(!1),f(Na),y(null)},[]),P=a.useCallback(I=>{f(w=>({...w,name:I})),I&&!gm(I)?y("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):y(null)},[]),T=a.useCallback(async()=>{const I=p.name.trim(),w=p.command.trim();if(!I){s("Script name is required","error");return}if(!gm(I)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!w){s("Script command is required","error");return}v(!0);try{await cy(I,w,i),s(h?"Script updated":"Script created","success"),g(null),m(!1),f(Na),y(null),await R()}catch(q){const W=xe(q);W?.includes("already exists")?s("A script with this name already exists","error"):s(W||"Failed to save script","error")}finally{v(!1)}},[p,h,s,R,i]),_=a.useCallback(async I=>{try{await dy(I,i),s("Script deleted","success"),k(null),h===I&&(g(null),f(Na)),await R()}catch(w){s(xe(w)||"Failed to delete script","error")}},[h,s,R,i]),L=a.useCallback((I,w)=>{r&&r(I,w)},[r]);if(!e)return null;const G=d||h!==null,$=Object.entries(o).map(([I,w])=>({name:I,command:w}));return t.jsx("div",{className:"modal-overlay open",onClick:n,"data-testid":"scripts-modal",children:t.jsxs("div",{className:"modal scripts-modal",onClick:I=>I.stopPropagation(),role:"dialog","aria-modal":"true","aria-label":"Scripts",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{children:[t.jsx(Bs,{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(it,{size:24,className:"spin",style:{margin:"0 auto 8px",display:"block"}}),"Loading scripts..."]}):G?t.jsxs("div",{className:"scripts-modal-form",style:{display:"flex",flexDirection:"column",gap:"16px"},children:[t.jsxs("div",{children:[t.jsx("label",{htmlFor:"script-name",style:{display:"block",marginBottom:"4px",fontSize:"13px",fontWeight:500,color:"var(--text)"},children:"Script Name"}),t.jsx("input",{id:"script-name",type:"text",className:"input",value:p.name,onChange:I=>P(I.target.value),placeholder:"e.g., build, test, lint",disabled:b||h!==null,"data-testid":"script-name-input",style:{width:"100%",borderColor:M?"var(--color-error)":void 0}}),M&&t.jsx("div",{style:{fontSize:"12px",color:"var(--color-error)",marginTop:"4px"},"data-testid":"script-name-error",children:M}),t.jsx("div",{style:{fontSize:"11px",color:"var(--text-muted)",marginTop:"4px"},children:"Letters, numbers, hyphens, and underscores only"})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"script-command",style:{display:"block",marginBottom:"4px",fontSize:"13px",fontWeight:500,color:"var(--text)"},children:"Command"}),t.jsx("textarea",{id:"script-command",className:"input",value:p.command,onChange:I=>f(w=>({...w,command:I.target.value})),placeholder:"e.g., npm run build",rows:3,disabled:b,"data-testid":"script-command-input",style:{width:"100%",resize:"vertical",fontFamily:"monospace"}})]}),t.jsxs("div",{className:"scripts-modal-form-actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end"},children:[t.jsx("button",{className:"btn btn-secondary",onClick:S,disabled:b,"data-testid":"script-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:T,disabled:b||!!M,"data-testid":"script-save-btn",children:b?t.jsxs(t.Fragment,{children:[t.jsx(it,{size:14,className:"spin",style:{marginRight:"6px"}}),"Saving..."]}):h?"Update":"Create"})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"scripts-modal-list-header",style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[t.jsx("div",{style:{fontSize:"13px",color:"var(--text-muted)"},children:$.length===0?"No scripts defined":`${$.length} script${$.length===1?"":"s"}`}),t.jsxs("button",{className:"btn btn-primary",onClick:j,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx(Vt,{size:14}),"Add Script"]})]}),$.length===0?t.jsxs("div",{style:{textAlign:"center",padding:"32px",color:"var(--text-muted)",fontSize:"14px",border:"1px dashed var(--border)",borderRadius:"8px"},"data-testid":"empty-state",children:[t.jsx(Bs,{size:32,style:{margin:"0 auto 12px",opacity:.5}}),t.jsx("div",{children:"No scripts defined yet."}),t.jsx("div",{style:{marginTop:"4px",fontSize:"12px"},children:"Add scripts to quickly run common commands from the dashboard."})]}):t.jsx("div",{className:"scripts-modal-list",style:{display:"flex",flexDirection:"column",gap:"8px"},children:$.map(I=>t.jsx("div",{className:"script-card","data-testid":`script-${I.name}`,style:{padding:"12px 16px",border:"1px solid var(--border)",borderRadius:"8px",background:"var(--card)"},children:t.jsxs("div",{className:"script-card-header",style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"4px"},children:t.jsx("span",{style:{fontWeight:600,fontSize:"14px",fontFamily:"monospace"},children:I.name})}),t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:I.command,children:e_(I.command)})]}),t.jsxs("div",{className:"script-card-actions",style:{display:"flex",gap:"4px",marginLeft:"8px",flexShrink:0},children:[t.jsxs("button",{className:"btn btn-secondary",onClick:()=>L(I.name,I.command),title:"Run script","aria-label":`Run ${I.name}`,"data-testid":`run-script-${I.name}`,style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 10px",fontSize:"12px"},children:[t.jsx(rn,{size:12}),"Run"]}),t.jsx("button",{className:"btn-icon",onClick:()=>C(I.name,I.command),title:"Edit","aria-label":`Edit ${I.name}`,"data-testid":`edit-script-${I.name}`,children:t.jsx(Vt,{size:14,style:{transform:"rotate(45deg)"}})}),x===I.name?t.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[t.jsx("button",{className:"btn-icon",onClick:()=>_(I.name),title:"Confirm delete","aria-label":`Confirm delete ${I.name}`,"data-testid":`confirm-delete-script-${I.name}`,style:{color:"var(--color-error)"},children:t.jsx(Ht,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>k(null),title:"Cancel delete","aria-label":"Cancel delete","data-testid":`cancel-delete-script-${I.name}`,children:t.jsx(Pt,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>k(I.name),title:"Delete","aria-label":`Delete ${I.name}`,"data-testid":`delete-script-${I.name}`,children:t.jsx(Ht,{size:14})})]})]})},I.name))})]})})]})})}function n_(e,n,s){const[i,r]=a.useState([]),[o,l]=a.useState("."),[c,u]=a.useState(!1),[d,m]=a.useState(null),[h,g]=a.useState(0),p=a.useCallback(()=>{g(b=>b+1)},[]),f=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 Ev(e,o==="."?void 0:o,s);b||r(x.entries)}catch(x){b||(m(xe(x)||"Failed to load files"),r([]))}finally{b||u(!1)}}return v(),()=>{b=!0}},[e,o,n,h,s]),{entries:i,currentPath:o,setPath:f,loading:c,error:d,refresh:p}}function s_(e,n,s,i){const[r,o]=a.useState(""),[l,c]=a.useState(""),[u,d]=a.useState(null),[m,h]=a.useState(!1),[g,p]=a.useState(!1),[f,b]=a.useState(null),v=a.useCallback(M=>{o(M),b(null)},[]);a.useEffect(()=>{if(!e||!n){o(""),c(""),d(null),b(null);return}let M=!1;async function y(){h(!0),b(null);try{const R=await Mv(e,n,i);M||(o(R.content),c(R.content),d(R.mtime))}catch(R){M||(b(xe(R)||"Failed to load file"),o(""),c(""),d(null))}finally{M||h(!1)}}return y(),()=>{M=!0}},[e,n,s,i]);const x=r!==l,k=a.useCallback(async()=>{if(!(!e||!n||!x)){p(!0),b(null);try{const M=await _v(e,n,r,i);c(r),d(M.mtime)}catch(M){throw b(xe(M)||"Failed to save file"),M}finally{p(!1)}}},[e,n,r,x,i]);return{content:r,setContent:v,originalContent:l,loading:m,saving:g,error:f,save:k,hasChanges:x,mtime:u}}const i_=1e4;function a_(e){const s=e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||e||"Project Root"}function r_(e){return{id:e.id,label:e.id,title:e.title,worktree:e.worktree,kind:"task"}}function o_(e){const[n,s]=a.useState("Project Root"),[i,r]=a.useState([]),[o,l]=a.useState(!0),[c,u]=a.useState(null);return a.useEffect(()=>{let d=!1;async function m(){try{const g=await Cv(e);if(d)return;s(a_(g.project)),r(g.tasks.map(r_)),u(null)}catch(g){d||u(xe(g)||"Failed to load workspaces")}finally{d||l(!1)}}m();const h=window.setInterval(()=>{m()},i_);return()=>{d=!0,window.clearInterval(h)}},[e]),{projectName:n,workspaces:i,loading:o,error:c}}function l_(e){return e===void 0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function c_(e){return e?new Date(e).toLocaleDateString():""}function bm(e,n){return e==="."?n:`${e}/${n}`}const Sa={visible:!1,x:0,y:0,entry:null,entryFullPath:""},xl={type:null,entry:null,entryFullPath:""},d_=200,u_=500,xm=10;function m_({x:e,y:n,entry:s,onAction:i,onClose:r}){const o=a.useRef(null),[l,c]=a.useState({x:e,y:n});a.useEffect(()=>{const m=o.current;if(!m)return;const h=m.getBoundingClientRect(),g=window.visualViewport,p=g?.width&&g.width>0?g.width:window.innerWidth,f=g?.height&&g.height>0?g.height:window.innerHeight,b=g?.offsetLeft??0,v=g?.offsetTop??0,x=8;let k=e-b,M=n-v;k+h.width>p-x&&(k=p-x-h.width),M+h.height>f-x&&(M=f-x-h.height),k<x&&(k=x),M<x&&(M=x),c({x:k+b,y:M+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:wi,disabled:!1},{id:"move",label:"Move",icon:fb,disabled:!1},{id:"rename",label:"Rename",icon:Hn,disabled:!1},...u?[{id:"download-zip",label:"Download as ZIP",icon:Zr,disabled:!1}]:[{id:"download",label:"Download",icon:hg,disabled:!1}],{id:"divider",label:"",icon:wi,disabled:!0},{id:"delete",label:"Delete",icon:Ht,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 h_({type:e,entry:n,entryFullPath:s,onConfirm:i,onCancel:r,loading:o,error:l}){const c=a.useRef(null),u=e==="rename"?n.name:"",[d,m]=a.useState(u);a.useEffect(()=>{setTimeout(()=>c.current?.focus(),50)},[]),a.useEffect(()=>{if(e==="rename"&&c.current){const f=n.name.lastIndexOf(".");f>0?c.current.setSelectionRange(0,f):c.current.select()}},[e,n.name]);const h=f=>{f.key==="Enter"&&d.trim()&&i(d.trim()),f.key==="Escape"&&r()};if(e==="delete")return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsxs("div",{className:"file-browser-dialog",onClick:f=>f.stopPropagation(),children:[t.jsxs("div",{className:"file-browser-dialog-title",children:["Delete ",n.type==="directory"?"Folder":"File"]}),t.jsxs("div",{className:"file-browser-dialog-message",children:["Are you sure you want to delete ",t.jsx("strong",{children:n.name}),"?",n.type==="directory"&&" This will delete all contents recursively."]}),l&&t.jsx("div",{className:"file-browser-dialog-error",children:l}),t.jsxs("div",{className:"file-browser-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:r,disabled:o,children:"Cancel"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>i(""),disabled:o,children:o?"Deleting...":"Delete"})]})]})});const p={copy:{title:"Copy",placeholder:"Destination path",confirm:"Copy"},move:{title:"Move",placeholder:"Destination path",confirm:"Move"},rename:{title:"Rename",placeholder:"New name",confirm:"Rename"}}[e];return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsxs("div",{className:"file-browser-dialog",onClick:f=>f.stopPropagation(),children:[t.jsx("div",{className:"file-browser-dialog-title",children:p.title}),t.jsx("div",{className:"file-browser-dialog-info",children:e==="rename"?n.name:s}),t.jsx("input",{ref:c,className:"file-browser-dialog-input",type:"text",value:d,onChange:f=>m(f.target.value),placeholder:p.placeholder,onKeyDown:h,disabled:o}),l&&t.jsx("div",{className:"file-browser-dialog-error",children:l}),t.jsxs("div",{className:"file-browser-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:r,disabled:o,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>i(d.trim()),disabled:o||!d.trim(),children:o?`${p.confirm}ing...`:p.confirm})]})]})})}function p_({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(Sa),[g,p]=a.useState(xl),[f,b]=a.useState(!1),[v,x]=a.useState(null),[k,M]=a.useState(!1),[y,R]=a.useState(null),j=a.useRef(null),C=a.useRef(null),S=a.useRef(null),P=a.useRef(!1),T=a.useCallback(()=>{j.current!==null&&(window.clearTimeout(j.current),j.current=null),C.current!==null&&(window.clearTimeout(C.current),C.current=null)},[]),_=a.useCallback(()=>{T(),S.current=null,M(!1),R(null)},[T]);a.useEffect(()=>()=>{T()},[T]);const L=a.useCallback((z,X,E,U)=>{h({visible:!0,x:z,y:X,entry:E,entryFullPath:U})},[]),G=a.useCallback((z,X,E)=>{if(z.touches.length!==1)return;const U=z.touches[0];U&&(_(),S.current={x:U.clientX,y:U.clientY},C.current=window.setTimeout(()=>{M(!0),R(E)},d_),j.current=window.setTimeout(()=>{const pe=S.current;pe&&(P.current=!0,M(!1),R(null),T(),L(pe.x,pe.y,X,E))},u_))},[_,T,L]),$=a.useCallback(z=>{const X=S.current,E=z.touches[0];!X||!E||(Math.abs(E.clientX-X.x)>xm||Math.abs(E.clientY-X.y)>xm)&&_()},[_]),I=a.useCallback(()=>{_()},[_]);a.useEffect(()=>{if(!m.visible)return;const z=document.querySelector(".file-browser-list"),X=()=>{P.current=!1,_(),h(Sa)};return z?.addEventListener("scroll",X),()=>z?.removeEventListener("scroll",X)},[_,m.visible]),a.useEffect(()=>{if(!m.visible)return;const z=X=>{X.key==="Escape"&&(P.current=!1,h(Sa))};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[m.visible]);const w=a.useCallback((z,X)=>{z.preventDefault(),z.stopPropagation(),_(),P.current=!1,L(z.clientX,z.clientY,X,bm(n,X.name))},[_,n,L]),q=a.useCallback(z=>{if(!m.entry)return;P.current=!1;const X=m.entry,E=m.entryFullPath;if(h(Sa),z==="download"){if(!c)return;const U=fh(c,E,d);window.open(Hs(U),"_blank");return}if(z==="download-zip"){if(!c)return;const U=$v(c,E,d);window.open(Hs(U),"_blank");return}p({type:z,entry:X,entryFullPath:E}),x(null)},[m,c,d]),W=a.useCallback(async z=>{if(!(!g.type||!g.entry||!c)){b(!0),x(null);try{switch(g.type){case"copy":await Tv(c,g.entryFullPath,z,d);break;case"move":await Rv(c,g.entryFullPath,z,d);break;case"rename":await Pv(c,g.entryFullPath,z,d);break;case"delete":await Iv(c,g.entryFullPath,d);break}p(xl),u?.()}catch(X){x(xe(X)||"Operation failed")}finally{b(!1)}}},[g,c,u,d]),B=a.useCallback(()=>{p(xl),x(null)},[]),A=a.useCallback((z,X)=>{if(P.current){P.current=!1;return}m.visible||(z.type==="directory"?i(X):s(X))},[m.visible,i,s]);return r?t.jsxs("div",{className:"file-browser-loading",children:[t.jsx(it,{className:"spin",size:24}),t.jsx("span",{children:"Loading files..."})]}):o?t.jsxs("div",{className:"file-browser-error",children:[t.jsxs("p",{children:["Error: ",o]}),l&&t.jsx("button",{className:"btn btn-sm",onClick:l,children:"Retry"})]}):t.jsxs("div",{className:"file-browser",children:[t.jsxs("div",{className:"file-browser-header",children:[n!=="."&&t.jsxs("button",{className:"file-browser-up",onClick:()=>{const z=n.split("/").filter(Boolean);z.pop(),i(z.length===0?".":z.join("/"))},children:[t.jsx(en,{size:16,style:{transform:"rotate(-90deg)"}}),"Up one level"]}),t.jsx("span",{className:"file-browser-path",children:n==="."?"Root":n})]}),t.jsx("div",{className:"file-browser-list",children:e.length===0?t.jsx("div",{className:"file-browser-empty",children:"(empty directory)"}):e.map(z=>{const X=bm(n,z.name),E=k&&y===X;return t.jsxs("div",{className:`file-node file-node--${z.type} ${E?"file-node--long-pressing":""}`,onClick:()=>A(z,X),onContextMenu:U=>w(U,z),onTouchStart:U=>G(U,z,X),onTouchMove:$,onTouchEnd:I,onTouchCancel:I,children:[t.jsx("div",{className:"file-node-icon",children:z.type==="directory"?t.jsx(jn,{size:16}):t.jsx(nh,{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:l_(z.size)}),z.mtime&&t.jsx("div",{className:"file-node-time",children:c_(z.mtime)})]},z.name)})}),m.visible&&m.entry&&t.jsx(m_,{x:m.x,y:m.y,entry:m.entry,onAction:q,onClose:()=>{P.current=!1,h(Sa)}}),g.type&&g.entry&&t.jsx(h_,{type:g.type,entry:g.entry,entryFullPath:g.entryFullPath,onConfirm:W,onCancel:B,loading:f,error:v})]})}function f_(e){if(!e)return!1;const n=e.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function g_({content:e,onChange:n,readOnly:s,filePath:i}){const[r,o]=a.useState(!1),[l,c]=a.useState(!0),u=f_(i),d=u&&(s?!0:r),m=a.useCallback(()=>{o(!1)},[]),h=a.useCallback(()=>{o(!0)},[]),g=a.useCallback(()=>{c(p=>!p)},[]);return t.jsxs("div",{className:"file-editor-container",children:[u?t.jsxs("div",{className:"file-editor-toolbar",children:[t.jsxs("div",{className:"file-editor-mode-toggle",children:[!s&&t.jsxs("button",{className:`btn btn-sm ${d?"":"btn-primary"}`,onClick:m,disabled:!d,"aria-label":"Edit mode",children:[t.jsx(th,{size:14}),"Edit"]}),t.jsxs("button",{className:`btn btn-sm ${d?"btn-primary":""}`,onClick:h,disabled:d,"aria-label":"Preview mode",children:[t.jsx(Vi,{size:14}),"Preview"]})]}),!s&&t.jsx("button",{className:`btn btn-sm ${l?"btn-primary":""}`,onClick:g,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(zr,{size:14})})]}):!s&&t.jsxs("div",{className:"file-editor-toolbar",children:[t.jsx("div",{className:"file-editor-mode-toggle"}),t.jsx("button",{className:`btn btn-sm ${l?"btn-primary":""}`,onClick:g,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(zr,{size:14})})]}),d?t.jsx("div",{className:"file-editor-preview markdown-body",children:t.jsx(Qs,{remarkPlugins:[Xs],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 b_(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function x_({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(Kc,{size:14}):t.jsx(Al,{size:14}),t.jsx("span",{className:"workspace-selector-trigger-label",children:l}),t.jsx(zt,{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(Kc,{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(Al,{size:14}),t.jsx("span",{children:c.id})]}),c.title&&t.jsx("span",{className:"workspace-selector-option-meta",title:c.title,children:b_(c.title)})]},c.id))]})]})]})}const v_=768,ef=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),y_=new Set([...ef,".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 vm(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return y_.has(n)}function k_(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return ef.has(n)}function j_({initialWorkspace:e="project",onClose:n,onWorkspaceChange:s,projectId:i}){const{projectName:r,workspaces:o}=o_(i),[l,c]=a.useState(e),[u,d]=a.useState(null),[m,h]=a.useState(!1),[g,p]=a.useState("list"),{entries:f,currentPath:b,setPath:v,loading:x,error:k,refresh:M}=n_(l,!0,i),{content:y,setContent:R,originalContent:j,loading:C,saving:S,error:P,save:T,hasChanges:_,mtime:L}=s_(l,u,!0,i);a.useEffect(()=>{c(e)},[e]),a.useEffect(()=>{const z=()=>{h(window.innerWidth<=v_)};return z(),window.addEventListener("resize",z),()=>window.removeEventListener("resize",z)},[]),a.useEffect(()=>{u||p("list")},[u]),a.useEffect(()=>{const z=X=>{X.key==="Escape"&&n(),(X.metaKey||X.ctrlKey)&&X.key==="s"&&(X.preventDefault(),_&&!S&&T())};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[n,_,S,T]);const G=a.useCallback(z=>{d(z),m&&p("editor")},[m]),$=a.useCallback(()=>{p("list")},[]),I=a.useCallback(()=>{R(j)},[j,R]),w=a.useCallback(z=>{c(z),d(null),p("list"),s?.(z)},[s]),W=`Files — ${a.useMemo(()=>l==="project"?"Project":o.find(z=>z.id===l)?.id??l,[l,o])}`,B=a.useMemo(()=>!u||!k_(u)?null:fh(l,u,i),[u,l,i]),A=z=>{const X=new Blob([z]).size;return X<1024?`${X} B`:`${(X/1024).toFixed(1)} KB`};return t.jsx("div",{className:"modal-overlay open",onClick:n,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal file-browser-modal",onClick:z=>z.stopPropagation(),children:[t.jsxs("div",{className:"modal-header file-browser-modal-header",children:[t.jsxs("div",{className:"file-browser-header-title",children:[t.jsx(jn,{size:18}),t.jsx("span",{children:W}),u&&t.jsx("span",{className:"file-browser-header-path",children:u})]}),t.jsxs("div",{className:"file-browser-header-actions",children:[t.jsx(x_,{currentWorkspace:l,projectName:r,workspaces:o,onSelect:w}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Pt,{size:20})})]})]}),t.jsxs("div",{className:"file-browser-body",children:[t.jsx("div",{className:`file-browser-sidebar ${m?"mobile":""} ${g==="list"?"active":""}`,children:t.jsx(p_,{entries:f,currentPath:b,onSelectFile:G,onNavigate:v,loading:x,error:k,onRetry:M,workspace:l,onRefresh:M,projectId:i})}),t.jsx("div",{className:`file-browser-content ${m?"mobile":""} ${g==="editor"?"active":""}`,children:u?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"file-browser-toolbar",children:[t.jsxs("div",{className:"file-browser-file-info",children:[m&&g==="editor"&&t.jsxs("button",{className:"file-browser-back-button",onClick:$,"aria-label":"Back to file list",children:[t.jsx(ia,{size:16}),t.jsx("span",{children:"Back"})]}),u,vm(u)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(Rg,{size:12}),"Binary file — read only"]}),L&&t.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date(L).toLocaleString()]}),C&&t.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),t.jsx("div",{className:"file-browser-actions",children:!B&&_&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:I,disabled:S,children:[t.jsx(Eb,{size:14}),"Discard"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void T(),disabled:S,children:[t.jsx(lh,{size:14}),S?"Saving...":"Save"]})]})})]}),P&&!B&&t.jsx("div",{className:"file-browser-error-banner",children:P}),B?t.jsx("div",{className:"file-browser-image-preview",children:t.jsx("img",{src:B,alt:u??"",className:"file-browser-image"})}):t.jsx("div",{className:"file-editor-wrapper",children:t.jsx(g_,{content:y,onChange:R,filePath:u,readOnly:vm(u)})}),!B&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:A(y)}),_&&t.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):t.jsxs("div",{className:"file-browser-placeholder",children:[t.jsx(jn,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to edit"})]})})]})]})})}function w_(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 Hx();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:xe(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 N_(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 S_(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}const tf="kb-usage-hidden-windows";function ym(e){const n=Nn(tf,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 C_(e,n){ts(tf,JSON.stringify(e),n)}function nf(e,n,s){return s[e]?.includes(n)??!1}function E_({window:e,viewMode:n,isHidden:s,onToggleHidden:i}){const r=S_(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),k=Math.floor(x/24),M=x%24;k>0&&M>0?d=`resets in ${k}d ${M}h`:k>0?d=`resets in ${k}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 g=0;h&&(g=o?100-m.percentElapsed:m.percentElapsed);const p=m?.status==="ahead",f=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}),t.jsx("button",{className:"btn-icon usage-window-hide-btn",onClick:i,"aria-label":`${s?"Show":"Hide"} ${e.label}`,"data-testid":"usage-window-hide-btn",children:s?t.jsx($r,{size:14}):t.jsx(Vi,{size:14})})]})]}),t.jsxs("div",{className:"usage-progress-wrapper",children:[t.jsx("div",{className:"usage-progress-bar",children:t.jsx("div",{className:`usage-progress-fill ${r}`,style:{width:`${l}%`},role:"progressbar","aria-valuenow":l,"aria-valuemin":0,"aria-valuemax":100,"aria-label":`${e.label}: ${c}`})}),h&&t.jsx("div",{className:"usage-pace-marker",style:{left:`${g}%`},"aria-hidden":"true","data-testid":"pace-marker"})]}),t.jsxs("div",{className:"usage-window-footer",children:[t.jsx("span",{className:"usage-window-left",children:u}),t.jsxs("span",{className:"usage-window-reset-group",children:[d&&t.jsx("span",{className:"usage-window-reset",children:d}),e.resetAt&&t.jsx("span",{className:"usage-window-reset-at",children:N_(e.resetAt)})]})]}),h&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[p&&t.jsxs(t.Fragment,{children:[t.jsx(lc,{size:14,className:"pace-icon pace-ahead"}),t.jsx("span",{className:"pace-text pace-ahead",children:m.message})]}),f&&t.jsxs(t.Fragment,{children:[t.jsx(Bb,{size:14,className:"pace-icon pace-behind"}),t.jsx("span",{className:"pace-text pace-behind",children:m.message})]}),b&&t.jsxs(t.Fragment,{children:[t.jsx(tn,{size:14,className:"pace-icon pace-ontrack"}),t.jsx("span",{className:"pace-text pace-ontrack",children:m.message})]})]})]})}function M_(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")?"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 __({provider:e,viewMode:n,hiddenWindows:s,onToggleWindow:i,onShowAllHidden:r}){const o=s[e.name]?.length??0,l=()=>{switch(e.status){case"ok":return t.jsx("span",{className:"usage-status-badge usage-status-badge--connected",children:"Connected"});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(Mn,{provider:M_(e.name),size:"md"}),t.jsx("span",{className:"usage-provider-name",children:e.name})]}),t.jsxs("div",{className:"usage-provider-actions",children:[l(),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,")"]})]})]}),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=nf(e.name,c.label,s);return t.jsx(E_,{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 A_(){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 T_({isOpen:e,onClose:n,projectId:s}){const{providers:i,loading:r,error:o,lastUpdated:l,refresh:c}=w_({autoRefresh:e}),[u,d]=a.useState(!1),[m,h]=a.useState("used"),[g,p]=a.useState(()=>ym(s)),f=a.useRef(null),b=a.useRef(e),v=a.useRef(!1);a.useEffect(()=>{e||(v.current=!1)},[e]),a.useEffect(()=>{i.length>0&&(v.current=!0)},[i.length]),a.useEffect(()=>{!b.current&&e&&(!l||Date.now()-l.getTime()>5e3)&&c(),b.current=e},[e,l,c]),a.useEffect(()=>{const j=Nn("kb-usage-view-mode",s);if(j==="used"||j==="remaining"){h(j);return}h("used")},[s]);const x=a.useCallback(j=>{h(j),ts("kb-usage-view-mode",j,s)},[s]);a.useEffect(()=>{p(ym(s))},[s]),a.useEffect(()=>{C_(g,s)},[g,s]);const k=a.useCallback((j,C)=>{p(S=>{if(nf(j,C,S)){const P=(S[j]??[]).filter(T=>T!==C);if(P.length===0){const{[j]:T,..._}=S;return _}return{...S,[j]:P}}return{...S,[j]:[...S[j]??[],C]}})},[]),M=a.useCallback(j=>{p(C=>{if(!C[j])return C;const{[j]:S,...P}=C;return P})},[]),y=a.useCallback(async()=>{d(!0),await c(),d(!1)},[c]);a.useEffect(()=>{if(!e)return;const j=C=>{C.key==="Escape"&&n()};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[e,n]);const R=a.useCallback(j=>{j.target===j.currentTarget&&n()},[n]);return e?t.jsx("div",{className:"modal-overlay open",onClick:R,"data-testid":"usage-modal-overlay",children:t.jsxs("div",{className:"modal usage-modal","data-testid":"usage-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"usage-header",children:[t.jsx(Ss,{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 ${m==="used"?"active":""}`,onClick:()=>x("used"),"aria-pressed":m==="used","data-testid":"usage-view-toggle-used",children:"Used"}),t.jsx("button",{className:`usage-view-toggle-btn ${m==="remaining"?"active":""}`,onClick:()=>x("remaining"),"aria-pressed":m==="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(Pt,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:f,children:(r||!v.current&&!o)&&i.length===0?t.jsx(A_,{}):o&&i.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:o}),t.jsx("button",{className:"btn btn-sm",onClick:y,children:"Retry"})]}):i.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:i.map(j=>t.jsx(__,{provider:j,viewMode:m,hiddenWindows:g,onToggleWindow:k,onShowAllHidden:M},j.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:l&&t.jsxs("span",{children:["Last updated: ",l.toLocaleTimeString()]})})}),t.jsxs("div",{className:"modal-actions-right usage-actions-right",children:[t.jsxs("button",{className:"btn btn-sm",onClick:y,disabled:r||u,"data-testid":"usage-refresh-btn",children:[t.jsx(hn,{size:14,className:u?"spin":"",style:{marginRight:6}}),"Refresh"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]})}):null}function sf(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 Yr(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 R_={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},af={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},I_={cron:Xm,webhook:ch,api:Zm,manual:vn},P_={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},$_={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function D_({result:e}){const n=e.completedAt&&e.startedAt?new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime():0;return t.jsxs("span",{className:`schedule-run-badge ${e.success?"success":"failure"}`,children:[e.success?t.jsx(tn,{size:12}):t.jsx(Ka,{size:12}),t.jsx("span",{children:e.success?"Success":"Failed"}),n>0&&t.jsx("span",{className:"schedule-run-duration",children:sf(n)})]})}function L_({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"} ${Yr(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx(tn,{size:12}):t.jsx(Ka,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:Yr(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:af[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:sf(r)}),s?t.jsx(Ys,{size:12}):t.jsx(zt,{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 z_({routine:e,onEdit:n,onDelete:s,onRun:i,onToggle:r,running:o}){const[l,c]=a.useState(!1),u=a.useCallback(()=>{window.confirm(`Delete routine "${e.name}"? This cannot be undone.`)&&s(e)},[e,s]),d=R_[e.trigger.type],m=I_[e.trigger.type],h=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"}`,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:d,color:d},children:[t.jsx(m,{size:10}),af[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(to,{size:10}):t.jsx(jn,{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:t.jsx(rn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>r(e),title:e.enabled?"Disable":"Enable","aria-label":e.enabled?`Disable ${e.name}`:`Enable ${e.name}`,"aria-pressed":e.enabled,children:e.enabled?t.jsx(Fs,{size:14}):t.jsx(rn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:"Edit","aria-label":`Edit ${e.name}`,children:t.jsx(Hn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:u,title:"Delete","aria-label":`Delete ${e.name}`,children:t.jsx(Ht,{size:14})})]})]}),t.jsxs("div",{className:"routine-card-meta",children:[e.steps&&e.steps.length>0?t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(Si,{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"&&h&&t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(ji,{size:12}),t.jsx("code",{className:"routine-cron",children:h})]}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Execution policy: ${e.executionPolicy}`,children:P_[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:$_[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:Yr(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:Yr(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(D_,{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})]})]}),e.runHistory.length>0&&t.jsxs("div",{className:"routine-card-history",children:[t.jsxs("button",{className:"schedule-history-toggle",onClick:()=>c(g=>!g),"aria-expanded":l,children:[l?t.jsx(Ys,{size:12}):t.jsx(zt,{size:12}),t.jsxs("span",{children:["Run History (",e.runHistory.length,")"]})]}),l&&t.jsxs("div",{className:"schedule-history-list",children:[e.runHistory.slice(0,10).map((g,p)=>t.jsx(L_,{result:g,index:p},`${g.startedAt}-${p}`)),e.runHistory.length>10&&t.jsxs("div",{className:"schedule-history-more",children:["…and ",e.runHistory.length-10," more"]})]})]})]})}function F_({type:e,size:n=12}){return e==="command"?t.jsxs("span",{className:"step-type-badge step-type-command",title:"Command step",children:[t.jsx(Bs,{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(sb,{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(Dn,{size:n}),t.jsx("span",{children:"AI Prompt"})]})}function vl(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function O_(e){return e==="command"?{id:vl(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:vl(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:vl(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function U_({step:e,onSave:n,onCancel:s}){const[i,r]=a.useState(e.name),[o,l]=a.useState(e.type),[c,u]=a.useState(e.command??""),[d,m]=a.useState(e.prompt??""),[h,g]=a.useState(e.modelProvider??""),[p,f]=a.useState(e.modelId??""),[b,v]=a.useState(e.taskTitle??""),[x,k]=a.useState(e.taskDescription??""),[M,y]=a.useState(e.taskColumn??"triage"),[R,j]=a.useState(e.timeoutMs),[C,S]=a.useState(e.continueOnFailure??!1),[P,T]=a.useState({}),[_,L]=a.useState([]),[G,$]=a.useState(!1),[I,w]=a.useState(null);a.useEffect(()=>{let z=!1;return $(!0),w(null),is().then(X=>{z||L(X.models)}).catch(X=>{z||w(X instanceof Error?X.message:"Failed to load models")}).finally(()=>{z||$(!1)}),()=>{z=!0}},[]);const q=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"),R!==void 0&&R<1e3&&(z.timeoutMs="Timeout must be at least 1 second (1000ms)"),T(z),Object.keys(z).length===0},[i,o,c,d,x,h,p,R]),W=h&&p?`${h}/${p}`:"",B=a.useCallback(z=>{if(!z)g(""),f("");else{const X=z.indexOf("/");X!==-1&&(g(z.slice(0,X)),f(z.slice(X+1)))}},[]),A=a.useCallback(()=>{if(!q())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"?M:void 0,modelProvider:(o==="ai-prompt"||o==="create-task")&&h.trim()?h.trim():void 0,modelId:(o==="ai-prompt"||o==="create-task")&&p.trim()?p.trim():void 0,timeoutMs:R||void 0,continueOnFailure:C};o!=="ai-prompt"&&delete z.prompt,o!=="create-task"&&(delete z.taskTitle,delete z.taskDescription,delete z.taskColumn),n(z)},[q,n,e,i,o,c,d,b,x,M,h,p,R,C]);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":!!P.name}),P.name&&t.jsx("small",{className:"field-error",children:P.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":!!P.command}),P.command&&t.jsx("small",{className:"field-error",children:P.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":!!P.prompt}),P.prompt&&t.jsx("small",{className:"field-error",children:P.prompt})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-model-${e.id}`,children:"Model (optional)"}),t.jsx(wn,{id:`step-model-${e.id}`,label:"Model",models:_,value:W,onChange:B,placeholder:"Use default",disabled:G}),I&&t.jsx("small",{className:"field-error",children:I}),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=>k(z.target.value),rows:4,"aria-invalid":!!P.taskDescription}),P.taskDescription&&t.jsx("small",{className:"field-error",children:P.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:M,onChange:z=>y(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(wn,{id:`step-task-model-${e.id}`,label:"Model",models:_,value:W,onChange:B,placeholder:"Use default",disabled:G}),I&&t.jsx("small",{className:"field-error",children:I}),P.modelProvider&&t.jsx("small",{className:"field-error",children:P.modelProvider}),t.jsx("small",{children:"AI model for executing the created task. Uses default if not selected."})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-timeout-${e.id}`,children:"Timeout (ms, optional)"}),t.jsx("input",{id:`step-timeout-${e.id}`,type:"number",min:1e3,step:1e3,placeholder:"Override schedule timeout",value:R??"",onChange:z=>j(z.target.value?Number(z.target.value):void 0),"aria-invalid":!!P.timeoutMs}),P.timeoutMs&&t.jsx("small",{className:"field-error",children:P.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:C,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:A,children:"Save Step"})]})]})}function B_({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=O_(d);n([...e,m]),r(m.id)},[e,n]),l=a.useCallback(d=>{n(e.filter(m=>m.id!==d)),i===d&&r(null)},[e,n,i]),c=a.useCallback((d,m)=>{const h=e.findIndex(f=>f.id===d);if(h<0)return;const g=m==="up"?h-1:h+1;if(g<0||g>=e.length)return;const p=[...e];[p[h],p[g]]=[p[g],p[h]],n(p)},[e,n]),u=a.useCallback(d=>{n(e.map(m=>m.id===d.id?d:m)),r(null)},[e,n]);return t.jsxs("div",{className:"steps-editor",children:[t.jsx("div",{className:"steps-editor-header",children:t.jsxs("span",{className:"steps-editor-title",children:["Steps (",e.length,")"]})}),e.length===0&&t.jsx("div",{className:"steps-empty-state",children:t.jsx("p",{children:"No steps added yet. Add a command or AI prompt step to get started."})}),t.jsx("div",{className:"steps-list",children:e.map((d,m)=>t.jsx("div",{className:"step-card",children:i===d.id?t.jsx(U_,{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(oc,{size:14})}),t.jsx("span",{className:"step-card-index",children:m+1}),t.jsx(F_,{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(Ys,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>c(d.id,"down"),disabled:m===e.length-1,title:"Move down","aria-label":`Move ${d.name} down`,children:t.jsx(zt,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(d.id),title:"Edit","aria-label":`Edit ${d.name}`,children:t.jsx(Hn,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>l(d.id),title:"Delete","aria-label":`Delete ${d.name}`,children:t.jsx(Ht,{size:14})})]})]})},d.id))}),t.jsxs("div",{className:"steps-add-buttons",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("command"),children:[t.jsx(Vt,{size:14}),"Add Command Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ai-prompt"),children:[t.jsx(Vt,{size:14}),"Add AI Prompt Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("create-task"),children:[t.jsx(Vt,{size:14}),"Add Create Task Step"]})]})]})}const rf={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},H_={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function q_(e){const n=e.trim();for(const[s,i]of Object.entries(rf))if(i===n)return s;return"custom"}function V_(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function W_(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 G_(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 K_=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],J_=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function km(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function jm({routine:e,onSubmit:n,onCancel:s,scope:i,projectId:r,onScopeChange:o}){const l=!!e,c=e?G_(e):{triggerType:"cron",cronExpression:"0 * * * *",webhookPath:"",webhookSecret:"",endpoint:""},[u,d]=a.useState(e?.name??""),[m,h]=a.useState(e?.description??""),[g,p]=a.useState(c.triggerType),[f,b]=a.useState(c.cronExpression),[v,x]=a.useState(()=>c.triggerType!=="cron"?"custom":q_(c.cronExpression)),[k,M]=a.useState(c.webhookPath),[y,R]=a.useState(c.webhookSecret),[j,C]=a.useState(c.endpoint),[S,P]=a.useState(e?.executionPolicy??"queue"),[T,_]=a.useState(e?.catchUpPolicy??"run_one"),[L,G]=a.useState(e?.enabled??!0),$=e?.steps&&e.steps.length===1&&e.steps[0].type==="ai-prompt"&&!e.command,I=e?.steps&&e.steps.length===1&&e.steps[0].type==="create-task"&&!e.command,[w,q]=a.useState(e?.steps&&e.steps.length>0&&!$&&!I?"advanced":"simple"),[W,B]=a.useState(()=>$?"ai-prompt":I?"create-task":"command"),[A,z]=a.useState(e?.command??""),[X,E]=a.useState(e?.steps??[]),[U,pe]=a.useState(!1),[ie,re]=a.useState(e?.timeoutMs??3e5),[F,ce]=a.useState($?e.steps?.[0]?.prompt??"":""),[ae,Q]=a.useState(I?e.steps?.[0]?.taskTitle??"":""),[de,Te]=a.useState(I?e.steps?.[0]?.taskDescription??"":""),[fe,Se]=a.useState(I?e.steps?.[0]?.taskColumn??"triage":"triage"),[te,we]=a.useState($||I?e.steps?.[0]?.modelProvider??"":""),[Pe,We]=a.useState($||I?e.steps?.[0]?.modelId??"":""),[Ke,Ne]=a.useState([]),[_e,Oe]=a.useState(!1),[ye,De]=a.useState(null),[se,J]=a.useState(i??"global"),[me,ee]=a.useState({}),[he,le]=a.useState(!1),Ie=a.useRef(!0);a.useEffect(()=>()=>{Ie.current=!1},[]),a.useEffect(()=>{i&&J(i)},[i]),a.useEffect(()=>{let be=!1;return Oe(!0),De(null),is().then(Je=>{be||Ne(Je.models)}).catch(Je=>{be||De(Je instanceof Error?Je.message:"Failed to load models")}).finally(()=>{be||Oe(!1)}),()=>{be=!0}},[]);const Ze=te&&Pe?`${te}/${Pe}`:"",at=a.useCallback(be=>{if(!be){we(""),We("");return}const Je=be.indexOf("/");Je!==-1&&(we(be.slice(0,Je)),We(be.slice(Je+1)))},[]),oe=a.useCallback(()=>{const be={};if(u.trim()||(be.name="Name is required"),se==="project"&&!r&&(be.scope="Project-specific entries require an active project."),g==="cron"&&v==="custom"&&(f.trim()?V_(f)||(be.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):be.cronExpression="Cron expression is required"),g==="webhook"&&!k.trim()&&(be.webhookPath="Webhook path is required"),g==="api"&&!j.trim()&&(be.endpoint="API endpoint is required"),w==="simple")W==="command"&&!A.trim()&&(be.command="Command is required"),W==="ai-prompt"&&!F.trim()&&(be.prompt="Prompt is required"),W==="create-task"&&!de.trim()&&(be.taskDescription="Task description is required"),(te.trim()&&!Pe.trim()||!te.trim()&&Pe.trim())&&(be.model="Both model provider and model ID must be set, or both must be empty");else{X.length===0&&(be.steps="At least one step is required"),U&&(be.stepsEditing="Please save or cancel all step edits before saving the routine");const Je=[];X.forEach((st,dt)=>{st.name?.trim()||Je.push(`Step ${dt+1}: Name is required`),st.type==="command"&&!st.command?.trim()&&Je.push(`Step ${dt+1}: Command is required`),st.type==="ai-prompt"&&!st.prompt?.trim()&&Je.push(`Step ${dt+1}: Prompt is required`),st.type==="create-task"&&!st.taskDescription?.trim()&&Je.push(`Step ${dt+1}: Task description is required`)}),Je.length>0&&(be.steps=Je.join("; "))}return ie<1e3&&(be.timeoutMs="Timeout must be at least 1 second (1000ms)"),ee(be),Object.keys(be).length===0},[u,g,f,v,k,j,se,r,w,W,A,F,de,te,Pe,X,U,ie]),Z=a.useCallback(async be=>{if(be.preventDefault(),!!oe()){le(!0);try{let Je=e?.scope??se??(r?"project":"global");Je==="project"&&!r&&(Je="global");const st=W_(g,f,k,y,j);let dt,Tt;w==="simple"?W==="command"?dt=A.trim()||void 0:W==="ai-prompt"?Tt=[{id:km(),type:"ai-prompt",name:u.trim(),prompt:F.trim(),modelProvider:te.trim()||void 0,modelId:Pe.trim()||void 0}]:Tt=[{id:km(),type:"create-task",name:u.trim(),taskTitle:ae.trim()||void 0,taskDescription:de.trim(),taskColumn:fe,modelProvider:te.trim()||void 0,modelId:Pe.trim()||void 0}]:Tt=X;const $t={name:u.trim(),agentId:e?.agentId??"",description:m.trim()||void 0,trigger:st,command:dt,steps:Tt,timeoutMs:ie,executionPolicy:S,catchUpPolicy:T,enabled:L,scope:Je};await n($t)}finally{Ie.current&&le(!1)}}},[oe,n,u,m,g,f,k,y,j,w,W,A,F,te,Pe,ae,de,fe,X,ie,S,T,L,se,r,e?.scope,e?.agentId]),ue="routine-name-error",Ce="routine-cron-error",$e="routine-webhook-error",ve="routine-endpoint-error",Ge="routine-command-error",je="routine-prompt-error",Ue="routine-task-description-error",He="routine-model-error",ge="routine-timeout-error",Fe=a.useCallback(be=>{x(be),be!=="custom"&&b(rf[be])},[]);return t.jsxs("form",{className:"routine-form",onSubmit:Z,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:be=>d(be.target.value),"aria-invalid":!!me.name,"aria-describedby":me.name?ue:void 0}),me.name&&t.jsx("small",{id:ue,className:"field-error",children:me.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:be=>h(be.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${se==="global"?" active":""}`,onClick:()=>{J("global"),o?.("global")},role:"radio","aria-checked":se==="global"?"true":"false",disabled:!!e?.scope,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:"Global scope",children:[t.jsx(to,{size:12}),"Global"]}),t.jsxs("button",{type:"button",className:`routine-scope-btn${se==="project"?" active":""}`,onClick:()=>{J("project"),o?.("project")},role:"radio","aria-checked":se==="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(jn,{size:12}),"Project"]})]}),t.jsx("small",{children:!r&&!e?.scope?"No active project. Routines will be created at global scope.":se==="project"&&r?"This routine will be scoped to the current project.":"This routine will be created at global scope."}),me.scope&&t.jsx("small",{className:"field-error",children:me.scope})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Trigger Type"}),t.jsxs("div",{className:"routine-trigger-type-selector",role:"radiogroup","aria-label":"Trigger type",children:[t.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="cron"?" active":""}`,onClick:()=>p("cron"),role:"radio","aria-checked":g==="cron",children:[t.jsx(Xm,{size:14}),"Cron"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="webhook"?" active":""}`,onClick:()=>p("webhook"),role:"radio","aria-checked":g==="webhook",children:[t.jsx(ch,{size:14}),"Webhook"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="api"?" active":""}`,onClick:()=>p("api"),role:"radio","aria-checked":g==="api",children:[t.jsx(Zm,{size:14}),"API"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="manual"?" active":""}`,onClick:()=>p("manual"),role:"radio","aria-checked":g==="manual",children:[t.jsx(vn,{size:14}),"Manual"]})]})]}),g==="cron"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-frequency",children:"Frequency"}),t.jsx("select",{id:"routine-frequency",value:v,onChange:be=>Fe(be.target.value),children:Object.entries(H_).map(([be,Je])=>t.jsx("option",{value:be,children:Je},be))}),t.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),t.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:f,onChange:be=>b(be.target.value),disabled:v!=="custom","aria-invalid":!!me.cronExpression,"aria-describedby":me.cronExpression?Ce:void 0}),me.cronExpression?t.jsx("small",{id:Ce,className:"field-error",children:me.cronExpression}):t.jsx("small",{children:v==="custom"?t.jsxs(t.Fragment,{children:["min hour day month weekday — ",t.jsx("a",{href:"https://crontab.guru",target:"_blank",rel:"noopener noreferrer",children:"crontab.guru"})]}):`Auto-filled from preset: ${f}`})]}),g==="webhook"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-path",children:"Webhook Path"}),t.jsx("input",{id:"routine-webhook-path",type:"text",placeholder:"/trigger/my-routine",value:k,onChange:be=>M(be.target.value),"aria-invalid":!!me.webhookPath,"aria-describedby":me.webhookPath?$e:void 0}),me.webhookPath?t.jsx("small",{id:$e,className:"field-error",children:me.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:y,onChange:be=>R(be.target.value)}),t.jsx("small",{children:"HMAC secret for signature verification. Leave empty for unauthenticated webhooks."})]})]}),g==="api"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-endpoint",children:"API Endpoint"}),t.jsx("input",{id:"routine-endpoint",type:"text",placeholder:"/api/routine/my-routine",value:j,onChange:be=>C(be.target.value),"aria-invalid":!!me.endpoint,"aria-describedby":me.endpoint?ve:void 0}),me.endpoint?t.jsx("small",{id:ve,className:"field-error",children:me.endpoint}):t.jsx("small",{children:"API endpoint path that triggers this routine"})]}),g==="manual"&&t.jsx("div",{className:"form-group",children:t.jsx("small",{className:"routine-trigger-info",children:"This routine will be triggered manually via the dashboard or API."})}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Action Mode"}),t.jsxs("div",{className:"schedule-mode-toggle",role:"radiogroup","aria-label":"Action mode",children:[t.jsx("button",{type:"button",className:`schedule-mode-btn${w==="simple"?" active":""}`,onClick:()=>q("simple"),role:"radio","aria-checked":w==="simple",children:"Simple"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${w==="advanced"?" active":""}`,onClick:()=>q("advanced"),role:"radio","aria-checked":w==="advanced",children:"Multi-Step"})]}),t.jsx("small",{children:w==="simple"?"Run one command, prompt, or task creation action":"Run multiple actions sequentially"})]}),w==="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${W==="command"?" active":""}`,onClick:()=>B("command"),role:"radio","aria-checked":W==="command",children:"Command"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${W==="ai-prompt"?" active":""}`,onClick:()=>B("ai-prompt"),role:"radio","aria-checked":W==="ai-prompt",children:"AI Prompt"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${W==="create-task"?" active":""}`,onClick:()=>B("create-task"),role:"radio","aria-checked":W==="create-task",children:"Create Task"})]})]}),W==="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:A,onChange:be=>z(be.target.value),"aria-invalid":!!me.command,"aria-describedby":me.command?Ge:void 0}),me.command?t.jsx("small",{id:Ge,className:"field-error",children:me.command}):t.jsx("small",{children:"Shell command to execute."})]}):W==="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:F,onChange:be=>ce(be.target.value),rows:3,"aria-invalid":!!me.prompt,"aria-describedby":me.prompt?je:void 0}),me.prompt?t.jsx("small",{id:je,className:"field-error",children:me.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(wn,{id:"routine-model",label:"Model",models:Ke,value:Ze,onChange:at,placeholder:"Use default",disabled:_e}),ye&&t.jsx("small",{className:"field-error",children:ye}),me.model&&t.jsx("small",{id:He,className:"field-error",children:me.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:ae,onChange:be=>Q(be.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:de,onChange:be=>Te(be.target.value),rows:4,"aria-invalid":!!me.taskDescription,"aria-describedby":me.taskDescription?Ue:void 0}),me.taskDescription?t.jsx("small",{id:Ue,className:"field-error",children:me.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:fe,onChange:be=>Se(be.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(wn,{id:"routine-task-model",label:"Executor Model",models:Ke,value:Ze,onChange:at,placeholder:"Use default",disabled:_e}),ye&&t.jsx("small",{className:"field-error",children:ye}),me.model&&t.jsx("small",{id:He,className:"field-error",children:me.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(B_,{steps:X,onChange:E,onEditingChange:pe}),me.steps&&t.jsx("small",{className:"field-error",children:me.steps}),me.stepsEditing&&t.jsx("small",{className:"field-error",children:me.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:ie,onChange:be=>re(Number(be.target.value)),"aria-invalid":!!me.timeoutMs,"aria-describedby":me.timeoutMs?ge:void 0}),me.timeoutMs?t.jsx("small",{id:ge,className:"field-error",children:me.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:be=>P(be.target.value),children:K_.map(be=>t.jsx("option",{value:be.value,children:be.label},be.value))}),t.jsx("small",{children:"How to handle concurrent executions of this routine"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-catchup-policy",children:"Catch-up Policy"}),t.jsx("select",{id:"routine-catchup-policy",value:T,onChange:be=>_(be.target.value),children:J_.map(be=>t.jsx("option",{value:be.value,children:be.label},be.value))}),t.jsx("small",{children:"What to do when a scheduled run is missed"})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:"routine-enabled",className:"checkbox-label",children:[t.jsx("input",{id:"routine-enabled",type:"checkbox",checked:L,onChange:be=>G(be.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:he,children:"Cancel"}),t.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:he,children:he?"Saving…":l?"Save Changes":"Create Routine"})]})]})}const Y_=3e4;function Q_({onClose:e,addToast:n,projectId:s}){const[i,r]=a.useState(()=>s?"project":"global"),[o,l]=a.useState([]),[c,u]=a.useState("list"),[d,m]=a.useState(),[h,g]=a.useState(null),p=a.useMemo(()=>({scope:i,projectId:i==="project"?s:void 0}),[i,s]),f=a.useCallback(async()=>{try{const _=await Zv(p);l(_)}catch(_){n(xe(_)||"Failed to load routines","error")}},[n,p]);a.useEffect(()=>{f()},[f]),a.useEffect(()=>{const _=setInterval(()=>{f()},Y_);return()=>clearInterval(_)},[f]),a.useEffect(()=>{const _=L=>{L.key==="Escape"&&(c!=="list"?(u("list"),m(void 0)):e())};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[e,c]);const b=a.useCallback(_=>{_.target===_.currentTarget&&e()},[e]),v=a.useCallback(async _=>{try{await ey(_,p),n("Routine created","success"),u("list"),await f()}catch(L){n(xe(L)||"Failed to create routine","error")}},[n,f,p]),x=a.useCallback(_=>{m(_),u("edit")},[]),k=a.useCallback(async _=>{if(d)try{await cd(d.id,_,p),n("Routine updated","success"),u("list"),m(void 0),await f()}catch(L){n(xe(L)||"Failed to update routine","error")}},[d,n,f,p]),M=a.useCallback(async _=>{try{await ty(_.id,p),n(`Deleted "${_.name}"`,"success"),await f()}catch(L){n(xe(L)||"Failed to delete routine","error")}},[n,f,p]),y=a.useCallback(async _=>{g(_.id);try{const{result:L}=await ny(_.id,p);L.success?n(`"${_.name}" completed successfully`,"success"):n(`"${_.name}" failed: ${L.error||"Unknown error"}`,"error"),await f()}catch(L){n(xe(L)||"Failed to run routine","error")}finally{g(null)}},[n,f,p]),R=a.useCallback(async _=>{try{await cd(_.id,{enabled:!_.enabled},p),n(`"${_.name}" ${_.enabled?"disabled":"enabled"}`,"success"),await f()}catch(L){n(xe(L)||"Failed to toggle routine","error")}},[n,f,p]),j=a.useCallback(()=>{u("list"),m(void 0)},[]),C=a.useCallback(_=>{r(_),u("list"),m(void 0)},[]),S=()=>c==="create"?t.jsx(jm,{onSubmit:v,onCancel:j,scope:i,projectId:s}):c==="edit"&&d?t.jsx(jm,{routine:d,onSubmit:k,onCancel:j,scope:i,projectId:s}):o.length===0?t.jsxs("div",{className:"routine-empty-state",children:[t.jsx(vn,{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(Vt,{size:14}),"Create your first automation"]})]}):t.jsx("div",{className:"routine-list",children:o.map(_=>t.jsx(z_,{routine:_,onEdit:x,onDelete:M,onRun:y,onToggle:R,running:h===_.id},_.id))}),P=()=>S(),T=c==="list"&&o.length>0;return t.jsx("div",{className:"modal-overlay open",onClick:b,children:t.jsxs("div",{className:"modal modal-lg",role:"dialog","aria-modal":"true","aria-labelledby":"schedules-modal-title",children:[t.jsxs("div",{className:"modal-header scheduling-modal-header",children:[t.jsxs("div",{className:"scheduling-header-main-row",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(vn,{size:20,className:"icon-triage"}),t.jsx("h3",{id:"schedules-modal-title",children:"Automations"})]}),t.jsxs("div",{className:"modal-header-actions",children:[T&&t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>u("create"),"aria-label":"Create new automation",children:[t.jsx(Vt,{size:14}),"New Automation"]}),t.jsx("button",{className:"modal-close",onClick:e,"aria-label":"Close",children:t.jsx(Pt,{size:20})})]})]}),t.jsx("div",{className:"scheduling-header-scope-row",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:()=>C("global"),"aria-pressed":i==="global",title:"Global (user-level) automations",children:[t.jsx(to,{size:14}),"Global"]}),t.jsxs("button",{type:"button",className:`scope-btn${i==="project"?" active":""}`,onClick:()=>C("project"),"aria-pressed":i==="project",title:"Project-scoped automations",children:[t.jsx(jn,{size:14}),"Project"]})]})})]}),t.jsxs("div",{className:"scheduling-summary","aria-live":"polite",children:[t.jsx(vn,{size:14}),t.jsxs("span",{children:[o.length," automation",o.length===1?"":"s"]})]}),t.jsx("div",{className:"detail-tabs",role:"tablist",children:t.jsxs("button",{className:"detail-tab detail-tab-active",role:"tab",id:"tab-routines","aria-selected":"true","aria-controls":"scheduled-tasks-content",onClick:()=>{u("list"),m(void 0)},children:[t.jsx(vn,{size:14})," Routines"]})}),t.jsx("div",{className:"schedule-modal-content",role:"tabpanel",id:"scheduled-tasks-content",children:P()})]})})}const X_=3e4,ec=new Map,yl=new Map;function wm(e){return e??"default"}function Nm(e){const n=ec.get(e);return n?Date.now()>=n.expiresAt?(ec.delete(e),null):n:null}function Z_(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 eA(e){const n=yl.get(e);if(n)return n;const s=Ba().then(({providers:i,ghCli:r})=>{const l={...Z_(i,r),ghCli:r,expiresAt:Date.now()+X_};return ec.set(e,l),l}).finally(()=>{yl.delete(e)});return yl.set(e,s),s}function of(e){const n=wm(e),s=Nm(n),[i,r]=a.useState(s?.hasAiProvider??!1),[o,l]=a.useState(s?.hasGithub??!1),[,c]=a.useState(s?.ghCli),[u,d]=a.useState(s==null),m=a.useRef(!!s);return a.useEffect(()=>{let h=!1;const g=wm(e),p=Nm(g);if(p)return r(p.hasAiProvider),l(p.hasGithub),c(p.ghCli),d(!1),m.current=!0,()=>{h=!0};m.current=!1;async function f(){!m.current&&d(!0);try{const v=await eA(g);if(h)return;r(v.hasAiProvider),l(v.hasGithub),c(v.ghCli)}catch{}finally{h||(m.current=!0,d(!1))}}return f(),()=>{h=!0}},[e]),a.useMemo(()=>({hasAiProvider:i,hasGithub:o,loading:u,hasWarnings:!i||!o}),[i,o,u])}function lf({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(Pt,{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 tA({isOpen:e,onClose:n,projectId:s,tasks:i,onCreateTask:r,addToast:o,onPlanningMode:l,onSubtaskBreakdown:c}){const[u,d]=a.useState(""),[m,h]=a.useState([]),[g,p]=a.useState([]),[f,b]=a.useState(!1),[v,x]=a.useState(""),[k,M]=a.useState(""),[y,R]=a.useState(""),[j,C]=a.useState(""),[S,P]=a.useState(""),[T,_]=a.useState("default"),[L,G]=a.useState(!1),[$,I]=a.useState([]),[w,q]=a.useState(!1),[W,B]=a.useState(void 0),[A,z]=a.useState(cs),[X,E]=a.useState(null),[U,pe]=a.useState([]),[ie,re]=a.useState(!1),[F,ce]=a.useState(!1),ae=a.useRef(null),[Q,de]=a.useState(!1),[Te,fe]=a.useState(""),Se=a.useRef(null),{hasAiProvider:te,hasGithub:we,loading:Pe}=of(s),We=a.useCallback(le=>{q(!0),I(le)},[]),Ke=a.useCallback(()=>{q(!1)},[]),Ne=a.useCallback(async()=>{if(U.length>0){re(!0);return}ce(!0);try{const le=await oa(void 0,s);pe(le),re(!0)}catch(le){const Ie=xe(le);o(Ie?`Failed to load agents: ${Ie}`:"Failed to load agents","error"),re(!1)}finally{ce(!1)}},[U.length,s,o]);a.useEffect(()=>{if(!ie)return;const le=Ie=>{ae.current&&!ae.current.contains(Ie.target)&&re(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[ie]),a.useEffect(()=>{if(!Q)return;const le=Ie=>{Se.current&&!Se.current.contains(Ie.target)&&(de(!1),fe(""))};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[Q]);const _e=i.filter(le=>!m.includes(le.id)).sort((le,Ie)=>{const Ze=Ie.createdAt.localeCompare(le.createdAt);if(Ze!==0)return Ze;const at=parseInt(le.id.slice(le.id.lastIndexOf("-")+1),10)||0;return(parseInt(Ie.id.slice(Ie.id.lastIndexOf("-")+1),10)||0)-at}),Oe=Te?_e.filter(le=>le.id.toLowerCase().includes(Te.toLowerCase())||le.title&&le.title.toLowerCase().includes(Te.toLowerCase())||le.description&&le.description.toLowerCase().includes(Te.toLowerCase())):_e,ye=(le,Ie)=>le.length>Ie?le.slice(0,Ie)+"…":le;a.useEffect(()=>{const le=u.trim()!==""||m.length>0||g.length>0||v!==""||k!==""||y!==""||j!==""||$.length>0||X!==null||W!==void 0||A!==cs;G(le)},[u,m,g,v,k,y,j,$,X,W,A]);const De=a.useCallback(()=>{L&&!confirm("You have unsaved changes. Discard them?")||(g.forEach(le=>URL.revokeObjectURL(le.previewUrl)),p([]),d(""),h([]),x(""),M(""),R(""),C(""),P(""),_("default"),I([]),q(!1),E(null),re(!1),B(void 0),z(cs),G(!1),n())},[L,n,g]),se=a.useCallback(async()=>{const le=u.trim();if(!(!le||f)){b(!0);try{const Ie=v.indexOf("/"),Ze=k.indexOf("/"),at=y.indexOf("/"),oe=await r({title:void 0,description:le,column:"triage",dependencies:m.length?m:void 0,enabledWorkflowSteps:w?$.length>0?$:[]:void 0,...X?{assignedAgentId:X}:{},modelPresetId:T==="preset"&&S||void 0,modelProvider:v&&Ie!==-1?v.slice(0,Ie):void 0,modelId:v&&Ie!==-1?v.slice(Ie+1):void 0,validatorModelProvider:k&&Ze!==-1?k.slice(0,Ze):void 0,validatorModelId:k&&Ze!==-1?k.slice(Ze+1):void 0,planningModelProvider:y&&at!==-1?y.slice(0,at):void 0,planningModelId:y&&at!==-1?y.slice(at+1):void 0,thinkingLevel:j!==""?j:void 0,reviewLevel:W,priority:A});if(g.length>0){const Z=[];for(const ue of g)try{await Ua(oe.id,ue.file,s)}catch{Z.push(ue.file.name)}Z.length>0&&o(`Failed to upload: ${Z.join(", ")}`,"error")}g.forEach(Z=>URL.revokeObjectURL(Z.previewUrl)),p([]),d(""),h([]),x(""),M(""),R(""),C(""),P(""),_("default"),I([]),q(!1),E(null),re(!1),B(void 0),z(cs),o(`Created ${oe.id}`,"success"),n()}catch(Ie){o(xe(Ie)||"Failed to create task","error")}finally{b(!1)}}},[u,m,g,v,k,y,j,f,r,o,n,s,T,S,$,w,X,W,A]),J=a.useCallback(le=>{le.key==="Escape"&&(le.preventDefault(),De())},[De]),ee=(X?U.find(le=>le.id===X):void 0)?.name??X,he=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:Se,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>de(le=>!le),disabled:f,"data-testid":"dep-trigger",children:m.length>0?`${m.length} selected`:"Add dependencies"}),Q&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Te,onChange:le=>fe(le.target.value),onClick:le=>le.stopPropagation()}),Oe.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Oe.map(le=>t.jsxs("div",{className:`dep-dropdown-item${m.includes(le.id)?" selected":""}`,onClick:()=>{h(m.includes(le.id)?m.filter(Ie=>Ie!==le.id):[...m,le.id]),de(!1),fe("")},onMouseDown:Ie=>Ie.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:le.id}),t.jsx("span",{className:"dep-dropdown-title",children:ye(le.title||le.description||le.id,30)})]},le.id))]})]}),m.length>0&&t.jsx("div",{className:"selected-deps",children:m.map(le=>t.jsxs("span",{className:"dep-chip",children:[le,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>h(m.filter(Ie=>Ie!==le)),disabled:f,children:"×"})]},le))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Assign Agent"}),t.jsxs("div",{className:"agent-trigger-wrap",ref:ae,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{ie?re(!1):Ne()},disabled:f,"data-testid":"new-task-agent-button",children:[t.jsx(an,{size:12,style:{verticalAlign:"middle"}}),ee?` ${ee}`:" Assign agent"]}),ie&&t.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:le=>le.preventDefault(),children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),F&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!F&&U.filter(le=>le.state!=="terminated").map(le=>t.jsxs("div",{className:`dep-dropdown-item${X===le.id?" selected":""}`,onMouseDown:Ie=>Ie.preventDefault(),onClick:()=>{E(le.id===X?null:le.id),re(!1)},"data-testid":`agent-option-${le.id}`,children:[t.jsx(an,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:le.role}),t.jsx("span",{className:"dep-dropdown-title",children:le.name})]},le.id)),!F&&U.filter(le=>le.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),X&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:le=>le.preventDefault(),onClick:()=>{E(null),re(!1)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return e?t.jsx("div",{className:"modal-overlay open",onClick:De,onKeyDown:J,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:le=>le.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:"New Task"}),t.jsx("button",{className:"modal-close",onClick:De,disabled:f,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!Pe&&t.jsx(lf,{hasAiProvider:te,hasGithub:we}),t.jsx(Xp,{mode:"create",description:u,onDescriptionChange:d,dependencies:m,onDependenciesChange:h,executorModel:v,onExecutorModelChange:x,validatorModel:k,onValidatorModelChange:M,presetMode:T,onPresetModeChange:_,selectedPresetId:S,onSelectedPresetIdChange:P,selectedWorkflowSteps:$,onWorkflowStepsChange:We,onDefaultOnApplied:Ke,pendingImages:g,onImagesChange:p,tasks:i,projectId:s,disabled:f,addToast:o,isActive:e,onPlanningMode:l,onSubtaskBreakdown:c,onClose:De,planningModel:y,onPlanningModelChange:R,thinkingLevel:j,onThinkingLevelChange:C,reviewLevel:W,onReviewLevelChange:B,priority:A,onPriorityChange:z,renderBelowPrimary:he,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:De,disabled:f,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:se,disabled:!u.trim()||f,children:f?"Creating...":"Create Task"})]})]})}):null}const nA=5e3;function sA(e={}){const{projectId:n,type:s,limit:i=50,autoRefresh:r=!0,useCentralFeed:o=!1}=e,[l,c]=a.useState([]),[u,d]=a.useState(!1),[m,h]=a.useState(null),[g,p]=a.useState(!1),f=a.useRef(null),b=a.useRef(void 0),v=a.useCallback(async()=>{try{d(!0),h(null);let M;o?M=await bd({limit:i,projectId:n,type:s}):M=(await dd({limit:i,type:s,projectId:n})).map(R=>({...R,projectId:n??"",projectName:""})),c(M),p(M.length===i),M.length>0&&(b.current=M[M.length-1].timestamp)}catch(M){h(M instanceof Error?M.message:"Failed to load activity log")}finally{d(!1)}},[i,n,s,o]),x=a.useCallback(async()=>{if(b.current)try{d(!0);let M;o?M=await bd({limit:i,projectId:n,type:s,since:b.current}):M=(await dd({limit:i,type:s,since:b.current,projectId:n})).map(R=>({...R,projectId:n??"",projectName:""})),c(y=>[...y,...M]),p(M.length===i),M.length>0&&(b.current=M[M.length-1].timestamp)}catch(M){h(M instanceof Error?M.message:"Failed to load more entries")}finally{d(!1)}},[i,n,s,o]),k=a.useCallback(()=>{c([]),p(!1),b.current=void 0},[]);return a.useEffect(()=>{v()},[v]),a.useEffect(()=>{if(r)return f.current=setInterval(()=>{v()},nA),()=>{f.current&&(clearInterval(f.current),f.current=null)}},[r,v]),{entries:l,loading:u,error:m,refresh:v,clear:k,hasMore:g,loadMore:x}}const kl={"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"},iA={"task:created":t.jsx(Vt,{size:14,className:"activity-icon created"}),"task:moved":t.jsx(Ga,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx(hn,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(Pt,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx(tn,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(Ka,{size:14,className:"activity-icon failed"}),"settings:updated":t.jsx(Oa,{size:14,className:"activity-icon settings"})};function aA(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 rA({isOpen:e,onClose:n,tasks:s,onOpenTaskDetail:i,projectId:r,projects:o=[],onProjectFilterChange:l,currentProject:c}){const[u,d]=a.useState("all"),[m,h]=a.useState(r||"all"),[g,p]=a.useState(!1);a.useEffect(()=>{h(r||"all")},[r]);const f=u==="all"?void 0:u,b=m==="all"?void 0:m,v=!c&&o.length>0,{entries:x,loading:k,error:M,refresh:y,hasMore:R}=sA({projectId:b,type:f,limit:100,autoRefresh:e,useCentralFeed:v}),j=x.map(_=>({id:_.id,timestamp:_.timestamp,type:_.type,taskId:_.taskId,taskTitle:_.taskTitle,details:_.details,metadata:_.metadata,projectId:_.projectId,projectName:_.projectName})),C=async()=>{try{await sy(),y(),p(!1)}catch{p(!1)}},S=_=>{i&&i(_)},P=_=>{h(_),l?.(_==="all"?void 0:_)};a.useEffect(()=>{if(!e)return;const _=L=>{L.key==="Escape"&&(g?p(!1):n())};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[e,n,g]);const T=u!=="all"||m!=="all";return e?t.jsx("div",{className:"modal-overlay open",onClick:_=>{_.target===_.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(Fa,{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(jn,{size:14}),t.jsxs("select",{value:m,onChange:_=>P(_.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[t.jsx("option",{value:"all",children:"All Projects"}),o.map(_=>t.jsx("option",{value:_.id,children:_.name},_.id))]})]}),t.jsxs("div",{className:"activity-log-filter",children:[t.jsx(Dr,{size:14}),t.jsxs("select",{value:u,onChange:_=>d(_.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:"All Events"}),Object.entries(kl).map(([_,L])=>t.jsx("option",{value:_,children:L},_))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>y(),title:"Refresh","data-testid":"activity-refresh",children:k?t.jsx(it,{size:14,className:"spin"}):t.jsx(hn,{size:14})}),j.length>0&&t.jsx("button",{className:"activity-log-clear",onClick:()=>p(!0),title:"Clear Log","data-testid":"activity-clear",children:t.jsx(Ht,{size:14})})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",title:"Close","data-testid":"activity-close",children:"×"})]}),T&&t.jsxs("div",{className:"activity-log-active-filters",children:[t.jsx("span",{className:"activity-log-filter-label",children:"Active filters:"}),m!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Project: ",o.find(_=>_.id===m)?.name||m]}),u!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",kl[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:[M&&t.jsxs("div",{className:"activity-log-error","data-testid":"activity-error",children:[t.jsx(ss,{size:16}),t.jsx("span",{children:M})]}),j.length===0&&!k&&!M&&t.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[t.jsx(Fa,{size:48,className:"activity-log-empty-icon"}),t.jsx("p",{children:T?"No activity matches the current filters":"No activity recorded yet"}),T&&t.jsx("button",{className:"btn btn-secondary",onClick:()=>{d("all"),h("all"),l?.(void 0)},children:"Clear Filters"})]}),t.jsx("div",{className:"activity-log-list",children:j.map(_=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:iA[_.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:kl[_.type]}),t.jsx("span",{className:"activity-log-entry-time",children:aA(_.timestamp)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[_.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>S(_.taskId),"data-testid":"activity-task-link",children:_.taskId}),_.taskTitle&&t.jsx("span",{className:"activity-log-task-title",children:_.taskTitle}),t.jsx("span",{className:"activity-log-entry-text",children:_.details})]}),_.metadata&&Object.keys(_.metadata).length>0&&t.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof _.metadata.from=="string"&&typeof _.metadata.to=="string"&&t.jsxs("span",{className:"activity-log-metadata-item",children:[_.metadata.from," → ",_.metadata.to]}),typeof _.metadata.merged=="boolean"&&t.jsx("span",{className:`activity-log-metadata-item ${_.metadata.merged?"success":"error"}`,children:_.metadata.merged?"Merged":"Not merged"})]})]})]},_.id))}),R&&!k&&t.jsx("button",{className:"activity-log-load-more",onClick:y,"data-testid":"activity-load-more",children:"Load More"}),k&&j.length>0&&t.jsx("div",{className:"activity-log-loading",children:t.jsx(it,{size:20,className:"spin"})})]}),g&&t.jsx("div",{className:"activity-log-confirm-overlay",children:t.jsxs("div",{className:"activity-log-confirm-dialog",children:[t.jsx("h3",{children:"Clear Activity Log?"}),t.jsx("p",{children:"This will permanently delete all activity log entries. This action cannot be undone."}),t.jsxs("div",{className:"activity-log-confirm-actions",children:[t.jsx("button",{className:"activity-log-confirm-cancel",onClick:()=>p(!1),children:"Cancel"}),t.jsx("button",{className:"activity-log-confirm-clear",onClick:C,children:"Clear Log"})]})]})})]})}):null}const Ca=[{id:"status",label:"Status",icon:oh},{id:"changes",label:"Changes",icon:eh},{id:"commits",label:"Commits",icon:za},{id:"branches",label:"Branches",icon:Os},{id:"worktrees",label:"Worktrees",icon:Wg},{id:"stashes",label:"Stashes",icon:Zr},{id:"remotes",label:"Remotes",icon:sh}];function Sm({status:e}){switch(e){case"added":case"untracked":return t.jsx(Eg,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(th,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(Ng,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return t.jsx(Ni,{size:14,className:"gm-file-icon gm-file-renamed"});default:return t.jsx(_g,{size:14,className:"gm-file-icon"})}}function Cm({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 oA(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 Zi(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 lA({isOpen:e,onClose:n,tasks:s,addToast:i,projectId:r}){const[o,l]=a.useState("status"),[c,u]=a.useState(!1),[d,m]=a.useState(null),h=a.useRef(null),g=oA(i),[p,f]=a.useState(null),[b,v]=a.useState([]),[x,k]=a.useState(new Set),[M,y]=a.useState(""),[R,j]=a.useState(!1),[C,S]=a.useState(null),[P,T]=a.useState(!1),[_,L]=a.useState(null),[G,$]=a.useState(null),I=a.useRef(0),[w,q]=a.useState([]),[W,B]=a.useState(null),[A,z]=a.useState(null),[X,E]=a.useState(!1),[U,pe]=a.useState(20),[ie,re]=a.useState(""),[F,ce]=a.useState([]),[ae,Q]=a.useState(""),[de,Te]=a.useState(""),[fe,Se]=a.useState(""),[te,we]=a.useState(null),[Pe,We]=a.useState([]),[Ke,Ne]=a.useState(!1),[_e,Oe]=a.useState(null),[ye,De]=a.useState(null),[se,J]=a.useState(!1),[me,ee]=a.useState([]),[he,le]=a.useState([]),[Ie,Ze]=a.useState(""),[at,oe]=a.useState(null),[Z,ue]=a.useState(null),[Ce,$e]=a.useState(null),ve=a.useCallback(async()=>{if(e){u(!0),m(null);try{switch(o){case"status":{const N=await As(r);f(N);break}case"changes":{const[N,H]=await Promise.all([As(r),$i(r)]);f(N),v(H),k(new Set),$(null),S(null),L(null);break}case"commits":{const N=await dv(U,r);q(N);break}case"branches":{const[N,H]=await Promise.all([pa(r),As(r)]);ce(N),f(H);break}case"worktrees":{const N=await pv(r);ee(N);break}case"stashes":{const N=await mr(r);le(N);break}case"remotes":{const N=await As(r);f(N);break}}}catch(N){m(xe(N)||"Failed to fetch git data"),i(xe(N)||"Failed to fetch git data","error")}finally{u(!1)}}},[o,e,U,i,r]);a.useEffect(()=>{e&&ve()},[ve,e]),a.useEffect(()=>{if(!e)return;const N=H=>{if(H.key==="Escape"){n();return}if((H.key==="ArrowUp"||H.key==="ArrowDown")&&H.altKey){H.preventDefault();const Ae=Ca.findIndex(ot=>ot.id===o);H.key==="ArrowUp"&&Ae>0?l(Ca[Ae-1].id):H.key==="ArrowDown"&&Ae<Ca.length-1&&l(Ca[Ae+1].id)}};return document.addEventListener("keydown",N),()=>document.removeEventListener("keydown",N)},[e,n,o]);const Ge=a.useCallback(async N=>{try{await ad(N,r),i(`Staged ${N.length} file(s)`,"success");const H=await $i(r);v(H),k(new Set),$(null),S(null),L(null)}catch(H){i(xe(H)||"Failed to stage files","error")}},[i,r]),je=a.useCallback(async N=>{try{await Nv(N,r),i(`Unstaged ${N.length} file(s)`,"success");const H=await $i(r);v(H),k(new Set),$(null),S(null),L(null)}catch(H){i(xe(H)||"Failed to unstage files","error")}},[i,r]),Ue=a.useCallback(async N=>{if(confirm(`Discard changes to ${N.length} file(s)? This cannot be undone.`))try{await Sv(N,r),i(`Discarded changes to ${N.length} file(s)`,"success");const[H,Ae]=await Promise.all([$i(r),As(r)]);v(H),f(Ae),k(new Set),$(null),S(null),L(null)}catch(H){i(xe(H)||"Failed to discard changes","error")}},[i,r]),He=a.useCallback(async N=>{if(N.preventDefault(),!!M.trim()){j(!0);try{const H=await rd(M.trim(),r);i(`Committed: ${H.hash}`,"success"),y("");const[Ae,ot]=await Promise.all([$i(r),As(r)]);v(Ae),f(ot),$(null),S(null),L(null)}catch(H){i(xe(H)||"Failed to commit","error")}finally{j(!1)}}},[M,i,r]),ge=a.useCallback(async()=>{if(M.trim()){j(!0);try{const N=b.filter(kt=>!kt.staged).map(kt=>kt.file);N.length>0&&await ad(N,r);const H=await rd(M.trim(),r);i(`Committed: ${H.hash}`,"success"),y("");const[Ae,ot]=await Promise.all([$i(r),As(r)]);v(Ae),f(ot),$(null),S(null),L(null)}catch(N){i(xe(N)||"Failed to commit","error")}finally{j(!1)}}},[M,b,i,r]),Fe=a.useCallback(async(N,H)=>{$({file:N,staged:H}),T(!0),L(null);const Ae=I.current+1;I.current=Ae;try{const ot=await wv(N,H,r);if(I.current!==Ae)return;S(ot)}catch(ot){if(I.current!==Ae)return;const kt=xe(ot)||"Failed to load file diff";S(null),L(kt),i(kt,"error")}finally{I.current===Ae&&T(!1)}},[i,r]),be=a.useCallback(N=>{k(H=>{const Ae=new Set(H);return Ae.has(N)?Ae.delete(N):Ae.add(N),Ae})},[]),Je=a.useCallback(async N=>{if(W===N){B(null),z(null);return}B(N),E(!0);try{const H=await Ur(N,r);z(H)}catch(H){i(xe(H)||"Failed to load diff","error"),z(null)}finally{E(!1)}},[W,i,r]),st=a.useCallback(()=>{pe(N=>Math.min(N+20,100))},[]),dt=a.useMemo(()=>{if(!ie.trim())return w;const N=ie.toLowerCase();return w.filter(H=>H.message.toLowerCase().includes(N)||H.author.toLowerCase().includes(N)||H.shortHash.toLowerCase().includes(N))},[w,ie]),Tt=a.useCallback(async N=>{if(N.preventDefault(),!!ae.trim()){u(!0);try{await fv(ae.trim(),de.trim()||void 0,r),i(`Created branch ${ae}`,"success"),Q(""),Te("");const H=await pa(r);ce(H)}catch(H){i(xe(H)||"Failed to create branch","error")}finally{u(!1)}}},[ae,de,i,r]),$t=a.useCallback(async N=>{u(!0);try{await gv(N,r),i(`Switched to ${N}`,"success");const[H,Ae]=await Promise.all([As(r),pa(r)]);f(H),ce(Ae)}catch(H){i(xe(H)||"Failed to checkout branch","error")}finally{u(!1)}},[i,r]),Dt=a.useCallback(async N=>{if(confirm(`Delete branch "${N}"?`)){u(!0);try{await id(N,void 0,r),i(`Deleted branch ${N}`,"success");const H=await pa(r);ce(H)}catch(H){if(xe(H).includes("not fully merged")){if(confirm("Branch has unmerged commits. Force delete?"))try{await id(N,!0,r),i(`Force deleted branch ${N}`,"success");const Ae=await pa(r);ce(Ae)}catch(Ae){i(xe(Ae)||"Failed to delete branch","error")}}else i(xe(H)||"Failed to delete branch","error")}finally{u(!1)}}},[i,r]),Bt=a.useMemo(()=>{if(!fe.trim())return F;const N=fe.toLowerCase();return F.filter(H=>H.name.toLowerCase().includes(N))},[F,fe]),qt=a.useCallback(async N=>{if(te===N){we(null),We([]),Oe(null),De(null);return}we(N),We([]),Oe(null),De(null),Ne(!0);try{const H=await hv(N,10,r);We(H)}catch{We([])}finally{Ne(!1)}},[te,r]),Lt=a.useCallback(async N=>{if(_e===N){Oe(null),De(null);return}Oe(N),De(null),J(!0);try{const H=await Ur(N,r);De(H)}catch{De(null)}finally{J(!1)}},[_e,r]),Ct=a.useCallback(()=>{we(null),We([]),Oe(null),De(null)},[]),xt=a.useCallback(async N=>{N.preventDefault(),oe("create");try{await yv(Ie.trim()||void 0,r),i("Changes stashed","success"),Ze("");const H=await mr(r);le(H)}catch(H){i(xe(H)||"Failed to stash changes","error")}finally{oe(null)}},[Ie,i,r]),Et=a.useCallback(async(N,H=!1)=>{oe(`apply-${N}`);try{await kv(N,H,r),i(H?"Stash popped":"Stash applied","success");const Ae=await mr(r);le(Ae)}catch(Ae){i(xe(Ae)||"Failed to apply stash","error")}finally{oe(null)}},[i,r]),Le=a.useCallback(async N=>{if(confirm(`Drop stash@{${N}}? This cannot be undone.`)){oe(`drop-${N}`);try{await jv(N,r),i("Stash dropped","success");const H=await mr(r);le(H)}catch(H){i(xe(H)||"Failed to drop stash","error")}finally{oe(null)}}},[i,r]),gt=a.useCallback(async()=>{ue("fetch");try{const N=await bv(void 0,r);$e(N),i(N.message||"Fetch completed",N.fetched?"success":"info");const H=await As(r);f(H)}catch(N){i(xe(N)||"Fetch failed","error")}finally{ue(null)}},[i,r]),ut=a.useCallback(async()=>{ue("pull");try{const N=await xv(r);$e(N),N.conflict?i("Merge conflict detected. Resolve manually.","error"):i(N.message||"Pull completed","success");const H=await As(r);f(H)}catch(N){i(xe(N)||"Pull failed","error")}finally{ue(null)}},[i,r]),Me=a.useCallback(async()=>{ue("push");try{const N=await vv(r);$e(N),i(N.message||"Push completed","success");const H=await As(r);f(H)}catch(N){i(xe(N)||"Push failed","error")}finally{ue(null)}},[i,r]),Qe=a.useMemo(()=>b.filter(N=>N.staged),[b]),rt=a.useMemo(()=>b.filter(N=>!N.staged),[b]);return e?t.jsx("div",{className:"modal-overlay open",onClick:N=>N.target===N.currentTarget&&n(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal gm-modal",ref:h,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h3",{children:[t.jsx(Al,{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:ve,disabled:c,title:"Refresh",children:t.jsx(hn,{size:14,className:c?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Pt,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:Ca.map(N=>{const H=N.icon;return t.jsxs("button",{role:"tab","aria-selected":o===N.id,className:`gm-nav-item${o===N.id?" active":""}`,onClick:()=>l(N.id),children:[t.jsx(H,{size:16}),t.jsx("span",{className:"gm-nav-label",children:N.label})]},N.id)})}),t.jsxs("div",{className:"gm-content",role:"tabpanel",children:[c&&t.jsxs("div",{className:"gm-loading",children:[t.jsx(it,{size:24,className:"spin"}),t.jsx("span",{children:"Loading..."})]}),d&&!c&&t.jsxs("div",{className:"gm-error",children:[t.jsx(ss,{size:18}),t.jsx("span",{children:d}),t.jsx("button",{className:"btn btn-sm",onClick:ve,children:"Retry"})]}),o==="status"&&!c&&p&&t.jsx(cA,{status:p,copyToClipboard:g}),o==="changes"&&!c&&t.jsx(dA,{status:p,stagedFiles:Qe,unstagedFiles:rt,selectedFiles:x,toggleFileSelection:be,onStageFiles:Ge,onUnstageFiles:je,onDiscardChanges:Ue,onSelectDiffFile:Fe,selectedDiffTarget:G,changeDiff:C,loadingChangeDiff:P,changeDiffError:_,commitMessage:M,setCommitMessage:y,onCommit:He,onStageAllAndCommit:ge,committing:R}),o==="commits"&&!c&&t.jsx(uA,{commits:dt,commitSearch:ie,setCommitSearch:re,selectedCommit:W,commitDiff:A,loadingDiff:X,onCommitClick:Je,onLoadMore:st,canLoadMore:w.length>=U&&U<100,copyToClipboard:g}),o==="branches"&&!c&&t.jsx(mA,{branches:Bt,branchSearch:fe,setBranchSearch:Se,newBranchName:ae,setNewBranchName:Q,branchBase:de,setBranchBase:Te,onCreateBranch:Tt,onCheckoutBranch:$t,onDeleteBranch:Dt,loading:c,allBranches:F,selectedBranch:te,branchCommits:Pe,loadingBranchCommits:Ke,expandedBranchCommit:_e,branchCommitDiff:ye,loadingBranchCommitDiff:se,onSelectBranch:qt,onBranchCommitClick:Lt,onCloseBranchDetails:Ct}),o==="worktrees"&&!c&&t.jsx(hA,{worktrees:me}),o==="stashes"&&!c&&t.jsx(pA,{stashes:he,stashMessage:Ie,setStashMessage:Ze,onCreateStash:xt,onApplyStash:Et,onDropStash:Le,stashLoading:at}),o==="remotes"&&!c&&t.jsx(fA,{status:p,remoteLoading:Z,lastRemoteResult:Ce,onFetch:gt,onPull:ut,onPush:Me,addToast:i,projectId:r,copyToClipboard:g})]})]})]})}):null}function cA({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(Os,{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(wi,{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(ss,{size:12}),"Modified"]}):t.jsxs(t.Fragment,{children:[t.jsx(tn,{size:12}),"Clean"]})})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Remote Sync"}),t.jsxs("span",{className:"gm-status-value",children:[e.ahead>0&&t.jsxs("span",{className:"gm-ahead",title:`${e.ahead} commit(s) ahead`,children:[t.jsx(yi,{size:12}),e.ahead]}),e.behind>0&&t.jsxs("span",{className:"gm-behind",title:`${e.behind} commit(s) behind`,children:[t.jsx(Wa,{size:12}),e.behind]}),e.ahead===0&&e.behind===0&&t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(tn,{size:12}),"Up to date"]})]})]})]})]})}function dA({status:e,stagedFiles:n,unstagedFiles:s,selectedFiles:i,toggleFileSelection:r,onStageFiles:o,onUnstageFiles:l,onDiscardChanges:c,onSelectDiffFile:u,selectedDiffTarget:d,changeDiff:m,loadingChangeDiff:h,changeDiffError:g,commitMessage:p,setCommitMessage:f,onCommit:b,onStageAllAndCommit:v,committing:x}){const k=s.filter(y=>i.has(`unstaged:${y.file}`)),M=n.filter(y=>i.has(`staged:${y.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(Os,{size:14}),e.branch]}),e.isDirty&&t.jsx("span",{className:"gm-dirty-badge",children:"Modified"})]}),t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Unstaged Changes (",s.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[k.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>o(k.map(y=>y.file)),title:"Stage selected",children:[t.jsx(Vt,{size:12})," Stage (",k.length,")"]}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>c(k.map(y=>y.file)),title:"Discard selected",children:t.jsx(Ka,{size:12})})]}),s.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>o(s.map(y=>y.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(y=>{const R=d?.file===y.file&&d.staged===!1;return t.jsxs("div",{className:`gm-file-item${R?" active":""}`,onClick:()=>u(y.file,!1),role:"button",tabIndex:0,onKeyDown:j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),u(y.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:j=>j.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`unstaged:${y.file}`),onChange:()=>r(`unstaged:${y.file}`)})}),t.jsx(Sm,{status:y.status}),t.jsx("span",{className:"gm-file-name",title:y.file,children:y.file}),t.jsx(Cm,{status:y.status}),t.jsx("button",{className:"gm-icon-btn",onClick:j=>{j.stopPropagation(),o([y.file])},title:"Stage file",children:t.jsx(Vt,{size:12})})]},`unstaged:${y.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:[M.length>0&&t.jsxs("button",{className:"btn btn-sm",onClick:()=>l(M.map(y=>y.file)),title:"Unstage selected",children:["Unstage (",M.length,")"]}),n.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(n.map(y=>y.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(y=>{const R=d?.file===y.file&&d.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${R?" active":""}`,onClick:()=>u(y.file,!0),role:"button",tabIndex:0,onKeyDown:j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),u(y.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:j=>j.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`staged:${y.file}`),onChange:()=>r(`staged:${y.file}`)})}),t.jsx(Sm,{status:y.status}),t.jsx("span",{className:"gm-file-name",title:y.file,children:y.file}),t.jsx(Cm,{status:y.status}),t.jsx("button",{className:"gm-icon-btn",onClick:j=>{j.stopPropagation(),l([y.file])},title:"Unstage file",children:t.jsx(Pt,{size:12})})]},`staged:${y.file}`)})})]}),(d||h||m||g)&&t.jsxs("div",{className:"gm-diff-section",children:[d&&t.jsxs("div",{className:"gm-diff-target",children:[t.jsx(eh,{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(it,{size:16,className:"spin"}),"Loading diff..."]}),g&&!h&&t.jsx("div",{className:"gm-diff-error",children:g}),m&&!h&&t.jsxs("div",{className:"gm-diff-viewer",children:[m.stat&&t.jsx("pre",{className:"gm-diff-stat",children:m.stat}),t.jsx("pre",{className:"gm-diff-patch",children:m.patch})]})]}),t.jsxs("form",{className:"gm-commit-form",onSubmit:b,children:[t.jsx("textarea",{className:"gm-commit-input",placeholder:"Commit message...",value:p,onChange:y=>f(y.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(it,{size:14,className:"spin"}):t.jsx(vi,{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 uA({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(Bi,{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:Zi(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(wi,{size:12})})}),i===m.hash&&t.jsx("div",{className:"gm-commit-diff",children:o?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(it,{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 mA({branches:e,branchSearch:n,setBranchSearch:s,newBranchName:i,setNewBranchName:r,branchBase:o,setBranchBase:l,onCreateBranch:c,onCheckoutBranch:u,onDeleteBranch:d,loading:m,allBranches:h,selectedBranch:g,branchCommits:p,loadingBranchCommits:f,expandedBranchCommit:b,branchCommitDiff:v,loadingBranchCommitDiff:x,onSelectBranch:k,onBranchCommitClick:M,onCloseBranchDetails:y}){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(Bi,{size:14}),t.jsx("input",{type:"text",placeholder:"Filter branches...",value:n,onChange:R=>s(R.target.value)})]})]}),t.jsxs("form",{className:"gm-create-form",onSubmit:c,children:[t.jsx("input",{type:"text",placeholder:"New branch name",value:i,onChange:R=>r(R.target.value),disabled:m}),t.jsxs("select",{value:o,onChange:R=>l(R.target.value),disabled:m,className:"gm-branch-select",children:[t.jsx("option",{value:"",children:"Base: HEAD"}),h.map(R=>t.jsx("option",{value:R.name,children:R.name},R.name))]}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:m||!i.trim(),children:[t.jsx(Vt,{size:14}),"Create"]})]}),t.jsx("div",{className:"gm-branches-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:n?"No matching branches":"No branches found"}):e.map(R=>t.jsxs("div",{children:[t.jsxs("div",{className:`gm-branch-item${R.isCurrent?" current":""}${g===R.name?" selected":""}`,onClick:()=>k(R.name),children:[t.jsxs("div",{className:"gm-branch-info",children:[t.jsxs("span",{className:"gm-branch-name",children:[R.isCurrent&&t.jsx(xn,{size:14,className:"gm-current-icon"}),R.name]}),R.remote&&t.jsxs("span",{className:"gm-branch-remote",children:["→ ",R.remote]}),R.lastCommitDate&&t.jsx("span",{className:"gm-branch-date",children:Zi(R.lastCommitDate)})]}),t.jsx("div",{className:"gm-branch-actions",children:!R.isCurrent&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:j=>{j.stopPropagation(),u(R.name)},disabled:m,title:"Checkout",children:t.jsx(Os,{size:14})}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:j=>{j.stopPropagation(),d(R.name)},disabled:m,title:"Delete",children:t.jsx(Ht,{size:14})})]})})]}),g===R.name&&t.jsxs("div",{className:"gm-branch-details",children:[t.jsxs("div",{className:"gm-branch-details-header",children:[t.jsxs("span",{className:"gm-branch-details-title",children:[t.jsx(za,{size:14}),"Commits on ",R.name]}),t.jsx("button",{className:"gm-icon-btn",onClick:y,title:"Close","data-testid":"close-branch-details",children:t.jsx(Pt,{size:14})})]}),f?t.jsxs("div",{className:"gm-branch-details-loading",children:[t.jsx(it,{size:16,className:"spin"}),"Loading commits..."]}):p.length===0?t.jsx("div",{className:"gm-empty",children:"No commits found"}):t.jsx("div",{className:"gm-branch-commits-list",children:p.map(j=>t.jsxs("div",{className:"gm-branch-commit",children:[t.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>M(j.hash),"data-testid":`branch-commit-${j.shortHash}`,children:[t.jsx("span",{className:"gm-commit-hash",children:j.shortHash}),t.jsx("span",{className:"gm-commit-message",title:j.message,children:j.message}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:j.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Zi(j.date)}),j.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),b===j.hash&&t.jsx("div",{className:"gm-commit-diff",children:x?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(it,{size:16,className:"spin"}),"Loading diff..."]}):v?t.jsxs(t.Fragment,{children:[v.stat&&t.jsx("pre",{className:"gm-diff-stat",children:v.stat}),t.jsx("pre",{className:"gm-diff-patch",children:v.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},j.hash))})]})]},R.name))})]})}function hA({worktrees:e}){return t.jsxs("div",{className:"gm-panel","data-testid":"worktrees-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Worktrees"}),t.jsxs("div",{className:"gm-worktree-stats",children:[t.jsxs("span",{children:[e.length," total"]}),t.jsx("span",{className:"gm-stat-separator",children:"•"}),t.jsxs("span",{children:[e.filter(n=>n.taskId).length," in use"]})]})]}),t.jsx("div",{className:"gm-worktrees-list",children:e.map(n=>t.jsx("div",{className:`gm-worktree-item${n.isMain?" main":""}`,children:t.jsxs("div",{className:"gm-worktree-info",children:[t.jsxs("div",{className:"gm-worktree-path-row",children:[n.isMain&&t.jsx("span",{className:"gm-badge main",children:"main"}),n.isBare&&t.jsx("span",{className:"gm-badge bare",children:"bare"}),t.jsx("span",{className:"gm-worktree-path",title:n.path,children:n.path.split("/").pop()||n.path})]}),t.jsxs("div",{className:"gm-worktree-detail",children:[n.branch&&t.jsxs("span",{className:"gm-worktree-branch",children:[t.jsx(Os,{size:12}),n.branch]}),n.taskId&&t.jsx("span",{className:"gm-worktree-task",children:n.taskId})]})]})},n.path))})]})}function pA({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(it,{size:14,className:"spin"}):t.jsx(Zr,{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(Os,{size:12}),c.branch]}),t.jsx("span",{children:Zi(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(it,{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(it,{size:14,className:"spin"}):t.jsx(Ht,{size:14})})]})]},c.index))})]})}function fA({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:i,onPull:r,onPush:o,addToast:l,projectId:c,copyToClipboard:u}){const d=J=>{try{return new URL(J).hostname}catch{return J.replace(/^git@/,"").split(":")[0]||J}},[m,h]=a.useState([]),[g,p]=a.useState(!1),[f,b]=a.useState(null),[v,x]=a.useState(""),[k,M]=a.useState(""),[y,R]=a.useState(null),[j,C]=a.useState(""),[S,P]=a.useState(""),[T,_]=a.useState(!1),[L,G]=a.useState([]),[$,I]=a.useState(!1),[w,q]=a.useState(null),[W,B]=a.useState([]),[A,z]=a.useState(!1),[X,E]=a.useState(null),U=m.find(J=>J.name===w),[pe,ie]=a.useState(null),[re,F]=a.useState(null),[ce,ae]=a.useState(!1),[Q,de]=a.useState(null),[Te,fe]=a.useState(null),[Se,te]=a.useState(!1);a.useEffect(()=>{we()},[]),a.useEffect(()=>{e&&e.ahead>0?Pe():e&&e.ahead===0&&G([])},[e?.ahead]),a.useEffect(()=>{m.length>0&&!w&&q(m[0].name)},[m]),a.useEffect(()=>{w?We(w):(B([]),E(null))},[w]),a.useEffect(()=>{w&&!m.find(J=>J.name===w)&&q(m.length>0?m[0].name:null)},[m,w]);const we=async()=>{p(!0);try{const J=await tv(c);h(J)}catch(J){l(xe(J)||"Failed to load remotes","error")}finally{p(!1)}},Pe=async()=>{I(!0);try{const J=await uv(c);G(J)}catch{G([])}finally{I(!1)}},We=async J=>{z(!0),E(null);try{const me=await mv(J,void 0,10,c);B(me)}catch(me){E(xe(me)||"Failed to load remote commits"),B([])}finally{z(!1)}},Ke=async J=>{if(J.preventDefault(),!(!v.trim()||!k.trim())){b("add");try{await nv(v.trim(),k.trim(),c),l(`Remote '${v}' added successfully`,"success"),x(""),M(""),_(!1),await we()}catch(me){l(xe(me)||"Failed to add remote","error")}finally{b(null)}}},Ne=async J=>{if(confirm(`Are you sure you want to remove remote '${J}'?`)){b(`remove-${J}`);try{await sv(J,c),l(`Remote '${J}' removed`,"success"),await we()}catch(me){l(xe(me)||"Failed to remove remote","error")}finally{b(null)}}},_e=async J=>{if(S.trim()){b(`rename-${J}`);try{await iv(J,S.trim(),c),l(`Remote renamed to '${S.trim()}'`,"success"),R(null),P(""),await we()}catch(me){l(xe(me)||"Failed to rename remote","error")}finally{b(null)}}},Oe=async J=>{if(j.trim()){b(`url-${J}`);try{await av(J,j.trim(),c),l("Remote URL updated","success"),R(null),C(""),await we()}catch(me){l(xe(me)||"Failed to update remote URL","error")}finally{b(null)}}},ye=a.useCallback(async(J,me)=>{if(me==="ahead"){if(pe===J){ie(null),F(null);return}ie(J),F(null),ae(!0);try{const ee=await Ur(J);F(ee)}catch{F(null)}finally{ae(!1)}}else{if(Q===J){de(null),fe(null);return}de(J),fe(null),te(!0);try{const ee=await Ur(J);fe(ee)}catch{fe(null)}finally{te(!1)}}},[pe,Q]),De=J=>{R(`url-${J.name}`),C(J.pushUrl||J.fetchUrl)},se=J=>{R(`name-${J.name}`),P(J.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:()=>_(!T),disabled:f!==null,title:T?"Cancel":"Add Remote",children:T?t.jsx(Pt,{size:14}):t.jsx(Vt,{size:14})})]}),T&&t.jsxs("form",{className:"gm-remote-form",onSubmit:Ke,children:[t.jsx("input",{type:"text",placeholder:"Remote name",value:v,onChange:J=>x(J.target.value),disabled:f==="add",className:"gm-input"}),t.jsx("input",{type:"text",placeholder:"Repository URL",value:k,onChange:J=>M(J.target.value),disabled:f==="add",className:"gm-input gm-input-url"}),t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:!v.trim()||!k.trim()||f==="add",children:[f==="add"?t.jsx(it,{size:12,className:"spin"}):t.jsx(Vt,{size:12}),"Add"]})]}),g?t.jsxs("div",{className:"gm-loading",children:[t.jsx(it,{size:16,className:"spin"}),"Loading..."]}):m.length===0?t.jsx("div",{className:"gm-empty",children:"No remotes"}):m.map(J=>t.jsxs("div",{className:`gm-remote-selector-item${w===J.name?" selected":""}`,onClick:()=>q(J.name),role:"button",tabIndex:0,children:[t.jsxs("div",{className:"gm-remote-selector-info",children:[t.jsxs("span",{className:"gm-remote-selector-name",children:[J.name,J.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),t.jsx("span",{className:"gm-remote-selector-host",children:d(J.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:me=>{me.stopPropagation(),Ne(J.name)},disabled:f!==null,title:"Remove remote",children:t.jsx(Ht,{size:14})})]},J.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[w&&U?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:w}),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(yi,{size:14}),e.ahead," to push"]}),e.behind>0&&t.jsxs("div",{className:"gm-remote-indicator behind",children:[t.jsx(Wa,{size:14}),e.behind," to pull"]})]})]}),t.jsxs("div",{className:"gm-remote-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:i,disabled:n!==null||g,children:[n==="fetch"?t.jsx(it,{size:14,className:"spin"}):t.jsx(hn,{size:14}),"Fetch"]}),t.jsxs("button",{className:"btn btn-primary",onClick:r,disabled:n!==null||g,children:[n==="pull"?t.jsx(it,{size:14,className:"spin"}):t.jsx(es,{size:14}),"Pull"]}),t.jsxs("button",{className:"btn btn-primary",onClick:o,disabled:n!==null||g,children:[n==="push"?t.jsx(it,{size:14,className:"spin"}):t.jsx(yi,{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:"}),y===`url-${w}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:j,onChange:J=>C(J.target.value),className:"gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Oe(w),disabled:f===`url-${w}`,children:f===`url-${w}`?t.jsx(it,{size:12,className:"spin"}):t.jsx(xn,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{R(null),C("")},title:"Cancel",children:t.jsx(Pt,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:U.fetchUrl,children:U.fetchUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>u(U.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:t.jsx(wi,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>De(U),disabled:f!==null,title:"Edit remote URL",children:t.jsx(Hn,{size:14})})]})]}),U.pushUrl&&U.pushUrl!==U.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:U.pushUrl,children:U.pushUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>u(U.pushUrl,"push URL"),title:"Copy push URL",children:t.jsx(wi,{size:14})})]})]}),t.jsx("div",{className:"gm-remote-detail-name-row",children:y===`name-${w}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:S,onChange:J=>P(J.target.value),className:"gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>_e(w),disabled:f===`rename-${w}`,children:f===`rename-${w}`?t.jsx(it,{size:12,className:"spin"}):t.jsx(xn,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{R(null),P("")},title:"Cancel",children:t.jsx(Pt,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>se(U),disabled:f!==null,title:"Edit remote name",children:t.jsx(Hn,{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(yi,{size:14}),"Commits to Push (",e.ahead,")"]})}),$?t.jsxs("div",{className:"gm-loading",children:[t.jsx(it,{size:14,className:"spin"}),"Loading..."]}):L.length>0?t.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:L.map(J=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>ye(J.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:J.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:J.message,children:J.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:J.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Zi(J.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:pe===J.hash?t.jsx(zt,{size:14}):t.jsx(en,{size:14})})]}),pe===J.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:ce?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(it,{size:16,className:"spin"}),"Loading diff..."]}):re?t.jsxs(t.Fragment,{children:[J.message&&t.jsx("div",{className:"gm-commit-message-full",children:J.message}),re.stat&&t.jsx("pre",{className:"gm-diff-stat",children:re.stat}),t.jsx("pre",{className:"gm-diff-patch",children:re.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},J.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(oh,{size:14}),"Recent commits on ",w]})}),A?t.jsxs("div",{className:"gm-loading",children:[t.jsx(it,{size:14,className:"spin"}),"Loading commits..."]}):X?t.jsxs("div",{className:"gm-error",children:[t.jsx(ss,{size:14}),X]}):W.length===0?t.jsxs("div",{className:"gm-empty",children:["No commits found on ",w,". Try fetching first."]}):t.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:W.map(J=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>ye(J.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:J.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:J.message,children:J.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:J.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Zi(J.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:Q===J.hash?t.jsx(zt,{size:14}):t.jsx(en,{size:14})})]}),Q===J.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:Se?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(it,{size:16,className:"spin"}),"Loading diff..."]}):Te?t.jsxs(t.Fragment,{children:[J.message&&t.jsx("div",{className:"gm-commit-message-full",children:J.message}),Te.stat&&t.jsx("pre",{className:"gm-diff-stat",children:Te.stat}),t.jsx("pre",{className:"gm-diff-patch",children:Te.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},J.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 Ea={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function gA(e,n){return e&&n?`${e}/${n}`:""}function bA(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 xA(e){switch(e){case"file-text":return Ni;case"check-circle":return tn;case"shield":return Pb;case"zap":return vn;case"eye":return Vi;case"globe":return to;case"layout-grid":return Ci;default:return tn}}function vA(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 yA({isOpen:e,onClose:n,addToast:s,projectId:i}){const[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState(!0),[m,h]=a.useState(!0),[g,p]=a.useState("my-steps"),[f,b]=a.useState(null),[v,x]=a.useState(!1),[k,M]=a.useState(Ea),[y,R]=a.useState(!1),[j,C]=a.useState(!1),[S,P]=a.useState(null),[T,_]=a.useState(null),[L,G]=a.useState({}),[$,I]=a.useState([]),w=a.useCallback(async()=>{try{d(!0);const F=await oo(i);o(F)}catch(F){s(xe(F)||"Failed to load workflow steps","error")}finally{d(!1)}},[s,i]),q=a.useCallback(async()=>{try{const F=await Xa(i);G(F||{})}catch{}},[i]),W=a.useCallback(async()=>{try{const F=await is();I(F.models||[])}catch{}},[]),B=a.useCallback(async()=>{try{h(!0);const F=await oy();c(F.templates)}catch(F){s(xe(F)||"Failed to load templates","error")}finally{h(!1)}},[s]);a.useEffect(()=>{e&&(w(),B(),q(),W())},[e,w,B,q,W]);const A=a.useCallback(()=>{x(!0),b(null),M(Ea)},[]),z=a.useCallback(F=>{b(F.id),x(!1),M({name:F.name,description:F.description,mode:F.mode||"prompt",phase:F.phase||"pre-merge",prompt:F.prompt,scriptName:F.scriptName||"",enabled:F.enabled,defaultOn:F.defaultOn||!1,modelProvider:F.modelProvider||"",modelId:F.modelId||""})},[]),X=a.useCallback(()=>{b(null),x(!1),M(Ea)},[]),E=a.useCallback(async()=>{if(!k.name.trim()||!k.description.trim()){s("Name and description are required","error");return}R(!0);try{const F=k.mode==="prompt"&&k.modelProvider&&k.modelId?{modelProvider:k.modelProvider,modelId:k.modelId}:k.mode==="prompt"?{modelProvider:void 0,modelId:void 0}:{};if(v){const ce={name:k.name.trim(),description:k.description.trim(),mode:k.mode,phase:k.phase,prompt:k.mode==="prompt"&&k.prompt.trim()||void 0,scriptName:k.mode==="script"?k.scriptName.trim():void 0,enabled:k.enabled,defaultOn:k.defaultOn||void 0,...F};await ud(ce,i),s("Workflow step created","success")}else f&&(await iy(f,{name:k.name.trim(),description:k.description.trim(),mode:k.mode,phase:k.phase,prompt:k.mode==="prompt"?k.prompt:"",scriptName:k.mode==="script"?k.scriptName.trim():void 0,enabled:k.enabled,defaultOn:k.defaultOn,...F},i),s("Workflow step updated","success"));x(!1),b(null),M(Ea),await w()}catch(F){s(xe(F)||"Failed to save workflow step","error")}finally{R(!1)}},[k,v,f,s,w]),U=a.useCallback(async F=>{try{await ay(F,i),s("Workflow step deleted","success"),P(null),f===F&&(b(null),M(Ea)),await w()}catch(ce){s(xe(ce)||"Failed to delete workflow step","error")}},[f,s,w]),pe=a.useCallback(async()=>{if(!(!f&&!v)&&k.mode==="prompt"){if(v){if(!k.name.trim()||!k.description.trim()){s("Name and description are required before refining","error");return}R(!0);try{const F=k.modelProvider&&k.modelId?{modelProvider:k.modelProvider,modelId:k.modelId}:{},ce={name:k.name.trim(),description:k.description.trim(),mode:"prompt",prompt:k.prompt.trim()||void 0,enabled:k.enabled,defaultOn:k.defaultOn||void 0,...F},ae=await ud(ce,i);x(!1),b(ae.id),C(!0);const Q=await md(ae.id,i);M(de=>({...de,prompt:Q.prompt})),s("Prompt refined with AI","success"),await w()}catch(F){s(xe(F)||"Failed to refine prompt","error")}finally{R(!1),C(!1)}return}if(f){C(!0);try{const F=await md(f,i);M(ce=>({...ce,prompt:F.prompt})),s("Prompt refined with AI","success"),await w()}catch(F){s(xe(F)||"Failed to refine prompt","error")}finally{C(!1)}}}},[f,v,k,s,w]),ie=a.useCallback(async F=>{_(F.id);try{await ly(F.id,i),s(`Added ${F.name} workflow step`,"success"),await w(),p("my-steps")}catch(ce){const ae=xe(ce);ae?.includes("already exists")?s(`A workflow step named '${F.name}' already exists`,"error"):s(ae||"Failed to add workflow step from template","error")}finally{_(null)}},[s,w]);if(!e)return null;const re=v||f!==null;return t.jsx("div",{className:"modal-overlay open",onClick:n,"data-testid":"workflow-step-manager",children:t.jsxs("div",{className:"modal workflow-step-manager-modal",onClick:F=>F.stopPropagation(),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:[!re&&t.jsxs("div",{className:"wfm-tab-row",children:[t.jsxs("button",{className:`btn ${g==="my-steps"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>p("my-steps"),"data-testid":"tab-my-steps",children:[t.jsx(Of,{size:14}),"My Workflow Steps (",r.length,")"]}),t.jsxs("button",{className:`btn ${g==="templates"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>p("templates"),"data-testid":"tab-templates",children:[t.jsx(Ci,{size:14}),"Templates (",l.length,")"]})]}),g==="my-steps"&&!re&&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(F=>t.jsx("div",{className:"wfm-step-card","data-testid":`workflow-step-${F.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:F.name}),t.jsx("span",{className:`wfm-badge ${F.enabled?"wfm-badge-enabled":"wfm-badge-disabled"}`,children:F.enabled?"Enabled":"Disabled"}),t.jsx("span",{className:`wfm-badge ${(F.mode||"prompt")==="script"?"wfm-badge-script":"wfm-badge-prompt"}`,children:(F.mode||"prompt")==="script"?"Script":"AI Prompt"}),t.jsx("span",{className:`wfm-badge ${(F.phase||"pre-merge")==="post-merge"?"wfm-badge-post-merge":"wfm-badge-pre-merge"}`,children:(F.phase||"pre-merge")==="post-merge"?"Post-merge":"Pre-merge"}),F.defaultOn&&t.jsx("span",{className:"wfm-badge wfm-badge-default-on",children:"Default on"})]}),t.jsx("div",{className:"wfm-step-card-desc",children:F.description})]}),t.jsxs("div",{className:"wfm-step-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>z(F),title:"Edit","aria-label":`Edit ${F.name}`,children:t.jsx(Hn,{size:14})}),S===F.id?t.jsxs("div",{className:"wfm-delete-confirm",children:[t.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>U(F.id),title:"Confirm delete","aria-label":`Confirm delete ${F.name}`,children:t.jsx(xn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>P(null),title:"Cancel delete","aria-label":"Cancel delete",children:t.jsx(Pt,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>P(F.id),title:"Delete","aria-label":`Delete ${F.name}`,children:t.jsx(Ht,{size:14})})]})]})},F.id))})]}),g==="templates"&&!re&&t.jsx(t.Fragment,{children:m?t.jsxs("div",{className:"wfm-loading",children:[t.jsx(it,{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(F=>{const ce=xA(F.icon),ae=vA(F.category),Q=T===F.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`template-${F.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(ce,{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:F.name}),t.jsx("span",{className:ae,children:F.category})]}),t.jsx("div",{className:"wfm-template-desc",children:F.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>ie(F),disabled:Q,"data-testid":`add-template-${F.id}`,children:Q?t.jsxs(t.Fragment,{children:[t.jsx(it,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Vt,{size:12}),"Add"]})})]})]})},F.id)})})}),re&&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:k.name,onChange:F=>M(ce=>({...ce,name:F.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:k.description,onChange:F=>M(ce=>({...ce,description:F.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 ${k.mode==="prompt"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>M(F=>({...F,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[t.jsx(li,{size:14}),"AI Prompt"]}),t.jsxs("button",{className:`btn ${k.mode==="script"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>M(F=>({...F,mode:"script",prompt:"",modelProvider:"",modelId:""})),"data-testid":"mode-script",children:[t.jsx(Bs,{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 ${k.phase==="pre-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>M(F=>({...F,phase:"pre-merge"})),"data-testid":"phase-pre-merge",children:"Pre-merge"}),t.jsx("button",{className:`btn ${k.phase==="post-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>M(F=>({...F,phase:"post-merge"})),"data-testid":"phase-post-merge",children:"Post-merge"})]}),t.jsx("div",{className:"wfm-field-hint",children:k.phase==="pre-merge"?"Runs before merge — can block merge on failure":"Runs after merge success — failures are logged but do not block"})]}),k.mode==="prompt"&&t.jsxs("div",{className:"wfm-field",children:[t.jsxs("div",{className:"wfm-prompt-header",children:[t.jsx("label",{children:"Agent Prompt"}),t.jsxs("button",{className:"btn-icon wfm-refine-btn",onClick:pe,disabled:!k.description.trim()||j,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[j?t.jsx(it,{size:12,className:"spin"}):t.jsx(Dn,{size:12}),t.jsx("span",{children:"Refine with AI"})]})]}),t.jsx("textarea",{value:k.prompt,onChange:F=>M(ce=>({...ce,prompt:F.target.value})),placeholder:"Leave empty to use AI refinement",rows:6,className:"wfm-prompt-textarea","data-testid":"workflow-step-prompt"})]}),k.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"}),k.modelProvider&&k.modelId&&t.jsxs("button",{type:"button",className:"btn-icon wfm-model-clear-btn",onClick:()=>M(F=>({...F,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[t.jsx(Pt,{size:12}),t.jsx("span",{children:"Use default"})]})]}),t.jsx("span",{className:"wfm-model-hint",children:k.modelProvider&&k.modelId?`Using ${k.modelProvider}/${k.modelId}`:"Using global default model"}),t.jsx("div",{"data-testid":"workflow-step-model-select",children:t.jsx(wn,{models:$,value:gA(k.modelProvider,k.modelId),onChange:F=>{const ce=bA(F);M(ae=>({...ae,modelProvider:ce.provider,modelId:ce.modelId}))},placeholder:"Select a model override…",label:"Model override for this workflow step"})})]}),k.mode==="script"&&t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Script"}),Object.keys(L).length===0?t.jsx("div",{className:"wfm-no-scripts","data-testid":"no-scripts-message",children:"No scripts configured. Add scripts in Settings → Scripts first."}):t.jsxs("select",{value:k.scriptName,onChange:F=>M(ce=>({...ce,scriptName:F.target.value})),"data-testid":"workflow-step-script-select",children:[t.jsx("option",{value:"",children:"Select a script…"}),Object.entries(L).map(([F,ce])=>t.jsxs("option",{value:F,children:[F," (",ce,")"]},F))]})]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:k.enabled,onChange:F=>M(ce=>({...ce,enabled:F.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:k.defaultOn,onChange:F=>M(ce=>({...ce,defaultOn:F.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:X,disabled:y,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:E,disabled:y||!k.name.trim()||!k.description.trim()||k.mode==="script"&&!k.scriptName.trim(),"data-testid":"save-workflow-step",children:y?"Saving...":v?"Create":"Save"})]})]})]})]})}),!re&&t.jsx("div",{className:"wfm-footer",children:t.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:A,"data-testid":"add-workflow-step",children:[t.jsx(Vt,{size:14}),"Add Workflow Step"]})})]})})}const kA=36e5,jA=3e5,jl=[{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 wA(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 NA(e){return typeof e!="number"||!Number.isFinite(e)?kA:Math.max(jA,Math.round(e))}function cP(e){if(jl.some(s=>s.value===e))return[...jl];const n={value:e,label:`${wA(e)} (custom)`};return[...jl,n].sort((s,i)=>s.value-i.value)}const SA=4,CA=5*6e4;function EA(e){const n=NA(e?.heartbeatIntervalMs);return Math.max(n*SA,CA)}function MA(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 _A(e){const{state:n,lastHeartbeatAt:s,lastError:i,pauseReason:r,runtimeConfig:o}=e,l=MA(e);if(n==="terminated")return{label:"Terminated",icon:t.jsx(ls,{size:14}),color:"var(--state-error-text)",stateDerived:!0};if(n==="error")return{label:i??"Error",icon:t.jsx(Ss,{size:14}),color:"var(--state-error-text)",stateDerived:!i};if(n==="paused")return{label:r?`Paused: ${r}`:"Paused",icon:t.jsx(Fs,{size:14}),color:"var(--state-paused-text)",stateDerived:!r};if(n==="running"||l&&n==="active")return{label:"Running",icon:t.jsx(Ss,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:t.jsx(an,{size:14}),color:"var(--text-secondary)",stateDerived:!1};const c=new Date(s).getTime(),u=Date.now()-c,d=EA(o);return u>d?{label:"Unresponsive",icon:t.jsx(Ss,{size:14}),color:"var(--state-error-text)",stateDerived:!1}:{label:"Healthy",icon:t.jsx(Kg,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}const Ma=[{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 AA({isOpen:e,onClose:n,addToast:s,projectId:i}){const[r,o]=a.useState([]),[l,c]=a.useState(!1),[u,d]=a.useState(!1),[m,h]=a.useState(""),[g,p]=a.useState("custom"),[f,b]=a.useState("all"),[v,x]=a.useState(()=>{if(typeof window>"u")return"list";const w=Nn("fn-agent-view",i);return w==="board"||w==="list"?w:"list"});a.useEffect(()=>{const w=Nn("fn-agent-view",i);if(w==="board"||w==="list"){x(w);return}x("list")},[i]),a.useEffect(()=>{ts("fn-agent-view",v,i)},[i,v]);const[k,M]=a.useState(null),y=a.useRef(null),R=a.useMemo(()=>f==="all"?r.filter(w=>w.state!=="terminated"):r,[r,f]),j=a.useCallback(async()=>{c(!0);try{const q=await oa(f!=="all"?{state:f}:void 0,i);o(q)}catch(w){s(`Failed to load agents: ${xe(w)}`,"error")}finally{c(!1)}},[f,s,i]);a.useEffect(()=>{e&&j()},[e,j]),a.useEffect(()=>{if(!e)return;const w=setInterval(()=>{j()},3e4);return()=>{clearInterval(w)}},[e,j]);const C=async()=>{if(m.trim())try{await by({name:m.trim(),role:g},i),s(`Agent "${m}" created`,"success"),h(""),d(!1),j()}catch(w){s(`Failed to create agent: ${xe(w)}`,"error")}},S=async(w,q)=>{try{await vy(w,q,i),s(`Agent state updated to ${q}`,"success"),j()}catch(W){s(`Failed to update state: ${xe(W)}`,"error")}},P=async(w,q)=>{if(confirm(`Delete agent "${q}"? This cannot be undone.`))try{await yy(w,i),s(`Agent "${q}" deleted`,"success"),j()}catch(W){s(`Failed to delete agent: ${xe(W)}`,"error")}},T=async(w,q)=>{const W=r.find(B=>B.id===w);if(W){if(W.role===q){M(null);return}try{await xy(w,{role:q},i),s(`Agent role updated to ${Ma.find(B=>B.value===q)?.label??q}`,"success"),M(null),j()}catch(B){s(`Failed to update role: ${xe(B)}`,"error")}}},_=(w,q)=>{w.key==="Escape"&&M(null)},L=w=>Ma.find(q=>q.value===w)?.label??w,G=w=>Ma.find(q=>q.value===w)?.icon??"◆",$=w=>_A(w),I=w=>w.color==="var(--state-active-text)"?"active":w.color==="var(--state-paused-text)"?"paused":w.color==="var(--state-error-text)"?"error":"muted";return e?t.jsx("div",{className:"modal-overlay open",onClick:w=>w.target===w.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(an,{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(Ci,{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(Tl,{size:16})})]}),t.jsx("button",{className:"btn-icon",onClick:()=>void j(),title:"Refresh",disabled:l,children:t.jsx(hn,{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(Dr,{size:14}),t.jsxs("select",{className:"agent-state-filter-select",value:f,onChange:w=>b(w.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--primary",onClick:()=>d(!u),children:[t.jsx(Vt,{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:w=>h(w.target.value),onKeyDown:w=>w.key==="Enter"&&C(),className:"input",autoFocus:!0}),t.jsx("select",{className:"select",value:g,onChange:w=>p(w.target.value),children:Ma.map(w=>t.jsxs("option",{value:w.value,children:[w.icon," ",w.label]},w.value))}),t.jsx("button",{className:"btn btn--primary",onClick:()=>void C(),children:"Create"})]}),t.jsx("div",{className:v==="board"?"agent-board":"agent-list",children:R.length===0?t.jsxs("div",{className:"agent-empty",children:[t.jsx(an,{size:48,opacity:.3}),t.jsx("p",{children:"No agents found"}),t.jsx("p",{className:"text-secondary",children:"Create an agent to get started"})]}):v==="board"?R.map(w=>{const q=$(w),W=I(q);return t.jsxs("div",{className:"agent-board-card","data-state":w.state,children:[t.jsxs("div",{className:"agent-board-header",children:[t.jsx("span",{className:"agent-board-icon",children:G(w.role)}),t.jsx("span",{className:"agent-board-badge","data-state":w.state,children:w.state}),t.jsx("span",{className:"agent-board-health","data-health":W,title:q.label,children:q.icon})]}),t.jsx("div",{className:"agent-board-name",title:w.name,children:w.name}),t.jsx("div",{className:"agent-board-id",children:w.id}),t.jsxs("div",{className:"agent-board-actions",children:[w.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void S(w.id,"active"),title:"Activate",children:t.jsx(rn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(w.id,w.name),title:"Delete",children:t.jsx(Ht,{size:14})})]}),w.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void S(w.id,"paused"),title:"Pause",children:t.jsx(Fs,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void S(w.id,"terminated"),title:"Stop",children:t.jsx(ls,{size:14})})]}),w.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void S(w.id,"active"),title:"Resume",children:t.jsx(rn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void S(w.id,"terminated"),title:"Stop",children:t.jsx(ls,{size:14})})]}),w.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void S(w.id,"paused"),title:"Pause",children:t.jsx(Fs,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void S(w.id,"terminated"),title:"Stop",children:t.jsx(ls,{size:14})})]}),w.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void S(w.id,"active"),title:"Retry",children:t.jsx(rn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void S(w.id,"terminated"),title:"Stop",children:t.jsx(ls,{size:14})})]}),w.state==="terminated"&&t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(w.id,w.name),title:"Delete",children:t.jsx(Ht,{size:14})})]})]},w.id)}):R.map(w=>{const q=$(w),W=I(q);return t.jsxs("div",{className:"agent-card","data-state":w.state,children:[t.jsxs("div",{className:"agent-card-header",children:[t.jsxs("div",{className:"agent-info",children:[k===w.id?t.jsx("select",{ref:y,className:"select agent-role-select",value:w.role,onChange:B=>void T(w.id,B.target.value),onKeyDown:B=>_(B,w.id),onBlur:()=>M(null),autoFocus:!0,children:Ma.map(B=>t.jsxs("option",{value:B.value,children:[B.icon," ",B.label]},B.value))}):t.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>M(w.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:B=>{(B.key==="Enter"||B.key===" ")&&M(w.id)},children:G(w.role)}),t.jsxs("div",{className:"agent-meta",children:[t.jsx("span",{className:"agent-name",children:w.name}),t.jsx("span",{className:"agent-id text-secondary",children:w.id})]})]}),t.jsxs("div",{className:"agent-badges",children:[t.jsx("span",{className:"badge agent-list-state-badge","data-state":w.state,children:w.state}),t.jsxs("span",{className:"badge agent-list-health-badge","data-health":W,title:q.label,children:[q.icon,!q.stateDerived&&` ${q.label}`]}),t.jsx("span",{className:"badge text-secondary",children:L(w.role)})]})]}),t.jsxs("div",{className:"agent-card-body",children:[w.taskId&&t.jsxs("div",{className:"agent-task",children:[t.jsx("span",{className:"text-secondary",children:"Working on:"}),t.jsx("span",{className:"badge",children:w.taskId})]}),w.lastHeartbeatAt&&t.jsxs("div",{className:"agent-heartbeat",children:[t.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),t.jsx("span",{children:new Date(w.lastHeartbeatAt).toLocaleString()})]})]}),t.jsxs("div",{className:"agent-card-actions",children:[w.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void S(w.id,"active"),title:"Activate",children:[t.jsx(rn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(w.id,w.name),title:"Delete",children:[t.jsx(Ht,{size:14})," Delete"]})]}),w.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void S(w.id,"paused"),title:"Pause",children:[t.jsx(Fs,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void S(w.id,"terminated"),title:"Stop",children:[t.jsx(ls,{size:14})," Stop"]})]}),w.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void S(w.id,"active"),title:"Resume",children:[t.jsx(rn,{size:14})," Resume"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void S(w.id,"terminated"),title:"Stop",children:[t.jsx(ls,{size:14})," Stop"]})]}),w.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void S(w.id,"paused"),title:"Pause",children:[t.jsx(Fs,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void S(w.id,"terminated"),title:"Stop",children:[t.jsx(ls,{size:14})," Stop"]})]}),w.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void S(w.id,"active"),title:"Retry",children:[t.jsx(rn,{size:14})," Retry"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void S(w.id,"terminated"),title:"Stop",children:[t.jsx(ls,{size:14})," Stop"]})]}),w.state==="terminated"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm btn--primary",onClick:()=>void S(w.id,"active"),title:"Start",children:[t.jsx(rn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(w.id,w.name),title:"Delete",children:[t.jsx(Ht,{size:14})," Delete"]})]})]})]},w.id)})})]})]})}):null}function TA({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 qx();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]),g=a.useCallback(async x=>{l(x?"enabling":"disabling"),u(null);try{const k=await Vx(x);d.current&&u({kind:k.enabled?"enabled":"disabled",restartRequired:k.restartRequired}),n?.(k.enabled),await m()}catch(k){d.current&&u({kind:"error",message:k instanceof Error?k.message:String(k)})}finally{d.current&&l(null)}},[n,m]),p=i?.binary.available??!1,f=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(it,{size:12,className:"animate-spin"}),"Testing…"]}):"Test"}),f?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void g(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void g(!0),disabled:o!==null||!p,title:p?void 0:"`claude` binary not detected on PATH — install Claude CLI first.",children:o==="enabling"?"Enabling…":"Enable"})]});return s?t.jsxs("div",{className:`auth-provider-card auth-provider-card--cli${e?" auth-provider-card--authenticated":""}`,"data-testid":"claude-cli-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(Mn,{provider:"claude-cli",size:"sm"}),t.jsx("strong",{children:"Anthropic — via Claude CLI"}),t.jsx(RA,{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(Em,{status:i,authenticated:e}),c&&t.jsx(Mm,{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(Mn,{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(Em,{status:i,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(Mm,{action:c})]})}function RA({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 Em({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(it,{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 Mm({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 IA(e){return e.match(/\bcode\s+([A-Z0-9]+(?:-[A-Z0-9]+)+)\b/i)?.[1]??null}function _m({instructions:e,"data-testid":n}){const[s,i]=a.useState(!1),r=IA(e),o=a.useCallback(async()=>{const l=r??e;try{await navigator.clipboard.writeText(l),i(!0),setTimeout(()=>i(!1),2e3)}catch{}},[r,e]);return t.jsx("p",{className:"auth-login-instructions","data-testid":n,children:r?t.jsx(t.Fragment,{children:e.split(r).map((l,c,u)=>t.jsxs("span",{children:[l,c<u.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:o,title:s?"Copied!":"Copy code","aria-label":s?"Copied to clipboard":"Copy device code",type:"button",children:s?t.jsx(xn,{size:12}):t.jsx(wi,{size:12})})]})]},c))}):e})}const Mi="fusion_model_onboarding_state",ea=[],ta=[],Qr=!1,Xr=!1,na={},PA=void 0,oi=["ai-setup","github","project-setup","first-task"],$A={"ai-setup":"AI Setup",github:"GitHub","project-setup":"Project","first-task":"First Task",complete:"Complete"};function us(){if(typeof window>"u")return null;try{const e=localStorage.getItem(Mi);if(!e)return null;const n=JSON.parse(e);return n&&typeof n=="object"&&"currentStep"in n&&typeof n.currentStep=="string"?DA(n):null}catch{return null}}function DA(e){const n=e.postOnboardingDismissedAt??PA;return{...e,completedSteps:e.completedSteps??ea,skippedSteps:e.skippedSteps??ta,dismissed:e.dismissed??Qr,completed:e.completed??Xr,stepData:e.stepData??na,...n?{postOnboardingDismissedAt:n}:{}}}function Ar(e,n){if(!(typeof window>"u")){if(!n){const s={currentStep:e,updatedAt:new Date().toISOString(),completedSteps:ea,skippedSteps:ta,dismissed:Qr,completed:Xr,stepData:na};try{localStorage.setItem(Mi,JSON.stringify(s))}catch{}return}try{const s=us(),i=new Date().toISOString(),r=n.completed??Xr;let o=n.dismissed??Qr;r&&(o=!1);const l=n.completedSteps??s?.completedSteps??ea,c=n.skippedSteps??s?.skippedSteps??ta,u={...s?.stepData??na};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(Mi,JSON.stringify(d))}catch{}}}function LA(e){if(!(typeof window>"u"))try{const n=us(),s=new Date().toISOString();if(!n){const o={currentStep:e,updatedAt:s,completedSteps:ea,skippedSteps:[e],dismissed:Qr,completed:Xr,stepData:na};localStorage.setItem(Mi,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(Mi,JSON.stringify(r))}catch{}}function Am(){if(!(typeof window>"u"))try{const e=us(),n=new Date().toISOString(),s=e?{...e,completedAt:n,completed:!0,dismissed:!1,updatedAt:n}:{currentStep:"complete",updatedAt:n,completedAt:n,completedSteps:ea,skippedSteps:ta,dismissed:!1,completed:!0,stepData:na};localStorage.setItem(Mi,JSON.stringify(s))}catch{}}function sa(){const e=us();return e?e.completed===!0?!0:typeof e.completedAt=="string"&&e.completedAt.length>0:!1}function zA(){if(!(typeof window>"u"))try{const e=us(),n=new Date().toISOString(),s=e?{...e,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:ea,skippedSteps:ta,dismissed:!1,completed:!1,stepData:na,postOnboardingDismissedAt:n};localStorage.setItem(Mi,JSON.stringify(s))}catch{}}function cf(){const e=us();return e?typeof e.postOnboardingDismissedAt=="string"&&e.postOnboardingDismissedAt.length>0:!1}function FA(){const e=us();return!e||sa()?!1:e.currentStep!=="complete"}function OA(){const e=us();if(!e||sa()||e.currentStep==="complete")return null;const n=e.currentStep,s=$A[n]??HA(e.currentStep);return{currentStep:e.currentStep,label:s,completedSteps:e.completedSteps}}function UA(){const e=us();return e?e.skippedSteps:ta}function BA(e){const n=us();return!n||!n.stepData?null:n.stepData[e]??null}function HA(e){return e.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const df="fusion_onboarding_events",Tm="fusion_onboarding_session_id",qA=200,VA=50;function js(e,n={}){if(!(typeof window>"u"))try{const s=GA(),i=YA(n.step),r={type:e,timestamp:new Date().toISOString(),...i?{step:i}:{},metadata:n,sessionId:WA()},o=JA([...s,r]);KA(o)}catch{}}function WA(){if(typeof window>"u")return"server-session";try{const e=sessionStorage.getItem(Tm);if(e)return e;const n=Rm();return sessionStorage.setItem(Tm,n),n}catch{return Rm()}}function Rm(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function GA(){try{const e=localStorage.getItem(df);if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(QA):[]}catch{return[]}}function KA(e){try{localStorage.setItem(df,JSON.stringify(e))}catch{}}function JA(e){const n=[...e];for(;n.length>qA;)n.splice(0,VA);return n}function YA(e){if(e==="ai-setup"||e==="github"||e==="first-task"||e==="complete")return e}function QA(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 XA={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"}}},uf={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:"..."}},ZA={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},Im={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 tc(e){if(Im[e])return Im[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 wl=["anthropic","openai","google","gemini","ollama"],eT=["anthropic","claude-cli","openai-codex","gemini","minimax","kimi","zai"],tT={anthropic:"anthropic","claude-cli":"claude-cli","openai-codex":"openai-codex",google:"gemini",gemini:"gemini",minimax:"minimax",kimi:"kimi",moonshot:"kimi","kimi-coding":"kimi",zai:"zai"},nT={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function nc(e){return tT[e]??e}function Pm(e){const n=nc(e),s=eT.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function $m(e,n){if(e.authenticated!==n.authenticated)return e.authenticated?-1:1;const s=Pm(e.id),i=Pm(n.id);if(s!==i)return s-i;const r=nc(e.id),o=nc(n.id);if(r!==o)return r.localeCompare(o);const l=nT[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 sT(e,n){const s=n.trim();if(!s)return"API key is required";const i=uf[e]??ZA;return i.pattern.test(s)?null:`${tc(e)} keys should follow this format: ${i.hint} (e.g. ${i.example})`}const mf={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"},iT={description:"AI provider — connect to start using AI models",apiKeyInfo:mf};function sc(e){return XA[e]??iT}function aT(e){return sc(e.id).apiKeyInfo??mf}function zs({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(en,{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 rT({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 oT({provider:e,apiKeyInfo:n,inputValue:s,isSaving:i,error:r,success:o,isConnected:l,onInputChange:c,onSave:u,onClear:d}){const m=`onboarding-apikey-input-${e.id}`,h=i||!s.trim(),g=uf[e.id],p=`input onboarding-apikey-input${r?" onboarding-apikey-input--error":""}${o?" onboarding-apikey-input--success":""}`,f=t.jsxs(t.Fragment,{children:[g&&t.jsxs("small",{className:"onboarding-apikey-hint",children:["Format: ",g.hint]}),t.jsx("p",{className:"onboarding-apikey-instructions",children:n.setupInstructions}),n.dashboardUrl&&t.jsx("a",{href:n.dashboardUrl,target:"_blank",rel:"noreferrer",className:"onboarding-apikey-dashboard-link",children:"Get your API key →"}),t.jsx("p",{className:"onboarding-apikey-usage",children:n.usageDescription})]});return l?t.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${e.id}`,children:[t.jsxs("div",{className:"onboarding-apikey-connected-header",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:n.fieldLabel}),t.jsx("span",{className:"auth-status-badge connected",children:"✓ API key saved"})]}),t.jsx("button",{className:"btn btn-sm",onClick:()=>d(e.id),disabled:i,children:i?"Removing…":"Remove Key"}),t.jsx(zs,{summary:"Advanced setup details",children:f}),r&&t.jsx("small",{className:"field-error",children:r})]}):t.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${e.id}`,children:[t.jsx("label",{htmlFor:m,className:"onboarding-apikey-field-label",children:n.fieldLabel}),t.jsxs("div",{className:"onboarding-apikey-input-row",children:[t.jsx("input",{id:m,type:"password",className:p,placeholder:n.inputPlaceholder??"Enter API key",value:s,onChange: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(zs,{summary:"Advanced setup details",children:f})]})}const lT=150;function cT({onComplete:e,addToast:n,projectId:s,onOpenSetupWizard:i,onOpenNewTask:r,onOpenGitHubImport:o,firstCreatedTask:l,onViewTask:c}){const u=us(),d=u?.currentStep,m=d==="complete"?"ai-setup":oi.includes(d)?d:"ai-setup",h=u?.completedSteps??[],g=u?.skippedSteps??UA(),[p,f]=a.useState(!0),[b,v]=a.useState(m),[x,k]=a.useState(h),[M,y]=a.useState(g),[R,j]=a.useState(!1),[C,S]=a.useState(""),[P,T]=a.useState(!1),[_,L]=a.useState(null),[G,$]=a.useState(null),[I,w]=a.useState([]),[q,W]=a.useState(void 0),[B,A]=a.useState(!0),[z,X]=a.useState(null),[E,U]=a.useState({}),[pe,ie]=a.useState([]),[re,F]=a.useState(""),[ce,ae]=a.useState(!1),[Q,de]=a.useState({}),[Te,fe]=a.useState({}),[Se,te]=a.useState({}),we=a.useRef({}),Pe=a.useRef(null),We=a.useRef(null),[Ke,Ne]=a.useState({}),[_e,Oe]=a.useState(()=>us()?.stepData?.github?.skipped===!0),ye=a.useRef(0),De=a.useRef(l),se=a.useRef(!1),J=u?.currentStep,me=!!u&&u.currentStep!=="complete",[ee,he]=a.useState(()=>us()?.stepData?.["ai-setup"]?.skippedProviders??{}),le=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"project-setup",label:"Project"},{key:"first-task",label:"First Task"}],Ie=le.findIndex(K=>K.key===b),Ze=b==="complete"?le.length:Ie;a.useEffect(()=>{b!=="complete"&&Ar(b,{completedSteps:x,skippedSteps:M})},[b,x,M]),a.useEffect(()=>{se.current||(se.current=!0,js("onboarding:wizard-opened",{source:me?"resume":"initial",resumedFromStep:J}))},[me,J]),a.useEffect(()=>{const K=De.current!=null,ze=l!=null;!K&&ze&&j(!0),ze||j(!1),De.current=l},[l]);const at=a.useRef(m);a.useEffect(()=>{if(at.current==="ai-setup"&&b!=="ai-setup"&&!I.some(ze=>ze.id!=="github"&&ze.authenticated)){const ze={};for(const tt of I)tt.id!=="github"&&!tt.authenticated&&!ee[tt.id]&&(ze[tt.id]=!0);if(Object.keys(ze).length>0){const tt={...ee,...ze};he(tt),Ar(b,{stepData:{"ai-setup":{skippedProviders:tt}}})}}at.current=b},[b,I,ee]);const oe=a.useCallback(async()=>{try{const{providers:K,ghCli:ze}=await Ba();w(K),W(ze),U(tt=>{const et={};for(const[mt,jt]of Object.entries(tt)){const _t=K.find(gn=>gn.id===mt);_t&&!_t.authenticated&&(et[mt]=jt)}return Object.keys(et).length===Object.keys(tt).length?tt:et}),he(tt=>{const et={...tt};for(const mt of K)mt.authenticated&&et[mt.id]&&delete et[mt.id];return Object.keys(et).length===Object.keys(tt).length?tt:et})}catch{}},[]),Z=a.useRef(!1);a.useEffect(()=>{Z.current&&oe(),Z.current=b!=="ai-setup"},[b,oe]);const ue=I.find(K=>K.id==="github"),Ce=!!ue,$e=ue?.authenticated??!1,ve=q?.authenticated??!1,Ge=$e||ve,je=!$e&&ve,Ue=a.useCallback(K=>{if(K.authenticated)return"connected";const ze=Ke?.[K.id];return ze==="timeout"||ze==="failed"?"retry":ee[K.id]?"skipped":"not-connected"},[Ke,ee]);function He({status:K}){const ze={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:tt,className:et}=ze[K];return t.jsx("span",{"data-testid":"provider-status-badge",className:et,"data-status":K,children:tt})}const ge=a.useCallback(()=>{if(Ge)return"connected";const K=Ke.github;return K==="pending"?"pending":K==="failed"||K==="timeout"?"failed":_e?"skipped":"not-connected"},[Ge,Ke,_e]);function Fe({status:K}){const ze={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:tt,className:et}=ze[K];return t.jsx("span",{"data-testid":"github-status-badge",className:et,"data-status":K,children:tt})}const be=a.useCallback(async()=>{try{const K=await is();ie(K.models)}catch{}},[]),Je=a.useCallback(async()=>{try{const K=await ra();if(K.defaultProvider&&K.defaultModelId){const ze=`${K.defaultProvider}/${K.defaultModelId}`;F(ze)}}catch{}},[]);a.useEffect(()=>{Promise.all([oe(),be(),Je()]).finally(()=>A(!1))},[oe,be,Je]),a.useEffect(()=>{const K=BA("ai-setup");if(K?.loginOutcomes){const ze=K.loginOutcomes,tt={};for(const[et,mt]of Object.entries(ze))mt!=="pending"&&(tt[et]=mt);Object.keys(tt).length>0&&Ne(tt)}},[]);const st=a.useCallback((K,ze)=>{Ar(b,{completedSteps:x,stepData:{"ai-setup":{loginOutcomes:{[K]:ze}}}})},[b,x]);a.useEffect(()=>{const K=Object.entries(Ke).filter(([ze,tt])=>tt!=="pending");for(const[ze,tt]of K)st(ze,tt)},[Ke,st]),a.useEffect(()=>()=>{We.current&&clearInterval(We.current),Object.values(we.current).forEach(clearTimeout),we.current={}},[]);const dt=a.useCallback(K=>{Oe(K),Ar(b,{completedSteps:x,stepData:{github:{skipped:K}}})},[b,x]),Tt=a.useCallback(K=>K==="complete"?-1:oi.indexOf(K),[]),$t=a.useCallback(()=>{k(ze=>[...new Set([...ze,b])]),y(ze=>ze.filter(tt=>tt!==b)),js("onboarding:step-completed",{step:b}),b==="github"&&!$e&&dt(!1);const K=Tt(b);K>=0&&K<oi.length-1&&v(oi[K+1])},[b,$e,dt,Tt]),Dt=a.useCallback(()=>{y(ze=>[...new Set([...ze,b])]),LA(b),js("onboarding:step-skipped",{step:b}),b==="github"&&!$e&&dt(!0);const K=Tt(b);K>=0&&K<oi.length-1&&v(oi[K+1])},[b,$e,dt,Tt]),Bt=a.useCallback(()=>{const K=b;k(tt=>tt.filter(et=>et!==K)),y(tt=>tt.filter(et=>et!==K)),K==="github"&&!$e&&dt(!1);const ze=Tt(b);ze>0&&v(oi[ze-1])},[b,$e,dt,Tt]),qt=a.useCallback(()=>{Dt()},[Dt]),Lt=a.useCallback(async K=>{Ne(ze=>{const tt=ze[K];if(tt&&tt!=="pending"){const{[K]:et,...mt}=ze;return mt}return ze}),U(ze=>{if(!(K in ze))return ze;const tt={...ze};return delete tt[K],tt}),Ne(ze=>({...ze,[K]:"pending"})),X(K),ye.current=0;try{const{url:ze,instructions:tt}=await Wx(K);tt?.trim()&&U(et=>({...et,[K]:tt})),window.open(Hs(ze),"_blank"),We.current=setInterval(async()=>{if(ye.current++,ye.current>=lT){We.current&&(clearInterval(We.current),We.current=null),X(null),Ne(et=>({...et,[K]:"timeout"})),U(et=>{if(!(K in et))return et;const mt={...et};return delete mt[K],mt}),n("Login timed out. Please try again.","warning");return}try{const{providers:et,ghCli:mt}=await Ba();w(et),W(mt),et.find(_t=>_t.id===K)?.authenticated&&(We.current&&(clearInterval(We.current),We.current=null),X(null),Ne(_t=>({..._t,[K]:"success"})),U(_t=>{if(!(K in _t))return _t;const gn={..._t};return delete gn[K],gn}),K==="github"&&dt(!1),n("Login successful","success"))}catch{}},2e3)}catch(ze){ze instanceof Error&&ze.message.includes("already in progress")||ze&&typeof ze=="object"&&"status"in ze&&ze.status===409?(n("Login already in progress. Please wait or cancel the current attempt.","warning"),Ne(et=>({...et,[K]:"failed"}))):(n(ze instanceof Error?ze.message:"Login failed","error"),Ne(et=>({...et,[K]:"failed"}))),X(null),U(et=>{if(!(K in et))return et;const mt={...et};return delete mt[K],mt})}},[n,dt]),Ct=a.useCallback(K=>{We.current&&(clearInterval(We.current),We.current=null),X(null),ye.current=0,Ne(ze=>({...ze,[K]:"cancelled"})),U(ze=>{if(!(K in ze))return ze;const tt={...ze};return delete tt[K],tt})},[]),xt=a.useCallback((K,ze)=>{de(et=>({...et,[K]:ze}));const tt=we.current[K];tt&&(clearTimeout(tt),delete we.current[K]),fe(et=>{if(!et[K])return et;const mt={...et};return delete mt[K],mt}),te(et=>{if(!et[K])return et;const mt={...et};return delete mt[K],mt})},[]),Et=a.useCallback(()=>{const K=Pe.current;if(!K)return;const ze=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof K.scrollTo=="function"){K.scrollTo({top:0,behavior:ze?"auto":"smooth"});return}}catch{}K.scrollTop=0},[]),Le=a.useCallback(async(K,ze)=>{const tt=(ze??Q[K]??"").trim(),et=sT(K,tt);if(et){fe(jt=>({...jt,[K]:et}));return}const mt=we.current[K];mt&&(clearTimeout(mt),delete we.current[K]),X(K),fe(jt=>{const _t={...jt};return delete _t[K],_t}),te(jt=>{if(!jt[K])return jt;const _t={...jt};return delete _t[K],_t});try{await Kx(K,tt),await oe(),Et(),de(jt=>{const _t={...jt};return delete _t[K],_t}),fe(jt=>{if(!jt[K])return jt;const _t={...jt};return delete _t[K],_t}),te(jt=>({...jt,[K]:"✓ Key saved"})),we.current[K]=setTimeout(()=>{te(jt=>{if(!jt[K])return jt;const _t={...jt};return delete _t[K],_t}),delete we.current[K]},3e3),n("API key saved","success")}catch(jt){const _t=jt instanceof TypeError&&jt.message.includes("Failed to fetch")?"Could not reach the server. Check your connection and try again.":jt instanceof Error?jt.message:"Failed to save API key";fe(gn=>({...gn,[K]:_t})),te(gn=>{if(!gn[K])return gn;const fs={...gn};return delete fs[K],fs}),n(_t,"error")}finally{X(null)}},[Q,n,oe,Et]),gt=a.useCallback(async K=>{X(K);try{await Jx(K),await oe(),n("API key removed","success")}catch(ze){n(ze instanceof Error?ze.message:"Failed to clear API key","error")}finally{X(null)}},[n,oe]),ut=a.useCallback(async K=>{X(K);try{await Gx(K),await oe(),n("Logged out","success")}catch(ze){n(ze instanceof Error?ze.message:"Logout failed","error")}finally{X(null)}},[n,oe]),Me=a.useCallback(K=>{F(K)},[]),Qe=a.useCallback(async()=>{try{const K={modelOnboardingComplete:!0};if(re){const ze=re.indexOf("/"),tt=ze!==-1?re.slice(0,ze):void 0,et=ze!==-1?re.slice(ze+1):re,mt=pe.find(jt=>jt.id===et);mt?(K.defaultProvider=mt.provider,K.defaultModelId=mt.id):tt&&et&&(K.defaultProvider=tt,K.defaultModelId=et)}await nn(K),Am()}catch{}},[re,pe,nn,Am]),rt=a.useCallback(async()=>{const K=[...new Set([...x,"first-task"])];ae(!0);try{await Qe(),js("onboarding:completed",{completedSteps:K,skippedSteps:M}),k(K),y(ze=>ze.filter(tt=>tt!=="first-task")),v("complete")}finally{ae(!1)}},[Qe,x,M]),N=a.useCallback(async()=>{if(!s)return;const K=C.trim();if(!K){L("Please enter a task description.");return}L(null),T(!0);let ze=!1;try{const tt=await mh({description:K},s);$(tt),j(!0),js("onboarding:first-task-created",{taskId:tt?.id}),n("Task created","success"),ze=!0}catch(tt){const et=tt instanceof Error?tt.message:"Something went wrong creating your task. Please try again.";L(et),n(et,"error")}finally{T(!1)}ze&&Qe()},[s,C,n,Qe]),H=a.useCallback(async()=>{ae(!0);try{await Qe()}finally{ae(!1)}js("onboarding:open-new-task",{}),r?.()},[Qe,r]),Ae=a.useCallback(async()=>{if(Ge){ae(!0);try{await Qe()}finally{ae(!1)}f(!1),e(),js("onboarding:open-github-import",{}),o?.()}},[Qe,Ge,e,o]),ot=a.useCallback(async()=>{js("onboarding:dismissed",{currentStep:b,completedSteps:x,skippedSteps:M}),ae(!0);try{await nn({modelOnboardingComplete:!0})}catch{}f(!1),e()},[b,x,M,e]),kt=a.useCallback(()=>{js("onboarding:finished",{}),f(!1),e()},[e]),Ot=a.useCallback(()=>{const K=l??G;K&&(Qe(),c?.(K),e())},[l,G,Qe,c,e]),sn=a.useCallback(()=>{Qe(),e()},[Qe,e]);if(!p)return null;const Rt=ge(),zn=I.filter(K=>K.id!=="github"),Wn=[...zn].sort($m),ms=Wn.some(K=>!K.type||K.type==="oauth"),pn=Wn.some(K=>K.type==="api_key"),Fn=zn.filter(K=>K.authenticated),Sn=Fn.length>0,fn=!!s,Gn=b==="github"&&!Sn,dn=(()=>{if(!re)return"";const K=re.indexOf("/"),ze=K===-1?void 0:re.slice(0,K),tt=K===-1?re:re.slice(K+1),et=pe.find(mt=>mt.id===tt&&(!ze||mt.provider===ze));return et?.name?et.name:ze?`${tc(ze)} ${tt}`:re})(),Mt=[];if(fn?Mt.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):Mt.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),Sn){const K=tc(Fn[0]?.id??"");Mt.push({label:"AI Provider",status:"connected",detail:`${K} connected — AI agents can work on tasks`})}else zn.length>0&&zn.some(K=>ee[K.id])?Mt.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):Mt.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});Ge?Mt.push({label:"GitHub",status:"connected",detail:je?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!Ce||_e?Mt.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):Mt.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),dn&&Mt.push({label:"Default Model",status:"connected",detail:dn});const yn=l??G,Kn=yn?.description?.split(`
|
|
616
|
-
`)[0]?.trim()||yn?.title||"",kn=new Set(wl),_n=Wn.filter(K=>kn.has(K.id)).sort((K,ze)=>{const tt=wl.indexOf(K.id),et=wl.indexOf(ze.id);return tt!==et?tt-et:$m(K,ze)}),hs=Wn.filter(K=>K.authenticated&&!kn.has(K.id)),ps=Wn.filter(K=>!K.authenticated&&!kn.has(K.id)),On=K=>{if(K.id==="claude-cli"&&K.type==="cli")return t.jsx(TA,{authenticated:K.authenticated,onToggled:()=>{oe()}},K.id);if(K.type==="api_key"){const ze=sc(K.id),tt=aT(K);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${K.id}`,className:`onboarding-provider-card${K.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${K.id}`,"aria-hidden":"true",children:t.jsx(Mn,{provider:K.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(ah,{size:14,className:"onboarding-provider-key-icon"}),K.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:ze.description}),t.jsx(He,{status:Ue(K)}),K.authenticated&&K.keyHint&&t.jsxs("span",{className:"auth-key-hint",children:["Key: ",K.keyHint]})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx(oT,{provider:K,apiKeyInfo:tt,inputValue:Q[K.id]??"",isSaving:z===K.id,error:Te[K.id],success:Se[K.id],isConnected:K.authenticated,onInputChange:xt,onSave:Le,onClear:gt})})]},K.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${K.id}`,className:`onboarding-provider-card${K.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${K.id}`,"aria-hidden":"true",children:t.jsx(Mn,{provider:K.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:K.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:sc(K.id).description}),t.jsx(He,{status:Ue(K)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:z===K.id?t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:K.authenticated?"Logging out…":"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Ct(K.id),children:"Cancel"})]}):K.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>ut(K.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>Lt(K.id),children:"Login"})}),z===K.id&&E[K.id]&&t.jsx(_m,{instructions:E[K.id],"data-testid":`onboarding-login-instructions-${K.id}`}),Ke[K.id]==="timeout"&&z!==K.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),Ke[K.id]==="failed"&&z!==K.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},K.id)};return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"onboarding-title",children:t.jsxs("div",{className:"modal model-onboarding-modal",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(vn,{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(Jc,{size:24})," Set Up Your Project"]}),b==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(Jc,{size:24})," Create Your First Task"]}),b==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx(tn,{size:24})," All Set!"]})]}),b!=="complete"&&t.jsx("button",{className:"modal-close",onClick:ot,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(Pt,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:le.map((K,ze)=>{const tt=Ze>ze,et=x.includes(K.key)&&tt,mt=M.includes(K.key)&&!x.includes(K.key)&&tt,jt=et||mt;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[ze>0&&t.jsx("div",{className:`model-onboarding-step-connector ${ze<=Ze?"done":""}`}),jt?t.jsxs("button",{className:`model-onboarding-step-indicator ${b===K.key?"active":""} ${et?"done":""} ${mt?"skipped":""}`,onClick:()=>v(K.key),"aria-label":`Go back to ${K.label}`,title:`Review ${K.label}`,children:[t.jsx("span",{className:"step-number",children:et?t.jsx(tn,{size:14}):mt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):ze+1}),t.jsx("span",{className:"step-label",children:K.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${b===K.key?"active":""} ${et?"done":""} ${mt?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:et?t.jsx(tn,{size:14}):mt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):ze+1}),t.jsx("span",{className:"step-label",children:K.label})]})]},K.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:Pe,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."}),!B&&I.length>0&&(()=>{const K=I.filter(jt=>jt.id!=="github"&&jt.authenticated).length,ze=I.filter(jt=>jt.id!=="github").length,tt=Object.keys(ee).filter(jt=>!I.find(_t=>_t.id===jt)?.authenticated).length;if(ze===0)return null;let et="onboarding-provider-summary",mt="";return K>0?(et+=" onboarding-provider-summary--connected",mt=`✓ ${K} of ${ze} provider${ze!==1?"s":""} connected`):tt>0?(et+=" onboarding-provider-summary--skipped",mt=`${tt} provider${tt!==1?"s":""} skipped`):(et+=" onboarding-provider-summary--none",mt="No providers connected yet"),t.jsx("div",{className:et,"data-testid":"provider-summary",children:mt})})(),t.jsx(zs,{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."})}),I.length>0&&!I.some(K=>K.authenticated)&&t.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),B?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(it,{size:24,className:"animate-spin"}),t.jsx("span",{children:"Loading providers…"})]}):I.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"}),_n.length>0?t.jsx("div",{className:"model-onboarding-providers",children:_n.map(K=>On(K))}):t.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),hs.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:hs.map(K=>On(K))})]}),t.jsx(zs,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:t.jsx("div",{"data-testid":"onboarding-advanced-provider-settings",children:ps.length>0?t.jsx("div",{className:"model-onboarding-providers",children:ps.map(K=>On(K))}):t.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."})})}),ms&&t.jsx(zs,{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."})}),pn&&t.jsx(zs,{summary:"What is an API key?",children:t.jsx("p",{className:"onboarding-helper-text",children:"An API key is a secret token that authenticates Fusion with the provider. You can find your key in the provider's dashboard under API settings. Keys are stored securely on your machine."})})]}),t.jsxs("div",{className:"onboarding-model-section",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Default Model (Optional)"}),t.jsx("p",{className:"model-onboarding-description",children:"Pick a default model for AI tasks, or leave this blank to choose later. Models vary in speed, capability, and cost."}),t.jsx(zs,{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."})}),pe.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(wn,{models:pe,value:re,onChange:Me,placeholder:"Select a default model…",label:"Default model"})}),re&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",pe.find(K=>K.id===re)?.name??re]})})]})]}),b==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[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."}),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"})]})}),Gn&&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(zs,{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."})}),Ce?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(Fe,{status:Rt})})]}),$e&&(z==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>ut("github"),children:"Disconnect"}))]}),(Rt==="not-connected"||Rt==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[z==="github"?t.jsxs("div",{className:"onboarding-github-connect-actions",children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Ct("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>Lt("github"),children:[t.jsx(es,{size:16}),"Connect"]}),z==="github"&&E.github&&t.jsx(_m,{instructions:E.github,"data-testid":"onboarding-login-instructions-github"})]}),Rt==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:je?"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."}),Rt==="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:()=>Lt("github"),children:"Retry"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:qt,children:"Skip for now"})]})]}),Rt==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),Rt==="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:()=>Lt("github"),children:"Connect anyway"})})]}),Rt==="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(es,{size:48,className:"optional-icon"}),je?t.jsx("p",{children:"GitHub CLI is already authenticated, so imports and PR tracking work now. OAuth integration in Settings → Authentication 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.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>v("project-setup"),children:"Continue without 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."}),fn?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(zs,{summary:"What does project setup do?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Project setup registers a workspace so Fusion knows where to read files, run commands, and track task changes."})})]}),b==="first-task"&&t.jsxs("div",{className:"model-onboarding-first-task",children:[t.jsx("p",{className:"model-onboarding-description",children:"Create your first task to start the board and launch AI execution."}),R&&yn?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx(tn,{size:56,className:"success-icon"}),t.jsx("h3",{className:"onboarding-task-created__title",children:"Your first task is ready!"}),t.jsx("div",{className:"onboarding-task-created__task-id",children:yn.id}),Kn&&t.jsx("p",{className:"onboarding-task-created__description",children:Kn}),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:Ot,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:sn,children:"Go to Dashboard"})]})]}):t.jsxs(t.Fragment,{children:[fn?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:C,onChange:K=>{S(K.target.value),L(null)},placeholder:"Example: Build a login page with email and password",rows:4}),t.jsx("div",{className:"onboarding-first-task-form__actions",children:t.jsx("button",{type:"button",className:"btn btn-primary",onClick:N,disabled:P,"data-testid":"onboarding-first-task-submit",children:P?t.jsxs(t.Fragment,{children:[t.jsx(it,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),_&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:_}),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(rT,{items:Mt}),fn&&t.jsxs(t.Fragment,{children:[t.jsx(zs,{summary:"What happens when I create a task?",children:t.jsx("p",{className:"onboarding-helper-text",children:"A task describes something you want done. Fusion's AI agents will read your description and work on implementing it. You can track progress on the board and review the results."})}),t.jsxs("div",{className:"onboarding-cta-options",children:[t.jsxs("button",{className:"onboarding-cta-card primary",onClick:H,disabled:ce,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(Vt,{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${Ge?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:Ae,disabled:ce||!Ge,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"}),!Ge&&t.jsx("small",{className:"onboarding-cta-note",children:"Requires GitHub connection"})]})]})]}),t.jsxs("p",{className:"onboarding-skip-note",children:["You can create tasks anytime from the board, or use"," ",t.jsx("code",{children:"fn task create"})," in the terminal."]})]})]})]}),b==="complete"&&t.jsxs("div",{className:"model-onboarding-complete",children:[t.jsx(tn,{size:48,className:"success-icon"}),t.jsx("p",{children:"Setup complete! Head to the board to create your first task, or explore the dashboard to see what's available."})]})]}),t.jsxs("div",{className:"model-onboarding-footer",children:[b==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:ot,disabled:ce,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Dt,children:"Skip setup →"}),t.jsx("button",{className:"btn btn-primary",onClick:$t,children:"Next →"})]}),b==="github"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Bt,children:"← Back"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Dt,children:"Skip GitHub →"}),t.jsx("button",{className:"btn btn-primary",onClick:$t,children:"Next →"})]}),b==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Bt,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:$t,disabled:!fn,children:"Next →"})]}),b==="first-task"&&!R&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Bt,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:rt,disabled:ce,children:ce?t.jsxs(t.Fragment,{children:[t.jsx(it,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),b==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:kt,children:[t.jsx(tn,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function hf({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 dT=a.lazy(()=>Zt(()=>import("./SetupWizardModal-D1bmCQrf.js"),__vite__mapDeps([6,1,7,8,9,0,2,10])).then(e=>({default:e.SetupWizardModal}))),uT=a.lazy(()=>Zt(()=>import("./SettingsModal-Bs_lNs5B.js"),__vite__mapDeps([11,1,12,13,14,0,2,15])).then(e=>({default:e.SettingsModal})));function mT(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{Zt(()=>import("./SettingsModal-Bs_lNs5B.js"),__vite__mapDeps([11,1,12,13,14,0,2,15]))},{timeout:1500})}function hT({projectId:e,tasks:n,projects:s,currentProject:i,addToast:r,toasts:o,removeToast:l,modalManager:c,projectActions:u,taskHandlers:d,taskOperations:m,deepLink:h,settings:g,onSettingsClose:p,onReopenOnboarding:f}){const[b,v]=a.useState(null),x=p??c.closeSettings,k=a.useCallback(()=>{c.openNewTask()},[c]),M=a.useCallback(()=>{c.openGitHubImport()},[c]),y=a.useCallback(j=>{v(null),c.closeModelOnboarding(),c.openDetailTask(j)},[c]),R=a.useCallback(async j=>{const C=await d.handleModalCreate(j);return c.modelOnboardingOpen&&v(C),C},[d.handleModalCreate,c.modelOnboardingOpen]);return a.useEffect(()=>{!c.modelOnboardingOpen&&b&&v(null)},[c.modelOnboardingOpen,b]),a.useEffect(()=>{mT()},[]),t.jsxs(t.Fragment,{children:[c.detailTask&&t.jsx(fi,{children:t.jsx(CM,{task:c.detailTask,projectId:e,tasks:n,onClose:h.handleDetailClose,onOpenDetail:c.openDetailTask,onMoveTask:m.moveTask,onDeleteTask:m.deleteTask,onMergeTask:m.mergeTask,onRetryTask:m.retryTask,onDuplicateTask:m.duplicateTask,onTaskUpdated:c.updateDetailTask,addToast:r,prAuthAvailable:g.prAuthAvailable,initialTab:c.detailTaskInitialTab})}),c.settingsOpen&&t.jsx(fi,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(uT,{onClose:x,addToast:r,initialSection:c.settingsInitialSection,projectId:e,themeMode:g.themeMode,colorTheme:g.colorTheme,onThemeModeChange:g.setThemeMode,onColorThemeChange:g.setColorTheme,onReopenOnboarding:f})})}),t.jsx(MM,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:d.handleGitHubImport,tasks:n,projectId:e}),t.jsx(fi,{children:t.jsx(RM,{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(fi,{children:t.jsx(zM,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:d.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx(ZM,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx(t_,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx(j_,{initialWorkspace:c.fileBrowserWorkspace,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),t.jsx(T_,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e}),c.schedulesOpen&&t.jsx(Q_,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx(fi,{children:t.jsx(tA,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:R,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan,onSubtaskBreakdown:c.openSubtaskBreakdown})}),t.jsx(rA,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:i,onOpenTaskDetail:j=>{const C=n.find(S=>S.id===j);C&&c.openDetailTask(C)}}),t.jsx(fi,{children:t.jsx(lA,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx(fi,{children:t.jsx(yA,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(AA,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(a.Suspense,{fallback:null,children:t.jsx(dT,{onProjectRegistered:u.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(cT,{onComplete:u.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:u.handleAddProject,onOpenNewTask:k,onOpenGitHubImport:M,firstCreatedTask:b,onViewTask:y}),t.jsx(hf,{toasts:o,onRemove:l})]})}function pT({errorMessage:e,isRetrying:n,onRetry:s}){return t.jsxs("div",{className:"project-overview-empty",role:"alert","aria-live":"polite",children:[t.jsx("h2",{children:"Can't reach the Fusion backend"}),t.jsx("p",{className:"settings-muted",children:"Fusion couldn't load your projects right now. Please make sure the backend is running and try again."}),t.jsxs("p",{className:"settings-muted",children:["Error: ",e]}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:s,disabled:n,children:n?"Retrying…":"Retry Connection"})]})}const ic=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function fT(e,n){if(n==="ready")return"done";const s=ic.findIndex(r=>r.id===n),i=ic.findIndex(r=>r.id===e);return i<s?"done":i===s?"active":"pending"}function gT({stage:e}){return t.jsx("div",{className:"dashboard-loader",role:"status","aria-live":"polite","aria-label":"Loading Fusion dashboard","data-stage":e,children:t.jsxs("div",{className:"dashboard-loader__content",children:[t.jsx("h1",{className:"dashboard-loader__logo",children:"Fusion"}),t.jsx("p",{className:"dashboard-loader__message",children:"Initializing dashboard..."}),t.jsx("ol",{className:"dashboard-loader__steps","aria-label":"Dashboard loading progress",children:ic.map(n=>{const s=fT(n.id,e);return t.jsxs("li",{className:`dashboard-loader__step dashboard-loader__step--${s}`,"data-testid":`dashboard-loader-step-${n.id}`,children:[t.jsx("span",{className:"dashboard-loader__step-icon","aria-hidden":"true",children:s==="done"?"✓":s==="active"?t.jsx(it,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:n.label})]},n.id)})})]})})}const bT=5e3;function xT(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function vT(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++,Hr(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 yT(e,n,s,i){const[r,o]=a.useState({globalPause:!1,enginePaused:!1,maxConcurrent:2}),[l,c]=a.useState(!0),[u,d]=a.useState(null),m=a.useRef(null),h=a.useRef(null),g=a.useCallback(async()=>{h.current&&h.current.abort(),h.current=new AbortController;try{c(!0),d(null);const v=await Ey(n);o(v)}catch(v){if(v instanceof Error&&v.name==="AbortError")return;d(v instanceof Error?v.message:"Failed to fetch executor stats")}finally{c(!1)}},[n]);a.useEffect(()=>(g(),()=>{h.current&&h.current.abort()}),[g]),a.useEffect(()=>(m.current&&clearInterval(m.current),m.current=setInterval(()=>{g()},bT),()=>{m.current&&(clearInterval(m.current),m.current=null)}),[g]);const p=vT(e,s,i),f=xT(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:f,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:u,refresh:g}}const kT={planning:Us,subtask:Si,mission_interview:ns,milestone_interview:ns,slice_interview:ns},jT={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function wT({sessions:e,generating:n,needsInput:s,onOpenSession:i,onDismissSession:r}){const[o,l]=a.useState(!1),[c,u]=a.useState(new Set),d=a.useRef(null),m=a.useRef(new Map),h=a.useRef(null),{activeTabMap:g}=la(),p=a.useMemo(()=>_i(),[]);if(a.useEffect(()=>{if(!o)return;const v=x=>{d.current&&!d.current.contains(x.target)&&l(!1)};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[o]),a.useEffect(()=>{const v=new Set,x=new Map;for(const k of e){const M=g.get(k.id),y=[k.status,k.updatedAt,M?.tabId??k.lockedByTab??"",M?.stale?"stale":"fresh"].join("|"),R=m.current.get(k.id);R&&R!==y&&v.add(k.id),x.set(k.id,y)}if(m.current=x,v.size!==0)return u(v),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{u(new Set),h.current=null},500),()=>{h.current&&(clearTimeout(h.current),h.current=null)}},[g,e]),e.length===0)return null;const f=e.length,b=s>0;return t.jsxs("div",{ref:d,className:"background-tasks-indicator",children:[t.jsxs("button",{className:`background-tasks-indicator__pill${b?" background-tasks-indicator__pill--attention":""}`,onClick:()=>l(v=>!v),title:`${f} background AI task${f!==1?"s":""}${s>0?` (${s} need${s!==1?"":"s"} input)`:""}`,children:[n>0&&t.jsx(it,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&t.jsx(Gc,{size:12}),t.jsxs("span",{children:["AI ",f]})]}),o&&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(v=>{const x=kT[v.type],k=v.status==="generating",M=v.status==="awaiting_input",y=v.status==="error",R=g.get(v.id),j=R?.tabId??v.lockedByTab??null,C=!!(j&&j!==p&&!R?.stale),S=c.has(v.id);return t.jsxs("div",{className:`background-tasks-indicator__item${S?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:S?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:S?"translateY(-1px)":void 0},onClick:()=>{C&&!window.confirm("This session is active in another tab. Open anyway?")||(i(v),l(!1))},children:[y?t.jsx(ss,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--color-error)"}}):t.jsx(x,{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:v.title}),t.jsxs("div",{className:"background-tasks-indicator__session-meta",children:[y?"Failed":jT[v.type],k&&" — generating...",M&&!C&&" — needs input",M&&C&&" — active in another tab"]})]}),k&&t.jsx(it,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),M&&!C&&t.jsx(Gc,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),M&&C&&t.jsx(so,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),t.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:P=>{P.stopPropagation(),r(v.id)},title:"Dismiss",children:t.jsx(Pt,{size:12})})]},v.id)})})]})]})}function NT(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 ST(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:rn};case"paused":return{label:"Paused",color:"var(--triage)",icon:Fs};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:vn}}}function CT({tasks:e,projectId:n,taskStuckTimeoutMs:s,backgroundSessions:i,backgroundGenerating:r,backgroundNeedsInput:o,onOpenBackgroundSession:l,onDismissBackgroundSession:c,lastFetchTimeMs:u,currentProjectPath:d,onOpenProjectDirectory:m}){const{stats:h,loading:g,error:p}=yT(e,n,s,u),[f,b]=a.useState(!1),v=a.useMemo(()=>ST(h.executorState),[h.executorState]),x=a.useMemo(()=>NT(h.lastActivityAt),[h.lastActivityAt]),k=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(lc,{size:14}),p]})}):g&&h.runningTaskCount===0?t.jsx("div",{className:"executor-status-bar executor-status-bar--loading",role:"status","aria-label":"Executor status",children:t.jsx("span",{className:"executor-status-bar__loading-text",children:"Loading..."})}):t.jsxs("div",{className:`executor-status-bar ${h.executorState==="running"?"executor-status-bar--running":""}`,role:"status","aria-label":"Executor status",children:[i&&i.length>0&&l&&c&&t.jsxs(t.Fragment,{children:[t.jsx(wT,{sessions:i,generating:r??0,needsInput:o??0,onOpenSession:l,onDismissSession:c}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--queued","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Queued"}),t.jsx("span",{className:"executor-status-bar__count",children:h.queuedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--running ${h.runningTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Running"}),t.jsx("span",{className:"executor-status-bar__count",children:h.runningTaskCount}),t.jsx("span",{className:"executor-status-bar__separator","aria-hidden":"true",children:"/"}),t.jsx("span",{className:"executor-status-bar__max",children:h.maxConcurrent})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),h.stuckTaskCount>0&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--stuck",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--stuck executor-status-bar__indicator--active","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Stuck"}),t.jsx("span",{className:"executor-status-bar__count executor-status-bar__count--error",children:h.stuckTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--blocked ${h.blockedTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Blocked"}),t.jsx("span",{className:`executor-status-bar__count ${h.blockedTaskCount>0?"executor-status-bar__count--warning":""}`,children:h.blockedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--review","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"In Review"}),t.jsx("span",{className:"executor-status-bar__count",children:h.inReviewCount})]}),d&&m&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--project-directory",children:[t.jsx("button",{className:`executor-status-bar__folder-toggle${f?" executor-status-bar__folder-toggle--active":""}`,onClick:()=>b(M=>!M),"aria-label":f?"Hide project directory":"Show project directory","aria-expanded":f,"data-testid":"executor-project-path-toggle",title:f?"Hide project directory":"Show project directory",children:t.jsx(jn,{size:12,"aria-hidden":"true"})}),f&&t.jsx("button",{className:"executor-status-bar__project-path",onClick:m,title:d,"data-testid":"executor-project-path-link",children:d})]})]}),t.jsx("div",{className:"executor-status-bar__spacer"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--time",children:[t.jsx(ji,{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(k,{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 ET={planning:Us,subtask:Si,mission_interview:ns,milestone_interview:ns,slice_interview:ns},MT={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},xi=new Set;function _T({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:i}){const[r,o]=a.useState(0),l=()=>o(f=>f+1);a.useEffect(()=>{if(xi.size===0)return;const f=new Map(e.map(v=>[v.id,v]));let b=!1;for(const v of xi){const x=f.get(v);x&&x.status!=="awaiting_input"&&x.status!=="error"&&(xi.delete(v),b=!0)}b&&l()},[e]);const c=a.useMemo(()=>e.filter(f=>(f.status==="awaiting_input"||f.status==="error")&&!xi.has(f.id)),[e,r]);if(c.length===0)return null;const u=c.filter(f=>f.status==="awaiting_input").length,d=c.filter(f=>f.status==="error").length;let m="";u>0&&d>0?m=`${u} AI session${u===1?"":"s"} need${u===1?"s":""} your input, ${d} failed`:u>0?m=`${u} AI session${u===1?"":"s"} need${u===1?"s":""} your input`:d>0&&(m=`${d} AI session${d===1?"":"s"} failed`);const h=f=>{xi.add(f),l()},g=f=>{xi.delete(f.id),l(),n(f)},p=()=>{for(const f of c)xi.add(f.id);l(),i()};return t.jsxs("section",{className:"session-notification-banner",role:"region","aria-live":"polite","aria-label":"AI sessions needing input or failed",children:[t.jsxs("div",{className:"session-notification-banner__header",children:[t.jsxs("div",{className:"session-notification-banner__headline",children:[t.jsx(ss,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:m})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[t.jsx(Pt,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Dismiss all"})]})]}),t.jsx("div",{className:"session-notification-banner__list",children:c.map(f=>{const b=ET[f.type],v=f.status==="error";return t.jsxs("article",{className:`session-notification-banner__item${v?" session-notification-banner__item--error":""}`,"data-session-type":f.type,"data-session-status":f.status,children:[t.jsxs("div",{className:"session-notification-banner__item-main",children:[v?t.jsx(ss,{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:f.title,children:f.title}),t.jsx("p",{className:"session-notification-banner__meta",children:v?"Failed":MT[f.type]})]})]}),t.jsxs("div",{className:"session-notification-banner__actions",children:[t.jsx("button",{className:"session-notification-banner__resume",onClick:()=>g(f),children:v?"Retry":"Resume"}),t.jsx("button",{className:"session-notification-banner__dismiss",onClick:()=>{h(f.id),s(f.id)},"aria-label":`Dismiss ${f.title}`,children:t.jsx(Pt,{size:14,"aria-hidden":"true"})})]})]},f.id)})})]})}function AT({onResume:e}){const n=OA();if(!n)return null;const s=n.completedSteps.length,i=oi.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(Dn,{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:()=>{js("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),e()},children:[t.jsx(rn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function TT({onOpenSettings:e,onOpenModelOnboarding:n}){const s=sa(),i=cf(),[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[M,y]=await Promise.all([Ba(),ra()]);if(x)return;const R=M.providers??[],j=R.find(_=>_.id==="github"),S=!R.some(_=>_.id!=="github"&&_.authenticated),P=!y.defaultProvider&&!y.defaultModelId,T=j?!j.authenticated:!1;h({needsAiProvider:S,needsDefaultModel:P,needsGitHub:T})}catch{x||c(!0)}finally{x||o(!1)}})(),()=>{x=!0}},[s,i]);const g=a.useCallback(()=>{zA(),d(!0)},[]),p=a.useCallback(()=>{n()},[n]),f=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:vn}),m.needsDefaultModel&&x.push({id:"default-model",title:"Select Default Model",description:"Choose a default AI model for task execution",actionLabel:"Choose Model",onAction:f,icon:ah}),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,f,p]);return!s||i||u||r||l||v.length===0?null:t.jsxs("section",{className:"post-onboarding-recommendations",role:"region","aria-label":"Setup recommendations",children:[t.jsxs("div",{className:"post-onboarding-recommendations__main",children:[t.jsx("div",{className:"post-onboarding-recommendations__icon","aria-hidden":"true",children:t.jsx(Us,{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 k=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(ss,{size:14,"aria-hidden":!0}),t.jsx(k,{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:g,"aria-label":"Dismiss recommendations",children:t.jsx(Pt,{size:16,"aria-hidden":!0})})]})}function RT({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 Nl(e){return e>99?"99+":String(e)}function IT({view:e,onChangeView:n,footerVisible:s,modalOpen:i=!1,onOpenSettings:r,onOpenActivityLog:o,onOpenMailbox:l,mailboxUnreadCount:c=0,onOpenGitManager:u,onOpenWorkflowSteps:d,onOpenSchedules:m,onOpenScripts:h,onToggleTerminal:g,onOpenFiles:p,onOpenGitHubImport:f,onOpenPlanning:b,onResumePlanning:v,activePlanningSessionCount:x=0,onOpenUsage:k,onRunScript:M,projectId:y,onViewAllProjects:R,showSkillsTab:j,experimentalFeatures:C}){const S=tr(),[P,T]=a.useState(!1),[_,L]=a.useState(!1),[G,$]=a.useState({}),[I,w]=a.useState(!1),q=a.useMemo(()=>Object.entries(G).sort(([re],[F])=>re.localeCompare(F)),[G]);a.useEffect(()=>{if(!_)return;let re=!1;return w(!0),Xa(y).then(F=>{re||$(F)}).catch(()=>{re||$({})}).finally(()=>{re||w(!1)}),()=>{re=!0}},[_,y]);const W=a.useCallback(()=>T(!1),[]),B=a.useCallback(re=>{W(),re?.()},[W]);if(a.useEffect(()=>{if(!P)return;const re=F=>{F.key==="Escape"&&T(!1)};return document.addEventListener("keydown",re),()=>document.removeEventListener("keydown",re)},[P]),S!=="mobile"||i)return null;const A=x>0&&v?v:b,z=!!C?.roadmap,X=!!j,E=z&&(!X||e==="roadmaps"),U=X&&(!z||e!=="roadmaps"),pe=X&&!U,ie=e==="documents"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||e==="roadmaps"&&!E||e==="skills"&&!U;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(Ci,{}),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(an,{}),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(ns,{}),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(li,{}),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(Gi,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),c>0&&t.jsx("span",{className:"mobile-nav-tab-badge",children:Nl(c)})]}),U&&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(vn,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),E&&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(Rl,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Roadmaps"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${ie?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>T(re=>!re),children:[t.jsx(_l,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),P&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mobile-more-sheet-backdrop",onClick:W}),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:()=>B(l),children:[t.jsx(Gi,{}),t.jsx("span",{children:"Mailbox"}),c>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:Nl(c)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>B(o),children:[t.jsx(Ss,{}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>B(u),children:[t.jsx(Os,{}),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:()=>B(g),children:[t.jsx(Bs,{}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>L(re=>!re),"aria-expanded":_,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(en,{size:14,className:`mobile-more-chevron${_?" mobile-more-chevron--open":""}`})})]}),_&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:I?t.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[t.jsx(it,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):q.length>0?t.jsxs(t.Fragment,{children:[q.map(([re,F])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${re}`,onClick:()=>{M&&M(re,F),W(),L(!1)},children:[t.jsx(rn,{size:14}),t.jsx("span",{children:re})]},re)),h&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{W(),L(!1),h()},children:[t.jsx(Ts,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):h&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":"mobile-more-scripts-manage",onClick:()=>{W(),L(!1),h()},children:[t.jsx(Ts,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-files",onClick:()=>B(p),children:[t.jsx(jn,{}),t.jsx("span",{children:"Files"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>B(A),children:[t.jsx(Us,{}),t.jsx("span",{children:"Planning"}),x>0&&t.jsx("span",{className:"mobile-more-item-badge",children:Nl(x)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>B(d),children:[t.jsx(Pl,{}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>B(m),children:[t.jsx(ji,{}),t.jsx("span",{children:"Automation"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>B(f),children:[t.jsx(RT,{}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>B(k),children:[t.jsx(Ss,{}),t.jsx("span",{children:"Usage"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>B(R),children:[t.jsx(ih,{}),t.jsx("span",{children:"Projects"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>B(()=>n("documents")),children:[t.jsx(Ni,{}),t.jsx("span",{children:"Documents"})]}),pe&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>B(()=>n("skills")),children:[t.jsx(vn,{}),t.jsx("span",{children:"Skills"})]}),z&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-roadmaps",onClick:()=>B(()=>n("roadmaps")),children:[t.jsx(Rl,{}),t.jsx("span",{children:"Roadmaps"})]}),C?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>B(()=>n("insights")),children:[t.jsx(Dn,{}),t.jsx("span",{children:"Insights"})]}),C?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>B(()=>n("memory")),children:[t.jsx(Pr,{}),t.jsx("span",{children:"Memory"})]}),C?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{B(()=>n("dev-server"))},children:[t.jsx(rh,{size:14}),t.jsx("span",{children:"Dev Server"})]}),t.jsx("div",{className:"mobile-more-separator"}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-settings",onClick:()=>B(r),children:[t.jsx(Oa,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function PT({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(an,{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 Lc="__fn_agent__";function pf(e,n){const s=typeof e=="string"?e.trim():"",i=typeof n=="string"?n.trim():"";return!s||!i?{}:{modelProvider:s,modelId:i}}function Dm(e,n,s){const i=typeof e=="string"?e.trim():"",r=pf(n,s),o=i||(r.modelProvider&&r.modelId?Lc:"");return o?{agentId:o,...r}:null}function Sl(e,n,s){const i=pf(n,s),r=i.modelProvider??"",o=i.modelId??"";return`${e}::${r}/${o}`}function $T(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 Lm(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:$T(e.metadata),createdAt:e.createdAt}}function DT(e,n){const[s,i]=a.useState(null),[r,o]=a.useState(!1),[l,c]=a.useState([]),[u,d]=a.useState(!1),[m,h]=a.useState(!1),[g,p]=a.useState(""),[f,b]=a.useState(""),[v,x]=a.useState([]),[k,M]=a.useState(""),y=a.useRef(null),R=a.useRef(!1),j=a.useRef(""),C=a.useRef(""),S=a.useRef(null);a.useEffect(()=>{j.current=k},[k]);const P=a.useCallback(async B=>{const A={agentId:B.agentId};return B.modelProvider&&B.modelId&&(A.modelProvider=B.modelProvider,A.modelId=B.modelId),(await Ok(A,e)).session},[e]),T=a.useCallback(async(B,A,z)=>{const X=Dm(B,A,z);if(!X)return;const E=Sl(X.agentId,X.modelProvider,X.modelId);o(!0);try{const{session:U}=await Fk({agentId:X.agentId,modelProvider:X.modelProvider,modelId:X.modelId},e);if(U)i(U),C.current=E;else{const pe=await P(X);i(pe),C.current=E}}catch(U){console.error("[useQuickChat] Failed to initialize session:",U),n?.("Failed to initialize chat","error")}finally{o(!1)}},[e,n,P]),_=a.useCallback(async()=>{if(s){d(!0);try{const B=await yd(s.id,{limit:50},e);c(B.messages.map(Lm))}catch(B){console.error("[useQuickChat] Failed to load messages:",B)}finally{d(!1)}}},[s,e]);a.useEffect(()=>{s?_():c([])},[s,_]);const L=a.useCallback(async()=>{if(s){d(!0);try{const B=await yd(s.id,{limit:50},e);c(B.messages.map(Lm))}catch(B){console.error("[useQuickChat] Failed to reload messages:",B)}finally{d(!1)}}},[s,e]),G=a.useCallback(async(B,A,z)=>{const X=Dm(B,A,z);if(!X)return;const E=Sl(X.agentId,X.modelProvider,X.modelId);if(S.current=X,y.current&&(y.current.close(),y.current=null),p(""),b(""),x([]),h(!1),E===C.current&&s){await L();return}c([]),C.current=E,await T(X.agentId,X.modelProvider,X.modelId)},[T,L,s]),$=a.useCallback(async(B,A)=>{await G(Lc,B,A)},[G]),I=a.useCallback(async()=>{const B=S.current;if(!B)return;const A=Sl(B.agentId,B.modelProvider,B.modelId);y.current&&(y.current.close(),y.current=null),p(""),b(""),x([]),h(!1),c([]),o(!0);try{const z=await P(B);i(z),C.current=A}catch(z){console.error("[useQuickChat] Failed to start a fresh session:",z),n?.("Failed to start a new chat","error")}finally{o(!1)}},[n,P]),w=a.useCallback(()=>{s&&(R.current=!0,y.current?.close(),y.current=null,Uk(s.id,e).catch(()=>{}),h(!1),p(""),b(""),x([]))},[s,e]),q=a.useCallback(()=>{j.current="",M("")},[]),W=a.useCallback(B=>{if(!s||!B.trim())return;if(m){j.current=B,M(B);return}R.current=!1,y.current&&(y.current.close(),y.current=null);const z={id:`temp-${Date.now()}`,sessionId:s.id,role:"user",content:B,createdAt:new Date().toISOString()};c(ie=>[...ie,z]),p(""),b(""),x([]),h(!0);let X="",E="",U=[];const pe={onThinking:ie=>{E+=ie,b(E)},onText:ie=>{X+=ie,p(X)},onToolStart:ie=>{U=[...U,{toolName:ie.toolName,args:ie.args,isError:!1,status:"running"}],x(U)},onToolEnd:ie=>{const re=[...U];for(let F=re.length-1;F>=0;F--){const ce=re[F];if(ce?.toolName===ie.toolName&&ce.status==="running"){re[F]={...ce,status:"completed",isError:ie.isError,result:ie.result},U=re,x(re);return}}U=[...re,{toolName:ie.toolName,isError:ie.isError,result:ie.result,status:"completed"}],x(U)},onDone:ie=>{const re={id:ie.messageId||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:X,thinkingOutput:E||void 0,toolCalls:U.length>0?U:void 0,createdAt:new Date().toISOString()};c(ce=>[...ce,re]),p(""),b(""),x([]),h(!1),y.current=null;const F=j.current.trim();F&&(j.current="",M(""),W(F))},onError:ie=>{if(p(""),b(""),x([]),h(!1),y.current=null,console.error("[useQuickChat] Stream error:",ie),n?.("Failed to get response","error"),!R.current){const re=j.current.trim();re&&(j.current="",M(""),W(re))}L()}};y.current=Bk(s.id,B,pe,e)},[s,m,e,n,L]);return a.useEffect(()=>()=>{y.current&&(y.current.close(),y.current=null)},[]),a.useMemo(()=>({activeSession:s,sessionsLoading:r,messages:l,messagesLoading:u,isStreaming:m,streamingText:g,streamingThinking:f,streamingToolCalls:v,pendingMessage:k,sendMessage:W,stopStreaming:w,clearPendingMessage:q,switchSession:G,startModelChat:$,startFreshSession:I,loadMessages:_,reloadMessages:L}),[s,r,l,u,m,g,f,v,k,W,w,q,G,$,I,_,L])}function LT(e,n){const[s,i]=a.useState([]),[r,o]=a.useState(null),[l,c]=a.useState(!1),u=a.useCallback(async g=>{c(!0);try{const p=n?.filterState,f=p&&p!=="all"?{state:p}:void 0,b=n?.showSystemAgents??!1,v=await oa({...f,...g,includeEphemeral:g?.includeEphemeral??b},e),x=Array.from(new Map(v.map(k=>[k.id,k])).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 g=await ky(e);o(g)}catch(g){console.error("Failed to load agent stats:",g)}},[e]);a.useEffect(()=>{u(),d()},[u,d]),a.useEffect(()=>{const g=e?`?projectId=${encodeURIComponent(e)}`:"",p=()=>{u(),d()};return qs(`/api/events${g}`,{events:{"agent:created":p,"agent:updated":p,"agent:deleted":p,"agent:stateChanged":p}})},[e,u,d]);const m=n?.showSystemAgents??!1,h=s.filter(g=>g.state!=="active"&&g.state!=="running"?!1:m||!nj(g));return{agents:s,activeAgents:h,stats:r,isLoading:l,loadAgents:u,loadStats:d}}function zT({visible:e,position:n,files:s,selectedIndex:i,onSelect:r,loading:o}){return e?t.jsxs("div",{className:"file-mention-popup",style:{top:n.top,left:n.left},"data-testid":"file-mention-popup",onMouseDown:l=>{l.preventDefault()},children:[o&&t.jsx("div",{className:"file-mention-popup-loading","data-testid":"file-mention-loading",children:t.jsx("span",{className:"spinner"})}),!o&&s.length===0&&t.jsx("div",{className:"file-mention-popup-empty","data-testid":"file-mention-empty",children:"No files found"}),!o&&s.length>0&&t.jsx("ul",{className:"file-mention-popup-list",role:"listbox",children:s.map((l,c)=>{const u=l.path.includes("/")?l.path.slice(0,l.path.lastIndexOf("/")+1):"",d=l.name;return t.jsxs("li",{className:`file-mention-popup-item${c===i?" file-mention-popup-item--selected":""}`,onClick:()=>r(l),onMouseEnter:()=>{},role:"option","aria-selected":c===i,"data-testid":`file-mention-item-${c}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(nh,{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 FT=200;function OT(e={}){const{projectId:n,workspace:s="project"}=e,[i,r]=a.useState(!1),[o,l]=a.useState(""),[c,u]=a.useState(-1),[d,m]=a.useState([]),[h,g]=a.useState(!1),[p,f]=a.useState(0),b=a.useRef(null),v=a.useRef(null);a.useEffect(()=>()=>{b.current&&clearTimeout(b.current),v.current?.abort()},[]);const x=a.useCallback((j,C)=>{if(C<0||C>j.length){r(!1);return}const S=P=>/[a-zA-Z0-9/_.-]/.test(P);for(let P=C-1;P>=0;P--){if(j[P]==="#")if(P===0){const T=j.slice(P+1,C);u(P),l(T),f(0),r(!0);return}else{const T=j[P-1];if(/[\s,.;:!?'"()[\]{}]/.test(T)){const _=j.slice(P+1,C);u(P),l(_),f(0),r(!0);return}r(!1);return}if(!S(j[P])){r(!1);return}}r(!1)},[]),k=a.useCallback(()=>{r(!1),l(""),u(-1),m([]),f(0),g(!1)},[]),M=a.useCallback(async j=>{if(!j.trim()){m([]),g(!1);return}v.current?.abort(),v.current=new AbortController;try{g(!0);const C=await Av(j,s,n);m(C.files),f(0)}catch(C){C.name!=="AbortError"&&m([])}finally{g(!1)}},[s,n]);a.useEffect(()=>{if(i)return b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{M(o)},FT),()=>{b.current&&clearTimeout(b.current)}},[o,i,M]);const y=a.useCallback((j,C)=>{if(!i||c<0)return C;const S=C.slice(0,c),P=C.slice(c+1),T=P.match(/[\s]|$/),_=T?T.index:P.length,L=P.slice(_);return`${S}#${j.path}${L}`},[i,c]),R=a.useCallback((j,C)=>{if(!i||d.length===0)return!1;switch(j.key){case"ArrowDown":return j.preventDefault(),f(S=>Math.min(S+1,d.length-1)),!0;case"ArrowUp":return j.preventDefault(),f(S=>Math.max(S-1,0)),!0;case"Enter":case"Tab":return d[p]?(j.preventDefault(),!0):!1;case"Escape":return j.preventDefault(),k(),!0;default:return!1}},[i,d,p,k]);return{mentionActive:i,files:d,loading:h,mentionQuery:o,selectedIndex:p,setSelectedIndex:f,detectMention:x,selectFile:y,dismissMention:k,handleKeyDown:R}}const UT={display:"inline-flex",alignItems:"center",maxWidth:"180px",padding:"var(--space-xs) var(--space-sm)",borderRadius:"var(--radius-pill)",border:"1px solid color-mix(in srgb, var(--todo) 35%, var(--border))",background:"color-mix(in srgb, var(--todo) 14%, transparent)",color:"var(--text)",fontSize:"11px",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},BT={display:"flex",alignItems:"center",gap:"var(--space-sm)",minWidth:0};function HT(e){return`${e.name?.trim()||e.id} (${e.role})`}function qT(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 VT(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 Ir(e,n){return e.length>n?`${e.slice(0,n)}…`:e}function WT(e){if(!e)return null;const n=Object.entries(e);return n.length===0?null:n.map(([s,i])=>{let r="";if(typeof i=="string")r=i;else try{r=JSON.stringify(i)}catch{r=String(i)}return`${s}=${Ir(r,50)}`}).join(", ")}function GT(e){if(e===void 0)return null;if(typeof e=="string")return Ir(e,200);try{return Ir(JSON.stringify(e),200)}catch{return Ir(String(e),200)}}function zm(e,n=!1){return!e||e.length===0?null:t.jsxs("div",{className:`chat-tool-calls${n?" chat-tool-calls--compact":""}`,"data-testid":"chat-tool-calls",children:[t.jsxs("div",{className:"chat-tool-calls-header",children:[t.jsx(Jb,{size:12,"aria-hidden":"true"}),t.jsx("span",{children:"Tool calls"})]}),e.map((s,i)=>{const r=s.status==="running",o=s.status==="completed"&&s.isError,l=WT(s.args),c=GT(s.result),u=r?l:c?`result: ${c}`:l?`args: ${l}`:null,d=r?"running":o?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${r?" chat-tool-call--running":""}${o?" chat-tool-call--error":""}`,open:r,children:[t.jsxs("summary",{children:[t.jsx("span",{className:"chat-tool-call-status-dot","aria-hidden":"true"}),t.jsx("span",{className:"chat-tool-call-name",children:s.toolName}),u&&t.jsx("span",{className:"chat-tool-call-preview",title:u,children:u}),t.jsx("span",{className:"chat-tool-call-status-text",children:d})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[l&&t.jsxs("div",{className:"chat-tool-call-row",children:[t.jsx("span",{className:"chat-tool-call-label",children:"args"}),t.jsx("span",{className:"chat-tool-call-value",children:l})]}),c&&t.jsxs("div",{className:`chat-tool-call-row${o?" chat-tool-call-row--error":""}`,children:[t.jsx("span",{className:"chat-tool-call-label",children:"result"}),t.jsx("span",{className:"chat-tool-call-value",children:c})]})]})]},`${s.toolName}-${i}`)})]})}const KT={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 JT(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}}function YT(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,k=window.innerWidth<=768?44:0,M=window.innerWidth>768?s():0,y=window.innerWidth-v-x,R=window.innerHeight-v-x-k-M;return{x:Math.max(x,Math.min(y,b.x)),y:Math.max(x,Math.min(R,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]),g=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 k=u.current.x-v,M=u.current.y-x,y=m({x:k,y:M});o(y)}},[l,m]),f=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:g,handlePointerMove:p,handlePointerUp:f}}function QT({projectId:e,addToast:n,showFAB:s=!0,open:i,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:c,onToggleModelFavorite:u}){const{agents:d}=LT(e),[m,h]=a.useState(!1),g=i!==void 0,p=g?i:m,f=g?Me=>{r?.(typeof Me=="function"?Me(p):Me)}:h,[b,v]=a.useState("agent"),[x,k]=a.useState(""),[M,y]=a.useState([]),[R,j]=a.useState(!1),[C,S]=a.useState(""),[P,T]=a.useState(""),[_,L]=a.useState(""),[G,$]=a.useState(!1),[I,w]=a.useState(0),[q,W]=a.useState(-1),[B,A]=a.useState(()=>new Set),[,z]=a.useState(!1),[X,E]=a.useState({top:0,left:0}),U=OT({projectId:e}),pe=a.useCallback(Me=>{if(!Me||!U.mentionActive)return;const Qe=Me.getBoundingClientRect();E({top:Qe.top-260,left:Qe.left+8})},[U.mentionActive]),ie=a.useRef(!1),re=a.useRef(!1),F=a.useRef(""),ce=a.useRef(0),ae=a.useRef(null),{position:Q,isDragging:de,handlePointerDown:Te,handlePointerMove:fe,handlePointerUp:Se}=YT(e,ie),{activeSession:te,messages:we,isStreaming:Pe,streamingText:We,streamingThinking:Ke,streamingToolCalls:Ne,sessionsLoading:_e,messagesLoading:Oe,sendMessage:ye,stopStreaming:De,pendingMessage:se,clearPendingMessage:J,switchSession:me,startModelChat:ee,startFreshSession:he}=DT(e,n),le=a.useRef(null),Ie=a.useRef(null),Ze=a.useRef(null),at=a.useRef(null),oe=a.useMemo(()=>qT(C),[C]),Z=a.useMemo(()=>M.find(Me=>`${Me.provider}/${Me.id}`===C)??null,[M,C]),ue=a.useMemo(()=>VT(Z,oe),[Z,oe]),Ce=a.useMemo(()=>b==="model"?oe?`${Lc}::${oe.modelProvider}/${oe.modelId}`:"":x?`${x}::`:"",[b,oe,x]),$e=b==="agent"?!!x:!!oe;a.useEffect(()=>{if(d.length===0){k(""),v("model");return}d.some(Qe=>Qe.id===x)||k(d[0]?.id??"")},[d,x]),a.useEffect(()=>{!p||re.current||(re.current=!0,j(!0),is().then(Me=>{const Qe=Me.models??[];if(y(Qe),d.length===0&&Qe.length>0&&!C){const rt=Qe[0];rt&&S(`${rt.provider}/${rt.id}`)}}).catch(Me=>{console.error("[QuickChatFAB] Failed to load models:",Me),y([])}).finally(()=>{j(!1)}))},[p,d.length,C]),a.useEffect(()=>{if(!p){F.current="";return}if(!Ce){F.current="";return}if(Ce!==F.current){if(F.current=Ce,b==="model"&&oe){ee(oe.modelProvider,oe.modelId);return}b==="agent"&&x&&me(x)}},[p,b,oe,x,Ce,ee,me]),a.useEffect(()=>{p||($(!1),L(""),W(-1))},[p]);const ve=a.useCallback(Me=>{k(Me)},[]),Ge=a.useCallback(Me=>{S(Me)},[]),je=a.useCallback(()=>{!$e||_e||he()},[$e,_e,he]),Ue=a.useMemo(()=>d.find(Me=>Me.id===x)??null,[d,x]),He=a.useMemo(()=>{const Me=_.trim().toLowerCase();return Me?d.filter(Qe=>Qe.name.toLowerCase().includes(Me)):d},[d,_]),ge=a.useMemo(()=>{const Me=new Map;for(const Qe of d)Me.set(Qe.name.toLowerCase(),Qe);return Me},[d]);a.useEffect(()=>{w(0)},[_,G]),a.useEffect(()=>()=>{ae.current!==null&&(window.clearTimeout(ae.current),ae.current=null)},[]),a.useEffect(()=>{if(!p)return;const Me=rt=>{const N=rt.target;le.current?.contains(N)||Ie.current?.contains(N)||N.closest(".model-combobox-dropdown--portal")||f(!1)},Qe=rt=>{rt.key==="Escape"&&f(!1)};return document.addEventListener("mousedown",Me),document.addEventListener("keydown",Qe),()=>{document.removeEventListener("mousedown",Me),document.removeEventListener("keydown",Qe)}},[p,f]),a.useEffect(()=>{if(!p)return;const Me=Ze.current;Me&&(Me.scrollTop=Me.scrollHeight)},[we,We,Ke,p]);const Fe=a.useMemo(()=>b==="agent"?Ue?`Message ${Ue.name||Ue.id}`:"Select an agent to start chatting":ue?`Message ${ue}`:"Select a model to start chatting",[b,Ue,ue]),be=!$e||!te||_e,Je=se.length>50?`${se.slice(0,50)}…`:se,st=a.useCallback(()=>{const Me=P.trim();!Me||be||(T(""),$(!1),L(""),W(-1),ye(Me))},[ye,be,P]),dt=a.useCallback((Me,Qe)=>{const rt=JT(Me,Qe);if(rt){$(!0),L(rt.filter),W(rt.start);return}$(!1),L(""),W(-1)},[]),Tt=a.useCallback(Me=>{const Qe=at.current;if(!Qe||q<0)return;const rt=Qe.selectionStart??ce.current,N=Qe.selectionEnd??rt,H=Math.max(rt,N),Ae=Math.min(q,H),kt=`${`@${Me.name.replace(/\s+/g,"_")}`} `,Ot=P.slice(0,Ae)+kt+P.slice(H),sn=Ae+kt.length;T(Ot),$(!1),L(""),w(0),W(-1),window.requestAnimationFrame(()=>{at.current&&(at.current.focus(),at.current.setSelectionRange(sn,sn))})},[q,P]),$t=a.useCallback(Me=>{const Qe=Me.target.value,rt=Me.target.selectionStart??Qe.length;ce.current=rt,T(Qe),dt(Qe,rt),U.detectMention(Qe,rt),z(U.mentionActive),U.mentionActive&&pe(Me.target)},[dt,U,pe]),Dt=a.useCallback(()=>{ae.current!==null&&window.clearTimeout(ae.current),ae.current=window.setTimeout(()=>{$(!1),L(""),W(-1),z(!1),U.dismissMention(),ae.current=null},120)},[U]),Bt=a.useCallback(()=>{ae.current!==null&&(window.clearTimeout(ae.current),ae.current=null)},[]),qt=a.useCallback(Me=>{const Qe=Me.currentTarget,rt=Qe.selectionStart??Qe.value.length;ce.current=rt,dt(Qe.value,rt),U.detectMention(Qe.value,rt),z(U.mentionActive),U.mentionActive&&pe(Qe)},[dt,U,pe]),Lt=a.useCallback(Me=>{Me.key!=="Escape"&&qt(Me)},[qt]),Ct=a.useCallback(Me=>{const Qe=/@([\w-]+)/g,rt=[];let N=0,H=Qe.exec(Me);for(;H;){const[Ae,ot=""]=H,kt=H.index;kt>N&&rt.push(Me.slice(N,kt));const Ot=ot.replace(/_/g," ").toLowerCase(),sn=ge.get(Ot);sn?rt.push(t.jsxs("span",{className:"chat-mention-chip",children:["@",sn.name.replace(/\s+/g,"_")]},`${sn.id}-${kt}`)):rt.push(Ae),N=kt+Ae.length,H=Qe.exec(Me)}return N<Me.length&&rt.push(Me.slice(N)),rt.length===0?Me:rt},[ge]),xt=a.useCallback(Me=>{A(Qe=>{const rt=new Set(Qe);return rt.has(Me)?rt.delete(Me):rt.add(Me),rt})},[]),Et=a.useCallback((Me,Qe=!1)=>Qe?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:Me}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(Qs,{remarkPlugins:[Xs],components:KT,children:Me})}),[]),Le=a.useCallback(Me=>{if(ce.current=Me.currentTarget.selectionStart??ce.current,U.mentionActive&&U.files.length>0){if(U.handleKeyDown(Me,P),Me.key==="Enter"||Me.key==="Tab"){const Qe=U.files[U.selectedIndex];if(Qe){const rt=U.selectFile(Qe,P);T(rt),U.dismissMention(),z(!1)}}return}if(G&&Me.key==="ArrowDown"){Me.preventDefault(),He.length>0&&w(Qe=>(Qe+1)%He.length);return}if(G&&Me.key==="ArrowUp"){Me.preventDefault(),He.length>0&&w(Qe=>Qe===0?He.length-1:Qe-1);return}if(G&&Me.key==="Enter"){Me.preventDefault();const Qe=He[I]??He[0];Qe&&Tt(Qe);return}if(G&&Me.key==="Escape"){Me.preventDefault(),Me.stopPropagation(),$(!1),L(""),W(-1);return}Me.key!=="Enter"||Me.shiftKey||(Me.preventDefault(),st())},[G,He,I,Tt,st,U,P]),gt=a.useCallback(()=>{if(ie.current){ie.current=!1;return}f(Me=>!Me)},[f]),ut=Q.y+60;return t.jsxs(t.Fragment,{children:[s&&t.jsx("button",{ref:Ie,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":de?"true":"false",style:{right:Q.x,bottom:Q.y},onPointerDown:Te,onPointerMove:fe,onPointerUp:Se,onClick:gt,children:t.jsx(li,{size:24})}),p&&t.jsxs("div",{className:"quick-chat-panel",ref:le,"data-testid":"quick-chat-panel",style:{right:Q.x,bottom:ut},children:[t.jsxs("div",{className:"quick-chat-panel-header",children:[t.jsxs("div",{style:BT,children:[t.jsx("h3",{children:"Quick Chat"}),ue&&t.jsx("span",{style:UT,"data-testid":"quick-chat-model-tag",title:ue,children:ue})]}),t.jsxs("div",{className:"quick-chat-panel-header-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm","data-testid":"quick-chat-new-thread",onClick:je,disabled:!$e||_e,children:"New chat"}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":"Close quick chat","data-testid":"quick-chat-close",onClick:()=>f(!1),children:t.jsx(Pt,{size:16})})]})]}),d.length>0&&t.jsxs("div",{className:"quick-chat-mode-toggle","data-testid":"quick-chat-mode-toggle",children:[t.jsx("button",{type:"button",className:`quick-chat-mode-btn${b==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-mode-agent",onClick:()=>{v("agent"),S("")},children:"Agent"}),t.jsx("button",{type:"button",className:`quick-chat-mode-btn${b==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-mode-model",onClick:()=>{v("model"),k("")},children:"Model"})]}),b==="agent"&&d.length>0&&t.jsxs("div",{className:"quick-chat-panel-agent-select",children:[t.jsx("label",{htmlFor:"quick-chat-agent-select",className:"visually-hidden",children:"Select agent"}),t.jsx("select",{id:"quick-chat-agent-select",value:x,onChange:Me=>ve(Me.target.value),"data-testid":"quick-chat-agent-select",children:d.map(Me=>t.jsx("option",{value:Me.id,children:HT(Me)},Me.id))})]}),b==="model"&&t.jsxs("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-model-select",children:[t.jsx("label",{htmlFor:"quick-chat-model-override",className:"visually-hidden",children:"Select model override"}),t.jsx(wn,{id:"quick-chat-model-override",models:M,value:C,onChange:Ge,label:"Select model override",placeholder:R?"Loading models…":"Select a model",disabled:R||M.length===0,favoriteProviders:o,favoriteModels:l,onToggleFavorite:c,onToggleModelFavorite:u})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:Ze,"data-testid":"quick-chat-messages",children:_e||Oe?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):we.length===0&&!We&&!Ke&&!Pe?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[we.map(Me=>{const Qe=Me.role==="user",rt=!Qe&&B.has(Me.id);return t.jsxs("div",{className:`quick-chat-panel-message ${Qe?"quick-chat-panel-message--sent":"quick-chat-panel-message--received"}`,"data-testid":`quick-chat-message-${Me.id}`,children:[Qe?t.jsx("p",{children:Ct(Me.content)}):t.jsxs(t.Fragment,{children:[Et(Me.content,rt),t.jsx("button",{type:"button",className:`btn btn-icon quick-chat-message-render-toggle${rt?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":rt?"Show rendered markdown":"Show plain text",onClick:()=>xt(Me.id),children:rt?t.jsx($r,{size:12}):t.jsx(Vi,{size:12})})]}),zm(Me.toolCalls,!0)]},Me.id)}),Pe&&t.jsxs("div",{className:"quick-chat-panel-message quick-chat-panel-message--received quick-chat-panel-message--streaming","data-testid":"quick-chat-streaming-message",children:[We?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:Et(We,B.has("__streaming__"))}),t.jsx("button",{type:"button",className:`btn btn-icon 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:()=>xt("__streaming__"),children:B.has("__streaming__")?t.jsx($r,{size:12}):t.jsx(Vi,{size:12})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:Ke?"Thinking…":"Connecting…"}),zm(Ne,!0),Ke&&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:Ke})]})]})]})}),t.jsxs("div",{className:"quick-chat-panel-input",children:[t.jsxs("div",{className:"quick-chat-input-wrapper",children:[t.jsx("input",{ref:at,type:"text",value:P,onChange:$t,onKeyDown:Le,onKeyUp:Lt,onClick:qt,onBlur:Dt,onFocus:Bt,placeholder:Fe,disabled:be,"data-testid":"quick-chat-input"}),t.jsx(PT,{agents:d,filter:_,highlightedIndex:I,visible:G,onSelect:Tt,position:"above"}),t.jsx(zT,{visible:U.mentionActive&&!G,position:X,files:U.files,selectedIndex:U.selectedIndex,onSelect:Me=>{const Qe=U.selectFile(Me,P);T(Qe),U.dismissMention(),z(!1),at.current?.focus()},loading:U.loading}),se&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${Je}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:J,children:"×"})]})]}),Pe?t.jsx("button",{type:"button",className:"chat-input-stop",onClick:De,"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:t.jsx(ls,{size:14})}):t.jsx("button",{type:"button",onClick:()=>void st(),disabled:be||P.trim().length===0,"data-testid":"quick-chat-send",children:t.jsx(vi,{size:16})})]})]})]})}function _a(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function Fm(e){return e.status==="generating"||e.status==="awaiting_input"}function Aa(e){return e==="complete"||e==="error"}function XT(e){const[n,s]=a.useState([]),i=a.useRef(new Map),r=a.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:c,requestSync:u}=la(),d=a.useCallback(()=>{Sh(e).then(p=>{const f=p.filter(v=>{const x=_a(v.updatedAt),k=r.current.get(v.id);return k===void 0?!0:x<=k?!1:(r.current.delete(v.id),!0)}),b=new Map;for(const v of f)b.set(v.id,_a(v.updatedAt));i.current=b,s(f)}).catch(p=>{console.warn("[useBackgroundSessions] Failed to fetch AI sessions:",p)})},[e]);a.useEffect(()=>{u(),d()},[d,u]),a.useEffect(()=>{s(p=>{if(o.size===0)return p;let f=!1;const 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,k=i.current.get(v.sessionId)??0;if(x<k)continue;const M=r.current.get(v.sessionId);if(M!==void 0&&x<=M)continue;if(M!==void 0&&x>M&&!Aa(v.status)&&r.current.delete(v.sessionId),Aa(v.status)){b.delete(v.sessionId)&&(f=!0),i.current.set(v.sessionId,x);continue}const y=b.get(v.sessionId),R=v.type??y?.type,j=v.title??y?.title;if(!y&&(!R||!j))continue;const C={id:v.sessionId,type:R??"planning",status:v.status,title:j??"AI Session",projectId:v.projectId??y?.projectId??e??null,lockedByTab:v.owningTabId??y?.lockedByTab??null,updatedAt:v.updatedAt??y?.updatedAt??new Date(x).toISOString()},S=b.get(v.sessionId);(!S||S.status!==C.status||S.title!==C.title||S.type!==C.type||S.projectId!==C.projectId||S.lockedByTab!==C.lockedByTab||S.updatedAt!==C.updatedAt)&&(b.set(v.sessionId,C),i.current.set(v.sessionId,x),f=!0)}return f?[...b.values()].sort((v,x)=>_a(x.updatedAt)-_a(v.updatedAt)):p})},[e,o]),a.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",f=v=>{try{const x=JSON.parse(v.data),k=_a(x.updatedAt)||Date.now();s(M=>{const y=i.current.get(x.id)??0;if(k<y)return M;const R=r.current.get(x.id);if(R!==void 0&&k<=R)return M;if(R!==void 0&&k>R&&!Aa(x.status)&&r.current.delete(x.id),i.current.set(x.id,k),Aa(x.status))return M.filter(C=>C.id!==x.id);const j=M.findIndex(C=>C.id===x.id);if(j>=0){const C=[...M];return C[j]=x,C}return Fm(x)?[x,...M]:M}),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:k}),Aa(x.status)&&c({sessionId:x.id,status:x.status,timestamp:k})}catch{}},b=v=>{try{const x=JSON.parse(v.data);s(k=>k.filter(M=>M.id!==x)),i.current.delete(x),r.current.delete(x)}catch{}};return qs(`/api/events${p}`,{events:{"ai_session:updated":f,"ai_session:deleted":b}})},[c,l,e]);const m=a.useCallback(async p=>{const b=n.find(y=>y.id===p)?.type,v=_i();let x=!1,k=!1;if(b==="planning")try{await gh(p,e,v)}catch(y){x=!0,y instanceof Error&&y.message.includes("locked")&&(k=!0,console.warn(`[useBackgroundSessions] Cannot dismiss planning session ${p}: locked by another tab`))}else if(b==="subtask")try{await vh(p,e,v)}catch(y){x=!0,y instanceof Error&&y.message.includes("locked")&&(k=!0,console.warn(`[useBackgroundSessions] Cannot dismiss subtask session ${p}: locked by another tab`))}else if(b==="mission_interview")try{await Nh(p,e,v)}catch(y){x=!0,y instanceof Error&&y.message.includes("locked")&&(k=!0,console.warn(`[useBackgroundSessions] Cannot dismiss mission interview session ${p}: locked by another tab`))}if(k)return;x&&console.warn(`[useBackgroundSessions] Cancellation failed for session ${p}, attempting delete anyway`);const M=Date.now();r.current.set(p,M),i.current.set(p,Math.max(i.current.get(p)??0,M)),c({sessionId:p,status:"complete",timestamp:M});try{await Mk(p)}catch{}s(y=>y.filter(R=>R.id!==p))},[c,e,n]),h=a.useMemo(()=>n.filter(p=>Fm(p)),[n]),g=a.useMemo(()=>h.filter(p=>p.type==="planning"),[h]);return{sessions:h,generating:h.filter(p=>p.status==="generating").length,needsInput:h.filter(p=>p.status==="awaiting_input").length,planningSessions:g,dismissSession:m,refresh:d}}function In(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 Om(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function ZT(e){const n=e?.projectId,s=e?.searchQuery,i=e?.sseEnabled??!0,[r,o]=a.useState([]),[l,c]=a.useState(!1),u=a.useRef(l);u.current=l;const d=a.useRef(r),m=a.useRef(0),h=a.useRef(0),g=a.useRef(s),p=a.useRef(null),f=a.useRef(void 0),b=a.useRef(0),v=a.useRef(n);d.current=r,g.current=s,v.current!==n&&(v.current=n,b.current++);const x=1e3,k=a.useCallback(async I=>{const w=++m.current,q=n,W=I?.searchQueryOverride??s,B=I?.includeArchivedOverride??u.current;try{const A=await vx(void 0,void 0,q,W,B);if(m.current!==w||n!==q)return;o(A.map(In)),f.current=Date.now()}catch{if(m.current!==w||n!==q)return;if(I?.clearOnError){o([]);return}o(A=>A)}},[n,s]);p.current=k;const M=a.useCallback(async()=>{u.current||(c(!0),u.current=!0,await p.current({includeArchivedOverride:!0}))},[]);a.useEffect(()=>{if(s===void 0)return;const I=setTimeout(()=>{k({searchQueryOverride:s})},300);return()=>clearTimeout(I)},[s]),a.useEffect(()=>{k({clearOnError:!0});const I=()=>{if(document.visibilityState!=="visible")return;const w=Date.now();w-h.current<x||(h.current=w,k())};return document.addEventListener("visibilitychange",I),()=>{document.removeEventListener("visibilitychange",I)}},[k]),a.useEffect(()=>{if(i===!1)return;const I=b.current,w=n?`?projectId=${encodeURIComponent(n)}`:"",q=()=>b.current!==I;let W=!0;const B=pe=>{if(q())return;const ie=In(JSON.parse(pe.data));if(g.current){p.current({searchQueryOverride:g.current});return}o(re=>re.some(F=>F.id===ie.id)?re:[...re,ie])},A=pe=>{if(q())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:ie,to:re}=JSON.parse(pe.data),F=In(ie);o(ce=>ce.map(ae=>ae.id===F.id?{...F,column:re}:ae)),f.current=Date.now()},z=pe=>{if(q())return;if(g.current){p.current({searchQueryOverride:g.current});return}const ie=In(JSON.parse(pe.data));o(re=>re.map(F=>{if(F.id!==ie.id||Om(ie.updatedAt,F.updatedAt)<0)return F;if(F.column===ie.column)return ie;const ae=Om(F.columnMovedAt,ie.columnMovedAt);return F.columnMovedAt&&!ie.columnMovedAt?{...ie,column:F.column,columnMovedAt:F.columnMovedAt}:ae>0?{...ie,column:F.column,columnMovedAt:F.columnMovedAt}:ie})),f.current=Date.now()},X=pe=>{if(q())return;if(g.current){p.current({searchQueryOverride:g.current});return}const ie=In(JSON.parse(pe.data));o(re=>re.filter(F=>F.id!==ie.id))},E=pe=>{if(q())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:ie}=JSON.parse(pe.data),re=In(ie);o(F=>F.map(ce=>ce.id===re.id?{...re,column:"done"}:ce))},U=qs(`/api/events${w}`,{events:{"task:created":B,"task:moved":A,"task:updated":z,"task:deleted":X,"task:merged":E},onReconnect:()=>{W&&(q()||p.current())}});return()=>{W=!1,U()}},[n,i]);const y=a.useCallback(async I=>{const w=In(await mh(I,n));return o(q=>q.some(W=>W.id===w.id)?q:[...q,w]),w},[n]),R=a.useCallback(async(I,w)=>In(await kx(I,w,n)),[n]),j=a.useCallback(async I=>In(await hh(I,n)),[n]),C=a.useCallback(async I=>In(await jx(I,n)),[n]),S=a.useCallback(async I=>wx(I,n),[n]),P=a.useCallback(async I=>In(await Nx(I,n)),[n]),T=a.useCallback(async I=>{const w=In(await Sx(I,n));return o(q=>q.some(W=>W.id===w.id)?q:[...q,w]),w},[n]),_=a.useCallback(async(I,w)=>{const q=d.current.find(B=>B.id===I),W=q?{...q,...w,updatedAt:new Date().toISOString()}:void 0;W&&o(B=>B.map(A=>A.id===I?W:A));try{const B=In(await Ks(I,w,n));return o(A=>A.map(z=>z.id===I?B:z)),B}catch(B){throw q&&o(A=>A.map(z=>z.id===I?q:z)),B}},[n]),L=a.useCallback(async I=>{const w=In(await Ex(I,n));return o(q=>q.map(W=>W.id===I?w:W)),w},[n]),G=a.useCallback(async I=>{const w=In(await Mx(I,n));return o(q=>q.map(W=>W.id===I?w:W)),w},[n]),$=a.useCallback(async()=>{const w=(await _x(n)).map(In);return o(q=>q.map(W=>w.find(A=>A.id===W.id)||W)),w},[n]);return{tasks:r,createTask:y,moveTask:R,pauseTask:j,deleteTask:C,mergeTask:S,retryTask:P,duplicateTask:T,updateTask:_,archiveTask:L,unarchiveTask:G,archiveAllDone:$,loadArchivedTasks:M,includeArchived:l,lastFetchTimeMs:f.current}}const eR=5e3,tR=1e3;function nR(){const[e,n]=a.useState([]),[s,i]=a.useState(!0),[r,o]=a.useState(null),l=a.useRef(null),c=a.useRef(0),u=a.useCallback(async()=>{try{o(null);const g=await pd();n(g)}catch(g){o(g instanceof Error?g.message:"Failed to fetch projects")}},[]);a.useEffect(()=>{let g=!1;async function p(){i(!0);const b=performance.now();try{const v=await pd(),k=`initial fetchProjectsAcrossNodes took ${Math.round(performance.now()-b)}ms (${v.length} projects)`;console.log(`[useProjects] ${k}`),Pa("[useProjects]",k),g||(n(v),o(null))}catch(v){const k=`initial fetch failed after ${Math.round(performance.now()-b)}ms: ${v instanceof Error?v.message:String(v)}`;console.warn(`[useProjects] ${k}`),Pa("[useProjects]",k),g||o(v instanceof Error?v.message:"Failed to fetch projects")}finally{g||i(!1)}}p();const f=()=>{if(document.visibilityState!=="visible")return;const b=Date.now();b-c.current<tR||(c.current=b,u())};return document.addEventListener("visibilitychange",f),()=>{g=!0,document.removeEventListener("visibilitychange",f)}},[u]),a.useEffect(()=>{if(!s)return l.current=setInterval(()=>{u()},eR),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async g=>{const p=await Cy(g);return n(f=>[...f,p]),p},[]),m=a.useCallback(async(g,p)=>{const f=await Ay(g,p);return n(b=>b.map(v=>v.id===g?f:v)),f},[]),h=a.useCallback(async g=>{await kh(g),n(p=>p.filter(f=>f.id!==g))},[]);return{projects:e,loading:s,error:r,refresh:u,register:d,update:m,unregister:h}}const sR=1e4,iR=1e3;function aR(){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 fd();n(p)}catch(p){o(p instanceof Error?p.message:"Failed to fetch nodes")}},[]);a.useEffect(()=>{let p=!1;async function f(){i(!0);try{const v=await fd();p||(n(v),o(null))}catch(v){p||o(v instanceof Error?v.message:"Failed to fetch nodes")}finally{p||i(!1)}}f();const b=()=>{if(document.visibilityState!=="visible")return;const v=Date.now();v-c.current<iR||(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()},sR),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async p=>{const f=await jy(p);return n(b=>[...b,f]),f},[]),m=a.useCallback(async(p,f)=>{const b=await wy(p,f);return n(v=>v.map(x=>x.id===p?b:x)),b},[]),h=a.useCallback(async p=>{await Ny(p),n(f=>f.filter(b=>b.id!==p))},[]),g=a.useCallback(async p=>{const f=await Sy(p);n(b=>b.map(v=>v.id===p?{...v,status:f.status,updatedAt:f.checkedAt}:v))},[]);return{nodes:e,loading:s,error:r,refresh:u,register:d,update:m,unregister:h,healthCheck:g}}const rR="kb-dashboard-current-project";function oR(e){return e??"local"}function lR(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=oR(s);a.useEffect(()=>{let p=!1;async function f(){try{const b=await ra();if(p)return;d.current=b.dashboardCurrentProjectIdByNode??{};const v=d.current[m];if(v){const x=e.find(k=>k.id===v);x&&(r(x),c.current=!0)}if(!v)try{const x=localStorage.getItem(rR);if(x){const k=JSON.parse(x);k?.id&&e.some(y=>y.id===k.id)&&(r(k),c.current=!0,d.current={...d.current,[m]:k.id},await nn({dashboardCurrentProjectIdByNode:d.current}).catch(()=>{}))}}catch{}}catch{}finally{p||l(!1)}}return f(),()=>{p=!0}},[m,e]),a.useEffect(()=>{if(!o){if(i){if(!e.some(b=>b.id===i.id)&&e.length>0){const b=e.find(v=>v.status==="active");r(b||e[0]||null);return}const f={...d.current,[m]:i.id};d.current=f,nn({dashboardCurrentProjectIdByNode:f}).catch(()=>{})}else if(e.length>0&&!u.current){const p=e.find(f=>f.status==="active");p&&r(p)}}},[i,e,o,m]);const h=a.useCallback(p=>{if(u.current=!1,r(p),p){const f={...d.current,[m]:p.id};d.current=f,nn({dashboardCurrentProjectIdByNode:f}).catch(()=>{})}},[m]),g=a.useCallback(()=>{u.current=!0,r(null);const p={...d.current};delete p[m],d.current=p,nn({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[m]);return{currentProject:i,setCurrentProject:h,clearCurrentProject:g,loading:o}}const ff=a.createContext(null);function cR({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()},[]),Jm.createElement(ff.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function dR(){const e=a.useContext(ff);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const gf="kb-dashboard-theme-mode",bf="kb-dashboard-color-theme",xf=[...ej],ac="theme-data",Cl="theme-data.css";function uR(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.endsWith("/")?e.slice(0,-1)+`/${Cl}`:e.replace(/\/[^/]+$/,`/${Cl}`):`/${Cl}`}const Ns=typeof window<"u",mR=Ns?a.useLayoutEffect:a.useEffect;function vf(e){return e==="dark"||e==="light"||e==="system"}function Um(){if(!Ns)return"dark";try{const e=localStorage.getItem(gf);if(vf(e))return e}catch{}return"dark"}function Bm(){if(!Ns)return"default";try{const e=localStorage.getItem(bf);if(e&&xf.includes(e))return e}catch{}return"default"}function Hm(e){if(Ns)try{localStorage.setItem(gf,e)}catch{}}function qm(e){if(Ns)try{localStorage.setItem(bf,e)}catch{}}function hR(e,n){return e==="system"?n?"dark":"light":e}function pR(e,n,s){if(!Ns)return;const i=hR(e,s);document.documentElement.setAttribute("data-theme",i),document.documentElement.setAttribute("data-color-theme",n)}function Vm(){if(!Ns)return;const e=uR(),n=document.getElementById(ac);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=ac,document.head.appendChild(s)}function Wm(){if(!Ns)return;const e=document.getElementById(ac);e&&e.remove()}function fR(){const[e,n]=a.useState(()=>Um()),[s,i]=a.useState(()=>Bm()),[r,o]=a.useState(!0),[l,c]=a.useState(()=>Ns?window.matchMedia("(prefers-color-scheme: dark)").matches:!0),u=a.useRef(e),d=a.useRef(s),m=a.useRef(!1),h=a.useRef(!1);a.useEffect(()=>{u.current=e},[e]),a.useEffect(()=>{d.current=s},[s]),a.useEffect(()=>{if(!Ns||!r)return;let f=!1;return ra().then(b=>{f||(vf(b.themeMode)&&!m.current&&(u.current!==b.themeMode&&(u.current=b.themeMode,n(b.themeMode)),Um()!==b.themeMode&&Hm(b.themeMode)),b.colorTheme&&xf.includes(b.colorTheme)&&!h.current&&(d.current!==b.colorTheme&&(d.current=b.colorTheme,i(b.colorTheme)),Bm()!==b.colorTheme&&qm(b.colorTheme)))}).catch(b=>{console.warn("[useTheme] Failed to hydrate theme from global settings",b)}).finally(()=>{f||o(!1)}),()=>{f=!0}},[r]),a.useEffect(()=>{if(!Ns)return;const f=window.matchMedia("(prefers-color-scheme: dark)"),b=v=>{c(v.matches)};return f.addEventListener("change",b),()=>f.removeEventListener("change",b)},[]),mR(()=>{pR(e,s,l)},[e,s,l]),a.useEffect(()=>{!Ns||r||(s!=="default"?Vm():Wm())},[s,r]);const g=a.useCallback(f=>{m.current=!0,u.current=f,n(f),Hm(f),nn({themeMode:f}).catch(b=>{console.warn("[useTheme] Failed to persist themeMode to global settings",b)})},[]),p=a.useCallback(f=>{h.current=!0,d.current=f,i(f),qm(f),f!=="default"?Vm():Wm(),nn({colorTheme:f}).catch(b=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",b)})},[]);return{themeMode:e,colorTheme:s,setThemeMode:g,setColorTheme:p,isSystemDark:l}}function gR(e){const{planningSessions:n}=e,[s,i]=a.useState(!1),[r,o]=a.useState(!1),[l,c]=a.useState(null),[u,d]=a.useState(void 0),[m,h]=a.useState(!1),[g,p]=a.useState(null),[f,b]=a.useState(void 0),[v,x]=a.useState(null),[k,M]=a.useState("definition"),[y,R]=a.useState(!1),[j,C]=a.useState(void 0),[S,P]=a.useState(!1),[T,_]=a.useState(!1),[L,G]=a.useState(!1),[$,I]=a.useState(!1),[w,q]=a.useState(void 0),[W,B]=a.useState(!1),[A,z]=a.useState("project"),[X,E]=a.useState(!1),[U,pe]=a.useState(!1),[ie,re]=a.useState(!1),[F,ce]=a.useState(!1),[ae,Q]=a.useState(!1),[de,Te]=a.useState(!1),[fe,Se]=a.useState(!1),te=!!(v||y||s||r||m||$||W||X||U||ie||ae||F||L||S||T||de||fe),we=a.useCallback(()=>i(!0),[]),Pe=a.useCallback(()=>i(!1),[]),We=a.useCallback(()=>o(!0),[]),Ke=a.useCallback(ut=>{c(ut),o(!0)},[]),Ne=a.useCallback(()=>{const ut=n[0];ut&&(d(ut.id),o(!0))},[n]),_e=a.useCallback(ut=>{d(ut),o(!0)},[]),Oe=a.useCallback(()=>{o(!1),c(null),d(void 0)},[]),ye=a.useCallback(ut=>{p(ut),h(!0)},[]),De=a.useCallback(ut=>{b(ut),h(!0)},[]),se=a.useCallback(()=>{h(!1),p(null),b(void 0)},[]),J=a.useCallback((ut,Me="definition")=>{x(ut),M(Me)},[]),me=a.useCallback(ut=>{x(ut),M("changes")},[]),ee=a.useCallback(ut=>{x(Me=>Me&&{...Me,...ut})},[]),he=a.useCallback(()=>{x(null)},[]),le=a.useCallback(ut=>{C(ut),R(!0)},[]),Ie=a.useCallback(()=>{R(!1),C(void 0)},[]),Ze=a.useCallback(()=>P(!0),[]),at=a.useCallback(()=>P(!1),[]),oe=a.useCallback(()=>_(!0),[]),Z=a.useCallback(()=>_(!1),[]),ue=a.useCallback(()=>G(!0),[]),Ce=a.useCallback(()=>G(!1),[]),$e=a.useCallback(()=>{I(ut=>!ut)},[]),ve=a.useCallback(()=>{I(!1),q(void 0)},[]),Ge=a.useCallback(()=>B(!0),[]),je=a.useCallback(()=>B(!1),[]),Ue=a.useCallback(ut=>{z(ut)},[]),He=a.useCallback(()=>E(!0),[]),ge=a.useCallback(()=>E(!1),[]),Fe=a.useCallback(()=>pe(!0),[]),be=a.useCallback(()=>pe(!1),[]),Je=a.useCallback(()=>re(!0),[]),st=a.useCallback(()=>re(!1),[]),dt=a.useCallback(()=>ce(!0),[]),Tt=a.useCallback(()=>ce(!1),[]),$t=a.useCallback(()=>Q(!0),[]),Dt=a.useCallback(()=>Q(!1),[]),Bt=a.useCallback(async(ut,Me)=>{Q(!1),q(Me),I(!0)},[]),qt=a.useCallback(()=>Te(!0),[]),Lt=a.useCallback(()=>Te(!1),[]),Ct=a.useCallback(()=>Se(!0),[]),xt=a.useCallback(()=>Se(!1),[]),Et=a.useCallback((ut,Me)=>{Me(`Created ${ut.id} from planning mode`,"success"),o(!1),c(null)},[]),Le=a.useCallback((ut,Me)=>{const Qe=ut.map(rt=>rt.id).join(", ");Me(`Created ${Qe} from planning mode`,"success"),o(!1),c(null)},[]),gt=a.useCallback((ut,Me)=>{const Qe=ut.map(rt=>rt.id).join(", ");Me(`Created ${Qe} from subtask breakdown`,"success"),h(!1),p(null)},[]);return{newTaskModalOpen:s,isPlanningOpen:r,planningInitialPlan:l,planningResumeSessionId:u,isSubtaskOpen:m,subtaskInitialDescription:g,subtaskResumeSessionId:f,detailTask:v,detailTaskInitialTab:k,settingsOpen:y,settingsInitialSection:j,schedulesOpen:S,githubImportOpen:T,usageOpen:L,terminalOpen:$,terminalInitialCommand:w,filesOpen:W,fileBrowserWorkspace:A,activityLogOpen:X,gitManagerOpen:U,workflowStepsOpen:ie,agentsOpen:F,scriptsOpen:ae,setupWizardOpen:de,modelOnboardingOpen:fe,anyModalOpen:te,openNewTask:we,closeNewTask:Pe,openPlanning:We,openPlanningWithInitialPlan:Ke,resumePlanning:Ne,openPlanningWithSession:_e,closePlanning:Oe,openSubtaskBreakdown:ye,openSubtaskWithSession:De,closeSubtask:se,openDetailTask:J,openDetailWithChangesTab:me,updateDetailTask:ee,closeDetailTask:he,openSettings:le,closeSettings:Ie,openSchedules:Ze,closeSchedules:at,openGitHubImport:oe,closeGitHubImport:Z,openUsage:ue,closeUsage:Ce,toggleTerminal:$e,closeTerminal:ve,openFiles:Ge,closeFiles:je,setFileWorkspace:Ue,openActivityLog:He,closeActivityLog:ge,openGitManager:Fe,closeGitManager:be,openWorkflowSteps:Je,closeWorkflowSteps:st,openAgents:dt,closeAgents:Tt,openScripts:$t,closeScripts:Dt,runScript:Bt,openSetupWizard:qt,closeSetupWizard:Lt,openModelOnboarding:Ct,closeModelOnboarding:xt,onPlanningTaskCreated:Et,onPlanningTasksCreated:Le,onSubtaskTasksCreated:gt}}function bR(e){const[n,s]=a.useState(2),[i,r]=a.useState("."),[o,l]=a.useState(!0),[c,u]=a.useState(!1),[d,m]=a.useState(!1),[h,g]=a.useState(void 0),[p,f]=a.useState(!1),[b,v]=a.useState(!1),[x,k]=a.useState({}),[M,y]=a.useState(!1),[R,j]=a.useState(!1),[C,S]=a.useState(!1),[P,T]=a.useState(!1),_=a.useCallback(async()=>{const[w,q]=await Promise.allSettled([Rx(e),ro(e)]);if(w.status==="fulfilled"&&(s(w.value.maxConcurrent),r(w.value.rootDir)),q.status==="fulfilled"){const W=q.value;l(!!W.autoMerge),u(!!W.globalPause),m(!!W.enginePaused),v(!!W.prAuthAvailable),g(W.taskStuckTimeoutMs),f(W.showQuickChatFAB===!0),k(W.experimentalFeatures??{});const B=W.experimentalFeatures??{};y(B.insights===!0),j(B.roadmap===!0),S(B.memoryView===!0),T(B.devServerView===!0||B.devServer===!0)}},[e]);a.useEffect(()=>{_()},[_]);const L=a.useCallback(async()=>{const w=!o;l(w);try{await dr({autoMerge:w},e)}catch{l(!w)}},[o,e]),G=a.useCallback(async()=>{const w=!c;u(w);try{await dr({globalPause:w,globalPauseReason:w?"manual":void 0},e)}catch{u(!w)}},[c,e]),$=a.useCallback(async()=>{const w=!d;m(w);try{await dr({enginePaused:w},e)}catch{m(!w)}},[d,e]),I=a.useCallback(async()=>{const w=!p;f(w);try{await dr({showQuickChatFAB:w},e)}catch{f(!w)}},[p,e]);return{maxConcurrent:n,rootDir:i,autoMerge:o,globalPaused:c,enginePaused:d,taskStuckTimeoutMs:h,showQuickChatFAB:p,prAuthAvailable:b,experimentalFeatures:x,insightsEnabled:M,roadmapEnabled:R,memoryEnabled:C,devServerEnabled:P,toggleAutoMerge:L,toggleGlobalPause:G,toggleEnginePause:$,toggleShowQuickChatFAB:I,refresh:_}}function xR(e){const{projectId:n,projects:s,projectsLoading:i,currentProject:r,setCurrentProject:o,addToast:l,openTaskDetail:c,closeTaskDetail:u}=e,d=a.useRef(!1),m=a.useRef(null);return a.useEffect(()=>{const g=new URLSearchParams(window.location.search),p=g.get("project"),f=g.get("task");if(!f||i)return;if(p){const v=s.find(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,Or(f,p??n).then(v=>{c(v),m.current=f}).catch(()=>{l(`Task ${f} not found`,"error")})},[n,s,i,r,o,l,c]),{handleDetailClose:a.useCallback(()=>{if(m.current){const g=new URLSearchParams(window.location.search);g.delete("task");const p=g.toString();window.history.replaceState(null,"",p?`${window.location.pathname}?${p}`:window.location.pathname),m.current=null}u()},[u])}}function vR(){const[e,n]=a.useState([]),[s,i]=a.useState([]),[r,o]=a.useState([]),l=a.useRef(s),c=a.useRef(r);a.useEffect(()=>{is().then(m=>{n(m.models),l.current=m.favoriteProviders,c.current=m.favoriteModels,i(m.favoriteProviders),o(m.favoriteModels)}).catch(()=>{})},[]),a.useEffect(()=>{l.current=s},[s]),a.useEffect(()=>{c.current=r},[r]);const u=a.useCallback(async m=>{const h=l.current,p=h.includes(m)?h.filter(f=>f!==m):[m,...h];l.current=p,i(()=>p);try{await nn({favoriteProviders:p,favoriteModels:c.current})}catch(f){throw l.current=h,i(()=>h),f}},[]),d=a.useCallback(async m=>{const h=c.current,p=h.includes(m)?h.filter(f=>f!==m):[m,...h];c.current=p,o(()=>p);try{await nn({favoriteProviders:l.current,favoriteModels:p})}catch(f){throw c.current=h,o(()=>h),f}},[]);return{availableModels:e,favoriteProviders:s,favoriteModels:r,toggleFavoriteProvider:u,toggleFavoriteModel:d}}function yR({projectId:e,openModelOnboarding:n,openSettings:s}){const i=a.useRef(!1);a.useEffect(()=>{if(i.current)return;i.current=!0;let r=!1,o=!1;Ba().then(({providers:l})=>{const c=l.some(d=>d.authenticated);if(l.length>0&&!c||l.length>0&&c)return ra().then(d=>{const m=!!(d.defaultProvider&&d.defaultModelId);(d.modelOnboardingComplete===!1||d.modelOnboardingComplete===void 0)&&(!c||!m)&&!sa()?r=!0:!c&&!sa()&&(o=!0)})}).then(()=>{r?(js("onboarding:auto-triggered",{trigger:"first-run"}),n()):o&&(js("onboarding:auto-triggered",{trigger:"missing-provider"}),s("authentication"))}).catch(()=>{})},[e,n,s])}const kR=["board","list","agents","missions","chat","documents","roadmaps","skills","mailbox","insights","memory","devserver","dev-server"];function Gm(e){return e!==null&&kR.includes(e)}function jR(e){return e==="devserver"?"dev-server":e}function wR(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"}),[g,p]=a.useState(()=>{const x=Nn("kb-dashboard-task-view");return Gm(x)?x:"board"}),f=a.useRef(!1);a.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",m)},[m]),a.useEffect(()=>{const x=Nn("kb-dashboard-task-view",r?.id);if(Gm(x)){const k=!f.current&&x==="devserver";p(k?"devserver":jR(x))}else p("board");r?.id&&(f.current=!0)},[r?.id]),a.useEffect(()=>{ts("kb-dashboard-task-view",g,r?.id)},[r?.id,g]),a.useEffect(()=>{n||i||r&&m==="overview"&&h("project")},[n,i,r,m]),a.useEffect(()=>{if(n||i||l||s||o>0||r)return;const 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"],k=x.indexOf(u),M=x[(k+1)%x.length];d(M)},[u,d]);return{viewMode:m,setViewMode:h,taskView:g,setTaskView:p,handleChangeTaskView:b,handleToggleTheme:v}}function NR(e){const{setCurrentProject:n,clearCurrentProject:s,setViewMode:i,currentProject:r,refreshProjects:o,toggleFavoriteProvider:l,toggleFavoriteModel:c,addToast:u,openSettings:d,openSetupWizard:m,closeSetupWizard:h,closeModelOnboarding:g}=e,p=a.useCallback(S=>{n(S),i("project")},[n,i]),f=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]),k=a.useCallback(()=>{g()},[g]),M=a.useCallback(async S=>{try{await My(S.id),u(`Project ${S.name} paused`,"success"),await o()}catch{u(`Failed to pause project ${S.name}`,"error")}},[u,o]),y=a.useCallback(async S=>{try{await _y(S.id),u(`Project ${S.name} resumed`,"success"),await o()}catch{u(`Failed to resume project ${S.name}`,"error")}},[u,o]),R=a.useCallback(async S=>{try{await kh(S.id),u(`Project ${S.name} removed`,"success"),r?.id===S.id&&(s(),i("overview")),await o()}catch{u(`Failed to remove project ${S.name}`,"error")}},[r,s,i,u,o]),j=a.useCallback(async S=>{try{await l(S)}catch{u("Failed to update favorites","error")}},[l,u]),C=a.useCallback(async S=>{try{await c(S)}catch{u("Failed to update model favorites","error")}},[c,u]);return{handleSelectProject:p,handleViewAllProjects:f,handleOpenSettings:b,handleAddProject:v,handleSetupComplete:x,handleModelOnboardingComplete:k,handlePauseProject:M,handleResumeProject:y,handleRemoveProject:R,handleToggleFavorite:j,handleToggleModelFavorite:C}}function SR(e){const{createTask:n,onPlanningTaskCreated:s,onPlanningTasksCreated:i,onSubtaskTasksCreated:r,addToast:o}=e,l=a.useCallback(async g=>n({...g,column:"triage"}),[n]),c=a.useCallback(async g=>await n({...g,column:"triage"}),[n]),u=a.useCallback(g=>{s(g,o)},[s,o]),d=a.useCallback(g=>{i(g,o)},[i,o]),m=a.useCallback(g=>{r(g,o)},[r,o]),h=a.useCallback(g=>{o(`Imported ${g.id} from GitHub`,"success")},[o]);return{handleBoardQuickCreate:l,handleModalCreate:c,handlePlanningTaskCreated:u,handlePlanningTasksCreated:d,handleSubtaskTasksCreated:m,handleGitHubImport:h}}async function CR(e){return lo("/health",{nodeId:e})}async function ER(e){return lo("/projects",{nodeId:e})}async function MR(e,n,s){const i=new URLSearchParams({projectId:n});return s&&s.trim()&&i.set("q",s.trim()),lo(`/tasks?${i.toString()}`,{nodeId:e})}async function _R(e,n){return lo(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:e})}async function dP(e){return D(`/nodes/${encodeURIComponent(e)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function uP(e){return D(`/nodes/${encodeURIComponent(e)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function mP(e){return D(`/nodes/${encodeURIComponent(e)}/settings/sync-status`)}async function hP(e){return D(`/nodes/${encodeURIComponent(e)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}function AR(e,n){const{projectId:s,searchQuery:i}=n??{},[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState(null),[m,h]=a.useState(!1),[g,p]=a.useState(null),f=a.useRef(null),b=a.useCallback(async()=>{if(!e){o([]),c([]),d(null),h(!1),p(null);return}f.current?.abort();const x=new AbortController;f.current=x,h(!0),p(null);try{const k=[CR(e),ER(e)];s&&(k.push(MR(e,s,i)),k.push(_R(e,s)));const M=await Promise.allSettled(k);if(x.signal.aborted)return;const y=M[0],R=M[1];if(y.status==="rejected"){p(`Failed to fetch node health: ${y.reason}`),h(!1);return}if(d(y.value),R.status==="rejected"){p(`Failed to fetch projects: ${R.reason}`),h(!1);return}if(o(R.value),s&&M[2]){const j=M[2];if(j.status==="rejected"){p(`Failed to fetch tasks: ${j.reason}`),h(!1);return}j.status==="fulfilled"&&c(j.value)}h(!1)}catch(k){x.signal.aborted||(p(k instanceof Error?k.message:"Unknown error"),h(!1))}},[e,s,i]);a.useEffect(()=>(b(),()=>{f.current?.abort()}),[b]);const v=a.useCallback(()=>{b()},[b]);return{projects:r,tasks:l,health:u,loading:m,error:g,refresh:v}}function TR(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 qs(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 RR="fusion-dashboard-current-node",yf=a.createContext(null);function IR({children:e}){const[n,s]=a.useState(null),[i,r]=a.useState(!0),o=a.useRef(!1),l=a.useRef(void 0);a.useEffect(()=>{let m=!1;async function h(){try{const g=await ra();if(m)return;l.current=g.dashboardCurrentNodeId;const p=g.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const f=localStorage.getItem(RR);if(f){const b=JSON.parse(f);b?.id&&b?.type==="remote"&&(l.current=b.id,await nn({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,nn({dashboardCurrentNodeId:m}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,nn({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,i]);const c=a.useCallback(m=>{s(m)},[]),u=a.useCallback(()=>{s(null),l.current=void 0,nn({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),d={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:u};return t.jsx(yf.Provider,{value:d,children:e})}function PR(){const e=a.useContext(yf);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}function $R({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&&(lx(l),window.location.reload())},[n]),o=a.useCallback(()=>{cx(),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 DR=a.lazy(()=>Zt(()=>import("./AgentsView-DpEpW88a.js").then(e=>e.A),__vite__mapDeps([16,1,17,8,18])).then(e=>({default:e.AgentsView}))),LR=a.lazy(()=>Zt(()=>import("./DocumentsView-Dx0M1YHw.js"),__vite__mapDeps([19,1,0,2,20])).then(e=>({default:e.DocumentsView}))),zR=a.lazy(()=>Zt(()=>import("./InsightsView-BtXdAo7D.js"),__vite__mapDeps([21,1,14,0,2,22])).then(e=>({default:e.InsightsView}))),FR=a.lazy(()=>Zt(()=>import("./NodesView-B_ZwUORz.js"),__vite__mapDeps([23,1,17,0,2,24])).then(e=>({default:e.NodesView}))),OR=a.lazy(()=>Zt(()=>import("./ChatView-BUt3C4cf.js"),__vite__mapDeps([25,1,0,2])).then(e=>({default:e.ChatView}))),UR=a.lazy(()=>Zt(()=>import("./RoadmapsView-DbUzBLeF.js"),__vite__mapDeps([26,1,0,2,27])).then(e=>({default:e.RoadmapsView}))),BR=a.lazy(()=>Zt(()=>import("./SkillsView-Dzzpd5Md.js"),__vite__mapDeps([28,1,0,2,29])).then(e=>({default:e.SkillsView}))),HR=a.lazy(()=>Zt(()=>import("./MemoryView-kKPuqmwf.js"),__vite__mapDeps([30,1,12,13,0,2,31])).then(e=>({default:e.MemoryView}))),qR=a.lazy(()=>Zt(()=>import("./DevServerView-BOyWtQJM.js"),__vite__mapDeps([32,1,0,2,33])).then(e=>({default:e.DevServerView})));function VR(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{Zt(()=>import("./AgentsView-DpEpW88a.js").then(n=>n.A),__vite__mapDeps([16,1,17,8,18])),Zt(()=>import("./DocumentsView-Dx0M1YHw.js"),__vite__mapDeps([19,1,0,2,20])),Zt(()=>import("./InsightsView-BtXdAo7D.js"),__vite__mapDeps([21,1,14,0,2,22])),Zt(()=>import("./NodesView-B_ZwUORz.js"),__vite__mapDeps([23,1,17,0,2,24])),Zt(()=>import("./ChatView-BUt3C4cf.js"),__vite__mapDeps([25,1,0,2])),Zt(()=>import("./RoadmapsView-DbUzBLeF.js"),__vite__mapDeps([26,1,0,2,27])),Zt(()=>import("./SkillsView-Dzzpd5Md.js"),__vite__mapDeps([28,1,0,2,29])),Zt(()=>import("./MemoryView-kKPuqmwf.js"),__vite__mapDeps([30,1,12,13,0,2,31])),Zt(()=>import("./DevServerView-BOyWtQJM.js"),__vite__mapDeps([32,1,0,2,33]))})}const El="kb-setup-warning-dismissed";function WR(){const{toasts:e,addToast:n,removeToast:s}=dR(),i=typeof window<"u"&&!!window.electronAPI;a.useEffect(()=>{VR()},[]);const{projects:r,loading:o,error:l,refresh:c}=nR(),{nodes:u}=aR(),{currentNode:d,currentNodeId:m,isRemote:h,setCurrentNode:g,clearCurrentNode:p}=PR(),{currentProject:f,setCurrentProject:b,clearCurrentProject:v,loading:x}=lR(r,{nodeId:m}),{hasAiProvider:k,hasGithub:M,loading:y,hasWarnings:R}=of(f?.id);a.useEffect(()=>{if(m&&!d&&u.length>0){const ct=u.find(ne=>ne.id===m);if(ct){g(ct);return}}m&&u.length>0&&(u.some(ne=>ne.id===m)||p())},[m,d,u,g,p]);const[j,C]=a.useState(""),S=AR(m,{projectId:f?.id,searchQuery:j||void 0});TR(m);const P=h&&S.projects.length>0?S.projects:r,{themeMode:T,colorTheme:_,setThemeMode:L,setColorTheme:G}=fR(),{sessions:$,generating:I,needsInput:w,planningSessions:q,dismissSession:W}=XT(f?.id),B=$.filter(ct=>ct.status==="awaiting_input"||ct.status==="error"),A=gR({projectId:f?.id,planningSessions:q}),{viewMode:z,setViewMode:X,taskView:E,handleChangeTaskView:U}=wR({projectsLoading:o,projectsError:l,currentProjectLoading:x,currentProject:f,projectsLength:r.length,setupWizardOpen:A.setupWizardOpen,openSetupWizard:A.openSetupWizard,themeMode:T,setThemeMode:L}),pe=a.useCallback(ct=>{ct==="missions"&&(ue(void 0),$e(void 0),Ge(void 0)),U(ct)},[U]),ie=E==="board"||E==="list",{tasks:re,createTask:F,moveTask:ce,pauseTask:ae,deleteTask:Q,mergeTask:de,retryTask:Te,updateTask:fe,duplicateTask:Se,archiveTask:te,unarchiveTask:we,archiveAllDone:Pe,loadArchivedTasks:We,lastFetchTimeMs:Ke}=ZT({...f?{projectId:f.id}:{},searchQuery:j||void 0,sseEnabled:ie}),[Ne,_e]=a.useState(!1),Oe=a.useRef(performance.now()),ye=a.useRef(!1),De=a.useRef(!1),se=a.useMemo(()=>o?"projects":x?"project":"tasks",[o,x]);a.useEffect(()=>{if(!o&&!ye.current){ye.current=!0;const ct=`projects loaded at ${Math.round(performance.now()-Oe.current)}ms from mount`;console.log(`[App] ${ct}`),Pa("[App]",ct)}if(!x&&!De.current){De.current=!0;const ct=`current-project resolved at ${Math.round(performance.now()-Oe.current)}ms from mount`;console.log(`[App] ${ct}`),Pa("[App]",ct)}},[o,x]),a.useEffect(()=>{if(Ne||o||x)return;const ct=performance.now(),ne=window.setTimeout(()=>{const Ee=`dashboard ready at ${Math.round(performance.now()-Oe.current)}ms from mount (settle delay=${Math.round(performance.now()-ct)}ms)`;console.log(`[App] ${Ee}`),Pa("[App]",Ee),_e(!0)},200);return()=>{window.clearTimeout(ne)}},[Ne,o,x]);const me=tr()==="mobile",[ee,he]=a.useState(0),le=a.useCallback(()=>{Ch(f?.id).then(ct=>{he(ct.unreadCount)}).catch(ct=>{console.warn("[App] Failed to fetch mailbox unread count:",ct)})},[f?.id]);a.useEffect(()=>{le();const ct=new URLSearchParams;f?.id&&ct.set("projectId",f.id);const ne=ct.size>0?`?${ct.toString()}`:"";return qs(`/api/events${ne}`,{events:{"message:sent":le,"message:received":le,"message:read":le,"message:deleted":le}})},[f?.id,le]);const[Ie,Ze]=a.useState(!1),[at,oe]=a.useState(!1),[Z,ue]=a.useState(void 0),[Ce,$e]=a.useState(void 0),[ve,Ge]=a.useState(void 0),[je,Ue]=a.useState(!1),[He,ge]=a.useState(!1),[Fe,be]=a.useState(()=>Nn(El,f?.id)==="true");a.useEffect(()=>{be(Nn(El,f?.id)==="true")},[f?.id]),a.useEffect(()=>{const ct=()=>{ge(!0)};return window.addEventListener(Dl,ct),()=>{window.removeEventListener(Dl,ct)}},[]);const Je=a.useCallback(()=>{ts(El,"true",f?.id),be(!0)},[f?.id]),{maxConcurrent:st,autoMerge:dt,globalPaused:Tt,enginePaused:$t,taskStuckTimeoutMs:Dt,showQuickChatFAB:Bt,prAuthAvailable:qt,experimentalFeatures:Lt,insightsEnabled:Ct,roadmapEnabled:xt,memoryEnabled:Et,devServerEnabled:Le,toggleAutoMerge:gt,toggleGlobalPause:ut,toggleEnginePause:Me,refresh:Qe}=bR(f?.id),rt=Lt.skillsView===!0,N=Lt.nodesView===!0,H=!0;a.useEffect(()=>{Object.keys(Lt).length!==0&&(E==="insights"&&!Ct&&U("board"),E==="roadmaps"&&!xt&&U("board"),E==="memory"&&!Et&&U("board"),(E==="devserver"||E==="dev-server")&&!Le&&U("board"))},[E,Ct,xt,Lt,U,H,Et,Le]),a.useEffect(()=>{Ie&&!N&&Ze(!1)},[Ie,N]);const{availableModels:Ae,favoriteProviders:ot,favoriteModels:kt,toggleFavoriteProvider:Ot,toggleFavoriteModel:sn}=vR();yR({projectId:f?.id,openModelOnboarding:A.openModelOnboarding,openSettings:A.openSettings});const{handleSelectProject:Rt,handleViewAllProjects:zn,handleOpenSettings:Wn,handleAddProject:ms,handleSetupComplete:pn,handleModelOnboardingComplete:Fn,handlePauseProject:Sn,handleResumeProject:fn,handleRemoveProject:Gn,handleToggleFavorite:dn,handleToggleModelFavorite:Mt}=NR({setCurrentProject:b,clearCurrentProject:v,setViewMode:X,currentProject:f,refreshProjects:c,toggleFavoriteProvider:Ot,toggleFavoriteModel:sn,addToast:n,openSettings:A.openSettings,openSetupWizard:A.openSetupWizard,closeSetupWizard:A.closeSetupWizard,closeModelOnboarding:A.closeModelOnboarding}),{handleDetailClose:yn}=xR({projectId:f?.id,projects:r,projectsLoading:o,currentProject:f,setCurrentProject:b,addToast:n,openTaskDetail:A.openDetailTask,closeTaskDetail:A.closeDetailTask}),{handleBoardQuickCreate:Kn,handleModalCreate:kn,handlePlanningTaskCreated:_n,handlePlanningTasksCreated:hs,handleSubtaskTasksCreated:ps,handleGitHubImport:On}=SR({createTask:F,onPlanningTaskCreated:A.onPlanningTaskCreated,onPlanningTasksCreated:A.onPlanningTasksCreated,onSubtaskTasksCreated:A.onSubtaskTasksCreated,addToast:n}),K=a.useCallback((ct,ne)=>{if(ne==="changes"){A.openDetailWithChangesTab(ct);return}A.openDetailTask(ct,ne)},[A]),ze=a.useCallback(()=>{N&&Ze(ct=>!ct)},[N]),tt=a.useCallback(()=>{A.setFileWorkspace("project"),A.openFiles()},[A]),et=a.useCallback(async()=>{oe(!0);try{await c()}finally{oe(!1)}},[c]),mt=a.useCallback(ct=>{$e(ct),ue(void 0),U("missions")},[U]),jt=a.useCallback(ct=>{ct.type==="planning"?A.openPlanningWithSession(ct.id):ct.type==="subtask"?A.openSubtaskWithSession(ct.id):ct.type==="mission_interview"?($e(void 0),ue(ct.id),Ge(void 0),U("missions")):(ct.type==="milestone_interview"||ct.type==="slice_interview")&&(ue(void 0),$e(void 0),Ge(ct.id),U("missions"))},[U,A]),_t=a.useCallback(()=>{for(const ct of B)W(ct.id)},[W,B]),gn=!o&&!x&&r.length===0&&!f&&!!l,fs=()=>gn?t.jsx(pT,{errorMessage:l??"Failed to fetch projects",isRetrying:at,onRetry:et}):Ie?t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(Xn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(FR,{addToast:n,onClose:()=>Ze(!1)})})})}):z==="overview"?t.jsx(Xn,{children:t.jsx(yw,{projects:r,loading:o,onSelectProject:Rt,onAddProject:ms,onPauseProject:Sn,onResumeProject:fn,onRemoveProject:Gn,nodes:u})}):E==="skills"?rt?t.jsx(Xn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(BR,{addToast:n,projectId:f?.id,onClose:()=>U("board")})})}):(U("board"),null):E==="chat"?t.jsx(Xn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(OR,{addToast:n,projectId:f?.id})})}):E==="mailbox"?t.jsx(Xn,{children:t.jsx(mN,{projectId:f?.id,addToast:n,onUnreadCountChange:he})}):E==="roadmaps"?t.jsx(Xn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(UR,{addToast:n,projectId:f?.id})})}):E==="missions"?t.jsx(Xn,{children:t.jsx(lN,{isInline:!0,isOpen:!0,onClose:()=>{$e(void 0),ue(void 0),Ge(void 0),U("board")},addToast:n,projectId:f?.id,onSelectTask:ct=>{const ne=re.find(Ee=>Ee.id===ct);ne&&A.openDetailTask(ne)},availableTasks:re.map(ct=>({id:ct.id,title:ct.title})),resumeSessionId:Z,targetMissionId:Ce,milestoneSliceResumeSessionId:ve,onMilestoneSliceResumeFetchError:()=>Ge(void 0)})}):E==="agents"&&H?t.jsx(Xn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(DR,{addToast:n,projectId:f?.id})})}):E==="documents"?t.jsx(Xn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(LR,{projectId:f?.id,addToast:n,onOpenDetail:A.openDetailTask})})}):E==="insights"?t.jsx(Xn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(zR,{projectId:f?.id,addToast:n,onClose:()=>U("board")})})}):E==="memory"?t.jsx(Xn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(HR,{addToast:n,projectId:f?.id})})}):E==="devserver"||E==="dev-server"?t.jsx(Xn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(qR,{addToast:n,projectId:f?.id})})}):E==="board"?t.jsx(Xn,{children:t.jsx(lw,{tasks:h&&S.tasks.length>0?S.tasks:re,projectId:f?.id,maxConcurrent:st,onMoveTask:ce,onPauseTask:ae,onOpenDetail:A.openDetailTask,addToast:n,onQuickCreate:Kn,onNewTask:A.openNewTask,onPlanningMode:A.openPlanningWithInitialPlan,onSubtaskBreakdown:A.openSubtaskBreakdown,autoMerge:dt,onToggleAutoMerge:gt,globalPaused:Tt,onUpdateTask:fe,onArchiveTask:te,onUnarchiveTask:we,onDeleteTask:Q,onArchiveAllDone:Pe,onLoadArchivedTasks:We,searchQuery:j,availableModels:Ae,onOpenDetailWithTab:K,favoriteProviders:ot,favoriteModels:kt,onToggleFavorite:dn,onToggleModelFavorite:Mt,taskStuckTimeoutMs:Dt,onOpenMission:mt,lastFetchTimeMs:Ke})}):t.jsx(Xn,{children:t.jsx(dw,{tasks:h&&S.tasks.length>0?S.tasks:re,projectId:f?.id,onMoveTask:ce,onOpenDetail:A.openDetailTask,addToast:n,globalPaused:Tt,onNewTask:A.openNewTask,onQuickCreate:Kn,onPlanningMode:A.openPlanningWithInitialPlan,onSubtaskBreakdown:A.openSubtaskBreakdown,availableModels:Ae,favoriteProviders:ot,favoriteModels:kt,onToggleFavorite:dn,onToggleModelFavorite:Mt,taskStuckTimeoutMs:Dt,searchQuery:j,lastFetchTimeMs:Ke})});if(!Ne)return t.jsxs(t.Fragment,{children:[t.jsx(gT,{stage:se}),t.jsx(hf,{toasts:e,onRemove:s})]});const Qt=!A.modelOnboardingOpen&&FA(),vt=!A.modelOnboardingOpen&&!Qt&&sa()&&!cf();return t.jsxs(t.Fragment,{children:[t.jsx(Jk,{isElectron:i,onOpenSettings:Wn,onOpenGitHubImport:A.openGitHubImport,onOpenPlanning:A.openPlanning,onResumePlanning:A.resumePlanning,activePlanningSessionCount:q.length,onOpenUsage:A.openUsage,onOpenActivityLog:A.openActivityLog,onOpenMailbox:()=>pe("mailbox"),mailboxUnreadCount:ee,onOpenSchedules:A.openSchedules,onOpenGitManager:A.openGitManager,onOpenNodes:ze,showNodesButton:N,onOpenWorkflowSteps:A.openWorkflowSteps,onOpenScripts:A.openScripts,onRunScript:A.runScript,onToggleTerminal:A.toggleTerminal,onOpenFiles:A.openFiles,filesOpen:A.filesOpen,globalPaused:Tt,enginePaused:$t,onToggleGlobalPause:ut,onToggleEnginePause:Me,view:E,onChangeView:z==="project"&&f?pe:void 0,showSkillsTab:rt,showAgentsTab:H,searchQuery:j,onSearchChange:C,projects:P,currentProject:f,onSelectProject:Rt,onViewAllProjects:zn,projectId:f?.id,mobileNavEnabled:me,availableNodes:u,currentNode:d,onSelectNode:ct=>{ct===null?p():g(ct)},isRemote:h,experimentalFeatures:{insights:Ct,roadmap:xt,memoryView:Et,devServer:Le,devServerView:Le}}),z==="project"&&f&&!Ie&&E!=="missions"&&!A.isPlanningOpen&&t.jsx(_T,{sessions:B,onResumeSession:jt,onDismissSession:W,onDismissAll:_t}),z==="project"&&f&&Qt&&t.jsx(AT,{onResume:A.openModelOnboarding}),z==="project"&&f&&vt&&t.jsx(TT,{onOpenModelOnboarding:A.openModelOnboarding,onOpenSettings:ct=>A.openSettings(ct)}),z==="project"&&f&&!y&&R&&!Fe&&t.jsx(lf,{hasAiProvider:k,hasGithub:M,onDismiss:Je}),t.jsx("div",{className:`project-content${z==="project"&&f?" project-content--with-footer":""}${me?" project-content--with-mobile-nav":""}`,children:fs()}),z==="project"&&f&&!Ie&&t.jsx(CT,{tasks:h&&S.tasks.length>0?S.tasks:re,projectId:f.id,taskStuckTimeoutMs:Dt,backgroundSessions:$,backgroundGenerating:I,backgroundNeedsInput:w,onOpenBackgroundSession:jt,onDismissBackgroundSession:W,lastFetchTimeMs:Ke,currentProjectPath:f.path,onOpenProjectDirectory:tt}),t.jsx(IT,{view:E,onChangeView:z==="project"&&f?pe:()=>{},footerVisible:z==="project"&&!!f,modalOpen:A.anyModalOpen,onOpenSettings:Wn,onOpenActivityLog:A.openActivityLog,onOpenMailbox:()=>pe("mailbox"),mailboxUnreadCount:ee,onOpenGitManager:A.openGitManager,onOpenWorkflowSteps:A.openWorkflowSteps,onOpenSchedules:A.openSchedules,onOpenScripts:A.openScripts,onToggleTerminal:A.toggleTerminal,onOpenFiles:A.openFiles,onOpenGitHubImport:A.openGitHubImport,onOpenPlanning:A.openPlanning,onResumePlanning:A.resumePlanning,activePlanningSessionCount:q.length,onOpenUsage:A.openUsage,onViewAllProjects:zn,onRunScript:A.runScript,projectId:f?.id,showSkillsTab:rt,experimentalFeatures:{insights:Ct,roadmap:xt,memoryView:Et,devServer:Le,devServerView:Le}}),z==="project"&&f&&E!=="chat"&&E!=="mailbox"&&E!=="insights"&&E!=="devserver"&&E!=="dev-server"&&t.jsx(QT,{projectId:f.id,addToast:n,showFAB:Bt,open:je,onOpenChange:Ue,favoriteProviders:ot,favoriteModels:kt,onToggleFavorite:dn,onToggleModelFavorite:Mt}),t.jsx(hT,{projectId:f?.id,tasks:re,projects:r,currentProject:f,addToast:n,toasts:e,removeToast:s,modalManager:A,projectActions:{handleAddProject:ms,handleSetupComplete:pn,handleModelOnboardingComplete:Fn},taskHandlers:{handleModalCreate:kn,handlePlanningTaskCreated:_n,handlePlanningTasksCreated:hs,handleSubtaskTasksCreated:ps,handleGitHubImport:On},taskOperations:{moveTask:ce,deleteTask:Q,mergeTask:de,retryTask:Te,duplicateTask:Se},deepLink:{handleDetailClose:yn},settings:{prAuthAvailable:qt,themeMode:T,colorTheme:_,setThemeMode:L,setColorTheme:G},onSettingsClose:()=>{A.closeSettings(),Qe()},onReopenOnboarding:()=>{A.closeSettings(),A.openModelOnboarding()}}),t.jsx($R,{open:He})]})}function GR(){return t.jsx(cR,{children:t.jsx(IR,{children:t.jsx(WR,{})})})}gx();tx();Sf.createRoot(document.getElementById("root")).render(t.jsx(a.StrictMode,{children:t.jsx(nx,{children:t.jsx(GR,{})})}));"serviceWorker"in navigator&&navigator.serviceWorker.register("/sw.js").then(e=>{console.log("SW registered:",e.scope)}).catch(e=>{console.log("SW registration failed:",e)});export{A4 as $,Ss as A,an as B,tn as C,en as D,rn as E,Ni as F,to as G,jl as H,Ht as I,Fs as J,zt as K,it as L,_A as M,xy as N,jA as O,Mn as P,wA as Q,hn as R,Bi as S,lc as T,vy as U,yy as V,Y4 as W,Pt as X,_4 as Y,vn as Z,Zt as _,ts as a,MI as a$,Or as a0,Mv as a1,$r as a2,Vi as a3,ia as a4,Qs as a5,Xs as a6,Ys as a7,eP as a8,sP as a9,XI as aA,ZI as aB,Uk as aC,Bk as aD,OT as aE,tr as aF,rc as aG,PT as aH,zT as aI,ls as aJ,vi as aK,li as aL,Jb as aM,hI as aN,fI as aO,pI as aP,gI as aQ,bI as aR,xI as aS,vI as aT,yI as aU,kI as aV,jI as aW,wI as aX,NI as aY,SI as aZ,CI as a_,nP as aa,tP as ab,iP as ac,Dn as ad,ss as ae,Bb as af,Us as ag,xg as ah,Zr as ai,ji as aj,mP as ak,dP as al,uP as am,hP as an,Lr as ao,Pb as ap,Oa as aq,hg as ar,Hn as as,lh as at,aR as au,nR as av,QI as aw,yd as ax,Ha as ay,Ok as az,aI as b,cI as b$,_I as b0,EI as b1,xn as b2,oc as b3,wi as b4,JI as b5,KI as b6,YI as b7,d4 as b8,c4 as b9,Wv as bA,T4 as bB,aa as bC,io as bD,rh as bE,Ki as bF,Cy as bG,lx as bH,cx as bI,Of as bJ,n_ as bK,k4 as bL,uI as bM,YR as bN,Ba as bO,rI as bP,QR as bQ,ZR as bR,tv as bS,Wx as bT,Hs as bU,Gx as bV,Kx as bW,Jx as bX,N4 as bY,oI as bZ,lI as b_,l4 as ba,u4 as bb,v4 as bc,y4 as bd,g4 as be,h4 as bf,p4 as bg,f4 as bh,m4 as bi,o4 as bj,b4 as bk,g_ as bl,P4 as bm,I4 as bn,O4 as bo,R4 as bp,$4 as bq,D4 as br,L4 as bs,z4 as bt,Yv as bu,F4 as bv,dc as bw,Gv as bx,Kv as by,Jv as bz,Ve as c,w4 as c$,aP as c0,rP as c1,mI as c2,XR as c3,jn as c4,p_ as c5,TA as c6,_m as c7,co as c8,e4 as c9,eI as cA,th as cB,V4 as cC,q4 as cD,kA as cE,Q4 as cF,Ka as cG,zE as cH,B4 as cI,U4 as cJ,_v as cK,H4 as cL,W4 as cM,zI as cN,FI as cO,Eb as cP,Il as cQ,VI as cR,WI as cS,BI as cT,UI as cU,HI as cV,OI as cW,qI as cX,dI as cY,S4 as cZ,j4 as c_,t4 as ca,n4 as cb,s4 as cc,i4 as cd,a4 as ce,r4 as cf,im as cg,oP as ch,lP as ci,x4 as cj,AI as ck,RI as cl,$I as cm,II as cn,TI as co,PI as cp,DI as cq,yh as cr,td as cs,Kg as ct,LI as cu,X4 as cv,G4 as cw,J4 as cx,K4 as cy,tI as cz,sI as d,E4 as d0,M4 as d1,C4 as d2,iI as e,GI as f,Nn as g,is as h,oa as i,wn as j,by as k,nI as l,LT as m,ro as n,dr as o,xe as p,nj as q,Z4 as r,qs as s,Tl as t,nn as u,Os as v,Vt as w,Dr as x,NA as y,cP as z};
|