@runfusion/fusion 0.10.0 → 0.11.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 +5586 -4785
- package/dist/client/assets/AgentDetailView-B5tq9ius.css +1 -0
- package/dist/client/assets/AgentDetailView-DQBjJSPJ.js +18 -0
- package/dist/client/assets/AgentsView-DlA0yHBg.js +522 -0
- package/dist/client/assets/AgentsView-xm_3NO4M.css +1 -0
- package/dist/client/assets/{ChatView-Bra9fNAG.js → ChatView-DK5CmiAk.js} +1 -1
- package/dist/client/assets/{DevServerView-UkgjEw9-.js → DevServerView-BVixhlF0.js} +1 -1
- package/dist/client/assets/{DirectoryPicker-Cls4HWxP.js → DirectoryPicker-tvBgHxa7.js} +1 -1
- package/dist/client/assets/{DocumentsView-BRBUPFVA.js → DocumentsView-DVw_wT6V.js} +1 -1
- package/dist/client/assets/{InsightsView-BRDqHCLb.js → InsightsView-G3MZhwSx.js} +2 -2
- package/dist/client/assets/{MemoryView-DvTrwFnQ.js → MemoryView-Bl9gx2Dw.js} +2 -2
- package/dist/client/assets/{NodesView-C4Ffl_o0.js → NodesView-dwVhD4V2.js} +4 -4
- package/dist/client/assets/{PiExtensionsManager-CeI1syeZ.js → PiExtensionsManager-CEHp6_Mj.js} +3 -3
- package/dist/client/assets/PluginManager-Dx0mcwat.js +1 -0
- package/dist/client/assets/ResearchView-BvlLYC_1.js +1 -0
- package/dist/client/assets/{RoadmapsView-DNb4x75S.js → RoadmapsView-DdYXssP2.js} +2 -2
- package/dist/client/assets/SettingsModal-Bgjg_4CD.js +31 -0
- package/dist/client/assets/{SettingsModal-CRMr4tL6.js → SettingsModal-CGWipm3s.js} +1 -1
- package/dist/client/assets/{SettingsModal-CDPDmHhd.css → SettingsModal-CriZP5Lp.css} +1 -1
- package/dist/client/assets/{SetupWizardModal-tF8B_aG_.js → SetupWizardModal-CKsJduYM.js} +1 -1
- package/dist/client/assets/{SkillsView-uyl47gSf.js → SkillsView-C4Tz7CxC.js} +1 -1
- package/dist/client/assets/{TodoView-CbzDtV53.js → TodoView-ByXJ90yL.js} +2 -2
- package/dist/client/assets/{folder-open-DPpmGJ-v.js → folder-open-CxOUgHDf.js} +1 -1
- package/dist/client/assets/index-BCz4ye4p.css +1 -0
- package/dist/client/assets/index-D7gT6mCr.js +656 -0
- package/dist/client/assets/{list-checks-D62pw1I8.js → list-checks--sf9u9ox.js} +1 -1
- package/dist/client/assets/{star-B8EbxNgI.js → star-CF1f2iPu.js} +1 -1
- package/dist/client/assets/{upload-CpnLno9z.js → upload-rOBd4OhB.js} +1 -1
- package/dist/client/assets/{users-B_C_0qzA.js → users-De-vFat1.js} +1 -1
- package/dist/client/fonts/SymbolsNerdFontMono-Regular.ttf +0 -0
- package/dist/client/index.html +16 -2
- package/dist/client/version.json +1 -1
- package/dist/extension.js +20410 -19703
- package/dist/pi-claude-cli/package.json +1 -1
- package/package.json +1 -1
- package/skill/fusion/SKILL.md +2 -0
- package/skill/fusion/references/engine-tools.md +4 -0
- package/skill/fusion/references/extension-tools.md +76 -0
- package/skill/fusion/references/fusion-capabilities.md +8 -0
- package/dist/client/assets/AgentDetailView-BtpZ4jxh.js +0 -18
- package/dist/client/assets/AgentDetailView-DIBOY8V-.css +0 -1
- package/dist/client/assets/AgentsView-Dxdtt0Bm.js +0 -522
- package/dist/client/assets/AgentsView-MotzGhZJ.css +0 -1
- package/dist/client/assets/PluginManager-BgeoYhLk.js +0 -1
- package/dist/client/assets/ResearchView-fmEOm4A2.js +0 -1
- package/dist/client/assets/SettingsModal-D1xq0WZm.js +0 -31
- package/dist/client/assets/index-BqK6TvSa.css +0 -1
- package/dist/client/assets/index-DyXZm9QN.js +0 -656
|
@@ -1,656 +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-tF8B_aG_.js","assets/DirectoryPicker-Cls4HWxP.js","assets/folder-open-DPpmGJ-v.js","assets/DirectoryPicker-DzKVmxOf.css","assets/SetupWizardModal-DRF5fOoR.css","assets/SettingsModal-D1xq0WZm.js","assets/SettingsModal-CRMr4tL6.js","assets/SettingsModal-CDPDmHhd.css","assets/users-B_C_0qzA.js","assets/star-B8EbxNgI.js","assets/SettingsModal-9HS8MnmW.css","assets/AgentsView-Dxdtt0Bm.js","assets/upload-CpnLno9z.js","assets/AgentsView-MotzGhZJ.css","assets/DocumentsView-BRBUPFVA.js","assets/DocumentsView-BrhyOdeE.css","assets/InsightsView-BRDqHCLb.js","assets/InsightsView-4KiUKzbz.css","assets/ResearchView-fmEOm4A2.js","assets/ResearchView-BVJFgfat.css","assets/NodesView-C4Ffl_o0.js","assets/NodesView-DCoS6iYh.css","assets/ChatView-Bra9fNAG.js","assets/RoadmapsView-DNb4x75S.js","assets/RoadmapsView-BOYnyMCh.css","assets/SkillsView-uyl47gSf.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-DvTrwFnQ.js","assets/MemoryView-DiajLXby.css","assets/DevServerView-UkgjEw9-.js","assets/DevServerView-DlZpuAnj.css","assets/TodoView-CbzDtV53.js","assets/list-checks-D62pw1I8.js","assets/TodoView-C1g65hJo.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as a,j as t,R as vo,a as ca,g as Kh,c as Rg}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 Gh=(...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 Tg=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 Pg=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 zd=e=>{const n=Pg(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 hl={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 Ig=e=>{for(const n in e)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},$g=a.createContext({}),Dg=()=>a.useContext($g),Lg=a.forwardRef(({color:e,size:n,strokeWidth:s,absoluteStrokeWidth:i,className:r="",children:o,iconNode:l,...c},u)=>{const{size:d=24,strokeWidth:m=2,absoluteStrokeWidth:h=!1,color:f="currentColor",className:p=""}=Dg()??{},g=i??h?Number(s??m)*24/Number(n??d):s??m;return a.createElement("svg",{ref:u,...hl,width:n??d??hl.width,height:n??d??hl.height,stroke:e??f,strokeWidth:g,className:Gh("lucide",p,r),...!o&&!Ig(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 He=(e,n)=>{const s=a.forwardRef(({className:i,...r},o)=>a.createElement(Lg,{ref:o,iconNode:n,className:Gh(`lucide-${Tg(zd(e))}`,`lucide-${e}`,i),...r}));return s.displayName=zd(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 zg=[["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"}]],Is=He("activity",zg);/**
|
|
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 Fg=[["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"}]],zo=He("archive",Fg);/**
|
|
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 Og=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],jr=He("arrow-down",Og);/**
|
|
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 Ug=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],Sa=He("arrow-left",Ug);/**
|
|
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 Bg=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],kr=He("arrow-right",Bg);/**
|
|
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 Hg=[["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"}]],Jh=He("arrow-up-down",Hg);/**
|
|
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 qg=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],zi=He("arrow-up",qg);/**
|
|
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 Vg=[["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"}]],Wg=He("book-open",Vg);/**
|
|
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 Kg=[["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"}]],Nn=He("bot",Kg);/**
|
|
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 Gg=[["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"}]],jc=He("box",Gg);/**
|
|
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 Jg=[["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"}]],yo=He("brain",Jg);/**
|
|
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 Yg=[["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"}]],Yh=He("calendar",Yg);/**
|
|
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 Qg=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],Xg=He("check-check",Qg);/**
|
|
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 Zg=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Hn=He("check",Zg);/**
|
|
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 eb=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Xt=He("chevron-down",eb);/**
|
|
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 tb=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],Fo=He("chevron-left",tb);/**
|
|
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 nb=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],vn=He("chevron-right",nb);/**
|
|
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 sb=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],pi=He("chevron-up",sb);/**
|
|
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 ib=[["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"}]],us=He("circle-alert",ib);/**
|
|
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 ab=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],yn=He("circle-check-big",ab);/**
|
|
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 rb=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],Oo=He("circle-dot",rb);/**
|
|
143
|
-
* @license lucide-react v1.7.0 - ISC
|
|
144
|
-
*
|
|
145
|
-
* This source code is licensed under the ISC license.
|
|
146
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
147
|
-
*/const ob=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["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"}]],kc=He("circle-question-mark",ob);/**
|
|
148
|
-
* @license lucide-react v1.7.0 - ISC
|
|
149
|
-
*
|
|
150
|
-
* This source code is licensed under the ISC license.
|
|
151
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
152
|
-
*/const lb=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],cb=He("circle-stop",lb);/**
|
|
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 db=[["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"}]],wr=He("circle-x",db);/**
|
|
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 ub=[["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"}]],mb=He("clipboard-list",ub);/**
|
|
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 hb=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],Si=He("clock",hb);/**
|
|
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 pb=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Qh=He("code",pb);/**
|
|
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 fb=[["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"}]],gb=He("columns-3",fb);/**
|
|
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 bb=[["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"}]],Oi=He("copy",bb);/**
|
|
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 xb=[["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"}]],vb=He("cpu",xb);/**
|
|
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 yb=[["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"}]],jb=He("download",yb);/**
|
|
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 kb=[["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"}]],wb=He("ellipsis-vertical",kb);/**
|
|
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 Nb=[["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"}]],wc=He("ellipsis",Nb);/**
|
|
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 Sb=[["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"}]],Cb=He("external-link",Sb);/**
|
|
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 Eb=[["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"}]],sd=He("eye-off",Eb);/**
|
|
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 _b=[["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"}]],Ca=He("eye",_b);/**
|
|
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 Mb=[["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"}]],Bs=He("file-code",Mb);/**
|
|
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 Ab=[["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"}]],Nc=He("file-diff",Ab);/**
|
|
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 Rb=[["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"}]],Tb=He("file-minus",Rb);/**
|
|
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 Pb=[["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"}]],Xh=He("file-pen",Pb);/**
|
|
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 Ib=[["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"}]],$b=He("file-plus",Ib);/**
|
|
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 Db=[["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"}]],Lb=He("file-question-mark",Db);/**
|
|
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 zb=[["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"}]],Ui=He("file-text",zb);/**
|
|
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 Fb=[["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"}]],Ob=He("file-type",Fb);/**
|
|
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 Ub=[["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"}]],Zh=He("file",Ub);/**
|
|
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 Bb=[["path",{d:"M18 19a5 5 0 0 1-5-5v8",key:"sz5oeg"}],["path",{d:"M9 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v5",key:"1w6njk"}],["circle",{cx:"13",cy:"12",r:"2",key:"1j92g6"}],["circle",{cx:"20",cy:"19",r:"2",key:"1obnsp"}]],Sc=He("folder-git-2",Bb);/**
|
|
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 Hb=[["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"}]],Fd=He("folder-root",Hb);/**
|
|
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 qb=[["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=He("folder",qb);/**
|
|
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 Vb=[["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"}]],jo=He("funnel",Vb);/**
|
|
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 Wb=[["path",{d:"M15 6a9 9 0 0 0-9 9V3",key:"1cii5b"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}]],Vs=He("git-branch",Wb);/**
|
|
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 Kb=[["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"}]],Nr=He("git-commit-horizontal",Kb);/**
|
|
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 Gb=[["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"}]],ep=He("git-merge",Gb);/**
|
|
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 Jb=[["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"}]],ks=He("git-pull-request",Jb);/**
|
|
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 Yb=[["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"}]],Uo=He("globe",Yb);/**
|
|
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 Qb=[["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"}]],tp=He("grid-3x3",Qb);/**
|
|
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 Xb=[["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"}]],id=He("grip-vertical",Xb);/**
|
|
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 Zb=[["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"}]],ex=He("hard-drive",Zb);/**
|
|
323
|
-
* @license lucide-react v1.7.0 - ISC
|
|
324
|
-
*
|
|
325
|
-
* This source code is licensed under the ISC license.
|
|
326
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
327
|
-
*/const tx=[["path",{d:"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"}]],nx=He("heart",tx);/**
|
|
328
|
-
* @license lucide-react v1.7.0 - ISC
|
|
329
|
-
*
|
|
330
|
-
* This source code is licensed under the ISC license.
|
|
331
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
332
|
-
*/const sx=[["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"}]],ur=He("history",sx);/**
|
|
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 ix=[["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"}]],nr=He("inbox",ix);/**
|
|
338
|
-
* @license lucide-react v1.7.0 - ISC
|
|
339
|
-
*
|
|
340
|
-
* This source code is licensed under the ISC license.
|
|
341
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
342
|
-
*/const ax=[["path",{d:"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"}]],np=He("key",ax);/**
|
|
343
|
-
* @license lucide-react v1.7.0 - ISC
|
|
344
|
-
*
|
|
345
|
-
* This source code is licensed under the ISC license.
|
|
346
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
347
|
-
*/const rx=[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]],ox=He("keyboard",rx);/**
|
|
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 lx=[["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"}]],Bi=He("layers",lx);/**
|
|
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 cx=[["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"}]],Hi=He("layout-grid",cx);/**
|
|
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 dx=[["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"}]],si=He("lightbulb",dx);/**
|
|
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 ux=[["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"}]],ha=He("link",ux);/**
|
|
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 mx=[["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"}]],hx=He("list-plus",mx);/**
|
|
373
|
-
* @license lucide-react v1.7.0 - ISC
|
|
374
|
-
*
|
|
375
|
-
* This source code is licensed under the ISC license.
|
|
376
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
377
|
-
*/const px=[["path",{d:"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"}]],Bo=He("list-tree",px);/**
|
|
378
|
-
* @license lucide-react v1.7.0 - ISC
|
|
379
|
-
*
|
|
380
|
-
* This source code is licensed under the ISC license.
|
|
381
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
382
|
-
*/const fx=[["path",{d:"M3 5h.01",key:"18ugdj"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 19h.01",key:"noohij"}],["path",{d:"M8 5h13",key:"1pao27"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 19h13",key:"m83p4d"}]],Cc=He("list",fx);/**
|
|
383
|
-
* @license lucide-react v1.7.0 - ISC
|
|
384
|
-
*
|
|
385
|
-
* This source code is licensed under the ISC license.
|
|
386
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
387
|
-
*/const gx=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],ot=He("loader-circle",gx);/**
|
|
388
|
-
* @license lucide-react v1.7.0 - ISC
|
|
389
|
-
*
|
|
390
|
-
* This source code is licensed under the ISC license.
|
|
391
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
392
|
-
*/const bx=[["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"}]],Ho=He("lock",bx);/**
|
|
393
|
-
* @license lucide-react v1.7.0 - ISC
|
|
394
|
-
*
|
|
395
|
-
* This source code is licensed under the ISC license.
|
|
396
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
397
|
-
*/const xx=[["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"}]],pa=He("mail",xx);/**
|
|
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 vx=[["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"}]],Ec=He("map",vx);/**
|
|
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 yx=[["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"}]],qo=He("maximize-2",yx);/**
|
|
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 jx=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}],["path",{d:"M12 8v6",key:"1ib9pf"}],["path",{d:"M9 11h6",key:"1fldmi"}]],kx=He("message-square-plus",jx);/**
|
|
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 wx=[["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"}]],wi=He("message-square",wx);/**
|
|
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 Nx=[["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"}]],Sr=He("minimize-2",Nx);/**
|
|
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 Sx=[["path",{d:"M5 12h14",key:"1ays0h"}]],Cx=He("minus",Sx);/**
|
|
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 Ex=[["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"}]],mr=He("monitor",Ex);/**
|
|
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 _x=[["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"}]],Mx=He("move",_x);/**
|
|
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 Ax=[["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"}]],_c=He("package",Ax);/**
|
|
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 Rx=[["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"}]],sp=He("paperclip",Rx);/**
|
|
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 Tx=[["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"}]],Hs=He("pause",Tx);/**
|
|
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 Px=[["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"}]],cs=He("pencil",Px);/**
|
|
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 Ix=[["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"}]],Sn=He("play",Ix);/**
|
|
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 $x=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],on=He("plus",$x);/**
|
|
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 Dx=[["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"}]],ip=He("radio",Dx);/**
|
|
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 Lx=[["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"}]],$n=He("refresh-cw",Lx);/**
|
|
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 zx=[["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"}]],Od=He("rocket",zx);/**
|
|
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 Fx=[["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"}]],Ox=He("rotate-ccw",Fx);/**
|
|
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 Ux=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]],Bx=He("rotate-cw",Ux);/**
|
|
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 Hx=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],ap=He("save",Hx);/**
|
|
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 qx=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],ki=He("search",qx);/**
|
|
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 Vx=[["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"}]],Li=He("send",Vx);/**
|
|
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 Wx=[["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"}]],hr=He("server",Wx);/**
|
|
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 Kx=[["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"}]],rr=He("settings",Kx);/**
|
|
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 Gx=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]],Jx=He("shield-alert",Gx);/**
|
|
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 Yx=[["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"}]],Qx=He("shield",Yx);/**
|
|
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 Xx=[["path",{d:"m12.5 17-.5-1-.5 1h1z",key:"3me087"}],["path",{d:"M15 22a1 1 0 0 0 1-1v-1a2 2 0 0 0 1.56-3.25 8 8 0 1 0-11.12 0A2 2 0 0 0 8 20v1a1 1 0 0 0 1 1z",key:"1o5pge"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}]],Zx=He("skull",Xx);/**
|
|
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 ev=[["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"}]],rs=He("sparkles",ev);/**
|
|
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 tv=[["path",{d:"M21 10.656V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h12.344",key:"2acyp4"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],rp=He("square-check-big",tv);/**
|
|
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 nv=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],js=He("square",nv);/**
|
|
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 sv=[["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"}]],xs=He("target",sv);/**
|
|
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 iv=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],mi=He("terminal",iv);/**
|
|
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 av=[["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"}]],ko=He("text-wrap",av);/**
|
|
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 rv=[["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"}]],rn=He("trash-2",rv);/**
|
|
568
|
-
* @license lucide-react v1.7.0 - ISC
|
|
569
|
-
*
|
|
570
|
-
* This source code is licensed under the ISC license.
|
|
571
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
572
|
-
*/const ov=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],lv=He("trending-up",ov);/**
|
|
573
|
-
* @license lucide-react v1.7.0 - ISC
|
|
574
|
-
*
|
|
575
|
-
* This source code is licensed under the ISC license.
|
|
576
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
577
|
-
*/const cv=[["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"}]],ad=He("triangle-alert",cv);/**
|
|
578
|
-
* @license lucide-react v1.7.0 - ISC
|
|
579
|
-
*
|
|
580
|
-
* This source code is licensed under the ISC license.
|
|
581
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
582
|
-
*/const dv=[["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"}]],Ud=He("unlink",dv);/**
|
|
583
|
-
* @license lucide-react v1.7.0 - ISC
|
|
584
|
-
*
|
|
585
|
-
* This source code is licensed under the ISC license.
|
|
586
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
587
|
-
*/const uv=[["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"}]],ea=He("user",uv);/**
|
|
588
|
-
* @license lucide-react v1.7.0 - ISC
|
|
589
|
-
*
|
|
590
|
-
* This source code is licensed under the ISC license.
|
|
591
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
592
|
-
*/const mv=[["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"}]],op=He("webhook",mv);/**
|
|
593
|
-
* @license lucide-react v1.7.0 - ISC
|
|
594
|
-
*
|
|
595
|
-
* This source code is licensed under the ISC license.
|
|
596
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
597
|
-
*/const hv=[["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"}]],Mc=He("workflow",hv);/**
|
|
598
|
-
* @license lucide-react v1.7.0 - ISC
|
|
599
|
-
*
|
|
600
|
-
* This source code is licensed under the ISC license.
|
|
601
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
602
|
-
*/const pv=[["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"}]],Bd=He("wrench",pv);/**
|
|
603
|
-
* @license lucide-react v1.7.0 - ISC
|
|
604
|
-
*
|
|
605
|
-
* This source code is licensed under the ISC license.
|
|
606
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
607
|
-
*/const fv=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Wt=He("x",fv);/**
|
|
608
|
-
* @license lucide-react v1.7.0 - ISC
|
|
609
|
-
*
|
|
610
|
-
* This source code is licensed under the ISC license.
|
|
611
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
612
|
-
*/const gv=[["path",{d:"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"}]],Gn=He("zap",gv),Ac="fusion:version-reload",Rc="fusion:version-update";function bv(){try{if(sessionStorage.getItem(Rc))return sessionStorage.removeItem(Rc),!0}catch{}return!1}function lp(e){if(sessionStorage.getItem(Ac)){console.warn("[versionCheck] reload already attempted, suppressing",e);return}sessionStorage.setItem(Ac,"1"),console.info("[versionCheck] reloading:",e),window.location.reload()}function xv(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 vv(e){return xv(e)?(lp(`chunk load error: ${e?.message??e}`),!0):!1}async function yv(){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 pl=!1;async function fl(){if(!(pl||document.visibilityState!=="visible")){pl=!0;try{const e=await yv();if(e&&e!=="mom6ta6e-9093ebdb"){try{sessionStorage.setItem(Rc,"1")}catch{}lp(`build version changed: mom6ta6e-9093ebdb -> ${e}`)}}finally{pl=!1}}}function jv(){window.setTimeout(()=>sessionStorage.removeItem(Ac),5e3),document.addEventListener("visibilitychange",()=>{fl()}),window.addEventListener("focus",()=>{fl()}),window.setTimeout(()=>void fl(),2e3)}class Vo 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),!vv(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(ad,{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 is({children:e,onError:n}){return t.jsx(Vo,{level:"page",onError:n,children:e})}function Pi({children:e,onError:n}){return t.jsx(Vo,{level:"modal",onError:n,children:e})}function kv({children:e,onError:n}){return t.jsx(Vo,{level:"root",onError:n,children:e})}const wv="modulepreload",Nv=function(e){return"/"+e},Hd={},un=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=Nv(d),d in Hd)return;Hd[d]=!0;const m=d.endsWith(".css"),h=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${h}`))return;const f=document.createElement("link");if(f.rel=m?"stylesheet":wv,m||(f.as="script"),f.crossOrigin="",f.href=d,u&&f.setAttribute("nonce",u),document.head.appendChild(f),m)return new Promise((p,g)=>{f.addEventListener("load",p),f.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return r.then(l=>{for(const c of l||[])c.status==="rejected"&&o(c.reason);return n().catch(o)})},rd="fn.authToken",qd="token",Sv="fn_token";let ua,Vd=!1,wo=!1;const Tc="fn:auth-token-recovery-required";function Cv(){try{const e=window.localStorage.getItem(rd);return e&&e.length>0?e:void 0}catch{return}}function cp(e){try{window.localStorage.setItem(rd,e)}catch{}}function Ev(){if(!(Vd||typeof window>"u")){Vd=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(qd);if(!n)return;cp(n),e.searchParams.delete(qd);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function fa(){if(ua!==void 0)return ua;const e=Ev();if(e)return ua=e,e;const n=Cv();if(n)return ua=n,n}function _v(e){ua=e,wo=!1,cp(e)}function Mv(){ua=void 0,wo=!1;try{window.localStorage.removeItem(rd)}catch{}}function Wd(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function Av(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function Rv(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!Av(e.protocol))return!1;const s=e.hostname===n.hostname,i=e.port===n.port,r=Wd(e.protocol)===Wd(n.protocol);return s&&i&&r}function Tv(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 ii(e){const n=fa();if(!n||typeof window>"u")return e;const s=Tv(e);return!s||!Rv(s.parsed)?e:(s.parsed.searchParams.set(Sv,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function fi(e){const n=fa();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function Pv(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function Iv(){typeof window>"u"||wo||(wo=!0,window.dispatchEvent(new CustomEvent(Tc)))}async function $v(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();Pv(i)&&Iv()}catch{}}function Dv(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,fa();const e=window.fetch.bind(window);window.fetch=function(s,i){const r=fa(),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=>($v(u),u))}}class Lv extends Error{status;details;constructor(n,s,i){super(n),this.name="ApiRequestError",this.status=s,this.details=i}}function zv(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function hs(e){return`/api${e}`}async function I(e,n={}){const s=hs(e),i=fa(),r=(()=>{if(i){const f=new Headers(n.headers??{});return f.has("Content-Type")||f.set("Content-Type","application/json"),fi(f)}if(!n.headers)return{"Content-Type":"application/json"};const h=new Headers(n.headers);return h.has("Content-Type")||h.set("Content-Type","application/json"),Object.fromEntries(h.entries())})(),o=await fetch(s,{...n,headers:r});if(o.status===204){if(!o.ok)throw new Error(`Request failed for ${s}: ${o.status} ${o.statusText}`);return}const l=o.headers.get("content-type")??"",c=await o.text(),u=l.includes("application/json");if(l.includes("text/html")||zv(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 Lv(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return m}function M4(){return I("/health")}function A4(){return I("/updates/check")}function Fv(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 I(`/tasks${l}`)}async function pr(e,n){const i=hs(W(`/tasks/${e}`,n));for(let r=1;r<=2;r++){const o=await fetch(i,{headers:fi({"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 dp(e,n){const{title:s,description:i,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:u,modelPresetId:d,modelProvider:m,modelId:h,validatorModelProvider:f,validatorModelId:p,planningModelProvider:g,planningModelId:b,thinkingLevel:v,summarize:x,reviewLevel:y,executionMode:k,priority:_,source:S}=e;return I(W("/tasks",n),{method:"POST",body:JSON.stringify({title:s,description:i,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:u,modelPresetId:d,modelProvider:m,modelId:h,validatorModelProvider:f,validatorModelId:p,planningModelProvider:g,planningModelId:b,thinkingLevel:v,summarize:x,reviewLevel:y,executionMode:k,priority:_,source:S})})}function ni(e,n,s){return I(W(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Ov(e,n,s,i,r,o,l,c,u){return I(W("/tasks/batch-update-models",u),{method:"POST",body:JSON.stringify({taskIds:e,modelProvider:n,modelId:s,validatorModelProvider:i,validatorModelId:r,planningModelProvider:o,planningModelId:l,nodeId:c})})}function Uv(e,n,s){return I(W(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n})})}function Bv(e,n,s){const i=new URLSearchParams,r=i.size>0?`?${i.toString()}`:"";return I(W(`/tasks/${e}${r}`,n),{method:"DELETE"})}function Hv(e,n){return I(W(`/tasks/${e}/merge`,n),{method:"POST"})}function qv(e,n){return I(W(`/tasks/${e}/retry`,n),{method:"POST"})}function Vv(e,n){return I(W(`/tasks/${e}/reset`,n),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({confirm:!0})})}function Wv(e,n){return I(W(`/tasks/${e}/duplicate`,n),{method:"POST"})}function up(e,n){return I(W(`/tasks/${e}/pause`,n),{method:"POST"})}function Kv(e,n){return I(W(`/tasks/${e}/unpause`,n),{method:"POST"})}function Gv(e,n){return I(W(`/tasks/${e}/archive`,n),{method:"POST"})}function Jv(e,n){return I(W(`/tasks/${e}/unarchive`,n),{method:"POST"})}function Yv(e){return I(W("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function Qv(e,n){return I(W(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function Xv(e,n){return I(W(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function Zv(e){return I(W("/config",e))}function Wo(e){return I(W("/settings",e))}function Hr(e,n){return I(W("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function ey(e){return I(W("/update-check",e))}function R4(e){return I(W("/remote/settings",e))}function T4(e,n){return I(W("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function P4(e){return I(W("/remote/status",e))}function I4(e){return I(W("/remote/install-cloudflared",e),{method:"POST"})}function $4(e){return I(W("/remote/tunnel/start",e),{method:"POST"})}function D4(e){return I(W("/remote/tunnel/stop",e),{method:"POST"})}function L4(e){return I(W("/remote/tunnel/kill-external",e),{method:"POST"})}function z4(e){return I(W("/remote/token/persistent/regenerate",e),{method:"POST"})}function F4(e,n){return I(W("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function mp(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 O4(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:i}=e,r=mp(null,s,i);return I(W(`/remote/url${r}`,n))}function U4(e="text",n={}){const{projectId:s,tokenType:i="persistent",ttlMs:r}=n,o=mp(e,i,r);return I(W(`/remote/qr${o}`,s))}function B4(e){return I(W("/memory",e))}function H4(e,n){return I(W("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function q4(e){return I(W("/memory/files",e))}function V4(e,n){const s=`path=${encodeURIComponent(e)}`;return I(W(`/memory/file?${s}`,n))}function W4(e,n,s){return I(W("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function K4(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 I(W("/memory/compact",i),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function G4(e){return I(W("/memory/dream",e),{method:"POST"})}function J4(e){return I(W("/memory/insights",e))}function Y4(e,n){return I(W("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function Q4(e){return I(W("/memory/extract",e),{method:"POST"})}function X4(e){return I(W("/memory/audit",e))}function Z4(e){return I(W("/memory/stats",e))}function e$(e){return I(W("/memory/backend",e))}function t$(e){return I(W("/memory/install-qmd",e),{method:"POST"})}function n$(e,n){return I(W("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function Gi(){return I("/settings/global")}function hn(e){return I("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function s$(e){return I(W("/settings/scopes",e))}function i$(e){return I(W("/settings/pi-extensions",e))}function a$(e,n){return I(W("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function r$(e,n,s){return I(W("/settings/test-notification",s),{method:"POST",body:JSON.stringify({providerId:e,...n??{}})})}function o$(){return I("/pi-settings")}async function l$(e){return I("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function c$(e){return I("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function d$(e){return I(W("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function fr(e,n,s){const i=new FormData;i.append("file",n);const r=await fetch(hs(W(`/tasks/${e}/attachments`,s)),{method:"POST",headers:fi(),body:i}),o=await r.json();if(!r.ok)throw new Error(o.error||"Upload failed");return o}async function ty(e,n,s){return I(W(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function Kd(e,n,s){const i=new URLSearchParams;s?.limit!==void 0&&i.set("limit",String(s.limit)),s?.offset!==void 0&&i.set("offset",String(s.offset));const r=i.toString()?`?${i.toString()}`:"",o=W(`/tasks/${e}/logs${r}`,n),l=await fetch(hs(o),{headers:fi()});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 ny(e,n,s,i){return I(W(`/tasks/${e}/comments/${n}`,i),{method:"PATCH",body:JSON.stringify({text:s})})}function sy(e,n,s){return I(W(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function iy(e,n){return I(W(`/tasks/${e}/documents`,n))}function ay(e,n,s){return I(W(`/tasks/${e}/documents/${n}/revisions`,s))}async function u$(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 I(W(r,n))}function m$(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const i=s.toString(),r=`/files/markdown-list${i?`?${i}`:""}`;return I(W(r,e))}function Gd(e,n,s,i,r){return I(W(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:i?.author,metadata:i?.metadata})})}function ry(e,n,s){return I(W(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function oy(e,n,s){return I(W(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function ly(e,n,s){return I(W(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function cy(e,n){return I(W(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function dy(e,n,s){return I(W(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function ms(){return I("/models")}function uy(){return I("/usage")}function my(){return I("/providers/claude-cli/status")}async function h$(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return I(`/providers/hermes/status${n}`)}async function p$(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return(await I(`/providers/hermes/profiles${n}`)).profiles??[]}async function f$(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return I(`/providers/openclaw/status${n}`)}async function g$(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),I(`/providers/paperclip/status?${n.toString()}`)}async function b$(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),(await I(`/providers/paperclip/companies?${n.toString()}`)).companies??[]}async function x$(e){const n=new URLSearchParams({apiUrl:e.apiUrl,companyId:e.companyId});return e.apiKey&&n.set("apiKey",e.apiKey),(await I(`/providers/paperclip/agents?${n.toString()}`)).agents??[]}async function v$(e){return I("/providers/paperclip/cli-mint-key",{method:"POST",body:JSON.stringify(e)})}async function y$(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return I(`/providers/paperclip/cli-status${s?`?${s}`:""}`)}async function j$(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return(await I(`/providers/paperclip/cli-companies${s?`?${s}`:""}`)).companies??[]}async function k$(e){const n=new URLSearchParams({companyId:e.companyId});return e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath),(await I(`/providers/paperclip/cli-agents?${n.toString()}`)).agents??[]}async function w$(e={}){const n=new URLSearchParams;e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return I(`/providers/paperclip/cli-discovery${s?`?${s}`:""}`)}function hy(e){return I("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}async function py(){const n=(await I("/custom-providers")).map(s=>({id:s.id,name:s.name,baseUrl:s.baseUrl,api:s.apiType==="anthropic-compatible"?"anthropic-messages":"openai-completions",apiKey:s.apiKey,models:(s.models??[]).map(i=>({id:i.id,name:i.name}))}));return Object.assign(n,{providers:n})}function fy(e){return I("/custom-providers",{method:"POST",body:JSON.stringify(e)})}function N$(e,n){const s=n,i={...typeof s.name=="string"?{name:s.name}:{},...typeof s.baseUrl=="string"?{baseUrl:s.baseUrl}:{},...typeof s.apiKey=="string"?{apiKey:s.apiKey}:{},...Array.isArray(s.models)?{models:s.models.map(r=>({id:r.id,name:r.name??r.id}))}:{},...s.api?{apiType:s.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible"}:{},..."apiType"in n?{apiType:n.apiType}:{}};return I(`/custom-providers/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(i)})}function S$(e){return I(`/custom-providers/${encodeURIComponent(e)}`,{method:"DELETE"})}function gy(e){const n=e.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible";return fy({name:e.name?.trim()||e.id,apiType:n,baseUrl:e.baseUrl,apiKey:e.apiKey,models:e.models?.map(s=>({id:s.id,name:s.name??s.id}))})}function gr(){return I("/auth/status")}function by(e){return I("/auth/login",{method:"POST",body:JSON.stringify({provider:e,origin:window.location.origin})})}function xy(e){return I("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function vy(e,n){return I("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function yy(e){return I("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function jy(e,n,s,i){return I("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:i})})}function ky(e,n,s,i){return I(W("/github/issues/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function wy(e,n,s){return I("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function Ny(e,n,s,i){return I(W("/github/pulls/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function Sy(e){return I(W("/git/remotes",e))}function Cy(e){return I(W("/git/remotes/detailed",e))}function Ey(e,n,s){return I(W("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function _y(e,n){return I(W(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function My(e,n,s){return I(W(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function Ay(e,n,s){return I(W(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function Ry(e,n,s){return I(W(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function Ty(e,n){return I(W(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}async function Py(e,n){return(await I(W("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:e})})).results}function qr(e,n,s,i){return I(W("/terminal/sessions",i),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function Jd(e,n){return I(W(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Iy(e){return I(W("/terminal/sessions",e))}function Os(e){return I(W("/git/status",e))}function $y(e,n){const s=e?`?limit=${e}`:"";return I(W(`/git/commits${s}`,n))}function No(e,n){return I(W(`/git/commits/${e}/diff`,n))}function Dy(e){return I(W("/git/commits/ahead",e))}function Ly(e,n,s,i){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return I(W(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,i))}function La(e){return I(W("/git/branches",e))}function zy(e,n,s){const i=`?limit=${n}`;return I(W(`/git/branches/${encodeURIComponent(e)}/commits${i}`,s))}function Fy(e){return I(W("/git/worktrees",e))}function Oy(e,n,s){return I(W("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function Uy(e,n){return I(W(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function Yd(e,n,s){const i=n?"?force=true":"";return I(W(`/git/branches/${encodeURIComponent(e)}${i}`,s),{method:"DELETE"})}function By(e,n){return I(W("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function Hy(e){return I(W("/git/pull",e),{method:"POST"})}function qy(e){return I(W("/git/push",e),{method:"POST"})}function Vr(e){return I(W("/git/stashes",e))}function Vy(e,n){return I(W("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function Wy(e,n,s){return I(W(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function Ky(e,n){return I(W(`/git/stashes/${e}`,n),{method:"DELETE"})}function Gy(e,n,s){const i=new URLSearchParams;return i.set("path",e),i.set("staged",String(n)),I(W(`/git/diff/file?${i.toString()}`,s))}function ta(e){return I(W("/git/changes",e))}function Qd(e,n){return I(W("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function Jy(e,n){return I(W("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function Xd(e,n){return I(W("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function Yy(e,n){return I(W("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function Qy(e){return I(W("/workspaces",e))}function Xy(e,n,s){const i=new URLSearchParams({workspace:e});return n&&i.set("path",n),s&&i.set("projectId",s),I(`/files?${i.toString()}`)}function Zy(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),I(`/files/${encodeURIComponent(n)}?${i.toString()}`)}function ej(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),I(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function tj(e,n,s){const i=new URLSearchParams({q:e});return n&&i.set("workspace",n),s&&i.set("projectId",s),I(`/files/search?${i.toString()}`)}function nj(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),I(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function sj(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),I(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function ij(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),I(`/files/${encodeURIComponent(n)}/delete?${i.toString()}`,{method:"POST"})}function aj(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),I(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function hp(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${i.toString()}`}function rj(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${i.toString()}`}function oj(e,n,s){return I(W("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function lj(e,n,s,i){return I(W("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function cj(e,n,s){return I(W(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function dj(e,n,s){return I(W(`/planning/${encodeURIComponent(e)}/stop`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function pp(e,n,s){return I(W("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function uj(e,n,s){return I(W("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function mj(e,n,s){return I(W("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function hj(e,n,s){return I(W("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const Pc=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(Pc))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function pj(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function Cr(e,n,s={}){const i=s.maxReconnectAttempts??10;let r=null,o=!1,l=0,c=null,u=null,d=!1;const m=p=>{const g=p.lastEventId;if(!g)return!0;const b=Number.parseInt(g,10);return Number.isFinite(b)?u!==null&&b<=u?!1:(u=b,!0):!0},h=()=>{if(o)return;const p=pj(e,u),g=new EventSource(ii(p));r=g,g.onopen=()=>{l=0,d=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},g.onmessage=b=>{const v=b;m(v)&&n.onMessage?.(v)};for(const[b,v]of Object.entries(n.events??{}))g.addEventListener(b,x=>{const y=x;m(y)&&v(y)});g.onerror=()=>{if(o||r!==g)return;if(g.readyState===EventSource.CONNECTING){d||(d=!0,s.onConnectionStateChange?.("reconnecting"));return}if(g.close(),l>=i){s.onFatalError?.("Connection lost");return}d=!0,s.onConnectionStateChange?.("reconnecting"),l+=1;const v=Math.min(1e3*2**(l-1),3e4);c=setTimeout(()=>{c=null,h()},v)}};h();const f={close:()=>{o=!0,c&&(clearTimeout(c),c=null),r?.close(),Pc.delete(f)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return Pc.add(f),f}function Zd(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 ga(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 fj(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 gj(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((i,r)=>fj(i,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function bj(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 eu(e){return Array.isArray(e)?e.map(Zd):(e.candidates??[]).map(Zd)}async function xj(e){try{const n=await I(W("/dev-server/candidates",e));return eu(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await I(W("/dev-server/detect",e));return eu(s)}throw n}}function od(e){return I(W("/dev-server/status",e)).then(ga)}async function C$(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 I(W(`/dev-server/logs/history${i}`,n));return gj(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await od(n);return bj(o.logs,e)}throw r}}function vj(e,n){const s=e.cwd??e.packagePath??".",i=e.scriptName;return I(W("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:i,scriptId:i,cwd:s,packagePath:e.packagePath})}).then(ga)}function yj(e){return I(W("/dev-server/stop",e),{method:"POST"}).then(ga)}function jj(e){return I(W("/dev-server/restart",e),{method:"POST"}).then(ga)}async function kj(e,n){const s=typeof e=="string"?{url:e}:e;try{const i=await I(W("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return ga(i)}catch(i){if(i instanceof Error&&/\/dev-server\/preview-url/.test(i.message)){const r=await I(W("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return ga(r)}throw i}}function E$(e){return hs(W("/dev-server/logs/stream",e))}async function _$(e){try{return(await I(W("/devserver",e))).sessions??[]}catch{try{const n=await od(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 M$(e,n){try{return await I(W(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await od(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 A$(e,n){try{return await I(W(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await vj({command:""},n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}}}async function R$(e,n){try{return await I(W(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await yj(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 T$(e,n){try{return await I(W(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await jj(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 P$(e,n,s){try{const i=await I(W(`/devserver/${encodeURIComponent(e)}/preview`,s),{method:"POST",body:JSON.stringify({url:n})});return{url:i.url??null,source:i.source??null}}catch{const i=await kj({url:n},s);return{url:i.previewUrl??i.manualUrl??null,source:"manual"}}}async function I$(e){try{return(await I(W("/devserver/detect",e))).candidates??[]}catch{try{return(await xj(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function $$(e,n){return hs(W(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function Er(e,n,s=25e3){const i=setInterval(()=>{nw(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(i)}}}function wj(e,n){return hs(W(`/planning/${encodeURIComponent(e)}/stream`,n))}function Nj(e,n,s,i){const r=wj(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Cr(r,{onOpen:()=>{c(),o=Er(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 _r(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 Sj(e){return I(_r("/routines",e))}function Cj(e,n){return I(_r("/routines",n),{method:"POST",body:JSON.stringify(e)})}function tu(e,n,s){return I(_r(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function Ej(e,n){await I(_r(`/routines/${e}`,n),{method:"DELETE"})}function _j(e,n){return I(_r(`/routines/${e}/trigger`,n),{method:"POST"})}function nu(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 I(`/activity${s}`)}function Mj(e){const n=W("/activity",e);return I(n,{method:"DELETE"})}function Ko(e){return I(W("/workflow-steps",e))}function su(e,n){return I(W("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function Aj(e,n,s){return I(W(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Rj(e,n){return I(W(`/workflow-steps/${e}`,n),{method:"DELETE"})}function iu(e,n){return I(W(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function Tj(e,n){return I(W(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function Pj(){return I("/workflow-step-templates")}function Ij(e,n){return I(W(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function br(e){return I(W("/scripts",e))}function $j(e,n,s){return I(W("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function Dj(e,n){return I(W(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function fp(e,n,s){return(await I(W("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const Wr={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 gp(e){if(!(e instanceof Error))return Wr.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?Wr.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?Wr.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:Wr.NETWORK}function Lj(e,n){return I(W("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function zj(e,n,s){return I(W(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Fj(e,n){return hs(W(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function Oj(e,n,s,i){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=Cr(Fj(e,n),{onOpen:()=>{l(),r=Er(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 Uj(e,n,s,i){return I(W("/subtasks/create-tasks",i),{method:"POST",body:JSON.stringify({sessionId:e,parentTaskId:s,subtasks:n.map(r=>({tempId:r.id,title:r.title,description:r.description,size:r.suggestedSize,dependsOn:r.dependsOn}))})})}function bp(e,n,s){return I(W("/subtasks/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function W(e,n){if(!n)return e;const s=e.includes("?")?"&":"?";return`${e}${s}projectId=${encodeURIComponent(n)}`}function Bj(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 Go(e,n){const{nodeId:s,localNodeId:i,...r}=n??{},o=Bj(e,s,i);return I(o,r)}function Ea(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 I(`/agents${i}`)}function xp(e,n){return I(W(`/agents/${encodeURIComponent(e)}`,n))}function Hj(e,n){return I(W("/agents",n),{method:"POST",body:JSON.stringify(e)})}function qj(e,n,s){return I(W(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function D$(e,n){return I(W(`/agents/${encodeURIComponent(e)}/upgrade-heartbeat-procedure`,n),{method:"POST"})}function L$(e,n,s){return I(W(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function z$(e,n,s){return I(W(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function F$(e,n,s){return I(W(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function O$(e,n){return I(W(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function U$(e,n,s){const i=`path=${encodeURIComponent(n)}`;return I(W(`/agents/${encodeURIComponent(e)}/memory/file?${i}`,s))}function B$(e,n,s,i){return I(W(`/agents/${encodeURIComponent(e)}/memory/file`,i),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function Vj(e,n,s){return I(W(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function Wj(e,n){return I(W(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function H$(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 I(`/agents/${encodeURIComponent(e)}/runs${r}`)}function q$(e,n,s){return I(W(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function V$(e,n,s){return I(W(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function W$(e,n,s){const i=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return I(W(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:i,triggerDetail:r})})}function K$(e,n){return I(W(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function Kj(e){return I(W("/agents/stats",e))}function G$(e,n){return I(W(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function J$(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeEphemeral&&s.set("includeEphemeral","true");const i=s.toString();return I(`/agents/org-tree${i?`?${i}`:""}`)}function Y$(e,n){return I(W(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function au(e,n,s){return I(W(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function Q$(e,n){return I(W(`/agents/${encodeURIComponent(e)}/tasks`,n))}function X$(){return I("/agents/companies")}function Z$(e,n){return I(W("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function eD(e,n){return I(W("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function tD(e,n){return I(W(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function nD(e){return I(W("/backups",e))}function sD(e){return I(W("/backups",e),{method:"POST"})}function iD(e,n){const s=W("/settings/export",n),i=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return I(i)}function aD(e,n,s){return I(W("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}function ru(){return I("/projects/across-nodes")}function or(e,n){I("/_perf/dashboard-load",{method:"POST",body:JSON.stringify({source:e,message:n})}).catch(()=>{})}function So(){return I("/nodes")}function Gj(e){return I("/nodes",{method:"POST",body:JSON.stringify(e)})}function Jj(e,n){return I(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function Yj(e){return I(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Qj(e){const n=await I(`/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 rD(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=fa();l&&o.set("fn_token",l);const c=o.toString(),u=`/browse-directory${c?`?${c}`:""}`;return I(u)}function Xj(e){return I("/projects",{method:"POST",body:JSON.stringify(e)})}function vp(e){return I(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function ou(e){return I(`/projects/${encodeURIComponent(e)}/health`)}function Zj(e){return I(W("/executor/stats",e))}function ek(e){return I(W("/system-stats",e))}function tk(e){return I(W("/kill-vitest",e),{method:"POST"})}function lu(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 I(`/activity-feed${s}`)}function nk(e){return I(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function sk(e){return I(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function oD(){return I("/global-concurrency")}function lD(e){return I("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function ik(e,n){return I(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function yp(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 I(`/tasks/${encodeURIComponent(e)}/diff${r}`)}function ak(e){return I(W("/missions",e))}function rk(e,n){return I(W("/missions",n),{method:"POST",body:JSON.stringify(e)})}function jp(e,n){return I(W(`/missions/${encodeURIComponent(e)}`,n))}function ok(e,n,s){return I(W(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function lk(e,n){return I(W(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function ck(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 I(W(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function dk(e){return I(W("/missions/health",e))}function uk(e,n,s){return I(W(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function mk(e,n,s){return I(W(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function hk(e,n){return I(W(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function pk(e,n,s){return I(W(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function fk(e,n,s){return I(W(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function gk(e,n){return I(W(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function bk(e,n){return I(W(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function xk(e,n,s){return I(W(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function vk(e,n,s){return I(W(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function yk(e,n){return I(W(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function jk(e,n,s){return I(W(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function kk(e,n){return I(W(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function wk(e,n,s,i){return I(W(`/missions/features/${encodeURIComponent(e)}/triage`,i),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s})})}function Nk(e,n){return I(W(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST"})}function gl(e,n){return I(W(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function Sk(e,n,s){return I(W(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function Ck(e,n,s){return I(W(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Ek(e,n,s){return I(W(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function _k(e,n,s){return I(W(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function Mk(e,n){return I(W(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function bl(e,n){return I(W(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function cu(e,n){return I(W(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function Ak(e,n){return I(W(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function du(e,n){return I(W(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function Rk(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 I(W(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function Tk(e,n){return I(W(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function Pk(e,n){return I(W(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function Ik(e,n){return I(W(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function $k(e,n){return I(W(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function Dk(e,n,s){return I(W(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function Lk(e,n,s){return I(W("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function zk(e,n,s,i){return I(W("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Fk(e,n,s){return I(W(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function kp(e,n,s){return I(W("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function Ok(e,n,s){return I(W("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function Uk(e,n,s,i){const r=hs(W(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Cr(r,{onOpen:()=>{c(),o=Er(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 Mr(e,n,s){return W(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function Ar(e,n,s){return W(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function Bk(e,n){return I(Mr(e,"/start",n),{method:"POST"})}function Hk(e,n,s,i){return I(Mr(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function qk(e,n,s,i){const r=hs(Mr(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Cr(r,{onOpen:()=>{c(),o=Er(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 Vk(e,n,s){return I(Mr(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function Wk(e,n){return I(Mr(e,"/skip",n),{method:"POST"})}function Kk(e,n){return I(Ar(e,"/start",n),{method:"POST"})}function Gk(e,n,s,i){return I(Ar(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Jk(e,n,s,i){const r=hs(Ar(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Cr(r,{onOpen:()=>{c(),o=Er(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 Yk(e,n,s){return I(Ar(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function Qk(e,n){return I(Ar(e,"/skip",n),{method:"POST"})}async function Xk(e,n){try{return await I(W(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function cD(e){return I(W("/roadmaps",e))}function dD(e,n){return I(W("/roadmaps",n),{method:"POST",body:JSON.stringify(e)})}function uD(e,n){return I(W(`/roadmaps/${encodeURIComponent(e)}`,n))}function mD(e,n,s){return I(W(`/roadmaps/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function hD(e,n){return I(W(`/roadmaps/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function pD(e,n,s){return I(W(`/roadmaps/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function fD(e,n,s){return I(W(`/roadmaps/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function gD(e,n){return I(W(`/roadmaps/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function bD(e,n,s){return I(W(`/roadmaps/milestones/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function xD(e,n,s){return I(W(`/roadmaps/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function vD(e,n){return I(W(`/roadmaps/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function yD(e,n,s){return I(W(`/roadmaps/${encodeURIComponent(e)}/milestones/reorder`,s),{method:"POST",body:JSON.stringify({orderedMilestoneIds:n})})}function jD(e,n,s){return I(W(`/roadmaps/milestones/${encodeURIComponent(e)}/features/reorder`,s),{method:"POST",body:JSON.stringify({orderedFeatureIds:n})})}function kD(e,n,s,i){return I(W(`/roadmaps/features/${encodeURIComponent(e)}/move`,i),{method:"POST",body:JSON.stringify({targetMilestoneId:n,targetIndex:s})})}function wD(e,n){return I(W(`/roadmaps/${encodeURIComponent(e)}/handoff`,n))}function ND(e,n,s,i){return I(W(`/roadmaps/${encodeURIComponent(e)}/suggestions/milestones`,i),{method:"POST",body:JSON.stringify({goalPrompt:n.trim(),...s!==void 0?{count:s}:{}})})}function SD(e,n,s){return I(W(`/roadmaps/milestones/${encodeURIComponent(e)}/suggestions/features`,s),{method:"POST",body:JSON.stringify({...n?.prompt!==void 0?{prompt:n.prompt.trim()}:{},...n?.count!==void 0?{count:n.count}:{}})})}function CD(e){return I(W("/todos",e))}function ED(e,n){const s={title:e};return I(W("/todos",n),{method:"POST",body:JSON.stringify(s)})}function _D(e,n,s){const i={title:n};return I(W(`/todos/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(i)})}function MD(e,n){return I(W(`/todos/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function AD(e,n,s){const i={text:n};return I(W(`/todos/${encodeURIComponent(e)}/items`,s),{method:"POST",body:JSON.stringify(i)})}function RD(e,n,s){const i=n;return I(W(`/todos/items/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(i)})}function TD(e,n){return I(W(`/todos/items/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function PD(e,n,s){return I(W(`/todos/${encodeURIComponent(e)}/items/reorder`,s),{method:"POST",body:JSON.stringify({itemIds:n})})}function ba(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function ld(e){const n=e?`?projectId=${encodeURIComponent(e)}`:"",s=await fetch(hs(`/ai-sessions${n}`),{headers:fi()});return s.ok?(await s.json()).sessions??[]:[]}async function hi(e){const n=await fetch(hs(`/ai-sessions/${encodeURIComponent(e)}`),{headers:fi()});return n.ok?n.json():null}async function Zk(e,n){const s=await I(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function ew(e,n){return I(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function tw(e,n){return I(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function wp(e){await fetch(hs(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:fi()})}function nw(e,n){return I(W(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function sw(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 I(`/messages/inbox${i}`)}function iw(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 I(`/messages/outbox${i}`)}function Np(e){return I(W("/messages/unread-count",e))}function aw(e,n){return I(W("/messages",n),{method:"POST",body:JSON.stringify(e)})}function rw(e,n){return I(W(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function ow(e){return I(W("/messages/read-all",e),{method:"POST"})}function lw(e,n){return I(W(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function cw(e,n,s){const i=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return I(W(i,s))}function dw(e,n){return I(W(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function ID(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 I(`/agents/${encodeURIComponent(e)}/reflections${r}`)}function $D(e,n){return I(W(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function DD(e,n,s){const i=new URLSearchParams;s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return I(`/agents/${encodeURIComponent(e)}/performance${r}`)}function LD(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 I(`/agents/${encodeURIComponent(e)}/ratings${r}`)}function zD(e,n,s){return I(W(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function FD(e,n){return I(W(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function OD(e,n,s){return I(W(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function UD(e,n){return I(W(`/agents/${encodeURIComponent(e)}/budget`,n))}function BD(e,n){return I(W(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function HD(e){return I(W("/plugins",e))}async function qD(e,n){return I(W("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function VD(e,n){return I(W(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function WD(e,n){return I(W(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function KD(e,n){return I(W(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function GD(e,n){return I(W(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function JD(e,n,s){return I(W(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function YD(e,n){return I(W(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function uw(e){return I(W("/plugins/ui-slots",e))}async function QD(e){return I(W("/plugins/runtimes",e))}async function XD(e){return(await I(W("/skills/discovered",e))).skills}async function ZD(e,n,s){return I(W("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function eL(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 I(W(`/skills/catalog${r}`,s))}async function tL(e,n){return(await I(W(`/skills/${encodeURIComponent(e)}/content`,n))).content}function nL(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const i=s.toString();return I(`/chat/sessions${i?`?${i}`:""}`)}async function mw(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 I(`/chat/sessions?${o.toString()}`)).sessions[0]??null}}function hw(e,n){return I(W("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function sL(e,n,s){return I(W(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function iL(e,n){return I(W(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function uu(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 I(W(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function pw(e,n){return I(W(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function fw(e,n,s,i,r,o){const l=hs(W(`/chat/sessions/${encodeURIComponent(e)}/messages`,r)),c=new AbortController;let u=!1;const d=(m,h)=>{if(!(!m||!h))switch(m){case"thinking":try{s.onThinking?.(JSON.parse(h))}catch{s.onThinking?.(h)}break;case"text":try{s.onText?.(JSON.parse(h))}catch{s.onText?.(h)}break;case"tool_start":try{s.onToolStart?.(JSON.parse(h))}catch{}break;case"tool_end":try{s.onToolEnd?.(JSON.parse(h))}catch{}break;case"done":try{s.onDone?.(JSON.parse(h))}catch{s.onDone?.({messageId:""})}break;case"error":try{const f=JSON.parse(h);s.onError?.(f.message||f)}catch{s.onError?.(h||"Stream error")}break}};return(async()=>{try{const m=Array.isArray(i)&&i.length>0,h=m?(()=>{const k=new FormData;return k.append("content",n),i.forEach(_=>k.append("attachments",_)),k})():JSON.stringify({content:n}),f=await fetch(l,{method:"POST",headers:m?fi():fi({"Content-Type":"application/json"}),body:h,signal:c.signal});if(!f.ok){const k=await f.text();let _=`Request failed: ${f.status}`;try{_=JSON.parse(k).error||_}catch{}s.onError?.(_);return}if(!f.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected");const p=f.body.getReader(),g=new TextDecoder;let b="",v="",x=[];const y=(k,_=!1)=>{b+=k;const S=b.split(`
|
|
613
|
-
`);b=S.pop()||"",_&&b.length>0&&(S.push(b),b="");for(const w of S){const M=w.endsWith("\r")?w.slice(0,-1):w;if(M.startsWith("event:"))v=M.slice(6).trim();else if(M.startsWith("data:")){const N=M.slice(5);x.push(N.startsWith(" ")?N.slice(1):N)}else if(M===""){const N=x.join(`
|
|
614
|
-
`);d(v,N),v="",x=[]}}if(_&&v&&x.length>0){const w=x.join(`
|
|
615
|
-
`);d(v,w),v="",x=[]}};for(;;){const{done:k,value:_}=await p.read();if(k){y(g.decode(),!0);break}y(g.decode(_,{stream:!0}))}}catch(m){if(m instanceof DOMException&&m.name==="AbortError"){u||s.onError?.("Connection aborted");return}if(u)return;s.onError?.(m instanceof Error?m.message:"Connection error")}})(),{close:()=>{u=!0,c.abort()},isConnected:()=>!u}}function aL(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 I(W(`/insights${i}`,n))}function rL(e,n){return I(W(`/insights/${encodeURIComponent(e)}/dismiss`,n),{method:"POST"})}function oL(e="manual",n,s){return I(W("/insights/run",s),{method:"POST",body:JSON.stringify({trigger:e,inputMetadata:n})})}function lL(e){return I(W("/insights/runs",e))}function cL(e,n){return I(W(`/insights/${encodeURIComponent(e)}/create-task`,n),{method:"POST"})}function dL(e={},n){const s=new URLSearchParams;e.q&&s.set("q",e.q),e.status&&s.set("status",e.status),e.limit!==void 0&&s.set("limit",String(e.limit));const i=s.size>0?`?${s.toString()}`:"";return I(W(`/research/runs${i}`,n))}function uL(e,n){return I(W("/research/runs",n),{method:"POST",body:JSON.stringify(e)})}function mL(e,n){return I(W(`/research/runs/${encodeURIComponent(e)}`,n))}function hL(e,n){return I(W(`/research/runs/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function pL(e,n){return I(W(`/research/runs/${encodeURIComponent(e)}/retry`,n),{method:"POST"})}function fL(e,n,s){return I(W(`/research/runs/${encodeURIComponent(e)}/export?format=${encodeURIComponent(n)}`,s))}function gL(e,n,s){return I(W(`/research/runs/${encodeURIComponent(e)}/create-task`,s),{method:"POST",body:JSON.stringify(n)})}function bL(e,n,s){return I(W(`/research/runs/${encodeURIComponent(e)}/attach-task`,s),{method:"POST",body:JSON.stringify(n)})}function gw(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 bw({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}=gw(e.status),r=e.status==="connecting";return t.jsxs("div",{className:"node-status-indicator node-status-indicator--remote",children:[t.jsx("span",{className:`node-status-indicator__dot ${i}`,children:r&&t.jsx("span",{className:"node-status-indicator__spinner"})}),t.jsx("span",{className:"node-status-indicator__name",children:e.name}),n&&t.jsxs("span",{className:"node-status-indicator__details",children:[e.type," · ",s]})]})}function xw(e){return e.charAt(0).toUpperCase()+e.slice(1)}function qi({status:e,showLabel:n=!1,className:s,compact:i=!1}){const r=xw(e);return t.jsxs("span",{className:`node-health-dot${i?" node-health-dot--compact":""}${s?` ${s}`:""}`,title:r,"aria-label":`Node status: ${r}`,children:[t.jsx("span",{className:`status-dot status-dot--${e}`}),n?t.jsx("span",{className:"node-health-dot__label",children:r}):null]})}const mu=new Map,vw=6e4;function Sp(e){const[n,s]=a.useState([]),[i,r]=a.useState(!0),[o,l]=a.useState(null),c=a.useRef(!1),u=a.useRef(!1),d=a.useCallback(m=>n.filter(h=>h.slot.slotId===m),[n]);return a.useEffect(()=>{const m=e??"default";let h=!1;async function f(){const p=mu.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 uw(e);if(h||u.current)return;mu.set(m,{slots:b,expiresAt:Date.now()+vw}),s(b),c.current=!0}catch(b){if(h||u.current)return;l(b instanceof Error?b.message:"Failed to fetch UI slots"),c.current=!0}finally{!h&&!u.current&&r(!1)}}return f(),()=>{h=!0}},[e]),a.useEffect(()=>{c.current=!1,u.current=!1},[e]),a.useEffect(()=>()=>{u.current=!0},[]),a.useMemo(()=>({slots:n,getSlotsForId:d,loading:i,error:o}),[n,d,i,o])}function Jo({slotId:e,projectId:n}){const{getSlotsForId:s,loading:i,error:r}=Sp(n);if(i||r||!e)return null;const o=s(e);return o.length===0?null:t.jsx(Vo,{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 yw(){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 Rr(){const[e,n]=a.useState(yw);return a.useEffect(()=>{if(typeof window>"u")return;const s=window.matchMedia("(max-width: 768px)"),i=window.matchMedia("(min-width: 769px) and (max-width: 1024px)"),r=()=>{s.matches?n("mobile"):i.matches?n("tablet"):n("desktop")};return s.addEventListener("change",r),i.addEventListener("change",r),()=>{s.removeEventListener("change",r),i.removeEventListener("change",r)}},[]),e}function _a(e){return e.replace(/\\/g,"/")}function cd(e){return e.replace(/[\\/]+$/g,"")}function dd(e){const n=_a(cd(e));return n?n.split("/").filter(Boolean):[]}function ud(e){const n=_a(cd(e));if(!n)return e;const s=n.split("/").filter(Boolean);return s[s.length-1]||n}function Cp(e,n){const s=dd(e);return s.length===0?_a(e):s.slice(-2).join("/")}function jw(e){const n=_a(cd(e)),s=n.lastIndexOf("/");return s<0?"":n.slice(0,s+1)}function kw(e,n){return!e||e==="."?n:[...dd(e),n].join("/")}function ww(e){const n=dd(e);return n.length===0?".":(n.pop(),n.length===0?".":n.join("/"))}function xL(e){const n=_a(e),s=n.match(/^([A-Za-z]:)(?:\/(.*))?$/);if(s){const r=`${s[1]}/`,o=(s[2]??"").split("/").filter(Boolean),l=[{label:s[1],path:r}];for(let c=0;c<o.length;c+=1)l.push({label:o[c],path:`${r}${o.slice(0,c+1).join("/")}`});return l}if(n.startsWith("/")){const r=n.split("/").filter(Boolean),o=[{label:"/",path:"/"}];for(let l=0;l<r.length;l+=1)o.push({label:r[l],path:`/${r.slice(0,l+1).join("/")}`});return o}const i=n.split("/").filter(Boolean);return i.map((r,o)=>({label:r,path:i.slice(0,o+1).join("/")}))}const Ep={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function Nw({projects:e,currentProject:n,onViewAll:s,onSelectProject:i}){const[r,o]=a.useState(!1),l=a.useRef(null);a.useEffect(()=>{if(!r)return;const u=d=>{l.current&&!l.current.contains(d.target)&&o(!1)};return document.addEventListener("mousedown",u),()=>document.removeEventListener("mousedown",u)},[r]),a.useEffect(()=>{if(!r)return;const u=d=>{d.key==="Escape"&&o(!1)};return document.addEventListener("keydown",u),()=>document.removeEventListener("keydown",u)},[r]);const c=a.useCallback(u=>{i?.(u),o(!1)},[i]);return t.jsx("div",{className:"project-selector",ref:l,children:e.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:`project-selector-trigger${r?" project-selector-trigger--open":""}`,onClick:()=>o(u=>!u),title:n?.name?`Switch project (current: ${n.name})`:"Switch project","aria-label":"Switch project","aria-expanded":r,"aria-haspopup":"listbox","data-testid":"project-selector-trigger",children:[t.jsx("span",{className:"project-selector-trigger-label",children:n?.name??"Projects"}),t.jsx(Xt,{size:12,className:`project-selector-chevron${r?" project-selector-chevron--open":""}`})]}),r&&t.jsxs("div",{className:"project-selector-dropdown",role:"listbox","aria-label":"Select project","data-testid":"project-selector-dropdown",children:[e.map(u=>{const d=n?.id===u.id,m=Ep[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:Cp(u.path)})]}),d&&t.jsx(Hn,{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 hu({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 Sw({onOpenSettings:e,onOpenGitHubImport:n,onOpenPlanning:s,onResumePlanning:i,activePlanningSessionCount:r=0,onOpenUsage:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:u,mailboxUnreadCount:d=0,onOpenSchedules:m,onOpenGitManager:h,onOpenNodes:f,showNodesButton:p,onOpenWorkflowSteps:g,onOpenScripts:b,onRunScript:v,onToggleTerminal:x,onOpenFiles:y,filesOpen:k,globalPaused:_,enginePaused:S,onToggleGlobalPause:w,onToggleEnginePause:M,view:N="board",onChangeView:D,showSkillsTab:E,showAgentsTab:T,searchQuery:U="",onSearchChange:K,projects:$=[],currentProject:R,onSelectProject:z,onViewAllProjects:B,projectId:J,isElectron:Q=!1,mobileNavEnabled:C,availableNodes:L=[],currentNode:P,onSelectNode:j,isRemote:O=!1,experimentalFeatures:H}){const ge=Rr(),be=ge==="mobile",me=be||ge==="tablet",F=be&&C,[de,ne]=a.useState(!1),[xe,oe]=a.useState(!1),[he,ae]=a.useState(!1),[je,Ae]=a.useState(!1),[Oe,Qe]=a.useState(!1),[Xe,Ye]=a.useState(!1),[it,Be]=a.useState(!1),[Ge,re]=a.useState(!1),[ke,X]=a.useState(!1),[Te,Le]=a.useState(!1),[fe,_e]=a.useState(!1),[Ue,nt]=a.useState({}),[ve,ce]=a.useState(!1),[De,ue]=a.useState(-1),[Re,Ke]=a.useState(null),[Pe,ft]=a.useState({}),[Z,le]=a.useState(!1),we=a.useRef(null),Ze=a.useRef(null),te=a.useRef(null),Je=a.useRef(null),dt=a.useRef(null),ut=a.useRef(null),Ct=a.useRef(!1),yt=a.useRef(null),bt=a.useRef(null),At=a.useRef(null),Rt=a.useRef(null),Ht=a.useRef(null),Et=a.useRef(null),Dt=a.useRef(null),Kt=a.useRef(null),$t=a.useRef(!1),Ft=a.useMemo(()=>L.filter(Ne=>Ne.type==="remote"),[L]),Ot=Ft.length>0,Tt=a.useMemo(()=>Object.entries(Ue).sort(([Ne],[at])=>Ne.localeCompare(at)),[Ue]),Pt=Tt.length>0,wt=Tt.length+(Pt?1:0),Gt=a.useMemo(()=>Object.entries(Pe).sort(([Ne],[at])=>Ne.localeCompare(at)),[Pe]),Ut=a.useMemo(()=>!!(H?.researchView||H?.todoView||H?.insights||H?.roadmap||E||H?.memoryView||H?.devServerView||!F),[H,E,F]),q=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}},[]),pe=a.useCallback(()=>{const Ne=Dt.current;if(!Ne)return;const at=Ne.getBoundingClientRect(),fn=Kt.current,{width:jn,height:In,offsetTop:Ce,offsetLeft:st}=q(),ht=16,Mt=16,ln=6,En=fn?.offsetWidth||Math.max(at.width,260),tn=Math.min(En,Math.max(jn-ht*2,160)),nn=fn?.offsetHeight||280,An=Math.min(nn,Math.max(In-Mt*2,160)),Un=at.top-Ce,kn=at.bottom-Ce,ns=at.right-st,cn=In-kn,vt=Un,G=cn<An&&vt>cn,Fe=Math.min(Math.max(ns-tn,ht),jn-ht-tn)+st,tt=G?Math.max(Mt+Ce,Un-An-ln+Ce):Math.min(kn+ln+Ce,In+Ce-Mt-An);Ke({top:tt,left:Fe,width:tn})},[q]),$e=a.useCallback((Ne,at)=>{v?.(Ne,at),_e(!1),ue(-1)},[v]),A=a.useCallback(()=>{b?.(),_e(!1),ue(-1)},[b]),ee=a.useCallback(Ne=>{switch(Ne.key){case"ArrowDown":Ne.preventDefault(),wt>0&&ue(at=>at<wt-1?at+1:0);break;case"ArrowUp":Ne.preventDefault(),wt>0&&ue(at=>at>0?at-1:wt-1);break;case"Enter":if(Ne.preventDefault(),De>=0)if(De<Tt.length){const[at,fn]=Tt[De];$e(at,fn)}else Pt&&De===Tt.length&&A();break;case"Home":Ne.preventDefault(),wt>0&&ue(0);break;case"End":Ne.preventDefault(),wt>0&&ue(wt-1);break}},[A,$e,De,Tt,Pt,wt]);a.useEffect(()=>{Ct.current=Oe},[Oe]),a.useEffect(()=>{$t.current=fe},[fe]),a.useEffect(()=>{if(!Oe||!me)return;let Ne=!1;return le(!0),br(J).then(at=>{Ne||ft(at)}).catch(()=>{Ne||ft({})}).finally(()=>{Ne||le(!1)}),()=>{Ne=!0}},[Oe,me,J]),a.useEffect(()=>{if(!fe||me)return;let Ne=!1;return ce(!0),br(J).then(at=>{Ne||nt(at)}).catch(()=>{Ne||nt({})}).finally(()=>{Ne||ce(!1)}),()=>{Ne=!0}},[fe,me,J]),a.useEffect(()=>{if(!fe)return;const Ne=at=>{Et.current&&!Et.current.contains(at.target)&&_e(!1)};return document.addEventListener("mousedown",Ne),()=>document.removeEventListener("mousedown",Ne)},[fe]),a.useEffect(()=>{if(!fe)return;const Ne=at=>{at.key==="Escape"&&(_e(!1),Dt.current?.focus())};return document.addEventListener("keydown",Ne),()=>document.removeEventListener("keydown",Ne)},[fe]),a.useEffect(()=>{if(fe){ue(-1);const Ne=window.setTimeout(()=>Kt.current?.focus(),0);return()=>window.clearTimeout(Ne)}Ke(null)},[fe]),a.useEffect(()=>{if(!fe)return;const Ne=requestAnimationFrame(()=>{pe()});return()=>cancelAnimationFrame(Ne)},[fe,ve,Tt.length,Pt,pe]),a.useEffect(()=>{if(!fe)return;const Ne=()=>pe();window.addEventListener("resize",Ne),window.addEventListener("scroll",Ne,!0);const at=window.visualViewport;return at&&(at.addEventListener("resize",Ne),at.addEventListener("scroll",Ne)),()=>{window.removeEventListener("resize",Ne),window.removeEventListener("scroll",Ne,!0),at&&(at.removeEventListener("resize",Ne),at.removeEventListener("scroll",Ne))}},[fe,pe]),a.useEffect(()=>{me&&(_e(!1),ue(-1))},[me]);const ze=de||U.length>0,mt=(xe||U.length>0)&&!he,jt=(N==="board"||N==="list")&&!be&&K&&!he&&U.length===0,Lt=(N==="board"||N==="list")&&!be&&K;a.useEffect(()=>{U===""&&ae(!1)},[U]),a.useEffect(()=>{if(!je)return;const Ne=at=>{Ze.current&&!Ze.current.contains(at.target)&&we.current&&!we.current.contains(at.target)&&Ae(!1)};return document.addEventListener("mousedown",Ne),()=>document.removeEventListener("mousedown",Ne)},[je]),a.useEffect(()=>{if(!ke)return;const Ne=at=>{Je.current&&!Je.current.contains(at.target)&&te.current&&!te.current.contains(at.target)&&X(!1)};return document.addEventListener("mousedown",Ne),()=>document.removeEventListener("mousedown",Ne)},[ke]),a.useEffect(()=>{if(!Xe)return;const Ne=at=>{yt.current&&!yt.current.contains(at.target)&&Ye(!1)};return document.addEventListener("mousedown",Ne),()=>document.removeEventListener("mousedown",Ne)},[Xe]),a.useEffect(()=>{const Ne=at=>{if(at.key==="Escape"){if(re(!1),X(!1),Ct.current){Qe(!1);return}if($t.current){_e(!1),Dt.current?.focus();return}Ae(!1),ne(!1),Ye(!1),Be(!1)}};return document.addEventListener("keydown",Ne),()=>document.removeEventListener("keydown",Ne)},[]),a.useEffect(()=>{if(!it)return;const Ne=at=>{bt.current&&!bt.current.contains(at.target)&&Be(!1)};return document.addEventListener("mousedown",Ne),()=>document.removeEventListener("mousedown",Ne)},[it]),a.useEffect(()=>{if(!Te)return;const Ne=at=>{Ht.current&&!Ht.current.contains(at.target)&&Le(!1)};return document.addEventListener("mousedown",Ne),()=>document.removeEventListener("mousedown",Ne)},[Te]),a.useEffect(()=>{if(!Te)return;const Ne=at=>{at.key==="Escape"&&Le(!1)};return document.addEventListener("keydown",Ne),()=>document.removeEventListener("keydown",Ne)},[Te]),a.useEffect(()=>{if(!Ge)return;const Ne=at=>{At.current&&!At.current.contains(at.target)&&Rt.current&&!Rt.current.contains(at.target)&&re(!1)};return document.addEventListener("mousedown",Ne),()=>document.removeEventListener("mousedown",Ne)},[Ge]);const _t=a.useCallback(()=>{ne(Ne=>!Ne)},[]),Jt=a.useCallback(()=>{oe(!0),ae(!1)},[]),Dn=a.useCallback(()=>{oe(!1),ae(!0),K&&K("")},[K]),Pn=a.useCallback(()=>{Ae(Ne=>!Ne)},[]),Yt=a.useCallback(Ne=>{Ne&&Ne(),Ae(!1),Qe(!1)},[]),Cn=a.useCallback(()=>{ne(!1),K&&K("")},[K]);return t.jsxs("div",{className:"header-wrapper",children:[t.jsxs("header",{className:"header",children:[t.jsxs("div",{className:"header-left",children:[t.jsxs("div",{className:"header-brand",children:[t.jsxs("svg",{className:"header-logo",width:24,height:24,viewBox:"0 0 128 128",fill:"none","aria-label":"Fusion logo",role:"img",children:[t.jsx("circle",{cx:"64",cy:"64",r:"52",stroke:"currentColor",strokeWidth:"8"}),t.jsx("path",{d:"M26 101C44 82 62 64 82 45C90 37 98 30 104 24C96 35 89 47 81 60C70 79 57 95 43 108C38 112 32 108 26 101Z",fill:"currentColor"})]}),t.jsx("h1",{className:"logo",children:"Fusion"})]}),be&&$.length>=1&&z&&t.jsxs("div",{className:"mobile-project-switch",ref:bt,children:[t.jsx("button",{className:`mobile-project-switch-trigger${it?" mobile-project-switch-trigger--open":""}`,onClick:()=>Be(Ne=>!Ne),title:"Switch project","aria-label":"Switch project","aria-expanded":it,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:t.jsx(Xt,{size:14,className:`mobile-project-switch-chevron${it?" mobile-project-switch-chevron--open":""}`})}),it&&t.jsx("div",{className:"mobile-project-switch-dropdown",role:"listbox","aria-label":"Select project","data-testid":"mobile-project-switch-dropdown",children:$.map(Ne=>{const at=R?.id===Ne.id,fn=Ep[Ne.status]?.color;return t.jsxs("button",{className:`mobile-project-switch-item${at?" mobile-project-switch-item--current":""}`,onClick:()=>{z(Ne),Be(!1)},role:"option","aria-selected":at,"data-testid":`mobile-project-switch-item-${Ne.id}`,children:[t.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:fn||"var(--text-muted)"}}),t.jsxs("div",{className:"mobile-project-switch-info",children:[t.jsx("span",{className:"mobile-project-switch-name",children:Ne.name}),t.jsx("span",{className:"mobile-project-switch-path",children:Cp(Ne.path)})]}),at&&t.jsx(Hn,{size:14,className:"mobile-project-switch-check"})]},Ne.id)})})]}),!me&&$.length>=1&&B&&t.jsx(Nw,{projects:$,currentProject:R??null,onViewAll:B,onSelectProject:z}),Ot&&t.jsxs("div",{className:`header-node-selector${be?" header-node-selector--mobile":""}`,ref:be?void 0:yt,children:[t.jsx(bw,{node:P??null,showDetails:!be}),!be&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:`btn-icon node-selector-trigger${Xe?" node-selector-trigger--open":""}`,onClick:()=>Ye(Ne=>!Ne),title:"Switch node","aria-label":"Switch node","aria-expanded":Xe,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:t.jsx(vn,{size:12,className:`node-selector-chevron${Xe?" node-selector-chevron--open":""}`})}),Xe&&t.jsxs("div",{className:"node-selector-dropdown",role:"listbox","aria-label":"Select node",children:[t.jsxs("button",{className:`node-selector-option${O?"":" node-selector-option--active"}`,onClick:()=>{j?.(null),Ye(!1)},role:"option","aria-selected":!O,"data-testid":"node-option-local",children:[t.jsx(qi,{status:"online",compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:"Local"})]}),Ft.map(Ne=>t.jsxs("button",{className:`node-selector-option${P?.id===Ne.id?" node-selector-option--active":""}`,onClick:()=>{j?.(Ne),Ye(!1)},role:"option","aria-selected":P?.id===Ne.id,"data-testid":`node-option-${Ne.id}`,children:[t.jsx(qi,{status:Ne.status,compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:Ne.name}),t.jsx("span",{className:"node-selector-option-status",children:Ne.status})]},Ne.id))]})]})]})]}),t.jsxs("div",{className:"header-actions",children:[F&&D&&(N==="board"||N==="list")&&t.jsxs("div",{className:"view-toggle","data-testid":"mobile-view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${N==="board"?" active":""}`,onClick:()=>D("board"),title:"Board view","aria-label":"Board view","aria-pressed":N==="board","data-testid":"mobile-view-toggle-board",children:t.jsx(Hi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${N==="list"?" active":""}`,onClick:()=>D("list"),title:"List view","aria-label":"List view","aria-pressed":N==="list","data-testid":"mobile-view-toggle-list",children:t.jsx(Cc,{size:16})})]}),K&&be&&(F||N==="board"||N==="list")&&!ze&&t.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:_t,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:t.jsx(ki,{size:16})}),jt&&t.jsx("button",{className:"btn-icon",onClick:Jt,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:t.jsx(ki,{size:16})}),be&&F&&o&&t.jsx("button",{className:"btn-icon",onClick:Ne=>o(Ne.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"mobile-header-usage-btn",children:t.jsx(Is,{size:16})}),!F&&D&&t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${N==="board"?" active":""}`,onClick:()=>D("board"),title:"Board view","aria-label":"Board view","aria-pressed":N==="board",children:t.jsx(Hi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${N==="list"?" active":""}`,onClick:()=>D("list"),title:"List view","aria-label":"List view","aria-pressed":N==="list",children:t.jsx(Cc,{size:16})}),T&&t.jsx("button",{className:`view-toggle-btn${N==="agents"?" active":""}`,onClick:()=>D("agents"),title:"Agents view","aria-label":"Agents view","aria-pressed":N==="agents",children:t.jsx(Nn,{size:16})}),t.jsx("button",{className:`view-toggle-btn${N==="missions"?" active":""}`,onClick:()=>D("missions"),title:"Missions view","aria-label":"Missions view","aria-pressed":N==="missions",children:t.jsx(xs,{size:16})}),t.jsx("button",{className:`view-toggle-btn${N==="chat"?" active":""}`,onClick:()=>D("chat"),title:"Chat view","aria-label":"Chat view","aria-pressed":N==="chat",children:t.jsx(wi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${N==="documents"?" active":""}`,onClick:()=>D("documents"),title:"Documents view","aria-label":"Documents view","aria-pressed":N==="documents",children:t.jsx(Ui,{size:16})}),t.jsx("button",{className:`view-toggle-btn${N==="mailbox"?" active":""}`,onClick:()=>D("mailbox"),title:"Mailbox view","aria-label":"Mailbox view","aria-pressed":N==="mailbox",children:t.jsx(pa,{size:16})}),Ut&&t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:Rt,className:`view-toggle-btn${["research","skills","roadmaps","insights","memory","dev-server","devserver"].includes(N)||H?.todoView&&N==="todos"?" active":""}`,onClick:()=>re(Ne=>!Ne),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":Ge,"data-testid":"view-toggle-overflow-trigger",children:t.jsx(Xt,{size:12})}),Ge&&t.jsxs("div",{ref:At,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[H?.researchView&&t.jsxs("button",{className:`view-toggle-overflow-item${N==="research"?" active":""}`,onClick:()=>{D("research"),re(!1)},role:"menuitem","data-testid":"view-overflow-research",children:[t.jsx(ki,{size:14}),t.jsx("span",{children:"Research"})]}),H?.insights&&t.jsxs("button",{className:`view-toggle-overflow-item${N==="insights"?" active":""}`,onClick:()=>{D("insights"),re(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[t.jsx(rs,{size:14}),t.jsx("span",{children:"Insights"})]}),H?.roadmap&&t.jsxs("button",{className:`view-toggle-overflow-item${N==="roadmaps"?" active":""}`,onClick:()=>{D("roadmaps"),re(!1)},role:"menuitem","data-testid":"view-overflow-roadmaps",children:[t.jsx(Ec,{size:14}),t.jsx("span",{children:"Roadmaps"})]}),E&&t.jsxs("button",{className:`view-toggle-overflow-item${N==="skills"?" active":""}`,onClick:()=>{D("skills"),re(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[t.jsx(Gn,{size:14}),t.jsx("span",{children:"Skills"})]}),H?.memoryView&&t.jsxs("button",{className:`view-toggle-overflow-item${N==="memory"?" active":""}`,onClick:()=>{D("memory"),re(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[t.jsx(yo,{size:14}),t.jsx("span",{children:"Memory"})]}),H?.devServerView&&t.jsxs("button",{className:`view-toggle-overflow-item${N==="dev-server"||N==="devserver"?" active":""}`,onClick:()=>{D("devserver"),re(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[t.jsx(mr,{size:14}),t.jsx("span",{children:"Dev Server"}),t.jsx("span",{className:"visually-hidden","data-testid":"view-toggle-dev-server"})]}),H?.todoView&&t.jsxs("button",{className:`view-toggle-overflow-item${N==="todos"?" active":""}`,onClick:()=>{D("todos"),re(!1)},role:"menuitem","data-testid":"view-overflow-todos",children:[t.jsx(rp,{size:14}),t.jsx("span",{children:"Todos"})]})]})]})]}),!me&&o&&t.jsx("button",{className:"btn-icon",onClick:Ne=>o(Ne.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"desktop-header-usage-btn",children:t.jsx(Is,{size:16})}),!me&&c&&t.jsx("button",{className:"btn-icon",onClick:c,title:"System Stats","data-testid":"desktop-header-system-stats-btn",children:t.jsx(mr,{size:16})}),!me&&l&&t.jsx("button",{className:"btn-icon",onClick:l,title:"View Activity Log",children:t.jsx(ur,{size:16})}),!me&&!Q&&t.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:t.jsx(hu,{size:16})}),!me&&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(si,{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})]}),!me&&t.jsxs("div",{className:"terminal-split-btn",ref:Et,children:[t.jsx("button",{className:"btn-icon btn-icon--terminal terminal-split-btn__main",onClick:x,title:"Open Terminal","data-testid":"terminal-toggle-btn",children:t.jsx(mi,{size:16})}),b&&v&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"terminal-split-btn__divider"}),t.jsx("button",{ref:Dt,className:`btn-icon terminal-split-btn__chevron${fe?" btn-icon--active":""}`,onClick:()=>_e(Ne=>!Ne),title:"Scripts","aria-haspopup":"listbox","aria-expanded":fe,"aria-label":"Quick scripts","data-testid":"scripts-btn",children:t.jsx(Xt,{size:12,className:`quick-scripts-dropdown__trigger-chevron${fe?" rotate":""}`})}),fe&&t.jsx("div",{ref:Kt,tabIndex:-1,className:"quick-scripts-dropdown__menu",role:"listbox","aria-label":"Scripts",onKeyDown:ee,"data-testid":"quick-scripts-dropdown",style:Re?{position:"fixed",top:`${Re.top}px`,left:`${Re.left}px`,width:`${Re.width}px`,right:"auto"}:void 0,children:ve?t.jsxs("div",{className:"quick-scripts-dropdown__loading","data-testid":"quick-scripts-loading",children:[t.jsx(ot,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts..."})]}):Tt.length===0?t.jsxs("div",{className:"quick-scripts-dropdown__empty","data-testid":"quick-scripts-empty",children:[t.jsx("div",{className:"quick-scripts-dropdown__empty-icon",children:t.jsx(mi,{size:16})}),t.jsx("p",{children:"No scripts configured"}),t.jsx("button",{className:"quick-scripts-dropdown__empty-action btn",onClick:A,children:"Add your first script"})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-scripts-dropdown__list",children:Tt.map(([Ne,at],fn)=>t.jsxs("button",{className:`quick-scripts-dropdown__item ${De===fn?"highlighted":""}`,onClick:()=>$e(Ne,at),role:"option","aria-selected":De===fn,"data-testid":`quick-script-item-${Ne}`,children:[t.jsx(Sn,{size:14,className:"quick-scripts-dropdown__item-icon"}),t.jsxs("div",{className:"quick-scripts-dropdown__item-info",children:[t.jsx("span",{className:"quick-scripts-dropdown__item-name",children:Ne}),t.jsx("span",{className:"quick-scripts-dropdown__item-command",title:at,children:at.length>50?`${at.slice(0,50)}...`:at})]})]},Ne))}),t.jsx("div",{className:"quick-scripts-dropdown__footer",children:t.jsxs("button",{className:`quick-scripts-dropdown__manage ${Pt&&De===Tt.length?"highlighted":""}`,onClick:A,"data-testid":"quick-scripts-manage",children:[t.jsx(rr,{size:14}),t.jsx("span",{children:"Manage Scripts..."})]})})]})})]})]}),!me&&y&&t.jsx("button",{className:`btn-icon${k?" btn-icon--active":""}`,onClick:y,title:"Browse files","data-testid":"files-toggle-btn",children:t.jsx(Jn,{size:16})}),!me&&h&&t.jsx("button",{className:"btn-icon",onClick:h,title:"Git Manager","data-testid":"git-manager-btn",children:t.jsx(Vs,{size:16})}),!me&&g&&t.jsx("button",{className:"btn-icon",onClick:g,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:t.jsx(Mc,{size:16})}),!me&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{ref:te,className:"btn-icon",onClick:()=>X(Ne=>!Ne),title:"More actions","aria-label":"More actions","aria-expanded":ke,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:t.jsx(wc,{size:16})}),ke&&t.jsxs("div",{ref:Je,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[f&&p!==!1&&t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{f(),X(!1)},role:"menuitem","data-testid":"desktop-overflow-nodes-btn",children:[t.jsx(hr,{size:14}),t.jsx("span",{children:"Nodes"})]}),t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{Yt(m),X(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[t.jsx(Si,{size:14}),t.jsx("span",{children:"Automation"})]})]})]}),t.jsxs("div",{className:"engine-control-split-btn",ref:Ht,children:[t.jsx("button",{className:`btn-icon engine-control-split-btn__main${_?" btn-icon--stopped":""}`,onClick:w,title:_?"Start AI engine":"Stop AI engine","data-testid":"engine-control-main-btn",children:_?t.jsx(Sn,{size:16}):t.jsx(js,{size:16})}),t.jsx("span",{className:"engine-control-split-btn__divider"}),t.jsx("button",{className:`btn-icon engine-control-split-btn__chevron${Te?" btn-icon--active":""}`,onClick:()=>Le(Ne=>!Ne),title:"Engine options","aria-haspopup":"menu","aria-expanded":Te,"data-testid":"engine-control-chevron-btn",children:t.jsx(Xt,{size:12})}),Te&&t.jsx("div",{className:"engine-control-split-btn__menu",role:"menu",children:t.jsxs("button",{className:`engine-control-split-btn__menu-item${S?" engine-control-split-btn__menu-item--active":""}`,onClick:()=>{M?.(),Le(!1)},role:"menuitem",title:S?"Resume scheduling":"Pause triage",disabled:!!_,"data-testid":"engine-control-pause-triage-btn",children:[S?t.jsx(Sn,{size:14}):t.jsx(Hs,{size:14}),t.jsx("span",{children:S?"Resume scheduling":"Pause triage"})]})})]}),!me&&t.jsx("button",{className:"btn-icon",onClick:e,title:"Settings",children:t.jsx(rr,{size:16})}),t.jsx(Jo,{slotId:"header-action",projectId:J}),me&&!F&&t.jsx("button",{ref:we,className:"btn-icon compact-overflow-trigger",onClick:Pn,title:"More header actions","aria-label":"More header actions","aria-expanded":je,"aria-haspopup":"menu",children:t.jsx(wc,{size:16})}),me&&!F&&je&&t.jsxs("div",{ref:Ze,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[$.length>=1&&B&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Yt(B),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[t.jsx(tp,{size:16}),t.jsx("span",{children:"Projects"})]}),y&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Yt(y),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:()=>Yt(r>0&&i?i:s),role:"menuitem","data-testid":"overflow-planning-btn",children:[t.jsxs("span",{className:"mobile-overflow-icon-wrapper",children:[t.jsx(si,{size:16}),r>0&&t.jsx("span",{className:"header-badge header-badge--pulse","data-testid":"overflow-planning-badge",children:r})]}),t.jsx("span",{children:r>0?`Resume planning session (${r})`:"Create a task with AI planning"})]}),h&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Yt(h),role:"menuitem","data-testid":"overflow-git-btn",children:[t.jsx(Vs,{size:16}),t.jsx("span",{children:"Git Manager"})]}),f&&p!==!1&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Yt(f),role:"menuitem","data-testid":"overflow-nodes-btn",children:[t.jsx(hr,{size:16}),t.jsx("span",{children:"Nodes"})]}),!Q&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Yt(n),role:"menuitem",children:[t.jsx(hu,{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:()=>Yt(x),role:"menuitem","data-testid":"overflow-terminal-primary-btn",children:[t.jsx(mi,{size:16}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{className:"mobile-overflow-split-toggle",onClick:()=>Qe(Ne=>!Ne),role:"menuitem","aria-expanded":Oe,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:t.jsx(vn,{size:14,className:`mobile-overflow-chevron${Oe?" mobile-overflow-chevron--open":""}`})})]}),Oe&&t.jsx("div",{className:"mobile-overflow-submenu",role:"menu","aria-label":"Scripts submenu",children:Z?t.jsxs("div",{className:"mobile-overflow-submenu-loading","data-testid":"overflow-scripts-loading",children:[t.jsx(ot,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):Gt.length>0?t.jsxs(t.Fragment,{children:[Gt.map(([Ne,at])=>t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{v&&v(Ne,at),Ae(!1),Qe(!1)},role:"menuitem","data-testid":`overflow-script-item-${Ne}`,children:[t.jsx(Sn,{size:14}),t.jsx("span",{children:Ne})]},Ne)),b&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>Yt(b),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(Bs,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):b&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>Yt(b),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(Bs,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Yt(m),role:"menuitem","data-testid":"overflow-schedules-btn",children:[t.jsx(Si,{size:16}),t.jsx("span",{children:"Automation"})]}),l&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Yt(l),role:"menuitem","data-testid":"overflow-activity-log-btn",children:[t.jsx(ur,{size:16}),t.jsx("span",{children:"View Activity Log"})]}),u&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Yt(u),role:"menuitem","data-testid":"overflow-mailbox-btn",children:[t.jsx(pa,{size:16}),t.jsxs("span",{children:["Mailbox",d>0?` (${d})`:""]})]}),o&&t.jsxs("button",{className:"mobile-overflow-item",onClick:Ne=>Yt(()=>o(Ne.currentTarget.getBoundingClientRect())),role:"menuitem","data-testid":"overflow-usage-btn",children:[t.jsx(Is,{size:16}),t.jsx("span",{children:"View Usage"})]}),g&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Yt(g),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[t.jsx(Mc,{size:16}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Yt(e),role:"menuitem",children:[t.jsx(rr,{size:16}),t.jsx("span",{children:"Settings"})]})]})]})]}),Lt&&mt&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{className:"header-search",children:[t.jsx(ki,{size:14,className:"header-search-icon"}),t.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:U,onChange:Ne=>K(Ne.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:Dn,"aria-label":"Close search",children:t.jsx(Wt,{size:14})})]})}),K&&be&&ze&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{ref:dt,className:"header-search mobile-search-expanded",children:[t.jsx(ki,{size:14,className:"header-search-icon"}),t.jsx("input",{ref:ut,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:U,onChange:Ne=>K(Ne.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:Cn,"aria-label":"Close search",children:t.jsx(Wt,{size:14})})]})})]})}const Cw={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","gridlock"],ntfyDashboardHost:void 0,webhookEnabled:!1,webhookUrl:void 0,webhookFormat:"generic",webhookEvents:[],notificationProviders:[],customProviders:[],defaultProjectId:void 0,setupComplete:void 0,favoriteProviders:void 0,favoriteModels:void 0,openrouterModelSync:!0,updateCheckEnabled:!0,updateCheckFrequency:"daily",showGitHubStarButton:!0,modelOnboardingComplete:void 0,useClaudeCli:void 0,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,researchGlobalEnabled:!0,researchGlobalMaxConcurrentRuns:3,researchGlobalDefaultTimeout:3e5,researchGlobalMaxSourcesPerRun:20,researchGlobalMaxSynthesisRounds:2,researchWebSearchProvider:"none",researchSearxngUrl:void 0,researchBraveApiKey:void 0,researchGoogleSearchApiKey:void 0,researchGoogleSearchCx:void 0,researchTavilyApiKey:void 0,researchGitHubEnabled:!1,researchLocalDocsEnabled:!0,researchMaxSearchResults:10,researchFetchTimeoutMs:3e4,researchUserAgent:"FusionResearchBot/1.0"},Ew={globalPause:!1,globalPauseReason:void 0,enginePaused:!1,maxConcurrent:2,maxTriageConcurrent:2,globalMaxConcurrent:4,maxWorktrees:4,pollIntervalMs:15e3,heartbeatMultiplier:1,groupOverlappingFiles:!0,overlapIgnorePaths:[],autoMerge:!0,mergeStrategy:"direct",requirePrApproval:!1,pushAfterMerge:!1,pushRemote:"origin",unavailableNodePolicy:"block",defaultNodeId:void 0,worktreeInitCommand:void 0,testCommand:void 0,buildCommand:void 0,recycleWorktrees:!1,worktreeNaming:"random",taskPrefix:"FN",includeTaskIdInCommit:!0,commitAuthorEnabled:!0,commitAuthorName:"Fusion",commitAuthorEmail:"noreply@runfusion.ai",planningProvider:void 0,planningModelId:void 0,planningFallbackProvider:void 0,planningFallbackModelId:void 0,defaultProviderOverride:void 0,defaultModelIdOverride:void 0,executionProvider:void 0,executionModelId:void 0,validatorProvider:void 0,validatorModelId:void 0,validatorFallbackProvider:void 0,validatorFallbackModelId:void 0,modelPresets:[],autoSelectModelPreset:!1,defaultPresetBySize:{},autoResolveConflicts:!0,smartConflictResolution:!0,worktreeRebaseBeforeMerge:!0,worktreeRebaseRemote:"",worktreeRebaseLocalBase:!0,mergeConflictStrategy:"smart-prefer-main",workflowStepTimeoutMs:36e4,strictScopeEnforcement:!1,buildRetryCount:0,verificationFixRetries:3,buildTimeoutMs:3e5,requirePlanApproval:!1,specStalenessEnabled:!1,specStalenessMaxAgeMs:360*60*1e3,taskStuckTimeoutMs:void 0,aiSessionTtlMs:10080*60*1e3,aiSessionCleanupIntervalMs:3600*1e3,autoUnpauseEnabled:!0,autoUnpauseBaseDelayMs:3e5,autoUnpauseMaxDelayMs:36e5,maxStuckKills:6,maxPostReviewFixes:1,maxSpawnedAgentsPerParent:5,maxSpawnedAgentsGlobal:20,maintenanceIntervalMs:9e5,autoArchiveDoneTasksEnabled:!0,autoArchiveDoneAfterMs:2880*60*1e3,archiveAgentLogMode:"compact",autoUpdatePrStatus:!1,githubCommentOnDone:!1,githubCommentTemplate:void 0,autoBackupEnabled:!1,autoBackupSchedule:"0 2 * * *",autoBackupRetention:7,autoBackupDir:".fusion/backups",autoSummarizeTitles:!1,useAiMergeCommitSummary:!0,titleSummarizerProvider:void 0,titleSummarizerModelId:void 0,titleSummarizerFallbackProvider:void 0,titleSummarizerFallbackModelId:void 0,scripts:void 0,setupScript:void 0,insightExtractionEnabled:!1,insightExtractionSchedule:"0 2 * * *",insightExtractionMinIntervalMs:864e5,memoryEnabled:!0,memoryBackendType:"qmd",memoryAutoSummarizeEnabled:!1,memoryAutoSummarizeThresholdChars:5e4,memoryAutoSummarizeSchedule:"0 3 * * *",memoryDreamsEnabled:!1,memoryDreamsSchedule:"0 4 * * *",tokenCap:void 0,runStepsInNewSessions:!1,maxParallelSteps:2,missionStaleThresholdMs:6e5,missionMaxTaskRetries:3,missionHealthCheckIntervalMs:3e5,agentPrompts:void 0,promptOverrides:void 0,remoteAccess:{activeProvider:null,providers:{tailscale:{enabled:!1,hostname:"",targetPort:0,acceptRoutes:!1},cloudflare:{enabled:!1,quickTunnel:!0,tunnelName:"",tunnelToken:null,ingressUrl:""}},tokenStrategy:{persistent:{enabled:!0,token:null},shortLived:{enabled:!1,ttlMs:9e5,maxTtlMs:864e5}},lifecycle:{rememberLastRunning:!1,wasRunningOnShutdown:!1,lastRunningProvider:null}},reflectionEnabled:!1,reflectionIntervalMs:36e5,reflectionAfterTask:!0,reviewHandoffPolicy:"disabled",showQuickChatFAB:!1,researchEnabled:!0,researchMaxConcurrentRuns:3,researchDefaultTimeout:3e5,researchMaxSourcesPerRun:20,researchMaxSynthesisRounds:2,experimentalFeatures:{}},_w=Object.freeze(Object.keys(Cw)),Mw=Object.freeze(Object.keys(Ew));function vL(e){return _w.includes(e)}function yL(e){return Mw.includes(e)}function ye(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Aw(e){return!!(e?.provider&&e?.modelId)}function Ci(...e){for(const n of e)if(Aw(n))return{provider:n.provider,modelId:n.modelId};return{}}function Yo(e){return Ci({provider:e?.defaultProviderOverride,modelId:e?.defaultModelIdOverride},{provider:e?.defaultProvider,modelId:e?.defaultModelId})}function Rw(e){return Ci({provider:e?.executionProvider,modelId:e?.executionModelId},{provider:e?.executionGlobalProvider,modelId:e?.executionGlobalModelId},Yo(e))}function Tw(e){return Ci({provider:e?.planningProvider,modelId:e?.planningModelId},{provider:e?.planningGlobalProvider,modelId:e?.planningGlobalModelId},Yo(e))}function Pw(e){return Ci({provider:e?.validatorProvider,modelId:e?.validatorModelId},{provider:e?.validatorGlobalProvider,modelId:e?.validatorGlobalModelId},Yo(e))}function jL(e){return Ci({provider:e?.titleSummarizerProvider,modelId:e?.titleSummarizerModelId},{provider:e?.titleSummarizerGlobalProvider,modelId:e?.titleSummarizerGlobalModelId},{provider:e?.planningProvider,modelId:e?.planningModelId},Yo(e))}function _p(e,n){return Ci({provider:e.modelProvider,modelId:e.modelId},Rw(n))}function Mp(e,n){return Ci({provider:e.validatorModelProvider,modelId:e.validatorModelId},Pw(n))}function Ap(e,n){return Ci({provider:e.planningModelProvider,modelId:e.planningModelId},Tw(n))}const kL=["off","minimal","low","medium","high"],Fi=["triage","todo","in-progress","in-review","done","archived"],md=["low","normal","high","urgent"],ws="normal",Iw=["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"],Fn={triage:"Planning",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},$w={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"},Ic={triage:["todo"],todo:["in-progress","triage"],"in-progress":["in-review","todo","triage","done"],"in-review":["done","in-progress","todo","triage"],done:["todo","triage","archived"],archived:["done"]};function Dw(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 Lw(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 zw({isOpen:e,options:n,onConfirm:s,onCancel:i}){const r=a.useRef(null);return a.useEffect(()=>{if(!e)return;r.current?.focus();const o=l=>{l.key==="Escape"&&(l.preventDefault(),i())};return document.addEventListener("keydown",o),()=>document.removeEventListener("keydown",o)},[e,i]),!e||!n?null:t.jsx("div",{className:"modal-overlay open",onClick:i,children:t.jsxs("div",{className:"modal confirm-dialog",onClick:o=>o.stopPropagation(),role:"dialog","aria-modal":"true","aria-label":n.title,children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:n.title}),t.jsx("button",{className:"modal-close",onClick:i,"aria-label":"Close confirmation dialog",children:"×"})]}),t.jsx("div",{className:"confirm-dialog__body",children:n.message}),t.jsxs("div",{className:"modal-actions confirm-dialog__actions",children:[t.jsx("button",{ref:r,className:"btn",onClick:i,children:n.cancelLabel??"Cancel"}),t.jsx("button",{className:`btn ${n.danger?"btn-danger":"btn-primary"}`,onClick:s,children:n.confirmLabel??"Confirm"})]})]})})}const Rp=a.createContext(null);function Fw({children:e}){const[n,s]=a.useState([]),i=a.useRef([]),r=a.useCallback(d=>{s(m=>{const h=d(m);return i.current=h,h})},[]),o=a.useCallback(d=>new Promise(m=>{r(h=>[...h,{options:d,resolve:m}])}),[r]),l=a.useCallback(d=>{const m=i.current[0];m&&(m.resolve(d),r(h=>h.slice(1)))},[r]),c=n[0]??null,u=a.useMemo(()=>({confirm:o}),[o]);return vo.createElement(Rp.Provider,{value:u},e,vo.createElement(zw,{isOpen:c!==null,options:c?.options??null,onConfirm:()=>l(!0),onCancel:()=>l(!1)}))}function Ws(){const e=a.useContext(Rp);return e||{confirm:async n=>!1}}function Ow(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 Tp({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(ks,{size:12}),t.jsxs("span",{children:["#",e.number]})]}),n&&t.jsxs("span",{className:`card-github-badge ${Ow(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,onClick:r,children:[t.jsx(Oo,{size:12}),t.jsxs("span",{children:["#",n.number]})]})]})}function Kr(e,n){return`${e??"default"}:${n}`}class Uw{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=Kr(this.projectId,o);this.subscriptionsByTask.set(l,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const i=Kr(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=Kr(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(ii(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=Kr(this.projectId,l.taskId),u=this.badgeUpdates.get(c);this.badgeUpdates.set(c,{prInfo:pu(l,"prInfo")?l.prInfo??null:u?.prInfo,issueInfo:pu(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 Ii=new Uw;let Bw=0;function pu(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function Pp(e){const n=a.useRef(null);n.current===null&&(n.current=`badge-hook-${Bw++}`);const s=a.useSyncExternalStore(o=>Ii.subscribe(o),()=>Ii.getSnapshot(),()=>Ii.getSnapshot()),i=a.useCallback(o=>{Ii.subscribeTask(n.current,o)},[]),r=a.useCallback(o=>{Ii.unsubscribeTask(n.current,o)},[]);return a.useEffect(()=>{Ii.setProjectId(e??null)},[e]),a.useEffect(()=>()=>{Ii.cleanupHook(n.current)},[]),{badgeUpdates:s.badgeUpdates,isConnected:s.isConnected,subscribeToBadge:i,unsubscribeFromBadge:r}}function Co(e,n,s,i){return e===void 0||!n?s:!i||n>=i?e??void 0:s}function Hw({taskId:e,prInfo:n,issueInfo:s,updatedAt:i,isInViewport:r,projectId:o}){const{badgeUpdates:l,subscribeToBadge:c,unsubscribeFromBadge:u}=Pp(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=Co(m?.prInfo,m?.timestamp,n,n?.lastCheckedAt??i),f=Co(m?.issueInfo,m?.timestamp,s,s?.lastCheckedAt??i);return!h&&!f?null:t.jsx(Tp,{prInfo:h,issueInfo:f})}const qw=a.memo(Hw);qw.displayName="TaskCardBadge";const Vw={sm:16,md:20,lg:24};function Ww({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 fu({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 Qs({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 Kw({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 gu({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 Gw({size:e,color:n,label:s="Z.ai"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"zai-icon","aria-label":s,children:t.jsx("path",{d:"M3 5H21V8.5L7 17.5H21V21H3V17.5L17 8.5H3Z",fill:n})})}function xl({size:e,color:n,label:s="Kimi"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"kimi-icon","aria-label":s,children:t.jsx("path",{d:"M12 3a9 9 0 1 0 9 9c0-.46-.04-.92-.1-1.36a5.39 5.39 0 0 1-4.4 2.26 5.4 5.4 0 0 1-3.14-9.8c.2-.07.4-.1.64-.1z",fill:n})})}function bu({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 xu({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 vu({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 za({size:e,color:n,label:s="Qwen"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"qwen-icon","aria-label":s,children:[t.jsx("circle",{cx:"11",cy:"12",r:"7.5",stroke:n,strokeWidth:"2",fill:"none"}),t.jsx("path",{d:"M14 15 L21 22",stroke:n,strokeWidth:"2.6",strokeLinecap:"round"})]})}function yu({size:e,color:n,label:s="LM Studio"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"lmstudio-icon","aria-label":s,children:[t.jsx("rect",{x:"2",y:"2",width:"20",height:"20",rx:"4.5",fill:n}),t.jsx("text",{x:"12",y:"16",textAnchor:"middle",fontFamily:"-apple-system, system-ui, sans-serif",fontSize:"9.5",fontWeight:"700",fill:"var(--provider-icon-contrast)",letterSpacing:"-0.4",children:"LM"})]})}function vl({size:e,color:n,label:s="Hugging Face"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"huggingface-icon","aria-label":s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"9",fill:n}),t.jsx("circle",{cx:"8.5",cy:"10.5",r:"1.4",fill:"var(--provider-icon-contrast)"}),t.jsx("circle",{cx:"15.5",cy:"10.5",r:"1.4",fill:"var(--provider-icon-contrast)"}),t.jsx("path",{d:"M7.5 14.5 Q12 18.5 16.5 14.5",stroke:"var(--provider-icon-contrast)",strokeWidth:"1.6",strokeLinecap:"round",fill:"none"}),t.jsx("path",{d:"M3.5 16 Q5 13.5 7 14.5 M20.5 16 Q19 13.5 17 14.5",stroke:n,strokeWidth:"1.8",strokeLinecap:"round",fill:"none"})]})}function ju({size:e,color:n,label:s="Mistral AI"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"mistral-icon","aria-label":s,children:t.jsx("path",{d:"M2 4h3v16H2zM7 4h3v12H7zM12 4h3v16h-3zM17 4h3v8h-3zM7 16h3v4H7zM17 8h3v12h-3z",fill:n})})}function yl({size:e,color:n,label:s="Azure"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"azure-icon","aria-label":s,children:t.jsx("path",{d:"M10.4 3.2 4.5 16.6l3.5.5L13 6 9.6 19.5h9.9zM3 19.5l4.6.6 8.6-1.7-7-1.6z",fill:n})})}function Jw({size:e,color:n,label:s="Cerebras"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"cerebras-icon","aria-label":s,children:[t.jsx("path",{d:"M19.5 6.5A8.5 8.5 0 1 0 19.5 17.5",stroke:n,strokeWidth:"2.4",strokeLinecap:"round",fill:"none"}),t.jsx("path",{d:"M16.5 9A4.6 4.6 0 1 0 16.5 15",stroke:n,strokeWidth:"1.8",strokeLinecap:"round",fill:"none"}),t.jsx("circle",{cx:"11",cy:"12",r:"1.6",fill:n})]})}function Yw({size:e,color:n,label:s="Groq"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"groq-icon","aria-label":s,children:t.jsx("path",{d:"M14 2 4 13h6l-2 9 10-11h-6z",fill:n})})}function ku({size:e,color:n,label:s="Vercel"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"vercel-icon","aria-label":s,children:t.jsx("path",{d:"M12 2 22 21H2z",fill:n})})}function jl({size:e,color:n,label:s="Fireworks AI"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"fireworks-icon","aria-label":s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"2.4",fill:n}),t.jsx("circle",{cx:"12",cy:"3.5",r:"1.4",fill:n}),t.jsx("circle",{cx:"12",cy:"20.5",r:"1.4",fill:n}),t.jsx("circle",{cx:"3.5",cy:"12",r:"1.4",fill:n}),t.jsx("circle",{cx:"20.5",cy:"12",r:"1.4",fill:n}),t.jsx("circle",{cx:"6",cy:"6",r:"1.2",fill:n}),t.jsx("circle",{cx:"18",cy:"6",r:"1.2",fill:n}),t.jsx("circle",{cx:"6",cy:"18",r:"1.2",fill:n}),t.jsx("circle",{cx:"18",cy:"18",r:"1.2",fill:n}),t.jsx("path",{d:"M12 5.5v3M12 15.5v3M5.5 12h3M15.5 12h3",stroke:n,strokeWidth:"1.4",strokeLinecap:"round"})]})}function Qw({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 wu({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 kl({size:e,color:n,label:s="Hermes"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 64 64",fill:"none",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":s,children:[t.jsx("rect",{x:"30",y:"10",width:"4",height:"46",rx:"2",fill:n}),t.jsx("path",{d:"M30 18 C24 14, 14 14, 10 18 C14 16, 22 16, 28 20",fill:n,opacity:"0.9"}),t.jsx("path",{d:"M30 22 C26 19, 18 19, 14 22 C18 20, 24 20, 28 24",fill:n,opacity:"0.7"}),t.jsx("path",{d:"M34 18 C40 14, 50 14, 54 18 C50 16, 42 16, 36 20",fill:n,opacity:"0.9"}),t.jsx("path",{d:"M34 22 C38 19, 46 19, 50 22 C46 20, 40 20, 36 24",fill:n,opacity:"0.7"}),t.jsx("path",{d:"M32 48 C22 44, 20 38, 26 34 C20 36, 18 42, 24 46 C18 40, 22 30, 30 28 C24 32, 22 38, 28 42",fill:"none",stroke:n,strokeWidth:"2.5",strokeLinecap:"round"}),t.jsx("path",{d:"M32 48 C42 44, 44 38, 38 34 C44 36, 46 42, 40 46 C46 40, 42 30, 34 28 C40 32, 42 38, 36 42",fill:"none",stroke:n,strokeWidth:"2.5",strokeLinecap:"round",opacity:"0.8"}),t.jsx("circle",{cx:"32",cy:"10",r:"4",fill:n})]})}function Nu({size:e,label:n="OpenClaw"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":n,children:[t.jsx("rect",{width:"16",height:"16",fill:"none"}),t.jsxs("g",{fill:"#3a0a0d",children:[t.jsx("rect",{x:"1",y:"5",width:"1",height:"3"}),t.jsx("rect",{x:"2",y:"4",width:"1",height:"1"}),t.jsx("rect",{x:"2",y:"8",width:"1",height:"1"}),t.jsx("rect",{x:"3",y:"3",width:"1",height:"1"}),t.jsx("rect",{x:"3",y:"9",width:"1",height:"1"}),t.jsx("rect",{x:"4",y:"2",width:"1",height:"1"}),t.jsx("rect",{x:"4",y:"10",width:"1",height:"1"}),t.jsx("rect",{x:"5",y:"2",width:"6",height:"1"}),t.jsx("rect",{x:"11",y:"2",width:"1",height:"1"}),t.jsx("rect",{x:"12",y:"3",width:"1",height:"1"}),t.jsx("rect",{x:"12",y:"9",width:"1",height:"1"}),t.jsx("rect",{x:"13",y:"4",width:"1",height:"1"}),t.jsx("rect",{x:"13",y:"8",width:"1",height:"1"}),t.jsx("rect",{x:"14",y:"5",width:"1",height:"3"}),t.jsx("rect",{x:"5",y:"11",width:"6",height:"1"}),t.jsx("rect",{x:"4",y:"12",width:"1",height:"1"}),t.jsx("rect",{x:"11",y:"12",width:"1",height:"1"}),t.jsx("rect",{x:"3",y:"13",width:"1",height:"1"}),t.jsx("rect",{x:"12",y:"13",width:"1",height:"1"}),t.jsx("rect",{x:"5",y:"14",width:"6",height:"1"})]}),t.jsxs("g",{fill:"#ff4f40",children:[t.jsx("rect",{x:"5",y:"3",width:"6",height:"1"}),t.jsx("rect",{x:"4",y:"4",width:"8",height:"1"}),t.jsx("rect",{x:"3",y:"5",width:"10",height:"1"}),t.jsx("rect",{x:"3",y:"6",width:"10",height:"1"}),t.jsx("rect",{x:"3",y:"7",width:"10",height:"1"}),t.jsx("rect",{x:"4",y:"8",width:"8",height:"1"}),t.jsx("rect",{x:"5",y:"9",width:"6",height:"1"}),t.jsx("rect",{x:"5",y:"12",width:"6",height:"1"}),t.jsx("rect",{x:"6",y:"13",width:"4",height:"1"})]}),t.jsxs("g",{fill:"#ff775f",children:[t.jsx("rect",{x:"1",y:"6",width:"2",height:"1"}),t.jsx("rect",{x:"2",y:"5",width:"1",height:"1"}),t.jsx("rect",{x:"2",y:"7",width:"1",height:"1"}),t.jsx("rect",{x:"13",y:"6",width:"2",height:"1"}),t.jsx("rect",{x:"13",y:"5",width:"1",height:"1"}),t.jsx("rect",{x:"13",y:"7",width:"1",height:"1"})]}),t.jsxs("g",{fill:"#081016",children:[t.jsx("rect",{x:"6",y:"5",width:"1",height:"1"}),t.jsx("rect",{x:"9",y:"5",width:"1",height:"1"})]}),t.jsxs("g",{fill:"#f5fbff",children:[t.jsx("rect",{x:"6",y:"4",width:"1",height:"1"}),t.jsx("rect",{x:"9",y:"4",width:"1",height:"1"})]})]})}function wl({size:e,color:n,label:s="Paperclip"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":s,children:t.jsx("path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",stroke:n,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}function Su({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 Xw={anthropic:{component:Ww,color:"var(--provider-anthropic)"},"claude-cli":{component:Su,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"pi-claude-cli":{component:Su,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},openai:{component:fu,color:"var(--provider-openai)"},"openai-codex":{component:fu,color:"var(--provider-openai)",label:"OpenAI Codex"},google:{component:Qs,color:"var(--provider-gemini)"},gemini:{component:Qs,color:"var(--provider-gemini)"},"google-antigravity":{component:Qs,color:"var(--provider-gemini)",label:"Google Gemini"},antigravity:{component:Qs,color:"var(--provider-gemini)",label:"Google Gemini"},"google-vertex":{component:Qs,color:"var(--provider-gemini)",label:"Google Vertex AI"},vertex:{component:Qs,color:"var(--provider-gemini)",label:"Google Vertex AI"},"google-cloud-code":{component:Qs,color:"var(--provider-gemini)",label:"Google Cloud Code"},"cloud-code":{component:Qs,color:"var(--provider-gemini)",label:"Google Cloud Code"},"google-gemini-cli":{component:Qs,color:"var(--provider-gemini)",label:"Google Gemini CLI"},"google-generative-ai":{component:Qs,color:"var(--provider-gemini)",label:"Google Generative AI"},ollama:{component:Kw,color:"var(--text)"},github:{component:wu,color:"var(--text)"},"github-copilot":{component:wu,color:"var(--text)",label:"GitHub Copilot"},openrouter:{component:Qw,color:"var(--provider-openrouter)"},minimax:{component:gu,color:"var(--provider-minimax)"},"minimax-cn":{component:gu,color:"var(--provider-minimax)",label:"MiniMax (CN)"},zai:{component:Gw,color:"var(--provider-zai)"},kimi:{component:xl,color:"var(--provider-kimi)"},moonshot:{component:xl,color:"var(--provider-kimi)"},"kimi-coding":{component:xl,color:"var(--provider-kimi)",label:"Kimi"},bedrock:{component:bu,color:"var(--provider-bedrock)"},"amazon-bedrock":{component:bu,color:"var(--provider-bedrock)",label:"Amazon Bedrock"},xai:{component:xu,color:"var(--text)"},grok:{component:xu,color:"var(--text)",label:"xAI"},opencode:{component:vu,color:"var(--provider-opencode)"},"opencode-go":{component:vu,color:"var(--provider-opencode)",label:"Opencode (Go)"},qwen:{component:za,color:"var(--provider-qwen)"},"qwen-ai":{component:za,color:"var(--provider-qwen)",label:"Qwen"},"qwen-coder":{component:za,color:"var(--provider-qwen)",label:"Qwen Coder"},alibaba:{component:za,color:"var(--provider-qwen)",label:"Qwen"},tongyi:{component:za,color:"var(--provider-qwen)",label:"Qwen"},lmstudio:{component:yu,color:"var(--provider-lmstudio)",label:"LM Studio"},"lm-studio":{component:yu,color:"var(--provider-lmstudio)",label:"LM Studio"},huggingface:{component:vl,color:"var(--provider-huggingface)",label:"Hugging Face"},"hugging-face":{component:vl,color:"var(--provider-huggingface)",label:"Hugging Face"},hf:{component:vl,color:"var(--provider-huggingface)",label:"Hugging Face"},mistral:{component:ju,color:"var(--provider-mistral)",label:"Mistral AI"},"mistral-ai":{component:ju,color:"var(--provider-mistral)",label:"Mistral AI"},azure:{component:yl,color:"var(--provider-azure)"},"azure-openai":{component:yl,color:"var(--provider-azure)",label:"Azure OpenAI"},"azure-openai-responses":{component:yl,color:"var(--provider-azure)",label:"Azure OpenAI"},fireworks:{component:jl,color:"var(--provider-fireworks)",label:"Fireworks AI"},"fireworks-ai":{component:jl,color:"var(--provider-fireworks)",label:"Fireworks AI"},fireworksai:{component:jl,color:"var(--provider-fireworks)",label:"Fireworks AI"},cerebras:{component:Jw,color:"var(--provider-cerebras)"},groq:{component:Yw,color:"var(--provider-groq)"},vercel:{component:ku,color:"var(--provider-vercel)"},"vercel-ai-gateway":{component:ku,color:"var(--provider-vercel)",label:"Vercel AI Gateway"},hermes:{component:kl,color:"var(--provider-hermes)",label:"Hermes"},"hermes-agent":{component:kl,color:"var(--provider-hermes)",label:"Hermes"},hermesagent:{component:kl,color:"var(--provider-hermes)",label:"Hermes"},openclaw:{component:Nu,color:"var(--provider-openclaw)",label:"OpenClaw"},"open-claw":{component:Nu,color:"var(--provider-openclaw)",label:"OpenClaw"},paperclip:{component:wl,color:"var(--provider-paperclip)",label:"Paperclip"},paperclipai:{component:wl,color:"var(--provider-paperclip)",label:"Paperclip"},"paperclip-ai":{component:wl,color:"var(--provider-paperclip)",label:"Paperclip"}};function On({provider:e,size:n="sm"}){const s=e.toLowerCase(),i=Xw[s],r=i?.component,o=i?.color??"var(--text-muted)",l=i?.label,c=Vw[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(vb,{size:c})})}const As={data:new Map,pendingPromise:null,lastFetchTime:null},Zw=5e3;function fo(e,n){return n?`${n}::${e}`:e}function eN(e,n){const s=As.data.get(fo(e,n));if(!(!s||Date.now()-s.timestamp>Zw))return s}function tN(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 Py(c,e)}catch(h){d=h instanceof Error?h:new Error(String(h));const f=ye(h);if(f?.includes("429")||f?.toLowerCase().includes("rate limit")){const p=Math.min(1e3*Math.pow(2,m),3e4);await new Promise(g=>setTimeout(g,p));continue}break}if(d)throw d;return{}},[e]),o=a.useCallback(async c=>{if(c.length===0)return;const d=Date.now()-5e3;if(c.every(f=>{const p=As.data.get(fo(f,e));return p&&p.timestamp>d})&&As.lastFetchTime&&As.lastFetchTime>d)return;if(i.current&&(clearTimeout(i.current),i.current=null),As.pendingPromise){s(!0);try{await As.pendingPromise}finally{s(!1)}return}s(!0);const h=r(c);As.pendingPromise=h;try{const f=await h,p=Date.now();for(const[g,b]of Object.entries(f))As.data.set(fo(g,e),{result:b,timestamp:p});As.lastFetchTime=p}catch{}finally{As.pendingPromise=null,s(!1)}},[r,e]),l=a.useCallback(c=>As.data.get(fo(c,e)),[e]);return{fetchBatch:o,isLoading:n,lastFetchTime:As.lastFetchTime,getBatchData:l}}const $c=new Map,nN=3e4;function Ip(e,n,s,i){return`${e}:${n??""}:${s??""}:${i??""}`}function sN(e,n,s,i){const r=Ip(e,n,s,i),o=$c.get(r);return o?Date.now()>o.expiresAt?($c.delete(r),null):o.stats:null}function iN(e,n,s,i,r){const o=Ip(e,n,s,i);$c.set(o,{stats:r,expiresAt:Date.now()+nN})}function aN(e,n,s,i,r={}){const o=r.enabled??!0,l=r.worktree,c=r.stepVersion,u=r.pollIntervalMs,[d,m]=a.useState(null),[h,f]=a.useState(!1);return a.useEffect(()=>{if(!o){m(null),f(!1);return}const p=n==="done"&&!!s,g=(n==="in-progress"||n==="in-review")&&!!l;if(!e||!p&&!g){m(null),f(!1);return}const b=g?l:void 0,v=c!==void 0?String(c):void 0;let x=!1;async function y(_=!1){if(!_){const S=sN(e,i,b,v);if(S){x||(m(S),f(!1));return}}f(!0);try{const S=await yp(e,b,i);x||(m(S.stats),iN(e,i,b,v,S.stats))}catch{x||m(null)}finally{x||f(!1)}}y();let k;return u&&g&&(k=setInterval(()=>{y(!0)},u)),()=>{x=!0,k&&clearInterval(k)}},[e,n,s,i,o,l,c,u]),{stats:d,loading:h}}const rN=new Set(["failed","stuck-killed"]);function Eo(e,n,s){if(e.column!=="in-progress"||e.status&&rN.has(e.status)||!n||n<=0)return!1;const i=new Date(e.updatedAt).getTime();return(s??Date.now())-i>n}function oN(e){switch(e){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function lN(e){return e==="done"||e==="skipped"}function cN(e,n,s){const i=s?.get(e)?.trim();if(i)return i;const r=n?.workflowStepName?.trim();return r||e}function $p(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:cN(u,d,n),status:d?oN(d.status):"pending",source:"workflow",phase:d?.phase??"pre-merge"}}),o=[...s,...r],l=o.length,c=o.filter(u=>lN(u.status)).length;return{total:l,completed:c,items:o}}function dN(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 Dp(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??""}
|
|
616
|
-
${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:dN(n)}})}function uN(e){if(!e||e.length===0)return null;let n=0,s=0;for(const i of Dp(e))typeof i.durationMs=="number"&&(n+=i.durationMs,s+=1);return s>0?n:null}const Dc=new Map;async function mN(e,n){const s=Dc.get(e);if(s)return s;try{const i=await jp(e,n);return Dc.set(e,i.title),i.title}catch{return e}}const Cu=12;function hN(e){return e.length<=Cu?e:e.slice(0,Cu-3)+"..."}const Lc=new Map;async function pN(e,n){const s=Lc.get(e);if(s)return s;try{const i=await xp(e,n);return Lc.set(e,i.name),i.name}catch{return e}}function fN(e){return typeof e=="string"&&md.includes(e)?e:ws}function gN(e,n){return e.length<=n?e:e.slice(0,n-3)+"..."}const bN=new Set(["triage","todo"]),Eu=new Set(["planning","researching","executing","finalizing","merging"]),_u=new Set(["merging","merging-pr"]),xN={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"},vN=new Set(["in-progress","in-review","done"]),yN=3e4;function Vi(e){if(!e)return null;const n=Date.parse(e);return Number.isFinite(n)?n:null}function jN(e){const n=Vi(e.columnMovedAt??e.updatedAt);if(n==null)return null;const s=Date.now();return n>s?null:n}function Mu(e,n){const s=Vi(e.columnMovedAt??e.updatedAt);return s==null?null:Math.max(0,n-s)}function Gr(e,n){const s=Vi(e.executionStartedAt);if(s==null)return null;const i=Vi(e.executionCompletedAt),r=i!=null&&i>=s?i:n;return Math.max(0,r-s)}function kN(e,n){const s=e.workflowStepResults;if(!s||s.length===0)return null;let i=0,r=0;for(const o of s){if(!o.startedAt)continue;const l=Vi(o.startedAt);if(l==null)continue;let c;if(o.completedAt){const u=Vi(o.completedAt);if(u==null||u<l)continue;c=u}else c=Math.max(l,n);i+=c-l,r+=1}return r>0?i:null}function Jr(e,n){const s=typeof e.timedExecutionMs=="number"?e.timedExecutionMs:uN(e.log),i=kN(e,n);return s==null&&i==null?null:(s??0)+(i??0)}function Au(e){if(!Number.isFinite(e)||e<0)return"";if(e<6e4)return"<1m";const n=Math.floor(e/6e4);if(n<60)return`${n}m`;const s=Math.floor(n/60);return s<24?`${s}h`:`${Math.floor(s/24)}d`}function wN(e){if(!Number.isFinite(e)||e<0||e===0)return"";const n=Math.ceil(e/6e4);if(n<59)return`${n}m`;const s=Math.ceil(e/36e5);return s<24?`${s}h`:`${Math.ceil(e/864e5)}d`}function Ru(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 NN(e,n){return e.length!==n.length?!1:e.every((s,i)=>s.name===n[i]?.name&&s.status===n[i]?.status)}function SN(e,n){return e.length!==n.length?!1:e.every((s,i)=>s===n[i])}function CN(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>s===n[i])}function EN(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 _N(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 MN(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 AN(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 RN(e,n){const s=e.task,i=n.task;return e.queued===n.queued&&e.projectId===n.projectId&&e.globalPaused===n.globalPaused&&e.taskStuckTimeoutMs===n.taskStuckTimeoutMs&&e.onOpenDetail===n.onOpenDetail&&e.addToast===n.addToast&&e.onUpdateTask===n.onUpdateTask&&e.onArchiveTask===n.onArchiveTask&&e.onUnarchiveTask===n.onUnarchiveTask&&e.onDeleteTask===n.onDeleteTask&&e.onRetryTask===n.onRetryTask&&e.onOpenDetailWithTab===n.onOpenDetailWithTab&&e.onOpenMission===n.onOpenMission&&e.onMoveTask===n.onMoveTask&&e.workflowStepNameLookup===n.workflowStepNameLookup&&s.id===i.id&&s.title===i.title&&s.description===i.description&&s.column===i.column&&s.columnMovedAt===i.columnMovedAt&&s.timedExecutionMs===i.timedExecutionMs&&s.updatedAt===i.updatedAt&&s.createdAt===i.createdAt&&s.status===i.status&&s.priority===i.priority&&s.executionMode===i.executionMode&&s.paused===i.paused&&s.error===i.error&&s.size===i.size&&s.blockedBy===i.blockedBy&&s.worktree===i.worktree&&s.baseBranch===i.baseBranch&&s.breakIntoSubtasks===i.breakIntoSubtasks&&s.currentStep===i.currentStep&&s.modelProvider===i.modelProvider&&s.modelId===i.modelId&&s.validatorModelProvider===i.validatorModelProvider&&s.validatorModelId===i.validatorModelId&&s.planningModelProvider===i.planningModelProvider&&s.planningModelId===i.planningModelId&&s.reviewLevel===i.reviewLevel&&s.missionId===i.missionId&&s.assignedAgentId===i.assignedAgentId&&s.mergeRetries===i.mergeRetries&&MN(s.attachments,i.attachments)&&AN(s.comments,i.comments)&&SN(s.dependencies,i.dependencies)&&NN(s.steps,i.steps)&&CN(s.enabledWorkflowSteps,i.enabledWorkflowSteps)&&_N(s.workflowStepResults,i.workflowStepResults)&&Ru(s.prInfo,i.prInfo)&&Ru(s.issueInfo,i.issueInfo)}function TN({task:e,projectId:n,queued:s,onOpenDetail:i,addToast:r,globalPaused:o,onUpdateTask:l,onArchiveTask:c,onUnarchiveTask:u,onDeleteTask:d,onRetryTask:m,onOpenDetailWithTab:h,taskStuckTimeoutMs:f,onOpenMission:p,onMoveTask:g,lastFetchTimeMs:b,workflowStepNameLookup:v}){const[x,y]=a.useState(!1),[k,_]=a.useState(!1),[S,w]=a.useState(!1),[M,N]=a.useState(e.description||""),[D,E]=a.useState(!1),[T,U]=a.useState(e.column==="in-progress"||e.column==="triage"&&e.steps.some(A=>A.status==="done"||A.status==="skipped")),[K,$]=a.useState(null),[R,z]=a.useState(null),[B,J]=a.useState(!1),[Q,C]=a.useState(!1),[L,P]=a.useState(()=>Date.now()),j=a.useRef(null),O=a.useRef(!1),H=a.useRef(null),ge=a.useRef(null),[be,se]=a.useState(!1),{badgeUpdates:me,subscribeToBadge:F,unsubscribeFromBadge:de}=Pp(n),{confirm:ne}=Ws(),xe=a.useRef(null),oe=a.useRef(!1),he=a.useCallback(A=>A instanceof Element?!!A.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);a.useEffect(()=>{N(e.description||"")},[e.id,e.description]),a.useEffect(()=>{if(!B)return;const A=ee=>{ge.current&&!ge.current.contains(ee.target)&&J(!1)};return document.addEventListener("click",A),()=>document.removeEventListener("click",A)},[B]),a.useEffect(()=>{if(!e.missionId){$(null);return}const A=Dc.get(e.missionId);if(A){$(A);return}let ee=!1;return mN(e.missionId,n).then(ze=>{ee||$(ze)}),()=>{ee=!0}},[e.missionId,n]),a.useEffect(()=>{if(!e.assignedAgentId){z(null);return}const A=Lc.get(e.assignedAgentId);if(A){z(A);return}z(null);let ee=!1;return pN(e.assignedAgentId,n).then(ze=>{ee||z(ze)}),()=>{ee=!0}},[e.assignedAgentId,n]),a.useEffect(()=>{if(S&&j.current){const A=j.current;A.focus(),A.style.height="auto",A.style.height=A.scrollHeight+"px"}},[S]),a.useEffect(()=>{if(typeof IntersectionObserver>"u"){se(!0);return}const A=H.current;if(!A)return;const ee=new IntersectionObserver(([ze])=>{se(ze?.isIntersecting??!0)},{rootMargin:"200px"});return ee.observe(A),()=>ee.disconnect()},[S,e.id]);const ae=a.useCallback(A=>{A.dataTransfer.setData("text/plain",e.id),A.dataTransfer.effectAllowed="move",y(!0)},[e.id]),je=a.useCallback(()=>{y(!1)},[]),Ae=a.useCallback(A=>A.dataTransfer.types.includes("Files"),[]),Oe=a.useCallback(A=>{Ae(A)&&(A.preventDefault(),A.stopPropagation(),A.dataTransfer.dropEffect="copy",_(!0))},[Ae]),Qe=a.useCallback(A=>{Ae(A)&&(A.preventDefault(),A.stopPropagation(),_(!1))},[Ae]),Xe=a.useCallback(async A=>{if(!Ae(A))return;A.preventDefault(),A.stopPropagation(),_(!1);const ee=Array.from(A.dataTransfer.files);for(const ze of ee)try{await fr(e.id,ze,n),r(`Attached ${ze.name} to ${e.id}`,"success")}catch(mt){r(`Failed to attach ${ze.name}: ${ye(mt)}`,"error")}},[e.id,Ae,r]),Ye=a.useCallback(()=>{S||i(e)},[e,i,S]),it=a.useCallback(A=>{if(O.current){O.current=!1;return}he(A.target)||Ye()},[Ye,he]),Be=a.useCallback(A=>{const ee=A.touches[0];ee&&(xe.current={x:ee.clientX,y:ee.clientY,time:Date.now()},oe.current=!1)},[]),Ge=a.useCallback(A=>{if(!xe.current)return;const ee=A.touches[0];if(!ee)return;const ze=Math.abs(ee.clientX-xe.current.x),mt=Math.abs(ee.clientY-xe.current.y);(ze>Tu||mt>Tu)&&(oe.current=!0)},[]),re=a.useCallback(A=>{if(he(A.target)||!xe.current)return;const ze=Date.now()-xe.current.time<PN,mt=!oe.current;ze&&mt&&(O.current=!0,Ye()),xe.current=null,oe.current=!1},[Ye,he]),ke=a.useCallback(async(A,ee)=>{A.stopPropagation();try{const ze=await pr(ee,n);i(ze)}catch{r(`Failed to load dependency ${ee}`,"error")}},[i,r]),X=e.status==="failed",Te=e.paused===!0,Le=fN(e.priority),fe=Le!==ws,_e=Eo(e,f,b),Ue=e.column==="triage"&&e.status==="awaiting-approval",nt=e.column==="archived",ve=!o&&!s&&!X&&!Te&&!_e&&!Ue&&(e.column==="in-progress"||Eu.has(e.status)),ce=!s&&!Te&&!S&&!nt,De=bN.has(e.column)&&!ve&&!Te&&!s&&l,ue=!!(e.prInfo||e.issueInfo),Re=!!(e.assignedAgentId&&R===null),Ke=a.useMemo(()=>{const A=[];return e.modelProvider&&A.push(e.modelProvider),e.validatorModelProvider&&!A.includes(e.validatorModelProvider)&&A.push(e.validatorModelProvider),e.planningModelProvider&&!A.includes(e.planningModelProvider)&&A.push(e.planningModelProvider),A},[e.modelProvider,e.validatorModelProvider,e.planningModelProvider]),Pe=a.useMemo(()=>$p(e,v),[e.steps,e.enabledWorkflowSteps,e.workflowStepResults,v]),ft=Pe.total>0&&(e.status==="executing"||e.column==="in-progress");a.useEffect(()=>{if(e.column!=="in-progress"&&e.column!=="in-review")return;const A=e.status!=null&&_u.has(e.status);if(!A&&e.column==="in-progress"){const ze=Gr(e,Date.now()),mt=Mu(e,Date.now()),jt=Jr(e,Date.now());if(ze==null&&mt==null&&jt==null)return}if(!A&&e.column==="in-review"){const ze=Gr(e,Date.now()),mt=Jr(e,Date.now());if(ze==null&&mt==null)return}P(Date.now());const ee=window.setInterval(()=>{P(Date.now())},yN);return()=>window.clearInterval(ee)},[e.column,e.status,e.columnMovedAt,e.updatedAt,e.workflowStepResults,e.timedExecutionMs,e.executionStartedAt,e.executionCompletedAt]);const Z=a.useMemo(()=>{if(!vN.has(e.column))return null;if(e.status!=null&&_u.has(e.status)){const Lt=Vi(e.updatedAt);if(Lt!=null){const _t=Math.max(0,L-Lt),Jt=Au(_t);if(Jt)return{label:Jt,title:`Merging ${Jt}`,ariaLabel:`Merging ${Jt}`}}}if(e.column==="in-progress"){const Lt=Gr(e,L)??Mu(e,L)??Jr(e,L);if(Lt==null)return null;const _t=Au(Lt);return _t?{label:_t,title:`In progress ${_t}`,ariaLabel:`In progress ${_t}`}:null}const ee=Gr(e,L)??Jr(e,L);if(ee==null)return null;const ze=wN(ee);if(!ze)return null;const mt=jN(e);if(mt==null)return{label:ze,title:`Execution time ${ze}`,ariaLabel:`Execution time ${ze}`};const jt=new Date(mt).toLocaleString();return{label:ze,title:`Execution time ${ze}. Completed ${jt}`,ariaLabel:`Execution time ${ze}. Completed ${jt}`}},[e.column,e.status,e.columnMovedAt,e.timedExecutionMs,e.updatedAt,e.workflowStepResults,e.log,e.executionStartedAt,e.executionCompletedAt,L]);a.useEffect(()=>{if(!ue||!be){de(e.id);return}return F(e.id),()=>{de(e.id)}},[ue,be,F,e.id,de]);const le=me.get(`${n??"default"}:${e.id}`),we=e.column==="in-progress"||e.column==="in-review",Ze=a.useMemo(()=>e.steps.map(A=>`${A.name}:${A.status}`).join("|"),[e.steps]),{stats:te}=aN(e.id,e.column,e.mergeDetails?.commitSha,n,{enabled:be,worktree:e.worktree,stepVersion:we?Ze:void 0,pollIntervalMs:we?3e4:void 0}),Je=a.useMemo(()=>eN(e.id,n),[e.id,n]),dt=a.useMemo(()=>{const A=le?.prInfo,ee=le?.timestamp,ze=Je?.result?.prInfo,mt=Je?.timestamp?new Date(Je.timestamp).toISOString():void 0,jt=e.prInfo,Lt=e.prInfo?.lastCheckedAt??e.updatedAt;let _t=Co(A,ee,jt,Lt);const Jt=ee&&ee>=Lt?ee:Lt;return ze&&mt&&(!Jt||mt>Jt)&&(_t=ze),_t},[le,Je,e.prInfo,e.updatedAt]),ut=a.useMemo(()=>{const A=le?.issueInfo,ee=le?.timestamp,ze=Je?.result?.issueInfo,mt=Je?.timestamp?new Date(Je.timestamp).toISOString():void 0,jt=e.issueInfo,Lt=e.issueInfo?.lastCheckedAt??e.updatedAt;let _t=Co(A,ee,jt,Lt);const Jt=ee&&ee>=Lt?ee:Lt;return ze&&mt&&(!Jt||mt>Jt)&&(_t=ze),_t},[le,Je,e.issueInfo,e.updatedAt]),Ct=a.useCallback(A=>{A?.stopPropagation(),!(!De||D)&&(w(!0),N(e.description||""))},[De,D,e.description]),yt=a.useCallback(()=>{w(!1),N(e.description||"")},[e.description]),bt=a.useCallback(()=>M!==(e.description||""),[M,e.description]),At=a.useCallback(async()=>{if(!(!l||D)){if(!bt()){yt();return}E(!0);try{await l(e.id,{description:M.trim()||void 0}),r(`Updated ${e.id}`,"success"),w(!1)}catch(A){r(`Failed to update ${e.id}: ${ye(A)}`,"error")}finally{E(!1)}}},[l,e.id,M,D,bt,yt,r]),Rt=a.useCallback(A=>{A.key==="Enter"&&!A.shiftKey?(A.preventDefault(),At()):A.key==="Escape"&&(A.preventDefault(),yt())},[At,yt]),Ht=a.useCallback(()=>{setTimeout(()=>{const A=document.activeElement;A===j.current||A?.closest(".card-editing-content")||(bt()?At():yt())},0)},[bt,At,yt]),Et=a.useCallback(A=>{De&&(A.stopPropagation(),Ct(A))},[De,Ct]),Dt=a.useCallback(A=>{A.stopPropagation(),Ct(A)},[Ct]),Kt=a.useCallback(A=>{N(A.target.value);const ee=A.target;ee.style.height="auto",ee.style.height=ee.scrollHeight+"px"},[]),$t=a.useCallback(A=>{A.stopPropagation(),c&&c(e.id).then(()=>{r(`Archived ${e.id}`,"success")}).catch(ee=>{r(`Failed to archive ${e.id}: ${ye(ee)}`,"error")})},[r,c,e.id]),Ft=a.useCallback(A=>{A.stopPropagation(),u&&u(e.id).then(()=>{r(`Unarchived ${e.id}`,"success")}).catch(ee=>{r(`Failed to unarchive ${e.id}: ${ye(ee)}`,"error")})},[r,u,e.id]),Ot=a.useCallback(async A=>{if(A.stopPropagation(),!(!d||!await ne({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0})))try{await d(e.id),r(`Deleted ${e.id}`,"success")}catch(ze){const mt=EN(ze);if(!mt||mt.dependentIds.length===0){r(`Failed to delete ${e.id}: ${ye(ze)}`,"error");return}const jt=mt.dependentIds.join(", ");if(!await ne({title:"Force Delete Task",message:`${e.id} is a dependency of ${jt}.
|
|
617
|
-
|
|
618
|
-
Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await d(e.id,{removeDependencyReferences:!0}),r(`Deleted ${e.id} after removing dependency references`,"success")}catch(_t){r(`Failed to delete ${e.id}: ${ye(_t)}`,"error")}}},[r,ne,d,e.id]),Tt=a.useCallback(A=>{A.stopPropagation(),h?.(e,"changes")},[e,h]),Pt=a.useCallback(A=>{A.stopPropagation(),U(ee=>!ee)},[]),wt=a.useCallback(A=>{A.stopPropagation(),e.missionId&&p&&p(e.missionId)},[e.missionId,p]),Gt=a.useCallback(A=>{A.stopPropagation(),J(ee=>!ee)},[]),Ut=a.useCallback((A,ee)=>{A.stopPropagation(),J(!1),g&&g(e.id,ee).then(()=>{r(`Moved ${e.id} to ${Fn[ee]}`,"success")}).catch(ze=>{r(`Failed to move ${e.id}: ${ye(ze)}`,"error")})},[r,g,e.id]),q=a.useCallback(async A=>{if(A.stopPropagation(),!(!m||Q)){C(!0);try{await m(e.id)}catch(ee){r(`Failed to retry ${e.id}: ${ye(ee)}`,"error")}finally{C(!1)}}},[r,Q,m,e.id]),pe=`card${x?" dragging":""}${s?" queued":""}${ve?" agent-active":""}${X?" failed":""}${Te?" paused":""}${_e?" stuck":""}${Ue?" awaiting-approval":""}${k?" file-drop-target":""}${S?" card-editing":""}${D?" card-saving":""}`,$e=(()=>{if(e.column==="in-progress"){const A=te?.filesChanged,ee=A==null||A===0?e.modifiedFiles?.length:void 0,ze=A!=null&&A>0?A:ee;return ze==null||ze===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:Tt,disabled:!h,children:[t.jsx(Jn,{size:12}),t.jsxs("span",{children:[ze," ",ze===1?"file":"files"," changed"]})]})}if(e.column==="in-review"){const A=te?.filesChanged,ee=A==null||A===0?e.modifiedFiles?.length:void 0,ze=A!=null&&A>0?A:ee;return ze==null||ze===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:Tt,disabled:!h,children:[t.jsx(Jn,{size:12}),t.jsxs("span",{children:[ze," ",ze===1?"file":"files"," changed"]})]})}if(e.column==="done"){const A=te?.filesChanged,ee=e.mergeDetails?.filesChanged,ze=A??ee;if(ze!=null&&ze>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:Tt,disabled:!h,children:[t.jsx(Jn,{size:12}),t.jsxs("span",{children:[ze," ",ze===1?"file":"files"," changed"]})]});const mt=e.modifiedFiles?.length;if(mt!=null&&mt>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:Tt,disabled:!h,children:[t.jsx(Jn,{size:12}),t.jsxs("span",{children:[mt," ",mt===1?"file":"files"," changed"]})]})}return null})();return S?t.jsx("div",{ref:H,className:pe,"data-id":e.id,onDoubleClick:Et,children:t.jsxs("div",{className:"card-editing-content",children:[t.jsx("textarea",{ref:j,className:"card-edit-desc-textarea",placeholder:"Task description",value:M,onChange:Kt,onKeyDown:Rt,onBlur:Ht,disabled:D,rows:4}),D&&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:H,className:pe,"data-id":e.id,draggable:ce,onDragStart:ce?ae:void 0,onDragEnd:ce?je:void 0,onDragOver:Oe,onDragLeave:Qe,onDrop:Xe,onClick:it,onTouchStart:Be,onTouchMove:Ge,onTouchEnd:re,onDoubleClick:Et,children:[t.jsxs("div",{className:"card-header",children:[t.jsx("span",{className:"card-id",children:e.id}),Te&&t.jsx("span",{className:"card-status-badge paused",children:"paused"}),!Te&&e.status&&e.status!=="queued"&&t.jsx("span",{className:`card-status-badge card-status-badge--${e.column}${Ue?" awaiting-approval":""}${Eu.has(e.status)?" pulsing":""}${X?" failed":""}${_e?" stuck":""}`,children:_e?"Stuck":Ue?"Awaiting Approval":e.status}),_e&&(Te||!e.status||e.status==="queued")&&t.jsx("span",{className:"card-status-badge stuck",children:"Stuck"}),ue&&t.jsx(Tp,{prInfo:dt,issueInfo:ut}),fe&&t.jsx("span",{className:`card-priority-badge card-priority-badge--${Le}`,children:Le}),e.executionMode==="fast"&&t.jsx("span",{className:"card-execution-mode-badge card-execution-mode-badge--fast",children:"Fast"}),e.missionId&&t.jsxs("span",{className:"card-mission-badge",onClick:wt,title:`Mission: ${K??e.missionId}`,role:p?"button":void 0,tabIndex:p?0:void 0,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[t.jsx(xs,{size:11}),hN(K??e.missionId)]}),t.jsxs("div",{className:"card-header-actions",children:[De&&t.jsx("button",{className:"card-edit-btn",onClick:Dt,title:"Edit task","aria-label":"Edit task",children:t.jsx(cs,{size:12})}),e.column==="triage"&&d&&t.jsx("button",{className:"card-delete-btn",onClick:Ot,title:"Delete task","aria-label":"Delete task",children:t.jsx(rn,{size:12})}),e.column==="done"&&c&&t.jsx("button",{className:"card-archive-btn",onClick:$t,title:"Archive task","aria-label":"Archive task",children:"Archive"}),e.column==="archived"&&u&&t.jsx("button",{className:"card-unarchive-btn",onClick:Ft,title:"Unarchive task","aria-label":"Unarchive task",children:"Unarchive"}),e.column==="in-progress"&&g&&t.jsxs("div",{className:"card-send-back",ref:ge,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:Gt,title:"Send back","aria-label":"Send back","aria-haspopup":"menu","aria-expanded":B,children:["Send back",t.jsx(Xt,{size:10})]}),B&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:Ic["in-progress"].filter(A=>A!=="in-review").map(A=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:ee=>Ut(ee,A),children:Fn[A]},A))})]}),e.column==="in-review"&&g&&t.jsxs("div",{className:"card-send-back",ref:ge,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:Gt,title:"Move task","aria-label":"Move task","aria-haspopup":"menu","aria-expanded":B,children:["Move",t.jsx(Xt,{size:10})]}),B&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:Ic["in-review"].map(A=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:ee=>Ut(ee,A),children:A==="done"?"Done (no merge)":Fn[A]},A))})]}),e.size&&t.jsx("span",{className:`card-size-badge size-${e.size.toLowerCase()}`,children:e.size})]})]}),X&&e.error&&t.jsxs("div",{className:"card-error",title:e.error,children:[t.jsx("span",{className:"card-error-icon",children:"⚠"}),t.jsx("span",{className:"card-error-text",children:e.error.length>60?e.error.slice(0,60)+"…":e.error}),m&&t.jsxs("button",{type:"button",className:"btn btn-sm card-error-retry-btn",onClick:q,disabled:Q,children:[t.jsx(Bx,{size:12}),Q?"Retrying…":"Retry"]})]}),t.jsx("div",{className:"card-title",title:e.title||e.description||void 0,children:Iu(e.title,Pu)||Iu(e.description,Pu)||e.id}),ft&&(()=>{const A=Pe.completed/Pe.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:`${A}%`,backgroundColor:xN[e.column]}})}),t.jsxs("span",{className:"card-progress-label",children:[Pe.completed,"/",Pe.total]})]}),t.jsxs("button",{type:"button",className:"card-steps-toggle",onClick:Pt,"aria-expanded":T,"aria-label":T?"Hide steps":"Show steps",children:[t.jsxs("span",{children:[Pe.total," step",Pe.total===1?"":"s"]}),t.jsx(Xt,{size:14,className:`card-steps-toggle-icon${T?" expanded":""}`})]}),T&&t.jsx("div",{className:"card-steps-list",children:Pe.items.map(ee=>{const ze=ee.source==="workflow"&&ee.status==="failed";return t.jsxs("div",{className:"card-step-item",children:[t.jsx("span",{className:`card-step-dot card-step-dot--${ee.status}${ze?" card-step-dot--workflow-failed":""}`,"aria-hidden":"true"}),t.jsx("span",{className:`card-step-name${ee.status==="done"?" completed":""}`,children:ee.name}),ee.source==="workflow"&&t.jsx("span",{className:`card-step-workflow-badge card-step-workflow-badge--${ee.phase}`,title:"Workflow check",children:"workflow"})]},ee.id)})})]})})(),($e||Z)&&t.jsxs("div",{className:"card-footer-row",children:[$e,Z&&t.jsxs("span",{className:"card-time-indicator",title:Z.title,"aria-label":Z.ariaLabel,children:[t.jsx(Si,{size:12}),t.jsx("span",{children:Z.label})]})]}),(e.dependencies&&e.dependencies.length>0||s||e.status==="queued"||e.blockedBy)&&t.jsxs("div",{className:"card-meta",children:[e.dependencies&&e.dependencies.length>0&&t.jsx("div",{className:"card-dep-list",children:e.dependencies.map(A=>t.jsxs("span",{className:"card-dep-badge clickable",onClick:ee=>void ke(ee,A),title:`Click to view ${A}`,children:[t.jsx(ha,{size:12,style:{verticalAlign:"middle"}})," ",A]},A))}),e.blockedBy&&t.jsxs("span",{className:"card-scope-badge","data-tooltip":`Blocked by ${e.blockedBy} (file overlap)`,children:[t.jsx(Bi,{size:12,style:{verticalAlign:"middle"}})," ",e.blockedBy]}),(s||e.status==="queued")&&e.column!=="in-progress"&&t.jsxs("span",{className:"queued-badge",children:[t.jsx(Si,{size:12,style:{verticalAlign:"middle"}})," Queued"]})]}),(e.assignedAgentId||Ke.length>0)&&t.jsxs("div",{className:"card-agent-row",children:[Ke.length>0&&t.jsx("span",{className:"card-provider-icons","data-testid":"card-provider-icons",children:Ke.map(A=>t.jsx(On,{provider:A,size:"sm"},A))}),e.assignedAgentId&&t.jsxs("span",{className:`card-agent-badge${Re?" card-agent-badge--loading":""}`,title:`Assigned to ${R??e.assignedAgentId}`,children:[t.jsx(Nn,{size:11}),t.jsx("span",{className:"card-agent-badge-text",children:gN(R??e.assignedAgentId,15)})]})]}),t.jsx(Jo,{slotId:"task-card-badge",projectId:n})]})}const Tu=10,PN=300,Pu=140;function Iu(e,n){return e?e.length>n?e.slice(0,n)+"…":e:""}const _o=a.memo(TN,RN);_o.displayName="TaskCard";function IN({label:e,activeTasks:n,queuedTasks:s,projectId:i,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:u,onOpenDetailWithTab:d,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p}){return t.jsxs("div",{className:"worktree-group",children:[t.jsxs("div",{className:"worktree-group-header",children:[t.jsx("span",{className:"worktree-icon",children:e==="Up Next"||e==="Unassigned"?t.jsx(mb,{size:14}):t.jsx(Vs,{size:14})}),t.jsx("span",{className:"worktree-label",children:e})]}),n.map(g=>t.jsx(_o,{task:g,projectId:i,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:u,onOpenDetailWithTab:d,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p},g.id)),s.map(g=>t.jsx(_o,{task:g,projectId:i,queued:!0,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:u,onOpenDetailWithTab:d,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p},g.id))]})}const Lp=a.memo(IN);Lp.displayName="WorktreeGroup";function $u(e){return e.toLowerCase().replace(/[-_./]/g,"")}function $N(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 DN(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 LN(e,n){const s=$u(e),i=$u(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&&$N(s,o)||s.length>=4&&DN(s,o,1))return!0;return!1}function zN(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=>LN(o,r))})}function Yn({models:e,value:n,onChange:s,placeholder:i="Select a model…",disabled:r=!1,id:o,label:l,favoriteProviders:c=[],onToggleFavorite:u,favoriteModels:d=[],onToggleModelFavorite:m,noChangeValue:h,noChangeLabel:f="No change"}){const[p,g]=a.useState(!1),[b,v]=a.useState(""),[x,y]=a.useState(0),[k,_]=a.useState(null),[S,w]=a.useState(null),M=a.useRef(null),N=a.useRef(null),D=a.useRef(null),E=a.useRef(null),T=a.useRef(null),U=a.useMemo(()=>zN(e,b),[e,b]),K=a.useMemo(()=>U.reduce((ne,xe)=>((ne[xe.provider]??=[]).push(xe),ne),{}),[U]),$=a.useMemo(()=>{const ne=[];for(const xe of d){const oe=xe.indexOf("/");if(oe===-1)continue;const he=xe.slice(0,oe),ae=xe.slice(oe+1),je=U.find(Ae=>Ae.provider===he&&Ae.id===ae);je&&ne.push({model:je,fullId:xe})}return ne},[d,U]),R=a.useMemo(()=>{const ne=Object.entries(K),xe=new Set(c);return ne.sort(([oe],[he])=>{const ae=xe.has(oe),je=xe.has(he);if(ae&&!je)return-1;if(!ae&&je)return 1;if(ae&&je){const Ae=c.indexOf(oe),Oe=c.indexOf(he);if(Ae!==Oe)return Ae-Oe}return oe.localeCompare(he)})},[K,c]),z=typeof h=="string"&&h.length>0,B=a.useMemo(()=>{if(!n||z&&n===h)return null;const ne=n.indexOf("/");return ne===-1?null:n.slice(0,ne)},[z,h,n]),J=a.useMemo(()=>{const ne=[];return z&&ne.push({type:"no-change",value:h,label:f}),ne.push({type:"default",value:"",label:"Use default"}),ne},[z,f,h]),Q=a.useMemo(()=>{const ne=[...J];for(const{model:xe,fullId:oe}of $)ne.push({type:"favorite",value:oe,label:xe.name,provider:xe.provider});return R.forEach(([xe,oe])=>{ne.push({type:"provider",value:`__group_${xe}`,label:xe,provider:xe}),oe.forEach(he=>{ne.push({type:"model",value:`${he.provider}/${he.id}`,label:he.name,provider:he.provider})})}),ne},[$,R,J]),C=a.useMemo(()=>{if(z&&n===h)return f;if(!n)return"Use default";const ne=n.indexOf("/");if(ne===-1)return n;const xe=n.slice(0,ne),oe=n.slice(ne+1);return e.find(ae=>ae.provider===xe&&ae.id===oe)?.name||n},[z,f,h,n,e]),L=a.useMemo(()=>Q.findIndex(ne=>ne.value===n),[Q,n]),P=a.useCallback(()=>{const ne=window.visualViewport;return ne&&ne.height>0&&ne.width>0?{width:ne.width,height:ne.height,offsetTop:ne.offsetTop,offsetLeft:ne.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),j=a.useCallback(()=>{const{height:ne}=P(),xe=typeof window.matchMedia=="function",oe=xe?window.matchMedia("(max-width: 640px)").matches:!1,he=xe?window.matchMedia("(max-width: 768px)").matches:!1;return ne<=0?320:oe?Math.min(ne*.6,360):he?Math.min(ne*.7,420):320},[P]),O=a.useCallback(()=>{const ne=N.current;if(!ne)return;const xe=ne.getBoundingClientRect(),{width:oe,height:he,offsetTop:ae,offsetLeft:je}=P(),Ae=16,Oe=16,Qe=4,Xe=j(),Ye=xe.bottom-ae,it=xe.top-ae,Be=xe.left-je,Ge=he-Ye,re=it,ke=Math.max(Ge-Oe-Qe,160),X=Math.max(re-Oe-Qe,160),Te=Ge<Xe&&re>Ge,Le=Math.max(Math.min(Te?X:ke,Xe),160),fe=Math.min(xe.width,oe-Ae*2),_e=Math.min(Math.max(Be,Ae),oe-Ae-fe)+je,Ue=Te?Math.max(Oe+ae,it-Le-Qe+ae):Math.min(Ye+Qe+ae,he+ae-Oe-Le);_({top:Ue,left:_e,width:fe,maxHeight:Le})},[P,j]);a.useEffect(()=>{w(document.body)},[]);const H=a.useRef(!1);a.useEffect(()=>{if(!p){H.current=!1;return}if(H.current||Q.length===0)return;const ne=Q.findIndex((xe,oe)=>oe>=(L>=0?L:0)&&xe.type!=="provider");y(ne>=0?ne:0),H.current=!0},[p,Q,L]),a.useEffect(()=>{p&&H.current&&(y(0),T.current&&(T.current.scrollTop=0))},[b,p]),a.useEffect(()=>{if(!p)return;O();const ne=requestAnimationFrame(()=>E.current?.focus());return()=>cancelAnimationFrame(ne)},[p,O]),a.useEffect(()=>{if(!p)return;const ne=()=>O();window.addEventListener("resize",ne),window.addEventListener("scroll",ne,!0);const xe=window.visualViewport;return xe&&(xe.addEventListener("resize",ne),xe.addEventListener("scroll",ne)),()=>{window.removeEventListener("resize",ne),window.removeEventListener("scroll",ne,!0),xe&&(xe.removeEventListener("resize",ne),xe.removeEventListener("scroll",ne))}},[p,O]),a.useEffect(()=>{if(!p)return;const ne=xe=>{const oe=xe.target,he=M.current?.contains(oe),ae=D.current?.contains(oe);!he&&!ae&&(g(!1),v(""))};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[p]);const ge=a.useCallback(ne=>{switch(ne.key){case"ArrowDown":if(ne.preventDefault(),!p)g(!0);else{let xe=x;for(let oe=1;oe<=Q.length;oe++){const he=(x+oe)%Q.length;if(Q[he]?.type!=="provider"){xe=he;break}}y(xe)}break;case"ArrowUp":if(ne.preventDefault(),p){let xe=x;for(let oe=1;oe<=Q.length;oe++){const he=(x-oe+Q.length)%Q.length;if(Q[he]?.type!=="provider"){xe=he;break}}y(xe)}break;case"Enter":if(ne.preventDefault(),p){const xe=Q[x];xe&&xe.type!=="provider"&&xe.type!=="favorite"&&(s(xe.value),g(!1),v(""))}else g(!0);break;case"Escape":ne.preventDefault(),g(!1),v("");break;case"Tab":p&&(g(!1),v(""));break}},[p,x,Q,s]),be=a.useCallback(ne=>{s(ne),g(!1),v("")},[s]),se=a.useCallback(()=>{v(""),E.current?.focus()},[]),me=a.useCallback(()=>{r||g(ne=>!ne)},[r]);a.useEffect(()=>{if(p&&T.current){const ne=T.current.querySelector(`[data-index="${x}"]`);ne&&typeof ne.scrollIntoView=="function"&&ne.scrollIntoView({block:"nearest"})}},[x,p]);const F=b.length>0,de=p&&k?t.jsxs("div",{ref:D,className:"model-combobox-dropdown model-combobox-dropdown--portal",role:"listbox","data-testid":"model-combobox-portal",onKeyDown:ge,style:{top:`${k.top}px`,left:`${k.left}px`,width:`${k.width}px`,maxHeight:`${k.maxHeight}px`},children:[t.jsxs("div",{className:"model-combobox-search-wrapper",children:[t.jsx("input",{ref:E,type:"text",className:"model-combobox-search",placeholder:"Filter models…",value:b,onChange:ne=>v(ne.target.value),onClick:ne=>ne.stopPropagation()}),F&&t.jsx("button",{type:"button",className:"model-combobox-clear",onClick:se,"aria-label":"Clear filter",children:"×"})]}),t.jsxs("div",{className:"model-combobox-results-count",children:[U.length," model",U.length!==1?"s":""]}),t.jsxs("div",{ref:T,className:"model-combobox-list",children:[J.map((ne,xe)=>t.jsx("div",{"data-index":xe,className:`model-combobox-option ${x===xe?"model-combobox-option--highlighted":""} ${n===ne.value?"model-combobox-option--selected":""}`,onClick:()=>be(ne.value),onMouseEnter:()=>y(xe),role:"option","aria-selected":n===ne.value,children:t.jsx("span",{className:"model-combobox-option-text model-combobox-option-text--default",children:ne.label})},`${ne.type}-${ne.value}`)),$.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"model-combobox-divider"}),$.map(({model:ne,fullId:xe},oe)=>{const he=oe+J.length,ae=x===he,je=n===xe;return t.jsxs("div",{"data-index":he,className:`model-combobox-option model-combobox-option--favorite ${ae?"model-combobox-option--highlighted":""} ${je?"model-combobox-option--selected":""}`,onClick:()=>be(xe),onMouseEnter:()=>y(he),role:"option","aria-selected":je,children:[t.jsxs("span",{className:"model-combobox-option-main",children:[t.jsx("span",{className:"model-combobox-option-icon",children:t.jsx(On,{provider:ne.provider,size:"sm"})}),t.jsx("span",{className:"model-combobox-option-text",children:ne.name})]}),t.jsx("span",{className:"model-combobox-option-id",children:ne.id}),m&&t.jsx("button",{type:"button",className:"model-combobox-option-favorite model-combobox-option-favorite--active",onClick:Ae=>{Ae.stopPropagation(),m(xe)},title:"Remove from favorites","aria-label":`Remove ${ne.name} from favorites`,children:"★"})]},xe)}),t.jsx("div",{className:"model-combobox-divider"})]}),R.map(([ne,xe])=>{const oe=Q.findIndex(je=>je.value===`__group_${ne}`),he=c.includes(ne),ae=xe.filter(je=>{const Ae=`${je.provider}/${je.id}`;return!d.includes(Ae)});return ae.length===0?null:t.jsxs("div",{className:"model-combobox-group",children:[t.jsxs("div",{className:"model-combobox-optgroup","data-index":oe,children:[t.jsx(On,{provider:ne,size:"sm"}),t.jsx("span",{className:"model-combobox-optgroup-text",children:ne}),u&&t.jsx("button",{type:"button",className:`model-combobox-optgroup-favorite ${he?"model-combobox-optgroup-favorite--active":""}`,onClick:je=>{je.stopPropagation(),u(ne)},title:he?"Remove from favorites":"Add to favorites","aria-label":he?`Remove ${ne} from favorites`:`Add ${ne} to favorites`,children:"★"})]}),ae.map(je=>{const Ae=`${je.provider}/${je.id}`,Oe=Q.findIndex(it=>it.value===Ae),Qe=x===Oe,Xe=n===Ae,Ye=d.includes(Ae);return t.jsxs("div",{"data-index":Oe,className:`model-combobox-option ${Qe?"model-combobox-option--highlighted":""} ${Xe?"model-combobox-option--selected":""}`,onClick:()=>be(Ae),onMouseEnter:()=>y(Oe),role:"option","aria-selected":Xe,children:[t.jsx("span",{className:"model-combobox-option-text",children:je.name}),t.jsx("span",{className:"model-combobox-option-id",children:je.id}),m&&t.jsx("button",{type:"button",className:`model-combobox-option-favorite ${Ye?"model-combobox-option-favorite--active":""}`,onClick:it=>{it.stopPropagation(),m(Ae)},title:Ye?"Remove from favorites":"Add to favorites","aria-label":Ye?`Remove ${je.name} from favorites`:`Add ${je.name} to favorites`,children:Ye?"★":"☆"})]},Ae)})]},ne)}),U.length===0&&F&&t.jsxs("div",{className:"model-combobox-no-results",children:["No models match '",b,"'"]})]})]}):null;return t.jsxs(t.Fragment,{children:[t.jsx("div",{ref:M,className:"model-combobox",onKeyDown:ge,children:t.jsxs("button",{ref:N,type:"button",id:o,className:"model-combobox-trigger",onClick:me,disabled:r,"aria-haspopup":"listbox","aria-expanded":p,"aria-label":l,children:[B&&t.jsx("span",{className:"model-combobox-trigger-icon",children:t.jsx(On,{provider:B,size:"sm"})}),t.jsx("span",{className:"model-combobox-trigger-text",children:C||i}),t.jsx("span",{className:"model-combobox-trigger-arrow",children:"▼"})]})}),S&&de?ca.createPortal(de,S):null]})}function hd(e,n){return typeof n!="string"||n.length===0?e:`kb:${n}:${e}`}function Qn(e,n){return typeof window>"u"?null:window.localStorage.getItem(hd(e,n))}function bs(e,n,s){typeof window>"u"||window.localStorage.setItem(hd(e,s),n)}function xr(e,n){typeof window>"u"||window.localStorage.removeItem(hd(e,n))}const FN=1e4,ON=1e3;function Qo(){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 So();n(p)}catch(p){o(p instanceof Error?p.message:"Failed to fetch nodes")}},[]);a.useEffect(()=>{let p=!1;async function g(){i(!0);try{const v=await So();p||(n(v),o(null))}catch(v){p||o(v instanceof Error?v.message:"Failed to fetch nodes")}finally{p||i(!1)}}g();const b=()=>{if(document.visibilityState!=="visible")return;const v=Date.now();v-c.current<ON||(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()},FN),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async p=>{const g=await Gj(p);return n(b=>[...b,g]),g},[]),m=a.useCallback(async(p,g)=>{const b=await Jj(p,g);return n(v=>v.map(x=>x.id===p?b:x)),b},[]),h=a.useCallback(async p=>{await Yj(p),n(g=>g.filter(b=>b.id!==p))},[]),f=a.useCallback(async p=>{const g=await Qj(p);n(b=>b.map(v=>v.id===p?{...v,status:g.status,updatedAt:g.checkedAt}:v))},[]);return{nodes:e,loading:s,error:r,refresh:u,register:d,update:m,unregister:h,healthCheck:f}}const Fa="kb-quick-entry-text",UN=["image/png","image/jpeg","image/gif","image/webp"];function BN(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function Nl(e,n){return e&&n?`${e}/${n}`:""}function Sl(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 zp({onCreate:e,addToast:n,tasks:s=[],availableModels:i,onPlanningMode:r,onSubtaskBreakdown:o,projectId:l,autoExpand:c=!0,favoriteProviders:u,favoriteModels:d,onToggleFavorite:m,onToggleModelFavorite:h}){const[f,p]=a.useState(()=>typeof window<"u"&&Qn(Fa,l)||""),[g,b]=a.useState(!1),[v,x]=a.useState(!1),[y,k]=a.useState(!1),_=a.useRef(null),S=a.useRef(null),w=a.useRef(!1),M=a.useRef(l),[N,D]=a.useState([]),E=a.useRef([]),[T,U]=a.useState([]),[K,$]=a.useState(!1),[R,z]=a.useState(""),[B,J]=a.useState(null),[Q,C]=a.useState([]),[L,P]=a.useState(void 0),[j,O]=a.useState(!1),[H,ge]=a.useState(!1),[be,se]=a.useState(!1),[me,F]=a.useState(!1),[de,ne]=a.useState(null),[xe,oe]=a.useState(void 0),[he,ae]=a.useState(void 0),[je,Ae]=a.useState(void 0),[Oe,Qe]=a.useState(void 0),[Xe,Ye]=a.useState(void 0),[it,Be]=a.useState(void 0),Ge=a.useRef(null),re=a.useRef(null),ke=a.useRef(null),X=a.useRef(null),Te=a.useRef(null),Le=a.useRef(null),[fe,_e]=a.useState(null),[Ue,nt]=a.useState(null),[ve,ce]=a.useState(null),De=a.useRef(null),ue=a.useRef(null),[Re,Ke]=a.useState(null),[Pe]=a.useState(()=>typeof document<"u"?document.body:null),[ft,Z]=a.useState(!1),[le,we]=a.useState(null),[Ze,te]=a.useState(i??[]),[Je,dt]=a.useState([]),[ut,Ct]=a.useState([]),[yt,bt]=a.useState(null),[At,Rt]=a.useState(void 0),[Ht,Et]=a.useState(!1),[Dt,Kt]=a.useState(void 0),{nodes:$t}=Qo(),[Ft,Ot]=a.useState(!1),[Tt,Pt]=a.useState(!1),wt=a.useRef(null),Gt=a.useRef(null),[Ut,q]=a.useState(null),pe=u??Je,$e=d??ut,A=!e;a.useEffect(()=>{if(i)te(i),Z(!1),we(null);else{let ie=!1;return Z(!0),we(null),ms().then(Ee=>{ie||(te(Ee.models),u||dt(Ee.favoriteProviders),d||Ct(Ee.favoriteModels))}).catch(Ee=>{ie||we(ye(Ee)||"Failed to load models")}).finally(()=>{ie||Z(!1)}),Wo(l).then(Ee=>{ie||bt(Ee)}).catch(()=>{}),()=>{ie=!0}}},[i,u,d,l]);const ee=Nl(xe,he),ze=Nl(je,Oe),mt=Nl(Xe,it),jt=!!(xe&&he),Lt=!!(je&&Oe),_t=!!(Xe&&it),Jt=Number(jt)+Number(Lt)+Number(_t),Dn=At?yt?.modelPresets?.find(ie=>ie.id===At)?.name??"Models":Jt>0?`${Jt} model${Jt===1?"":"s"}`:"Models",Pn=a.useCallback((ie,Ee)=>{if(!ie||!Ee)return"Using default";const Me=Ze.find(ct=>ct.provider===ie&&ct.id===Ee);return Me?`${Me.provider}/${Me.id}`:`${ie}/${Ee}`},[Ze]);a.useEffect(()=>{p(Qn(Fa,l)||"")},[l]),a.useEffect(()=>{typeof window<"u"&&bs(Fa,f,l)},[f,l]),a.useEffect(()=>{M.current!==l&&(M.current=l,C([]),P(void 0),J(null),O(!1),_e(null))},[l]),a.useEffect(()=>{typeof window<"u"&&localStorage.removeItem("kb-quick-entry-expanded")},[]),a.useEffect(()=>{E.current=N},[N]),a.useEffect(()=>()=>{E.current.forEach(ie=>URL.revokeObjectURL(ie.previewUrl))},[]);const Yt=a.useCallback(()=>{const ie=_.current;if(!ie)return;ie.style.height="auto";const Ee=Math.min(ie.scrollHeight,200);ie.style.height=`${Ee}px`},[]);a.useEffect(()=>{v&&Yt()},[f,v,Yt]),a.useEffect(()=>{if(!g&&f===""&&_.current){const ie=setTimeout(()=>{_.current?.focus()},0);return()=>clearTimeout(ie)}},[g,f]),a.useEffect(()=>{K||z("")},[K]),a.useEffect(()=>{if(!Ft)return;const ie=Ee=>{const Me=Ee.target,ct=wt.current?.contains(Me),gt=Gt.current?.contains(Me);!ct&&!gt&&Ot(!1)};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[Ft]),a.useEffect(()=>{if(!me)return;const ie=Ee=>{const Me=Ee.target,ct=Ge.current?.contains(Me),gt=re.current?.contains(Me),sn=Me instanceof Element&&Me.closest?.(".model-combobox-dropdown--portal")!=null;!ct&&!gt&&!sn&&(F(!1),ne(null))};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[me]),a.useEffect(()=>{if(!H)return;const ie=Ee=>{const Me=Ee.target;Te.current?.contains(Me)||Le.current?.contains(Me)||(ge(!1),nt(null))};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[H]),a.useEffect(()=>{if(!j)return;const ie=Ee=>{const Me=Ee.target;ke.current?.contains(Me)||X.current?.contains(Me)||(O(!1),_e(null))};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[j]);const Cn=a.useCallback(()=>{N.forEach(ie=>URL.revokeObjectURL(ie.previewUrl)),D([]),S.current&&(S.current.value=""),p(""),U([]),J(null),O(!1),_e(null),ge(!1),nt(null),oe(void 0),ae(void 0),Ae(void 0),Qe(void 0),Ye(void 0),Be(void 0),Rt(void 0),Et(!1),Kt(void 0),$(!1),F(!1),ce(null),ne(null),Ot(!1),Pt(!1),x(!1),k(!1),w.current=!0,_.current&&(_.current.style.height="auto"),typeof window<"u"&&xr(Fa,l)},[N,l]),Ne=a.useCallback(ie=>{if(!ie||ie.length===0)return;const Ee=[];for(let Me=0;Me<ie.length;Me++){const ct=ie[Me];UN.includes(ct.type)&&Ee.push({file:ct,previewUrl:URL.createObjectURL(ct)})}Ee.length>0&&D(Me=>[...Me,...Ee])},[]),at=a.useCallback(ie=>{g||Ne(ie.clipboardData?.files)},[Ne,g]),fn=a.useCallback(ie=>{D(Ee=>{const Me=Ee[ie];return Me&&URL.revokeObjectURL(Me.previewUrl),Ee.filter((ct,gt)=>gt!==ie)})},[]),jn=a.useCallback(async()=>{const ie=f.trim();if(!ie||g||!e)return;const Ee=f;b(!0),p("");try{const Me=await e({description:ie,column:"triage",dependencies:T.length?T:void 0,...B?{assignedAgentId:B}:{},modelPresetId:At,modelProvider:jt?xe:void 0,modelId:jt?he:void 0,validatorModelProvider:Lt?je:void 0,validatorModelId:Lt?Oe:void 0,planningModelProvider:_t?Xe:void 0,planningModelId:_t?it:void 0,...Ht?{executionMode:"fast"}:{},nodeId:Dt});if(Me&&N.length>0){const ct=[];for(const gt of N)try{await fr(Me.id,gt.file,l)}catch{ct.push(gt.file.name)}ct.length>0&&n(`Failed to upload: ${ct.join(", ")}`,"error")}Cn()}catch(Me){p(Ee),n(ye(Me)||"Failed to create task","error")}finally{b(!1)}},[f,g,e,T,B,jt,xe,he,Lt,je,Oe,_t,Xe,it,N,l,n,Cn,Ht,Dt]),In=a.useCallback(ie=>{if(ie.key==="Enter"){if(ie.shiftKey&&v)return;ie.preventDefault(),jn()}else if(ie.key==="Escape"){if(ie.preventDefault(),de){ne(null);return}if(me){F(!1),ce(null);return}if(K){$(!1);return}if(Ft){Ot(!1);return}if(H){ge(!1),nt(null);return}if(j){O(!1),_e(null);return}f.trim()&&(p(""),_.current&&(_.current.style.height="auto"),typeof window<"u"&&xr(Fa,l)),x(!1),k(!1),_.current?.blur()}},[jn,f,v,K,j,H,me,de,Ft,l,k]),Ce=a.useCallback(()=>{w.current&&(w.current=!1)},[]),st=a.useCallback(()=>{c&&x(!0)},[c]),ht=a.useCallback(ie=>{U(Ee=>Ee.includes(ie)?Ee.filter(Me=>Me!==ie):[...Ee,ie])},[]),Mt=a.useCallback(()=>{const ie=window.visualViewport;return ie&&ie.width>0&&ie.height>0?{width:ie.width,height:ie.height,offsetTop:ie.offsetTop,offsetLeft:ie.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),ln=a.useCallback(()=>{const ie=Ge.current;if(!ie)return;const Ee=ie.getBoundingClientRect(),{width:Me,height:ct,offsetTop:gt,offsetLeft:sn}=Mt(),mn=16,dn=16,gn=4,wn=Me<=768,Xn=Math.min(wn?ct*.6:ct*.5,360),Zn=Math.max(Ee.width*1.35,320),Ln=wn?Math.min(Me-mn*2,360):Zn,es=Math.min(Ln,Math.max(Me-mn*2,240)),Vn=Ee.top-gt,ps=Ee.bottom-gt,Rn=Ee.left-sn,Wn=ct-ps,fs=Vn,Ls=Math.max(Wn-dn-gn,160),ss=Math.max(fs-dn-gn,160),_n=Wn<Xn&&fs>Wn,Bn=Math.max(Math.min(_n?ss:Ls,Xn),160),zs=Math.min(Math.max(Rn,mn),Me-mn-es)+sn,di=_n?Math.max(dn+gt,Vn-Bn-gn+gt):Math.min(ps+gn+gt,ct+gt-dn-Bn);ce({top:di,left:zs,width:es,maxHeight:Bn})},[Mt]),En=a.useCallback(()=>{const ie=wt.current?.querySelector(".refine-button");if(!ie)return;const Ee=ie.getBoundingClientRect(),{width:Me,height:ct,offsetTop:gt,offsetLeft:sn}=Mt(),mn=8,dn=12,gn=4,wn=Math.min(200,Math.max(ct-dn*2,160)),Xn=Math.min(200,Me-mn*2),Zn=Ee.top-gt,Ln=Ee.bottom-gt,es=Ee.left-sn,Vn=ct-Ln,ps=Zn,Rn=Vn<wn&&ps>Vn,Wn=Math.min(Math.max(es,mn),Me-mn-Xn)+sn,fs=Rn?Math.max(dn+gt,Zn-wn-gn+gt):Math.min(Ln+gn+gt,ct+gt-dn-wn);q({top:fs,left:Wn})},[Mt]),tn=a.useCallback(()=>{const ie=De.current;if(!ie)return;const Ee=ie.getBoundingClientRect(),{width:Me,height:ct,offsetTop:gt,offsetLeft:sn}=Mt(),mn=16,dn=16,gn=4,wn=Me<=768,Xn=Math.min(wn?ct*.6:ct*.5,320),Zn=wn?Math.min(Me-mn*2,360):Math.max(Ee.width,280),Ln=Math.min(Zn,Math.max(Me-mn*2,240)),es=Ee.top-gt,Vn=Ee.bottom-gt,ps=Ee.left-sn,Rn=ct-Vn,Wn=es,fs=Math.max(Rn-dn-gn,200),Ls=Math.max(Wn-dn-gn,200),ss=Rn<Xn&&Wn>Rn,_n=Math.max(Math.min(ss?Ls:fs,Xn),200),Bn=Math.min(Math.max(ps,mn),Me-mn-Ln)+sn,zs=ss?Math.max(dn+gt,es-_n-gn+gt):Math.min(Vn+gn+gt,ct+gt-dn-_n);Ke({top:zs,left:Bn,width:Ln,maxHeight:_n})},[Mt]),nn=a.useCallback(()=>{const ie=ke.current?.querySelector("button");if(!ie)return;const Ee=ie.getBoundingClientRect(),{width:Me,height:ct,offsetTop:gt,offsetLeft:sn}=Mt(),mn=16,dn=16,gn=4,wn=Me<=768,Xn=Math.min(wn?ct*.6:ct*.5,320),Zn=wn?Math.min(Me-mn*2,280):Math.max(Ee.width,240),Ln=Math.min(Zn,Math.max(Me-mn*2,200)),es=Ee.top-gt,Vn=Ee.bottom-gt,ps=Ee.left-sn,Rn=ct-Vn,Wn=es,fs=Math.max(Rn-dn-gn,160),Ls=Math.max(Wn-dn-gn,160),ss=Rn<Xn&&Wn>Rn,_n=Math.max(Math.min(ss?Ls:fs,Xn),160),Bn=Math.min(Math.max(ps,mn),Me-mn-Ln)+sn,zs=ss?Math.max(dn+gt,es-_n-gn+gt):Math.min(Vn+gn+gt,ct+gt-dn-_n);_e({top:zs,left:Bn,width:Ln,maxHeight:_n})},[Mt]),An=a.useCallback(()=>{const ie=Te.current?.querySelector("button");if(!ie)return;const Ee=ie.getBoundingClientRect(),{width:Me,height:ct,offsetTop:gt,offsetLeft:sn}=Mt(),mn=16,dn=16,gn=4,wn=Me<=768,Xn=Math.min(wn?ct*.6:ct*.5,320),Zn=wn?Math.min(Me-mn*2,280):Math.max(Ee.width,240),Ln=Math.min(Zn,Math.max(Me-mn*2,200)),es=Ee.top-gt,Vn=Ee.bottom-gt,ps=Ee.left-sn,Rn=ct-Vn,Wn=es,fs=Math.max(Rn-dn-gn,160),Ls=Math.max(Wn-dn-gn,160),ss=Rn<Xn&&Wn>Rn,_n=Math.max(Math.min(ss?Ls:fs,Xn),160),Bn=Math.min(Math.max(ps,mn),Me-mn-Ln)+sn,zs=ss?Math.max(dn+gt,es-_n-gn+gt):Math.min(Vn+gn+gt,ct+gt-dn-_n);nt({top:zs,left:Bn,width:Ln,maxHeight:_n})},[Mt]);a.useEffect(()=>{if(!me)return;const ie=()=>ln();window.addEventListener("resize",ie),window.addEventListener("scroll",ie,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",ie),Ee.addEventListener("scroll",ie)),()=>{window.removeEventListener("resize",ie),window.removeEventListener("scroll",ie,!0),Ee&&(Ee.removeEventListener("resize",ie),Ee.removeEventListener("scroll",ie))}},[me,ln]),a.useEffect(()=>{if(!Ft)return;const ie=()=>En();window.addEventListener("resize",ie),window.addEventListener("scroll",ie,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",ie),Ee.addEventListener("scroll",ie)),()=>{window.removeEventListener("resize",ie),window.removeEventListener("scroll",ie,!0),Ee&&(Ee.removeEventListener("resize",ie),Ee.removeEventListener("scroll",ie))}},[Ft,En]),a.useEffect(()=>{if(!K)return;const ie=()=>tn();window.addEventListener("resize",ie),window.addEventListener("scroll",ie,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",ie),Ee.addEventListener("scroll",ie)),()=>{window.removeEventListener("resize",ie),window.removeEventListener("scroll",ie,!0),Ee&&(Ee.removeEventListener("resize",ie),Ee.removeEventListener("scroll",ie))}},[K,tn]),a.useEffect(()=>{if(!j)return;const ie=()=>nn();window.addEventListener("resize",ie),window.addEventListener("scroll",ie,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",ie),Ee.addEventListener("scroll",ie)),()=>{window.removeEventListener("resize",ie),window.removeEventListener("scroll",ie,!0),Ee&&(Ee.removeEventListener("resize",ie),Ee.removeEventListener("scroll",ie))}},[j,nn]),a.useEffect(()=>{if(!H)return;const ie=()=>An();window.addEventListener("resize",ie),window.addEventListener("scroll",ie,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",ie),Ee.addEventListener("scroll",ie)),()=>{window.removeEventListener("resize",ie),window.removeEventListener("scroll",ie,!0),Ee&&(Ee.removeEventListener("resize",ie),Ee.removeEventListener("scroll",ie))}},[H,An]);const Un=a.useCallback(ie=>{const Ee=Sl(ie);Ye(Ee.provider),Be(Ee.modelId)},[]),kn=a.useCallback(ie=>{const Ee=Sl(ie);oe(Ee.provider),ae(Ee.modelId)},[]),ns=a.useCallback(ie=>{const Ee=Sl(ie);Ae(Ee.provider),Qe(Ee.modelId)},[]),cn=a.useCallback(async ie=>{if(m){m(ie);return}const Ee=Je,ct=Ee.includes(ie)?Ee.filter(gt=>gt!==ie):[ie,...Ee];dt(ct);try{await hn({favoriteProviders:ct,favoriteModels:ut})}catch{dt(Ee)}},[Je,ut,m]),vt=a.useCallback(async ie=>{if(h){h(ie);return}const Ee=ut,ct=Ee.includes(ie)?Ee.filter(gt=>gt!==ie):[ie,...Ee];Ct(ct);try{await hn({favoriteProviders:Je,favoriteModels:ct})}catch{Ct(Ee)}},[ut,Je,h]),G=a.useCallback(()=>{const ie=f.trim();if(!ie){n("Enter a description first","error");return}r?.(ie),Cn()},[f,r,n,Cn]),Fe=a.useCallback(()=>{const ie=f.trim();if(!ie){n("Enter a description first","error");return}o?.(ie),Cn()},[f,o,n,Cn]),tt=a.useCallback(()=>{jn()},[jn]),rt=a.useCallback(async ie=>{const Ee=f.trim();if(!(!Ee||Tt)){Ot(!1),Pt(!0);try{const Me=await fp(Ee,ie,l);p(Me),n("Description refined with AI","success"),_.current&&(_.current.style.height="auto",_.current.style.height=`${Math.min(_.current.scrollHeight,200)}px`)}catch(Me){const ct=gp(Me);n(ct,"error")}finally{Pt(!1)}}},[f,Tt,n,l]),kt=(ie,Ee)=>ie.length>Ee?ie.slice(0,Ee)+"…":ie,St=a.useCallback(async()=>{if(i){te(i),we(null),Z(!1);return}Z(!0),we(null);try{const ie=await ms();te(ie.models),u||dt(ie.favoriteProviders),d||Ct(ie.favoriteModels)}catch(ie){we(ye(ie)||"Failed to load models")}finally{Z(!1)}},[i,u,d]),zt=a.useCallback(async()=>{if(Q.length>0&&L===l){O(!0),nn();return}se(!0);try{const ie=await Ea(void 0,l);C(ie),P(l),O(!0),nn()}catch(ie){const Ee=ye(ie);n(Ee?`Failed to load agents: ${Ee}`:"Failed to load agents","error"),O(!1)}finally{se(!1)}},[Q.length,L,l,n,nn]),Ds=(B?Q.find(ie=>ie.id===B):void 0)?.name??B,ci=Dt?$t.find(ie=>ie.id===Dt):void 0,Cs=y,Gs=a.useCallback(()=>{k(ie=>{const Ee=!ie;return x(Ee),Ee})},[]);return t.jsxs("div",{className:`quick-entry-box ${y?"quick-entry-box--expanded":"quick-entry-box--collapsed"}`,"data-testid":"quick-entry-box",children:[t.jsx("div",{className:"description-with-refine",children:t.jsxs("div",{className:"quick-entry-main-row",children:[t.jsx("div",{className:"quick-entry-textarea-wrap",children:t.jsx("textarea",{ref:_,className:`quick-entry-input ${v?"quick-entry-input--expanded":""}`,placeholder:g?"Creating...":"Add a task...",value:f,onChange:ie=>p(ie.target.value),onKeyDown:In,onPaste:at,onFocus:st,onBlur:Ce,disabled:g||A,"data-testid":"quick-entry-input",rows:2,"aria-controls":"quick-entry-controls","aria-expanded":y})}),t.jsx("button",{type:"button",className:"btn btn-sm quick-entry-toggle",onClick:Gs,"aria-expanded":y,"aria-controls":"quick-entry-controls","data-testid":"quick-entry-toggle",title:y?"Collapse":"Expand",children:y?t.jsx(pi,{size:14}):t.jsx(Xt,{size:14})})]})}),t.jsxs("div",{id:"quick-entry-controls",className:"quick-entry-controls",hidden:!Cs,"aria-hidden":!Cs,children:[Cs&&!g&&t.jsxs("div",{className:"quick-entry-actions","data-testid":"quick-entry-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:G,onMouseDown:ie=>ie.preventDefault(),disabled:!f.trim(),"data-testid":"plan-button",title:"Open planning mode with current description",children:[t.jsx(si,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Plan"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:Fe,onMouseDown:ie=>ie.preventDefault(),disabled:!f.trim(),"data-testid":"subtask-button",title:"Break down into AI-generated subtasks",children:[t.jsx(Bo,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Subtask"]}),t.jsxs("div",{className:"refine-trigger-wrap",ref:wt,children:[t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${Tt?"refine-button--loading":""}`,onClick:()=>{Ot(ie=>{const Ee=!ie;return Ee?En():q(null),Ee})},disabled:!f.trim()||Tt,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(rs,{size:12,style:{verticalAlign:"middle"}}),Tt?"Refining...":"Refine"]}),Ft&&Pe&&Ut&&ca.createPortal(t.jsxs("div",{ref:Gt,className:"refine-menu refine-menu--portal",onMouseDown:ie=>ie.preventDefault(),style:{position:"fixed",top:`${Ut.top}px`,left:`${Ut.left}px`},children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>rt("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:()=>rt("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:()=>rt("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:()=>rt("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"})]})]}),Pe)]}),t.jsx("div",{className:"dep-trigger-wrap",children:t.jsxs("button",{ref:De,type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-deps",onClick:()=>{$(ie=>{const Ee=!ie;return Ee?(F(!1),ce(null),ne(null),O(!1),_e(null),ge(!1),nt(null),tn()):Ke(null),Ee})},children:[t.jsx(ha,{size:12,style:{verticalAlign:"middle"}}),T.length>0?`${T.length} deps`:"Deps"]})}),K&&Pe&&Re&&(()=>{const ie=R.toLowerCase(),Ee=(ie?s.filter(Me=>Me.id.toLowerCase().includes(ie)||Me.title&&Me.title.toLowerCase().includes(ie)||Me.description&&Me.description.toLowerCase().includes(ie)):[...s]).sort((Me,ct)=>{const gt=ct.createdAt.localeCompare(Me.createdAt);if(gt!==0)return gt;const sn=parseInt(Me.id.slice(Me.id.lastIndexOf("-")+1),10)||0;return(parseInt(ct.id.slice(ct.id.lastIndexOf("-")+1),10)||0)-sn});return ca.createPortal(t.jsxs("div",{ref:ue,className:"dep-dropdown dep-dropdown--portal",onMouseDown:Me=>Me.preventDefault(),style:{position:"fixed",top:`${Re.top}px`,left:`${Re.left}px`,width:`${Re.width}px`,maxHeight:Re.maxHeight?`${Re.maxHeight}px`:void 0,overflowY:Re.maxHeight?"auto":void 0},children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:R,onChange:Me=>z(Me.target.value),onClick:Me=>Me.stopPropagation()}),Ee.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No existing tasks"}):Ee.map(Me=>t.jsxs("div",{className:`dep-dropdown-item${T.includes(Me.id)?" selected":""}`,onMouseDown:ct=>ct.preventDefault(),onClick:()=>ht(Me.id),children:[t.jsx("span",{className:"dep-dropdown-id",children:Me.id}),t.jsx("span",{className:"dep-dropdown-title",children:kt(Me.title||Me.description||Me.id,60)})]},Me.id))]}),Pe)})(),t.jsxs("button",{type:"button",className:"btn btn-sm","data-testid":"quick-entry-attach",onClick:()=>S.current?.click(),children:[t.jsx(sp,{size:12,style:{verticalAlign:"middle"}}),N.length>0?`Attach (${N.length})`:"Attach"]}),t.jsxs("button",{ref:Ge,type:"button",className:"btn btn-sm","data-testid":"quick-entry-models",onClick:()=>{$(!1),O(!1),_e(null),ge(!1),nt(null),ne(null),F(!0),ln()},children:[t.jsx(yo,{size:12,style:{verticalAlign:"middle"}}),Dn]}),t.jsx("div",{className:"node-trigger-wrap",ref:Te,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-node-button",onClick:()=>{$(!1),O(!1),_e(null),F(!1),ce(null),ne(null),ge(ie=>{const Ee=!ie;return Ee?An():nt(null),Ee})},children:[t.jsx(hr,{size:12,style:{verticalAlign:"middle"}}),` ${ci?.name??"Node"}`,ci&&t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(qi,{status:ci.status,showLabel:!0})})]})}),H&&Pe&&Ue&&ca.createPortal(t.jsxs("div",{ref:Le,className:"dep-dropdown node-picker-dropdown node-picker-dropdown--portal",onMouseDown:ie=>ie.preventDefault(),style:{position:"fixed",top:`${Ue.top}px`,left:`${Ue.left}px`,width:`${Ue.width}px`,maxHeight:Ue.maxHeight?`${Ue.maxHeight}px`:void 0,overflowY:Ue.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select execution node"}),t.jsx("div",{className:`dep-dropdown-item node-picker-item${Dt==null?" selected":""}`,onMouseDown:ie=>ie.preventDefault(),onClick:()=>{Kt(void 0),ge(!1),nt(null)},children:t.jsx("span",{className:"node-picker-item-name",children:"Project default / local"})}),$t.map(ie=>t.jsxs("div",{className:`dep-dropdown-item node-picker-item${Dt===ie.id?" selected":""}`,onMouseDown:Ee=>Ee.preventDefault(),onClick:()=>{Kt(ie.id),ge(!1),nt(null)},children:[t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(qi,{status:ie.status})}),t.jsx("span",{className:"node-picker-item-name",children:ie.name}),t.jsx("span",{className:"node-picker-item-status",children:BN(ie.status)})]},ie.id))]}),Pe),t.jsx("div",{className:"agent-trigger-wrap",ref:ke,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{j?(O(!1),_e(null)):(ge(!1),nt(null),zt())},"data-testid":"quick-entry-agent-button",children:[t.jsx(Nn,{size:12,style:{verticalAlign:"middle"}}),Ds?` ${Ds}`:" Agent"]})}),j&&Pe&&fe&&ca.createPortal(t.jsxs("div",{ref:X,className:"dep-dropdown agent-picker-dropdown agent-picker-dropdown--portal",onMouseDown:ie=>ie.preventDefault(),style:{position:"fixed",top:`${fe.top}px`,left:`${fe.left}px`,width:`${fe.width}px`,maxHeight:fe.maxHeight?`${fe.maxHeight}px`:void 0,overflowY:fe.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),be&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!be&&Q.filter(ie=>ie.state!=="terminated").map(ie=>t.jsxs("div",{className:`dep-dropdown-item${B===ie.id?" selected":""}`,onMouseDown:Ee=>Ee.preventDefault(),onClick:()=>{J(ie.id===B?null:ie.id),O(!1),_e(null)},children:[t.jsx(Nn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:ie.role}),t.jsx("span",{className:"dep-dropdown-title",children:ie.name})]},ie.id)),!be&&Q.filter(ie=>ie.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),B&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:ie=>ie.preventDefault(),onClick:()=>{J(null),O(!1),_e(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]}),Pe),t.jsx("button",{type:"button",className:`btn btn-sm ${Ht?"btn-primary":""}`,onClick:()=>Et(ie=>!ie),onMouseDown:ie=>ie.preventDefault(),"aria-pressed":Ht,"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:tt,onMouseDown:ie=>ie.preventDefault(),disabled:!f.trim()||g,"data-testid":"quick-entry-save",title:"Create task",children:[t.jsx(ap,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Save"]})]}),N.length>0&&t.jsx("div",{className:"inline-create-previews",children:N.map((ie,Ee)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:ie.previewUrl,alt:ie.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>fn(Ee),disabled:g,title:"Remove image","data-testid":`quick-entry-preview-remove-${Ee}`,children:"×"})]},ie.previewUrl))}),me&&Pe&&ve&&ca.createPortal(t.jsx("div",{ref:re,className:"model-nested-menu model-nested-menu--portal",onMouseDown:ie=>ie.preventDefault(),"data-testid":"model-nested-menu",style:{position:"fixed",top:`${ve.top}px`,left:`${ve.left}px`,width:`${ve.width}px`,maxHeight:ve.maxHeight?`${ve.maxHeight}px`:void 0,overflowY:ve.maxHeight?"auto":void 0},children:de===null?t.jsxs("div",{className:"model-menu-items",children:[t.jsxs("button",{type:"button",className:`model-menu-item ${_t?"model-menu-item--active":""}`,onClick:()=>ne("plan"),"data-testid":"model-menu-plan",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(si,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Plan"]}),t.jsx("span",{className:"model-menu-item-value",children:_t?Pn(Xe,it):"Using default"}),t.jsx(vn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${jt?"model-menu-item--active":""}`,onClick:()=>ne("executor"),"data-testid":"model-menu-executor",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(rs,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Executor"]}),t.jsx("span",{className:"model-menu-item-value",children:jt?Pn(xe,he):"Using default"}),t.jsx(vn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${Lt?"model-menu-item--active":""}`,onClick:()=>ne("validator"),"data-testid":"model-menu-validator",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(yo,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Reviewer"]}),t.jsx("span",{className:"model-menu-item-value",children:Lt?Pn(je,Oe):"Using default"}),t.jsx(vn,{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:()=>ne(null),"data-testid":"model-submenu-back",children:[t.jsx(Xt,{size:12,style:{transform:"rotate(90deg)",marginRight:4}}),"Back"]}),t.jsxs("div",{className:"model-submenu-header",children:[de==="plan"&&"Plan Model",de==="executor"&&"Executor Model",de==="validator"&&"Reviewer Model"]}),t.jsx(Yn,{models:Ze,value:de==="plan"?mt:de==="executor"?ee:ze,onChange:de==="plan"?Un:de==="executor"?kn:ns,placeholder:"Using default",disabled:ft,id:`model-${de}-select`,label:`${de} model`,favoriteProviders:pe,onToggleFavorite:cn,favoriteModels:$e,onToggleModelFavorite:vt}),le&&t.jsxs("div",{className:"model-submenu-error",children:[t.jsx("span",{children:le}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:St,children:"Retry"})]})]})}),Pe)]}),t.jsx("input",{ref:S,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:ie=>{Ne(ie.target.files),ie.currentTarget.value=""},"data-testid":"quick-entry-file-input"}),t.jsx("div",{className:"quick-entry-hint",children:"Enter to create · Esc to cancel"})]})}function HN(e){return ud(e)||e}function qN(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 VN(e,n,s){const i=e.filter(g=>g.worktree),r=e.filter(g=>!g.worktree),o=new Map;for(const g of i){const b=g.worktree,v=o.get(b)||[];v.push(g),o.set(b,v)}const l=new Map(n.map(g=>[g.id,g])),u=n.filter(g=>g.column==="todo").filter(g=>!g.paused&&(g.dependencies||[]).every(b=>{const v=l.get(b);return v&&(v.column==="done"||v.column==="in-review"||v.column==="archived")})),m=qN(u).map(g=>l.get(g)).filter(g=>g!==void 0&&u.includes(g)),h=[],f=Array.from(o.keys());for(const g of f)h.push({label:HN(g),activeTasks:o.get(g),queuedTasks:[]});r.length>0&&h.push({label:"Unassigned",activeTasks:r,queuedTasks:[]});const p=m.slice(0,s);return p.length>0&&h.push({label:"Up Next",activeTasks:[],queuedTasks:p}),h}const Du=100,Cl=50,Lu=25;function WN({column:e,tasks:n,projectId:s,maxConcurrent:i,onMoveTask:r,onPauseTask:o,onOpenDetail:l,addToast:c,onQuickCreate:u,onNewTask:d,autoMerge:m,onToggleAutoMerge:h,globalPaused:f,onUpdateTask:p,onRetryTask:g,onArchiveTask:b,onUnarchiveTask:v,onDeleteTask:x,onArchiveAllDone:y,collapsed:k,onToggleCollapse:_,allTasks:S,availableModels:w,onPlanningMode:M,onSubtaskBreakdown:N,onOpenDetailWithTab:D,favoriteProviders:E,favoriteModels:T,onToggleFavorite:U,onToggleModelFavorite:K,isSearchActive:$,taskStuckTimeoutMs:R,onOpenMission:z,lastFetchTimeMs:B,workflowStepNameLookup:J}){const[Q,C]=a.useState(!1),[L,P]=a.useState(Cl),[j,O]=a.useState(!1),[H,ge]=a.useState(!1),[be,se]=a.useState(!1),[me,F]=a.useState(!1),de=a.useRef(null),ne=Lw(n.length),{confirm:xe}=Ws();a.useEffect(()=>{if(!j)return;function _e(nt){de.current?.contains(nt.target)||O(!1)}function Ue(nt){nt.key==="Escape"&&O(!1)}return document.addEventListener("mousedown",_e),document.addEventListener("keydown",Ue),()=>{document.removeEventListener("mousedown",_e),document.removeEventListener("keydown",Ue)}},[j]);const oe=e==="archived",he=oe&&k,ae=!oe&&!$&&e!=="in-progress"&&n.length>Du;a.useEffect(()=>{P(_e=>e==="in-progress"||oe||n.length<=Du?Cl:Math.min(Math.max(_e,Cl),n.length))},[e,oe,n.length]);const je=a.useCallback(_e=>{oe||(_e.preventDefault(),_e.dataTransfer.dropEffect="move",C(!0))},[oe]),Ae=a.useCallback(_e=>{_e.currentTarget.contains(_e.relatedTarget)||C(!1)},[]),Oe=a.useCallback(async _e=>{_e.preventDefault(),C(!1);const Ue=_e.dataTransfer.getData("text/plain");if(!Ue)return;const nt=n.find(ve=>ve.id===Ue);if(!(nt&&nt.column===e))try{await r(Ue,e)}catch(ve){c(ye(ve),"error")}},[e,r,c,n]),Qe=a.useMemo(()=>e!=="in-progress"?[]:VN(n,n,i),[e,n,i]),Xe=a.useMemo(()=>ae?n.slice(0,L):n,[ae,n,L]),Ye=Math.max(0,n.length-Xe.length),it=a.useCallback(()=>{P(_e=>Math.min(_e+Lu,n.length))},[n.length]),Be=a.useCallback(async()=>{if(O(!1),!(n.length===0||!await xe({title:"Replan All Tasks",message:`Move all ${n.length} todo task${n.length===1?"":"s"} back to planning to be replanned?`}))){ge(!0);try{const Ue=await Promise.allSettled(n.map(ce=>r(ce.id,"triage"))),nt=Ue.filter(ce=>ce.status==="rejected").length,ve=Ue.length-nt;nt===0?c(`Moved ${ve} task${ve===1?"":"s"} to planning for replanning`,"success"):c(`Moved ${ve} of ${Ue.length} tasks; ${nt} failed`,"error")}finally{ge(!1)}}},[n,r,c,xe]),Ge=a.useMemo(()=>n.filter(_e=>!_e.paused),[n]),re=Ge.length,ke=e==="todo"||e==="in-progress"||e==="in-review",X=H||be||me,Te=a.useCallback(async()=>{if(!(!o||(O(!1),re===0)||!await xe({title:"Stop All Tasks",message:`Stop all ${re} ${Fn[e].toLowerCase()} task${re===1?"":"s"}?`,danger:!0}))){se(!0);try{const Ue=await Promise.allSettled(Ge.map(ce=>o(ce.id))),nt=Ue.filter(ce=>ce.status==="rejected").length,ve=Ue.length-nt;nt===0?c(`Stopped ${ve} task${ve===1?"":"s"}`,"success"):c(`Stopped ${ve} of ${Ue.length} tasks; ${nt} failed`,"error")}finally{se(!1)}}},[o,re,e,Ge,c,xe]),Le=a.useCallback(async()=>{if(O(!1),!(n.length===0||!await xe({title:"Move All to Todo",message:`Move all ${n.length} ${Fn[e].toLowerCase()} task${n.length===1?"":"s"} to Todo?`}))){F(!0);try{const Ue=await Promise.allSettled(n.map(ce=>r(ce.id,"todo"))),nt=Ue.filter(ce=>ce.status==="rejected").length,ve=Ue.length-nt;nt===0?c(`Moved ${ve} task${ve===1?"":"s"} to Todo`,"success"):c(`Moved ${ve} of ${Ue.length} tasks to Todo; ${nt} failed`,"error")}finally{F(!1)}}},[n,e,r,c,xe]),fe=a.useCallback(async()=>{if(!(!y||n.length===0||!await xe({title:"Archive All Done",message:`Archive all ${n.length} done tasks?`,danger:!0})))try{const Ue=await y();c(`Archived ${Ue.length} tasks`,"success")}catch(Ue){c(ye(Ue)||"Failed to archive tasks","error")}},[y,n.length,c,xe]);return t.jsxs("div",{className:`column${Q?" drag-over":""}${oe?" column-archived":""}${he?" column-collapsed":""}`,"data-column":e,onDragOver:je,onDragLeave:Ae,onDrop:Oe,children:[t.jsxs("div",{className:"column-header",children:[t.jsx("div",{className:`column-dot dot-${e}`}),t.jsx("h2",{children:Fn[e]}),t.jsx("span",{className:`column-count${ne?" count-flash":""}`,children:n.length}),e==="in-review"&&h&&t.jsxs("label",{className:"auto-merge-toggle",title:m?"Auto-merge enabled":"Auto-merge disabled",children:[t.jsx("input",{type:"checkbox",checked:!!m,onChange:h}),t.jsx("span",{className:"toggle-slider"}),t.jsx("span",{className:"toggle-label",children:"Auto-merge"})]}),d&&t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:d,children:"+ New Task"}),e==="done"&&y&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:fe,disabled:n.length===0,title:"Archive all done tasks","aria-label":"Archive all done tasks",children:t.jsx(zo,{size:16})}),oe&&_&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:_,title:k?"Expand archived tasks":"Collapse archived tasks","aria-label":k?"Expand archived tasks":"Collapse archived tasks",children:k?t.jsx(Xt,{size:16}):t.jsx(pi,{size:16})}),ke&&t.jsxs("div",{className:"column-menu",ref:de,children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>O(_e=>!_e),"aria-haspopup":"menu","aria-expanded":j,"aria-label":`${Fn[e]} column actions`,title:"Column actions",disabled:X,children:t.jsx(wb,{size:16})}),j&&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 Be(),disabled:n.length===0||H,children:["Replan All",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Planning"]})]}),(e==="in-progress"||e==="in-review")&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Te(),disabled:re===0||be||!o,children:["Stop All",t.jsx("span",{className:"column-menu-item-hint",children:n.length===0?"No tasks in this column":re===0?"All tasks are already paused":`Pause ${re} active task${re===1?"":"s"}`})]}),t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Le(),disabled:n.length===0||me,children:["Move All to Todo",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Todo"]})]})]})]})]})]}),!he&&t.jsx("p",{className:"column-desc",children:$w[e]}),!he&&t.jsxs("div",{className:"column-body",children:[e==="triage"&&u&&t.jsx(zp,{onCreate:u,addToast:c,tasks:S??[],availableModels:w,onPlanningMode:M,onSubtaskBreakdown:N,projectId:s,autoExpand:!1,favoriteProviders:E,favoriteModels:T,onToggleFavorite:U,onToggleModelFavorite:K}),e==="in-progress"?Qe.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):Qe.map(_e=>t.jsx(Lp,{label:_e.label,activeTasks:_e.activeTasks,queuedTasks:_e.queuedTasks,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onOpenDetailWithTab:D,taskStuckTimeoutMs:R,onOpenMission:z,lastFetchTimeMs:B,workflowStepNameLookup:J},_e.label)):n.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):t.jsxs(t.Fragment,{children:[Xe.map(_e=>t.jsx(_o,{task:_e,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onArchiveTask:b,onUnarchiveTask:v,onDeleteTask:x,onOpenDetailWithTab:D,taskStuckTimeoutMs:R,onOpenMission:z,onMoveTask:r,lastFetchTimeMs:B,workflowStepNameLookup:J},_e.id)),ae&&Ye>0&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:it,children:["Load ",Math.min(Lu,Ye)," more (",Ye," remaining)"]})]}),t.jsx(Jo,{slotId:"board-column-footer",projectId:s})]})]})}const Fp=a.memo(WN);Fp.displayName="Column";function KN(e,n){return[...e].sort((s,i)=>{if(n==="in-review"){const r=s.status==="merging"||s.status==="merging-pr",o=i.status==="merging"||i.status==="merging-pr";if(r!==o)return r?-1:1}return s.columnMovedAt&&i.columnMovedAt?i.columnMovedAt.localeCompare(s.columnMovedAt):s.columnMovedAt&&!i.columnMovedAt?-1:!s.columnMovedAt&&i.columnMovedAt?1:s.createdAt.localeCompare(i.createdAt)})}function GN(e,n){return e.length!==n.length?!1:e.every((s,i)=>s===n[i])}const zu=new Map;function JN(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 YN({tasks:e,projectId:n,maxConcurrent:s,onMoveTask:i,onPauseTask:r,onOpenDetail:o,addToast:l,onQuickCreate:c,onNewTask:u,autoMerge:d,onToggleAutoMerge:m,globalPaused:h,onUpdateTask:f,onRetryTask:p,onArchiveTask:g,onUnarchiveTask:b,onDeleteTask:v,onArchiveAllDone:x,onLoadArchivedTasks:y,searchQuery:k="",availableModels:_,onPlanningMode:S,onSubtaskBreakdown:w,onOpenDetailWithTab:M,favoriteProviders:N,favoriteModels:D,onToggleFavorite:E,onToggleModelFavorite:T,taskStuckTimeoutMs:U,onOpenMission:K,lastFetchTimeMs:$}){const[R,z]=a.useState(!0),B=a.useRef(!1),{fetchBatch:J}=tN(n),Q=a.useRef(null),[C,L]=a.useState(zu),P=k.trim()!=="",j=a.useRef({triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]}),O=a.useCallback(()=>{z(be=>{const se=!be;return!se&&!B.current&&y&&(B.current=!0,y()),se})},[y]),H=a.useMemo(()=>{const be=Object.fromEntries(Fi.map(F=>[F,[]]));for(const F of e)be[F.column].push(F);const se=j.current,me={};for(const F of Fi){const de=KN(be[F],F);me[F]=GN(se[F],de)?se[F]:de}return j.current=me,me},[e]);a.useEffect(()=>{let be=!1;return Ko(n).then(se=>{if(be)return;const me=new Map(se.map(F=>[F.id,F.name]));L(F=>JN(F,me)?F:me)}).catch(()=>{be||L(se=>se.size===0?se:zu)}),()=>{be=!0}},[n]);const ge=a.useMemo(()=>e.filter(be=>be.prInfo||be.issueInfo).map(be=>be.id),[e]);return a.useEffect(()=>{if(ge.length!==0)return Q.current&&clearTimeout(Q.current),Q.current=setTimeout(()=>{const be=[];for(let se=0;se<ge.length;se+=50)be.push(ge.slice(se,se+50));be.forEach(se=>{J(se)})},500),()=>{Q.current&&clearTimeout(Q.current)}},[ge,J]),t.jsx(t.Fragment,{children:t.jsx("main",{className:"board",id:"board",children:Fi.map(be=>t.jsx(Fp,{column:be,tasks:H[be],projectId:n,maxConcurrent:s,onMoveTask:i,onPauseTask:r,onOpenDetail:o,addToast:l,globalPaused:h,onUpdateTask:f,onRetryTask:p,onArchiveTask:g,onUnarchiveTask:b,onDeleteTask:v,allTasks:e,availableModels:_,onOpenDetailWithTab:M,favoriteProviders:N,favoriteModels:D,onToggleFavorite:E,onToggleModelFavorite:T,isSearchActive:P,taskStuckTimeoutMs:U,onOpenMission:K,lastFetchTimeMs:$,workflowStepNameLookup:C,...be==="triage"?{onQuickCreate:c,onNewTask:u,onPlanningMode:S,onSubtaskBreakdown:w}:{},...be==="in-review"?{autoMerge:d,onToggleAutoMerge:m}:{},...be==="done"?{onArchiveAllDone:x}:{},...be==="archived"?{collapsed:R,onToggleCollapse:O}:{}},be))})})}const Oa={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-secondary)"},Fu=new Set(["planning","researching","executing","finalizing","merging"]),zc=["id","title","status","column","dependencies","progress"];function QN(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function XN(e){return e==="online"?"●":e==="connecting"?"◐":e==="error"?"✕":"○"}function Ou(e){try{const n=Qn("kb-dashboard-list-columns",e);if(n){const i=JSON.parse(n).filter(r=>zc.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set(zc)}function Uu(e){try{const n=Qn("kb-dashboard-hide-done",e);if(n!==null)return n==="true"}catch{}return!1}function Bu(e){try{const n=Qn("kb-dashboard-list-collapsed",e);if(n){const i=JSON.parse(n).filter(r=>Fi.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set}function Hu(e){try{const n=Qn("kb-dashboard-selected-tasks",e);if(n){const s=JSON.parse(n);return new Set(s)}}catch{}return new Set}function ZN(e){return e.status==="executing"||e.column==="in-progress"}function qu(e){const n=$p(e);return n.total===0||!ZN(e)?{label:"-",percent:0,hasProgress:!1}:{label:`${n.completed}/${n.total}`,percent:n.completed/n.total*100,hasProgress:!0}}function e1({tasks:e,onMoveTask:n,onOpenDetail:s,addToast:i,globalPaused:r,onNewTask:o,onQuickCreate:l,availableModels:c,favoriteProviders:u=[],favoriteModels:d=[],onToggleFavorite:m,onToggleModelFavorite:h,onPlanningMode:f,onSubtaskBreakdown:p,onTasksUpdated:g,projectId:b,projectName:v,taskStuckTimeoutMs:x,searchQuery:y="",lastFetchTimeMs:k}){const[_,S]=a.useState("id"),[w,M]=a.useState("desc"),[N,D]=a.useState(null),[E,T]=a.useState(null),[U,K]=a.useState(null),R=Rr()==="mobile",[z,B]=a.useState(()=>Ou(b)),[J,Q]=a.useState(()=>Uu(b)),[C,L]=a.useState(()=>Bu(b));a.useEffect(()=>{typeof window<"u"&&bs("kb-dashboard-list-columns",JSON.stringify([...z]),b)},[b,z]),a.useEffect(()=>{typeof window<"u"&&bs("kb-dashboard-hide-done",J.toString(),b)},[J,b]),a.useEffect(()=>{typeof window<"u"&&bs("kb-dashboard-list-collapsed",JSON.stringify([...C]),b)},[C,b]);const[P,j]=a.useState(!1),O=a.useRef(null),[H,ge]=a.useState(()=>Hu(b));a.useEffect(()=>{B(Ou(b)),Q(Uu(b)),L(Bu(b)),ge(Hu(b))},[b]),a.useEffect(()=>{typeof window<"u"&&bs("kb-dashboard-selected-tasks",JSON.stringify([...H]),b)},[b,H]);const be=a.useCallback(Z=>{ge(le=>{const we=new Set(le);return we.has(Z)?we.delete(Z):we.add(Z),we})},[]),se=a.useCallback(()=>{ge(new Set)},[]),me=a.useCallback(Z=>{B(le=>{const we=new Set(le);return we.has(Z)?we.size>1&&we.delete(Z):we.add(Z),we})},[]);a.useEffect(()=>{if(!P)return;const Z=we=>{O.current&&!O.current.contains(we.target)&&j(!1)},le=we=>{we.key==="Escape"&&j(!1)};return document.addEventListener("mousedown",Z),document.addEventListener("keydown",le),()=>{document.removeEventListener("mousedown",Z),document.removeEventListener("keydown",le)}},[P]);const F={id:"ID",title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},de=a.useCallback(Z=>{_===Z?M(le=>le==="asc"?"desc":"asc"):(S(Z),M("asc"))},[_]),ne=a.useCallback(Z=>{K(le=>le===Z?null:Z)},[]),xe=a.useCallback(Z=>{L(le=>{const we=new Set(le);return we.has(Z)?we.delete(Z):we.add(Z),we})},[]),oe=a.useCallback(()=>{K(null)},[]),he=a.useMemo(()=>{let Z=y?e.filter(te=>te.id.toLowerCase().includes(y.toLowerCase())||te.title&&te.title.toLowerCase().includes(y.toLowerCase())||te.description.toLowerCase().includes(y.toLowerCase())):[...e];J&&!U&&(Z=Z.filter(te=>te.column!=="done"&&te.column!=="archived"));const we=[...U?Z.filter(te=>te.column===U):Z].sort((te,Je)=>{let dt=0;switch(_){case"id":dt=te.id.localeCompare(Je.id);break;case"title":dt=(te.title||te.description).localeCompare(Je.title||Je.description);break;case"status":dt=(te.status||"").localeCompare(Je.status||"");break;case"column":dt=te.column.localeCompare(Je.column);break}return w==="asc"?dt:-dt}),Ze={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};return we.forEach(te=>Ze[te.column].push(te)),Ze},[e,y,_,w,J,U]),ae=a.useMemo(()=>Object.values(he).reduce((Z,le)=>Z+le.length,0),[he]),je=a.useMemo(()=>e.filter(Z=>Z.column==="done"||Z.column==="archived").length,[e]),Ae=a.useMemo(()=>J?je:0,[J,je]),Oe=a.useCallback(()=>{const Z=Object.values(he).flat().filter(le=>le.column!=="archived").map(le=>le.id);ge(le=>{if(Z.every(Ze=>le.has(Ze))){const Ze=new Set(le);return Z.forEach(te=>Ze.delete(te)),Ze}else return new Set([...le,...Z])})},[he]),Qe=a.useMemo(()=>{const Z=Object.values(he).flat().filter(le=>le.column!=="archived");return Z.length===0?!1:Z.every(le=>H.has(le.id))},[he,H]),Xe=a.useMemo(()=>{const Z=Object.values(he).flat().filter(we=>we.column!=="archived");if(Z.length===0)return!1;const le=Z.filter(we=>H.has(we.id)).length;return le>0&&le<Z.length},[he,H]),[Ye,it]=a.useState("__no_change__"),[Be,Ge]=a.useState("__no_change__"),[re,ke]=a.useState("__no_change__"),[X,Te]=a.useState([]),[Le,fe]=a.useState(!1),_e=a.useMemo(()=>re&&re!=="__no_change__"?X.find(Z=>Z.id===re):void 0,[X,re]),[Ue,nt]=a.useState(!1);a.useEffect(()=>{if(H.size===0)return;let Z=!1;return(async()=>{fe(!0);try{const we=await So();Z||Te(we)}catch(we){console.error("Failed to fetch nodes for bulk edit",we),Z||Te([])}finally{Z||fe(!1)}})(),()=>{Z=!0}},[H.size]);const ve=a.useCallback(async()=>{if(H.size===0)return;const Z=Array.from(H).filter(we=>{const Ze=e.find(te=>te.id===we);return Ze&&Ze.column!=="archived"});if(Z.length===0){i("No valid tasks to update (archived tasks cannot be modified)","error");return}const le={taskIds:Z};if(Ye!=="__no_change__")if(Ye==="")le.modelProvider=null,le.modelId=null;else{const we=Ye.indexOf("/");we!==-1&&(le.modelProvider=Ye.slice(0,we),le.modelId=Ye.slice(we+1))}if(Be!=="__no_change__")if(Be==="")le.validatorModelProvider=null,le.validatorModelId=null;else{const we=Be.indexOf("/");we!==-1&&(le.validatorModelProvider=Be.slice(0,we),le.validatorModelId=Be.slice(we+1))}if(re!=="__no_change__"&&(re===""?le.nodeId=null:le.nodeId=re),Object.keys(le).length===1){i("No changes to apply","info");return}nt(!0);try{const we=await Ov(le.taskIds,le.modelProvider,le.modelId,le.validatorModelProvider,le.validatorModelId,void 0,void 0,le.nodeId,b);g&&g(we.updated),i(`Updated ${Z.length} task${Z.length===1?"":"s"}`,"success"),se(),it("__no_change__"),Ge("__no_change__"),ke("__no_change__")}catch(we){i(ye(we)||"Failed to update models","error")}finally{nt(!1)}},[H,e,Ye,Be,re,b,i,se,g]),ce=a.useCallback(Z=>{s(Z)},[s]),De=a.useCallback((Z,le)=>{if(le.paused){Z.preventDefault();return}Z.dataTransfer.setData("text/plain",le.id),Z.dataTransfer.effectAllowed="move",D(le.id)},[]),ue=a.useCallback(()=>{D(null),T(null)},[]),Re=a.useCallback((Z,le)=>{Z.preventDefault(),Z.dataTransfer.dropEffect="move",T(le)},[]),Ke=a.useCallback(()=>{T(null)},[]),Pe=a.useCallback(async(Z,le)=>{Z.preventDefault(),T(null);const we=Z.dataTransfer.getData("text/plain");if(we){if(le==="archived"){i("Tasks can only be archived via the archive button","error");return}try{await n(we,le)}catch(Ze){i(ye(Ze),"error")}}},[n,i]),ft=Z=>_!==Z?t.jsx(Jh,{size:14,className:"sort-icon"}):w==="asc"?t.jsx(zi,{size:14,className:"sort-icon active"}):t.jsx(jr,{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:O,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>j(Z=>!Z),"aria-expanded":P,"aria-haspopup":"menu",children:[t.jsx(gb,{size:14}),"Columns"]}),P&&t.jsx("div",{className:"list-column-dropdown",role:"menu",children:zc.map(Z=>{const le=z.has(Z),we=le&&z.size===1;return t.jsxs("label",{className:`list-column-dropdown-item${we?" disabled":""}`,role:"menuitem",title:we?"At least one column must be visible":"",children:[t.jsx("input",{type:"checkbox",checked:le,onChange:()=>me(Z),disabled:we}),t.jsx("span",{children:F[Z]})]},Z)})})]}),t.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>Q(Z=>!Z),"aria-pressed":J,title:J?"Show done tasks":"Hide done tasks",children:[J?t.jsx(Ca,{size:14}):t.jsx(sd,{size:14}),J?"Show Done":"Hide Done"]}),t.jsxs("div",{className:"list-stats",children:[U?`${ae} of ${e.length} tasks in ${Fn[U]}`:`${ae} of ${e.length} tasks`,Ae>0&&!U&&t.jsxs("span",{className:"list-stats-hidden",children:[" (",Ae," hidden)"]}),U&&t.jsx("button",{className:"btn btn-sm",onClick:oe,"aria-label":"Clear column filter",style:{marginLeft:"8px"},children:"Clear"})]}),H.size>0&&t.jsxs("div",{className:"list-selection-stats",children:[t.jsxs("span",{className:"selection-count",children:[H.size," selected"]}),t.jsx("button",{className:"btn btn-sm btn-link",onClick:se,children:"Clear"})]}),H.size>0&&c&&c.length>0&&t.jsxs("div",{className:"bulk-edit-toolbar",children:[t.jsx("span",{className:"bulk-edit-label",children:"Bulk Edit Models & Node:"}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx(Yn,{models:c,value:Ye,onChange:it,label:"Executor Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:u,onToggleFavorite:m,favoriteModels:d,onToggleModelFavorite:h})}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx(Yn,{models:c,value:Be,onChange:Ge,label:"Reviewer Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:u,onToggleFavorite:m,favoriteModels:d,onToggleModelFavorite:h})}),t.jsxs("div",{className:"bulk-edit-dropdown bulk-edit-node-wrap",children:[t.jsxs("select",{className:"select bulk-node-select",value:re,onChange:Z=>ke(Z.target.value),"aria-label":"Node Override",disabled:Le,children:[t.jsx("option",{value:"__no_change__",children:"No change"}),t.jsx("option",{value:"",children:"Use project default"}),X.map(Z=>t.jsx("option",{value:Z.id,children:`${XN(Z.status)} ${Z.name||Z.id} (${QN(Z.status)})`},Z.id))]}),_e?t.jsx(qi,{status:_e.status,showLabel:!0}):null]}),t.jsx("button",{className:"btn btn-primary btn-sm bulk-edit-apply-btn",onClick:ve,disabled:Ue||Ye==="__no_change__"&&Be==="__no_change__"&&re==="__no_change__",children:Ue?"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:Fi.map(Z=>{const le=e.filter(Je=>Je.column===Z).length,we=Z==="done"||Z==="archived",Ze=J&&we?0:le,te=J&&we&&le>0;return t.jsxs("div",{className:`list-drop-zone${E===Z?" drag-over":""}${U===Z?" active":""}`,onClick:()=>ne(Z),onDragOver:Je=>Re(Je,Z),onDragLeave:Ke,onDrop:Je=>Pe(Je,Z),"data-column":Z,children:[t.jsx("span",{className:"drop-zone-dot",style:{background:Oa[Z]}}),t.jsx("span",{className:"drop-zone-label",children:Fn[Z]}),t.jsx("span",{className:"drop-zone-count",children:te?`${Ze} of ${le}`:le})]},Z)})}),t.jsxs("div",{className:"list-table-container",children:[t.jsx("div",{className:"list-quick-entry-above-table",children:t.jsx(zp,{onCreate:l??(async()=>i("Task creation not available","error")),addToast:i,tasks:e,availableModels:c,onPlanningMode:f,onSubtaskBreakdown:p,projectId:b,autoExpand:!1,favoriteProviders:u,favoriteModels:d,onToggleFavorite:m,onToggleModelFavorite:h})}),ae===0?t.jsx("div",{className:"list-empty",children:y?"No tasks match your filter":"No tasks yet"}):R?t.jsx("div",{className:"list-cards",children:Fi.map(Z=>{if(U&&Z!==U||J&&(Z==="done"||Z==="archived")&&!U)return null;const le=he[Z],we=le.length===0;if(y&&we)return null;const Ze=C.has(Z);return t.jsxs(a.Fragment,{children:[t.jsxs("div",{className:`list-card-section-header${Ze?" list-section-header--collapsed":""}`,onClick:()=>xe(Z),"aria-expanded":!Ze,role:"button",tabIndex:0,onKeyDown:te=>{(te.key==="Enter"||te.key===" ")&&(te.preventDefault(),xe(Z))},children:[t.jsx(vn,{size:14,className:`list-section-chevron${Ze?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${Z}`}),t.jsx("span",{className:"list-section-title",children:Fn[Z]}),t.jsx("span",{className:"list-section-count",children:le.length})]}),!Ze&&t.jsx(t.Fragment,{children:we?t.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):le.map(te=>{const Je=te.status==="failed",dt=te.paused===!0,ut=Eo(te,x,k),Ct=!r&&!Je&&!dt&&!ut&&(te.column==="in-progress"||Fu.has(te.status)),yt=typeof te.status=="string"&&te.status.trim().length>0,bt=!!(te.dependencies&&te.dependencies.length>0),At=qu(te),Rt=At.hasProgress,Ht=H.size>0;return t.jsxs("div",{className:`list-card${Ct?" agent-active":""}${Ht?" list-card--selectable":""}`,onClick:()=>ce(te),"data-id":te.id,children:[Ht&&t.jsx("label",{className:"list-card-checkbox",onClick:Et=>Et.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:H.has(te.id),onChange:Et=>{Et.stopPropagation(),be(te.id)},onClick:Et=>Et.stopPropagation(),disabled:te.column==="archived","aria-label":`Select ${te.id}`})}),t.jsxs("div",{className:"list-card-row",children:[t.jsx("span",{className:"list-card-id",children:te.id}),te.executionMode==="fast"&&t.jsx("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",children:"Fast"}),t.jsx("span",{className:"list-card-spacer"}),ut?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):yt?t.jsx("span",{className:`list-status-badge list-status-badge--${te.column}${Je?" failed":""}${Ct?" pulsing":""}`,children:te.status}):null]}),t.jsx("div",{className:"list-card-row",children:t.jsx("div",{className:"list-card-title",children:te.title||te.description})}),(bt||Rt)&&t.jsxs("div",{className:"list-card-row list-card-meta",children:[bt&&t.jsxs("span",{className:"list-dep-badge",title:te.dependencies.join(", "),children:[t.jsx(ha,{size:12})," ",te.dependencies.length]}),Rt&&t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${At.percent}%`,backgroundColor:Oa[te.column]}})}),t.jsx("span",{className:"list-progress-label",children:At.label})]})]})]},te.id)})})]},Z)})}):t.jsxs("table",{className:"list-table",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{className:"list-header-cell list-header-checkbox",children:t.jsx("input",{type:"checkbox",checked:Qe,ref:Z=>{Z&&(Z.indeterminate=Xe)},onChange:Oe,"aria-label":"Select all visible tasks"})}),z.has("id")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>de("id"),children:["ID ",ft("id")]}),z.has("title")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>de("title"),children:["Title ",ft("title")]}),z.has("status")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>de("status"),children:["Status ",ft("status")]}),z.has("column")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>de("column"),children:["Column ",ft("column")]}),z.has("dependencies")&&t.jsx("th",{className:"list-header-cell",children:"Dependencies"}),z.has("progress")&&t.jsx("th",{className:"list-header-cell",children:"Progress"})]})}),t.jsx("tbody",{children:Fi.map(Z=>{if(U&&Z!==U||J&&(Z==="done"||Z==="archived")&&!U)return null;const le=he[Z],we=le.length===0;if(y&&we)return null;const Ze=C.has(Z);return t.jsxs(a.Fragment,{children:[t.jsx("tr",{className:`list-section-header${Ze?" list-section-header--collapsed":""}`,onClick:()=>xe(Z),"aria-expanded":!Ze,children:t.jsxs("th",{colSpan:z.size+1,className:"list-section-cell",children:[t.jsx(vn,{size:14,className:`list-section-chevron${Ze?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${Z}`}),t.jsx("span",{className:"list-section-title",children:Fn[Z]}),t.jsx("span",{className:"list-section-count",children:le.length})]})}),!Ze&&t.jsx(t.Fragment,{children:we?t.jsx("tr",{className:"list-section-empty",children:t.jsx("td",{colSpan:z.size+1,className:"list-empty-cell",children:"No tasks"})}):le.map(te=>{const Je=te.status==="failed",dt=te.paused===!0,ut=Eo(te,x,k),Ct=!r&&!Je&&!dt&&!ut&&(te.column==="in-progress"||Fu.has(te.status)),yt=N===te.id;return t.jsxs("tr",{className:`list-row${Je?" failed":""}${dt?" paused":""}${ut?" stuck":""}${Ct?" agent-active":""}${yt?" dragging":""}`,onClick:()=>ce(te),draggable:!dt,onDragStart:bt=>De(bt,te),onDragEnd:ue,"data-id":te.id,children:[t.jsx("td",{className:"list-cell list-cell-checkbox",children:t.jsx("input",{type:"checkbox",checked:H.has(te.id),onChange:bt=>{bt.stopPropagation(),be(te.id)},onClick:bt=>bt.stopPropagation(),disabled:te.column==="archived","aria-label":`Select ${te.id}`})}),z.has("id")&&t.jsx("td",{className:"list-cell list-cell-id",children:te.id}),z.has("title")&&t.jsx("td",{className:"list-cell list-cell-title",children:t.jsxs("div",{className:"list-title-content",children:[te.executionMode==="fast"&&t.jsx("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",children:"Fast"}),t.jsx("span",{className:"list-title-text",children:te.title||te.description})]})}),z.has("status")&&t.jsx("td",{className:"list-cell",children:ut?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):te.status?t.jsx("span",{className:`list-status-badge list-status-badge--${te.column}${Je?" failed":""}${Ct?" pulsing":""}`,children:te.status}):t.jsx("span",{className:"list-status-badge",children:"-"})}),z.has("column")&&t.jsx("td",{className:"list-cell",children:t.jsx("span",{className:"list-column-badge",style:{background:`${Oa[te.column]}20`,color:Oa[te.column]},children:Fn[te.column]})}),z.has("dependencies")&&t.jsx("td",{className:"list-cell list-cell-deps",children:te.dependencies&&te.dependencies.length>0?t.jsxs("span",{className:"list-dep-badge",title:te.dependencies.join(", "),children:[t.jsx(ha,{size:12})," ",te.dependencies.length]}):"-"}),z.has("progress")&&t.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const bt=qu(te);return bt.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:`${bt.percent}%`,backgroundColor:Oa[te.column]}})}),t.jsx("span",{className:"list-progress-label",children:bt.label})]}):"-"})()})]},te.id)})})]},Z)})})]})]})]})}const t1={active:{label:"Active",color:"var(--success)",icon:Sn},paused:{label:"Paused",color:"var(--warning)",icon:Hs},errored:{label:"Error",color:"var(--color-error)",icon:us},initializing:{label:"Initializing",color:"var(--info)",icon:ot}};function n1(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 s1(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 i1(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 a1({project:e,health:n,onSelect:s,onPause:i,onResume:r,onRemove:o,node:l,nodeNameFallback:c,isLoading:u=!1}){const[d,m]=a.useState(!1),h=t1[e.status],f=h.icon,p=a.useCallback(()=>{s(e)},[s,e]),g=a.useCallback(_=>{_.stopPropagation(),i(e)},[i,e]),b=a.useCallback(_=>{_.stopPropagation(),r(e)},[r,e]),v=a.useCallback(_=>{if(_.stopPropagation(),!d){m(!0);return}o(e),m(!1)},[d,o,e]),x=e.status==="paused",y=e.status==="errored",k=e.status==="initializing";return t.jsxs("div",{className:`project-card ${u?"project-card-loading":""} ${y?"project-card-errored":""}`,onClick:p,"data-project-id":e.id,role:"button",tabIndex:0,onKeyDown:_=>{(_.key==="Enter"||_.key===" ")&&(_.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:s1(e.path)})]}),t.jsxs("div",{className:"project-card-status-badge",style:{color:h.color,borderColor:h.color},children:[t.jsx(f,{size:12,className:k?"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:n1(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(Sn,{size:14}),t.jsx("span",{children:"Resume"})]}):t.jsxs("button",{className:"project-card-action project-card-action-pause",onClick:g,disabled:u||k,title:k?"Cannot pause while initializing":"Pause project","aria-label":"Pause project",children:[t.jsx(Hs,{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(kr,{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(rn,{size:14}),t.jsx("span",{children:d?"Confirm":""})]})]})]})]})}const r1=a.memo(a1,i1);function o1(){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(Is,{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(yn,{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(us,{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 l1=1e4,Vu=5;function c1(e){const[n,s]=a.useState({}),[i,r]=a.useState(!0),[o,l]=a.useState(null),c=a.useRef(null),u=a.useRef(null),d=a.useRef(!1),m=a.useCallback(async()=>{if(e.length===0){s({}),d.current||(d.current=!0),r(!1);return}u.current&&u.current.abort(),u.current=new AbortController,!d.current&&r(!0),l(null);try{const p={};for(let g=0;g<e.length;g+=Vu){const b=e.slice(g,g+Vu),v=await Promise.allSettled(b.map(async x=>{try{return await ou(x)}catch{return null}}));if(b.forEach((x,y)=>{const k=v[y];p[x]=k.status==="fulfilled"?k.value:null}),u.current?.signal.aborted)return}s(p),d.current=!0}catch(p){if(p instanceof Error&&p.name==="AbortError")return;l(p instanceof Error?p.message:"Failed to fetch health data"),d.current=!0}finally{r(!1)}},[e]),h=a.useCallback(async f=>{try{const p=await ou(f);s(g=>({...g,[f]:p}))}catch(p){console.error(`Failed to fetch health for project ${f}:`,p)}},[]);return a.useEffect(()=>(d.current=!1,m(),()=>{u.current&&u.current.abort()}),[m]),a.useEffect(()=>{if(e.length!==0)return c.current&&clearInterval(c.current),c.current=setInterval(()=>{m()},l1),()=>{c.current&&(clearInterval(c.current),c.current=null)}},[m,e.length]),{healthMap:n,loading:i,error:o,refresh:m,refreshProject:h}}function d1({projects:e,loading:n=!1,onSelectProject:s,onAddProject:i,onPauseProject:r,onResumeProject:o,onRemoveProject:l,nodes:c=[]}){const[u,d]=a.useState("all"),[m,h]=a.useState(null),[f,p]=a.useState("activity"),[g,b]=a.useState("desc");a.useEffect(()=>{if(typeof window>"u")return;const K=localStorage.getItem("kb-dashboard-recent-projects");if(K)try{const $=JSON.parse(K);x($)}catch{}},[]);const[v,x]=a.useState([]),y=a.useMemo(()=>e.map(K=>K.id),[e]),{healthMap:k,loading:_}=c1(y),S=a.useMemo(()=>e.map(K=>({project:K,health:k[K.id]||null})),[e,k]),w=a.useMemo(()=>{let K=[...S];return u!=="all"&&(K=K.filter(({project:$})=>$.status===u)),m!==null&&(K=K.filter(({project:$})=>$.nodeId===m)),K},[S,u,m]),M=a.useMemo(()=>{const K=[...w];return K.sort(($,R)=>{let z=0;switch(f){case"name":z=$.project.name.localeCompare(R.project.name);break;case"activity":{const B=$.project.lastActivityAt||$.health?.lastActivityAt||$.project.updatedAt,J=R.project.lastActivityAt||R.health?.lastActivityAt||R.project.updatedAt;z=new Date(J).getTime()-new Date(B).getTime();break}case"status":{const B={errored:0,initializing:1,paused:2,active:3};z=B[$.project.status]-B[R.project.status];break}}return g==="asc"?z:-z}),K},[w,f,g]),N=a.useMemo(()=>{const K=e.length,$=e.filter(L=>L.status==="active").length,R=e.filter(L=>L.status==="errored").length,z=new Set;e.forEach(L=>{L.nodeId&&z.add(L.nodeId)});const B=z.size||(K>0?1:0);let J=0,Q=0,C=0;return Object.values(k).forEach(L=>{L&&(J+=L.activeTaskCount,Q+=L.totalTasksCompleted,C+=L.inFlightAgentCount)}),{totalProjects:K,activeProjects:$,erroredProjects:R,totalNodes:B,totalActiveTasks:J,totalCompletedTasks:Q,totalInFlightAgents:C}},[e,k]),D=a.useMemo(()=>({all:e.length,active:e.filter(K=>K.status==="active").length,paused:e.filter(K=>K.status==="paused").length,errored:e.filter(K=>K.status==="errored").length}),[e]),E=a.useMemo(()=>{const K=new Map;return e.forEach($=>{const R=$.nodeId,z=K.get(R);if(z)z.count++;else{const J=c.find(Q=>Q.id===R)?.name??$._sourceNodeName??"Local";K.set(R,{name:J,count:1})}}),Array.from(K.entries()).map(([$,{name:R,count:z}])=>({nodeId:$??null,name:R,count:z}))},[e,c]),T=a.useCallback(K=>{const $=[K.id,...v.filter(R=>R!==K.id)].slice(0,3);x($),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify($)),s(K)},[s,v]);return n||_&&e.length>0&&Object.keys(k).length===0?t.jsx(o1,{}):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(nr,{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(on,{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(Hi,{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:N.totalProjects}),t.jsx("span",{className:"project-stat__label",children:"Total"})]})]}),t.jsxs("div",{className:"project-stat project-stat--active",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Is,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:N.totalActiveTasks}),t.jsx("span",{className:"project-stat__label",children:"Active Tasks"})]})]}),t.jsxs("div",{className:"project-stat project-stat--completed",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(yn,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:N.totalCompletedTasks}),t.jsx("span",{className:"project-stat__label",children:"Completed"})]})]}),N.erroredProjects>0&&t.jsxs("div",{className:"project-stat project-stat--error",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(us,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:N.erroredProjects}),t.jsx("span",{className:"project-stat__label",children:"Errored"})]})]}),N.totalNodes>1&&t.jsxs("div",{className:"project-stat project-stat--nodes",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(hr,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:N.totalNodes}),t.jsx("span",{className:"project-stat__label",children:"Nodes"})]})]})]}),t.jsxs("button",{className:"btn btn-primary project-overview__add-btn",onClick:i,children:[t.jsx(on,{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:D.all})]}),t.jsxs("button",{className:`project-filter-tab ${u==="active"?"active":""}`,onClick:()=>d("active"),children:["Active",t.jsx("span",{className:"project-filter-count",children:D.active})]}),t.jsxs("button",{className:`project-filter-tab ${u==="paused"?"active":""}`,onClick:()=>d("paused"),children:["Paused",t.jsx("span",{className:"project-filter-count",children:D.paused})]}),t.jsxs("button",{className:`project-filter-tab ${u==="errored"?"active":""} ${D.errored>0?"has-errors":""}`,onClick:()=>d("errored"),children:["Errored",t.jsx("span",{className:"project-filter-count",children:D.errored})]})]}),E.length>1&&t.jsxs("div",{className:"project-node-filter",children:[t.jsx(hr,{size:14}),t.jsxs("select",{value:m??"",onChange:K=>{h(K.target.value||null)},className:"project-node-filter-select","aria-label":"Filter by node",children:[t.jsx("option",{value:"",children:"All Nodes"}),E.map(({nodeId:K,name:$,count:R})=>t.jsxs("option",{value:K??"",children:[$," (",R,")"]},K??"local"))]})]}),t.jsxs("div",{className:"project-sort",children:[t.jsx(jo,{size:14}),t.jsxs("select",{value:`${f}-${g}`,onChange:K=>{const[$,R]=K.target.value.split("-");p($),b(R)},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(Jh,{size:14})]})]}),t.jsx("div",{className:"project-grid",children:M.map(({project:K,health:$})=>{const R=c.find(B=>B.id===K.nodeId),z=R?void 0:K._sourceNodeName;return t.jsx(r1,{project:K,health:$,node:R,nodeNameFallback:z,onSelect:T,onPause:r,onResume:o,onRemove:l},K.id)})}),M.length===0&&t.jsxs("div",{className:"project-overview__no-results",children:[t.jsx(jo,{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 u1=45e3,m1=3e3,h1=2e3,p1=1500,Wu="fusion:sse-client-id";let na=null;const Ni=new Map;function Ku(){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 Op(){if(!(typeof window>"u")){if(na)return na;try{const e=window.sessionStorage.getItem(Wu);if(e)return na=e,e;const n=Ku();return window.sessionStorage.setItem(Wu,n),na=n,n}catch{return na=Ku(),na}}}function Up(e){if(!(typeof window>"u"))try{return{parsed:new URL(e,window.location.origin),preserveRelativePath:e.startsWith("/")}}catch{return}}function Bp(e){return e.origin===window.location.origin&&e.pathname==="/api/events"}function f1(e){const n=Op();if(!n)return e;const s=Up(e);return!s||!Bp(s.parsed)?e:(s.parsed.searchParams.set("clientId",n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function pd(e,n){const s=Op();if(!s)return;const i=Up(e);if(!i||!Bp(i.parsed))return;const r=new URL(`/api/events/${n}`,window.location.origin);r.searchParams.set("clientId",s);const o=i.parsed.searchParams.get("projectId");return o&&r.searchParams.set("projectId",o),ii(`${r.pathname}${r.search}${r.hash}`)}function g1(e){if(typeof window>"u")return;const n=pd(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 Xo(e){e.keepaliveTimer&&(clearInterval(e.keepaliveTimer),e.keepaliveTimer=null)}function Gu(e){if(typeof window>"u"||typeof window.fetch!="function")return;const n=pd(e.url,"keepalive");if(!n)return;const s=typeof AbortController<"u"?new AbortController:null,i=s?window.setTimeout(()=>s.abort(),p1):null;window.fetch(n,{method:"POST",cache:"no-store",signal:s?.signal}).catch(()=>{}).finally(()=>{i!==null&&window.clearTimeout(i)})}function b1(e){Xo(e),pd(e.url,"keepalive")&&(Gu(e),e.keepaliveTimer=window.setInterval(()=>{Gu(e)},h1))}if(typeof window<"u"){const e=()=>{for(const s of Array.from(Ni.values()))if(!s.closed){if(Xo(s),g1(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(Ni.values()))i.subscribers.size!==0&&(i.closed=!1,fd(i))};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e),window.addEventListener("pageshow",n)}function sr(e){e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),e.heartbeatTimer=setTimeout(()=>{Hp(e)},u1)}function Hp(e){if(e.heartbeatTimer&&(clearTimeout(e.heartbeatTimer),e.heartbeatTimer=null),e.es&&(e.es.close(),e.es=null),Xo(e),e.nativeListeners.clear(),e.closed||e.subscribers.size===0||e.reconnectTimer)return;const n=Ni.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=Ni.get(e.url);s&&s===e&&e.subscribers.size>0&&fd(e)},m1)}}function fd(e){if(e.es||e.closed)return;e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=null);const n=new EventSource(ii(f1(e.url)));e.es=n,b1(e),n.addEventListener("open",()=>{sr(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);Hp(e)}),n.addEventListener("message",()=>sr(e)),n.addEventListener("heartbeat",()=>sr(e)),qp(e),sr(e)}function qp(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=>{sr(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 x1(e){e.closed=!0,e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),Xo(e),e.reconnectTimer&&clearTimeout(e.reconnectTimer),e.es&&e.es.close(),e.es=null,e.nativeListeners.clear(),Ni.delete(e.url)}function Ks(e,n={}){let s=Ni.get(e);s||(s={url:e,es:null,subscribers:new Set,nativeListeners:new Map,heartbeatTimer:null,keepaliveTimer:null,reconnectTimer:null,hasOpenedOnce:!1,closed:!1},Ni.set(e,s));const i={events:new Map,onOpen:n.onOpen,onReconnect:n.onReconnect,onError:n.onError};if(n.events)for(const[l,c]of Object.entries(n.events)){let u=i.events.get(l);u||(u=new Set,i.events.set(l,u)),u.add(c)}s.subscribers.add(i);const r=!!s.es&&s.hasOpenedOnce;fd(s),qp(s),r&&queueMicrotask(()=>{s.subscribers.has(i)&&i.onOpen?.()});let o=!0;return()=>{if(!o)return;o=!1;const l=Ni.get(e);l&&(l.subscribers.delete(i),l.subscribers.size===0&&x1(l))}}const gd="kb-planning-last-description",bd="kb-subtask-last-description",xd="kb-mission-last-goal";function v1(e,n){bs(gd,e,n)}function y1(e){return Qn(gd,e)||""}function sa(e){xr(gd,e)}function j1(e,n){bs(bd,e,n)}function k1(e){return Qn(bd,e)||""}function El(e){xr(bd,e)}function w1(e,n){bs(xd,e,n)}function N1(e){return Qn(xd,e)||""}function vi(e){xr(xd,e)}function S1(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 C1(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 E1(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 $s({entries:e,defaultShowThinking:n=!1}){const[s,i]=a.useState({}),r=E1(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?S1(o):void 0,h=o.question&&m!==void 0?C1(o.question,m):"";return t.jsxs("div",{className:"conversation-entry",children:[c?t.jsxs("div",{className:"conversation-entry-question",children:[t.jsxs("span",{className:"conversation-entry-question-label",children:["Q",o.questionNumber]}),t.jsx("p",{children:o.question?.question})]}):t.jsx("div",{className:"conversation-entry-question",children:t.jsx("span",{className:"conversation-entry-question-label",children:"AI Reasoning"})}),c&&t.jsxs("div",{className:"conversation-entry-response",children:[t.jsx("strong",{children:"Your response"}),t.jsx("p",{children:h||"—"})]}),u&&t.jsxs("div",{className:"conversation-entry-thinking",children:[t.jsxs("button",{type:"button",className:"conversation-thinking-toggle",onClick:()=>{i(f=>({...f,[l]:!d}))},"aria-expanded":d,children:[t.jsx("span",{"aria-hidden":"true",children:d?"▾":"▸"}),d?`Hide ${c?"AI thinking":"AI reasoning"}`:`Show ${c?"AI thinking":"AI reasoning"}`]}),d&&t.jsx("pre",{children:o.thinkingOutput})]})]},`${o.question?.id??"thinking"}-${l}`)})})}const Ju="fusion-tab-id";function _1(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Ji(){if(typeof window>"u")return"server-tab";const e=window.sessionStorage.getItem(Ju);if(e)return e;const n=_1();return window.sessionStorage.setItem(Ju,n),n}function Zo(e){const n=a.useMemo(()=>Ji(),[]),[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(Zk(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=ew(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=ii(`/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:Ks("/api/events",{events:{"ai_session:updated":m=>{try{const h=JSON.parse(m.data);if(h.id!==e)return;const f=h.lockedByTab??null;o(f),i(!!(f&&f!==n))}catch{}}}}),[e,n]);const u=a.useCallback(async()=>{if(e){c(!0);try{await Promise.resolve(tw(e,n)),i(!1),o(null)}finally{c(!1)}}},[e,n]);return{isLockedByOther:s,currentHolder:r,takeControl:u,isLoading:l}}const M1="fusion:ai-session-sync",Yu="fusion:ai-session-sync",A1=3e4,R1=6e4;function Xs(){return Date.now()}function T1(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Qu(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 P1{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=T1(),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:Xs()})}broadcastUpdate(n){const s=n.timestamp??Xs();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??Xs();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=Xs();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=Xs();this.releaseTabOwnership(n,s,i),this.ownedSessions.delete(n),this.publish({type:"tab:inactive",tabId:s,sessionId:n,timestamp:i})}broadcastHeartbeat(n){const s=Xs();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(M1),this.channel.onmessage=s=>{const i=Qu(s.data);i&&this.handleIncomingMessage(i)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==Yu||!s.newValue))try{const i=JSON.parse(s.newValue),r=Qu(i.message);r&&this.handleIncomingMessage(r)}catch{}};window.addEventListener("storage",n),this.cleanupStorageListener=()=>{window.removeEventListener("storage",n)}}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{const n=Xs();this.updateHeartbeat(this.tabId,n),this.publish({type:"tab:heartbeat",tabId:this.tabId,timestamp:n})},A1)}startStaleSweep(){this.staleSweepInterval=setInterval(()=>{this.emit()},1e4)}setupBeforeUnloadCleanup(){const n=()=>{for(const[s,i]of this.ownedSessions.entries()){const r=Xs();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(Yu,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:Xs()});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=Xs(),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>R1;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 Zs=new P1;function Ma(){const e=a.useSyncExternalStore(c=>Zs.subscribe(c),()=>Zs.getSnapshot(),()=>Zs.getSnapshot());a.useEffect(()=>{Zs.requestSync()},[]);const n=a.useCallback(c=>{Zs.broadcastUpdate(c)},[]),s=a.useCallback(c=>{Zs.broadcastCompleted(c)},[]),i=a.useCallback((c,u)=>{Zs.broadcastLock(c,u)},[]),r=a.useCallback((c,u)=>{Zs.broadcastUnlock(c,u)},[]),o=a.useCallback(c=>{Zs.broadcastHeartbeat(c)},[]),l=a.useCallback(()=>{Zs.requestSync()},[]);return{tabId:e.tabId,sessions:e.sessions,activeTabMap:e.activeTabMap,broadcastUpdate:n,broadcastCompleted:s,broadcastLock:i,broadcastUnlock:r,broadcastHeartbeat:o,requestSync:l}}function I1(e,n){return e&&n?`${e}/${n}`:""}function $1(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 D1=["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 L1({isOpen:e,onClose:n,onMissionCreated:s,projectId:i,initialGoal:r,resumeSessionId:o}){const[l,c]=a.useState(""),[u,d]=a.useState({type:"initial"}),[m,h]=a.useState(null),[f,p]=a.useState([]),[g,b]=a.useState([]),[v,x]=a.useState(null),[y,k]=a.useState(!1),_=a.useRef(!1),[S,w]=a.useState(""),[M,N]=a.useState(!0),[D,E]=a.useState(!1),[T,U]=a.useState(!1),[K,$]=a.useState(!1),R=a.useRef(null),z=a.useRef(null),B=a.useRef(null),J=a.useRef(null),[Q,C]=a.useState(o??null),L=a.useMemo(()=>Ji(),[]),{isLockedByOther:P,takeControl:j,isLoading:O}=Zo(e?Q:null),{activeTabMap:H,broadcastUpdate:ge,broadcastCompleted:be,broadcastLock:se,broadcastUnlock:me,broadcastHeartbeat:F}=Ma(),{confirm:de}=Ws(),[ne,xe]=a.useState(void 0),[oe,he]=a.useState(void 0),[ae,je]=a.useState([]),[Ae,Oe]=a.useState(!0),[Qe,Xe]=a.useState(null),[Ye,it]=a.useState([]),[Be,Ge]=a.useState([]),re=I1(ne,oe);a.useEffect(()=>{(async()=>{try{Oe(!0);const le=await ms();je(le.models),it(le.favoriteProviders),Ge(le.favoriteModels)}catch(le){Xe(ye(le)||"Failed to load models")}finally{Oe(!1)}})()},[]);const ke=a.useCallback(Z=>{it(le=>{const we=le,te=we.includes(Z)?we.filter(Je=>Je!==Z):[Z,...we];return hn({favoriteProviders:te,favoriteModels:Be}).catch(()=>{it(we)}),te})},[Be]),X=a.useCallback(Z=>{Ge(le=>{const we=le,te=we.includes(Z)?we.filter(Je=>Je!==Z):[Z,...we];return hn({favoriteProviders:Ye,favoriteModels:te}).catch(()=>{Ge(we)}),te})},[Ye]),Te=a.useCallback((Z,le)=>{if(!Z||!le)return"Using default";const we=ae.find(Ze=>Ze.provider===Z&&Ze.id===le);return we?`${we.provider}/${we.id}`:`${Z}/${le}`},[ae]),Le=a.useCallback(Z=>{z.current?.close();const le=Uk(Z,i,{onThinking:we=>{w(Ze=>Ze+we),ge({sessionId:Z,status:"generating",needsInput:!1,owningTabId:L,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onQuestion:we=>{E(!1),U(!1),vi(i),d({type:"question",sessionId:Z,question:we}),w(""),k(!0),ge({sessionId:Z,status:"awaiting_input",needsInput:!0,owningTabId:L,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onSummary:we=>{E(!1),U(!1),vi(i),d({type:"summary",sessionId:Z,summary:we}),x(we),w(""),k(!0),ge({sessionId:Z,status:"complete",needsInput:!1,owningTabId:L,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onError:we=>{const Ze=we||"Session failed while contacting the AI.";E(!1),U(!1),h(null),d({type:"error",sessionId:Z,errorMessage:Ze}),w(""),k(!0),B.current=Z,ge({sessionId:Z,status:"error",needsInput:!1,owningTabId:L,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null}),be({sessionId:Z,status:"error"})},onComplete:()=>{E(!1),U(!1),B.current=null,be({sessionId:Z,status:"complete"})},onConnectionStateChange:we=>{E(we==="reconnecting")}});z.current=le},[be,ge,l,i,L]),fe=a.useCallback(async Z=>{const le=Z??l;if(le.trim()){h(null),w(""),p([]),b([]),E(!1),d({type:"loading"});try{const{sessionId:we}=await Lk(le.trim(),i,ne&&oe?{modelProvider:ne,modelId:oe}:void 0);B.current=we,C(we),vi(i),Le(we),p([])}catch(we){E(!1),h(ye(we)||"Failed to start interview session"),d({type:"initial"}),B.current=null,C(null)}}},[Le,l,ne,oe,i]);a.useEffect(()=>{e&&u.type==="initial"&&R.current?.focus()},[e,u.type]),a.useEffect(()=>{if(e&&r&&!_.current&&u.type==="initial"){c(r);const Z=setTimeout(()=>{_.current=!0,fe(r)},0);return()=>clearTimeout(Z)}else if(e&&!r&&!_.current&&u.type==="initial"){const Z=N1(i);Z&&c(Z)}},[e,r,u.type,fe]),a.useEffect(()=>{e||(_.current=!1,E(!1),U(!1),C(null))},[e]),a.useEffect(()=>{if(!e||!o||u.type!=="initial")return;let Z=!1;return hi(o).then(le=>{if(Z||!le)return;const we=ba(le.conversationHistory);if(b(we),C(le.id),p(we.map(Ze=>Ze.response).filter(Ze=>!!(Ze&&typeof Ze=="object"&&!Array.isArray(Ze)))),le.status==="awaiting_input"&&le.currentQuestion)try{vi(i);const Ze=JSON.parse(le.currentQuestion);B.current=le.id,k(!0),d({type:"question",sessionId:le.id,question:Ze})}catch{h("Failed to restore session question.")}else if(le.status==="complete"&&le.result)try{vi(i);const Ze=JSON.parse(le.result);B.current=le.id,k(!0),x(Ze),d({type:"summary",sessionId:le.id,summary:Ze})}catch{h("Failed to restore session result.")}else le.status==="generating"?(B.current=le.id,k(!0),le.thinkingOutput&&w(le.thinkingOutput),d({type:"loading"}),Le(le.id)):le.status==="error"&&(B.current=le.id,k(!0),h(null),d({type:"error",sessionId:le.id,errorMessage:le.error??"The session encountered an error."}))}).catch(()=>{Z||h("Failed to resume session.")}),()=>{Z=!0}},[Le,e,o,u.type,i]),a.useEffect(()=>{if(!e){J.current&&(me(J.current,L),J.current=null);return}if(Q&&J.current!==Q){J.current&&me(J.current,L),se(Q,L),J.current=Q;return}!Q&&J.current&&(me(J.current,L),J.current=null)},[se,me,e,Q,L]),a.useEffect(()=>{if(!e||!Q||J.current!==Q)return;F(L);const Z=setInterval(()=>{F(L)},3e4);return()=>{clearInterval(Z)}},[F,e,Q,L]),a.useEffect(()=>()=>{z.current?.close(),z.current=null,J.current&&(me(J.current,L),J.current=null)},[me,L]),a.useEffect(()=>{if(!e)return;const Z=le=>{(u.type==="question"||u.type==="summary")&&(le.preventDefault(),le.returnValue=""),z.current?.close()};return window.addEventListener("beforeunload",Z),()=>window.removeEventListener("beforeunload",Z)},[e,u]);const _e=a.useCallback(()=>{z.current?.close(),z.current=null,n()},[n]),Ue=a.useCallback(async()=>{if(l&&w1(l,i),!(y&&!await de({title:"Close Interview",message:"Are you sure you want to close? Your interview progress will be lost.",danger:!0}))){if(z.current?.close(),z.current=null,u.type==="question"||u.type==="summary"||u.type==="error")try{await kp(u.sessionId,i,L)}catch{}c(""),d({type:"initial"}),h(null),p([]),b([]),x(null),w(""),E(!1),U(!1),k(!1),$(!1),xe(void 0),he(void 0),B.current=null,C(null),n()}},[l,y,u,n,i,L,de]);a.useEffect(()=>{if(!e)return;const Z=le=>{le.key==="Escape"&&Ue()};return document.addEventListener("keydown",Z),()=>document.removeEventListener("keydown",Z)},[e,Ue]);const nt=a.useCallback(async Z=>{if(u.type!=="question")return;const{sessionId:le}=u;h(null),p(we=>[...we,Z]),b(we=>[...we,{question:u.question,response:Z}]),d({type:"loading"}),w("");try{Le(le),await zk(le,Z,i,L),k(!0)}catch(we){z.current?.close(),z.current=null,h(ye(we)||"Failed to submit response"),d({type:"question",sessionId:le,question:u.question})}},[u,i,L,Le]),ve=a.useCallback(async()=>{if(u.type!=="error")return;const Z=u.sessionId;h(null),U(!0),w(""),d({type:"loading"}),Le(Z);try{B.current=Z,C(Z),await Fk(Z,i,L)}catch(le){let we=le;if((ye(le)||"").includes("not in an error state"))try{const te=await hi(Z);if(!te)throw new Error("Failed to refresh interview session.");const Je=ba(te.conversationHistory);if(b(Je),p(Je.map(dt=>dt.response).filter(dt=>!!(dt&&typeof dt=="object"&&!Array.isArray(dt)))),B.current=te.id,C(te.id),k(!0),te.status==="generating")w(te.thinkingOutput??""),d({type:"loading"}),z.current?.isConnected()||Le(te.id);else if(te.status==="awaiting_input"){if(!te.currentQuestion)throw new Error("Interview session is awaiting input but has no current question.");vi(i);const dt=JSON.parse(te.currentQuestion);d({type:"question",sessionId:te.id,question:dt}),z.current?.isConnected()||Le(te.id)}else if(te.status==="complete"){if(!te.result)throw new Error("Interview session is complete but has no result.");vi(i);const dt=JSON.parse(te.result);x(dt),d({type:"summary",sessionId:te.id,summary:dt})}else te.status==="error"&&d({type:"error",sessionId:te.id,errorMessage:te.error??"Retry failed. Please try again."});E(!1);return}catch(te){we=te}z.current?.close(),z.current=null,d({type:"error",sessionId:Z,errorMessage:ye(we)||"Retry failed. Please try again."}),E(!1)}finally{U(!1)}},[Le,i,L,u]),ce=a.useCallback(async()=>{if(u.type==="summary"){h(null),$(!0);try{const Z=await Ok(u.sessionId,v||void 0,i);s(Z),vi(i),z.current?.close(),z.current=null,c(""),d({type:"initial"}),h(null),p([]),b([]),x(null),w(""),E(!1),U(!1),k(!1),$(!1),B.current=null,C(null),n()}catch(Z){h(ye(Z)||"Failed to create mission"),$(!1)}}},[u,v,s,n,i]),De=()=>u.type==="question"?Math.min(f.length+1,6):6,ue=u.type==="loading"||u.type==="question"||u.type==="summary"||u.type==="error",Re=Q?H.get(Q):null,Ke=Re&&Re.tabId!==L,Pe=!!(Ke&&!Re.stale),ft=P&&(!Ke||Re.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Z=>Z.target===Z.currentTarget&&Ue(),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(xs,{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:_e,title:"Send to background","aria-label":"Send to background",children:t.jsx(Sr,{size:16})}),t.jsx("button",{className:"modal-close",onClick:Ue,"aria-label":"Close",children:t.jsx(Wt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[m&&t.jsx("div",{className:"form-error planning-error",children:m}),D&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Pe&&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(rs,{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:R,id:"mission-goal",rows:4,className:"planning-textarea",placeholder:"e.g., Build a real-time collaborative document editor with presence, comments, and version history...",value:l,onChange:Z=>c(Z.target.value),onKeyDown:Z=>{Z.key==="Enter"&&!Z.shiftKey&&l.trim()&&(Z.preventDefault(),fe())}})]}),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:D1.map((Z,le)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>c(Z),children:Z.length>45?Z.slice(0,45)+"...":Z},le))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"mission-interview-modal-model",className:"form-label",children:["Planning Model",Ae&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(Yn,{id:"mission-interview-modal-model",label:"Planning Model",value:re,onChange:Z=>{const{provider:le,modelId:we}=$1(Z);xe(le),he(we)},models:ae,disabled:Ae,favoriteProviders:Ye,onToggleFavorite:ke,favoriteModels:Be,onToggleModelFavorite:X}),Qe&&t.jsxs("div",{className:"form-hint form-hint-error",children:[Qe," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{Oe(!0);const Z=await ms();je(Z.models),it(Z.favoriteProviders),Ge(Z.favoriteModels),Xe(null)}catch(Z){Xe(ye(Z)||"Failed to load models")}finally{Oe(!1)}})()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${ne&&oe?"model-badge-custom":"model-badge-default"}`,children:Te(ne,oe)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>fe(),disabled:!l.trim(),children:[t.jsx(xs,{size:16,className:"icon-mr-8"}),"Start Interview"]})})]}),u.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(ot,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:S?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>N(!M),type:"button",children:M?"Hide thinking":"Show thinking"}),M&&S&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:S})})]})]}),u.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[g.length>0&&t.jsxs(t.Fragment,{children:[t.jsx($s,{entries:g}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:u.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void ve(),disabled:T,children:[T?t.jsx(ot,{size:14,className:"spin"}):t.jsx($n,{size:14}),t.jsx("span",{className:"icon-ml-6",children:T?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Ue,disabled:T,children:"Cancel"})]})]})]})}),u.type==="question"&&t.jsx(z1,{question:u.question,progress:De(),historyEntries:g,onSubmit:nt}),u.type==="summary"&&v&&t.jsx(F1,{summary:v,historyEntries:g,onSummaryChange:x,onApprove:ce,onStartOver:()=>{d({type:"initial"}),k(!1),x(null),p([]),b([]),C(null),z.current?.close(),z.current=null},isCreating:K}),P&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Ho,{size:16}),t.jsx("span",{children:ft?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),ft&&t.jsx("button",{type:"button",onClick:()=>{j()},disabled:O,className:"btn btn-primary session-lock-take-control",children:O?"Taking control...":"Take Control"})]})})]})]})}):null}function z1({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($s,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3,4,5,6].map(m=>t.jsx("div",{className:`planning-progress-step ${m<=n?"active":""}`},m))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~6"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:l,onChange:m=>c(m.target.value),onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&l.trim()&&(m.preventDefault(),u())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(m=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:m.id,checked:r[e.id]===m.id,onChange:()=>o({[e.id]:m.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(m=>{const h=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:m.id,checked:h.includes(m.id),onChange:f=>{const p=f.target.checked?[...h,m.id]:h.filter(g=>g!==m.id);o({[e.id]:p})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!0?"selected":""}`,onClick:()=>o({[e.id]:!0}),children:[t.jsx(yn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(Wt,{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(kr,{size:16,className:"icon-ml-4"})]})})]})}function F1({summary:e,historyEntries:n,onSummaryChange:s,onApprove:i,onStartOver:r,isCreating:o}){const[l,c]=a.useState(()=>new Set(e.milestones.map((_,S)=>S))),[u,d]=a.useState(()=>{const _=new Set;return e.milestones.forEach((S,w)=>{S.slices.forEach((M,N)=>_.add(`${w}-${N}`))}),_}),m=_=>{c(S=>{const w=new Set(S);return w.has(_)?w.delete(_):w.add(_),w})},h=_=>{d(S=>{const w=new Set(S);return w.has(_)?w.delete(_):w.add(_),w})},f=(_,S)=>{const w=[...e.milestones];w[_]={...w[_],...S},s({...e,milestones:w})},p=(_,S,w)=>{const M=[...e.milestones],N=[...M[_].slices];N[S]={...N[S],...w},M[_]={...M[_],slices:N},s({...e,milestones:M})},g=(_,S,w,M)=>{const N=[...e.milestones],D=[...N[_].slices],E=[...D[S].features];E[w]={...E[w],...M},D[S]={...D[S],features:E},N[_]={...N[_],slices:D},s({...e,milestones:N})},b=_=>{const S=e.milestones.filter((w,M)=>M!==_);s({...e,milestones:S})},v=(_,S)=>{const w=[...e.milestones];w[_]={...w[_],slices:w[_].slices.filter((M,N)=>N!==S)},s({...e,milestones:w})},x=(_,S,w)=>{const M=[...e.milestones],N=[...M[_].slices];N[S]={...N[S],features:N[S].features.filter((D,E)=>E!==w)},M[_]={...M[_],slices:N},s({...e,milestones:M})},y=(_,S)=>{const w=[...e.milestones],M=[...w[_].slices];M[S]={...M[S],features:[...M[S].features,{title:"New feature",description:""}]},w[_]={...w[_],slices:M},s({...e,milestones:w})},k=e.milestones.reduce((_,S)=>_+S.slices.reduce((w,M)=>w+M.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($s,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(yn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Mission Plan Ready"}),t.jsxs("p",{className:"text-muted",children:[e.milestones.length," milestones, ",k," 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:_=>s({...e,missionTitle:_.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:_=>s({...e,missionDescription:_.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Roadmap"}),t.jsx("div",{className:"roadmap-list",children:e.milestones.map((_,S)=>t.jsxs("div",{className:"roadmap-card",children:[t.jsxs("div",{className:"roadmap-card-header",onClick:()=>m(S),children:[l.has(S)?t.jsx(Xt,{size:16,className:"icon-text-secondary"}):t.jsx(vn,{size:16,className:"icon-text-secondary"}),t.jsx(Bi,{size:16,className:"icon-milestone"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-title",value:_.title,onChange:w=>f(S,{title:w.target.value}),onClick:w=>w.stopPropagation()}),e.milestones.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:w=>{w.stopPropagation(),b(S)},title:"Remove milestone",children:t.jsx(rn,{size:14,className:"icon-text-secondary"})})]}),l.has(S)&&t.jsxs("div",{className:"roadmap-card-body",children:[t.jsx("textarea",{className:"planning-textarea roadmap-textarea-md",rows:2,placeholder:"Milestone description...",value:_.description||"",onChange:w=>f(S,{description:w.target.value})}),t.jsxs("div",{className:"roadmap-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Verification Criteria"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-sm",rows:2,placeholder:"How to confirm this milestone is complete...",value:_.verification||"",onChange:w=>f(S,{verification:w.target.value})})]}),_.slices.map((w,M)=>{const N=`${S}-${M}`;return t.jsxs("div",{className:"roadmap-slice-card",children:[t.jsxs("div",{className:"roadmap-slice-header",onClick:()=>h(N),children:[u.has(N)?t.jsx(Xt,{size:14,className:"icon-text-secondary"}):t.jsx(vn,{size:14,className:"icon-text-secondary"}),t.jsx(_c,{size:14,className:"icon-slice"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:w.title,onChange:D=>p(S,M,{title:D.target.value}),onClick:D=>D.stopPropagation()}),_.slices.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:D=>{D.stopPropagation(),v(S,M)},title:"Remove slice",children:t.jsx(rn,{size:12,className:"icon-text-secondary"})})]}),u.has(N)&&t.jsxs("div",{className:"roadmap-slice-body",children:[t.jsxs("div",{className:"roadmap-slice-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Slice Verification"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-xs",rows:1,placeholder:"How to confirm this slice is done...",value:w.verification||"",onChange:D=>p(S,M,{verification:D.target.value})})]}),w.features.map((D,E)=>t.jsxs("div",{className:"roadmap-feature-row",children:[t.jsx(jc,{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:D.title,onChange:T=>g(S,M,E,{title:T.target.value})}),D.description&&t.jsx("p",{className:"roadmap-feature-text",children:D.description}),D.acceptanceCriteria&&t.jsxs("p",{className:"roadmap-feature-text--italic",children:["AC: ",D.acceptanceCriteria]})]}),t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:()=>x(S,M,E),title:"Remove feature",children:t.jsx(rn,{size:12,className:"icon-text-secondary"})})]},E)),t.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>y(S,M),children:[t.jsx(on,{size:12}),"Add Feature"]})]})]},M)})]})]},S))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:r,disabled:o,children:[t.jsx(Sa,{size:16,className:"icon-mr-4"}),"Start Over"]}),t.jsx("button",{className:"btn btn-primary",onClick:i,disabled:o||e.milestones.length===0,children:o?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:16,className:"spin icon-mr-8"}),"Creating Mission..."]}):t.jsxs(t.Fragment,{children:[t.jsx(yn,{size:16,className:"icon-mr-8"}),"Approve Plan"]})})]})]})}function O1({isOpen:e,onClose:n,onApplied:s,targetType:i,targetId:r,targetTitle:o,missionContext:l,projectId:c,resumeSessionId:u}){const[d,m]=a.useState({type:"initial"}),[h,f]=a.useState(null),[p,g]=a.useState([]),[b,v]=a.useState([]),[x,y]=a.useState(null),[k,_]=a.useState(""),[S,w]=a.useState(!0),[M,N]=a.useState(!1),[D,E]=a.useState(!1),T=a.useRef(null),U=a.useRef(null),K=a.useRef(null),$=a.useRef(null),[R,z]=a.useState(null),B=a.useMemo(()=>Ji(),[]);Zo(e?R:null);const{activeTabMap:J,broadcastUpdate:Q,broadcastCompleted:C,broadcastLock:L,broadcastUnlock:P,broadcastHeartbeat:j}=Ma(),O=i==="milestone"?Bk:Kk,H=i==="milestone"?Hk:Gk,ge=i==="milestone"?qk:Jk,be=i==="milestone"?Vk:Yk,se=i==="milestone"?Wk:Qk,me=i==="milestone"?"Milestone":"Slice",F=i==="milestone"?"milestone_interview":"slice_interview",de=a.useCallback(Be=>{U.current?.close();const Ge=ge(Be,c,{onThinking:re=>{_(ke=>ke+re),Q({sessionId:Be,status:"generating",needsInput:!1,owningTabId:B,type:F,title:o,projectId:c??null})},onQuestion:re=>{N(!1),ne(),m({type:"question",sessionId:Be,question:re}),_(""),Q({sessionId:Be,status:"awaiting_input",needsInput:!0,owningTabId:B,type:F,title:o,projectId:c??null})},onSummary:re=>{N(!1),ne(),m({type:"summary",sessionId:Be,summary:re}),y(re),_(""),Q({sessionId:Be,status:"complete",needsInput:!1,owningTabId:B,type:F,title:o,projectId:c??null})},onError:re=>{const ke=re||"Session failed while contacting the AI.";N(!1),f(null),m({type:"error",sessionId:Be,errorMessage:ke}),_(""),K.current=Be,Q({sessionId:Be,status:"error",needsInput:!1,owningTabId:B,type:F,title:o,projectId:c??null}),C({sessionId:Be,status:"error"})},onComplete:()=>{N(!1),K.current=null,C({sessionId:Be,status:"complete"})},onConnectionStateChange:re=>{N(re==="reconnecting")}});U.current=Ge},[C,Q,ge,F,c,B,o]),ne=()=>{y(null),g([]),v([]),_("")},xe=a.useCallback(async()=>{f(null),ne(),N(!1),m({type:"loading"});try{const{sessionId:Be}=await O(r,c);K.current=Be,z(Be),de(Be)}catch(Be){N(!1),f(ye(Be)||`Failed to start ${me.toLowerCase()} interview`),m({type:"initial"}),K.current=null,z(null)}},[de,c,O,r,me]),oe=a.useCallback(async()=>{f(null),E(!0);try{await se(r,c),s(),m({type:"applied"})}catch(Be){f(ye(Be)||`Failed to skip ${me.toLowerCase()} interview`),E(!1)}},[s,c,se,r,me]);a.useEffect(()=>{e&&d.type==="initial"&&T.current?.focus()},[e,d.type]),a.useEffect(()=>{if(!e||!u||d.type!=="initial")return;let Be=!1;return hi(u).then(Ge=>{if(Be||!Ge)return;const re=ba(Ge.conversationHistory);if(v(re),z(Ge.id),g(re.map(ke=>ke.response).filter(ke=>!!(ke&&typeof ke=="object"&&!Array.isArray(ke)))),Ge.status==="awaiting_input"&&Ge.currentQuestion)try{const ke=JSON.parse(Ge.currentQuestion);K.current=Ge.id,m({type:"question",sessionId:Ge.id,question:ke})}catch{f("Failed to restore session question.")}else if(Ge.status==="complete"&&Ge.result)try{const ke=JSON.parse(Ge.result);K.current=Ge.id,y(ke),m({type:"summary",sessionId:Ge.id,summary:ke})}catch{f("Failed to restore session result.")}else Ge.status==="generating"?(K.current=Ge.id,Ge.thinkingOutput&&_(Ge.thinkingOutput),m({type:"loading"}),de(Ge.id)):Ge.status==="error"&&(K.current=Ge.id,f(null),m({type:"error",sessionId:Ge.id,errorMessage:Ge.error??"The session encountered an error."}))}).catch(()=>{Be||f("Failed to resume session.")}),()=>{Be=!0}},[de,e,u,d.type]),a.useEffect(()=>{e||(N(!1),z(null))},[e]),a.useEffect(()=>{if(!(!e||!R)){if($.current!==R){$.current&&P($.current,B),L(R,B),$.current=R;return}!R&&$.current&&(P($.current,B),$.current=null)}},[L,P,e,R,B]),a.useEffect(()=>{if(!e||!R||$.current!==R)return;j(B);const Be=setInterval(()=>{j(B)},3e4);return()=>{clearInterval(Be)}},[j,e,R,B]),a.useEffect(()=>()=>{U.current?.close(),U.current=null,$.current&&(P($.current,B),$.current=null)},[P,B]);const he=a.useCallback(()=>{U.current?.close(),U.current=null,n()},[n]),ae=a.useCallback(async()=>{U.current?.close(),U.current=null,ne(),m({type:"initial"}),f(null),K.current=null,z(null),n()},[n]),je=a.useCallback(async Be=>{if(d.type!=="question")return;const{sessionId:Ge}=d;f(null),g(re=>[...re,Be]),v(re=>[...re,{question:d.question,response:Be}]),m({type:"loading"}),_("");try{de(Ge),await H(Ge,Be,c,B)}catch(re){U.current?.close(),U.current=null,f(ye(re)||"Failed to submit response"),m({type:"question",sessionId:Ge,question:d.question})}},[de,c,H,B,d]),Ae=a.useCallback(async()=>{if(d.type==="summary"){f(null),E(!0);try{await be(d.sessionId,x||void 0,c),s(),m({type:"applied"})}catch(Be){f(ye(Be)||"Failed to apply interview results"),E(!1)}}},[be,x,s,c,d]),Oe=()=>d.type==="question"?Math.min(p.length+1,6):6,Qe=d.type==="loading"||d.type==="question"||d.type==="summary"||d.type==="error",Xe=R?J.get(R):null,it=!!(Xe&&Xe.tabId!==B&&!Xe.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Be=>Be.target===Be.currentTarget&&ae(),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(rs,{size:20,className:"icon-triage"}),t.jsxs("h3",{children:["Plan ",me,": ",o]})]}),t.jsxs("div",{className:"modal-header-actions",children:[Qe&&t.jsx("button",{className:"modal-send-to-background",onClick:he,title:"Send to background","aria-label":"Send to background",children:t.jsx(Sr,{size:16})}),t.jsx("button",{className:"modal-close",onClick:ae,"aria-label":"Close",children:t.jsx(Wt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[h&&t.jsx("div",{className:"form-error planning-error",children:h}),M&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),it&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),d.type==="initial"&&t.jsxs("div",{className:"planning-initial",children:[t.jsx("div",{className:"planning-view-scroll",children:t.jsxs("div",{className:"planning-intro",children:[t.jsx(rs,{size:32,className:"icon-triage-lg"}),t.jsxs("h4",{children:["Refine ",me," 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 xe(),children:[t.jsx(rs,{size:16,className:"icon-mr-8"}),"Start Interview"]}),t.jsxs("button",{className:"btn planning-use-context-btn",onClick:()=>void oe(),disabled:D,children:[D?t.jsx(ot,{size:16,className:"spin"}):null,"Use Mission Context"]}),t.jsx("button",{className:"btn",onClick:ae,children:"Cancel"})]})]}),d.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(ot,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:k?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>w(!S),type:"button",children:S?"Hide thinking":"Show thinking"}),S&&k&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:k})})]})]}),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($s,{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:ae,children:"Cancel"})})]})]})}),d.type==="question"&&t.jsx(U1,{question:d.question,progress:Oe(),historyEntries:b,onSubmit:je}),d.type==="summary"&&x&&t.jsx(B1,{summary:x,historyEntries:b,onSummaryChange:y,onApply:Ae,onCancel:ae,isApplying:D}),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(yn,{size:48,className:"icon-success"}),t.jsxs("h4",{children:[me," 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 U1({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($s,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3,4,5,6].map(m=>t.jsx("div",{className:`planning-progress-step ${m<=n?"active":""}`},m))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~6"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:l,onChange:m=>c(m.target.value),onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&l.trim()&&(m.preventDefault(),u())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(m=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:m.id,checked:r[e.id]===m.id,onChange:()=>o({[e.id]:m.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(m=>{const h=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:m.id,checked:h.includes(m.id),onChange:f=>{const p=f.target.checked?[...h,m.id]:h.filter(g=>g!==m.id);o({[e.id]:p})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!0?"selected":""}`,onClick:()=>o({[e.id]:!0}),children:[t.jsx(yn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(Wt,{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(kr,{size:16,className:"icon-ml-4"})]})})]})}function B1({summary:e,historyEntries:n,onSummaryChange:s,onApply:i,onCancel:r,isApplying:o}){const[l,c]=a.useState(e),[u,d]=a.useState(!0),m=(h,f)=>{const p={...l,[h]:f};c(p),s(p)};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx($s,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-panel",children:[t.jsx("div",{className:"planning-summary-header",children:t.jsxs("button",{className:"planning-summary-toggle",onClick:()=>d(!u),"aria-expanded":u,children:[u?t.jsx(Xt,{size:16}):t.jsx(vn,{size:16}),t.jsx("span",{children:"Refined Scope"})]})}),u&&t.jsxs("div",{className:"planning-summary-content",children:[l.description&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:l.description,onChange:h=>m("description",h.target.value)})]}),l.planningNotes&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Planning Notes"}),t.jsx("textarea",{rows:3,value:l.planningNotes,onChange:h=>m("planningNotes",h.target.value)})]}),l.verification&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Verification Criteria"}),t.jsx("textarea",{rows:2,value:l.verification,onChange:h=>m("verification",h.target.value)})]}),!l.description&&!l.planningNotes&&!l.verification&&t.jsx("p",{className:"text-muted planning-summary-empty",children:"No additional details were generated for this item."})]})]})]}),t.jsxs("div",{className:"planning-view-footer",children:[t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:i,disabled:o,children:[o?t.jsx(ot,{size:16,className:"spin"}):null,"Apply"]}),t.jsx("button",{className:"btn",onClick:r,disabled:o,children:"Cancel"})]})]})}const Ua={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)"}},Xu={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)"}},Zu={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)"}},Yr={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)"}},Qr={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)"}},Xr={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)"}},em={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)"}},H1=3;function q1(e){return e==="completed"?"planned":e==="needs_update"?"needs_update":"not_started"}function tm({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 nm(e){return e?e.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const _l={title:"",description:"",status:"planning",autopilotEnabled:!1},Ml={title:"",description:"",status:"planning",dependencies:[]},Al={title:"",description:"",status:"pending"},Rl={title:"",description:"",acceptanceCriteria:"",status:"defined"},V1=3600*1e3;function Mo(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 W1(e){if(!e)return"healthy";const n=typeof e.lastErrorAt=="string"&&Date.now()-new Date(e.lastErrorAt).getTime()<=V1,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 K1(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 G1(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 Tl(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 Vp=["feature_triaged","feature_completed"],Wp=["slice_activated","slice_completed","milestone_completed"],Kp=["mission_started","mission_paused","mission_resumed","mission_completed"],Gp=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function sm(e,n){switch(n){case"errors":return e==="error"||e==="warning";case"state_changes":return Kp.includes(e);case"tasks":return Vp.includes(e);case"slices":return Wp.includes(e);case"autopilot":return Gp.includes(e);default:return!0}}function J1(e){return e==="error"||e==="warning"?"mission-event__type--error":Kp.includes(e)?"mission-event__type--state":Vp.includes(e)?"mission-event__type--task":Wp.includes(e)?"mission-event__type--slice":Gp.includes(e)?"mission-event__type--autopilot":"mission-event__type--default"}function Y1(e){return e.replace(/_/g," ")}function Q1(e,n){return n?e==="watching"?`Watching since ${Mo(n)}`:`Last activation ${Mo(n)}`:null}function X1({isOpen:e,isInline:n=!1,onClose:s,addToast:i,projectId:r,onSelectTask:o,availableTasks:l=[],resumeSessionId:c,targetMissionId:u,milestoneSliceResumeSessionId:d,onMilestoneSliceResumeFetchError:m}){const h=n||e,[f,p]=a.useState([]),[g,b]=a.useState(null),[v,x]=a.useState(!0),[y,k]=a.useState(!1),[_,S]=a.useState(!1),[w,M]=a.useState(null),[N,D]=a.useState(_l),[E,T]=a.useState(!1),[U,K]=a.useState(new Set),[$,R]=a.useState(new Set),[z,B]=a.useState(null),[J,Q]=a.useState(Ml),[C,L]=a.useState(!1),[P,j]=a.useState(null),[O,H]=a.useState(Al),[ge,be]=a.useState(!1),[se,me]=a.useState(null),[F,de]=a.useState(null),[ne,xe]=a.useState(Rl),[oe,he]=a.useState(!1),[ae,je]=a.useState(null),[Ae,Oe]=a.useState(null),[Qe,Xe]=a.useState(""),[Ye,it]=a.useState(!1),[Be,Ge]=a.useState([]),[re,ke]=a.useState(void 0),X=re??c,[Te,Le]=a.useState(null),[fe,_e]=a.useState(null),[Ue,nt]=a.useState(null);a.useEffect(()=>{h&&X&&it(!0)},[h,X]),a.useEffect(()=>{if(!h||X)return;let V=!1;return ld(r).then(Se=>{if(V)return;const Ie=Se.filter(pt=>pt.type==="mission_interview"&&(pt.status==="awaiting_input"||pt.status==="error"));Ge(Ie)}).catch(Se=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",Se)}),()=>{V=!0}},[h,r,X]),a.useEffect(()=>{if(!h||!d)return;let V=!1;return hi(d).then(Se=>{if(!(V||!Se))try{const Ie=JSON.parse(Se.inputPayload||"{}");Ie.targetId&&Ie.targetType&&Le({type:Ie.targetType,id:Ie.targetId,title:Ie.targetTitle||Se.title,resumeSessionId:d})}catch{Le({type:"milestone",id:"",title:Se.title,resumeSessionId:d})}}).catch(Se=>{V||(console.warn("[MissionManager] Failed to fetch session for milestone/slice resume:",Se),m?.())}),()=>{V=!0}},[h,d,m]);const[ve,ce]=a.useState(null),[De,ue]=a.useState(new Map),[Re,Ke]=a.useState(null),[Pe,ft]=a.useState({title:"",assertion:"",status:"pending"}),[Z,le]=a.useState(!1),[we,Ze]=a.useState(null),[te,Je]=a.useState(new Map),[dt,ut]=a.useState(new Set),[Ct,yt]=a.useState(new Set),[bt,At]=a.useState(null),[Rt,Ht]=a.useState(new Map),[Et,Dt]=a.useState(null),[Kt,$t]=a.useState(null),[Ft,Ot]=a.useState(!0),[Tt,Pt]=a.useState(new Set),[wt,Gt]=a.useState(new Map),[Ut,q]=a.useState(null),[pe,$e]=a.useState(new Map),[A,ee]=a.useState(null),[ze,mt]=a.useState(new Map),[jt,Lt]=a.useState(new Map),[_t,Jt]=a.useState("structure"),[Dn,Pn]=a.useState([]),Yt=a.useRef([]),Cn=a.useRef([]),Ne=a.useRef(null),at=a.useRef(null),fn=a.useRef("structure"),jn=a.useRef("all"),[In,Ce]=a.useState(!1),[st,ht]=a.useState(0),[Mt,ln]=a.useState("all"),[En,tn]=a.useState(new Set),nn=a.useRef(null),An=a.useRef(null);Cn.current=f,Ne.current=g,at.current=Et,fn.current=_t,jn.current=Mt;const Un=a.useCallback((V="auto")=>{const Se=An.current;if(Se&&typeof Se.scrollIntoView=="function"){Se.scrollIntoView({block:"end",behavior:V});return}const Ie=nn.current;Ie&&(Ie.scrollTop=Ie.scrollHeight)},[]),kn=a.useCallback(()=>{const V=nn.current;return V?V.scrollHeight-V.scrollTop-V.clientHeight<=100:!0},[]),ns=a.useCallback(async V=>{if(V.length===0){Lt(new Map);return}const Se=await dk(r);Lt(Ie=>{const pt=new Map(Ie);for(const[Zt,Bt]of Object.entries(Se))K1(Bt)&&pt.set(Zt,Bt);return pt})},[r]),cn=a.useCallback(async()=>{try{x(!0);const V=await ak(r);p(V),ns(V)}catch(V){i(ye(V)||"Failed to load missions","error")}finally{x(!1)}},[i,r,ns]),vt=a.useCallback(async V=>{try{k(!0);const Se=await jp(V,r);if(b(Se),Se.milestones.length>0){const Ie=Se.milestones[0].id;Dt(Ie),Ot(!0),K(new Set([Ie])),gl(Ie,r).then(pt=>{ue(Zt=>{const Bt=new Map(Zt);return Bt.set(Ie,pt),Bt})}).catch(()=>{}),bl(Ie,r).then(pt=>{Ht(Zt=>{const Bt=new Map(Zt);return Bt.set(Ie,pt),Bt})}).catch(()=>{}),Se.milestones[0].slices.length>0&&R(new Set([Se.milestones[0].slices[0].id]))}else Dt(null),$t(null)}catch(Se){i(ye(Se)||"Failed to load mission details","error")}finally{k(!1)}},[i,r]);a.useEffect(()=>{if(!h||!Et){$t(null);return}let V=!1;return $t(null),cu(Et,r).then(Se=>{if(!V){if(!Tl(Se)){$t(null);return}$t(Se),Ht(Ie=>{const pt=new Map(Ie);return pt.set(Et,Se.rollup),pt})}}).catch(()=>{V||$t(null)}),()=>{V=!0}},[h,Et,r]),a.useEffect(()=>{Ot(!0)},[Et]);const G=a.useCallback(V=>{!V||V!==at.current||cu(V,r).then(Se=>{at.current!==V||!Tl(Se)||($t(Se),Ht(Ie=>{const pt=new Map(Ie);return pt.set(V,Se.rollup),pt}))}).catch(()=>{})},[r]),Fe=a.useCallback(async(V,Se)=>{const Ie=Se?.append??!1,pt=Ie?Yt.current.length:0;Ie||(Ce(!0),tn(new Set));try{const Zt=await ck(V,{limit:50,offset:pt,eventType:void 0},r),Bt=Zt.events.filter(an=>sm(an.eventType,Mt));Pn(an=>{if(!Ie)return Bt;const Ve=new Set(an.map(xt=>xt.id)),We=[...an];for(const xt of Bt)Ve.has(xt.id)||We.push(xt);return We}),ht(Zt.total),Ie||requestAnimationFrame(()=>{Un("auto")})}catch(Zt){i(ye(Zt)||"Failed to load mission activity","error")}finally{Ie||Ce(!1)}},[i,Mt,r,Un]);a.useEffect(()=>{Yt.current=Dn},[Dn]),a.useEffect(()=>{h&&(cn(),b(null),Dt(null),$t(null),Pn([]),ht(0),Jt("structure"),ln("all"),tn(new Set))},[h,cn]);const tt=a.useRef(null);a.useEffect(()=>{h&&u&&tt.current!==u&&f.length>0&&(tt.current=u,vt(u))},[h,u,f,vt]),a.useEffect(()=>{h||(tt.current=null)},[h]),a.useEffect(()=>{!h||!g||_t!=="activity"||Fe(g.id)},[_t,h,Fe,g,Mt]),a.useEffect(()=>{if(!h||typeof EventSource>"u")return;const V=new URLSearchParams;r&&V.set("projectId",r);const Se=`/api/events${V.size>0?`?${V.toString()}`:""}`,Ie=()=>{ns(Cn.current)},pt=ts=>{Ie();const Mn=ts;if(Mn.data)try{const Vt=JSON.parse(Mn.data);Vt?.id&&p(Ti=>Ti.map(Ms=>Ms.id===Vt.id?{...Ms,...Vt}:Ms))}catch{}Ne.current&&vt(Ne.current.id)},Zt=ts=>{Ie(),Ne.current&&vt(Ne.current.id)},Bt=()=>{Ie(),Ne.current&&vt(Ne.current.id)},an=ts=>{Ie(),Ne.current&&vt(Ne.current.id)},Ve=ts=>{const Mn=ts;if(Mn.data)try{const Vt=JSON.parse(Mn.data);Vt&&Vt.featureId&&(Ys(Vt.featureId),Tn(Vt.featureId),Vt.milestoneId&&G(Vt.milestoneId))}catch{}},We=ts=>{const Mn=ts;if(Mn.data)try{const Vt=JSON.parse(Mn.data);Vt&&Vt.featureId&&(Ys(Vt.featureId),Tn(Vt.featureId),Vt.milestoneId&&G(Vt.milestoneId),Ne.current&&vt(Ne.current.id))}catch{}},xt=ts=>{const Mn=ts;if(Mn.data)try{const Vt=JSON.parse(Mn.data);Vt&&Vt.milestoneId&&(Bn(Vt.milestoneId),G(Vt.milestoneId))}catch{}},bn=ts=>{const Mn=ts;if(Mn.data)try{const Vt=JSON.parse(Mn.data);Vt&&Vt.milestoneId&&(_n(Vt.milestoneId),Bn(Vt.milestoneId),G(Vt.milestoneId))}catch{}};return Ks(Se,{events:{"mission:updated":pt,"slice:updated":Zt,"feature:updated":Bt,"milestone:updated":an,"mission:event":ts=>{Ie();const Mn=Ne.current;if(!Mn||fn.current!=="activity")return;const Vt=kn(),Ti=ts;if(Ti.data)try{const Ms=JSON.parse(Ti.data);if(!G1(Ms)||Ms.missionId!==Mn.id||!sm(Ms.eventType,jn.current))return;Pn(ui=>{const ul=ui.filter(ml=>ml.id!==Ms.id);return[Ms,...ul].slice(0,100)}),ht(ui=>ui+1),Vt&&requestAnimationFrame(()=>{const ui=nn.current;ui&&(ui.scrollTop=0)})}catch{}},"validator-run:started":Ve,"validator-run:completed":We,"milestone:validation:updated":xt,"assertion:created":bn,"assertion:updated":bn,"assertion:deleted":bn,"assertion:linked":bn,"assertion:unlinked":bn,"fix-feature:created":ts=>{const Mn=ts;if(Mn.data)try{const Vt=JSON.parse(Mn.data);if(Vt&&Vt.sourceFeatureId){Ys(Vt.sourceFeatureId);const Ti=Vt?.feature?.sliceId,Ms=Ne.current;if(Ti&&Ms){const ui=Ms.milestones.find(ul=>ul.slices.some(ml=>ml.id===Ti));ui&&G(ui.id)}Ne.current&&vt(Ne.current.id)}}catch{}}}})},[h,kn,vt,ns,r,G]);const rt=a.useCallback(()=>{S(!0),M(null),D(_l)},[]),kt=a.useCallback(V=>{M(V.id),S(!1),D({title:V.title,description:V.description||"",status:V.status,autopilotEnabled:V.autopilotEnabled??!1})},[]),St=a.useCallback(()=>{M(null),S(!1),D(_l)},[]),zt=a.useCallback(async()=>{if(!N.title.trim()){i("Mission title is required","error");return}try{if(T(!0),_)await rk({title:N.title.trim(),description:N.description.trim()||void 0,autopilotEnabled:N.autopilotEnabled},r),i("Mission created","success");else if(w){const V={title:N.title.trim(),description:N.description.trim()||void 0,status:N.status,autopilotEnabled:N.autopilotEnabled};N.autopilotEnabled&&(V.autoAdvance=!0),await ok(w,V,r),i("Mission updated","success"),g?.id===w&&await vt(w)}await cn(),St()}catch(V){i(ye(V)||"Failed to save mission","error")}finally{T(!1)}},[N,_,w,i,cn,vt,g,St,r]),qn=a.useCallback(async V=>{try{await lk(V,r),i("Mission deleted","success"),g?.id===V&&b(null),await cn(),ce(null)}catch(Se){i(ye(Se)||"Failed to delete mission","error")}},[i,cn,g,r]),Ds=a.useCallback(()=>{L(!0),B(null),Q(Ml)},[]),ci=a.useCallback(V=>{B(V.id),L(!1),Q({title:V.title,description:V.description||"",status:V.status,dependencies:V.dependencies})},[]),Cs=a.useCallback(()=>{B(null),L(!1),Q(Ml)},[]),Gs=a.useCallback(async()=>{if(!J.title.trim()){i("Milestone title is required","error");return}try{T(!0),C&&g?(await uk(g.id,{title:J.title.trim(),description:J.description.trim()||void 0,dependencies:J.dependencies},r),i("Milestone created","success")):z&&(await mk(z,{title:J.title.trim(),description:J.description.trim()||void 0,status:J.status,dependencies:J.dependencies},r),i("Milestone updated","success")),await vt(g.id),Cs()}catch(V){i(ye(V)||"Failed to save milestone","error")}finally{T(!1)}},[J,C,z,g,i,vt,Cs,N.title,r]),ie=a.useCallback(async V=>{try{await hk(V,r),i("Milestone deleted","success"),await vt(g.id),ce(null)}catch(Se){i(ye(Se)||"Failed to delete milestone","error")}},[i,vt,g,r]),Ee=a.useCallback(V=>{Dt(V),Ot(!0),K(Se=>{const Ie=new Set(Se);return!Ie.has(V)?(Ie.add(V),gl(V,r).then(Zt=>{ue(Bt=>{const an=new Map(Bt);return an.set(V,Zt),an})}).catch(()=>{}),bl(V,r).then(Zt=>{Ht(Bt=>{const an=new Map(Bt);return an.set(V,Zt),an})}).catch(()=>{})):Ie.delete(V),Ie})},[r]),Me=a.useCallback(V=>{me(V),be(!0),j(null),H(Al)},[]),ct=a.useCallback(V=>{j(V.id),be(!1),H({title:V.title,description:V.description||"",status:V.status})},[]),gt=a.useCallback(()=>{j(null),be(!1),me(null),H(Al)},[]),sn=a.useCallback(async()=>{if(!O.title.trim()){i("Slice title is required","error");return}try{T(!0),ge&&se?(await pk(se,{title:O.title.trim(),description:O.description.trim()||void 0},r),i("Slice created","success")):P&&(await fk(P,{title:O.title.trim(),description:O.description.trim()||void 0,status:O.status},r),i("Slice updated","success")),await vt(g.id),gt()}catch(V){i(ye(V)||"Failed to save slice","error")}finally{T(!1)}},[O,ge,P,se,g,i,vt,gt,r]),mn=a.useCallback(async V=>{try{await gk(V,r),i("Slice deleted","success"),await vt(g.id),ce(null)}catch(Se){i(ye(Se)||"Failed to delete slice","error")}},[i,vt,g,r]),dn=a.useCallback(async V=>{try{await bk(V,r),i("Slice activated","success"),await vt(g.id)}catch(Se){i(ye(Se)||"Failed to activate slice","error")}},[i,vt,g,r]),gn=a.useCallback(V=>{R(Se=>{const Ie=new Set(Se);return Ie.has(V)?Ie.delete(V):Ie.add(V),Ie})},[]),wn=a.useCallback(V=>{je(V),he(!0),de(null),xe(Rl)},[]),Xn=a.useCallback(V=>{de(V.id),he(!1),xe({title:V.title,description:V.description||"",acceptanceCriteria:V.acceptanceCriteria||"",status:V.status})},[]),Zn=a.useCallback(()=>{de(null),he(!1),je(null),xe(Rl)},[]),Ln=a.useCallback(async()=>{if(!ne.title.trim()){i("Feature title is required","error");return}try{T(!0),oe&&ae?(await xk(ae,{title:ne.title.trim(),description:ne.description.trim()||void 0,acceptanceCriteria:ne.acceptanceCriteria.trim()||void 0},r),i("Feature created","success")):F&&(await vk(F,{title:ne.title.trim(),description:ne.description.trim()||void 0,acceptanceCriteria:ne.acceptanceCriteria.trim()||void 0,status:ne.status},r),i("Feature updated","success")),await vt(g.id),Zn()}catch(V){i(ye(V)||"Failed to save feature","error")}finally{T(!1)}},[ne,oe,F,ae,g,i,vt,Zn,r]),es=a.useCallback(async V=>{try{await yk(V,r),i("Feature deleted","success"),await vt(g.id),ce(null)}catch(Se){i(ye(Se)||"Failed to delete feature","error")}},[i,vt,g,r]),Vn=a.useCallback(async()=>{if(!Ae||!Qe.trim()){i("Task ID is required","error");return}try{await jk(Ae,Qe.trim(),r),i("Feature linked to task","success"),await vt(g.id),Oe(null),Xe("")}catch(V){i(ye(V)||"Failed to link feature to task","error")}},[Ae,Qe,i,vt,g,r]),ps=a.useCallback(async V=>{try{await kk(V,r),i("Feature unlinked from task","success"),await vt(g.id)}catch(Se){i(ye(Se)||"Failed to unlink feature","error")}},[i,vt,g,r]),Rn=a.useCallback(async V=>{try{T(!0),await wk(V,void 0,void 0,r),i("Feature triaged — task created","success"),await vt(g.id)}catch(Se){i(ye(Se)||"Failed to triage feature","error")}finally{T(!1)}},[i,vt,g,r]),Wn=a.useCallback(async V=>{nt(V);try{const Se=await Xk(V,r);_e({featureId:V,enrichedDescription:Se.description})}catch{await Rn(V)}finally{nt(null)}},[Rn,r]),fs=a.useCallback(async()=>{fe&&(_e(null),await Rn(fe.featureId))},[Rn,fe]),Ls=a.useCallback(()=>{_e(null)},[]),ss=a.useCallback(async V=>{try{T(!0);const Se=await Nk(V,r);i(`Triaged ${Se.count} feature${Se.count!==1?"s":""}`,"success"),await vt(g.id)}catch(Se){i(ye(Se)||"Failed to triage slice features","error")}finally{T(!1)}},[i,vt,g,r]),_n=a.useCallback(async V=>{try{const Se=await gl(V,r);ue(Ie=>{const pt=new Map(Ie);return pt.set(V,Se),pt})}catch{}},[r]),Bn=a.useCallback(async V=>{try{const Se=await bl(V,r);Ht(Ie=>{const pt=new Map(Ie);return pt.set(V,Se),pt})}catch{}},[r]),zs=a.useCallback(async V=>{if(!Pe.title.trim()||!Pe.assertion.trim()){i("Title and assertion text are required","error");return}try{T(!0),await Sk(V,{title:Pe.title.trim(),assertion:Pe.assertion.trim(),status:Pe.status},r),i("Assertion created","success"),await _n(V),await Bn(V),le(!1),ft({title:"",assertion:"",status:"pending"})}catch(Se){i(ye(Se)||"Failed to create assertion","error")}finally{T(!1)}},[Pe,i,_n,Bn,r]),di=a.useCallback(V=>{Ke(V.id),ft({title:V.title,assertion:V.assertion,status:V.status})},[]),bi=a.useCallback(()=>{Ke(null),le(!1),ft({title:"",assertion:"",status:"pending"})},[]),al=a.useCallback(async(V,Se)=>{if(!Pe.title.trim()||!Pe.assertion.trim()){i("Title and assertion text are required","error");return}try{T(!0),await Ck(V,{title:Pe.title.trim(),assertion:Pe.assertion.trim(),status:Pe.status},r),i("Assertion updated","success"),await _n(Se),await Bn(Se),bi()}catch(Ie){i(ye(Ie)||"Failed to update assertion","error")}finally{T(!1)}},[Pe,i,_n,Bn,bi,r]),Js=a.useCallback(async V=>{try{const Se=await Mk(V,r);Je(Ie=>{const pt=new Map(Ie);return pt.set(V,Se),pt})}catch{}},[r]),Ta=a.useCallback(async V=>{const Se=we!==V;Ze(Ie=>Ie===V?null:V),Se&&await Js(V)},[we,Js]),Pa=a.useCallback(V=>{Ze(V),Js(V),requestAnimationFrame(()=>{const Se=document.querySelector(`[data-mission-assertion-id="${V}"]`);Se instanceof HTMLElement&&typeof Se.scrollIntoView=="function"&&Se.scrollIntoView({behavior:"smooth",block:"center"})})},[Js]),$r=a.useCallback(async(V,Se)=>{try{ut(Ie=>new Set(Ie).add(Se)),await Ek(V,Se,r),i("Feature linked to assertion","success"),await Js(Se),At(null)}catch(Ie){i(ye(Ie)||"Failed to link feature","error")}finally{ut(Ie=>{const pt=new Set(Ie);return pt.delete(Se),pt})}},[i,Js,r]),rl=a.useCallback(async(V,Se)=>{const Ie=`${V}-${Se}`;try{yt(pt=>new Set(pt).add(Ie)),await _k(V,Se,r),i("Feature unlinked from assertion","success"),await Js(Se)}catch(pt){i(ye(pt)||"Failed to unlink feature","error")}finally{yt(pt=>{const Zt=new Set(pt);return Zt.delete(Ie),Zt})}},[i,Js,r]),ol=a.useCallback(async V=>{try{Pt(Ie=>new Set(Ie).add(V)),await Ak(V,r),i("Validation triggered","success");const Se=await du(V,r);Gt(Ie=>{const pt=new Map(Ie);return pt.set(V,Se),pt})}catch(Se){i(ye(Se)||"Failed to trigger validation","error")}finally{Pt(Se=>{const Ie=new Set(Se);return Ie.delete(V),Ie})}},[i,r]),Ys=a.useCallback(async V=>{try{const Se=await du(V,r);Gt(Ie=>{const pt=new Map(Ie);return pt.set(V,Se),pt})}catch{}},[r]),Tn=a.useCallback(async V=>{try{const Se=await Rk(V,{limit:10},r);$e(Ie=>{const pt=new Map(Ie);return pt.set(V,Se),pt})}catch{}},[r]),xi=a.useCallback(V=>{const Se=Ne.current;if(Se){for(const Ie of Se.milestones)for(const pt of Ie.slices)if(pt.features.find(Bt=>Bt.id===V)){K(Bt=>{const an=new Set(Bt);return an.add(Ie.id),an}),R(Bt=>{const an=new Set(Bt);return an.add(pt.id),an}),q(V),Dt(Ie.id),Ys(V),Tn(V),requestAnimationFrame(()=>{const Bt=document.querySelector(`[data-mission-feature-id="${V}"]`);Bt instanceof HTMLElement&&typeof Bt.scrollIntoView=="function"&&Bt.scrollIntoView({behavior:"smooth",block:"center"})});return}}},[Ys,Tn]),ls=a.useCallback(async V=>{try{const Se=await Tk(V,r);mt(Ie=>{const pt=new Map(Ie);return pt.set(V,Se),pt})}catch{}},[r]),Dr=a.useCallback(async V=>{Ut===V?q(null):(q(V),await Ys(V),await Tn(V))},[Ut,Ys,Tn]),Lr=a.useCallback(async V=>{A===V?ee(null):(ee(V),await ls(V))},[A,ls]),Ia=a.useCallback(async V=>{try{await Pk(V,r),i("Mission resumed","success"),await vt(V),cn()}catch(Se){i(ye(Se)||"Failed to resume mission","error")}},[i,vt,cn,r]),Mi=a.useCallback(async V=>{try{const Ie=(await Ik(V,r)).pausedTaskIds?.length??0;i(`Mission stopped (${Ie} task${Ie!==1?"s":""} paused)`,"success"),await vt(V),cn()}catch(Se){i(ye(Se)||"Failed to stop mission","error")}},[i,vt,cn,r]),zr=a.useCallback(async V=>{try{await $k(V,r),i("Mission started — first slice activated","success"),await vt(V),cn()}catch(Se){i(ye(Se)||"Failed to start mission","error")}},[i,vt,cn,r]),Fr=a.useCallback(async(V,Se)=>{try{await Dk(V,{enabled:Se},r),i(Se?"Autopilot enabled":"Autopilot disabled","success"),await vt(V),cn()}catch(Ie){i(ye(Ie)||"Failed to update autopilot","error")}},[i,vt,cn,r]),Y=a.useCallback(V=>{Jt("structure"),Dt(null),$t(null),Pn([]),ht(0),ln("all"),tn(new Set),vt(V.id)},[vt]),qe=a.useCallback(()=>{b(null),Dt(null),$t(null),Jt("structure"),Pn([]),ht(0),ln("all"),tn(new Set),cn()},[cn]),lt=Dn.length<st,It=g?.autopilotState??"inactive",Fs=It==="watching"||It==="activating",Es=Q1(It,g?.lastAutopilotActivityAt),Qi=a.useMemo(()=>!Kt||!Et||!Tl(Kt)?null:Kt.rollup.milestoneId===Et?Kt:null,[Et,Kt]),Or=a.useMemo(()=>{const V=new Map;for(const Se of Qi?.validationTelemetry.validationRounds??[]){const Ie=V.get(Se.featureId);(!Ie||Se.startedAt>Ie.startedAt)&&V.set(Se.featureId,Se)}return V},[Qi]),ll=a.useCallback(()=>{!g||In||!lt||Fe(g.id,{append:!0})},[In,lt,Fe,g]),cl=a.useCallback(V=>{tn(Se=>{const Ie=new Set(Se);return Ie.has(V)?Ie.delete(V):Ie.add(V),Ie})},[]),$a=a.useCallback(V=>{V.key==="Enter"&&!V.shiftKey&&(V.preventDefault(),zt())},[zt]),Ur=a.useCallback(V=>{V.key==="Enter"&&!V.shiftKey&&(V.preventDefault(),Gs())},[Gs]),Br=a.useCallback(V=>{V.key==="Enter"&&!V.shiftKey&&(V.preventDefault(),sn())},[sn]),Xi=a.useCallback(V=>{V.key==="Enter"&&!V.shiftKey&&(V.preventDefault(),Ln())},[Ln]),Da=a.useRef(null);if(a.useEffect(()=>{if(!h)return;const V=Se=>{Se.key==="Escape"&&s()};return document.addEventListener("keydown",V),()=>document.removeEventListener("keydown",V)},[h,s]),!h)return null;const Ai=t.jsxs("div",{ref:Da,className:`mission-manager${n?" mission-manager--inline":""}`,role:n?void 0:"dialog","aria-modal":n?void 0:!0,"aria-label":n?void 0:"Mission Manager","data-testid":"mission-manager-dialog",children:[t.jsxs("div",{className:`mission-manager__header${n?" mission-manager__header--inline":""}`,children:[t.jsxs("div",{className:"mission-manager__header-title",children:[g?t.jsx("button",{className:"mission-manager__back-btn",onClick:qe,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:t.jsx(Fo,{size:18})}):null,t.jsx(xs,{size:18,className:"mission-manager__header-icon"}),t.jsx("h2",{className:"mission-manager__title",children:g?g.title:"Missions"})]}),!n&&t.jsx("button",{className:"modal-close",onClick:s,title:"Close","aria-label":"Close Mission Manager","data-testid":"mission-close-btn",children:t.jsx(Wt,{size:18})})]}),t.jsx("div",{className:"mission-manager__body",children:v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(ot,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(ot,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):g?t.jsxs("div",{className:"mission-detail",children:[t.jsxs("div",{className:"mission-detail__header",children:[t.jsxs("div",{className:"mission-detail__title-row",children:[t.jsxs("div",{className:"mission-detail__title-text",children:[Fs&&t.jsx("span",{className:"mission-detail__autopilot-dot",title:"Autopilot watching"}),t.jsx("h3",{className:"mission-detail__title",children:g.title})]}),t.jsx("span",{className:"mission-status-badge",style:{backgroundColor:(Ua[g.status]||Ua.planning).bg,color:(Ua[g.status]||Ua.planning).text},children:g.status})]}),g.description&&t.jsx("p",{className:"mission-detail__description",children:g.description}),t.jsx("div",{className:"mission-detail__meta",children:t.jsxs("span",{className:"mission-detail__meta-info",children:[g.milestones.length," milestones"]})}),t.jsxs("div",{className:"mission-detail__autopilot",children:[t.jsxs("div",{className:"mission-detail__autopilot-toggle",children:[t.jsxs("label",{className:"mission-toggle","data-testid":"mission-autopilot-toggle",children:[t.jsx("input",{type:"checkbox",checked:g.autopilotEnabled??!1,onChange:V=>Fr(g.id,V.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(Gn,{size:14,className:"mission-detail__autopilot-icon"}),"Autopilot"]})]}),t.jsxs("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(Qr[It]||Qr.inactive).bg,color:(Qr[It]||Qr.inactive).text},"data-testid":"autopilot-state-badge",children:[Fs&&t.jsx("span",{className:"mission-detail__autopilot-pulse"}),It]})]}),Es&&t.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:Es})]}),t.jsxs("div",{className:"mission-detail__actions",children:[g.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Mi(g.id),title:"Stop mission","aria-label":"Stop mission",children:t.jsx(js,{size:14})}),g.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Ia(g.id),title:"Resume mission","aria-label":"Resume mission",children:t.jsx(Sn,{size:14})}),g.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>zr(g.id),title:"Start mission","aria-label":"Start mission",children:t.jsx(Sn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>kt(g),title:"Edit mission","aria-label":"Edit mission",children:t.jsx(cs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ce({type:"mission",id:g.id}),title:"Delete mission","aria-label":"Delete mission",children:t.jsx(rn,{size:14})})]})]}),w===g.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:N.title,onChange:V=>D({...N,title:V.target.value}),onKeyDown:$a,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:N.description,onChange:V=>D({...N,description:V.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:N.status,onChange:V=>D({...N,status:V.target.value}),children:[t.jsx("option",{value:"planning",children:"Planning"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"blocked",children:"Blocked"}),t.jsx("option",{value:"complete",children:"Complete"}),t.jsx("option",{value:"archived",children:"Archived"})]}),t.jsxs("label",{className:"mission-checkbox",children:[t.jsx("input",{type:"checkbox",checked:N.autopilotEnabled,onChange:V=>D({...N,autopilotEnabled:V.target.checked})}),t.jsx(Gn,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:zt,disabled:E,children:[E?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Hn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:St,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-detail__tabs",role:"tablist","aria-label":"Mission detail tabs",children:[t.jsx("button",{className:`mission-btn ${_t==="structure"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Jt("structure"),role:"tab","aria-selected":_t==="structure","data-testid":"mission-tab-structure",children:"Structure"}),t.jsxs("button",{className:`mission-btn ${_t==="activity"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Jt("activity"),role:"tab","aria-selected":_t==="activity","data-testid":"mission-tab-activity",children:["Activity (",st,")"]})]}),_t==="structure"?t.jsxs("div",{className:"mission-detail__milestones",children:[g.milestones.map(V=>{const Se=Qi?.rollup.milestoneId===V.id?Qi:null,Ie=Se?.rollup??Rt.get(V.id),pt=Se?.validationTelemetry.validationRounds??[],Zt=Se?.fixFeatures??[],Bt=em[Ie?.state??"not_started"]??em.not_started,an=Ie&&(Ie.state==="blocked"||Ie.state==="failed")?Se?.validationTelemetry.validationRounds.find(Ve=>Ve.blockedReason)?.blockedReason:void 0;return t.jsxs("div",{className:"mission-milestone",children:[t.jsxs("div",{className:"mission-milestone__header",onClick:()=>Ee(V.id),children:[t.jsx("button",{className:"mission-milestone__expand",children:U.has(V.id)?t.jsx(Xt,{size:16}):t.jsx(vn,{size:16})}),t.jsx(Bi,{size:16,className:"mission-milestone__icon"}),t.jsx("span",{className:"mission-milestone__title",children:V.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Xu[V.status].bg,color:Xu[V.status].text},children:V.status}),t.jsxs("span",{className:"mission-milestone__count",children:[V.slices.length," slices"]}),t.jsx(tm,{state:q1(V.interviewState)}),Ie&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Bt.bg,color:Bt.text},title:"Validation state",children:nm(Ie.state)}),Ie.totalAssertions>0&&t.jsx("div",{className:"mission-milestone__coverage-bar",title:`${Ie.passedAssertions??0} of ${Ie.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-milestone__coverage-bar-fill",style:{width:`${(Ie.passedAssertions??0)/Ie.totalAssertions*100}%`,backgroundColor:(Ie.passedAssertions??0)===Ie.totalAssertions?"var(--color-success)":"var(--color-warning)"}})})]}),V.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Le({type:"milestone",id:V.id,title:V.title}),title:"Plan milestone","aria-label":"Plan milestone",children:t.jsx(Ui,{size:14})}),t.jsxs("div",{className:"mission-milestone__actions",onClick:Ve=>Ve.stopPropagation(),children:[t.jsx("button",{className:"mission-icon-btn",onClick:()=>Me(V.id),title:"Add slice",children:t.jsx(on,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>ci(V),title:"Edit milestone",children:t.jsx(cs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ce({type:"milestone",id:V.id}),title:"Delete milestone",children:t.jsx(rn,{size:14})})]})]}),U.has(V.id)&&t.jsxs("div",{className:"mission-milestone__body",children:[(C||z===V.id)&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:J.title,onChange:Ve=>Q({...J,title:Ve.target.value}),onKeyDown:Ur,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:J.description,onChange:Ve=>Q({...J,description:Ve.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Gs,disabled:E,children:[E?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Hn,{size:14}),z?"Update":"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Cs,children:"Cancel"})]})]}),Se&&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:[Se.validationTelemetry.totalRuns," rounds",Se.validationTelemetry.lastValidatorStatus?` · Last ${Se.validationTelemetry.lastValidatorStatus}`:""]})]}),an&&t.jsxs("div",{className:"mission-blocked-reason",children:[t.jsx("strong",{children:"Blocked reason:"})," ",an]}),pt.length>0&&t.jsxs("div",{className:"mission-validation-rounds",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm mission-validation-rounds__toggle",onClick:()=>Ot(Ve=>!Ve),title:Ft?"Hide validation rounds":"Show validation rounds",children:[Ft?t.jsx(Xt,{size:12}):t.jsx(vn,{size:12}),"Validation rounds (",pt.length,")"]}),Ft&&t.jsx("div",{className:"mission-validation-rounds__list",children:pt.map(Ve=>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--${Ve.validatorStatus}`,children:Ve.validatorStatus}),t.jsx("span",{className:"mission-validation-round__feature",children:Ve.featureTitle}),t.jsxs("span",{className:"mission-validation-round__attempts",children:["impl #",Ve.implementationAttempt," · reviewer #",Ve.validatorAttempt]})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),Ve.failedAssertionIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Ve.failedAssertionIds.map(We=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Pa(We),title:`Jump to assertion ${We}`,children:We},`${Ve.roundId}-${We}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Generated fix features:"}),Ve.generatedFixFeatureIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Ve.generatedFixFeatureIds.map(We=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>xi(We),title:`Jump to fix feature ${We}`,children:We},`${Ve.roundId}-${We}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),Ve.blockedReason&&t.jsx("div",{className:"mission-validation-round__blocked-reason",children:Ve.blockedReason})]},Ve.roundId))})]}),Zt.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:Zt.map(Ve=>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:()=>xi(Ve.id),title:`Jump to feature ${Ve.id}`,children:Ve.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Yr[Ve.status].bg,color:Yr[Ve.status].text},children:Ve.status}),Ve.loopState&&t.jsx("span",{className:`mission-loop-state mission-loop-state--${Ve.loopState}`,children:Ve.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:()=>xi(Ve.sourceFeatureId),title:`Jump to source feature ${Ve.sourceFeatureId}`,children:Ve.sourceFeatureId}),t.jsx("span",{children:"Run:"}),t.jsx("span",{className:"mission-fix-feature__run",children:Ve.runId})]}),Ve.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:Ve.failedAssertionIds.map(We=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Pa(We),title:`Jump to assertion ${We}`,children:We},`${Ve.id}-${We}`))})]})]},Ve.id))})]})]}),t.jsxs("div",{className:"mission-slices",children:[V.slices.map(Ve=>t.jsxs("div",{className:"mission-slice",children:[t.jsxs("div",{className:"mission-slice__header",onClick:()=>gn(Ve.id),children:[t.jsx("button",{className:"mission-slice__expand",children:$.has(Ve.id)?t.jsx(Xt,{size:16}):t.jsx(vn,{size:16})}),t.jsx(_c,{size:16,className:"mission-slice__icon"}),t.jsx("span",{className:"mission-slice__title",children:Ve.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Zu[Ve.status].bg,color:Zu[Ve.status].text},children:Ve.status}),t.jsxs("span",{className:"mission-slice__count",children:[Ve.features?.length||0," features"]}),t.jsx(tm,{state:Ve.planState??"not_started"}),Ve.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Le({type:"slice",id:Ve.id,title:Ve.title}),title:"Plan slice","aria-label":"Plan slice",children:t.jsx(Ui,{size:14})}),t.jsxs("div",{className:"mission-slice__actions",onClick:We=>We.stopPropagation(),children:[Ve.status==="pending"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>dn(Ve.id),title:"Activate slice",children:t.jsx(Sn,{size:14})}),Ve.status==="active"&&Ve.features?.some(We=>We.status==="defined")&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>ss(Ve.id),title:"Triage all features",disabled:E,children:E?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Gn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>wn(Ve.id),title:"Add feature",children:t.jsx(on,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>ct(Ve),title:"Edit slice",children:t.jsx(cs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ce({type:"slice",id:Ve.id}),title:"Delete slice",children:t.jsx(rn,{size:14})})]})]}),$.has(Ve.id)&&t.jsxs("div",{className:"mission-slice__body",children:[ge&&se===V.id&&!P&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:O.title,onChange:We=>H({...O,title:We.target.value}),onKeyDown:Br,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:O.description,onChange:We=>H({...O,description:We.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:sn,disabled:E,children:[E?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Hn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:gt,children:"Cancel"})]})]}),P===Ve.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:O.title,onChange:We=>H({...O,title:We.target.value}),onKeyDown:Br,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:O.description,onChange:We=>H({...O,description:We.target.value}),rows:2}),t.jsxs("select",{value:O.status,onChange:We=>H({...O,status:We.target.value}),children:[t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"complete",children:"Complete"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:sn,disabled:E,children:[E?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Hn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:gt,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-features",children:[Ve.features?.map(We=>t.jsxs("div",{className:"mission-feature","data-mission-feature-id":We.id,children:[t.jsxs("div",{className:"mission-feature__header",children:[t.jsx("button",{className:"mission-feature__expand",onClick:()=>Dr(We.id),title:Ut===We.id?"Collapse details":"Expand to show run history",children:Ut===We.id?t.jsx(Xt,{size:14}):t.jsx(vn,{size:14})}),t.jsx(jc,{size:14,className:"mission-feature__icon"}),t.jsx("span",{className:"mission-feature__title",children:We.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Yr[We.status].bg,color:Yr[We.status].text},children:We.status}),We.loopState&&We.loopState!=="idle"&&t.jsxs("span",{className:`mission-loop-state mission-loop-state--${We.loopState}`,title:`Loop state: ${We.loopState}`,children:[We.loopState==="implementing"&&"⏳",We.loopState==="validating"&&"🔄",We.loopState==="needs_fix"&&"🔧",We.loopState==="passed"&&"✅",We.loopState==="blocked"&&"🚫"]}),We.generatedFromFeatureId&&t.jsx("button",{className:"mission-feature__lineage",onClick:()=>xi(We.generatedFromFeatureId),title:`Generated from feature: ${We.generatedFromFeatureId}`,children:"🔗 Fix"}),(We.loopState==="validating"||We.loopState==="needs_fix")&&(()=>{const xt=wt.get(We.id),bn=Or.get(We.id),_s=xt?.implementationAttemptCount??bn?.implementationAttempt??We.implementationAttemptCount??0,Ri=xt?.retryBudgetRemaining??Math.max(0,H1-_s);return t.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",_s," · ",Ri," ",Ri===1?"retry":"retries"," left"]})})(),We.loopState==="implementing"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>ol(We.id),title:"Validate feature",disabled:Tt.has(We.id),children:Tt.has(We.id)?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(rs,{size:14})}),We.taskId&&t.jsx("span",{className:"mission-feature__task-link",onClick:()=>o?.(We.taskId),title:"Click to view task",children:We.taskId}),t.jsxs("div",{className:"mission-feature__actions",children:[We.status==="defined"&&!We.taskId&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Wn(We.id),title:"Triage — create task",disabled:E||Ue===We.id,children:Ue===We.id?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Gn,{size:14})}),We.taskId?t.jsx("button",{className:"mission-icon-btn",onClick:()=>ps(We.id),title:"Unlink task",children:t.jsx(Ud,{size:14})}):We.status!=="defined"?t.jsx("button",{className:"mission-icon-btn",onClick:()=>Oe(We.id),title:"Link to task",children:t.jsx(ha,{size:14})}):null,t.jsx("button",{className:"mission-icon-btn",onClick:()=>Xn(We),title:"Edit feature",children:t.jsx(cs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ce({type:"feature",id:We.id}),title:"Delete feature",children:t.jsx(rn,{size:14})})]})]}),We.description&&t.jsx("p",{className:"mission-feature__description",children:We.description}),We.acceptanceCriteria&&t.jsxs("p",{className:"mission-feature__criteria",children:[t.jsx("strong",{children:"Acceptance:"})," ",We.acceptanceCriteria]}),fe?.featureId===We.id&&t.jsxs("div",{className:"mission-triage-preview",children:[t.jsx("div",{className:"mission-triage-preview__header",children:"Enriched Description Preview"}),t.jsx("div",{className:"mission-triage-preview__content",children:fe.enrichedDescription}),t.jsxs("div",{className:"mission-triage-preview__actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:fs,disabled:E,children:[E?t.jsx(ot,{size:14,className:"spinner"}):null,"Create Task"]}),t.jsx("button",{className:"btn",onClick:Ls,disabled:E,children:"Cancel"})]})]}),F===We.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:ne.title,onChange:xt=>xe({...ne,title:xt.target.value}),onKeyDown:Xi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:ne.description,onChange:xt=>xe({...ne,description:xt.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:ne.acceptanceCriteria,onChange:xt=>xe({...ne,acceptanceCriteria:xt.target.value}),rows:2}),t.jsxs("select",{value:ne.status,onChange:xt=>xe({...ne,status:xt.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:Ln,disabled:E,children:[E?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Hn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Zn,children:"Cancel"})]})]}),Ut===We.id&&t.jsxs("div",{className:"mission-feature__run-history",children:[t.jsx("div",{className:"mission-feature__run-history-header",children:t.jsx("span",{className:"mission-feature__run-history-title",children:"Validation Runs"})}),(pe.get(We.id)??[]).map(xt=>t.jsxs("div",{className:"mission-run",children:[t.jsxs("div",{className:"mission-run__header",onClick:()=>Lr(xt.id),children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-run__status mission-run__status--${xt.status}`,title:xt.status,children:xt.status}),t.jsx("span",{className:"mission-run__time",children:new Date(xt.startedAt).toLocaleString()}),xt.completedAt&&t.jsxs("span",{className:"mission-run__duration",children:[Math.round((new Date(xt.completedAt).getTime()-new Date(xt.startedAt).getTime())/1e3),"s"]}),xt.triggerType&&t.jsx("span",{className:"mission-run__trigger",children:xt.triggerType}),t.jsx("button",{className:"mission-icon-btn",title:A===xt.id?"Hide details":"Show details",children:A===xt.id?t.jsx(Xt,{size:12}):t.jsx(vn,{size:12})})]}),A===xt.id&&ze.get(xt.id)&&t.jsxs("div",{className:"mission-run__details",children:[xt.summary&&t.jsx("p",{className:"mission-run__summary",children:xt.summary}),xt.blockedReason&&t.jsxs("p",{className:"mission-run__blocked-reason",children:[t.jsx("strong",{children:"Blocked:"})," ",xt.blockedReason]}),ze.get(xt.id)?.failures&&ze.get(xt.id).failures.length>0&&t.jsxs("div",{className:"mission-run__failures",children:[t.jsx("span",{className:"mission-run__failures-title",children:"Failed Assertions:"}),ze.get(xt.id).failures.map(bn=>t.jsxs("div",{className:"mission-run__failure",children:[t.jsx("span",{className:"mission-run__failure-message",children:bn.message}),bn.expected&&t.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",bn.expected]}),bn.actual&&t.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",bn.actual]})]},bn.id))]}),(!ze.get(xt.id)?.failures||ze.get(xt.id).failures.length===0)&&t.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},xt.id)),(!pe.get(We.id)||pe.get(We.id).length===0)&&t.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},We.id)),oe&&ae===Ve.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:ne.title,onChange:We=>xe({...ne,title:We.target.value}),onKeyDown:Xi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:ne.description,onChange:We=>xe({...ne,description:We.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:ne.acceptanceCriteria,onChange:We=>xe({...ne,acceptanceCriteria:We.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Ln,disabled:E,children:[E?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Hn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Zn,children:"Cancel"})]})]}),!oe&&(!Ve.features||Ve.features.length===0)&&t.jsxs("div",{className:"mission-manager__empty mission-features__empty",children:[t.jsx(jc,{size:16}),t.jsx("span",{children:"No fix features generated."})]})]})]})]},Ve.id)),V.slices.length===0&&!ge&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(_c,{size:16}),t.jsx("span",{children:"No slices yet"})]}),t.jsxs("div",{className:"mission-assertions",children:[t.jsxs("div",{className:"mission-assertions__header",children:[t.jsx("span",{className:"mission-assertions__title",children:"Assertions"}),Ie&&t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Bt.bg,color:Bt.text},children:nm(Ie.state)}),Ie&&Ie.totalAssertions>0&&t.jsx("div",{className:"mission-assertions__coverage-bar",title:`${Ie.passedAssertions??0} of ${Ie.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-assertions__coverage-bar-fill",style:{width:`${(Ie.passedAssertions??0)/Ie.totalAssertions*100}%`,backgroundColor:(Ie.passedAssertions??0)===Ie.totalAssertions?"var(--color-success)":"var(--color-warning)"}})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>{le(!0),Ke(null),ft({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:t.jsx(on,{size:14})})]}),Z&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:Pe.title,onChange:Ve=>ft({...Pe,title:Ve.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:Pe.assertion,onChange:Ve=>ft({...Pe,assertion:Ve.target.value}),rows:2}),t.jsxs("select",{value:Pe.status,onChange:Ve=>ft({...Pe,status:Ve.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:()=>zs(V.id),disabled:E,children:[E?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Hn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bi,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-assertions__list",children:[(Array.isArray(De.get(V.id))?De.get(V.id):[]).map(Ve=>t.jsxs("div",{className:"mission-assertion","data-mission-assertion-id":Ve.id,children:[t.jsx("div",{className:"mission-assertion__header",children:Re===Ve.id?t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:Pe.title,onChange:We=>ft({...Pe,title:We.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text",value:Pe.assertion,onChange:We=>ft({...Pe,assertion:We.target.value}),rows:2}),t.jsxs("select",{value:Pe.status,onChange:We=>ft({...Pe,status:We.target.value}),children:[t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"passed",children:"Passed"}),t.jsx("option",{value:"failed",children:"Failed"}),t.jsx("option",{value:"blocked",children:"Blocked"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:()=>al(Ve.id,V.id),disabled:E,children:[E?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Hn,{size:14}),"Save"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bi,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(Xr[Ve.status]??Xr.pending).bg,color:(Xr[Ve.status]??Xr.pending).text},children:Ve.status}),t.jsx("span",{className:"mission-assertion__title",children:Ve.title}),(()=>{const xt=te.get(Ve.id)?.length??0;return xt>0?t.jsxs("span",{className:"mission-assertion__linked-count",title:`${xt} linked feature${xt!==1?"s":""}`,children:["(",xt," linked)"]}):null})(),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ta(Ve.id),title:"Toggle details",children:we===Ve.id?t.jsx(Xt,{size:14}):t.jsx(vn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>di(Ve),title:"Edit assertion",children:t.jsx(cs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ce({type:"assertion",id:Ve.id}),title:"Delete assertion",children:t.jsx(rn,{size:14})})]})}),we===Ve.id&&t.jsxs("div",{className:"mission-assertion__body",children:[t.jsx("p",{className:"mission-assertion__text",children:Ve.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()=>{we!==Ve.id&&await Ta(Ve.id),At(bt===Ve.id?null:Ve.id)},title:"Link a feature",children:[t.jsx(ha,{size:12}),"Link Feature"]})]}),bt===Ve.id&&t.jsx("div",{className:"mission-assertion__feature-picker",children:t.jsx("div",{className:"mission-assertion__feature-picker-dropdown",children:(()=>{const We=new Set((te.get(Ve.id)??[]).map(bn=>bn.id)),xt=[];return g?.milestones.forEach(bn=>bn.slices.forEach(_s=>xt.push(..._s.features.filter(Ri=>!We.has(Ri.id))))),xt.length===0?t.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):xt.map(bn=>t.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>$r(bn.id,Ve.id),disabled:dt.has(Ve.id),children:[t.jsx("span",{className:"mission-assertion__feature-picker-title",children:bn.title}),dt.has(Ve.id)&&t.jsx(ot,{size:12,className:"spinner"})]},bn.id))})()})}),(()=>{const We=te.get(Ve.id)??[];return We.length===0?t.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):We.map(xt=>{const bn=`${xt.id}-${Ve.id}`,_s=Ct.has(bn);return t.jsxs("div",{className:"mission-assertion__linked-feature",children:[t.jsx("span",{className:"mission-assertion__linked-feature-title",children:xt.title}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>rl(xt.id,Ve.id),disabled:_s,title:"Unlink feature",children:_s?t.jsx(ot,{size:12,className:"spinner"}):t.jsx(Ud,{size:12})})]},xt.id)})})()]})]})]},Ve.id)),(!De.get(V.id)||De.get(V.id)?.length===0)&&!Z&&t.jsx("div",{className:"mission-manager__empty mission-assertions__empty",children:t.jsx("span",{children:"No assertions defined. Add one to define completion criteria."})})]})]})]})]})]},V.id)}),g&&!C&&z===null&&t.jsxs("button",{className:"mission-add-btn",onClick:Ds,children:[t.jsx(on,{size:16}),"Add Milestone"]}),C&&z===null&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:J.title,onChange:V=>Q({...J,title:V.target.value}),onKeyDown:Ur,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:J.description,onChange:V=>Q({...J,description:V.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Gs,disabled:E,children:[E?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Hn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Cs,children:"Cancel"})]})]}),g.milestones.length===0&&!C&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Bi,{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:Mt,onChange:V=>ln(V.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:[Dn.length," of ",st]})]}),!In&<&&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:ll,"data-testid":"mission-activity-load-more",children:"Load more"})}),In?t.jsxs("div",{className:"mission-manager__loading mission-detail__activity-loading",children:[t.jsx(ot,{size:18,className:"spinner"}),t.jsx("span",{children:"Loading mission activity..."})]}):Dn.length===0?t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Is,{size:18}),t.jsx("span",{children:"No events yet."})]}):t.jsxs("div",{ref:nn,className:"mission-events","data-testid":"mission-activity-events",children:[Dn.map(V=>{const Se=!!(V.metadata&&Object.keys(V.metadata).length>0),Ie=En.has(V.id);return t.jsxs("div",{className:"mission-event",children:[t.jsxs("div",{className:"mission-event__header",children:[t.jsx("span",{className:`mission-event__type ${J1(V.eventType)}`,children:Y1(V.eventType)}),t.jsx("span",{className:"mission-event__time",children:Mo(V.timestamp)})]}),t.jsx("p",{className:"mission-event__description",children:V.description}),t.jsx("span",{className:"mission-event__timestamp",children:new Date(V.timestamp).toLocaleString()}),Se&&t.jsxs("div",{className:"mission-event__metadata",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>cl(V.id),"data-testid":`mission-event-metadata-${V.id}`,children:[Ie?"Hide":"Show"," metadata"]}),Ie&&t.jsx("pre",{className:"mission-event__metadata-content",children:JSON.stringify(V.metadata,null,2)})]})]},V.id)}),t.jsx("div",{ref:An})]})]})]}):t.jsxs("div",{className:"mission-list",children:[_&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:N.title,onChange:V=>D({...N,title:V.target.value}),onKeyDown:$a,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:N.description,onChange:V=>D({...N,description:V.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:zt,disabled:E,children:[E?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Hn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:St,children:"Cancel"})]})]}),f.map(V=>{const Se=V,Ie=g,pt=Ie&&Ie.id===Se.id,Zt=Ua[Se.status]||{bg:"",text:""},Bt=Se.summary,an=jt.get(Se.id),Ve=W1(an),We=!!(Bt&&(Bt.totalMilestones>0||Bt.totalFeatures>0)),xt=an?.totalTasks??0,bn=an?.tasksCompleted??0,_s=an?.tasksFailed??0,Ri=an?.estimatedCompletionPercent??Bt?.progressPercent??0,ts=We||xt>0||_s>0||!!an?.lastActivityAt,Mn=Se.status==="active"&&(an?.currentMilestoneId||an?.currentSliceId)?"Current milestone/slice in progress":null;return t.jsxs("div",{className:`mission-list__item ${pt?"mission-list__item--selected":""}`,onClick:()=>Y(V),children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(xs,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{className:"mission-list__item-title",children:Se.title}),V.autopilotEnabled&&t.jsx("span",{title:"Autopilot enabled",children:t.jsx(Gn,{size:12,className:"mission-list__item-autopilot-icon"})}),t.jsx("span",{className:`mission-health-badge mission-health-badge--${Ve}`,"data-testid":`mission-health-badge-${Se.id}`,"aria-label":`Mission health: ${Ve}`}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Zt.bg,color:Zt.text},children:Se.status})]}),Se.description&&t.jsx("p",{className:"mission-list__item-description",children:Se.description}),Mn&&t.jsxs("p",{className:"mission-list__item-active-slice",children:["Active: ",Mn]}),ts&&t.jsxs("div",{className:"mission-list__item-summary",children:[We&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"mission-list__item-stat",children:[Bt.completedMilestones,"/",Bt.totalMilestones," milestones"]}),t.jsxs("span",{className:"mission-list__item-stat",children:[Bt.completedFeatures,"/",Bt.totalFeatures," features"]})]}),t.jsxs("span",{className:"mission-list__item-stat","data-testid":`mission-task-stats-${Se.id}`,children:[bn,"/",xt," tasks"]}),_s>0&&t.jsxs("button",{className:"mission-list__item-failed",onClick:Vt=>{Vt.stopPropagation(),Y(V)},"data-testid":`mission-failed-${Se.id}`,title:"View mission failures",children:[_s," failed"]}),t.jsxs("span",{className:"mission-relative-time","data-testid":`mission-last-activity-${Se.id}`,children:["Activity ",Mo(an?.lastActivityAt)]}),t.jsx("div",{className:`mission-list__item-progress mission-list__item-progress--${Ve}`,children:t.jsx("div",{className:"mission-list__item-progress-bar",style:{width:`${Ri}%`}})})]})]}),t.jsxs("div",{className:"mission-list__item-actions",onClick:Vt=>Vt.stopPropagation(),children:[Se.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Mi(Se.id),title:"Stop mission",children:t.jsx(js,{size:14})}),Se.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Ia(Se.id),title:"Resume mission",children:t.jsx(Sn,{size:14})}),Se.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>zr(Se.id),title:"Start mission",children:t.jsx(Sn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>kt(V),title:"Edit mission",children:t.jsx(cs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ce({type:"mission",id:Se.id}),title:"Delete mission",children:t.jsx(rn,{size:14})})]})]},Se.id)}),w&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:N.title,onChange:V=>D({...N,title:V.target.value}),onKeyDown:$a,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:N.description,onChange:V=>D({...N,description:V.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:N.status,onChange:V=>D({...N,status:V.target.value}),children:[t.jsx("option",{value:"planning",children:"Planning"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"blocked",children:"Blocked"}),t.jsx("option",{value:"complete",children:"Complete"}),t.jsx("option",{value:"archived",children:"Archived"})]}),t.jsxs("label",{className:"mission-checkbox",children:[t.jsx("input",{type:"checkbox",checked:N.autopilotEnabled,onChange:V=>D({...N,autopilotEnabled:V.target.checked})}),t.jsx(Gn,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:zt,disabled:E,children:[E?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Hn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:St,children:"Cancel"})]})]}),f.length===0&&!_&&t.jsxs("div",{className:"mission-manager__empty mission-manager__empty--large",children:[t.jsx(xs,{size:32}),t.jsx("span",{children:"No missions yet. Create one to start planning."})]}),!_&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[Be.length>0&&t.jsxs("div",{className:"mission-resume-prompt",children:[t.jsx(us,{size:16}),t.jsx("span",{children:Be.length===1?`Resume "${Be[0].title}"?`:`${Be.length} interview sessions pending`}),t.jsx("div",{style:{display:"flex",gap:"4px",marginLeft:"auto"},children:Be.map(V=>t.jsxs("button",{className:"mission-add-btn",onClick:()=>{ke(V.id),it(!0),Ge([])},children:[V.status==="error"?t.jsx($n,{size:14}):t.jsx(rs,{size:14}),V.status==="error"?"Retry":"Resume"]},V.id))})]}),t.jsxs("div",{style:{display:"flex",gap:"8px"},children:[t.jsxs("button",{className:"mission-add-btn",onClick:()=>it(!0),children:[t.jsx(rs,{size:16}),"Plan with AI"]}),t.jsxs("button",{className:"mission-add-btn",onClick:rt,children:[t.jsx(on,{size:16}),"New Mission"]})]})]})]})}),ve&&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 ",ve.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()=>{ve.type==="mission"?await qn(ve.id):ve.type==="milestone"?await ie(ve.id):ve.type==="slice"?await mn(ve.id):ve.type==="feature"&&await es(ve.id)},children:"Delete"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>ce(null),children:"Cancel"})]})]})}),Ae&&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:Qe,onChange:V=>Xe(V.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(V=>t.jsxs("button",{className:"mission-task-suggestions__item",onClick:()=>Xe(V.id),children:[V.id,": ",V.title||"Untitled"]},V.id))})]}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--primary",onClick:Vn,children:"Link"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>{Oe(null),Xe("")},children:"Cancel"})]})]})})]}),Zi=t.jsx(L1,{isOpen:Ye,onClose:()=>it(!1),onMissionCreated:()=>{cn(),i("Mission created from AI interview","success")},projectId:r,resumeSessionId:X}),dl=Te?t.jsx(O1,{isOpen:!0,onClose:()=>Le(null),onApplied:()=>{Le(null),g&&vt(g.id)},targetType:Te.type,targetId:Te.id,targetTitle:Te.title,missionContext:g?.title,projectId:r,resumeSessionId:Te.resumeSessionId}):null;return n?t.jsxs(t.Fragment,{children:[Ai,Zi,dl]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mission-manager-overlay open",onClick:V=>V.target===V.currentTarget&&s(),"data-testid":"mission-manager-overlay",role:"dialog","aria-modal":"true",children:Ai}),Zi,dl]})}const Zr=2e3;function im({recipient:e,replyContext:n,agents:s=[],projectId:i,onSend:r,onCancel:o,addToast:l,isLoadingAgents:c=!1}){const[u,d]=a.useState(e?.id??""),[m,h]=a.useState(e?.type??"agent"),[f,p]=a.useState(""),[g,b]=a.useState(!1),[v,x]=a.useState(null),y=u.trim()!==""&&f.trim().length>0&&f.length<=Zr,k=a.useCallback(async()=>{if(!(!y||g)){b(!0),x(null);try{const S=m==="agent"?"user-to-agent":"system";await aw({toId:u.trim(),toType:m,content:f.trim(),type:S,...n?{metadata:{replyTo:{messageId:n.messageId}}}:{}},i),r()}catch(S){const w=ye(S)||"Failed to send message";x(w),l?.(w,"error")}finally{b(!1)}}},[y,g,u,m,f,n,i,r,l]),_=a.useCallback(S=>{d(S),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(Wt,{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:S=>_(S.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(S=>t.jsx("option",{value:S.id,children:S.name||S.id},S.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(Nn,{size:14}),e.id]})]}),n&&t.jsxs("div",{className:"message-composer-field","data-testid":"message-composer-reply-context",children:[t.jsx("span",{className:"message-composer-label",children:"Replying to:"}),t.jsx("span",{className:"message-composer-recipient-fixed",children:n.preview?.trim()?n.preview:`Message ${n.messageId}`})]}),t.jsxs("div",{className:"message-composer-field message-composer-field--content",children:[t.jsx("label",{className:"message-composer-label",htmlFor:"message-content",children:"Message:"}),t.jsx("textarea",{id:"message-content",className:"message-composer-textarea",placeholder:"Type your message…",value:f,onChange:S=>p(S.target.value),maxLength:Zr,rows:4,"data-testid":"message-composer-content"}),t.jsx("div",{className:"message-composer-charcount","data-testid":"message-composer-charcount",children:t.jsxs("span",{className:f.length>Zr?"over-limit":"",children:[f.length,"/",Zr]})})]}),v&&t.jsxs("div",{className:"message-composer-error","data-testid":"message-composer-error",children:[t.jsx(us,{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:k,disabled:!y||g,"data-testid":"message-composer-send",children:g?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:14,className:"spin"}),t.jsx("span",{children:"Sending…"})]}):t.jsxs(t.Fragment,{children:[t.jsx(Li,{size:14}),t.jsx("span",{children:"Send"})]})})]})]})}function ia(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 Z1(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 e0(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 am(e,n=80){return e.length<=n?e:`${e.slice(0,n)}…`}function t0(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 n0({projectId:e,addToast:n,onUnreadCountChange:s}){const[i,r]=a.useState("inbox"),[o,l]=a.useState(null),[c,u]=a.useState(null),[d,m]=a.useState(0),[h,f]=a.useState(!1),[p,g]=a.useState(null),[b,v]=a.useState([]),[x,y]=a.useState(!1),[k,_]=a.useState(null),[S,w]=a.useState(null),[M,N]=a.useState(null),[D,E]=a.useState("inbox"),[T,U]=a.useState(null),[K,$]=a.useState([]),R=a.useMemo(()=>new Map(K.map(ae=>[ae.id,ae.name??""])),[K]),z=a.useCallback((ae,je)=>Z1(ae,je,R),[R]),J=Rr()==="mobile",Q=!J,C=a.useCallback(async()=>{f(!0);try{const ae=await sw({limit:50},e);l(ae),m(ae.unreadCount),s?.(ae.unreadCount)}catch{}finally{f(!1)}},[e,s]),L=a.useCallback(async()=>{f(!0);try{const ae=await iw({limit:50},e);u(ae)}catch{}finally{f(!1)}},[e]),P=a.useCallback(async ae=>{f(!0);try{const je=await dw(ae,e);U(je)}catch{}finally{f(!1)}},[e]),j=a.useCallback(async()=>{try{const ae=await Ea(void 0,e);$(ae)}catch{}},[e]),O=a.useCallback(async()=>{try{const ae=await Np(e);m(ae.unreadCount),s?.(ae.unreadCount)}catch{}},[e,s]);a.useEffect(()=>{i==="inbox"?C():i==="outbox"?L():i==="agents"&&j()},[i,C,L,j]),a.useEffect(()=>{M&&P(M)},[M,P]),a.useEffect(()=>{O()},[O]),a.useEffect(()=>{j()},[j]),a.useEffect(()=>{if(typeof EventSource>"u")return;const ae=e?`?projectId=${encodeURIComponent(e)}`:"",je=()=>{O(),i==="inbox"?C():i==="outbox"&&L(),M&&P(M)};return Ks(`/api/events${ae}`,{events:{"message:sent":je,"message:received":je,"message:read":je,"message:deleted":je}})},[e,i,M,O,C,L,P]);const H=a.useCallback(async ae=>{if(g(ae),!ae.read)try{const je=await rw(ae.id,e);je&&l(Oe=>Oe&&{...Oe,messages:Oe.messages.map(Qe=>Qe.id===je.id?je:Qe),unreadCount:Math.max(0,Oe.unreadCount-1)});const Ae=Math.max(0,d-1);m(Ae),s?.(Ae)}catch{}try{const je=await cw(ae.fromId,ae.fromType,e);v(je)}catch{v([ae])}},[e,d,s]),ge=a.useCallback(()=>{g(null),v([])},[]),be=a.useCallback(async()=>{try{const ae=await ow(e);m(0),s?.(0),l(je=>je&&{...je,messages:je.messages.map(Ae=>({...Ae,read:!0})),unreadCount:0}),n?.(`Marked ${ae.markedAsRead} messages as read`,"success")}catch{n?.("Failed to mark messages as read","error")}},[e,n,s]),se=a.useCallback(async ae=>{try{await lw(ae,e),g(null),v([]),i==="inbox"?C():i==="outbox"?L():M&&P(M),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[e,i,M,C,L,P,n]),me=a.useCallback(ae=>{_({id:ae.fromId,type:ae.fromType}),w({messageId:ae.id,preview:am(ae.content,120)}),y(!0)},[]),F=a.useCallback(()=>{y(!1),_(null),w(null),n?.("Message sent","success"),i==="outbox"?L():i==="agents"&&M&&P(M),O()},[i,L,M,P,n,O]),de=a.useCallback(()=>{_(i==="agents"&&M?{id:M,type:"agent"}:null),w(null),y(!0)},[i,M]),ne=a.useCallback(()=>{y(!1),_(null),w(null)},[]),xe=()=>!p||x?null:t.jsxs("div",{className:"mailbox-message-detail","data-testid":"mailbox-message-detail",children:[t.jsxs("div",{className:"mailbox-message-detail-header",children:[J&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:ge,"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:e0(p.type)}),t.jsx("span",{className:"mailbox-message-time",children:ia(p.createdAt)})]}),t.jsxs("div",{className:"mailbox-message-detail-actions",children:[p.fromType==="agent"&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>me(p),"data-testid":"mailbox-reply",children:[t.jsx(wi,{size:14}),t.jsx("span",{children:"Reply"})]}),t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>se(p.id),"data-testid":"mailbox-delete",children:[t.jsx(rn,{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(Nn,{size:14}):t.jsx(ea,{size:14}),z(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(Nn,{size:14}):t.jsx(ea,{size:14}),z(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(ae=>{const je=ae.metadata?.replyTo?.messageId,Ae=je?b.find(Oe=>Oe.id===je):void 0;return t.jsxs("div",{className:`mailbox-conversation-msg ${ae.id===p.id?"current":""}`,children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:z(ae.fromId,ae.fromType)}),t.jsx("span",{className:"mailbox-message-time",children:ia(ae.createdAt)})]}),je&&t.jsxs("div",{className:"mailbox-reply-context","data-testid":`mailbox-reply-context-${ae.id}`,children:["↪ Replying to ",Ae?am(Ae.content,60):`message ${je}`]}),t.jsx("div",{className:"mailbox-conversation-msg-body",children:ae.content})]},ae.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})]})]}),oe=()=>t.jsxs(t.Fragment,{children:[i==="inbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[h&&!o&&t.jsx(Pl,{}),o&&o.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-inbox-empty",children:[t.jsx(nr,{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:t0(o.messages).map(ae=>t.jsxs("div",{className:`mailbox-conversation-group ${ae.unreadCount>0?"unread":""}`,onClick:()=>H(ae.latestMessage),"data-testid":`mailbox-conversation-${ae.key}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ae.fromType==="agent"?t.jsx(Nn,{size:16}):t.jsx(ea,{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:z(ae.fromId,ae.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:ia(ae.latestMessage.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ae.latestMessage.content.slice(0,80),ae.latestMessage.content.length>80?"…":""]})]}),ae.unreadCount>0&&t.jsx("div",{className:"mailbox-group-unread-badge","data-testid":`mailbox-unread-badge-${ae.key}`,children:ae.unreadCount>9?"9+":ae.unreadCount})]},ae.key))})]}),i==="outbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-outbox-list",children:[h&&!c&&t.jsx(Pl,{}),c&&c.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-outbox-empty",children:[t.jsx(Li,{size:32}),t.jsx("p",{children:"No sent messages"})]}),c?.messages.map(ae=>t.jsxs("div",{className:"mailbox-item",onClick:()=>H(ae),"data-testid":`mailbox-item-${ae.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ae.toType==="agent"?t.jsx(Nn,{size:16}):t.jsx(ea,{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: ",z(ae.toId,ae.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:ia(ae.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ae.content.slice(0,80),ae.content.length>80?"…":""]})]})]},ae.id))]}),i==="agents"&&t.jsx("div",{className:"mailbox-agents","data-testid":"mailbox-agents",children:K.length===0?t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Nn,{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:M??"",onChange:ae=>{N(ae.target.value||null),E("inbox")},"data-testid":"mailbox-agent-select",children:[t.jsx("option",{value:"",children:"Select an agent…"}),K.map(ae=>t.jsx("option",{value:ae.id,children:ae.name||ae.id},ae.id))]})}),t.jsxs("button",{className:"btn btn-sm btn-secondary mailbox-compose-btn",onClick:de,"data-testid":"mailbox-compose-btn",children:[t.jsx(wi,{size:14}),t.jsx("span",{children:"Compose"})]})]}),M&&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 ${D==="inbox"?"active":""}`,onClick:()=>E("inbox"),"data-testid":"mailbox-agent-subtab-inbox",children:[t.jsx(nr,{size:12}),t.jsx("span",{children:"Inbox"}),T&&T.unreadCount>0&&t.jsx("span",{className:"mailbox-tab-badge",children:T.unreadCount})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${D==="outbox"?"active":""}`,onClick:()=>E("outbox"),"data-testid":"mailbox-agent-subtab-outbox",children:[t.jsx(Li,{size:12}),t.jsx("span",{children:"Outbox"})]})]}),t.jsxs("div",{className:"mailbox-agents-content",children:[!M&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Nn,{size:32}),t.jsx("p",{children:"Select an agent to view their mailbox"})]}),M&&h&&!T&&t.jsx(Pl,{}),M&&T&&D==="inbox"&&T.inbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(nr,{size:32}),t.jsx("p",{children:"No received messages for this agent"})]}),M&&T&&D==="outbox"&&T.outbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Li,{size:32}),t.jsx("p",{children:"No sent messages for this agent"})]}),M&&T&&D==="inbox"&&T.inbox.map(ae=>t.jsxs("div",{className:`mailbox-item ${ae.read?"":"unread"}`,onClick:()=>H(ae),"data-testid":`mailbox-item-${ae.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ae.fromType==="agent"?t.jsx(Nn,{size:16}):t.jsx(ea,{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:z(ae.fromId,ae.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:ia(ae.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ae.content.slice(0,80),ae.content.length>80?"…":""]})]})]},ae.id)),M&&T&&D==="outbox"&&T.outbox.map(ae=>t.jsxs("div",{className:"mailbox-item",onClick:()=>H(ae),"data-testid":`mailbox-item-${ae.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ae.toType==="agent"?t.jsx(Nn,{size:16}):t.jsx(ea,{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: ",z(ae.toId,ae.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:ia(ae.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ae.content.slice(0,80),ae.content.length>80?"…":""]})]})]},ae.id))]})]})})]}),he=()=>x?t.jsx(im,{recipient:k,replyContext:S,agents:K,projectId:e,onSend:F,onCancel:ne,addToast:n}):p?xe():t.jsxs("div",{className:"mailbox-split-empty","data-testid":"mailbox-split-empty",children:[t.jsx(pa,{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(pa,{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:de,title:"Compose message","data-testid":"mailbox-header-compose",children:[t.jsx(wi,{size:14}),t.jsx("span",{children:"Compose"})]}),i==="inbox"&&d>0&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:be,title:"Mark all as read","data-testid":"mailbox-mark-all-read",children:[t.jsx(Xg,{size:14}),t.jsx("span",{children:"Mark all read"})]}),t.jsx("button",{className:"btn-icon",onClick:()=>{i==="inbox"?C():i==="outbox"?L():M&&P(M)},disabled:h,title:"Refresh","data-testid":"mailbox-refresh",children:h?t.jsx(ot,{size:14,className:"spin"}):t.jsx($n,{size:14})})]})]}),t.jsxs("div",{className:"mailbox-tabs","data-testid":"mailbox-tabs",children:[t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="inbox"?"active":""}`,onClick:()=>{r("inbox"),g(null)},"data-testid":"mailbox-tab-inbox",children:[t.jsx(nr,{size:14}),t.jsx("span",{children:"Inbox"}),d>0&&t.jsx("span",{className:"mailbox-tab-badge",children:d})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="outbox"?"active":""}`,onClick:()=>{r("outbox"),g(null)},"data-testid":"mailbox-tab-outbox",children:[t.jsx(Li,{size:14}),t.jsx("span",{children:"Outbox"})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="agents"?"active":""}`,onClick:()=>{r("agents"),g(null)},"data-testid":"mailbox-tab-agents",children:[t.jsx(Nn,{size:14}),t.jsx("span",{children:"Agents"})]})]}),t.jsx("div",{className:"mailbox-content","data-testid":"mailbox-content",children:Q?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:oe()}),t.jsx("div",{className:"mailbox-split-detail-pane","data-testid":"mailbox-split-detail-pane",children:he()})]}):t.jsxs(t.Fragment,{children:[xe(),x&&t.jsx(im,{recipient:k,replyContext:S,agents:K,projectId:e,onSend:F,onCancel:ne,addToast:n}),!p&&!x&&oe()]})})]})}function Pl(){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 oi(e,n,s){a.useEffect(()=>{if(!n)return;const i=e.current;if(!i)return;try{const u=localStorage.getItem(s);if(u){const{width:d,height:m}=JSON.parse(u);typeof d=="number"&&d>0&&(i.style.width=`${d}px`),typeof m=="number"&&m>0&&(i.style.height=`${m}px`)}}catch{}if(typeof ResizeObserver>"u")return;let r=i.offsetWidth,o=i.offsetHeight,l=null;const c=new ResizeObserver(()=>{const u=i.offsetWidth,d=i.offsetHeight;u===r&&d===o||(r=u,o=d,l&&clearTimeout(l),l=setTimeout(()=>{try{localStorage.setItem(s,JSON.stringify({width:u,height:d}))}catch{}},200))});return c.observe(i),()=>{c.disconnect(),l&&clearTimeout(l)}},[e,n,s])}function Ei(e){const n=a.useRef(!1),s=a.useCallback(r=>{n.current=r.target===r.currentTarget},[]),i=a.useCallback(r=>{const o=n.current&&r.target===r.currentTarget;n.current=!1,o&&e()},[e]);return{onMouseDown:s,onMouseUp:i}}function s0(e,n){const s={};return(e[e.length-1]===""?[...e,""]:e).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const i0=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,a0=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,r0={};function rm(e,n){return(r0.jsx?a0:i0).test(e)}const o0=/[ \t\n\f\r]/g;function l0(e){return typeof e=="object"?e.type==="text"?om(e.value):!1:om(e)}function om(e){return e.replace(o0,"")===""}class Tr{constructor(n,s,i){this.normal=s,this.property=n,i&&(this.space=i)}}Tr.prototype.normal={};Tr.prototype.property={};Tr.prototype.space=void 0;function Jp(e,n){const s={},i={};for(const r of e)Object.assign(s,r.property),Object.assign(i,r.normal);return new Tr(s,i,n)}function Fc(e){return e.toLowerCase()}class vs{constructor(n,s){this.attribute=s,this.property=n}}vs.prototype.attribute="";vs.prototype.booleanish=!1;vs.prototype.boolean=!1;vs.prototype.commaOrSpaceSeparated=!1;vs.prototype.commaSeparated=!1;vs.prototype.defined=!1;vs.prototype.mustUseProperty=!1;vs.prototype.number=!1;vs.prototype.overloadedBoolean=!1;vs.prototype.property="";vs.prototype.spaceSeparated=!1;vs.prototype.space=void 0;let c0=0;const qt=Yi(),zn=Yi(),Oc=Yi(),et=Yi(),xn=Yi(),ma=Yi(),ys=Yi();function Yi(){return 2**++c0}const Uc=Object.freeze(Object.defineProperty({__proto__:null,boolean:qt,booleanish:zn,commaOrSpaceSeparated:ys,commaSeparated:ma,number:et,overloadedBoolean:Oc,spaceSeparated:xn},Symbol.toStringTag,{value:"Module"})),Il=Object.keys(Uc);class vd extends vs{constructor(n,s,i,r){let o=-1;if(super(n,s),lm(this,"space",r),typeof i=="number")for(;++o<Il.length;){const l=Il[o];lm(this,Il[o],(i&Uc[l])===Uc[l])}}}vd.prototype.defined=!0;function lm(e,n,s){s&&(e[n]=s)}function Aa(e){const n={},s={};for(const[i,r]of Object.entries(e.properties)){const o=new vd(i,e.transform(e.attributes||{},i),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(i)&&(o.mustUseProperty=!0),n[i]=o,s[Fc(i)]=i,s[Fc(o.attribute)]=i}return new Tr(n,s,e.space)}const Yp=Aa({properties:{ariaActiveDescendant:null,ariaAtomic:zn,ariaAutoComplete:null,ariaBusy:zn,ariaChecked:zn,ariaColCount:et,ariaColIndex:et,ariaColSpan:et,ariaControls:xn,ariaCurrent:null,ariaDescribedBy:xn,ariaDetails:null,ariaDisabled:zn,ariaDropEffect:xn,ariaErrorMessage:null,ariaExpanded:zn,ariaFlowTo:xn,ariaGrabbed:zn,ariaHasPopup:null,ariaHidden:zn,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:xn,ariaLevel:et,ariaLive:null,ariaModal:zn,ariaMultiLine:zn,ariaMultiSelectable:zn,ariaOrientation:null,ariaOwns:xn,ariaPlaceholder:null,ariaPosInSet:et,ariaPressed:zn,ariaReadOnly:zn,ariaRelevant:null,ariaRequired:zn,ariaRoleDescription:xn,ariaRowCount:et,ariaRowIndex:et,ariaRowSpan:et,ariaSelected:zn,ariaSetSize:et,ariaSort:null,ariaValueMax:et,ariaValueMin:et,ariaValueNow:et,ariaValueText:null,role:null},transform(e,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function Qp(e,n){return n in e?e[n]:n}function Xp(e,n){return Qp(e,n.toLowerCase())}const d0=Aa({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:ma,acceptCharset:xn,accessKey:xn,action:null,allow:null,allowFullScreen:qt,allowPaymentRequest:qt,allowUserMedia:qt,alt:null,as:null,async:qt,autoCapitalize:null,autoComplete:xn,autoFocus:qt,autoPlay:qt,blocking:xn,capture:null,charSet:null,checked:qt,cite:null,className:xn,cols:et,colSpan:null,content:null,contentEditable:zn,controls:qt,controlsList:xn,coords:et|ma,crossOrigin:null,data:null,dateTime:null,decoding:null,default:qt,defer:qt,dir:null,dirName:null,disabled:qt,download:Oc,draggable:zn,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:qt,formTarget:null,headers:xn,height:et,hidden:Oc,high:et,href:null,hrefLang:null,htmlFor:xn,httpEquiv:xn,id:null,imageSizes:null,imageSrcSet:null,inert:qt,inputMode:null,integrity:null,is:null,isMap:qt,itemId:null,itemProp:xn,itemRef:xn,itemScope:qt,itemType:xn,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:qt,low:et,manifest:null,max:null,maxLength:et,media:null,method:null,min:null,minLength:et,multiple:qt,muted:qt,name:null,nonce:null,noModule:qt,noValidate:qt,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:qt,optimum:et,pattern:null,ping:xn,placeholder:null,playsInline:qt,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:qt,referrerPolicy:null,rel:xn,required:qt,reversed:qt,rows:et,rowSpan:et,sandbox:xn,scope:null,scoped:qt,seamless:qt,selected:qt,shadowRootClonable:qt,shadowRootDelegatesFocus:qt,shadowRootMode:null,shape:null,size:et,sizes:null,slot:null,span:et,spellCheck:zn,src:null,srcDoc:null,srcLang:null,srcSet:null,start:et,step:null,style:null,tabIndex:et,target:null,title:null,translate:null,type:null,typeMustMatch:qt,useMap:null,value:zn,width:et,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:xn,axis:null,background:null,bgColor:null,border:et,borderColor:null,bottomMargin:et,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:qt,declare:qt,event:null,face:null,frame:null,frameBorder:null,hSpace:et,leftMargin:et,link:null,longDesc:null,lowSrc:null,marginHeight:et,marginWidth:et,noResize:qt,noHref:qt,noShade:qt,noWrap:qt,object:null,profile:null,prompt:null,rev:null,rightMargin:et,rules:null,scheme:null,scrolling:zn,standby:null,summary:null,text:null,topMargin:et,valueType:null,version:null,vAlign:null,vLink:null,vSpace:et,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:qt,disableRemotePlayback:qt,prefix:null,property:null,results:et,security:null,unselectable:null},space:"html",transform:Xp}),u0=Aa({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:ys,accentHeight:et,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:et,amplitude:et,arabicForm:null,ascent:et,attributeName:null,attributeType:null,azimuth:et,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:et,by:null,calcMode:null,capHeight:et,className:xn,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:et,diffuseConstant:et,direction:null,display:null,dur:null,divisor:et,dominantBaseline:null,download:qt,dx:null,dy:null,edgeMode:null,editable:null,elevation:et,enableBackground:null,end:null,event:null,exponent:et,externalResourcesRequired:null,fill:null,fillOpacity:et,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:ma,g2:ma,glyphName:ma,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:et,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:et,horizOriginX:et,horizOriginY:et,id:null,ideographic:et,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:et,k:et,k1:et,k2:et,k3:et,k4:et,kernelMatrix:ys,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:et,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:et,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:et,overlineThickness:et,paintOrder:null,panose1:null,path:null,pathLength:et,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:xn,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:et,pointsAtY:et,pointsAtZ:et,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:ys,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:ys,rev:ys,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:ys,requiredFeatures:ys,requiredFonts:ys,requiredFormats:ys,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:et,specularExponent:et,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:et,strikethroughThickness:et,string:null,stroke:null,strokeDashArray:ys,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:et,strokeOpacity:et,strokeWidth:null,style:null,surfaceScale:et,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:ys,tabIndex:et,tableValues:null,target:null,targetX:et,targetY:et,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:ys,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:et,underlineThickness:et,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:et,values:null,vAlphabetic:et,vMathematical:et,vectorEffect:null,vHanging:et,vIdeographic:et,version:null,vertAdvY:et,vertOriginX:et,vertOriginY:et,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:et,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Qp}),Zp=Aa({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,n){return"xlink:"+n.slice(5).toLowerCase()}}),ef=Aa({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Xp}),tf=Aa({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,n){return"xml:"+n.slice(3).toLowerCase()}}),m0={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"},h0=/[A-Z]/g,cm=/-[a-z]/g,p0=/^data[-\w.:]+$/i;function f0(e,n){const s=Fc(n);let i=n,r=vs;if(s in e.normal)return e.property[e.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&p0.test(n)){if(n.charAt(4)==="-"){const o=n.slice(5).replace(cm,b0);i="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=n.slice(4);if(!cm.test(o)){let l=o.replace(h0,g0);l.charAt(0)!=="-"&&(l="-"+l),n="data"+l}}r=vd}return new r(i,n)}function g0(e){return"-"+e.toLowerCase()}function b0(e){return e.charAt(1).toUpperCase()}const x0=Jp([Yp,d0,Zp,ef,tf],"html"),yd=Jp([Yp,u0,Zp,ef,tf],"svg");function v0(e){return e.join(" ").trim()}var aa={},$l,dm;function y0(){if(dm)return $l;dm=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=`
|
|
619
|
-
`,d="/",m="*",h="",f="comment",p="declaration";function g(v,x){if(typeof v!="string")throw new TypeError("First argument must be a string");if(!v)return[];x=x||{};var y=1,k=1;function _($){var R=$.match(n);R&&(y+=R.length);var z=$.lastIndexOf(u);k=~z?$.length-z:k+$.length}function S(){var $={line:y,column:k};return function(R){return R.position=new w($),D(),R}}function w($){this.start=$,this.end={line:y,column:k},this.source=x.source}w.prototype.content=v;function M($){var R=new Error(x.source+":"+y+":"+k+": "+$);if(R.reason=$,R.filename=x.source,R.line=y,R.column=k,R.source=v,!x.silent)throw R}function N($){var R=$.exec(v);if(R){var z=R[0];return _(z),v=v.slice(z.length),R}}function D(){N(s)}function E($){var R;for($=$||[];R=T();)R!==!1&&$.push(R);return $}function T(){var $=S();if(!(d!=v.charAt(0)||m!=v.charAt(1))){for(var R=2;h!=v.charAt(R)&&(m!=v.charAt(R)||d!=v.charAt(R+1));)++R;if(R+=2,h===v.charAt(R-1))return M("End of comment missing");var z=v.slice(2,R-2);return k+=2,_(z),v=v.slice(R),k+=2,$({type:f,comment:z})}}function U(){var $=S(),R=N(i);if(R){if(T(),!N(r))return M("property missing ':'");var z=N(o),B=$({type:p,property:b(R[0].replace(e,h)),value:z?b(z[0].replace(e,h)):h});return N(l),B}}function K(){var $=[];E($);for(var R;R=U();)R!==!1&&($.push(R),E($));return $}return D(),K()}function b(v){return v?v.replace(c,h):h}return $l=g,$l}var um;function j0(){if(um)return aa;um=1;var e=aa&&aa.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(aa,"__esModule",{value:!0}),aa.default=s;const n=e(y0());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 aa}var Ba={},mm;function k0(){if(mm)return Ba;mm=1,Object.defineProperty(Ba,"__esModule",{value:!0}),Ba.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 Ba.camelCase=u,Ba}var Ha,hm;function w0(){if(hm)return Ha;hm=1;var e=Ha&&Ha.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},n=e(j0()),s=k0();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,Ha=i,Ha}var N0=w0();const S0=Kh(N0),nf=sf("end"),jd=sf("start");function sf(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 C0(e){const n=jd(e),s=nf(e);if(n&&s)return{start:n,end:s}}function lr(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?pm(e.position):"start"in e||"end"in e?pm(e):"line"in e||"column"in e?Bc(e):""}function Bc(e){return fm(e&&e.line)+":"+fm(e&&e.column)}function pm(e){return Bc(e&&e.start)+"-"+Bc(e&&e.end)}function fm(e){return e&&typeof e=="number"?e:1}class os 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=lr(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}}os.prototype.file="";os.prototype.name="";os.prototype.reason="";os.prototype.message="";os.prototype.stack="";os.prototype.column=void 0;os.prototype.line=void 0;os.prototype.ancestors=void 0;os.prototype.cause=void 0;os.prototype.fatal=void 0;os.prototype.place=void 0;os.prototype.ruleId=void 0;os.prototype.source=void 0;const kd={}.hasOwnProperty,E0=new Map,_0=/[A-Z]/g,M0=new Set(["table","tbody","thead","tfoot","tr"]),A0=new Set(["td","th"]),af="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function R0(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=F0(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=z0(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"?yd:x0,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},o=rf(r,e,void 0);return o&&typeof o!="string"?o:r.create(e,r.Fragment,{children:o||void 0},void 0)}function rf(e,n,s){if(n.type==="element")return T0(e,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return P0(e,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return $0(e,n,s);if(n.type==="mdxjsEsm")return I0(e,n);if(n.type==="root")return D0(e,n,s);if(n.type==="text")return L0(e,n)}function T0(e,n,s){const i=e.schema;let r=i;n.tagName.toLowerCase()==="svg"&&i.space==="html"&&(r=yd,e.schema=r),e.ancestors.push(n);const o=lf(e,n.tagName,!1),l=O0(e,n);let c=Nd(e,n);return M0.has(n.tagName)&&(c=c.filter(function(u){return typeof u=="string"?!l0(u):!0})),of(e,l,o,n),wd(l,c),e.ancestors.pop(),e.schema=i,e.create(n,o,l,s)}function P0(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)}vr(e,n.position)}function I0(e,n){if(n.data&&n.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(n.data.estree);vr(e,n.position)}function $0(e,n,s){const i=e.schema;let r=i;n.name==="svg"&&i.space==="html"&&(r=yd,e.schema=r),e.ancestors.push(n);const o=n.name===null?e.Fragment:lf(e,n.name,!0),l=U0(e,n),c=Nd(e,n);return of(e,l,o,n),wd(l,c),e.ancestors.pop(),e.schema=i,e.create(n,o,l,s)}function D0(e,n,s){const i={};return wd(i,Nd(e,n)),e.create(n,e.Fragment,i,s)}function L0(e,n){return n.value}function of(e,n,s,i){typeof s!="string"&&s!==e.Fragment&&e.passNode&&(n.node=i)}function wd(e,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(e.children=s)}}function z0(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 F0(e,n){return s;function s(i,r,o,l){const c=Array.isArray(o.children),u=jd(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 O0(e,n){const s={};let i,r;for(r in n.properties)if(r!=="children"&&kd.call(n.properties,r)){const o=B0(e,r,n.properties[r]);if(o){const[l,c]=o;e.tableCellAlignToStyle&&l==="align"&&typeof c=="string"&&A0.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 U0(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 vr(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 vr(e,n.position);else o=i.value===null?!0:i.value;s[r]=o}return s}function Nd(e,n){const s=[];let i=-1;const r=e.passKeys?new Map:E0;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=rf(e,o,l);c!==void 0&&s.push(c)}return s}function B0(e,n,s){const i=f0(e.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=i.commaSeparated?s0(s):v0(s)),i.property==="style"){let r=typeof s=="object"?s:H0(e,String(s));return e.stylePropertyNameCase==="css"&&(r=q0(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&i.space?m0[i.property]||i.property:i.attribute,s]}}function H0(e,n){try{return S0(n,{reactCompat:!0})}catch(s){if(e.ignoreInvalidStyle)return{};const i=s,r=new os("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=af+"#cannot-parse-style-attribute",r}}function lf(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=rm(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=rm(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(i.type==="Literal"){const r=i.value;return kd.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(i);vr(e)}function vr(e,n){const s=new os("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=af+"#cannot-handle-mdx-estrees-without-createevaluater",s}function q0(e){const n={};let s;for(s in e)kd.call(e,s)&&(n[V0(s)]=e[s]);return n}function V0(e){let n=e.replace(_0,W0);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function W0(e){return"-"+e.toLowerCase()}const Dl={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"]},K0={};function Sd(e,n){const s=K0,i=typeof s.includeImageAlt=="boolean"?s.includeImageAlt:!0,r=typeof s.includeHtml=="boolean"?s.includeHtml:!0;return cf(e,i,r)}function cf(e,n,s){if(G0(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 gm(e.children,n,s)}return Array.isArray(e)?gm(e,n,s):""}function gm(e,n,s){const i=[];let r=-1;for(;++r<e.length;)i[r]=cf(e[r],n,s);return i.join("")}function G0(e){return!!(e&&typeof e=="object")}const bm=document.createElement("i");function Cd(e){const n="&"+e+";";bm.innerHTML=n;const s=bm.textContent;return s.charCodeAt(s.length-1)===59&&e!=="semi"||s===n?!1:s}function Ns(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 Ts(e,n){return e.length>0?(Ns(e,e.length,0,n),e):n}const xm={}.hasOwnProperty;function df(e){const n={};let s=-1;for(;++s<e.length;)J0(n,e[s]);return n}function J0(e,n){let s;for(s in n){const r=(xm.call(e,s)?e[s]:void 0)||(e[s]={}),o=n[s];let l;if(o)for(l in o){xm.call(r,l)||(r[l]=[]);const c=o[l];Y0(r[l],Array.isArray(c)?c:c?[c]:[])}}}function Y0(e,n){let s=-1;const i=[];for(;++s<n.length;)(n[s].add==="after"?e:i).push(n[s]);Ns(e,0,0,i)}function uf(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 qs(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const ds=_i(/[A-Za-z]/),as=_i(/[\dA-Za-z]/),Q0=_i(/[#-'*+\--9=?A-Z^-~]/);function Ao(e){return e!==null&&(e<32||e===127)}const Hc=_i(/\d/),X0=_i(/[\dA-Fa-f]/),Z0=_i(/[!-/:-@[-`{-~]/);function Nt(e){return e!==null&&e<-2}function pn(e){return e!==null&&(e<0||e===32)}function Qt(e){return e===-2||e===-1||e===32}const el=_i(/\p{P}|\p{S}/u),Wi=_i(/\s/);function _i(e){return n;function n(s){return s!==null&&s>-1&&e.test(String.fromCharCode(s))}}function Ra(e){const n=[];let s=-1,i=0,r=0;for(;++s<e.length;){const o=e.charCodeAt(s);let l="";if(o===37&&as(e.charCodeAt(s+1))&&as(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 en(e,n,s,i){const r=i?i-1:Number.POSITIVE_INFINITY;let o=0;return l;function l(u){return Qt(u)?(e.enter(s),c(u)):n(u)}function c(u){return Qt(u)&&o++<r?(e.consume(u),c):(e.exit(s),n(u))}}const eS={tokenize:tS};function tS(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"),en(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 Nt(c)?(e.consume(c),e.exit("chunkText"),o):(e.consume(c),l)}}const nS={tokenize:sS},vm={tokenize:iS};function sS(e){const n=this,s=[];let i=0,r,o,l;return c;function c(k){if(i<s.length){const _=s[i];return n.containerState=_[1],e.attempt(_[0].continuation,u,d)(k)}return d(k)}function u(k){if(i++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,r&&y();const _=n.events.length;let S=_,w;for(;S--;)if(n.events[S][0]==="exit"&&n.events[S][1].type==="chunkFlow"){w=n.events[S][1].end;break}x(i);let M=_;for(;M<n.events.length;)n.events[M][1].end={...w},M++;return Ns(n.events,S+1,0,n.events.slice(_)),n.events.length=M,d(k)}return c(k)}function d(k){if(i===s.length){if(!r)return f(k);if(r.currentConstruct&&r.currentConstruct.concrete)return g(k);n.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return n.containerState={},e.check(vm,m,h)(k)}function m(k){return r&&y(),x(i),f(k)}function h(k){return n.parser.lazy[n.now().line]=i!==s.length,l=n.now().offset,g(k)}function f(k){return n.containerState={},e.attempt(vm,p,g)(k)}function p(k){return i++,s.push([n.currentConstruct,n.containerState]),f(k)}function g(k){if(k===null){r&&y(),x(0),e.consume(k);return}return r=r||n.parser.flow(n.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:o}),b(k)}function b(k){if(k===null){v(e.exit("chunkFlow"),!0),x(0),e.consume(k);return}return Nt(k)?(e.consume(k),v(e.exit("chunkFlow")),i=0,n.interrupt=void 0,c):(e.consume(k),b)}function v(k,_){const S=n.sliceStream(k);if(_&&S.push(null),k.previous=o,o&&(o.next=k),o=k,r.defineSkip(k.start),r.write(S),n.parser.lazy[k.start.line]){let w=r.events.length;for(;w--;)if(r.events[w][1].start.offset<l&&(!r.events[w][1].end||r.events[w][1].end.offset>l))return;const M=n.events.length;let N=M,D,E;for(;N--;)if(n.events[N][0]==="exit"&&n.events[N][1].type==="chunkFlow"){if(D){E=n.events[N][1].end;break}D=!0}for(x(i),w=M;w<n.events.length;)n.events[w][1].end={...E},w++;Ns(n.events,N+1,0,n.events.slice(M)),n.events.length=w}}function x(k){let _=s.length;for(;_-- >k;){const S=s[_];n.containerState=S[1],S[0].exit.call(n,e)}s.length=k}function y(){r.write([null]),o=void 0,r=void 0,n.containerState._closeFlow=void 0}}function iS(e,n,s){return en(e,e.attempt(this.parser.constructs.document,n,s),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function xa(e){if(e===null||pn(e)||Wi(e))return 1;if(el(e))return 2}function tl(e,n,s){const i=[];let r=-1;for(;++r<e.length;){const o=e[r].resolveAll;o&&!i.includes(o)&&(n=o(n,s),i.push(o))}return n}const qc={name:"attention",resolveAll:aS,tokenize:rS};function aS(e,n){let s=-1,i,r,o,l,c,u,d,m;for(;++s<e.length;)if(e[s][0]==="enter"&&e[s][1].type==="attentionSequence"&&e[s][1]._close){for(i=s;i--;)if(e[i][0]==="exit"&&e[i][1].type==="attentionSequence"&&e[i][1]._open&&n.sliceSerialize(e[i][1]).charCodeAt(0)===n.sliceSerialize(e[s][1]).charCodeAt(0)){if((e[i][1]._close||e[s][1]._open)&&(e[s][1].end.offset-e[s][1].start.offset)%3&&!((e[i][1].end.offset-e[i][1].start.offset+e[s][1].end.offset-e[s][1].start.offset)%3))continue;u=e[i][1].end.offset-e[i][1].start.offset>1&&e[s][1].end.offset-e[s][1].start.offset>1?2:1;const h={...e[i][1].end},f={...e[s][1].start};ym(h,-u),ym(f,u),l={type:u>1?"strongSequence":"emphasisSequence",start:h,end:{...e[i][1].end}},c={type:u>1?"strongSequence":"emphasisSequence",start:{...e[s][1].start},end:f},o={type:u>1?"strongText":"emphasisText",start:{...e[i][1].end},end:{...e[s][1].start}},r={type:u>1?"strong":"emphasis",start:{...l.start},end:{...c.end}},e[i][1].end={...l.start},e[s][1].start={...c.end},d=[],e[i][1].end.offset-e[i][1].start.offset&&(d=Ts(d,[["enter",e[i][1],n],["exit",e[i][1],n]])),d=Ts(d,[["enter",r,n],["enter",l,n],["exit",l,n],["enter",o,n]]),d=Ts(d,tl(n.parser.constructs.insideSpan.null,e.slice(i+1,s),n)),d=Ts(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=Ts(d,[["enter",e[s][1],n],["exit",e[s][1],n]])):m=0,Ns(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 rS(e,n){const s=this.parser.constructs.attentionMarkers.null,i=this.previous,r=xa(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=xa(u),h=!m||m===2&&r||s.includes(u),f=!r||r===2&&m||s.includes(i);return d._open=!!(o===42?h:h&&(r||!f)),d._close=!!(o===42?f:f&&(m||!h)),n(u)}}function ym(e,n){e.column+=n,e.offset+=n,e._bufferIndex+=n}const oS={name:"autolink",tokenize:lS};function lS(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 ds(p)?(e.consume(p),l):p===64?s(p):d(p)}function l(p){return p===43||p===45||p===46||as(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||as(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||Ao(p)?s(p):(e.consume(p),u)}function d(p){return p===64?(e.consume(p),m):Q0(p)?(e.consume(p),d):s(p)}function m(p){return as(p)?h(p):s(p)}function h(p){return p===46?(e.consume(p),i=0,m):p===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.exit("autolink"),n):f(p)}function f(p){if((p===45||as(p))&&i++<63){const g=p===45?f:h;return e.consume(p),g}return s(p)}}const Pr={partial:!0,tokenize:cS};function cS(e,n,s){return i;function i(o){return Qt(o)?en(e,r,"linePrefix")(o):r(o)}function r(o){return o===null||Nt(o)?n(o):s(o)}}const mf={continuation:{tokenize:uS},exit:mS,name:"blockQuote",tokenize:dS};function dS(e,n,s){const i=this;return r;function r(l){if(l===62){const c=i.containerState;return c.open||(e.enter("blockQuote",{_container:!0}),c.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(l),e.exit("blockQuoteMarker"),o}return s(l)}function o(l){return Qt(l)?(e.enter("blockQuotePrefixWhitespace"),e.consume(l),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),n):(e.exit("blockQuotePrefix"),n(l))}}function uS(e,n,s){const i=this;return r;function r(l){return Qt(l)?en(e,o,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l):o(l)}function o(l){return e.attempt(mf,n,s)(l)}}function mS(e){e.exit("blockQuote")}const hf={name:"characterEscape",tokenize:hS};function hS(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 Z0(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),n):s(o)}}const pf={name:"characterReference",tokenize:pS};function pS(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=as,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=X0,m):(e.enter("characterReferenceValue"),o=7,l=Hc,m(h))}function m(h){if(h===59&&r){const f=e.exit("characterReferenceValue");return l===as&&!Cd(i.sliceSerialize(f))?s(h):(e.enter("characterReferenceMarker"),e.consume(h),e.exit("characterReferenceMarker"),e.exit("characterReference"),n)}return l(h)&&r++<o?(e.consume(h),m):s(h)}}const jm={partial:!0,tokenize:gS},km={concrete:!0,name:"codeFenced",tokenize:fS};function fS(e,n,s){const i=this,r={partial:!0,tokenize:S};let o=0,l=0,c;return u;function u(w){return d(w)}function d(w){const M=i.events[i.events.length-1];return o=M&&M[1].type==="linePrefix"?M[2].sliceSerialize(M[1],!0).length:0,c=w,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),m(w)}function m(w){return w===c?(l++,e.consume(w),m):l<3?s(w):(e.exit("codeFencedFenceSequence"),Qt(w)?en(e,h,"whitespace")(w):h(w))}function h(w){return w===null||Nt(w)?(e.exit("codeFencedFence"),i.interrupt?n(w):e.check(jm,b,_)(w)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),f(w))}function f(w){return w===null||Nt(w)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),h(w)):Qt(w)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),en(e,p,"whitespace")(w)):w===96&&w===c?s(w):(e.consume(w),f)}function p(w){return w===null||Nt(w)?h(w):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(w))}function g(w){return w===null||Nt(w)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),h(w)):w===96&&w===c?s(w):(e.consume(w),g)}function b(w){return e.attempt(r,_,v)(w)}function v(w){return e.enter("lineEnding"),e.consume(w),e.exit("lineEnding"),x}function x(w){return o>0&&Qt(w)?en(e,y,"linePrefix",o+1)(w):y(w)}function y(w){return w===null||Nt(w)?e.check(jm,b,_)(w):(e.enter("codeFlowValue"),k(w))}function k(w){return w===null||Nt(w)?(e.exit("codeFlowValue"),y(w)):(e.consume(w),k)}function _(w){return e.exit("codeFenced"),n(w)}function S(w,M,N){let D=0;return E;function E(R){return w.enter("lineEnding"),w.consume(R),w.exit("lineEnding"),T}function T(R){return w.enter("codeFencedFence"),Qt(R)?en(w,U,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(R):U(R)}function U(R){return R===c?(w.enter("codeFencedFenceSequence"),K(R)):N(R)}function K(R){return R===c?(D++,w.consume(R),K):D>=l?(w.exit("codeFencedFenceSequence"),Qt(R)?en(w,$,"whitespace")(R):$(R)):N(R)}function $(R){return R===null||Nt(R)?(w.exit("codeFencedFence"),M(R)):N(R)}}}function gS(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 Ll={name:"codeIndented",tokenize:xS},bS={partial:!0,tokenize:vS};function xS(e,n,s){const i=this;return r;function r(d){return e.enter("codeIndented"),en(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):Nt(d)?e.attempt(bS,l,u)(d):(e.enter("codeFlowValue"),c(d))}function c(d){return d===null||Nt(d)?(e.exit("codeFlowValue"),l(d)):(e.consume(d),c)}function u(d){return e.exit("codeIndented"),n(d)}}function vS(e,n,s){const i=this;return r;function r(l){return i.parser.lazy[i.now().line]?s(l):Nt(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),r):en(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):Nt(l)?r(l):s(l)}}const yS={name:"codeText",previous:kS,resolve:jS,tokenize:wS};function jS(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 kS(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function wS(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)):Nt(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||Nt(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 NS{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&&qa(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),qa(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),qa(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);qa(this.right,s.reverse())}else{const s=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);qa(this.left,s.reverse())}}}function qa(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 ff(e){const n={};let s=-1,i,r,o,l,c,u,d;const m=new NS(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,SS(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 Ns(e,0,Number.POSITIVE_INFINITY,m.slice(0)),!d}function SS(e,n){const s=e.get(n)[1],i=e.get(n)[2];let r=n-1;const o=[];let l=s._tokenizer;l||(l=i.parser[s.contentType](s.start),s._contentTypeTextTrailing&&(l._contentTypeTextTrailing=!0));const c=l.events,u=[],d={};let m,h,f=-1,p=s,g=0,b=0;const v=[b];for(;p;){for(;e.get(++r)[1]!==p;);o.push(r),p._tokenizer||(m=i.sliceStream(p),p.next||m.push(null),h&&l.defineSkip(p.start),p._isInFirstContentOfListItem&&(l._gfmTasklistFirstContentOfListItem=!0),l.write(m),p._isInFirstContentOfListItem&&(l._gfmTasklistFirstContentOfListItem=void 0)),h=p,p=p.next}for(p=s;++f<c.length;)c[f][0]==="exit"&&c[f-1][0]==="enter"&&c[f][1].type===c[f-1][1].type&&c[f][1].start.line!==c[f][1].end.line&&(b=f+1,v.push(b),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(l.events=[],p?(p._tokenizer=void 0,p.previous=void 0):v.pop(),f=v.length;f--;){const x=c.slice(v[f],v[f+1]),y=o.pop();u.push([y,y+x.length-1]),e.splice(y,2,x)}for(u.reverse(),f=-1;++f<u.length;)d[g+u[f][0]]=g+u[f][1],g+=u[f][1]-u[f][0]-1;return d}const CS={resolve:_S,tokenize:MS},ES={partial:!0,tokenize:AS};function _S(e){return ff(e),e}function MS(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):Nt(c)?e.check(ES,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 AS(e,n,s){const i=this;return r;function r(l){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),en(e,o,"linePrefix")}function o(l){if(l===null||Nt(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 gf(e,n,s,i,r,o,l,c,u){const d=u||Number.POSITIVE_INFINITY;let m=0;return h;function h(x){return x===60?(e.enter(i),e.enter(r),e.enter(o),e.consume(x),e.exit(o),f):x===null||x===32||x===41||Ao(x)?s(x):(e.enter(i),e.enter(l),e.enter(c),e.enter("chunkString",{contentType:"string"}),b(x))}function f(x){return x===62?(e.enter(o),e.consume(x),e.exit(o),e.exit(r),e.exit(i),n):(e.enter(c),e.enter("chunkString",{contentType:"string"}),p(x))}function p(x){return x===62?(e.exit("chunkString"),e.exit(c),f(x)):x===null||x===60||Nt(x)?s(x):(e.consume(x),x===92?g:p)}function g(x){return x===60||x===62||x===92?(e.consume(x),p):p(x)}function b(x){return!m&&(x===null||x===41||pn(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||Ao(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 bf(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):Nt(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||Nt(p)||c++>999?(e.exit("chunkString"),m(p)):(e.consume(p),u||(u=!Qt(p)),p===92?f:h)}function f(p){return p===91||p===92||p===93?(e.consume(p),c++,h):h(p)}}function xf(e,n,s,i,r,o){let l;return c;function c(f){return f===34||f===39||f===40?(e.enter(i),e.enter(r),e.consume(f),e.exit(r),l=f===40?41:f,u):s(f)}function u(f){return f===l?(e.enter(r),e.consume(f),e.exit(r),e.exit(i),n):(e.enter(o),d(f))}function d(f){return f===l?(e.exit(o),u(l)):f===null?s(f):Nt(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),en(e,d,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),m(f))}function m(f){return f===l||f===null||Nt(f)?(e.exit("chunkString"),d(f)):(e.consume(f),f===92?h:m)}function h(f){return f===l||f===92?(e.consume(f),m):m(f)}}function cr(e,n){let s;return i;function i(r){return Nt(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),s=!0,i):Qt(r)?en(e,i,s?"linePrefix":"lineSuffix")(r):n(r)}}const RS={name:"definition",tokenize:PS},TS={partial:!0,tokenize:IS};function PS(e,n,s){const i=this;let r;return o;function o(p){return e.enter("definition"),l(p)}function l(p){return bf.call(i,e,c,s,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function c(p){return r=qs(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 pn(p)?cr(e,d)(p):d(p)}function d(p){return gf(e,m,s,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function m(p){return e.attempt(TS,h,h)(p)}function h(p){return Qt(p)?en(e,f,"whitespace")(p):f(p)}function f(p){return p===null||Nt(p)?(e.exit("definition"),i.parser.defined.push(r),n(p)):s(p)}}function IS(e,n,s){return i;function i(c){return pn(c)?cr(e,r)(c):s(c)}function r(c){return xf(e,o,s,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function o(c){return Qt(c)?en(e,l,"whitespace")(c):l(c)}function l(c){return c===null||Nt(c)?n(c):s(c)}}const $S={name:"hardBreakEscape",tokenize:DS};function DS(e,n,s){return i;function i(o){return e.enter("hardBreakEscape"),e.consume(o),r}function r(o){return Nt(o)?(e.exit("hardBreakEscape"),n(o)):s(o)}}const LS={name:"headingAtx",resolve:zS,tokenize:FS};function zS(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"},Ns(e,i,s-i+1,[["enter",r,n],["enter",o,n],["exit",o,n],["exit",r,n]])),e}function FS(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||pn(m)?(e.exit("atxHeadingSequence"),c(m)):s(m)}function c(m){return m===35?(e.enter("atxHeadingSequence"),u(m)):m===null||Nt(m)?(e.exit("atxHeading"),n(m)):Qt(m)?en(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||pn(m)?(e.exit("atxHeadingText"),c(m)):(e.consume(m),d)}}const OS=["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"],wm=["pre","script","style","textarea"],US={concrete:!0,name:"htmlFlow",resolveTo:qS,tokenize:VS},BS={partial:!0,tokenize:KS},HS={partial:!0,tokenize:WS};function qS(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 VS(e,n,s){const i=this;let r,o,l,c,u;return d;function d(j){return m(j)}function m(j){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(j),h}function h(j){return j===33?(e.consume(j),f):j===47?(e.consume(j),o=!0,b):j===63?(e.consume(j),r=3,i.interrupt?n:C):ds(j)?(e.consume(j),l=String.fromCharCode(j),v):s(j)}function f(j){return j===45?(e.consume(j),r=2,p):j===91?(e.consume(j),r=5,c=0,g):ds(j)?(e.consume(j),r=4,i.interrupt?n:C):s(j)}function p(j){return j===45?(e.consume(j),i.interrupt?n:C):s(j)}function g(j){const O="CDATA[";return j===O.charCodeAt(c++)?(e.consume(j),c===O.length?i.interrupt?n:U:g):s(j)}function b(j){return ds(j)?(e.consume(j),l=String.fromCharCode(j),v):s(j)}function v(j){if(j===null||j===47||j===62||pn(j)){const O=j===47,H=l.toLowerCase();return!O&&!o&&wm.includes(H)?(r=1,i.interrupt?n(j):U(j)):OS.includes(l.toLowerCase())?(r=6,O?(e.consume(j),x):i.interrupt?n(j):U(j)):(r=7,i.interrupt&&!i.parser.lazy[i.now().line]?s(j):o?y(j):k(j))}return j===45||as(j)?(e.consume(j),l+=String.fromCharCode(j),v):s(j)}function x(j){return j===62?(e.consume(j),i.interrupt?n:U):s(j)}function y(j){return Qt(j)?(e.consume(j),y):E(j)}function k(j){return j===47?(e.consume(j),E):j===58||j===95||ds(j)?(e.consume(j),_):Qt(j)?(e.consume(j),k):E(j)}function _(j){return j===45||j===46||j===58||j===95||as(j)?(e.consume(j),_):S(j)}function S(j){return j===61?(e.consume(j),w):Qt(j)?(e.consume(j),S):k(j)}function w(j){return j===null||j===60||j===61||j===62||j===96?s(j):j===34||j===39?(e.consume(j),u=j,M):Qt(j)?(e.consume(j),w):N(j)}function M(j){return j===u?(e.consume(j),u=null,D):j===null||Nt(j)?s(j):(e.consume(j),M)}function N(j){return j===null||j===34||j===39||j===47||j===60||j===61||j===62||j===96||pn(j)?S(j):(e.consume(j),N)}function D(j){return j===47||j===62||Qt(j)?k(j):s(j)}function E(j){return j===62?(e.consume(j),T):s(j)}function T(j){return j===null||Nt(j)?U(j):Qt(j)?(e.consume(j),T):s(j)}function U(j){return j===45&&r===2?(e.consume(j),z):j===60&&r===1?(e.consume(j),B):j===62&&r===4?(e.consume(j),L):j===63&&r===3?(e.consume(j),C):j===93&&r===5?(e.consume(j),Q):Nt(j)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(BS,P,K)(j)):j===null||Nt(j)?(e.exit("htmlFlowData"),K(j)):(e.consume(j),U)}function K(j){return e.check(HS,$,P)(j)}function $(j){return e.enter("lineEnding"),e.consume(j),e.exit("lineEnding"),R}function R(j){return j===null||Nt(j)?K(j):(e.enter("htmlFlowData"),U(j))}function z(j){return j===45?(e.consume(j),C):U(j)}function B(j){return j===47?(e.consume(j),l="",J):U(j)}function J(j){if(j===62){const O=l.toLowerCase();return wm.includes(O)?(e.consume(j),L):U(j)}return ds(j)&&l.length<8?(e.consume(j),l+=String.fromCharCode(j),J):U(j)}function Q(j){return j===93?(e.consume(j),C):U(j)}function C(j){return j===62?(e.consume(j),L):j===45&&r===2?(e.consume(j),C):U(j)}function L(j){return j===null||Nt(j)?(e.exit("htmlFlowData"),P(j)):(e.consume(j),L)}function P(j){return e.exit("htmlFlow"),n(j)}}function WS(e,n,s){const i=this;return r;function r(l){return Nt(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 KS(e,n,s){return i;function i(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(Pr,n,s)}}const GS={name:"htmlText",tokenize:JS};function JS(e,n,s){const i=this;let r,o,l;return c;function c(C){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(C),u}function u(C){return C===33?(e.consume(C),d):C===47?(e.consume(C),S):C===63?(e.consume(C),k):ds(C)?(e.consume(C),N):s(C)}function d(C){return C===45?(e.consume(C),m):C===91?(e.consume(C),o=0,g):ds(C)?(e.consume(C),y):s(C)}function m(C){return C===45?(e.consume(C),p):s(C)}function h(C){return C===null?s(C):C===45?(e.consume(C),f):Nt(C)?(l=h,B(C)):(e.consume(C),h)}function f(C){return C===45?(e.consume(C),p):h(C)}function p(C){return C===62?z(C):C===45?f(C):h(C)}function g(C){const L="CDATA[";return C===L.charCodeAt(o++)?(e.consume(C),o===L.length?b:g):s(C)}function b(C){return C===null?s(C):C===93?(e.consume(C),v):Nt(C)?(l=b,B(C)):(e.consume(C),b)}function v(C){return C===93?(e.consume(C),x):b(C)}function x(C){return C===62?z(C):C===93?(e.consume(C),x):b(C)}function y(C){return C===null||C===62?z(C):Nt(C)?(l=y,B(C)):(e.consume(C),y)}function k(C){return C===null?s(C):C===63?(e.consume(C),_):Nt(C)?(l=k,B(C)):(e.consume(C),k)}function _(C){return C===62?z(C):k(C)}function S(C){return ds(C)?(e.consume(C),w):s(C)}function w(C){return C===45||as(C)?(e.consume(C),w):M(C)}function M(C){return Nt(C)?(l=M,B(C)):Qt(C)?(e.consume(C),M):z(C)}function N(C){return C===45||as(C)?(e.consume(C),N):C===47||C===62||pn(C)?D(C):s(C)}function D(C){return C===47?(e.consume(C),z):C===58||C===95||ds(C)?(e.consume(C),E):Nt(C)?(l=D,B(C)):Qt(C)?(e.consume(C),D):z(C)}function E(C){return C===45||C===46||C===58||C===95||as(C)?(e.consume(C),E):T(C)}function T(C){return C===61?(e.consume(C),U):Nt(C)?(l=T,B(C)):Qt(C)?(e.consume(C),T):D(C)}function U(C){return C===null||C===60||C===61||C===62||C===96?s(C):C===34||C===39?(e.consume(C),r=C,K):Nt(C)?(l=U,B(C)):Qt(C)?(e.consume(C),U):(e.consume(C),$)}function K(C){return C===r?(e.consume(C),r=void 0,R):C===null?s(C):Nt(C)?(l=K,B(C)):(e.consume(C),K)}function $(C){return C===null||C===34||C===39||C===60||C===61||C===96?s(C):C===47||C===62||pn(C)?D(C):(e.consume(C),$)}function R(C){return C===47||C===62||pn(C)?D(C):s(C)}function z(C){return C===62?(e.consume(C),e.exit("htmlTextData"),e.exit("htmlText"),n):s(C)}function B(C){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),J}function J(C){return Qt(C)?en(e,Q,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(C):Q(C)}function Q(C){return e.enter("htmlTextData"),l(C)}}const Ed={name:"labelEnd",resolveAll:ZS,resolveTo:eC,tokenize:tC},YS={tokenize:nC},QS={tokenize:sC},XS={tokenize:iC};function ZS(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&&Ns(e,0,e.length,s),e}function eC(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=Ts(c,e.slice(o+1,o+i+3)),c=Ts(c,[["enter",m,n]]),c=Ts(c,tl(n.parser.constructs.insideSpan.null,e.slice(o+i+4,l-3),n)),c=Ts(c,[["exit",m,n],e[l-2],e[l-1],["exit",d,n]]),c=Ts(c,e.slice(l+1)),c=Ts(c,[["exit",u,n]]),Ns(e,o,e.length,c),e}function tC(e,n,s){const i=this;let r=i.events.length,o,l;for(;r--;)if((i.events[r][1].type==="labelImage"||i.events[r][1].type==="labelLink")&&!i.events[r][1]._balanced){o=i.events[r][1];break}return c;function c(f){return o?o._inactive?h(f):(l=i.parser.defined.includes(qs(i.sliceSerialize({start:o.end,end:i.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(f),e.exit("labelMarker"),e.exit("labelEnd"),u):s(f)}function u(f){return f===40?e.attempt(YS,m,l?m:h)(f):f===91?e.attempt(QS,m,l?d:h)(f):l?m(f):h(f)}function d(f){return e.attempt(XS,m,h)(f)}function m(f){return n(f)}function h(f){return o._balanced=!0,s(f)}}function nC(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 pn(h)?cr(e,o)(h):o(h)}function o(h){return h===41?m(h):gf(e,l,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function l(h){return pn(h)?cr(e,u)(h):m(h)}function c(h){return s(h)}function u(h){return h===34||h===39||h===40?xf(e,d,s,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):m(h)}function d(h){return pn(h)?cr(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 sC(e,n,s){const i=this;return r;function r(c){return bf.call(i,e,o,l,"reference","referenceMarker","referenceString")(c)}function o(c){return i.parser.defined.includes(qs(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)))?n(c):s(c)}function l(c){return s(c)}}function iC(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 aC={name:"labelStartImage",resolveAll:Ed.resolveAll,tokenize:rC};function rC(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 oC={name:"labelStartLink",resolveAll:Ed.resolveAll,tokenize:lC};function lC(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 zl={name:"lineEnding",tokenize:cC};function cC(e,n){return s;function s(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),en(e,n,"linePrefix")}}const go={name:"thematicBreak",tokenize:dC};function dC(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||Nt(d))?(e.exit("thematicBreak"),n(d)):s(d)}function u(d){return d===r?(e.consume(d),i++,u):(e.exit("thematicBreakSequence"),Qt(d)?en(e,c,"whitespace")(d):c(d))}}const gs={continuation:{tokenize:pC},exit:gC,name:"list",tokenize:hC},uC={partial:!0,tokenize:bC},mC={partial:!0,tokenize:fC};function hC(e,n,s){const i=this,r=i.events[i.events.length-1];let o=r&&r[1].type==="linePrefix"?r[2].sliceSerialize(r[1],!0).length:0,l=0;return c;function c(p){const g=i.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(g==="listUnordered"?!i.containerState.marker||p===i.containerState.marker:Hc(p)){if(i.containerState.type||(i.containerState.type=g,e.enter(g,{_container:!0})),g==="listUnordered")return e.enter("listItemPrefix"),p===42||p===45?e.check(go,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 Hc(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(Pr,i.interrupt?s:m,e.attempt(uC,f,h))}function m(p){return i.containerState.initialBlankLine=!0,o++,f(p)}function h(p){return Qt(p)?(e.enter("listItemPrefixWhitespace"),e.consume(p),e.exit("listItemPrefixWhitespace"),f):s(p)}function f(p){return i.containerState.size=o+i.sliceSerialize(e.exit("listItemPrefix"),!0).length,n(p)}}function pC(e,n,s){const i=this;return i.containerState._closeFlow=void 0,e.check(Pr,r,o);function r(c){return i.containerState.furtherBlankLines=i.containerState.furtherBlankLines||i.containerState.initialBlankLine,en(e,n,"listItemIndent",i.containerState.size+1)(c)}function o(c){return i.containerState.furtherBlankLines||!Qt(c)?(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,l(c)):(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,e.attempt(mC,n,l)(c))}function l(c){return i.containerState._closeFlow=!0,i.interrupt=void 0,en(e,e.attempt(gs,n,s),"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function fC(e,n,s){const i=this;return en(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 gC(e){e.exit(this.containerState.type)}function bC(e,n,s){const i=this;return en(e,r,"listItemPrefixWhitespace",i.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function r(o){const l=i.events[i.events.length-1];return!Qt(o)&&l&&l[1].type==="listItemPrefixWhitespace"?n(o):s(o)}}const Nm={name:"setextUnderline",resolveTo:xC,tokenize:vC};function xC(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 vC(e,n,s){const i=this;let r;return o;function o(d){let m=i.events.length,h;for(;m--;)if(i.events[m][1].type!=="lineEnding"&&i.events[m][1].type!=="linePrefix"&&i.events[m][1].type!=="content"){h=i.events[m][1].type==="paragraph";break}return!i.parser.lazy[i.now().line]&&(i.interrupt||h)?(e.enter("setextHeadingLine"),r=d,l(d)):s(d)}function l(d){return e.enter("setextHeadingLineSequence"),c(d)}function c(d){return d===r?(e.consume(d),c):(e.exit("setextHeadingLineSequence"),Qt(d)?en(e,u,"lineSuffix")(d):u(d))}function u(d){return d===null||Nt(d)?(e.exit("setextHeadingLine"),n(d)):s(d)}}const yC={tokenize:jC};function jC(e){const n=this,s=e.attempt(Pr,i,e.attempt(this.parser.constructs.flowInitial,r,en(e,e.attempt(this.parser.constructs.flow,r,e.attempt(CS,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 kC={resolveAll:yf()},wC=vf("string"),NC=vf("text");function vf(e){return{resolveAll:yf(e==="text"?SC:void 0),tokenize:n};function n(s){const i=this,r=this.parser.constructs[e],o=s.attempt(r,l,c);return l;function l(m){return d(m)?o(m):c(m)}function c(m){if(m===null){s.consume(m);return}return s.enter("data"),s.consume(m),u}function u(m){return d(m)?(s.exit("data"),o(m)):(s.consume(m),u)}function d(m){if(m===null)return!0;const h=r[m];let f=-1;if(h)for(;++f<h.length;){const p=h[f];if(!p.previous||p.previous.call(i,i.previous))return!0}return!1}}}function yf(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 SC(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 CC={42:gs,43:gs,45:gs,48:gs,49:gs,50:gs,51:gs,52:gs,53:gs,54:gs,55:gs,56:gs,57:gs,62:mf},EC={91:RS},_C={[-2]:Ll,[-1]:Ll,32:Ll},MC={35:LS,42:go,45:[Nm,go],60:US,61:Nm,95:go,96:km,126:km},AC={38:pf,92:hf},RC={[-5]:zl,[-4]:zl,[-3]:zl,33:aC,38:pf,42:qc,60:[oS,GS],91:oC,92:[$S,hf],93:Ed,95:qc,96:yS},TC={null:[qc,kC]},PC={null:[42,95]},IC={null:[]},$C=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:PC,contentInitial:EC,disable:IC,document:CC,flow:MC,flowInitial:_C,insideSpan:TC,string:AC,text:RC},Symbol.toStringTag,{value:"Module"}));function DC(e,n,s){let i={_bufferIndex:-1,_index:0,line:s&&s.line||1,column:s&&s.column||1,offset:s&&s.offset||0};const r={},o=[];let l=[],c=[];const u={attempt:M(S),check:M(w),consume:y,enter:k,exit:_,interrupt:M(w,{interrupt:!0})},d={code:null,containerState:{},defineSkip:b,events:[],now:g,parser:e,previous:null,sliceSerialize:f,sliceStream:p,write:h};let m=n.tokenize.call(d,u);return n.resolveAll&&o.push(n),d;function h(T){return l=Ts(l,T),v(),l[l.length-1]!==null?[]:(N(n,0),d.events=tl(o,d.events,d),d.events)}function f(T,U){return zC(p(T),U)}function p(T){return LC(l,T)}function g(){const{_bufferIndex:T,_index:U,line:K,column:$,offset:R}=i;return{_bufferIndex:T,_index:U,line:K,column:$,offset:R}}function b(T){r[T.line]=T.column,E()}function v(){let T;for(;i._index<l.length;){const U=l[i._index];if(typeof U=="string")for(T=i._index,i._bufferIndex<0&&(i._bufferIndex=0);i._index===T&&i._bufferIndex<U.length;)x(U.charCodeAt(i._bufferIndex));else x(U)}}function x(T){m=m(T)}function y(T){Nt(T)?(i.line++,i.column=1,i.offset+=T===-3?2:1,E()):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=T}function k(T,U){const K=U||{};return K.type=T,K.start=g(),d.events.push(["enter",K,d]),c.push(K),K}function _(T){const U=c.pop();return U.end=g(),d.events.push(["exit",U,d]),U}function S(T,U){N(T,U.from)}function w(T,U){U.restore()}function M(T,U){return K;function K($,R,z){let B,J,Q,C;return Array.isArray($)?P($):"tokenize"in $?P([$]):L($);function L(ge){return be;function be(se){const me=se!==null&&ge[se],F=se!==null&&ge.null,de=[...Array.isArray(me)?me:me?[me]:[],...Array.isArray(F)?F:F?[F]:[]];return P(de)(se)}}function P(ge){return B=ge,J=0,ge.length===0?z:j(ge[J])}function j(ge){return be;function be(se){return C=D(),Q=ge,ge.partial||(d.currentConstruct=ge),ge.name&&d.parser.constructs.disable.null.includes(ge.name)?H():ge.tokenize.call(U?Object.assign(Object.create(d),U):d,u,O,H)(se)}}function O(ge){return T(Q,C),R}function H(ge){return C.restore(),++J<B.length?j(B[J]):z}}}function N(T,U){T.resolveAll&&!o.includes(T)&&o.push(T),T.resolve&&Ns(d.events,U,d.events.length-U,T.resolve(d.events.slice(U),d)),T.resolveTo&&(d.events=T.resolveTo(d.events,d))}function D(){const T=g(),U=d.previous,K=d.currentConstruct,$=d.events.length,R=Array.from(c);return{from:$,restore:z};function z(){i=T,d.previous=U,d.currentConstruct=K,d.events.length=$,c=R,E()}}function E(){i.line in r&&i.column<2&&(i.column=r[i.line],i.offset+=r[i.line]-1)}}function LC(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 zC(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=`
|
|
620
|
-
`;break}case-3:{l=`\r
|
|
621
|
-
`;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 FC(e){const i={constructs:df([$C,...(e||{}).extensions||[]]),content:r(eS),defined:[],document:r(nS),flow:r(yC),lazy:{},string:r(wC),text:r(NC)};return i;function r(o){return l;function l(c){return DC(i,o,c)}}}function OC(e){for(;!ff(e););return e}const Sm=/[\0\t\n\r]/g;function UC(){let e=1,n="",s=!0,i;return r;function r(o,l,c){const u=[];let d,m,h,f,p;for(o=n+(typeof o=="string"?o.toString():new TextDecoder(l||void 0).decode(o)),h=0,n="",s&&(o.charCodeAt(0)===65279&&h++,s=void 0);h<o.length;){if(Sm.lastIndex=h,d=Sm.exec(o),f=d&&d.index!==void 0?d.index:o.length,p=o.charCodeAt(f),!d){n=o.slice(h);break}if(p===10&&h===f&&i)u.push(-3),i=void 0;else switch(i&&(u.push(-5),i=void 0),h<f&&(u.push(o.slice(h,f)),e+=f-h),p){case 0:{u.push(65533),e++;break}case 9:{for(m=Math.ceil(e/4)*4,u.push(-2);e++<m;)u.push(-1);break}case 10:{u.push(-4),e=1;break}default:i=!0,e=1}h=f+1}return c&&(i&&u.push(-5),n&&u.push(n),u.push(null)),u}}const BC=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function HC(e){return e.replace(BC,qC)}function qC(e,n,s){if(n)return n;if(s.charCodeAt(0)===35){const r=s.charCodeAt(1),o=r===120||r===88;return uf(s.slice(o?2:1),o?16:10)}return Cd(s)||e}const jf={}.hasOwnProperty;function VC(e,n,s){return n&&typeof n=="object"&&(s=n,n=void 0),WC(s)(OC(FC(s).document().write(UC()(e,n,!0))))}function WC(e){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(Oe),autolinkProtocol:D,autolinkEmail:D,atxHeading:o(he),blockQuote:o(F),characterEscape:D,characterReference:D,codeFenced:o(de),codeFencedFenceInfo:l,codeFencedFenceMeta:l,codeIndented:o(de,l),codeText:o(ne,l),codeTextData:D,data:D,codeFlowValue:D,definition:o(xe),definitionDestinationString:l,definitionLabelString:l,definitionTitleString:l,emphasis:o(oe),hardBreakEscape:o(ae),hardBreakTrailing:o(ae),htmlFlow:o(je,l),htmlFlowData:D,htmlText:o(je,l),htmlTextData:D,image:o(Ae),label:l,link:o(Oe),listItem:o(Xe),listItemValue:f,listOrdered:o(Qe,h),listUnordered:o(Qe),paragraph:o(Ye),reference:j,referenceString:l,resourceDestinationString:l,resourceTitleString:l,setextHeading:o(he),strong:o(it),thematicBreak:o(Ge)},exit:{atxHeading:u(),atxHeadingSequence:S,autolink:u(),autolinkEmail:me,autolinkProtocol:se,blockQuote:u(),characterEscapeValue:E,characterReferenceMarkerHexadecimal:H,characterReferenceMarkerNumeric:H,characterReferenceValue:ge,characterReference:be,codeFenced:u(v),codeFencedFence:b,codeFencedFenceInfo:p,codeFencedFenceMeta:g,codeFlowValue:E,codeIndented:u(x),codeText:u(R),codeTextData:E,data:E,definition:u(),definitionDestinationString:_,definitionLabelString:y,definitionTitleString:k,emphasis:u(),hardBreakEscape:u(U),hardBreakTrailing:u(U),htmlFlow:u(K),htmlFlowData:E,htmlText:u($),htmlTextData:E,image:u(B),label:Q,labelText:J,lineEnding:T,link:u(z),listItem:u(),listOrdered:u(),listUnordered:u(),paragraph:u(),referenceString:O,resourceDestinationString:C,resourceTitleString:L,resource:P,setextHeading:u(N),setextHeadingLineSequence:M,setextHeadingText:w,strong:u(),thematicBreak:u()}};kf(n,(e||{}).mdastExtensions||[]);const s={};return i;function i(re){let ke={type:"root",children:[]};const X={stack:[ke],tokenStack:[],config:n,enter:c,exit:d,buffer:l,resume:m,data:s},Te=[];let Le=-1;for(;++Le<re.length;)if(re[Le][1].type==="listOrdered"||re[Le][1].type==="listUnordered")if(re[Le][0]==="enter")Te.push(Le);else{const fe=Te.pop();Le=r(re,fe,Le)}for(Le=-1;++Le<re.length;){const fe=n[re[Le][0]];jf.call(fe,re[Le][1].type)&&fe[re[Le][1].type].call(Object.assign({sliceSerialize:re[Le][2].sliceSerialize},X),re[Le][1])}if(X.tokenStack.length>0){const fe=X.tokenStack[X.tokenStack.length-1];(fe[1]||Cm).call(X,void 0,fe[0])}for(ke.position={start:yi(re.length>0?re[0][1].start:{line:1,column:1,offset:0}),end:yi(re.length>0?re[re.length-2][1].end:{line:1,column:1,offset:0})},Le=-1;++Le<n.transforms.length;)ke=n.transforms[Le](ke)||ke;return ke}function r(re,ke,X){let Te=ke-1,Le=-1,fe=!1,_e,Ue,nt,ve;for(;++Te<=X;){const ce=re[Te];switch(ce[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{ce[0]==="enter"?Le++:Le--,ve=void 0;break}case"lineEndingBlank":{ce[0]==="enter"&&(_e&&!ve&&!Le&&!nt&&(nt=Te),ve=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:ve=void 0}if(!Le&&ce[0]==="enter"&&ce[1].type==="listItemPrefix"||Le===-1&&ce[0]==="exit"&&(ce[1].type==="listUnordered"||ce[1].type==="listOrdered")){if(_e){let De=Te;for(Ue=void 0;De--;){const ue=re[De];if(ue[1].type==="lineEnding"||ue[1].type==="lineEndingBlank"){if(ue[0]==="exit")continue;Ue&&(re[Ue][1].type="lineEndingBlank",fe=!0),ue[1].type="lineEnding",Ue=De}else if(!(ue[1].type==="linePrefix"||ue[1].type==="blockQuotePrefix"||ue[1].type==="blockQuotePrefixWhitespace"||ue[1].type==="blockQuoteMarker"||ue[1].type==="listItemIndent"))break}nt&&(!Ue||nt<Ue)&&(_e._spread=!0),_e.end=Object.assign({},Ue?re[Ue][1].start:ce[1].end),re.splice(Ue||Te,0,["exit",_e,ce[2]]),Te++,X++}if(ce[1].type==="listItemPrefix"){const De={type:"listItem",_spread:!1,start:Object.assign({},ce[1].start),end:void 0};_e=De,re.splice(Te,0,["enter",De,ce[2]]),Te++,X++,nt=void 0,ve=!0}}}return re[ke][1]._spread=fe,X}function o(re,ke){return X;function X(Te){c.call(this,re(Te),Te),ke&&ke.call(this,Te)}}function l(){this.stack.push({type:"fragment",children:[]})}function c(re,ke,X){this.stack[this.stack.length-1].children.push(re),this.stack.push(re),this.tokenStack.push([ke,X||void 0]),re.position={start:yi(ke.start),end:void 0}}function u(re){return ke;function ke(X){re&&re.call(this,X),d.call(this,X)}}function d(re,ke){const X=this.stack.pop(),Te=this.tokenStack.pop();if(Te)Te[0].type!==re.type&&(ke?ke.call(this,re,Te[0]):(Te[1]||Cm).call(this,re,Te[0]));else throw new Error("Cannot close `"+re.type+"` ("+lr({start:re.start,end:re.end})+"): it’s not open");X.position.end=yi(re.end)}function m(){return Sd(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function f(re){if(this.data.expectingFirstListItemValue){const ke=this.stack[this.stack.length-2];ke.start=Number.parseInt(this.sliceSerialize(re),10),this.data.expectingFirstListItemValue=void 0}}function p(){const re=this.resume(),ke=this.stack[this.stack.length-1];ke.lang=re}function g(){const re=this.resume(),ke=this.stack[this.stack.length-1];ke.meta=re}function b(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function v(){const re=this.resume(),ke=this.stack[this.stack.length-1];ke.value=re.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function x(){const re=this.resume(),ke=this.stack[this.stack.length-1];ke.value=re.replace(/(\r?\n|\r)$/g,"")}function y(re){const ke=this.resume(),X=this.stack[this.stack.length-1];X.label=ke,X.identifier=qs(this.sliceSerialize(re)).toLowerCase()}function k(){const re=this.resume(),ke=this.stack[this.stack.length-1];ke.title=re}function _(){const re=this.resume(),ke=this.stack[this.stack.length-1];ke.url=re}function S(re){const ke=this.stack[this.stack.length-1];if(!ke.depth){const X=this.sliceSerialize(re).length;ke.depth=X}}function w(){this.data.setextHeadingSlurpLineEnding=!0}function M(re){const ke=this.stack[this.stack.length-1];ke.depth=this.sliceSerialize(re).codePointAt(0)===61?1:2}function N(){this.data.setextHeadingSlurpLineEnding=void 0}function D(re){const X=this.stack[this.stack.length-1].children;let Te=X[X.length-1];(!Te||Te.type!=="text")&&(Te=Be(),Te.position={start:yi(re.start),end:void 0},X.push(Te)),this.stack.push(Te)}function E(re){const ke=this.stack.pop();ke.value+=this.sliceSerialize(re),ke.position.end=yi(re.end)}function T(re){const ke=this.stack[this.stack.length-1];if(this.data.atHardBreak){const X=ke.children[ke.children.length-1];X.position.end=yi(re.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(ke.type)&&(D.call(this,re),E.call(this,re))}function U(){this.data.atHardBreak=!0}function K(){const re=this.resume(),ke=this.stack[this.stack.length-1];ke.value=re}function $(){const re=this.resume(),ke=this.stack[this.stack.length-1];ke.value=re}function R(){const re=this.resume(),ke=this.stack[this.stack.length-1];ke.value=re}function z(){const re=this.stack[this.stack.length-1];if(this.data.inReference){const ke=this.data.referenceType||"shortcut";re.type+="Reference",re.referenceType=ke,delete re.url,delete re.title}else delete re.identifier,delete re.label;this.data.referenceType=void 0}function B(){const re=this.stack[this.stack.length-1];if(this.data.inReference){const ke=this.data.referenceType||"shortcut";re.type+="Reference",re.referenceType=ke,delete re.url,delete re.title}else delete re.identifier,delete re.label;this.data.referenceType=void 0}function J(re){const ke=this.sliceSerialize(re),X=this.stack[this.stack.length-2];X.label=HC(ke),X.identifier=qs(ke).toLowerCase()}function Q(){const re=this.stack[this.stack.length-1],ke=this.resume(),X=this.stack[this.stack.length-1];if(this.data.inReference=!0,X.type==="link"){const Te=re.children;X.children=Te}else X.alt=ke}function C(){const re=this.resume(),ke=this.stack[this.stack.length-1];ke.url=re}function L(){const re=this.resume(),ke=this.stack[this.stack.length-1];ke.title=re}function P(){this.data.inReference=void 0}function j(){this.data.referenceType="collapsed"}function O(re){const ke=this.resume(),X=this.stack[this.stack.length-1];X.label=ke,X.identifier=qs(this.sliceSerialize(re)).toLowerCase(),this.data.referenceType="full"}function H(re){this.data.characterReferenceType=re.type}function ge(re){const ke=this.sliceSerialize(re),X=this.data.characterReferenceType;let Te;X?(Te=uf(ke,X==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Te=Cd(ke);const Le=this.stack[this.stack.length-1];Le.value+=Te}function be(re){const ke=this.stack.pop();ke.position.end=yi(re.end)}function se(re){E.call(this,re);const ke=this.stack[this.stack.length-1];ke.url=this.sliceSerialize(re)}function me(re){E.call(this,re);const ke=this.stack[this.stack.length-1];ke.url="mailto:"+this.sliceSerialize(re)}function F(){return{type:"blockquote",children:[]}}function de(){return{type:"code",lang:null,meta:null,value:""}}function ne(){return{type:"inlineCode",value:""}}function xe(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function oe(){return{type:"emphasis",children:[]}}function he(){return{type:"heading",depth:0,children:[]}}function ae(){return{type:"break"}}function je(){return{type:"html",value:""}}function Ae(){return{type:"image",title:null,url:"",alt:null}}function Oe(){return{type:"link",title:null,url:"",children:[]}}function Qe(re){return{type:"list",ordered:re.type==="listOrdered",start:null,spread:re._spread,children:[]}}function Xe(re){return{type:"listItem",spread:re._spread,checked:null,children:[]}}function Ye(){return{type:"paragraph",children:[]}}function it(){return{type:"strong",children:[]}}function Be(){return{type:"text",value:""}}function Ge(){return{type:"thematicBreak"}}}function yi(e){return{line:e.line,column:e.column,offset:e.offset}}function kf(e,n){let s=-1;for(;++s<n.length;){const i=n[s];Array.isArray(i)?kf(e,i):KC(e,i)}}function KC(e,n){let s;for(s in n)if(jf.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 Cm(e,n){throw e?new Error("Cannot close `"+e.type+"` ("+lr({start:e.start,end:e.end})+"): a different token (`"+n.type+"`, "+lr({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+lr({start:n.start,end:n.end})+") is still open")}function GC(e){const n=this;n.parser=s;function s(i){return VC(i,{...n.data("settings"),...e,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function JC(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 YC(e,n){const s={type:"element",tagName:"br",properties:{},children:[]};return e.patch(n,s),[e.applyData(n,s),{type:"text",value:`
|
|
622
|
-
`}]}function QC(e,n){const s=n.value?n.value+`
|
|
623
|
-
`:"",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 XC(e,n){const s={type:"element",tagName:"del",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function ZC(e,n){const s={type:"element",tagName:"em",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function e2(e,n){const s=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=String(n.identifier).toUpperCase(),r=Ra(i.toLowerCase()),o=e.footnoteOrder.indexOf(i);let l,c=e.footnoteCounts.get(i);c===void 0?(c=0,e.footnoteOrder.push(i),l=e.footnoteOrder.length):l=o+1,c+=1,e.footnoteCounts.set(i,c);const u={type:"element",tagName:"a",properties:{href:"#"+s+"fn-"+r,id:s+"fnref-"+r+(c>1?"-"+c:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(l)}]};e.patch(n,u);const d={type:"element",tagName:"sup",properties:{},children:[u]};return e.patch(n,d),e.applyData(n,d)}function t2(e,n){const s={type:"element",tagName:"h"+n.depth,properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function n2(e,n){if(e.options.allowDangerousHtml){const s={type:"raw",value:n.value};return e.patch(n,s),e.applyData(n,s)}}function wf(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 s2(e,n){const s=String(n.identifier).toUpperCase(),i=e.definitionById.get(s);if(!i)return wf(e,n);const r={src:Ra(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 i2(e,n){const s={src:Ra(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 a2(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 r2(e,n){const s=String(n.identifier).toUpperCase(),i=e.definitionById.get(s);if(!i)return wf(e,n);const r={href:Ra(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 o2(e,n){const s={href:Ra(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 l2(e,n,s){const i=e.all(n),r=s?c2(s):Nf(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:`
|
|
624
|
-
`}),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:`
|
|
625
|
-
`});const d={type:"element",tagName:"li",properties:o,children:l};return e.patch(n,d),e.applyData(n,d)}function c2(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=Nf(s[i])}return n}function Nf(e){const n=e.spread;return n??e.children.length>1}function d2(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 u2(e,n){const s={type:"element",tagName:"p",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function m2(e,n){const s={type:"root",children:e.wrap(e.all(n))};return e.patch(n,s),e.applyData(n,s)}function h2(e,n){const s={type:"element",tagName:"strong",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function p2(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=jd(n.children[1]),u=nf(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 f2(e,n,s){const i=s?s.children:void 0,o=(i?i.indexOf(n):1)===0?"th":"td",l=s&&s.type==="table"?s.align:void 0,c=l?l.length:n.children.length;let u=-1;const d=[];for(;++u<c;){const h=n.children[u],f={},p=l?l[u]:void 0;p&&(f.align=p);let g={type:"element",tagName:o,properties:f,children:[]};h&&(g.children=e.all(h),e.patch(h,g),g=e.applyData(h,g)),d.push(g)}const m={type:"element",tagName:"tr",properties:{},children:e.wrap(d,!0)};return e.patch(n,m),e.applyData(n,m)}function g2(e,n){const s={type:"element",tagName:"td",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}const Em=9,_m=32;function b2(e){const n=String(e),s=/\r?\n|\r/g;let i=s.exec(n),r=0;const o=[];for(;i;)o.push(Mm(n.slice(r,i.index),r>0,!0),i[0]),r=i.index+i[0].length,i=s.exec(n);return o.push(Mm(n.slice(r),r>0,!1)),o.join("")}function Mm(e,n,s){let i=0,r=e.length;if(n){let o=e.codePointAt(i);for(;o===Em||o===_m;)i++,o=e.codePointAt(i)}if(s){let o=e.codePointAt(r-1);for(;o===Em||o===_m;)r--,o=e.codePointAt(r-1)}return r>i?e.slice(i,r):""}function x2(e,n){const s={type:"text",value:b2(String(n.value))};return e.patch(n,s),e.applyData(n,s)}function v2(e,n){const s={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(n,s),e.applyData(n,s)}const y2={blockquote:JC,break:YC,code:QC,delete:XC,emphasis:ZC,footnoteReference:e2,heading:t2,html:n2,imageReference:s2,image:i2,inlineCode:a2,linkReference:r2,link:o2,listItem:l2,list:d2,paragraph:u2,root:m2,strong:h2,table:p2,tableCell:g2,tableRow:f2,text:x2,thematicBreak:v2,toml:eo,yaml:eo,definition:eo,footnoteDefinition:eo};function eo(){}const Sf=-1,nl=0,dr=1,Ro=2,_d=3,Md=4,Ad=5,Rd=6,Cf=7,Ef=8,Am=typeof self=="object"?self:globalThis,j2=(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 nl:case Sf:return s(l,r);case dr:{const c=s([],r);for(const u of l)c.push(i(u));return c}case Ro:{const c=s({},r);for(const[u,d]of l)c[i(u)]=i(d);return c}case _d:return s(new Date(l),r);case Md:{const{source:c,flags:u}=l;return s(new RegExp(c,u),r)}case Ad:{const c=s(new Map,r);for(const[u,d]of l)c.set(i(u),i(d));return c}case Rd:{const c=s(new Set,r);for(const u of l)c.add(i(u));return c}case Cf:{const{name:c,message:u}=l;return s(new Am[c](u),r)}case Ef: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 Am[o](l),r)};return i},Rm=e=>j2(new Map,e)(0),ra="",{toString:k2}={},{keys:w2}=Object,Va=e=>{const n=typeof e;if(n!=="object"||!e)return[nl,n];const s=k2.call(e).slice(8,-1);switch(s){case"Array":return[dr,ra];case"Object":return[Ro,ra];case"Date":return[_d,ra];case"RegExp":return[Md,ra];case"Map":return[Ad,ra];case"Set":return[Rd,ra];case"DataView":return[dr,s]}return s.includes("Array")?[dr,s]:s.includes("Error")?[Cf,s]:[Ro,s]},to=([e,n])=>e===nl&&(n==="function"||n==="symbol"),N2=(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]=Va(l);switch(c){case nl:{let m=l;switch(u){case"bigint":c=Ef,m=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+u);m=null;break;case"undefined":return r([Sf],l)}return r([c,m],l)}case dr:{if(u){let f=l;return u==="DataView"?f=new Uint8Array(l.buffer):u==="ArrayBuffer"&&(f=new Uint8Array(l)),r([u,[...f]],l)}const m=[],h=r([c,m],l);for(const f of l)m.push(o(f));return h}case Ro:{if(u)switch(u){case"BigInt":return r([u,l.toString()],l);case"Boolean":case"Number":case"String":return r([u,l.valueOf()],l)}if(n&&"toJSON"in l)return o(l.toJSON());const m=[],h=r([c,m],l);for(const f of w2(l))(e||!to(Va(l[f])))&&m.push([o(f),o(l[f])]);return h}case _d:return r([c,l.toISOString()],l);case Md:{const{source:m,flags:h}=l;return r([c,{source:m,flags:h}],l)}case Ad:{const m=[],h=r([c,m],l);for(const[f,p]of l)(e||!(to(Va(f))||to(Va(p))))&&m.push([o(f),o(p)]);return h}case Rd:{const m=[],h=r([c,m],l);for(const f of l)(e||!to(Va(f)))&&m.push(o(f));return h}}const{message:d}=l;return r([c,{name:u,message:d}],l)};return o},Tm=(e,{json:n,lossy:s}={})=>{const i=[];return N2(!(n||s),!!n,new Map,i)(e),i},To=typeof structuredClone=="function"?(e,n)=>n&&("json"in n||"lossy"in n)?Rm(Tm(e,n)):structuredClone(e):(e,n)=>Rm(Tm(e,n));function S2(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 C2(e,n){return"Back to reference "+(e+1)+(n>1?"-"+n:"")}function E2(e){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=e.options.footnoteBackContent||S2,i=e.options.footnoteBackLabel||C2,r=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",l=e.options.footnoteLabelProperties||{className:["sr-only"]},c=[];let u=-1;for(;++u<e.footnoteOrder.length;){const d=e.footnoteById.get(e.footnoteOrder[u]);if(!d)continue;const m=e.all(d),h=String(d.identifier).toUpperCase(),f=Ra(h.toLowerCase());let p=0;const g=[],b=e.footnoteCounts.get(h);for(;b!==void 0&&++p<=b;){g.length>0&&g.push({type:"text",value:" "});let y=typeof s=="string"?s:s(u,p);typeof y=="string"&&(y={type:"text",value:y}),g.push({type:"element",tagName:"a",properties:{href:"#"+n+"fnref-"+f+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof i=="string"?i:i(u,p),className:["data-footnote-backref"]},children:Array.isArray(y)?y:[y]})}const v=m[m.length-1];if(v&&v.type==="element"&&v.tagName==="p"){const y=v.children[v.children.length-1];y&&y.type==="text"?y.value+=" ":v.children.push({type:"text",value:" "}),v.children.push(...g)}else m.push(...g);const x={type:"element",tagName:"li",properties:{id:n+"fn-"+f},children:e.wrap(m,!0)};e.patch(d,x),c.push(x)}if(c.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...To(l),id:"footnote-label"},children:[{type:"text",value:r}]},{type:"text",value:`
|
|
626
|
-
`},{type:"element",tagName:"ol",properties:{},children:e.wrap(c,!0)},{type:"text",value:`
|
|
627
|
-
`}]}}const sl=(function(e){if(e==null)return R2;if(typeof e=="function")return il(e);if(typeof e=="object")return Array.isArray(e)?_2(e):M2(e);if(typeof e=="string")return A2(e);throw new Error("Expected function, string, or object as test")});function _2(e){const n=[];let s=-1;for(;++s<e.length;)n[s]=sl(e[s]);return il(i);function i(...r){let o=-1;for(;++o<n.length;)if(n[o].apply(this,r))return!0;return!1}}function M2(e){const n=e;return il(s);function s(i){const r=i;let o;for(o in e)if(r[o]!==n[o])return!1;return!0}}function A2(e){return il(n);function n(s){return s&&s.type===e}}function il(e){return n;function n(s,i,r){return!!(T2(s)&&e.call(this,s,typeof i=="number"?i:void 0,r||void 0))}}function R2(){return!0}function T2(e){return e!==null&&typeof e=="object"&&"type"in e}const _f=[],P2=!0,Vc=!1,I2="skip";function Mf(e,n,s,i){let r;typeof n=="function"&&typeof s!="function"?(i=s,s=n):r=n;const o=sl(r),l=i?-1:1;c(e,void 0,[])();function c(u,d,m){const h=u&&typeof u=="object"?u:{};if(typeof h.type=="string"){const p=typeof h.tagName=="string"?h.tagName:typeof h.name=="string"?h.name:void 0;Object.defineProperty(f,"name",{value:"node ("+(u.type+(p?"<"+p+">":""))+")"})}return f;function f(){let p=_f,g,b,v;if((!n||o(u,d,m[m.length-1]||void 0))&&(p=$2(s(u,m)),p[0]===Vc))return p;if("children"in u&&u.children){const x=u;if(x.children&&p[0]!==I2)for(b=(i?x.children.length:-1)+l,v=m.concat(x);b>-1&&b<x.children.length;){const y=x.children[b];if(g=c(y,b,v)(),g[0]===Vc)return g;b=typeof g[1]=="number"?g[1]:b+l}}return p}}}function $2(e){return Array.isArray(e)?e:typeof e=="number"?[P2,e]:e==null?_f:[e]}function Td(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),Mf(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 Wc={}.hasOwnProperty,D2={};function L2(e,n){const s=n||D2,i=new Map,r=new Map,o=new Map,l={...y2,...s.handlers},c={all:d,applyData:F2,definitionById:i,footnoteById:r,footnoteCounts:o,footnoteOrder:[],handlers:l,one:u,options:s,patch:z2,wrap:U2};return Td(e,function(m){if(m.type==="definition"||m.type==="footnoteDefinition"){const h=m.type==="definition"?i:r,f=String(m.identifier).toUpperCase();h.has(f)||h.set(f,m)}}),c;function u(m,h){const f=m.type,p=c.handlers[f];if(Wc.call(c.handlers,f)&&p)return p(c,m,h);if(c.options.passThrough&&c.options.passThrough.includes(f)){if("children"in m){const{children:b,...v}=m,x=To(v);return x.children=c.all(m),x}return To(m)}return(c.options.unknownHandler||O2)(c,m,h)}function d(m){const h=[];if("children"in m){const f=m.children;let p=-1;for(;++p<f.length;){const g=c.one(f[p],m);if(g){if(p&&f[p-1].type==="break"&&(!Array.isArray(g)&&g.type==="text"&&(g.value=Pm(g.value)),!Array.isArray(g)&&g.type==="element")){const b=g.children[0];b&&b.type==="text"&&(b.value=Pm(b.value))}Array.isArray(g)?h.push(...g):h.push(g)}}}return h}}function z2(e,n){e.position&&(n.position=C0(e))}function F2(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,To(o)),"children"in s&&s.children&&r!==null&&r!==void 0&&(s.children=r)}return s}function O2(e,n){const s=n.data||{},i="value"in n&&!(Wc.call(s,"hProperties")||Wc.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 U2(e,n){const s=[];let i=-1;for(n&&s.push({type:"text",value:`
|
|
628
|
-
`});++i<e.length;)i&&s.push({type:"text",value:`
|
|
629
|
-
`}),s.push(e[i]);return n&&e.length>0&&s.push({type:"text",value:`
|
|
630
|
-
`}),s}function Pm(e){let n=0,s=e.charCodeAt(n);for(;s===9||s===32;)n++,s=e.charCodeAt(n);return e.slice(n)}function Im(e,n){const s=L2(e,n),i=s.one(e,void 0),r=E2(s),o=Array.isArray(i)?{type:"root",children:i}:i||{type:"root",children:[]};return r&&o.children.push({type:"text",value:`
|
|
631
|
-
`},r),o}function B2(e,n){return e&&"run"in e?async function(s,i){const r=Im(s,{file:i,...n});await e.run(r,i)}:function(s,i){return Im(s,{file:i,...e||n})}}function $m(e){if(e)throw e}var Fl,Dm;function H2(){if(Dm)return Fl;Dm=1;var e=Object.prototype.hasOwnProperty,n=Object.prototype.toString,s=Object.defineProperty,i=Object.getOwnPropertyDescriptor,r=function(d){return typeof Array.isArray=="function"?Array.isArray(d):n.call(d)==="[object Array]"},o=function(d){if(!d||n.call(d)!=="[object Object]")return!1;var m=e.call(d,"constructor"),h=d.constructor&&d.constructor.prototype&&e.call(d.constructor.prototype,"isPrototypeOf");if(d.constructor&&!m&&!h)return!1;var f;for(f in d);return typeof f>"u"||e.call(d,f)},l=function(d,m){s&&m.name==="__proto__"?s(d,m.name,{enumerable:!0,configurable:!0,value:m.newValue,writable:!0}):d[m.name]=m.newValue},c=function(d,m){if(m==="__proto__")if(e.call(d,m)){if(i)return i(d,m).value}else return;return d[m]};return Fl=function u(){var d,m,h,f,p,g,b=arguments[0],v=1,x=arguments.length,y=!1;for(typeof b=="boolean"&&(y=b,b=arguments[1]||{},v=2),(b==null||typeof b!="object"&&typeof b!="function")&&(b={});v<x;++v)if(d=arguments[v],d!=null)for(m in d)h=c(b,m),f=c(d,m),b!==f&&(y&&f&&(o(f)||(p=r(f)))?(p?(p=!1,g=h&&r(h)?h:[]):g=h&&o(h)?h:{},l(b,{name:m,newValue:u(y,g,f)})):typeof f<"u"&&l(b,{name:m,newValue:f}));return b},Fl}var q2=H2();const Ol=Kh(q2);function Kc(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 V2(){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?W2(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 W2(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 ei={basename:K2,dirname:G2,extname:J2,join:Y2,sep:"/"};function K2(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 G2(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 J2(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 Y2(...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?".":Q2(s)}function Q2(e){Ir(e);const n=e.codePointAt(0)===47;let s=X2(e,!n);return s.length===0&&!n&&(s="."),s.length>0&&e.codePointAt(e.length-1)===47&&(s+="/"),n?"/"+s:s}function X2(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 Z2={cwd:eE};function eE(){return"/"}function Gc(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function tE(e){if(typeof e=="string")e=new URL(e);else if(!Gc(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 nE(e)}function nE(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 Ul=["history","path","basename","stem","extname","dirname"];class Af{constructor(n){let s;n?Gc(n)?s={path:n}:typeof n=="string"||sE(n)?s={value:n}:s=n:s={},this.cwd="cwd"in s?"":Z2.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let i=-1;for(;++i<Ul.length;){const o=Ul[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)Ul.includes(r)||(this[r]=s[r])}get basename(){return typeof this.path=="string"?ei.basename(this.path):void 0}set basename(n){Hl(n,"basename"),Bl(n,"basename"),this.path=ei.join(this.dirname||"",n)}get dirname(){return typeof this.path=="string"?ei.dirname(this.path):void 0}set dirname(n){Lm(this.basename,"dirname"),this.path=ei.join(n||"",this.basename)}get extname(){return typeof this.path=="string"?ei.extname(this.path):void 0}set extname(n){if(Bl(n,"extname"),Lm(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=ei.join(this.dirname,this.stem+(n||""))}get path(){return this.history[this.history.length-1]}set path(n){Gc(n)&&(n=tE(n)),Hl(n,"path"),this.path!==n&&this.history.push(n)}get stem(){return typeof this.path=="string"?ei.basename(this.path,this.extname):void 0}set stem(n){Hl(n,"stem"),Bl(n,"stem"),this.path=ei.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 os(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 Bl(e,n){if(e&&e.includes(ei.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+ei.sep+"`")}function Hl(e,n){if(!e)throw new Error("`"+n+"` cannot be empty")}function Lm(e,n){if(!e)throw new Error("Setting `"+n+"` requires `path` to be set too")}function sE(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const iE=(function(e){const i=this.constructor.prototype,r=i[e],o=function(){return r.apply(o,arguments)};return Object.setPrototypeOf(o,i),o}),aE={}.hasOwnProperty;class Pd extends iE{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=V2()}copy(){const n=new Pd;let s=-1;for(;++s<this.attachers.length;){const i=this.attachers[s];n.use(...i)}return n.data(Ol(!0,{},this.namespace)),n}data(n,s){return typeof n=="string"?arguments.length===2?(Wl("data",this.frozen),this.namespace[n]=s,this):aE.call(this.namespace,n)&&this.namespace[n]||void 0:n?(Wl("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=no(n),i=this.parser||this.Parser;return ql("parse",i),i(String(s),s)}process(n,s){const i=this;return this.freeze(),ql("process",this.parser||this.Parser),Vl("process",this.compiler||this.Compiler),s?r(void 0,s):new Promise(r);function r(o,l){const c=no(n),u=i.parse(c);i.run(u,c,function(m,h,f){if(m||!h||!f)return d(m);const p=h,g=i.stringify(p,f);lE(g)?f.value=g:f.result=g,d(m,f)});function d(m,h){m||!h?l(m):o?o(h):s(void 0,h)}}}processSync(n){let s=!1,i;return this.freeze(),ql("processSync",this.parser||this.Parser),Vl("processSync",this.compiler||this.Compiler),this.process(n,r),Fm("processSync","process",s),i;function r(o,l){s=!0,$m(o),i=l}}run(n,s,i){zm(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=no(s);r.run(n,u,d);function d(m,h,f){const p=h||n;m?c(m):l?l(p):i(void 0,p,f)}}}runSync(n,s){let i=!1,r;return this.run(n,s,o),Fm("runSync","run",i),r;function o(l,c){$m(l),r=c,i=!0}}stringify(n,s){this.freeze();const i=no(s),r=this.compiler||this.Compiler;return Vl("stringify",r),zm(n),r(n,i)}use(n,...s){const i=this.attachers,r=this.namespace;if(Wl("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=Ol(!0,r.settings,d.settings))}function c(d){let m=-1;if(d!=null)if(Array.isArray(d))for(;++m<d.length;){const h=d[m];o(h)}else throw new TypeError("Expected a list of plugins, not `"+d+"`")}function u(d,m){let h=-1,f=-1;for(;++h<i.length;)if(i[h][0]===d){f=h;break}if(f===-1)i.push([d,...m]);else if(m.length>0){let[p,...g]=m;const b=i[f][1];Kc(b)&&Kc(p)&&(p=Ol(!0,b,p)),i[f]=[d,p,...g]}}}}const rE=new Pd().freeze();function ql(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Vl(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Wl(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 zm(e){if(!Kc(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Fm(e,n,s){if(!s)throw new Error("`"+e+"` finished async. Use `"+n+"` instead")}function no(e){return oE(e)?e:new Af(e)}function oE(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function lE(e){return typeof e=="string"||cE(e)}function cE(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const dE="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Om=[],Um={allowDangerousHtml:!0},uE=/^(https?|ircs?|mailto|xmpp)$/i,mE=[{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 ai(e){const n=hE(e),s=pE(e);return fE(n.runSync(n.parse(s),s),e)}function hE(e){const n=e.rehypePlugins||Om,s=e.remarkPlugins||Om,i=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Um}:Um;return rE().use(GC).use(s).use(B2,i).use(n)}function pE(e){const n=e.children||"",s=new Af;return typeof n=="string"&&(s.value=n),s}function fE(e,n){const s=n.allowedElements,i=n.allowElement,r=n.components,o=n.disallowedElements,l=n.skipHtml,c=n.unwrapDisallowed,u=n.urlTransform||gE;for(const m of mE)Object.hasOwn(n,m.from)&&(""+m.from+(m.to?"use `"+m.to+"` instead":"remove it")+dE+m.id,void 0);return Td(e,d),R0(e,{Fragment:t.Fragment,components:r,ignoreInvalidStyle:!0,jsx:t.jsx,jsxs:t.jsxs,passKeys:!0,passNode:!0});function d(m,h,f){if(m.type==="raw"&&f&&typeof h=="number")return l?f.children.splice(h,1):f.children[h]={type:"text",value:m.value},h;if(m.type==="element"){let p;for(p in Dl)if(Object.hasOwn(Dl,p)&&Object.hasOwn(m.properties,p)){const g=m.properties[p],b=Dl[p];(b===null||b.includes(m.tagName))&&(m.properties[p]=u(String(g||""),p,m))}}if(m.type==="element"){let p=s?!s.includes(m.tagName):o?o.includes(m.tagName):!1;if(!p&&i&&typeof h=="number"&&(p=!i(m,h,f)),p&&f&&typeof h=="number")return c&&m.children?f.children.splice(h,1,...m.children):f.children.splice(h,1),h}}}function gE(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||uE.test(e.slice(0,n))?e:""}function Bm(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 bE(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function xE(e,n,s){const r=sl((s||{}).ignore||[]),o=vE(n);let l=-1;for(;++l<o.length;)Mf(e,"text",c);function c(d,m){let h=-1,f;for(;++h<m.length;){const p=m[h],g=f?f.children:void 0;if(r(p,g?g.indexOf(p):void 0,f))return;f=p}if(f)return u(d,m)}function u(d,m){const h=m[m.length-1],f=o[l][0],p=o[l][1];let g=0;const v=h.children.indexOf(d);let x=!1,y=[];f.lastIndex=0;let k=f.exec(d.value);for(;k;){const _=k.index,S={index:k.index,input:k.input,stack:[...m,d]};let w=p(...k,S);if(typeof w=="string"&&(w=w.length>0?{type:"text",value:w}:void 0),w===!1?f.lastIndex=_+1:(g!==_&&y.push({type:"text",value:d.value.slice(g,_)}),Array.isArray(w)?y.push(...w):w&&y.push(w),g=_+k[0].length,x=!0),!f.global)break;k=f.exec(d.value)}return x?(g<d.value.length&&y.push({type:"text",value:d.value.slice(g)}),h.children.splice(v,1,...y)):y=[d],v+y.length}}function vE(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([yE(r[0]),jE(r[1])])}return n}function yE(e){return typeof e=="string"?new RegExp(bE(e),"g"):e}function jE(e){return typeof e=="function"?e:function(){return e}}const Kl="phrasing",Gl=["autolink","link","image","label"];function kE(){return{transforms:[ME],enter:{literalAutolink:NE,literalAutolinkEmail:Jl,literalAutolinkHttp:Jl,literalAutolinkWww:Jl},exit:{literalAutolink:_E,literalAutolinkEmail:EE,literalAutolinkHttp:SE,literalAutolinkWww:CE}}}function wE(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Kl,notInConstruct:Gl},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Kl,notInConstruct:Gl},{character:":",before:"[ps]",after:"\\/",inConstruct:Kl,notInConstruct:Gl}]}}function NE(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function Jl(e){this.config.enter.autolinkProtocol.call(this,e)}function SE(e){this.config.exit.autolinkProtocol.call(this,e)}function CE(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 EE(e){this.config.exit.autolinkEmail.call(this,e)}function _E(e){this.exit(e)}function ME(e){xE(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,AE],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,RE]],{ignore:["link","linkReference"]})}function AE(e,n,s,i,r){let o="";if(!Rf(r)||(/^w/i.test(n)&&(s=n+s,n="",o="http://"),!TE(s)))return!1;const l=PE(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 RE(e,n,s,i){return!Rf(i,!0)||/[-\d_]$/.test(s)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+s,children:[{type:"text",value:n+"@"+s}]}}function TE(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 PE(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=Bm(e,"(");let o=Bm(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 Rf(e,n){const s=e.input.charCodeAt(e.index-1);return(e.index===0||Wi(s)||el(s))&&(!n||s!==47)}Tf.peek=BE;function IE(){this.buffer()}function $E(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function DE(){this.buffer()}function LE(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function zE(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=qs(this.sliceSerialize(e)).toLowerCase(),s.label=n}function FE(e){this.exit(e)}function OE(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=qs(this.sliceSerialize(e)).toLowerCase(),s.label=n}function UE(e){this.exit(e)}function BE(){return"["}function Tf(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 HE(){return{enter:{gfmFootnoteCallString:IE,gfmFootnoteCall:$E,gfmFootnoteDefinitionLabelString:DE,gfmFootnoteDefinition:LE},exit:{gfmFootnoteCallString:zE,gfmFootnoteCall:FE,gfmFootnoteDefinitionLabelString:OE,gfmFootnoteDefinition:UE}}}function qE(e){let n=!1;return e&&e.firstLineBlank&&(n=!0),{handlers:{footnoteDefinition:s,footnoteReference:Tf},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?`
|
|
632
|
-
`:" ")+o.indentLines(o.containerFlow(i,c.current()),n?Pf:VE))),d(),u}}function VE(e,n,s){return n===0?e:Pf(e,n,s)}function Pf(e,n,s){return(s?"":" ")+e}const WE=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];If.peek=QE;function KE(){return{canContainEols:["delete"],enter:{strikethrough:JE},exit:{strikethrough:YE}}}function GE(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:WE}],handlers:{delete:If}}}function JE(e){this.enter({type:"delete",children:[]},e)}function YE(e){this.exit(e)}function If(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 QE(){return"~"}function XE(e){return e.length}function ZE(e,n){const s=n||{},i=(s.align||[]).concat(),r=s.stringLength||XE,o=[],l=[],c=[],u=[];let d=0,m=-1;for(;++m<e.length;){const b=[],v=[];let x=-1;for(e[m].length>d&&(d=e[m].length);++x<e[m].length;){const y=e_(e[m][x]);if(s.alignDelimiters!==!1){const k=r(y);v[x]=k,(u[x]===void 0||k>u[x])&&(u[x]=k)}b.push(y)}l[m]=b,c[m]=v}let h=-1;if(typeof i=="object"&&"length"in i)for(;++h<d;)o[h]=Hm(i[h]);else{const b=Hm(i);for(;++h<d;)o[h]=b}h=-1;const f=[],p=[];for(;++h<d;){const b=o[h];let v="",x="";b===99?(v=":",x=":"):b===108?v=":":b===114&&(x=":");let y=s.alignDelimiters===!1?1:Math.max(1,u[h]-v.length-x.length);const k=v+"-".repeat(y)+x;s.alignDelimiters!==!1&&(y=v.length+y+x.length,y>u[h]&&(u[h]=y),p[h]=y),f[h]=k}l.splice(1,0,f),c.splice(1,0,p),m=-1;const g=[];for(;++m<l.length;){const b=l[m],v=c[m];h=-1;const x=[];for(;++h<d;){const y=b[h]||"";let k="",_="";if(s.alignDelimiters!==!1){const S=u[h]-(v[h]||0),w=o[h];w===114?k=" ".repeat(S):w===99?S%2?(k=" ".repeat(S/2+.5),_=" ".repeat(S/2-.5)):(k=" ".repeat(S/2),_=k):_=" ".repeat(S)}s.delimiterStart!==!1&&!h&&x.push("|"),s.padding!==!1&&!(s.alignDelimiters===!1&&y==="")&&(s.delimiterStart!==!1||h)&&x.push(" "),s.alignDelimiters!==!1&&x.push(k),x.push(y),s.alignDelimiters!==!1&&x.push(_),s.padding!==!1&&x.push(" "),(s.delimiterEnd!==!1||h!==d-1)&&x.push("|")}g.push(s.delimiterEnd===!1?x.join("").replace(/ +$/,""):x.join(""))}return g.join(`
|
|
633
|
-
`)}function e_(e){return e==null?"":String(e)}function Hm(e){const n=typeof e=="string"?e.codePointAt(0):0;return n===67||n===99?99:n===76||n===108?108:n===82||n===114?114:0}function t_(e,n,s,i){const r=s.enter("blockquote"),o=s.createTracker(i);o.move("> "),o.shift(2);const l=s.indentLines(s.containerFlow(e,o.current()),n_);return r(),l}function n_(e,n,s){return">"+(s?"":" ")+e}function s_(e,n){return qm(e,n.inConstruct,!0)&&!qm(e,n.notInConstruct,!1)}function qm(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 Vm(e,n,s,i){let r=-1;for(;++r<s.unsafe.length;)if(s.unsafe[r].character===`
|
|
634
|
-
`&&s_(s.stack,s.unsafe[r]))return/[ \t]/.test(i.before)?"":" ";return`\\
|
|
635
|
-
`}function i_(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 a_(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 r_(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 o_(e,n,s,i){const r=r_(s),o=e.value||"",l=r==="`"?"GraveAccent":"Tilde";if(a_(e,s)){const h=s.enter("codeIndented"),f=s.indentLines(o,l_);return h(),f}const c=s.createTracker(i),u=r.repeat(Math.max(i_(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:`
|
|
636
|
-
`,encode:["`"],...c.current()})),h()}return m+=c.move(`
|
|
637
|
-
`),o&&(m+=c.move(o+`
|
|
638
|
-
`)),m+=c.move(u),d(),m}function l_(e,n,s){return(s?"":" ")+e}function Id(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 c_(e,n,s,i){const r=Id(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?" ":`
|
|
639
|
-
`,...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 d_(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 yr(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Po(e,n,s){const i=xa(e),r=xa(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}}$f.peek=u_;function $f(e,n,s,i){const r=d_(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=Po(i.before.charCodeAt(i.before.length-1),d,r);m.inside&&(u=yr(d)+u.slice(1));const h=u.charCodeAt(u.length-1),f=Po(i.after.charCodeAt(0),h,r);f.inside&&(u=u.slice(0,-1)+yr(h));const p=l.move(r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+u+p}function u_(e,n,s){return s.options.emphasis||"*"}function m_(e,n){let s=!1;return Td(e,function(i){if("value"in i&&/\r?\n|\r/.test(i.value)||i.type==="break")return s=!0,Vc}),!!((!e.depth||e.depth<3)&&Sd(e)&&(n.options.setext||s))}function h_(e,n,s,i){const r=Math.max(Math.min(6,e.depth||1),1),o=s.createTracker(i);if(m_(e,s)){const m=s.enter("headingSetext"),h=s.enter("phrasing"),f=s.containerPhrasing(e,{...o.current(),before:`
|
|
640
|
-
`,after:`
|
|
641
|
-
`});return h(),m(),f+`
|
|
642
|
-
`+(r===1?"=":"-").repeat(f.length-(Math.max(f.lastIndexOf("\r"),f.lastIndexOf(`
|
|
643
|
-
`))+1))}const l="#".repeat(r),c=s.enter("headingAtx"),u=s.enter("phrasing");o.move(l+" ");let d=s.containerPhrasing(e,{before:"# ",after:`
|
|
644
|
-
`,...o.current()});return/^[\t ]/.test(d)&&(d=yr(d.charCodeAt(0))+d.slice(1)),d=d?l+" "+d:l,s.options.closeAtx&&(d+=" "+l),u(),c(),d}Df.peek=p_;function Df(e){return e.value||""}function p_(){return"<"}Lf.peek=f_;function Lf(e,n,s,i){const r=Id(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 f_(){return"!"}zf.peek=g_;function zf(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 g_(){return"!"}Ff.peek=b_;function Ff(e,n,s){let i=e.value||"",r="`",o=-1;for(;new RegExp("(^|[^`])"+r+"([^`]|$)").test(i);)r+="`";for(/[^ \r\n]/.test(i)&&(/^[ \r\n]/.test(i)&&/[ \r\n]$/.test(i)||/^`|`$/.test(i))&&(i=" "+i+" ");++o<s.unsafe.length;){const l=s.unsafe[o],c=s.compilePattern(l);let u;if(l.atBreak)for(;u=c.exec(i);){let d=u.index;i.charCodeAt(d)===10&&i.charCodeAt(d-1)===13&&d--,i=i.slice(0,d)+" "+i.slice(u.index+1)}}return r+i+r}function b_(){return"`"}function Of(e,n){const s=Sd(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))}Uf.peek=x_;function Uf(e,n,s,i){const r=Id(s),o=r==='"'?"Quote":"Apostrophe",l=s.createTracker(i);let c,u;if(Of(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 x_(e,n,s){return Of(e,s)?"<":"["}Bf.peek=v_;function Bf(e,n,s,i){const r=e.referenceType,o=s.enter("linkReference");let l=s.enter("label");const c=s.createTracker(i);let u=c.move("[");const d=s.containerPhrasing(e,{before:u,after:"]",...c.current()});u+=c.move(d+"]["),l();const m=s.stack;s.stack=[],l=s.enter("reference");const h=s.safe(s.associationId(e),{before:u,after:"]",...c.current()});return l(),s.stack=m,o(),r==="full"||!d||d!==h?u+=c.move(h+"]"):r==="shortcut"?u=u.slice(0,-1):u+=c.move("]"),u}function v_(){return"["}function $d(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 y_(e){const n=$d(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 j_(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 Hf(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 k_(e,n,s,i){const r=s.enter("list"),o=s.bulletCurrent;let l=e.ordered?j_(s):$d(s);const c=e.ordered?l==="."?")":".":y_(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),Hf(s)===l&&m){let h=-1;for(;++h<e.children.length;){const f=e.children[h];if(f&&f.type==="listItem"&&f.children&&f.children[0]&&f.children[0].type==="thematicBreak"){u=!0;break}}}}u&&(l=c),s.bulletCurrent=l;const d=s.containerFlow(e,i);return s.bulletLastUsed=l,s.bulletCurrent=o,r(),d}function w_(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 N_(e,n,s,i){const r=w_(s);let o=s.bulletCurrent||$d(s);n&&n.type==="list"&&n.ordered&&(o=(typeof n.start=="number"&&n.start>-1?n.start:1)+(s.options.incrementListMarker===!1?0:n.children.indexOf(e))+o);let l=o.length+1;(r==="tab"||r==="mixed"&&(n&&n.type==="list"&&n.spread||e.spread))&&(l=Math.ceil(l/4)*4);const c=s.createTracker(i);c.move(o+" ".repeat(l-o.length)),c.shift(l);const u=s.enter("listItem"),d=s.indentLines(s.containerFlow(e,c.current()),m);return u(),d;function m(h,f,p){return f?(p?"":" ".repeat(l))+h:(p?o:o+" ".repeat(l-o.length))+h}}function S_(e,n,s,i){const r=s.enter("paragraph"),o=s.enter("phrasing"),l=s.containerPhrasing(e,i);return o(),r(),l}const C_=sl(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function E_(e,n,s,i){return(e.children.some(function(l){return C_(l)})?s.containerPhrasing:s.containerFlow).call(s,e,i)}function __(e){const n=e.options.strong||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize strong with `"+n+"` for `options.strong`, expected `*`, or `_`");return n}qf.peek=M_;function qf(e,n,s,i){const r=__(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=Po(i.before.charCodeAt(i.before.length-1),d,r);m.inside&&(u=yr(d)+u.slice(1));const h=u.charCodeAt(u.length-1),f=Po(i.after.charCodeAt(0),h,r);f.inside&&(u=u.slice(0,-1)+yr(h));const p=l.move(r+r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+u+p}function M_(e,n,s){return s.options.strong||"*"}function A_(e,n,s,i){return s.safe(e.value,i)}function R_(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 T_(e,n,s){const i=(Hf(s)+(s.options.ruleSpaces?" ":"")).repeat(R_(s));return s.options.ruleSpaces?i.slice(0,-1):i}const Vf={blockquote:t_,break:Vm,code:o_,definition:c_,emphasis:$f,hardBreak:Vm,heading:h_,html:Df,image:Lf,imageReference:zf,inlineCode:Ff,link:Uf,linkReference:Bf,list:k_,listItem:N_,paragraph:S_,root:E_,strong:qf,text:A_,thematicBreak:T_};function P_(){return{enter:{table:I_,tableData:Wm,tableHeader:Wm,tableRow:D_},exit:{codeText:L_,table:$_,tableData:Yl,tableHeader:Yl,tableRow:Yl}}}function I_(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 $_(e){this.exit(e),this.data.inTable=void 0}function D_(e){this.enter({type:"tableRow",children:[]},e)}function Yl(e){this.exit(e)}function Wm(e){this.enter({type:"tableCell",children:[]},e)}function L_(e){let n=this.resume();this.data.inTable&&(n=n.replace(/\\([\\|])/g,z_));const s=this.stack[this.stack.length-1];s.type,s.value=n,this.exit(e)}function z_(e,n){return n==="|"?n:e}function F_(e){const n=e||{},s=n.tableCellPadding,i=n.tablePipeAlign,r=n.stringLength,o=s?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
|
|
645
|
-
`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:f,table:l,tableCell:u,tableRow:c}};function l(p,g,b,v){return d(m(p,b,v),p.align)}function c(p,g,b,v){const x=h(p,b,v),y=d([x]);return y.slice(0,y.indexOf(`
|
|
646
|
-
`))}function u(p,g,b,v){const x=b.enter("tableCell"),y=b.enter("phrasing"),k=b.containerPhrasing(p,{...v,before:o,after:o});return y(),x(),k}function d(p,g){return ZE(p,{align:g,alignDelimiters:i,padding:s,stringLength:r})}function m(p,g,b){const v=p.children;let x=-1;const y=[],k=g.enter("table");for(;++x<v.length;)y[x]=h(v[x],g,b);return k(),y}function h(p,g,b){const v=p.children;let x=-1;const y=[],k=g.enter("tableRow");for(;++x<v.length;)y[x]=u(v[x],p,g,b);return k(),y}function f(p,g,b){let v=Vf.inlineCode(p,g,b);return b.stack.includes("tableCell")&&(v=v.replace(/\|/g,"\\$&")),v}}function O_(){return{exit:{taskListCheckValueChecked:Km,taskListCheckValueUnchecked:Km,paragraph:B_}}}function U_(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:H_}}}function Km(e){const n=this.stack[this.stack.length-2];n.type,n.checked=e.type==="taskListCheckValueChecked"}function B_(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 H_(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=Vf.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 q_(){return[kE(),HE(),KE(),P_(),O_()]}function V_(e){return{extensions:[wE(),qE(e),GE(),F_(e),U_()]}}const W_={tokenize:X_,partial:!0},Wf={tokenize:Z_,partial:!0},Kf={tokenize:eM,partial:!0},Gf={tokenize:tM,partial:!0},K_={tokenize:nM,partial:!0},Jf={name:"wwwAutolink",tokenize:Y_,previous:Qf},Yf={name:"protocolAutolink",tokenize:Q_,previous:Xf},gi={name:"emailAutolink",tokenize:J_,previous:Zf},li={};function G_(){return{text:li}}let $i=48;for(;$i<123;)li[$i]=gi,$i++,$i===58?$i=65:$i===91&&($i=97);li[43]=gi;li[45]=gi;li[46]=gi;li[95]=gi;li[72]=[gi,Yf];li[104]=[gi,Yf];li[87]=[gi,Jf];li[119]=[gi,Jf];function J_(e,n,s){const i=this;let r,o;return l;function l(h){return!Jc(h)||!Zf.call(i,i.previous)||Dd(i.events)?s(h):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(h))}function c(h){return Jc(h)?(e.consume(h),c):h===64?(e.consume(h),u):s(h)}function u(h){return h===46?e.check(K_,m,d)(h):h===45||h===95||as(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&&ds(i.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),n(h)):s(h)}}function Y_(e,n,s){const i=this;return r;function r(l){return l!==87&&l!==119||!Qf.call(i,i.previous)||Dd(i.events)?s(l):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(W_,e.attempt(Wf,e.attempt(Kf,o),s),s)(l))}function o(l){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),n(l)}}function Q_(e,n,s){const i=this;let r="",o=!1;return l;function l(h){return(h===72||h===104)&&Xf.call(i,i.previous)&&!Dd(i.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),r+=String.fromCodePoint(h),e.consume(h),c):s(h)}function c(h){if(ds(h)&&r.length<5)return r+=String.fromCodePoint(h),e.consume(h),c;if(h===58){const f=r.toLowerCase();if(f==="http"||f==="https")return e.consume(h),u}return s(h)}function u(h){return h===47?(e.consume(h),o?d:(o=!0,u)):s(h)}function d(h){return h===null||Ao(h)||pn(h)||Wi(h)||el(h)?s(h):e.attempt(Wf,e.attempt(Kf,m),s)(h)}function m(h){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),n(h)}}function X_(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 Z_(e,n,s){let i,r,o;return l;function l(d){return d===46||d===95?e.check(Gf,u,c)(d):d===null||pn(d)||Wi(d)||d!==45&&el(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 eM(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(Gf,n,o)(l):l===null||pn(l)||Wi(l)?n(l):(e.consume(l),r)}function o(l){return l===41&&i++,e.consume(l),r}}function tM(e,n,s){return i;function i(c){return c===33||c===34||c===39||c===41||c===42||c===44||c===46||c===58||c===59||c===63||c===95||c===126?(e.consume(c),i):c===38?(e.consume(c),o):c===93?(e.consume(c),r):c===60||c===null||pn(c)||Wi(c)?n(c):s(c)}function r(c){return c===null||c===40||c===91||pn(c)||Wi(c)?n(c):i(c)}function o(c){return ds(c)?l(c):s(c)}function l(c){return c===59?(e.consume(c),i):ds(c)?(e.consume(c),l):s(c)}}function nM(e,n,s){return i;function i(o){return e.consume(o),r}function r(o){return as(o)?s(o):n(o)}}function Qf(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||pn(e)}function Xf(e){return!ds(e)}function Zf(e){return!(e===47||Jc(e))}function Jc(e){return e===43||e===45||e===46||e===95||as(e)}function Dd(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 sM={tokenize:uM,partial:!0};function iM(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:lM,continuation:{tokenize:cM},exit:dM}},text:{91:{name:"gfmFootnoteCall",tokenize:oM},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:aM,resolveTo:rM}}}}function aM(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=qs(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 rM(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 oM(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||pn(h))return s(h);if(h===93){e.exit("chunkString");const f=e.exit("gfmFootnoteCallString");return r.includes(qs(i.sliceSerialize(f)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),n):s(h)}return pn(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 lM(e,n,s){const i=this,r=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);let o,l=0,c;return u;function u(g){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),d}function d(g){return g===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",m):s(g)}function m(g){if(l>999||g===93&&!c||g===null||g===91||pn(g))return s(g);if(g===93){e.exit("chunkString");const b=e.exit("gfmFootnoteDefinitionLabelString");return o=qs(i.sliceSerialize(b)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),f}return pn(g)||(c=!0),l++,e.consume(g),g===92?h:m}function h(g){return g===91||g===92||g===93?(e.consume(g),l++,m):m(g)}function f(g){return g===58?(e.enter("definitionMarker"),e.consume(g),e.exit("definitionMarker"),r.includes(o)||r.push(o),en(e,p,"gfmFootnoteDefinitionWhitespace")):s(g)}function p(g){return n(g)}}function cM(e,n,s){return e.check(Pr,n,e.attempt(sM,n,s))}function dM(e){e.exit("gfmFootnoteDefinition")}function uM(e,n,s){const i=this;return en(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 mM(e){let s=(e||{}).singleTilde;const i={name:"strikethrough",tokenize:o,resolveAll:r};return s==null&&(s=!0),{text:{126:i},insideSpan:{null:[i]},attentionMarkers:{null:[126]}};function r(l,c){let u=-1;for(;++u<l.length;)if(l[u][0]==="enter"&&l[u][1].type==="strikethroughSequenceTemporary"&&l[u][1]._close){let d=u;for(;d--;)if(l[d][0]==="exit"&&l[d][1].type==="strikethroughSequenceTemporary"&&l[d][1]._open&&l[u][1].end.offset-l[u][1].start.offset===l[d][1].end.offset-l[d][1].start.offset){l[u][1].type="strikethroughSequence",l[d][1].type="strikethroughSequence";const m={type:"strikethrough",start:Object.assign({},l[d][1].start),end:Object.assign({},l[u][1].end)},h={type:"strikethroughText",start:Object.assign({},l[d][1].end),end:Object.assign({},l[u][1].start)},f=[["enter",m,c],["enter",l[d][1],c],["exit",l[d][1],c],["enter",h,c]],p=c.parser.constructs.insideSpan.null;p&&Ns(f,f.length,0,tl(p,l.slice(d+1,u),c)),Ns(f,f.length,0,[["exit",h,c],["enter",l[u][1],c],["exit",l[u][1],c],["exit",m,c]]),Ns(l,d-1,u-d+3,f),u=d+f.length-2;break}}for(u=-1;++u<l.length;)l[u][1].type==="strikethroughSequenceTemporary"&&(l[u][1].type="data");return l}function o(l,c,u){const d=this.previous,m=this.events;let h=0;return f;function f(g){return d===126&&m[m.length-1][1].type!=="characterEscape"?u(g):(l.enter("strikethroughSequenceTemporary"),p(g))}function p(g){const b=xa(d);if(g===126)return h>1?u(g):(l.consume(g),h++,p);if(h<2&&!s)return u(g);const v=l.exit("strikethroughSequenceTemporary"),x=xa(g);return v._open=!x||x===2&&!!b,v._close=!b||b===2&&!!x,c(g)}}}class hM{constructor(){this.map=[]}add(n,s,i){pM(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 pM(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 fM(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 gM(){return{flow:{null:{name:"table",tokenize:bM,resolveAll:xM}}}}function bM(e,n,s){const i=this;let r=0,o=0,l;return c;function c(E){let T=i.events.length-1;for(;T>-1;){const $=i.events[T][1].type;if($==="lineEnding"||$==="linePrefix")T--;else break}const U=T>-1?i.events[T][1].type:null,K=U==="tableHead"||U==="tableRow"?w:u;return K===w&&i.parser.lazy[i.now().line]?s(E):K(E)}function u(E){return e.enter("tableHead"),e.enter("tableRow"),d(E)}function d(E){return E===124||(l=!0,o+=1),m(E)}function m(E){return E===null?s(E):Nt(E)?o>1?(o=0,i.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(E),e.exit("lineEnding"),p):s(E):Qt(E)?en(e,m,"whitespace")(E):(o+=1,l&&(l=!1,r+=1),E===124?(e.enter("tableCellDivider"),e.consume(E),e.exit("tableCellDivider"),l=!0,m):(e.enter("data"),h(E)))}function h(E){return E===null||E===124||pn(E)?(e.exit("data"),m(E)):(e.consume(E),E===92?f:h)}function f(E){return E===92||E===124?(e.consume(E),h):h(E)}function p(E){return i.interrupt=!1,i.parser.lazy[i.now().line]?s(E):(e.enter("tableDelimiterRow"),l=!1,Qt(E)?en(e,g,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(E):g(E))}function g(E){return E===45||E===58?v(E):E===124?(l=!0,e.enter("tableCellDivider"),e.consume(E),e.exit("tableCellDivider"),b):S(E)}function b(E){return Qt(E)?en(e,v,"whitespace")(E):v(E)}function v(E){return E===58?(o+=1,l=!0,e.enter("tableDelimiterMarker"),e.consume(E),e.exit("tableDelimiterMarker"),x):E===45?(o+=1,x(E)):E===null||Nt(E)?_(E):S(E)}function x(E){return E===45?(e.enter("tableDelimiterFiller"),y(E)):S(E)}function y(E){return E===45?(e.consume(E),y):E===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(E),e.exit("tableDelimiterMarker"),k):(e.exit("tableDelimiterFiller"),k(E))}function k(E){return Qt(E)?en(e,_,"whitespace")(E):_(E)}function _(E){return E===124?g(E):E===null||Nt(E)?!l||r!==o?S(E):(e.exit("tableDelimiterRow"),e.exit("tableHead"),n(E)):S(E)}function S(E){return s(E)}function w(E){return e.enter("tableRow"),M(E)}function M(E){return E===124?(e.enter("tableCellDivider"),e.consume(E),e.exit("tableCellDivider"),M):E===null||Nt(E)?(e.exit("tableRow"),n(E)):Qt(E)?en(e,M,"whitespace")(E):(e.enter("data"),N(E))}function N(E){return E===null||E===124||pn(E)?(e.exit("data"),M(E)):(e.consume(E),E===92?D:N)}function D(E){return E===92||E===124?(e.consume(E),N):N(E)}}function xM(e,n){let s=-1,i=!0,r=0,o=[0,0,0,0],l=[0,0,0,0],c=!1,u=0,d,m,h;const f=new hM;for(;++s<e.length;){const p=e[s],g=p[1];p[0]==="enter"?g.type==="tableHead"?(c=!1,u!==0&&(Gm(f,n,u,d,m),m=void 0,u=0),d={type:"table",start:Object.assign({},g.start),end:Object.assign({},g.end)},f.add(s,0,[["enter",d,n]])):g.type==="tableRow"||g.type==="tableDelimiterRow"?(i=!0,h=void 0,o=[0,0,0,0],l=[0,s+1,0,0],c&&(c=!1,m={type:"tableBody",start:Object.assign({},g.start),end:Object.assign({},g.end)},f.add(s,0,[["enter",m,n]])),r=g.type==="tableDelimiterRow"?2:m?3:1):r&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")?(i=!1,l[2]===0&&(o[1]!==0&&(l[0]=l[1],h=so(f,n,o,r,void 0,h),o=[0,0,0,0]),l[2]=s)):g.type==="tableCellDivider"&&(i?i=!1:(o[1]!==0&&(l[0]=l[1],h=so(f,n,o,r,void 0,h)),o=l,l=[o[1],s,0,0])):g.type==="tableHead"?(c=!0,u=s):g.type==="tableRow"||g.type==="tableDelimiterRow"?(u=s,o[1]!==0?(l[0]=l[1],h=so(f,n,o,r,s,h)):l[1]!==0&&(h=so(f,n,l,r,s,h)),r=0):r&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")&&(l[3]=s)}for(u!==0&&Gm(f,n,u,d,m),f.consume(n.events),s=-1;++s<n.events.length;){const p=n.events[s];p[0]==="enter"&&p[1].type==="table"&&(p[1]._align=fM(n.events,s))}return e}function so(e,n,s,i,r,o){const l=i===1?"tableHeader":i===2?"tableDelimiter":"tableData",c="tableContent";s[0]!==0&&(o.end=Object.assign({},da(n.events,s[0])),e.add(s[0],0,[["exit",o,n]]));const u=da(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=da(n.events,s[2]),m=da(n.events,s[3]),h={type:c,start:Object.assign({},d),end:Object.assign({},m)};if(e.add(s[2],0,[["enter",h,n]]),i!==2){const f=n.events[s[2]],p=n.events[s[3]];if(f[1].end=Object.assign({},p[1].end),f[1].type="chunkText",f[1].contentType="text",s[3]>s[2]+1){const g=s[2]+1,b=s[3]-s[2]-1;e.add(g,b,[])}}e.add(s[3]+1,0,[["exit",h,n]])}return r!==void 0&&(o.end=Object.assign({},da(n.events,r)),e.add(r,0,[["exit",o,n]]),o=void 0),o}function Gm(e,n,s,i,r){const o=[],l=da(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 da(e,n){const s=e[n],i=s[0]==="enter"?"start":"end";return s[1][i]}const vM={name:"tasklistCheck",tokenize:jM};function yM(){return{text:{91:vM}}}function jM(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 pn(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 Nt(u)?n(u):Qt(u)?e.check({tokenize:kM},n,s)(u):s(u)}}function kM(e,n,s){return en(e,i,"whitespace");function i(r){return r===null?s(r):n(r)}}function wM(e){return df([G_(),iM(),mM(e),gM(),yM()])}const NM={};function ri(e){const n=this,s=e||NM,i=n.data(),r=i.micromarkExtensions||(i.micromarkExtensions=[]),o=i.fromMarkdownExtensions||(i.fromMarkdownExtensions=[]),l=i.toMarkdownExtensions||(i.toMarkdownExtensions=[]);r.push(wM(s)),o.push(q_()),l.push(V_(s))}const Jm=500,Ym=100;function Ql(e){return e.length>Jm?e.slice(-Jm):e}function eg(e,n,s){const[i,r]=a.useState([]),[o,l]=a.useState(!1),[c,u]=a.useState(!1),[d,m]=a.useState(null),[h,f]=a.useState(!1),p=a.useRef(null),g=a.useRef(!1),b=a.useRef(0),v=a.useRef(e),x=a.useRef(s),y=a.useRef(n),k=a.useRef(0);(v.current!==e||x.current!==s||y.current!==n)&&(v.current=e,x.current=s,y.current=n,b.current++,g.current=!0,r([]),l(!1),u(!1),m(null),f(!1),p.current&&(p.current(),p.current=null)),a.useEffect(()=>{if(!e||!n){p.current&&(p.current(),p.current=null);return}const M=b.current,N=++k.current;g.current=!1;const D=e,E=s;async function T(){if(!D)return;l(!0),f(!1);try{const K=await Kd(D,E,{limit:Ym});if(g.current||b.current!==M||k.current!==N)return;r(Ql(K.entries)),u(K.hasMore),m(K.total)}catch{if(g.current||b.current!==M||k.current!==N)return;r([]),u(!1),m(null)}finally{!g.current&&b.current===M&&k.current===N&&l(!1)}const U=E?`?projectId=${encodeURIComponent(E)}`:"";p.current=Ks(`/api/tasks/${D}/logs/stream${U}`,{events:{"agent:log":K=>{if(!(g.current||b.current!==M))try{const $=JSON.parse(K.data);r(R=>Ql([...R,$])),m(R=>R!==null?R+1:null)}catch{}}}})}return T(),()=>{g.current=!0,p.current&&(p.current(),p.current=null)}},[e,n,s]);const S=a.useCallback(async()=>{if(!e||h)return;const M=b.current,N=i.length,D=e;f(!0);try{const E=await Kd(D,s,{limit:Ym,offset:N});if(g.current||b.current!==M)return;r(T=>{const U=[...E.entries,...T];return Ql(U)}),u(E.hasMore),m(E.total)}catch{}finally{f(!1)}},[e,s,i.length,h]),w=a.useCallback(()=>r([]),[]);return{entries:i,loading:o,clear:w,loadMore:S,hasMore:c,total:d,loadingMore:h}}function SM(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 Qm={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})},tg=50,CM={triage:"Plan"};function Xm(e){return e.scrollHeight-(e.scrollTop+e.clientHeight)<=tg}function Yc(e){return[e.taskId,e.timestamp,e.agent??"",e.type,e.text,e.detail??""].join("|")}function EM(e){const n=new Map;return e.map(s=>{const i=Yc(s),r=n.get(i)??0;return n.set(i,r+1),`${i}|${r}`})}function _M(e){return e==="tool"||e==="tool_result"||e==="tool_error"}function MM(e,n){return e.agent?_M(e.type)?!0:!n||n.agent!==e.agent||n.type!==e.type:!1}function AM(e,n){const s=[];for(let i=0;i<e.length;i+=1){const r=e[i],o=n[i]??`${Yc(r)}|fallback`,l=i>0?e[i-1]:void 0,c=MM(r,l);if(r.type==="text"||r.type==="thinking"){const u=[r];let d=i+1;for(;d<e.length;){const h=e[d];if(h.type!==r.type||h.agent!==r.agent)break;u.push(h),d+=1}const m=n[d-1]??`${Yc(e[d-1])}|fallback`;s.push({kind:r.type,entries:u,key:`${o}->${m}`,showBadge:c}),i=d-1;continue}s.push({kind:"single",entry:r,key:o,showBadge:c})}return s}function RM({entries:e,loading:n,executorModel:s,validatorModel:i,planningModel:r,hasMore:o=!1,onLoadMore:l,loadingMore:c=!1,totalCount:u=null}){const d=a.useRef(null),m=a.useRef(0),h=a.useRef(0),f=a.useRef(null),p=a.useRef(null),[g,b]=a.useState(!0),[v,x]=a.useState(!1),[y,k]=a.useState(!1),[_,S]=a.useState(!0),w=a.useMemo(()=>EM(e),[e]),M=a.useMemo(()=>AM(e,w),[e,w]);a.useLayoutEffect(()=>{const R=d.current;if(!R)return;const z=e.length,B=m.current,J=h.current||R.scrollHeight,Q=w[0]??null,C=w[w.length-1]??null,L=f.current!==Q,P=p.current!==C;if(z>B)if(B===0)R.scrollTop=R.scrollHeight;else{const j=J-(R.scrollTop+R.clientHeight)<=tg,O=P&&!L,H=L&&!P;if(O&&j&&(R.scrollTop=R.scrollHeight),H){const ge=R.scrollHeight-J;ge>0&&(R.scrollTop+=ge)}}m.current=z,h.current=R.scrollHeight,f.current=Q,p.current=C,S(Xm(R))},[e,w]);const N=a.useCallback(()=>{const R=d.current;R&&S(Xm(R))},[]),D=a.useCallback(()=>{const R=d.current;R&&(R.scrollTop=R.scrollHeight,S(!0))},[]),E=a.useCallback(R=>{R.key==="Escape"&&v&&x(!1)},[v]);a.useEffect(()=>{if(v)return document.addEventListener("keydown",E),()=>{document.removeEventListener("keydown",E)}},[v,E]);const T=s?.provider&&s?.modelId,U=i?.provider&&i?.modelId,K=r?.provider&&r?.modelId,$=a.useMemo(()=>{const R=[];return T&&R.push({role:"Executor",provider:s.provider,modelId:s.modelId}),U&&R.push({role:"Reviewer",provider:i.provider,modelId:i.modelId}),K&&R.push({role:"Planning",provider:r.provider,modelId:r.modelId}),R},[T,s,U,i,K,r]);return n&&e.length===0?t.jsx("div",{className:"agent-log-viewer","data-testid":"agent-log-viewer",children:t.jsx("div",{className:"agent-log-loading",children:"Loading agent logs…"})}):e.length===0?t.jsx("div",{className:"agent-log-viewer","data-testid":"agent-log-viewer",children:t.jsx("div",{className:"agent-log-empty",children:"No agent output yet."})}):t.jsxs("div",{className:`agent-log-viewer agent-log-viewer--streaming${v?" agent-log-viewer--fullscreen":""}`,"data-testid":"agent-log-viewer",children:[t.jsxs("div",{className:"agent-log-model-header","data-testid":"agent-log-model-header",children:[t.jsxs("div",{className:"agent-log-model-icons",children:[$.map(R=>t.jsx(On,{provider:R.provider,size:"sm"},`${R.role}-${R.provider}-${R.modelId??"default"}`)),t.jsx("button",{className:"agent-log-model-expand-btn",onClick:()=>k(R=>!R),"aria-label":y?"Collapse model details":"Expand model details","aria-expanded":y,"aria-controls":"agent-log-model-details","data-testid":"agent-log-model-expand",children:y?t.jsx(Xt,{size:14}):t.jsx(vn,{size:14})})]}),t.jsxs("div",{className:"agent-log-model-header-toggle",children:[t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>b(R=>!R),"aria-label":g?"Switch to plain text mode":"Switch to markdown mode","aria-pressed":g,"data-testid":"agent-log-mode-toggle",title:g?"Show raw text":"Show formatted markdown",children:g?"Markdown":"Plain"}),t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>x(R=>!R),"aria-label":v?"Exit full screen":"Expand agent log to full screen","data-testid":"agent-log-fullscreen-toggle",title:v?"Exit full screen":"Expand agent log to full screen",children:v?t.jsx(Sr,{size:14}):t.jsx(qo,{size:14})})]}),y&&t.jsxs("div",{id:"agent-log-model-details",className:"agent-log-model-details",children:[t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Executor:"}),T?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(On,{provider:s.provider,size:"sm"}),t.jsxs("span",{children:[s.provider,"/",s.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]}),t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Reviewer:"}),U?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(On,{provider:i.provider,size:"sm"}),t.jsxs("span",{children:[i.provider,"/",i.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]}),t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Planning:"}),K?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(On,{provider:r.provider,size:"sm"}),t.jsxs("span",{children:[r.provider,"/",r.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]})]})]}),t.jsxs("div",{ref:d,className:"agent-log-viewer-scroll",onScroll:N,children:[u!==null&&t.jsxs("div",{className:"agent-log-summary","data-testid":"agent-log-summary",children:["Showing ",e.length," of ",u," entries"]}),o&&l&&t.jsx("div",{className:"agent-log-load-more","data-testid":"agent-log-load-more",children:t.jsx("button",{className:"agent-log-mode-toggle",onClick:l,disabled:c,"data-testid":"agent-log-load-more-button",children:c?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:14,className:"animate-spin"}),"Loading…"]}):"Load More"})}),M.map(R=>{const z=R.kind==="single"?R.entry:R.entries[0],B=R.showBadge?t.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:SM(z.timestamp)}):null,J=R.showBadge?t.jsxs("span",{className:"agent-log-badge-row",children:[t.jsxs("span",{className:"agent-log-agent-badge",children:["[",CM[z.agent]??z.agent,"]"]}),B]}):null;if(R.kind==="single"){const{entry:C}=R;if(C.type==="tool")return t.jsxs("div",{className:"agent-log-tool",children:[J,"⚡ ",C.text,C.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",C.detail]})]},R.key);if(C.type==="tool_result")return t.jsxs("div",{className:"agent-log-tool-result",children:[J,"✓ ",C.text,C.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",C.detail]})]},R.key);if(C.type==="tool_error")return t.jsxs("div",{className:"agent-log-tool-error",children:[J,"✗ ",C.text,C.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",C.detail]})]},R.key)}const Q=R.kind==="single"?z.text:R.entries.map(C=>C.text).join("");return R.kind==="thinking"?t.jsxs("div",{className:"agent-log-thinking",children:[J,g?t.jsx("div",{className:"markdown-body",children:t.jsx(ai,{remarkPlugins:[ri],components:Qm,children:Q})}):Q]},R.key):t.jsxs("div",{className:"agent-log-text",children:[J,g?t.jsx("div",{className:"markdown-body",children:t.jsx(ai,{remarkPlugins:[ri],components:Qm,children:Q})}):Q]},R.key)}),!_&&t.jsxs("button",{type:"button",className:"agent-log-return-to-live",onClick:D,"data-testid":"agent-log-return-to-live",children:[t.jsx(Xt,{size:12}),t.jsx("span",{children:"Live"})]})]})]})}function va(e){return e??void 0}function io(e){return{provider:va(e.modelProvider),modelId:va(e.modelId)}}function ao(e){return{provider:va(e.validatorModelProvider),modelId:va(e.validatorModelId)}}function ro(e){return{provider:va(e.planningModelProvider),modelId:va(e.planningModelId)}}function TM(e,n){return _p(e,n)}function PM(e,n){return Mp(e,n)}function IM(e,n){return Ap(e,n)}function Xl(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 Zl(e){return e.provider&&e.modelId?`${e.provider}/${e.modelId}`:""}function ec(e,n){return e.provider===n.provider&&e.modelId===n.modelId}function $M(e,n){const i={executor:"Executor",validator:"Reviewer",planning:"Planning"}[e]||e;return!n.provider||!n.modelId?`${i} model set to default`:`${i} model set to ${n.provider}/${n.modelId}`}function DM({task:e,addToast:n,onTaskUpdated:s,settings:i}){const[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState([]),[m,h]=a.useState(!1),[f,p]=a.useState(null),[g,b]=a.useState(()=>io(e)),[v,x]=a.useState(()=>io(e)),[y,k]=a.useState(()=>ao(e)),[_,S]=a.useState(()=>ao(e)),[w,M]=a.useState(()=>ro(e)),[N,D]=a.useState(()=>ro(e)),[E,T]=a.useState(()=>e.thinkingLevel??null),[U,K]=a.useState(()=>e.thinkingLevel??null),[$,R]=a.useState(null),z=a.useRef(e.id);a.useEffect(()=>{h(!0),p(null),ms().then(oe=>{o(oe.models),c(oe.favoriteProviders),d(oe.favoriteModels)}).catch(oe=>{p(oe.message||"Failed to load models")}).finally(()=>{h(!1)})},[]);const B=a.useCallback(async oe=>{const he=l,je=he.includes(oe)?he.filter(Ae=>Ae!==oe):[oe,...he];c(je);try{await hn({favoriteProviders:je,favoriteModels:u})}catch{c(he),n("Failed to update favorites","error")}},[l,u,n]),J=a.useCallback(async oe=>{const he=u,je=he.includes(oe)?he.filter(Ae=>Ae!==oe):[oe,...he];d(je);try{await hn({favoriteProviders:l,favoriteModels:je})}catch{d(he),n("Failed to update model favorites","error")}},[u,l,n]);a.useEffect(()=>{z.current=e.id;const oe=io(e),he=ao(e),ae=ro(e);b(oe),x(oe),k(he),S(he),M(ae),D(ae);const je=e.thinkingLevel??null;T(je),K(je),R(null)},[e.id,e.modelProvider,e.modelId,e.validatorModelProvider,e.validatorModelId,e.planningModelProvider,e.planningModelId,e.thinkingLevel]);const Q=a.useMemo(()=>Zl(g),[g]),C=a.useMemo(()=>Zl(y),[y]),L=a.useMemo(()=>Zl(w),[w]),P=a.useMemo(()=>TM(e,i),[e,i]),j=a.useMemo(()=>PM(e,i),[e,i]),O=a.useMemo(()=>IM(e,i),[e,i]),H=$!==null,ge=a.useCallback(async(oe,he)=>{const ae=e.id,je=v,Ae=_,Oe=N;R(oe);try{const Qe=s?oe==="executor"?{modelProvider:he.provider??null,modelId:he.modelId??null}:oe==="validator"?{validatorModelProvider:he.provider??null,validatorModelId:he.modelId??null}:{planningModelProvider:he.provider??null,planningModelId:he.modelId??null}:{modelProvider:(oe==="executor"?he:v).provider??null,modelId:(oe==="executor"?he:v).modelId??null,validatorModelProvider:(oe==="validator"?he:_).provider??null,validatorModelId:(oe==="validator"?he:_).modelId??null,planningModelProvider:(oe==="planning"?he:N).provider??null,planningModelId:(oe==="planning"?he:N).modelId??null},Xe=await ni(ae,Qe);if(z.current!==ae)return;const Ye=io(Xe),it=ao(Xe),Be=ro(Xe);x(Ye),b(Ye),S(it),k(it),D(Be),M(Be),s?.(Xe),n($M(oe,{executor:Ye,validator:it,planning:Be}[oe]),"success")}catch(Qe){if(z.current!==ae)return;oe==="executor"?b(je):oe==="validator"?k(Ae):M(Oe),n(ye(Qe)||"Failed to save model settings","error")}finally{z.current===ae&&R(null)}},[e.id,v,_,N,n,s]),be=a.useCallback(oe=>{const he=Xl(oe);b(he),!ec(he,v)&&ge("executor",he)},[v,ge]),se=a.useCallback(oe=>{const he=Xl(oe);k(he),!ec(he,_)&&ge("validator",he)},[_,ge]),me=a.useCallback(oe=>{const he=Xl(oe);M(he),!ec(he,N)&&ge("planning",he)},[N,ge]),F=a.useCallback(async oe=>{const he=e.id,ae=U,je=oe===""?null:oe;T(je),R("thinking");try{const Ae=await ni(he,{thinkingLevel:je});if(z.current!==he)return;const Oe=Ae.thinkingLevel??null;K(Oe),T(Oe),s?.(Ae);const Qe=i?.defaultThinkingLevel??"off";n(Oe===null?`Thinking level set to default (${Qe})`:`Thinking level set to ${Oe}`,"success")}catch(Ae){if(z.current!==he)return;T(ae),n(ye(Ae)||"Failed to save thinking level","error")}finally{z.current===he&&R(null)}},[e.id,U,i,n,s]),de=!v.provider&&!v.modelId,ne=!_.provider&&!_.modelId,xe=!N.provider&&!N.modelId;return t.jsxs("div",{className:"model-selector-tab",children:[t.jsx("h4",{children:"Model Configuration"}),t.jsx("p",{className:"model-selector-intro",children:"Override the AI models used for this task. When not specified, project or global defaults are used."}),m?t.jsx("div",{className:"model-selector-loading",children:"Loading available models…"}):f?t.jsxs("div",{className:"model-selector-error",children:["Error loading models: ",f,t.jsx("button",{className:"btn btn-sm",onClick:()=>{h(!0),p(null),ms().then(oe=>{o(oe.models),c(oe.favoriteProviders),d(oe.favoriteModels)}).catch(oe=>p(oe.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:de?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",P.provider&&P.modelId?` (${P.provider}/${P.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[v.provider&&t.jsx(On,{provider:v.provider,size:"sm"}),v.provider,"/",v.modelId]})}),t.jsx(Yn,{id:"executorModel",label:"Executor Model",value:Q,onChange:be,models:r,disabled:H,placeholder:"Select executor model…",favoriteProviders:l,onToggleFavorite:B,favoriteModels:u,onToggleModelFavorite:J}),t.jsx("small",{children:"The AI model used to implement this task."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"validatorModel",children:"Reviewer Model"}),t.jsx("div",{className:"model-selector-current",children:ne?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",j.provider&&j.modelId?` (${j.provider}/${j.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[_.provider&&t.jsx(On,{provider:_.provider,size:"sm"}),_.provider,"/",_.modelId]})}),t.jsx(Yn,{id:"validatorModel",label:"Reviewer Model",value:C,onChange:se,models:r,disabled:H,placeholder:"Select reviewer model…",favoriteProviders:l,onToggleFavorite:B,favoriteModels:u,onToggleModelFavorite:J}),t.jsx("small",{children:"The AI model used to review code and plans for this task."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"planningModel",children:"Planning Model"}),t.jsx("div",{className:"model-selector-current",children:xe?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",O.provider&&O.modelId?` (${O.provider}/${O.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[N.provider&&t.jsx(On,{provider:N.provider,size:"sm"}),N.provider,"/",N.modelId]})}),t.jsx(Yn,{id:"planningModel",label:"Planning Model",value:L,onChange:me,models:r,disabled:H,placeholder:"Select planning model…",favoriteProviders:l,onToggleFavorite:B,favoriteModels:u,onToggleModelFavorite:J}),t.jsx("small",{children:"The AI model used for task specification (triage phase)."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"thinkingLevel",children:"Thinking Level"}),t.jsx("div",{className:"model-selector-current",children:U===null?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default (",i?.defaultThinkingLevel??"off",")"]}):t.jsx("span",{className:"model-badge model-badge-custom",children:U})}),t.jsxs("select",{id:"thinkingLevel",value:E??"",onChange:oe=>F(oe.target.value),disabled:H,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:de&&ne&&xe&&U===null?"Using project or global default models.":"Model settings are up to date."})]})]})}const LM={open:t.jsx(Oo,{size:16}),closed:t.jsx(wr,{size:16}),merged:t.jsx(ep,{size:16})};function zM({taskId:e,projectId:n,prInfo:s,automationStatus:i,autoMerge:r=!1,prAuthAvailable:o,onPrCreated:l,onPrUpdated:c,addToast:u}){const[d,m]=a.useState(!1),[h,f]=a.useState(""),[p,g]=a.useState(""),[b,v]=a.useState(!1),[x,y]=a.useState(!1),[k,_]=a.useState(null),S=a.useCallback(async()=>{if(h.trim()){v(!0);try{const D=await Ry(e,{title:h.trim(),body:p.trim()||void 0},n);l(D),m(!1),f(""),g(""),u(`Created PR #${D.number}`,"success")}catch(D){u(ye(D)||"Failed to create PR","error")}finally{v(!1)}}},[e,h,p,n,l,u]),w=a.useCallback(async()=>{if(s){y(!0);try{const D=await Ty(e,n);_(D),c(D.prInfo),u("PR status refreshed","success")}catch(D){u(ye(D)||"Failed to refresh PR","error")}finally{y(!1)}}},[e,s,n,c,u]);if(!s)return i==="creating-pr"?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(ks,{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(ks,{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(ks,{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:D=>f(D.target.value),disabled:b,className:"pr-input"}),t.jsx("textarea",{placeholder:"PR description (optional)",value:p,onChange:D=>g(D.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:S,disabled:!h.trim()||b,children:b?"Creating…":"Create PR"})]})]})]}):t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(ks,{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(on,{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 M=LM[s.status]??t.jsx(Oo,{size:16}),N=k?.blockingReasons??[];return t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(ks,{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:M}),t.jsx("span",{className:`pr-status-badge pr-status-badge--${s.status}`,children:s.status}),t.jsxs("span",{className:"pr-number",children:["#",s.number]}),t.jsx("div",{className:"pr-spacer"}),t.jsx("button",{className:"btn btn-sm pr-refresh-btn",onClick:w,disabled:x,title:"Refresh PR status",children:t.jsx($n,{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:N.length>0?`Waiting for: ${N.join("; ")}`:"Waiting for required checks or review feedback before auto-merge."}),s.status==="merged"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:"This PR is merged. fn will finish local cleanup and move the task to Done."}),t.jsxs("div",{className:"pr-footer",children:[s.commentCount>0&&t.jsxs("span",{className:"pr-comments",children:[t.jsx(wi,{size:14}),s.commentCount]}),t.jsxs("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"pr-link",children:[t.jsx(Cb,{size:14}),"View on GitHub"]})]})]})]})}const Zm=2e3;function FM(e){const n=e.updatedAt||e.createdAt,s=new Date(n).toLocaleString();return e.updatedAt?`${s} (edited)`:s}function OM(e){return e==="agent"||e==="system"}function UM({task:e,onTaskUpdated:n,addToast:s,currentAuthor:i="user",projectId:r}){const[o,l]=a.useState(""),[c,u]=a.useState(null),[d,m]=a.useState(""),[h,f]=a.useState(!1),[p,g]=a.useState(null),b=a.useMemo(()=>[...e.comments||[]].sort((M,N)=>new Date(N.createdAt).getTime()-new Date(M.createdAt).getTime()),[e.comments]),v=o.length>Zm;async function x(){const M=o.trim();if(M){f(!0);try{const N=await oy(e.id,M,r);l(""),n?.(N),s("Comment added","success")}catch(N){s(ye(N)||"Failed to add comment","error")}finally{f(!1)}}}async function y(M){const N=d.trim();if(N){f(!0);try{const D=await ny(e.id,M,N,r);u(null),m(""),n?.(D),s("Comment updated","success")}catch(D){s(ye(D)||"Failed to update comment","error")}finally{f(!1)}}}async function k(M){g(M);try{const N=await sy(e.id,M,r);n?.(N),s("Comment deleted","success")}catch(N){s(ye(N)||"Failed to delete comment","error")}finally{g(null)}}function _(M){M.key==="Enter"&&(M.ctrlKey||M.metaKey)&&(M.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(M=>{const N=M.author===i,D=c===M.id,E=OM(M.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:[E?t.jsx("span",{className:"ai-guidance-badge","data-testid":"ai-guidance-badge",children:"AI Guidance"}):t.jsx("strong",{children:M.author}),t.jsx("span",{className:"detail-log-timestamp",children:FM(M)})]}),N&&!D?t.jsxs("div",{className:"comments-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{u(M.id),m(M.text)},children:"Edit"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void k(M.id),disabled:p===M.id,children:p===M.id?"Deleting…":"Delete"})]}):null]}),D?t.jsxs("div",{className:"comments-edit-form",children:[t.jsx("textarea",{value:d,onChange:T=>m(T.target.value),rows:3,className:"comments-textarea"}),t.jsxs("div",{className:"comments-edit-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{u(null),m("")},disabled:h,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void y(M.id),disabled:h||!d.trim(),children:"Save"})]})]}):t.jsx("div",{className:"detail-log-outcome comments-outcome-text",children:M.text})]},M.id)})}),t.jsxs("div",{className:"comments-compose-form",children:[t.jsx("textarea",{value:o,onChange:M=>l(M.target.value),onKeyDown:_,rows:3,placeholder:"Add a comment",className:"comments-textarea"}),t.jsxs("div",{className:"comments-footer-row",children:[t.jsxs("span",{className:`comments-char-count${v?" comments-char-count--over":""}`,children:[o.length," / ",Zm]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void x(),disabled:h||!o.trim()||v,children:h?"Posting…":"Add Comment"})]})]})]})}function BM(e){return e?e.slice(0,7):"Unknown"}function HM({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:BM(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 ng(e){return e.split(`
|
|
647
|
-
`).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}
|
|
648
|
-
`},i):t.jsx(vo.Fragment,{children:`${s}
|
|
649
|
-
`},i)})}function qM(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function VM({isOpen:e,taskId:n,files:s,stats:i,mergeDetails:r,column:o,onClose:l,onRefresh:c}){const[u,d]=a.useState(null),[m,h]=a.useState(!0),f=a.useRef(null);oi(f,e,"fusion:changes-diff-modal-size");const p=Ei(l);a.useEffect(()=>{s.length>0&&u===null&&d(0)},[s,u]);const g=a.useCallback(()=>{d(y=>y!==null&&y>0?y-1:y)},[]),b=a.useCallback(()=>{d(y=>y!==null&&y<s.length-1?y+1:y)},[]);if(a.useEffect(()=>{if(!e)return;const y=k=>{if(k.key==="Escape"){l();return}k.key==="ArrowUp"&&(k.metaKey||k.ctrlKey)&&(k.preventDefault(),g()),k.key==="ArrowDown"&&(k.metaKey||k.ctrlKey)&&(k.preventDefault(),b())};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[e,l,g,b]),!e)return null;const v=u!==null?s[u]:null,x=o==="done";return t.jsx("div",{className:"modal-overlay open",...p,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal changes-diff-modal",ref:f,children:[t.jsxs("div",{className:"modal-header changes-diff-modal-header",children:[t.jsxs("div",{className:"changes-diff-header-title",children:[t.jsx(Bs,{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(Fo,{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:b,disabled:u===null||u>=s.length-1,title:"Next file (Ctrl+↓)","aria-label":"Next file",children:t.jsx(vn,{size:14})})]}),t.jsx("button",{className:`btn btn-sm ${m?"btn-primary":""}`,onClick:()=>h(y=>!y),title:m?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(ko,{size:14})}),c&&t.jsxs("button",{className:"btn btn-sm",onClick:c,children:[t.jsx($n,{size:14}),"Refresh"]}),t.jsx("button",{className:"modal-close",onClick:l,"aria-label":"Close",children:t.jsx(Wt,{size:20})})]})]}),t.jsxs("div",{className:"changes-diff-body",children:[t.jsxs("div",{className:"changes-diff-sidebar",children:[x&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(Nr,{size:14}),t.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergeCommitMessage&&t.jsx("div",{className:"commit-diff-message",children:r.mergeCommitMessage}),r.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),t.jsx("div",{className:"changes-diff-file-list",children:s.map((y,k)=>t.jsxs("button",{className:`changes-diff-file-item ${u===k?"selected":""}`,onClick:()=>d(k),title:y.path,children:[t.jsx("span",{className:`changes-file-status changes-file-status--${y.status}`,children:qM(y.status)}),t.jsx("span",{className:"changes-diff-file-path",title:y.path,children:t.jsx("bdo",{dir:"ltr",children:y.path})}),t.jsxs("span",{className:"changes-diff-file-stat",children:["+",y.additions," -",y.deletions]})]},y.path))})]}),t.jsx("div",{className:"changes-diff-content",children:v?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"changes-diff-file-header-bar",children:[t.jsx("span",{className:"changes-diff-file-header-name",children:v.path}),t.jsxs("span",{className:"changes-diff-file-header-stats",children:["+",v.additions," -",v.deletions]})]}),v.patch?t.jsx("div",{className:"changes-diff-viewer",children:t.jsx("pre",{className:`changes-diff-patch ${m?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:t.jsx("code",{children:ng(v.patch)})})}):t.jsx("div",{className:"changes-diff-empty",children:"No diff available for this file."})]}):t.jsxs("div",{className:"changes-diff-empty",children:[t.jsx(Bs,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to view its diff"})]})})]})]})})}function sg(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function tc(e,n,s){return t.jsxs("div",{className:"detail-section task-changes-tab",children:[n&&s&&t.jsxs("div",{className:"commit-diff-meta",children:[s.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(Nr,{size:14}),t.jsx("code",{children:s.commitSha.slice(0,7)})]}),s.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(s.mergedAt).toLocaleString()]})]}),t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Bs,{size:24}),t.jsxs("p",{children:[e.length," file",e.length===1?"":"s"," modified during execution."]}),t.jsx("span",{className:"task-changes-state-hint",children:n?"The recorded merge commit has no diff (likely collapsed into a squash on main). Showing file paths only — patches unavailable.":"The live worktree diff is empty. Showing the last file paths captured during execution — patches unavailable."})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:e.map(i=>t.jsx("div",{className:"changes-file-item",children:t.jsxs("div",{className:"changes-file-header changes-file-header--static",children:[t.jsx("span",{className:"changes-file-status changes-file-status--unknown",title:"status unknown",children:sg("unknown")}),t.jsx("span",{className:"changes-file-path",title:i,children:t.jsx("bdo",{dir:"ltr",children:i})})]})},i))})]})}function WM({taskId:e,worktree:n,projectId:s,column:i,mergeDetails:r,modifiedFiles:o}){const[l,c]=a.useState([]),[u,d]=a.useState({filesChanged:0,additions:0,deletions:0}),[m,h]=a.useState(!0),[f,p]=a.useState(null),[g,b]=a.useState(new Set),[v,x]=a.useState(null),[y,k]=a.useState(!0),[_,S]=a.useState(!1),w=i==="done",M=w&&!!r?.commitSha,N=i==="in-progress"||i==="in-review"||M,D=a.useCallback(async()=>{if(!N){h(!1);return}try{h(!0),p(null);const $=await yp(e,void 0,s),R=$.files.map(z=>({path:z.path,status:z.status,additions:z.additions,deletions:z.deletions,patch:z.patch}));c(R),d($.stats),R.length>0&&(b(new Set([R[0].path])),x(0))}catch($){p(ye($)||"Failed to load diff")}finally{h(!1)}},[e,s,N]);a.useEffect(()=>{D()},[D]);const E=$=>{b(R=>{const z=new Set(R);if(z.has($))z.delete($);else{z.add($);const B=l.findIndex(J=>J.path===$);B!==-1&&x(B)}return z})},T=$=>{if($<0||$>=l.length)return;const R=l[$].path;b(new Set([R])),x($)},U=v!==null&&v>0,K=v!==null&&v<l.length-1;if(m)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--loading",children:[t.jsx("div",{className:"loading-spinner"}),t.jsx("span",{children:"Loading changes..."})]})});if(f)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--error",children:[t.jsx(us,{size:16}),t.jsxs("span",{children:["Error loading changes: ",f]})]})});if(!w&&!n)return o&&o.length>0?tc(o,!1):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Bs,{size:24}),t.jsx("p",{children:"No worktree available for this task."}),t.jsx("span",{className:"task-changes-state-hint",children:"Changes will be shown once the task is in progress."})]})});if(w&&!M){if(o&&o.length>0)return tc(o,!0,r);const $=r?.filesChanged,R=r?.insertions,z=r?.deletions,B=$!=null||R!=null||z!=null;return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Bs,{size:24}),t.jsx("p",{children:"Detailed file changes unavailable."}),t.jsx("span",{className:"task-changes-state-hint",children:B?`Merge summary: ${$??0} file${($??0)===1?"":"s"} changed, +${R??0} additions, -${z??0} deletions.`:"No merge commit was recorded for this task."})]})})}return l.length===0?o&&o.length>0?tc(o,w,r):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Bs,{size:24}),t.jsx("p",{children:"No files modified."}),t.jsx("span",{className:"task-changes-state-hint",children:w?"No file changes were recorded in the merge commit.":"The agent did not modify any files during execution."})]})}):t.jsxs("div",{className:"detail-section task-changes-tab",children:[w&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(Nr,{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(Bs,{size:16}),"Files Changed (",u.filesChanged,")"]}),t.jsxs("span",{className:"task-changes-stats changes-stat-summary",children:[t.jsxs("span",{className:"diff-add",children:["+",u.additions]})," ",t.jsxs("span",{className:"diff-del",children:["-",u.deletions]})]})]}),t.jsxs("div",{className:"changes-header-actions-wrapper",children:[t.jsxs("div",{className:"changes-header-actions",children:[l.length>0&&t.jsxs("div",{className:"changes-nav",children:[t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>U&&T(v-1),disabled:!U,title:"Previous file","aria-label":"Previous file",children:t.jsx(Fo,{size:14})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:v!==null?`${v+1}/${l.length}`:`—/${l.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>K&&T(v+1),disabled:!K,title:"Next file","aria-label":"Next file",children:t.jsx(vn,{size:14})})]}),t.jsx("button",{className:`btn btn-sm ${y?"btn-primary":""}`,onClick:()=>k($=>!$),title:y?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(ko,{size:14})})]}),t.jsxs("div",{className:"changes-header-actions-secondary",children:[t.jsx("button",{className:"btn btn-sm",onClick:D,disabled:m,children:"Refresh"}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>S(!0),title:"Expand to full-screen diff view","aria-label":"Expand diff view",children:t.jsx(qo,{size:14})})]})]})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:l.map($=>{const R=g.has($.path);return t.jsxs("div",{className:`changes-file-item ${R?"expanded":""}`,children:[t.jsxs("button",{className:"changes-file-header",onClick:()=>E($.path),children:[t.jsx("span",{className:"changes-file-toggle",children:R?t.jsx(Xt,{size:14}):t.jsx(vn,{size:14})}),t.jsx("span",{className:`changes-file-status changes-file-status--${$.status}`,title:$.status,children:sg($.status)}),t.jsx("span",{className:"changes-file-path",title:$.path,children:t.jsx("bdo",{dir:"ltr",children:$.path})}),t.jsxs("span",{className:"changes-file-stat",title:`+${$.additions} -${$.deletions}`,children:["+",$.additions," -",$.deletions]})]}),R&&$.patch&&t.jsx("div",{className:"changes-file-content",children:t.jsx("pre",{className:`changes-diff-patch ${y?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:t.jsx("code",{children:ng($.patch)})})})]},$.path)})}),t.jsx(VM,{isOpen:_,taskId:e,files:l,stats:u,mergeDetails:r,column:i,onClose:()=>S(!1),onRefresh:D})]})}function eh(e){return{executorValue:e?.executorProvider&&e?.executorModelId?`${e.executorProvider}/${e.executorModelId}`:"",validatorValue:e?.validatorProvider&&e?.validatorModelId?`${e.validatorProvider}/${e.validatorModelId}`:""}}function KM(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function wL(e,n){const s=KM(e),i=new Set(n.map(c=>c.id));if(!i.has(s))return s;const r=30;let o=s,l=1;for(;i.has(o)&&l<100;){const c=`-${l}`;o=`${s.slice(0,r-c.length)}${c}`,l++}return o}function GM(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}const th=["image/png","image/jpeg","image/gif","image/webp"];function JM(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 ig({mode:e,description:n,onDescriptionChange:s,title:i,onTitleChange:r,dependencies:o,onDependenciesChange:l,nodeId:c,onNodeIdChange:u,nodeOptions:d,nodeOverrideDisabled:m=!1,nodeOverrideDisabledReason:h,priority:f,onPriorityChange:p,executorModel:g,onExecutorModelChange:b,validatorModel:v,onValidatorModelChange:x,planningModel:y,onPlanningModelChange:k,thinkingLevel:_,onThinkingLevelChange:S,presetMode:w,onPresetModeChange:M,selectedPresetId:N,onSelectedPresetIdChange:D,selectedWorkflowSteps:E,onWorkflowStepsChange:T,onDefaultOnApplied:U,pendingImages:K,onImagesChange:$,tasks:R,projectId:z,disabled:B=!1,addToast:J,isActive:Q=!0,onAutoSaveDescription:C,onPlanningMode:L,onSubtaskBreakdown:P,onClose:j,renderBelowPrimary:O,renderBelowModelConfiguration:H,hideDependencies:ge,autoExpandMoreOptionsOnSelection:be=!0,reviewLevel:se,onReviewLevelChange:me,executionMode:F,onExecutionModeChange:de}){const ne=(ge?!1:o.length>0)||K.length>0||E.length>0||w!=="default"||(f??ws)!==ws||g!==""||v!==""||(y||"")!==""||(_||"")!==""||se!==void 0||F==="fast"||(c||"")!=="",[xe,oe]=a.useState(!1),[he,ae]=a.useState(be?ne:!1),[je,Ae]=a.useState(""),[Oe,Qe]=a.useState([]),[Xe,Ye]=a.useState([]),[it,Be]=a.useState([]),[Ge,re]=a.useState(!1),[ke,X]=a.useState(null),[Te,Le]=a.useState([]),[fe,_e]=a.useState("idle"),[Ue,nt]=a.useState(!1),[ve,ce]=a.useState(!1),[De,ue]=a.useState(!1),Re=a.useRef(null),Ke=a.useRef(null),Pe=a.useRef(null),ft=a.useRef(null),Z=a.useRef(null),le=a.useRef(null),we=a.useRef(null),Ze=a.useRef(!1),te=a.useRef(ne),Je=a.useRef(n.trim()),dt=a.useRef(n.trim());a.useEffect(()=>{Q&&(re(!0),ms().then(A=>{Qe(A.models),Ye(A.favoriteProviders),Be(A.favoriteModels)}).catch(()=>{}).finally(()=>re(!1)),Wo(z).then(A=>X(A)).catch(()=>X(null)),Ko(z).then(A=>Le(A.filter(ee=>ee.enabled))).catch(()=>Le([])))},[Q,z]);const ut=ke?.modelPresets||[],Ct=ut.find(A=>A.id===N),yt=(ge?!1:o.length>0)||K.length>0||E.length>0||w!=="default"||(f??ws)!==ws||g!==""||v!==""||(y||"")!==""||(_||"")!==""||se!==void 0||F==="fast"||(c||"")!=="";a.useEffect(()=>{if(e!=="create"||!Q||!ke?.autoSelectModelPreset)return;const A=(ke.defaultPresetBySize,void 0);if(A){const ee=eh(A);D(A.id),M("preset"),b(ee.executorValue),x(ee.validatorValue)}},[Q,ke,ut,e]);const bt=a.useRef(!1);a.useEffect(()=>{if(e!=="create"||!Q||bt.current||Te.length===0)return;const A=Te.filter(ze=>ze.defaultOn);if(A.length===0)return;bt.current=!0;const ee=A.map(ze=>ze.id);T(ee),U?.(ee)},[e,Q,Te]),a.useEffect(()=>{Q||(bt.current=!1)},[Q]),a.useEffect(()=>{if(!be){te.current=yt;return}yt&&!te.current&&ae(!0),te.current=yt},[yt,be]),a.useEffect(()=>{he||(oe(!1),Ae(""))},[he]),a.useEffect(()=>{e!=="edit"||!Q||ft.current&&(ft.current.focus(),ft.current.select())},[e,Q]),a.useEffect(()=>{if(!xe)return;const A=ee=>{Ke.current&&!Ke.current.contains(ee.target)&&oe(!1)};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[xe]),a.useEffect(()=>{(e!=="edit"||B)&&ue(!1)},[e,B]),a.useEffect(()=>{if(e!=="edit"){_e("idle");return}const A=n.trim();Je.current=A,dt.current=A,_e("idle")},[e]),a.useEffect(()=>{if(e!=="edit"||!C||!Q)return;const A=n.trim(),ee=Je.current;if(A===ee||A===dt.current){le.current&&(clearTimeout(le.current),le.current=null),Ze.current||_e("idle");return}return le.current&&clearTimeout(le.current),le.current=setTimeout(async()=>{if(!Ze.current){Ze.current=!0,_e("saving");try{await C(A),dt.current=A,_e("saved"),we.current&&clearTimeout(we.current),we.current=setTimeout(()=>{_e("idle"),we.current=null},2e3)}catch{_e("idle")}finally{Ze.current=!1,le.current=null}}},1500),()=>{le.current&&(clearTimeout(le.current),le.current=null)}},[e,n,C,Q]),a.useEffect(()=>()=>{le.current&&clearTimeout(le.current),we.current&&clearTimeout(we.current)},[]),a.useEffect(()=>{if(!Ue)return;const A=ee=>{Re.current&&!Re.current.contains(ee.target)&&nt(!1)};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[Ue]);const At=a.useCallback(A=>{const ee=A.clipboardData?.items;if(ee)for(let ze=0;ze<ee.length;ze++){const mt=ee[ze];if(mt.type.startsWith("image/")){const jt=mt.getAsFile();if(jt&&th.includes(jt.type)){A.preventDefault(),$([...K,{file:jt,previewUrl:URL.createObjectURL(jt)}]);return}}}},[K,$]),Rt=a.useCallback(A=>{A.preventDefault();const ee=A.dataTransfer.files;for(let ze=0;ze<ee.length;ze++){const mt=ee[ze];if(th.includes(mt.type)){$([...K,{file:mt,previewUrl:URL.createObjectURL(mt)}]);return}}},[K,$]),Ht=a.useCallback(A=>{const ee=K[A];ee&&URL.revokeObjectURL(ee.previewUrl),$(K.filter((ze,mt)=>mt!==A))},[K,$]),Et=a.useCallback(A=>{l(o.includes(A)?o.filter(ee=>ee!==A):[...o,A])},[o,l]),Dt=(A,ee)=>A.length>ee?A.slice(0,ee)+"…":A,Kt=a.useCallback(A=>{s(A.target.value);const ee=A.target;ee.style.height="auto",ee.style.height=ee.scrollHeight+"px"},[s]),$t=a.useCallback(()=>{ue(A=>!A)},[]),Ft=a.useCallback(A=>{!De||A.key!=="Escape"||(A.preventDefault(),A.stopPropagation(),ue(!1))},[De]),Ot=a.useCallback(async A=>{const ee=n.trim();if(!(!ee||ve)){ce(!0);try{const ze=await fp(ee,A,z);s(ze),nt(!1),J("Description refined with AI","success"),Pe.current&&(Pe.current.style.height="auto",Pe.current.style.height=Pe.current.scrollHeight+"px")}catch(ze){const mt=gp(ze);J(mt,"error")}finally{ce(!1)}}},[n,ve,J,s,z]),Tt=a.useCallback(async A=>{const ee=Xe,mt=ee.includes(A)?ee.filter(jt=>jt!==A):[A,...ee];Ye(mt);try{await hn({favoriteProviders:mt,favoriteModels:it})}catch{Ye(ee)}},[Xe,it]),Pt=a.useCallback(async A=>{const ee=it,mt=ee.includes(A)?ee.filter(jt=>jt!==A):[A,...ee];Be(mt);try{await hn({favoriteProviders:Xe,favoriteModels:mt})}catch{Be(ee)}},[it,Xe]),wt=a.useCallback(A=>{if(A<=0)return;const ee=[...E];[ee[A-1],ee[A]]=[ee[A],ee[A-1]],T(ee)},[E,T]),Gt=a.useCallback(A=>{if(A>=E.length-1)return;const ee=[...E];[ee[A],ee[A+1]]=[ee[A+1],ee[A]],T(ee)},[E,T]),Ut=a.useCallback(A=>{T(E.filter(ee=>ee!==A))},[E,T]),q=new Map;for(const A of Te)q.set(A.id,{name:A.name,description:A.description});const pe=R.filter(A=>!o.includes(A.id)).sort((A,ee)=>{const ze=ee.createdAt.localeCompare(A.createdAt);if(ze!==0)return ze;const mt=parseInt(A.id.slice(A.id.lastIndexOf("-")+1),10)||0;return(parseInt(ee.id.slice(ee.id.lastIndexOf("-")+1),10)||0)-mt}),$e=je?pe.filter(A=>A.id.toLowerCase().includes(je.toLowerCase())||A.title&&A.title.toLowerCase().includes(je.toLowerCase())||A.description&&A.description.toLowerCase().includes(je.toLowerCase())):pe;return t.jsxs("div",{className:"task-form",onDrop:Rt,onDragOver:A=>A.preventDefault(),onPaste:At,children:[t.jsxs("div",{className:"task-form-primary-section",children:[e==="edit"&&r&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"task-form-title",children:"Title"}),t.jsx("input",{ref:ft,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:"Task title",value:i||"",onChange:A=>r(A.target.value),disabled:B})]}),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${fe==="idle"?"":" is-visible"}`,"aria-live":"polite",children:fe==="saving"?"Saving...":fe==="saved"?"Saved":""})]}),t.jsxs("div",{className:`description-with-refine${De?" description--fullscreen":""}`,ref:Re,onKeyDown:Ft,children:[De&&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:$t,"aria-label":"Collapse description",title:"Collapse description",children:t.jsx(Sr,{size:14})})]}),t.jsx("textarea",{ref:Pe,autoFocus:e==="create",id:"task-form-description",value:n,onChange:Kt,placeholder:"What needs to be done?",rows:e==="edit"?8:5,disabled:B||ve}),(()=>{const A=!!n.trim()&&!B;return t.jsxs(t.Fragment,{children:[!De&&t.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${A?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:$t,"aria-label":"Expand description",title:"Expand description",children:t.jsx(qo,{size:14})}),A&&t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${ve?"refine-button--loading":""}`,onClick:()=>nt(ee=>!ee),disabled:ve,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(rs,{size:12,style:{verticalAlign:"middle"}}),ve?"Refining...":"Refine"]})]})})(),Ue&&t.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:A=>A.preventDefault(),children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>Ot("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:()=>Ot("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:()=>Ot("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:()=>Ot("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"&&(L||P)&&t.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[L&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const A=n.trim();if(!A){J("Enter a description first","error");return}j?.(),L(A)},disabled:B||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),P&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const A=n.trim();if(!A){J("Enter a description first","error");return}j?.(),P(A)},disabled:B||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),O,t.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>ae(A=>!A),"aria-expanded":he,"aria-controls":"task-form-more-options",disabled:B,"data-testid":"task-form-more-options-toggle",children:[t.jsx("span",{children:"More options"}),he?t.jsx(pi,{size:14}):t.jsx(Xt,{size:14})]}),t.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${he?"":" collapsed"}`,"aria-hidden":!he,hidden:!he,"data-testid":"task-form-more-options",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Attachments"}),K.length>0&&t.jsx("div",{className:"inline-create-previews",children:K.map((A,ee)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:A.previewUrl,alt:A.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>Ht(ee),disabled:B,title:"Remove image",children:"×"})]},A.previewUrl))}),t.jsx("input",{ref:Z,type:"file",accept:"image/*",onChange:A=>{const ee=A.target.files?.[0];ee&&($([...K,{file:ee,previewUrl:URL.createObjectURL(ee)}]),A.target.value="")},style:{display:"none"}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>Z.current?.click(),disabled:B,children:"Attach Screenshot"}),t.jsx("small",{children:"You can also paste images or drag & drop"})]}),u&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"task-node-select",children:"Execution Node Override"}),t.jsxs("select",{id:"task-node-select",className:"select",value:c??"",onChange:A=>u(A.target.value||void 0),disabled:B||m,children:[t.jsx("option",{value:"",children:"Use project default / local"}),(d??[]).map(A=>t.jsxs("option",{value:A.id,children:[A.name," (",GM(A.status),")"]},A.id))]}),(()=>{const A=(d??[]).find(ee=>ee.id===c);return A?t.jsx("div",{className:"task-form-node-status",children:t.jsx(qi,{status:A.status,showLabel:!0})}):null})(),t.jsx("small",{children:h??"Task override takes priority over project default node routing."})]}),!ge&&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:Ke,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>oe(A=>!A),disabled:B,children:o.length>0?`${o.length} selected`:"Add dependencies"}),xe&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:je,onChange:A=>Ae(A.target.value),onClick:A=>A.stopPropagation()}),$e.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):$e.map(A=>t.jsxs("div",{className:`dep-dropdown-item${o.includes(A.id)?" selected":""}`,onClick:()=>Et(A.id),onMouseDown:ee=>ee.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:A.id}),t.jsx("span",{className:"dep-dropdown-title",children:Dt(A.title||A.description||A.id,30)})]},A.id))]})]}),o.length>0&&t.jsx("div",{className:"selected-deps",children:o.map(A=>t.jsxs("span",{className:"dep-chip",children:[A,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>Et(A),disabled:B,children:"×"})]},A))})]})}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Model Configuration"}),p&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"task-priority",className:"model-select-label",children:"Priority"}),t.jsx("select",{id:"task-priority","data-testid":"task-priority-select",value:f??ws,onChange:A=>p(A.target.value),disabled:B,children:md.map(A=>t.jsx("option",{value:A,children:A[0].toUpperCase()+A.slice(1)},A))})]}),de&&F!==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:F,onChange:A=>de(A.target.value),disabled:B,children:[t.jsx("option",{value:"standard",children:"Standard"}),t.jsx("option",{value:"fast",children:"Fast"})]})]}),Ge?t.jsx("div",{className:"model-selector-loading",children:"Loading models…"}):Oe.length===0?t.jsx("small",{children:"No models available. Configure authentication in Settings."}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"model-preset",className:"model-select-label",children:"Preset"}),t.jsxs("select",{id:"model-preset",value:w==="preset"?N:w,onChange:A=>{const ee=A.target.value;if(ee==="default"){M("default"),D(""),b(""),x("");return}if(ee==="custom"){M("custom"),D("");return}const ze=ut.find(jt=>jt.id===ee),mt=eh(ze);M("preset"),D(ee),b(mt.executorValue),x(mt.validatorValue)},disabled:B,children:[t.jsx("option",{value:"default",children:"Use default"}),ut.length>0?t.jsx("option",{disabled:!0,children:"──────────"}):null,ut.map(A=>t.jsx("option",{value:A.id,children:A.name},A.id)),t.jsx("option",{value:"custom",children:"Custom"})]})]}),w==="preset"&&Ct?t.jsxs("small",{children:["Using preset: ",Ct.name]}):null,w==="preset"?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>M("custom"),disabled:B,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(Yn,{id:"executor-model",label:"Executor Model",value:g,onChange:A=>{M("custom"),D(""),b(A)},models:Oe,disabled:B||w==="preset",favoriteProviders:Xe,onToggleFavorite:Tt,favoriteModels:it,onToggleModelFavorite:Pt})]}),t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"validator-model",className:"model-select-label",children:"Reviewer"}),t.jsx(Yn,{id:"validator-model",label:"Reviewer Model",value:v,onChange:A=>{M("custom"),D(""),x(A)},models:Oe,disabled:B||w==="preset",favoriteProviders:Xe,onToggleFavorite:Tt,favoriteModels:it,onToggleModelFavorite:Pt})]}),k&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"planning-model",className:"model-select-label",children:"Planning"}),t.jsx(Yn,{id:"planning-model",label:"Planning Model",value:y||"",onChange:A=>{M("custom"),D(""),k(A)},models:Oe,disabled:B||w==="preset",favoriteProviders:Xe,onToggleFavorite:Tt,favoriteModels:it,onToggleModelFavorite:Pt})]}),S&&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:_||"",onChange:A=>S(A.target.value),disabled:B||w==="preset",children:[t.jsxs("option",{value:"",children:["Default (",ke?.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"})]})]}),me&&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:se??"",onChange:A=>me(A.target.value===""?void 0:parseInt(A.target.value,10)),disabled:B,children:[t.jsx("option",{value:"",children:"Default (Auto — triage decides)"}),t.jsx("option",{value:"0",children:"0 — None"}),t.jsx("option",{value:"1",children:"1 — Plan Only"}),t.jsx("option",{value:"2",children:"2 — Plan and Code"}),t.jsx("option",{value:"3",children:"3 — Full"})]})]})]})]}),H,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:Te.length>0&&Te.map(A=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${A.id}`,children:[t.jsx("input",{type:"checkbox",checked:E.includes(A.id),onChange:ee=>{T(ee.target.checked?[...E,A.id]:E.filter(ze=>ze!==A.id))},disabled:B}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[A.name,JM(A.phase||"pre-merge",A.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:A.description})]})]},A.id))})]}),E.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),E.map((A,ee)=>{const ze=q.get(A);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${A}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:ee+1}),t.jsx("span",{className:"workflow-step-order-name",children:ze?.name||A}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>wt(ee),disabled:B||ee===0,"data-testid":`workflow-step-move-up-${A}`,title:"Move up",children:t.jsx(pi,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Gt(ee),disabled:B||ee===E.length-1,"data-testid":`workflow-step-move-down-${A}`,title:"Move down",children:t.jsx(Xt,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Ut(A),disabled:B,"data-testid":`workflow-step-remove-${A}`,title:"Remove",children:t.jsx(Wt,{size:14})})]})]},A)})]})]})]})]})}const nh={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 YM(e){switch(e){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return e}}function QM(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 XM(e){return e?new Date(e).toLocaleString():null}function ZM(e){const n=e.split(`
|
|
650
|
-
`);return n.length<=1?e:`${n.length} lines`}function oo(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 eA({entries:e,startedAt:n,stepId:s}){const i=a.useRef(null),r=new Date(n).getTime(),o=e.filter(l=>new Date(l.timestamp).getTime()>=r);return a.useEffect(()=>{const l=i.current;l&&(l.scrollTop=l.scrollHeight)},[o.length]),e.length===0?t.jsx("div",{className:"workflow-live-log","data-testid":`workflow-live-log-${s}`,children:t.jsx("div",{className:"workflow-live-log-empty",children:"Waiting for agent output…"})}):t.jsx("div",{ref:i,className:"workflow-live-log","data-testid":`workflow-live-log-${s}`,children:o.map((l,c)=>l.type==="tool"?t.jsxs("div",{className:"workflow-live-log-tool",children:["⚡ ",l.text,l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",l.detail]})]},c):l.type==="tool_result"?t.jsxs("div",{className:"workflow-live-log-tool-result",children:["✓ ",l.text,l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",l.detail]})]},c):l.type==="tool_error"?t.jsxs("div",{className:"workflow-live-log-tool-error",children:["✗ ",l.text,l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",l.detail]})]},c):l.type==="thinking"?t.jsx("div",{className:"workflow-live-log-thinking",children:l.text},c):t.jsx("span",{className:"workflow-live-log-text",children:l.text},c))})}function tA({taskId:e,results:n,loading:s,enabledWorkflowSteps:i,canEdit:r,projectId:o,isTaskInProgress:l,onWorkflowStepsChange:c}){const[u,d]=a.useState({}),[m,h]=a.useState({}),[f,p]=a.useState(null),[g,b]=a.useState([]),[v,x]=a.useState(!1),y=n.some(j=>j.status==="pending"),{entries:k}=eg(e,!!l&&y,o);a.useEffect(()=>{let j=!1;return Ko(o).then(O=>{j||b(O.filter(H=>H.enabled))}).catch(()=>{j||b([])}),()=>{j=!0}},[o]);const _=i??[],S=a.useMemo(()=>g.map(j=>({id:j.id,name:j.name,description:j.description,phase:j.phase||"pre-merge"})),[g]),w=a.useMemo(()=>new Map(S.map(j=>[j.id,j])),[S]),M=j=>{d(O=>({...O,[j]:!O[j]}))},N=j=>{h(O=>{const H=O[j]??"markdown";return{...O,[j]:H==="markdown"?"plain":"markdown"}})},D=j=>{p(j)},E=()=>{p(null)};a.useEffect(()=>{if(!f)return;const j=O=>{O.key==="Escape"&&E()};return document.addEventListener("keydown",j),()=>{document.removeEventListener("keydown",j)}},[f]);const T=a.useCallback((j,O)=>{if(c){if(O){if(_.includes(j)){c(_);return}c([..._,j]);return}c(_.filter(H=>H!==j))}},[c,_]),U=a.useCallback(j=>{if(!c||j<=0)return;const O=[..._];[O[j-1],O[j]]=[O[j],O[j-1]],c(O)},[c,_]),K=a.useCallback(j=>{if(!c||j>=_.length-1)return;const O=[..._];[O[j],O[j+1]]=[O[j+1],O[j]],c(O)},[c,_]),$=a.useCallback(j=>{c&&c(_.filter(O=>O!==j))},[c,_]),R=n.length>0,z=_.length>0;a.useEffect(()=>{r||x(!1)},[r]);const B=a.useMemo(()=>_.map(j=>{const O=w.get(j);return{id:j,name:O?.name||j,description:O?.description||"Step definition not found.",phase:O?.phase||"pre-merge"}}),[_,w]),J=()=>!r||!v||s?null:t.jsxs("div",{className:"workflow-results-editor","data-testid":"workflow-steps-editor",children:[t.jsxs("div",{className:"workflow-steps-section",children:[t.jsx("small",{className:"workflow-steps-description",children:"Select steps to run after task implementation completes"}),t.jsx("div",{className:"workflow-steps-list",children:S.map(j=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${j.id}`,children:[t.jsx("input",{type:"checkbox",checked:_.includes(j.id),onChange:O=>T(j.id,O.target.checked)}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[j.name,oo(j.phase,j.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:j.description})]})]},j.id))})]}),_.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),_.map((j,O)=>{const H=w.get(j);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${j}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:O+1}),t.jsx("span",{className:"workflow-step-order-name",children:H?.name||j}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>U(O),disabled:O===0,"data-testid":`workflow-step-move-up-${j}`,title:"Move up",children:t.jsx(pi,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>K(O),disabled:O===_.length-1,"data-testid":`workflow-step-move-down-${j}`,title:"Move down",children:t.jsx(Xt,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>$(j),"data-testid":`workflow-step-remove-${j}`,title:"Remove",children:t.jsx(Wt,{size:14})})]})]},j)})]})]}),Q=()=>{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(!R)return t.jsxs("div",{className:"workflow-results-empty","data-testid":"workflow-results-empty",children:[t.jsx("p",{children:"No workflow steps configured for this task."}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."})]});const j=n.filter(se=>se.status==="passed").length,O=n.filter(se=>se.status==="failed").length,H=n.filter(se=>se.status==="skipped").length,ge=n.filter(se=>se.status==="pending").length,be=[`${n.length} step${n.length!==1?"s":""}`];return j>0&&be.push(`${j} passed`),O>0&&be.push(`${O} failed`),H>0&&be.push(`${H} skipped`),ge>0&&be.push(`${ge} running`),t.jsxs("div",{className:"workflow-results-list","data-testid":"workflow-results-list",children:[t.jsx("div",{className:"workflow-results-summary-bar","data-testid":"workflow-results-summary",children:be.join(" · ")}),n.map((se,me)=>{const F=se.phase||"pre-merge",de=u[se.workflowStepId]??!1;return t.jsxs("div",{className:`workflow-result-item workflow-result-item--${se.status}`,"data-testid":`workflow-result-item-${se.workflowStepId}`,children:[t.jsxs("div",{className:"workflow-result-header",children:[t.jsxs("div",{className:"workflow-result-name",children:[se.workflowStepName,oo(F,se.workflowStepId,"workflow-result-phase")]}),t.jsx("span",{className:`workflow-result-badge workflow-result-badge--${se.status}`,"data-testid":`workflow-result-badge-${se.workflowStepId}`,children:YM(se.status)})]}),t.jsxs("div",{className:"workflow-result-meta",children:[se.startedAt&&t.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",XM(se.startedAt)]}),se.completedAt&&t.jsx("span",{className:"workflow-result-duration",children:QM(se.startedAt,se.completedAt)})]}),se.status==="pending"&&se.startedAt?t.jsx(eA,{entries:k,startedAt:se.startedAt,stepId:se.workflowStepId}):se.output?t.jsxs("div",{className:"workflow-result-output-section",children:[t.jsxs("div",{className:"workflow-result-output-header",children:[t.jsx("span",{className:"workflow-result-output-label",children:"Output:"}),t.jsx("button",{className:"workflow-result-toggle",onClick:()=>M(se.workflowStepId),"data-testid":`workflow-result-toggle-${se.workflowStepId}`,children:de?"Hide output":"Show output"}),!de&&t.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${se.workflowStepId}`,children:ZM(se.output)}),de&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>N(se.workflowStepId),"data-testid":`workflow-result-mode-toggle-${se.workflowStepId}`,title:(m[se.workflowStepId]??"markdown")==="markdown"?"Switch to plain text":"Switch to markdown",children:(m[se.workflowStepId]??"markdown")==="markdown"?"Markdown":"Plain"}),t.jsx("button",{className:"workflow-result-expand-toggle",onClick:()=>D(se.workflowStepId),"data-testid":`workflow-result-expand-${se.workflowStepId}`,title:"Expand output",children:t.jsx(qo,{size:12})})]})]}),de&&t.jsx("div",{className:`workflow-result-output${(m[se.workflowStepId]??"markdown")==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":`workflow-result-output-${se.workflowStepId}`,children:(m[se.workflowStepId]??"markdown")==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(ai,{remarkPlugins:[ri],components:nh,children:se.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:se.output})})]}):null]},`${se.workflowStepId}-${me}`)})]})},C=r?t.jsx("button",{type:"button",className:"modal-edit-btn workflow-results-edit-toggle",onClick:()=>x(j=>!j),"data-testid":"workflow-steps-edit-toggle","aria-label":v?"Done editing workflow steps":"Edit workflow steps",title:v?"Done":"Edit",children:v?t.jsxs(t.Fragment,{children:[t.jsx(Hn,{size:14}),"Done"]}):t.jsxs(t.Fragment,{children:[t.jsx(cs,{size:14}),"Edit"]})}):null,L=!s&&!R&&z,P=r&&R;return t.jsxs("div",{className:"workflow-results-tab","data-task-id":e,children:[L?t.jsxs("div",{className:"workflow-configured-steps","data-testid":"workflow-configured-steps",children:[t.jsxs("div",{className:"workflow-configured-header","data-testid":"workflow-configured-header",children:[t.jsxs("div",{className:"workflow-configured-title-row",children:[t.jsx("h4",{children:"Configured Workflow Steps"}),t.jsxs("span",{className:"workflow-configured-count","data-testid":"workflow-configured-count",children:[B.length," step",B.length===1?"":"s"]})]}),C]}),t.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:B.map(j=>t.jsxs("div",{className:"workflow-configured-item","data-testid":`workflow-configured-step-${j.id}`,children:[t.jsxs("div",{className:"workflow-configured-name",children:[j.name,oo(j.phase,j.id,"workflow-configured-phase")]}),t.jsx("p",{className:"workflow-configured-description",children:j.description})]},j.id))}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."}),J()]}):t.jsxs(t.Fragment,{children:[P&&t.jsxs("div",{className:"workflow-results-edit-header","data-testid":"workflow-results-edit-header",children:[t.jsx("h4",{children:"Workflow Steps"}),C]}),Q(),J()]}),f&&(()=>{const j=n.find(ge=>ge.workflowStepId===f);if(!j)return null;const O=m[j.workflowStepId]??"markdown",H=j.phase||"pre-merge";return t.jsx("div",{className:"workflow-output-modal-overlay",onClick:ge=>{ge.target===ge.currentTarget&&E()},"data-testid":"workflow-output-modal",children:t.jsxs("div",{className:"workflow-output-modal",role:"dialog","aria-modal":"true",children:[t.jsxs("div",{className:"workflow-output-modal-header",children:[t.jsxs("div",{className:"workflow-output-modal-title",children:[t.jsx("span",{className:"workflow-output-modal-name",children:j.workflowStepName}),oo(H,j.workflowStepId,"workflow-output-modal-phase")]}),t.jsxs("div",{className:"workflow-output-modal-controls",children:[t.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>N(j.workflowStepId),"data-testid":"workflow-output-modal-mode-toggle",title:O==="markdown"?"Switch to plain text":"Switch to markdown",children:O==="markdown"?"Markdown":"Plain"}),t.jsx("button",{className:"workflow-output-modal-close",onClick:E,"data-testid":"workflow-output-modal-close","aria-label":"Close",children:t.jsx(Wt,{size:16})})]})]}),t.jsx("div",{className:"workflow-output-modal-body",children:t.jsx("div",{className:`workflow-result-output workflow-result-output--expanded${O==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":"workflow-output-modal-content",children:O==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(ai,{remarkPlugins:[ri],components:nh,children:j.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:j.output})})})]})})})()]})}function nA(e){return e==="block"?"Block execution":e==="fallback-local"?"Fall back to local":"Not configured"}const sA=new Set(["planning","researching","executing","finalizing","merging"]);function iA(e){return e!==void 0&&e!=="online"}function aA({task:e,settings:n,addToast:s,onTaskUpdated:i}){const[r,o]=a.useState([]),[l,c]=a.useState(!1),[u,d]=a.useState(null),[m,h]=a.useState(e.nodeId??""),[f,p]=a.useState(!1),g=a.useRef(e.id);a.useEffect(()=>{g.current=e.id,h(e.nodeId??""),p(!1)},[e.id,e.nodeId]),a.useEffect(()=>{c(!0),d(null),So().then(E=>{o(E)}).catch(E=>{d(ye(E)||"Failed to load nodes")}).finally(()=>{c(!1)})},[]);const b=a.useMemo(()=>new Map(r.map(E=>[E.id,E])),[r]),v=a.useMemo(()=>[...r].sort((E,T)=>E.name.localeCompare(T.name)),[r]),x=n,y=e.nodeId??x?.defaultNodeId??null,k=e.nodeId?"Per-task override":x?.defaultNodeId?"Project default":"No routing",_=y?b.get(y):void 0,S=_?`${_.name} (${_.type})`:y?`${y} (node unavailable or unknown)`:"Local (no routing configured)",w=e.column==="in-progress"||sA.has(e.status),M=w||f||l,N=a.useCallback(async E=>{if(E===m)return;const T=e.id,U=m;h(E),p(!0);try{const K=await ni(T,{nodeId:E||null});if(g.current!==T)return;h(K.nodeId??""),i?.(K),s(E?"Node override updated":"Node override cleared","success")}catch(K){if(g.current!==T)return;h(U),s(ye(K)||"Failed to update node override","error")}finally{g.current===T&&p(!1)}},[s,i,m,e.id]),D=a.useCallback(()=>{N("")},[N]);return t.jsxs("div",{className:"routing-tab",children:[t.jsx("h4",{children:"Task Routing"}),t.jsx("p",{className:"routing-tab__intro",children:"View the effective execution node and control per-task node override."}),t.jsxs("section",{className:"routing-tab__section",children:[t.jsx("h5",{children:"Routing Summary"}),t.jsxs("div",{className:"routing-summary-grid",role:"list",children:[t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Effective node"}),t.jsxs("span",{className:"routing-summary-value",children:[_?t.jsx(qi,{status:_.status,compact:!0}):null,S,iA(_?.status)?t.jsx("span",{className:"routing-summary-warning",children:"Unhealthy"}):null]})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Routing source"}),t.jsx("span",{className:"routing-summary-value",children:k})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Unavailable-node policy"}),t.jsx("span",{className:"routing-summary-value",children:nA(x?.unavailableNodePolicy)})]})]}),w&&y?t.jsx("div",{className:"routing-tab__info-banner",children:"Routing is locked while this task is active. Node override cannot be changed until the task is no longer active."}):null]}),t.jsxs("section",{className:"routing-tab__section",children:[t.jsx("h5",{children:"Node Override"}),w?t.jsx("div",{className:"routing-tab__warning-banner",children:"Node override cannot be changed while the task is active."}):null,t.jsx("label",{className:"routing-tab__selector-label",htmlFor:`routing-node-${e.id}`,children:"Select execution node"}),t.jsxs("select",{id:`routing-node-${e.id}`,className:"select routing-tab__selector",value:m,disabled:M,onChange:E=>{N(E.target.value)},children:[t.jsx("option",{value:"",children:"Use project default"}),v.map(E=>t.jsxs("option",{value:E.id,title:`Status: ${E.status}`,children:[E.name," (",E.type,") — ",E.status]},E.id))]}),u?t.jsx("div",{className:"routing-tab__error",children:u}):null,e.nodeId?t.jsxs("div",{className:"routing-tab__override-row",children:[t.jsxs("span",{className:"routing-tab__override-text",children:["Override set to: ",b.get(e.nodeId)?.name??e.nodeId]}),t.jsx("button",{type:"button",className:"btn btn-sm",disabled:w||f,onClick:D,children:"Clear override"})]}):null]})]})}const rA=/^[a-zA-Z0-9_-]{1,64}$/,oA=200;function sh(e){return e?new Date(e).toLocaleString():""}function lA(e,n=oA){return e.length<=n?e:e.substring(0,n)+"…"}function cA({taskId:e,addToast:n,onTaskUpdated:s,projectId:i,canEdit:r=!1}){const[o,l]=a.useState([]),[c,u]=a.useState(!0),[d,m]=a.useState(null),[h,f]=a.useState(""),[p,g]=a.useState(null),[b,v]=a.useState(""),[x,y]=a.useState(null),[k,_]=a.useState([]),[S,w]=a.useState(!1),[M,N]=a.useState(!1),[D,E]=a.useState(""),[T,U]=a.useState(""),[K,$]=a.useState(!1),[R,z]=a.useState(null),[B,J]=a.useState(null),[Q,C]=a.useState(!1),L=a.useCallback(async()=>{try{const F=await iy(e,i);l(F)}catch(F){n(ye(F)||"Failed to load documents","error")}finally{u(!1)}},[e,i,n]);a.useEffect(()=>{L()},[L]);async function P(F){d===F.key?(m(null),f(""),g(null),v(""),y(null),_([]),C(!1)):(m(F.key),f(F.content),g(null),v(""),y(null),_([]),C(!1))}async function j(F){if(x===F)y(null),_([]);else{y(F),w(!0);try{const de=await ay(e,F,i);_(de)}catch(de){n(ye(de)||"Failed to load revisions","error")}finally{w(!1)}}}function O(){d&&(g(d),v(h))}function H(){g(null),v("")}async function ge(){if(!(!p||!b.trim())){$(!0);try{await Gd(e,p,b,{},i),g(null),v(""),await L();const F=o.find(de=>de.key===p);F&&f(F.content),n("Document saved","success")}catch(F){n(ye(F)||"Failed to save document","error")}finally{$(!1)}}}async function be(){const F=D.trim(),de=T.trim();if(!F){n("Document key is required","error");return}if(!rA.test(F)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!de){n("Content is required","error");return}$(!0);try{await Gd(e,F,de,{},i),N(!1),E(""),U(""),await L(),n("Document created","success")}catch(ne){n(ye(ne)||"Failed to create document","error")}finally{$(!1)}}async function se(F){z(F);try{await ry(e,F,i),J(null),z(null),d===F&&(m(null),f("")),x===F&&(y(null),_([])),await L(),n("Document deleted","success")}catch(de){n(ye(de)||"Failed to delete document","error")}finally{z(null)}}function me(F){f(F.content),g(null),v("")}return c?t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),t.jsx("div",{className:"detail-log-empty",children:"Loading documents…"})]}):t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),M&&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:D,onChange:F=>E(F.target.value),placeholder:"e.g., plan, notes, research",disabled:K}),t.jsx("span",{className:"form-hint",children:"Alphanumeric, hyphens, underscores (1-64 chars)"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-content",children:"Content"}),t.jsx("textarea",{id:"doc-content",value:T,onChange:F=>U(F.target.value),rows:6,placeholder:"Enter document content…",disabled:K})]}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{N(!1),E(""),U("")},disabled:K,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void be(),disabled:K||!D.trim()||!T.trim(),children:K?"Creating…":"Create"})]})]}),o.length===0&&!M?t.jsx("div",{className:"detail-log-empty",children:"No documents yet."}):t.jsx("div",{className:"task-documents-list",children:o.map(F=>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(Ui,{size:14}),t.jsx("span",{className:"task-document-key",children:F.key}),t.jsxs("span",{className:"task-document-revision-badge",children:["v",F.revision]})]}),t.jsxs("div",{className:"task-document-meta",children:[t.jsx("span",{className:"task-document-author",children:F.author}),t.jsx("span",{className:"task-document-timestamp",children:sh(F.updatedAt||F.createdAt)})]})]}),d===F.key&&p!==F.key&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"task-document-content-header",children:t.jsx("button",{className:"btn btn-sm document-mode-toggle",onClick:()=>C(de=>!de),"aria-label":Q?"Switch to plain text":"Switch to markdown","aria-pressed":Q,title:Q?"Switch to plain text":"Switch to markdown",children:Q?"Markdown":"Plain"})}),t.jsx("div",{className:"task-document-content",children:Q?t.jsx("div",{className:"task-document-content-markdown",children:t.jsx("div",{className:"markdown-body",children:t.jsx(ai,{remarkPlugins:[ri],children:h})})}):t.jsx("pre",{className:"task-document-content-text",children:h})}),x===F.key&&t.jsxs("div",{className:"task-document-revisions",children:[t.jsx("h5",{children:"Revision History"}),S?t.jsx("div",{className:"detail-log-empty",children:"Loading…"}):k.length<=1?t.jsx("div",{className:"detail-log-empty",children:"No previous revisions."}):t.jsx("div",{className:"task-document-revision-list",children:k.filter(de=>de.revision<F.revision).sort((de,ne)=>ne.revision-de.revision).map(de=>t.jsxs("div",{className:"task-document-revision-item",onClick:()=>me(de),children:[t.jsxs("div",{className:"revision-header",children:[t.jsxs("span",{className:"revision-badge",children:["v",de.revision]}),t.jsx("span",{className:"revision-author",children:de.author}),t.jsx("span",{className:"revision-timestamp",children:sh(de.createdAt)})]}),t.jsx("div",{className:"revision-preview",children:lA(de.content,100)})]},de.id))})]})]}),p===F.key&&t.jsxs("div",{className:"task-document-edit-form",children:[t.jsx("textarea",{value:b,onChange:de=>v(de.target.value),rows:10,disabled:K}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:H,disabled:K,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void ge(),disabled:K||!b.trim(),children:K?"Saving…":"Save"})]})]}),t.jsxs("div",{className:"task-document-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>void P(F),children:d===F.key?t.jsxs(t.Fragment,{children:[t.jsx(pi,{size:14})," Collapse"]}):t.jsxs(t.Fragment,{children:[t.jsx(Xt,{size:14})," Expand"]})}),d===F.key&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>void j(F.key),children:[t.jsx(ur,{size:14})," History"]}),r&&p!==F.key&&t.jsx("button",{className:"btn btn-sm",onClick:O,children:"Edit"}),r&&(B===F.key?t.jsxs("div",{className:"confirm-delete-actions",children:[t.jsx("span",{children:"Delete?"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void se(F.key),disabled:R===F.key,children:R===F.key?"…":"Yes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>J(null),disabled:R===F.key,children:"No"})]}):t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>J(F.key),children:t.jsx(rn,{size:14})}))]})]})]},F.key))}),r&&!M&&t.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>N(!0),children:[t.jsx(on,{size:14})," New Document"]})]})}function lo(e){return e.toLocaleString()}function nc(e){const n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString()}function Wa(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 dA(e){const n=Date.now(),s=e.map(o=>{if(!o.startedAt)return null;const l=new Date(o.startedAt).getTime();if(Number.isNaN(l))return null;let c;if(o.completedAt){const u=new Date(o.completedAt).getTime();if(Number.isNaN(u)||u<l)return null;c=u}else c=Math.max(l,n);return{name:o.workflowStepName||o.workflowStepId,durationMs:c-l}}).filter(o=>o!==null),i=s.reduce((o,l)=>o+l.durationMs,0),r=s.reduce((o,l)=>!o||l.durationMs>o.durationMs?l:o,void 0);return{timedStepCount:s.length,totalDurationMs:i,longestStep:r}}function uA({tokenUsage:e,loading:n,task:s}){const i=Dp(s?.log??[]),r=i.filter(m=>typeof m.durationMs=="number"),o=r.reduce((m,h)=>m+(h.durationMs??0),0),l=Math.max(o,s?.timedExecutionMs??0),c=r.reduce((m,h)=>!m||(h.durationMs??0)>(m.durationMs??0)?h:m,void 0),u=dA(s?.workflowStepResults??[]),d=s?.steps?.length??0;return t.jsxs("section",{className:"task-token-stats-panel","aria-label":"Task execution statistics",children:[t.jsx("h4",{children:"Execution & Token Stats"}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Execution Timing"}),t.jsxs("div",{className:"task-token-stats-panel__grid",role:"list","aria-label":"Execution timing metrics",children:[t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Timing events"}),t.jsx("span",{className:"task-token-stats-panel__value",children:i.length.toLocaleString()})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Timed duration"}),t.jsx("span",{className:"task-token-stats-panel__value",children:Wa(l)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Workflow timed steps"}),t.jsx("span",{className:"task-token-stats-panel__value",children:u.timedStepCount.toLocaleString()})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Workflow runtime"}),t.jsx("span",{className:"task-token-stats-panel__value",children:Wa(u.totalDurationMs)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Total execution time"}),t.jsx("span",{className:"task-token-stats-panel__value",children:Wa(l+u.totalDurationMs)})]})]}),t.jsxs("dl",{className:"task-token-stats-panel__timestamps",children:[t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Longest timing event"}),t.jsx("dd",{children:c?.durationMs?`${c.summary} (${Wa(c.durationMs)})`:"No timed events recorded yet."})]}),t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Longest workflow step"}),t.jsx("dd",{children:u.longestStep?`${u.longestStep.name} (${Wa(u.longestStep.durationMs)})`:"No completed workflow step timings yet."})]})]})]}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Execution Details"}),t.jsxs("dl",{className:"task-token-stats-panel__details",children:[t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Execution mode"}),t.jsx("dd",{children:s?.executionMode==="fast"?"Fast":"Standard"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Runtime status"}),t.jsx("dd",{children:s?.status??"Not set"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Paused"}),t.jsx("dd",{children:s?.paused?"Yes":"No"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Step progress"}),t.jsx("dd",{children:d>0?`${Math.min((s?.currentStep??0)+1,d)} / ${d}`:"No steps"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Retries (recovery / workflow / merge / task_done)"}),t.jsx("dd",{children:`${s?.recoveryRetryCount??0} / ${s?.workflowStepRetries??0} / ${s?.mergeRetries??0} / ${s?.taskDoneRetryCount??0}`})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Recovery state"}),t.jsx("dd",{children:s?.nextRecoveryAt?`Next recovery at ${nc(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:lo(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:lo(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:lo(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:lo(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:nc(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:nc(e.lastUsedAt)})})]})]})]}):t.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:"No token usage recorded for this task yet."})]})]})}const mA=new Set(["planning","researching","executing","finalizing","merging"]);function hA(e,n){return _p(e,n)}function pA(e,n){return Mp(e,n)}function fA(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 gA(e,n,s){if(e.planningModelProvider&&e.planningModelId)return{provider:e.planningModelProvider,modelId:e.planningModelId};const i=fA(n);return i||Ap(e,s)}function bA(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 xA(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 vA(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function yA(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 ih(e,n){return e.length>n?e.slice(0,n)+"…":e}function ah(e=[],n=[]){return e.length===n.length&&e.every((s,i)=>s===n[i])}function sc(e){const n=e.indexOf("/");return!e||n===-1?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function ic(e){return e.trim()}function jA(e){const n=e.trim();return n.length>0?n:void 0}function Ka(e){return typeof e=="string"&&md.includes(e)?e:ws}function Ga(e){return e==="fast"?"fast":"standard"}function kA(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}function wA(e){switch(e.sourceType){case"dashboard_ui":return{label:"Dashboard"};case"quick_chat":return{label:"Quick Chat"};case"chat_session":return{label:"Chat Session"};case"agent_heartbeat":return{label:e.sourceAgentId?`Agent (${e.sourceAgentId})`:"Agent"};case"automation":return{label:"Automation"};case"cron":return{label:"Scheduled Task"};case"workflow_step":return{label:"Workflow Step"};case"github_import":return{label:"GitHub Import",contextInfo:kA(e.sourceMetadata)};case"task_refine":return{label:"Refinement",parentTaskId:e.sourceParentTaskId};case"task_duplicate":return{label:"Duplicate",parentTaskId:e.sourceParentTaskId};case"cli":return{label:"CLI"};case"api":return{label:"API"};case"recovery":return{label:"Recovery"};case"unknown":default:return null}}const ac=200,NA=new Set(["triage","todo"]);function SA({task:e,projectId:n,tasks:s=[],onClose:i,onOpenDetail:r,onMoveTask:o,onDeleteTask:l,onMergeTask:c,onRetryTask:u,onResetTask:d,onDuplicateTask:m,onTaskUpdated:h,addToast:f,prAuthAvailable:p,initialTab:g="definition"}){const[b,v]=a.useState(g),[x,y]=a.useState(()=>"prompt"in e?e:null),[k,_]=a.useState(()=>!("prompt"in e));a.useEffect(()=>{if("prompt"in e){y(e),_(!1);return}let Y=!1;return _(!0),y(null),pr(e.id,n).then(qe=>{Y||(y(qe),_(!1))}).catch(()=>{Y||_(!1)}),()=>{Y=!0}},[e.id,n]);const S=x?{...x,...e,prompt:x.prompt,log:x.log}:{...e,prompt:""},w=e.status==="failed"||e.status==="stuck-killed"||e.status==="planning"||e.status==="needs-replan"||(e.stuckKillCount??0)>0||(e.recoveryRetryCount??0)>0||!!e.nextRecoveryAt,M=wA(S);a.useEffect(()=>{v(g)},[g]),a.useEffect(()=>{T(!1)},[e.id]);const[N,D]=a.useState("activity"),[E,T]=a.useState(!1),[U,K]=a.useState(e.attachments||[]),[$,R]=a.useState(!1),[z,B]=a.useState(e.dependencies||[]),[J,Q]=a.useState(!1),[C,L]=a.useState(""),[P,j]=a.useState(null),[O,H]=a.useState([]),[ge,be]=a.useState(!1),[se,me]=a.useState(!1),[F,de]=a.useState(!1),[ne,xe]=a.useState(!1),[oe,he]=a.useState(!1),[ae,je]=a.useState(S.prompt||""),[Ae,Oe]=a.useState(""),[Qe,Xe]=a.useState(!1),[Ye,it]=a.useState(""),[Be,Ge]=a.useState(!1),[re,ke]=a.useState(!1),[X,Te]=a.useState(e.title||""),[Le,fe]=a.useState(e.description||""),[_e,Ue]=a.useState(e.dependencies||[]),[nt,ve]=a.useState(""),[ce,De]=a.useState(""),[ue,Re]=a.useState(""),[Ke,Pe]=a.useState(""),[ft,Z]=a.useState("default"),[le,we]=a.useState(void 0),[Ze,te]=a.useState(ws),[Je,dt]=a.useState(e.nodeId),[ut,Ct]=a.useState(Ga(e.executionMode)),[yt,bt]=a.useState(""),[At,Rt]=a.useState(e.enabledWorkflowSteps||[]),[Ht,Et]=a.useState(e.sourceIssue?.provider??""),[Dt,Kt]=a.useState(e.sourceIssue?.repository??""),[$t,Ft]=a.useState(e.sourceIssue?.externalIssueId??""),[Ot,Tt]=a.useState(e.sourceIssue?.url??""),[Pt,wt]=a.useState([]),[Gt,Ut]=a.useState(!1),q=a.useRef(!1),[pe,$e]=a.useState(!1),[A,ee]=a.useState(!1),[ze,mt]=a.useState(!1),jt=a.useRef(null),Lt=a.useRef(null),_t=a.useRef(null),Jt=a.useRef(null);oi(Jt,!0,"fusion:task-detail-modal-size");const{getSlotsForId:Dn}=Sp(n),Pn=Dn("task-detail-tab");a.useEffect(()=>(q.current=!0,()=>{q.current=!1}),[]);const[Yt,Cn]=a.useState(void 0),[Ne,at]=a.useState([]),[fn,jn]=a.useState(!1),[In,Ce]=a.useState(e.enabledWorkflowSteps||[]),st=e.column==="in-progress"||mA.has(e.status);a.useEffect(()=>{Te(e.title||""),fe(e.description||""),Et(e.sourceIssue?.provider??""),Kt(e.sourceIssue?.repository??""),Ft(e.sourceIssue?.externalIssueId??""),Tt(e.sourceIssue?.url??""),Ct(Ga(e.executionMode)),mt(!1),ke(!1)},[e.id,e.title,e.description,e.sourceIssue,e.executionMode]),a.useEffect(()=>{Ce(e.enabledWorkflowSteps||[])},[e.id,e.enabledWorkflowSteps]),a.useEffect(()=>{let Y=!1;return Wo(n).then(qe=>{Y||Cn(qe)}).catch(()=>{}),()=>{Y=!0}},[n]),a.useEffect(()=>{if(b!=="workflow")return;let Y=!1;return jn(!0),Tj(e.id,n).then(qe=>{Y||at(qe)}).catch(qe=>{Y||f(`Failed to load workflow results: ${ye(qe)}`,"error")}).finally(()=>{Y||jn(!1)}),()=>{Y=!0}},[b,e.id,n,f]),a.useEffect(()=>{if(b!=="workflow")return;const Y=n?`?projectId=${encodeURIComponent(n)}`:"",qe=lt=>{try{const It=JSON.parse(lt.data);It.id===e.id&&Array.isArray(It.workflowStepResults)&&at(It.workflowStepResults)}catch{}};return Ks(`/api/events${Y}`,{events:{"task:updated":qe}})},[b,e.id,n]),a.useEffect(()=>{J||L("")},[J]),a.useEffect(()=>{if(!e.assignedAgentId){j(null);return}const Y=O.find(lt=>lt.id===e.assignedAgentId);if(Y){j(Y);return}let qe=!1;return xp(e.assignedAgentId,n).then(lt=>{qe||j(lt)}).catch(()=>{qe||j(null)}),()=>{qe=!0}},[e.assignedAgentId,n,O]),a.useEffect(()=>{be(!1)},[e.id]),a.useEffect(()=>{if(!(pe||A))return;const qe=lt=>{const It=lt.target,Fs=jt.current?.contains(It),Es=_t.current?.contains(It);!Fs&&pe&&$e(!1),!Es&&A&&ee(!1)};return document.addEventListener("mousedown",qe),()=>document.removeEventListener("mousedown",qe)},[pe,A]),a.useEffect(()=>{if(!(pe||A))return;const qe=lt=>{lt.key==="Escape"&&(lt.stopPropagation(),pe&&$e(!1),A&&ee(!1))};return document.addEventListener("keydown",qe),()=>document.removeEventListener("keydown",qe)},[pe,A]),a.useEffect(()=>{he(!1),je(S.prompt||""),Oe("")},[e.id,S.prompt]);const ht=NA.has(e.column)&&!Gt,Mt=a.useCallback(()=>{if(!ht)return;ke(!0),Te(e.title||""),fe(e.description||""),Ue(e.dependencies||[]);const Y=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"",qe=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"",lt=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";ve(Y),De(qe),Re(lt),Pe(e.thinkingLevel??""),dt(e.nodeId),Z(Y||qe||lt?"custom":"default"),bt(""),Rt(e.enabledWorkflowSteps||[]),Ct(Ga(e.executionMode)),Et(e.sourceIssue?.provider??""),Kt(e.sourceIssue?.repository??""),Ft(e.sourceIssue?.externalIssueId??""),Tt(e.sourceIssue?.url??""),wt([]),we(e.reviewLevel),te(Ka(e.priority))},[ht,e]),ln=a.useCallback(()=>{ke(!1),Te(e.title||""),fe(e.description||""),Ue(e.dependencies||[]),dt(e.nodeId),Et(e.sourceIssue?.provider??""),Kt(e.sourceIssue?.repository??""),Ft(e.sourceIssue?.externalIssueId??""),Tt(e.sourceIssue?.url??""),te(Ka(e.priority)),Ct(Ga(e.executionMode)),Pt.forEach(Y=>URL.revokeObjectURL(Y.previewUrl)),wt([])},[e.title,e.description,e.dependencies,e.nodeId,e.priority,e.executionMode,Pt]),En=a.useCallback(async()=>{Ut(!0);try{const Y={},qe=X.trim(),lt=Le.trim();qe&&qe!==(e.title??"")&&(Y.title=qe),lt&<!==(e.description??"")&&(Y.description=lt),ah(_e,e.dependencies??[])||(Y.dependencies=_e),ah(At,e.enabledWorkflowSteps??[])||(Y.enabledWorkflowSteps=At);const It=sc(nt),Fs=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"";nt!==Fs&&(Y.modelProvider=It?.provider??null,Y.modelId=It?.modelId??null);const Es=sc(ce),Qi=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"";ce!==Qi&&(Y.validatorModelProvider=Es?.provider??null,Y.validatorModelId=Es?.modelId??null);const Or=sc(ue),ll=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";ue!==ll&&(Y.planningModelProvider=Or?.provider??null,Y.planningModelId=Or?.modelId??null);const cl=e.thinkingLevel??"";Ke!==cl&&(Y.thinkingLevel=Ke!==""?Ke:null),(e.nodeId??void 0)!==Je&&(Y.nodeId=Je??null);const $a=e.reviewLevel;le!==$a&&(Y.reviewLevel=le);const Ur=Ka(e.priority);Ze!==Ur&&(Y.priority=Ze);const Br=Ga(e.executionMode);ut!==Br&&(Y.executionMode=ut==="fast"?"fast":null);const Xi=ic(Ht),Da=ic(Dt),Ai=ic($t),Zi=jA(Ot);if(Xi.length===0&&Da.length===0&&Ai.length===0&&!Zi)e.sourceIssue&&(Y.sourceIssue=null);else{if(!Xi||!Da||!Ai){f("Source issue provider, repository, and issue identifier are required","error"),Ut(!1);return}const Se=Number.parseInt(Ai,10),Ie=e.sourceIssue?.issueNumber??Se;if(!Number.isFinite(Ie)||Ie<=0){f("Source issue identifier must be numeric for new metadata","error"),Ut(!1);return}const pt={provider:Xi,repository:Da,externalIssueId:Ai,issueNumber:Ie,...Zi?{url:Zi}:{}},Zt=e.sourceIssue;(!Zt||Zt.provider!==pt.provider||Zt.repository!==pt.repository||Zt.externalIssueId!==pt.externalIssueId||Zt.issueNumber!==pt.issueNumber||(Zt.url??void 0)!==pt.url)&&(Y.sourceIssue=pt)}if(Object.keys(Y).length>0){const Se=await ni(e.id,Y,n);h?.(Se)}if(Pt.length>0){const Se=[];for(const Ie of Pt)try{const pt=await fr(e.id,Ie.file,n);K(Zt=>[...Zt,pt])}catch{Se.push(Ie.file.name)}Se.length>0&&f(`Failed to upload: ${Se.join(", ")}`,"error")}Pt.forEach(Se=>URL.revokeObjectURL(Se.previewUrl)),wt([]),f(`Updated ${e.id}`,"success"),ke(!1)}catch(Y){f(`Failed to update ${e.id}: ${ye(Y)}`,"error")}finally{q.current&&Ut(!1)}},[e,X,Le,_e,nt,ce,ue,Ke,Je,le,Ze,ut,At,Ht,Dt,$t,Ot,Pt,f,n,h]),tn=a.useCallback(async Y=>{try{await ni(e.id,{description:Y},n),f("Description saved","success")}catch(qe){f(`Failed to save: ${ye(qe)}`,"error")}},[e.id,f,n]),nn=a.useCallback(Y=>{re&&(Y.key==="Escape"?(Y.preventDefault(),ln()):Y.key==="Enter"&&(Y.ctrlKey||Y.metaKey)&&(Y.preventDefault(),En()))},[re,ln,En]);a.useEffect(()=>{if(re)return document.addEventListener("keydown",nn),()=>document.removeEventListener("keydown",nn)},[re,nn]);const An=a.useRef(null),{nodes:Un}=Qo(),{confirm:kn}=Ws(),{entries:ns,loading:cn,loadMore:vt,hasMore:G,total:Fe,loadingMore:tt}=eg(e.id,b==="logs"&&N==="agent-log",n);a.useEffect(()=>{const Y=qe=>{qe.key==="Escape"&&!re&&i()};return document.addEventListener("keydown",Y),()=>document.removeEventListener("keydown",Y)},[i,re]);const rt=Ei(i),kt=a.useCallback(async Y=>{try{await o(e.id,Y),i(),f(`Moved to ${Fn[Y]}`,"success")}catch(qe){f(ye(qe),"error")}},[e.id,o,i,f]),St=a.useCallback(async()=>{if(await kn({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0}))try{await l(e.id),i(),f(`Deleted ${e.id}`,"info")}catch(qe){const lt=yA(qe);if(!lt||lt.dependentIds.length===0){f(ye(qe),"error");return}const It=lt.dependentIds.join(", ");if(!await kn({title:"Force Delete Task",message:`${e.id} is a dependency of ${It}.
|
|
651
|
-
|
|
652
|
-
Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await l(e.id,{removeDependencyReferences:!0}),i(),f(`Deleted ${e.id} after removing dependency references`,"info")}catch(Es){f(ye(Es),"error")}}},[e.id,l,i,f,kn]),zt=a.useCallback(async()=>{await kn({title:"Merge Task",message:`Merge ${e.id} into the current branch?`})&&(i(),f(`Merging ${e.id}...`,"info"),c(e.id).then(qe=>{const lt=qe.merged?`Merged ${e.id} (branch: ${qe.branch})`:`Closed ${e.id} (${qe.error||"no branch to merge"})`;f(lt,"success")}).catch(qe=>{f(ye(qe),"error")}))},[e.id,c,i,f,kn]),qn=a.useCallback(()=>{u&&(i(),u(e.id).then(()=>{f(`Retried ${e.id}`,"success")}).catch(Y=>{f(ye(Y),"error")}))},[e.id,u,i,f]),Ds=a.useCallback(()=>{d&&window.confirm(`This will erase all progress for ${e.id} and start the task from scratch. Continue?`)&&(i(),d(e.id).then(()=>{f(`Reset ${e.id} — fresh run will be allocated`,"success")}).catch(Y=>{f(ye(Y),"error")}))},[e.id,d,i,f]),ci=a.useCallback(async()=>{if(!(!m||!await kn({title:"Duplicate Task",message:`Duplicate ${e.id}? This will create a new task in Triage with the same description and prompt.`})))try{const qe=await m(e.id);i(),f(`Duplicated ${e.id} → ${qe.id}`,"success")}catch(qe){f(ye(qe),"error")}},[e.id,m,i,f,kn]),Cs=a.useCallback(async()=>{try{e.paused?(await Kv(e.id,n),f(`Unpaused ${e.id}`,"success")):(await up(e.id,n),f(`Paused ${e.id}`,"success")),i()}catch(Y){f(ye(Y),"error")}},[e.id,e.paused,i,f]),Gs=a.useCallback(async()=>{try{await Qv(e.id,n),f(`Plan approved — ${e.id} moved to Todo`,"success"),i()}catch(Y){f(ye(Y),"error")}},[e.id,i,f]),ie=a.useCallback(async()=>{if(await kn({title:"Reject Plan",message:"Reject this plan? The specification will be discarded and regenerated.",danger:!0}))try{await Xv(e.id,n),f(`Plan rejected — ${e.id} returned to Planning for replanning`,"info"),i()}catch(qe){f(ye(qe),"error")}},[e.id,i,f,kn]),Ee=a.useCallback(async()=>{if(await kn({title:"Rebuild Plan",message:"Rebuild the plan for this task? The task will move to planning for replanning."}))try{await cy(e.id,n),i(),f(`Replanning ${e.id}...`,"info")}catch(qe){f(ye(qe),"error")}},[e.id,n,i,f,kn]),Me=a.useCallback(()=>{Xe(!0),it("")},[]),ct=a.useCallback(()=>{$e(!1),ee(!1)},[]),gt=a.useCallback(Y=>{ct(),kt(Y)},[ct]),sn=a.useCallback(Y=>{ct(),Y()},[ct]),mn=a.useCallback(()=>{ct(),zt()},[ct,zt]),dn=a.useCallback(()=>{Xe(!1),it(""),Ge(!1)},[]),gn=a.useCallback(async()=>{if(!Ye.trim()){f("Please enter feedback describing what needs refinement","error");return}if(Ye.length>2e3){f("Feedback must be 2000 characters or less","error");return}Ge(!0);try{const Y=await dy(e.id,Ye.trim(),n);f(`Refinement task created: ${Y.id}`,"success"),i()}catch(Y){f(ye(Y),"error")}finally{Ge(!1)}},[e.id,Ye,f,i]),wn=a.useCallback(async Y=>{R(!0);try{const qe=await fr(e.id,Y,n);K(lt=>[...lt,qe]),f("Screenshot attached","success")}catch(qe){f(ye(qe),"error")}finally{R(!1)}},[e.id,f]),Xn=a.useCallback(async Y=>{const qe=Y.target.files?.[0];qe&&(await wn(qe),An.current&&(An.current.value=""))},[wn]);a.useEffect(()=>{const Y=qe=>{const lt=qe.clipboardData?.items;if(lt)for(let It=0;It<lt.length;It++){const Fs=lt[It];if(Fs.type.startsWith("image/")){const Es=Fs.getAsFile();if(Es){qe.preventDefault(),wn(Es);return}}}};return document.addEventListener("paste",Y),()=>document.removeEventListener("paste",Y)},[wn]);const Zn=a.useCallback(Y=>{Y.preventDefault()},[]),Ln=a.useCallback(Y=>{Y.preventDefault();const qe=Y.dataTransfer.files;for(let lt=0;lt<qe.length;lt++){const It=qe[lt];if(It.type.startsWith("image/")){wn(It);return}}},[wn]),es=a.useCallback(async Y=>{try{await ty(e.id,Y,n),K(qe=>qe.filter(lt=>lt.filename!==Y)),f("Attachment deleted","info")}catch(qe){f(ye(qe),"error")}},[e.id,f]),Vn=a.useCallback(async Y=>{const qe=In;Ce(Y);try{const lt=await ni(e.id,{enabledWorkflowSteps:Y},n);f("Workflow steps updated","success"),h?.(lt)}catch(lt){Ce(qe),f(`Failed to update workflow steps: ${ye(lt)}`,"error")}},[e.id,n,In,h,f]),ps=a.useCallback(async()=>{me(!0);try{const Y=await Ea(void 0,n);H(Y),be(!0)}catch(Y){f(`Failed to load agents: ${ye(Y)}`,"error"),be(!1)}finally{me(!1)}},[n,f]),Rn=a.useCallback(async Y=>{try{const qe=await au(e.id,Y,n),lt=O.find(It=>It.id===Y)??null;j(lt||(It=>It?.id===Y?It:null)),be(!1),h?.(qe),f("Assigned agent updated","success")}catch(qe){f(`Failed to assign agent: ${ye(qe)}`,"error")}},[e.id,n,O,h,f]),Wn=a.useCallback(async()=>{try{const Y=await au(e.id,null,n);j(null),be(!1),h?.(Y),f("Agent unassigned","success")}catch(Y){f(`Failed to unassign agent: ${ye(Y)}`,"error")}},[e.id,n,h,f]),fs=a.useCallback(async Y=>{const qe=[...z,Y];B(qe);try{await ni(e.id,{dependencies:qe},n)}catch(lt){B(z),f(ye(lt),"error")}},[e.id,z,f]),Ls=a.useCallback(async(Y,qe)=>{Y.stopPropagation();const lt=z.filter(It=>It!==qe);B(lt);try{await ni(e.id,{dependencies:lt},n)}catch(It){B(z),f(ye(It),"error")}},[e.id,z,f]),ss=a.useCallback(async Y=>{try{const qe=await pr(Y,n);r(qe)}catch{f(`Failed to load dependency ${Y}`,"error")}},[r,f]),_n=a.useCallback(async Y=>{de(!0);try{await ni(S.id,{prompt:Y},n),f("Spec updated","success"),x&&(x.prompt=Y)}catch(qe){throw f(ye(qe),"error"),qe}finally{de(!1)}},[S,x,f]),Bn=a.useCallback(async Y=>{xe(!0);try{await ly(e.id,Y,n),f("AI revision requested. Task moved to planning.","success"),i()}catch(qe){const lt=ye(qe);lt.includes("done")||lt.includes("archived")?f("Cannot request revision: Task must be in 'triage', 'todo', 'in-progress', or 'in-review' column.","error"):f(lt,"error")}finally{xe(!1)}},[e.id,f,i]),zs=a.useCallback(()=>{he(!0),je(S.prompt||""),Oe("")},[S.prompt]),di=a.useCallback(()=>{he(!1),je(S.prompt||""),Oe("")},[S.prompt]),bi=a.useCallback(async()=>{if(ae===(S.prompt||"")){di();return}he(!1);try{await _n(ae)}catch(Y){throw he(!0),Y}},[ae,S.prompt,_n,di]),al=a.useCallback(async()=>{Ae.trim()&&await Bn(Ae.trim())},[Ae,Bn]),Js=a.useCallback(Y=>{Y.key==="Escape"?(Y.preventDefault(),di()):Y.key==="Enter"&&(Y.ctrlKey||Y.metaKey)&&(Y.preventDefault(),bi())},[di,bi]),Ta=s.filter(Y=>Y.id!==e.id&&!z.includes(Y.id)).sort((Y,qe)=>{const lt=qe.createdAt.localeCompare(Y.createdAt);if(lt!==0)return lt;const It=parseInt(Y.id.slice(Y.id.lastIndexOf("-")+1),10)||0;return(parseInt(qe.id.slice(qe.id.lastIndexOf("-")+1),10)||0)-It}),Pa=P?.name??e.assignedAgentId??null,$r=a.useMemo(()=>{const Y=[];return S.modelProvider&&Y.push(S.modelProvider),S.validatorModelProvider&&!Y.includes(S.validatorModelProvider)&&Y.push(S.validatorModelProvider),S.planningModelProvider&&!Y.includes(S.planningModelProvider)&&Y.push(S.planningModelProvider),Y},[S.modelProvider,S.validatorModelProvider,S.planningModelProvider]),rl=Ic[e.column]||[],ol=["todo","in-progress"],Ys=e.column==="in-review"?ol:rl,Tn=Ys[0],xi=Ys.slice(1),ls=xi.length>0,Dr=a.useCallback(()=>{$e(!1),Lt.current?.focus()},[]),Lr=a.useCallback(Y=>{if(!ls){Tn&>(Tn);return}const qe=Y.currentTarget.querySelector(".detail-move-btn__arrow");if(!!(Y.target instanceof Element&&Y.target.closest(".detail-move-btn__arrow")||qe&&Y.clientX>0&&Y.clientX>=qe.getBoundingClientRect().left)){$e(It=>!It),ee(!1);return}Tn&>(Tn)},[ls,Tn,gt]),Ia=a.useCallback(Y=>{!ls||!(Y.key==="ArrowDown"||Y.altKey&&Y.key==="ArrowDown")||(Y.preventDefault(),$e(!0),ee(!1))},[ls]),Mi=a.useCallback(Y=>{Y.key==="Escape"&&(Y.preventDefault(),Y.stopPropagation(),Dr())},[Dr]);a.useEffect(()=>{if(!pe)return;jt.current?.querySelector(".detail-move-menu-item")?.focus()},[pe]);const zr={"creating-pr":"Creating PR…","awaiting-pr-checks":"Awaiting PR checks","merging-pr":"Merging PR…"},Fr=e.status?zr[e.status]:void 0;return t.jsx("div",{className:"modal-overlay open",...rt,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg task-detail-modal",ref:Jt,onDragOver:Zn,onDrop:Ln,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:Fn[e.column]})]}),t.jsxs("div",{className:"modal-header-actions",children:[!re&&ht&&t.jsx("button",{className:"modal-edit-btn",onClick:Mt,title:"Edit task","aria-label":"Edit task",children:t.jsx(cs,{size:14})}),t.jsx("button",{className:"modal-close",onClick:i,"aria-label":"Close",children:"×"})]})]}),t.jsxs("div",{className:`detail-body${b==="logs"&&N==="agent-log"&&!re?" detail-body--agent-log":""}`,children:[re?t.jsx("div",{className:"modal-edit-form",children:t.jsx(ig,{mode:"edit",title:X,onTitleChange:Te,description:Le,onDescriptionChange:fe,dependencies:_e,onDependenciesChange:Ue,executorModel:nt,onExecutorModelChange:ve,validatorModel:ce,onValidatorModelChange:De,planningModel:ue,onPlanningModelChange:Re,thinkingLevel:Ke,onThinkingLevelChange:Pe,presetMode:ft,onPresetModeChange:Z,selectedPresetId:yt,onSelectedPresetIdChange:bt,selectedWorkflowSteps:At,onWorkflowStepsChange:Rt,pendingImages:Pt,onImagesChange:wt,tasks:s.filter(Y=>Y.id!==e.id),projectId:n,disabled:Gt,addToast:f,isActive:re,onAutoSaveDescription:tn,reviewLevel:le,onReviewLevelChange:we,priority:Ze,onPriorityChange:te,nodeId:Je,onNodeIdChange:dt,nodeOptions:Un,nodeOverrideDisabled:st,nodeOverrideDisabledReason:st?"Execution node override is locked while a task is active/in progress.":void 0,executionMode:ut,onExecutionModeChange:Ct,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:Ht,onChange:Y=>Et(Y.target.value),disabled:Gt,"data-testid":"task-source-provider-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Repository (e.g. owner/repo)",value:Dt,onChange:Y=>Kt(Y.target.value),disabled:Gt,"data-testid":"task-source-repository-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Issue identifier",value:$t,onChange:Y=>Ft(Y.target.value),disabled:Gt,"data-testid":"task-source-external-id-input"}),t.jsx("input",{type:"url",className:"modal-edit-input",placeholder:"Issue URL",value:Ot,onChange:Y=>Tt(Y.target.value),disabled:Gt,"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,qe=!E&&Y.length>ac;return t.jsxs(t.Fragment,{children:[t.jsx("h2",{className:"detail-title",children:qe?Y.slice(0,ac)+"…":Y}),Y.length>ac&&t.jsx("button",{className:"detail-description-toggle",onClick:()=>T(!E),children:E?"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--${Ka(e.priority)}`,children:["Priority: ",Ka(e.priority)]}),M&&t.jsxs("div",{className:"detail-provenance",children:[t.jsx(Vs,{"aria-hidden":"true"}),t.jsxs("span",{children:["Created via ",M.label,M.parentTaskId&&t.jsxs(t.Fragment,{children:[" ","of"," ",t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>ss(M.parentTaskId),children:M.parentTaskId})]}),M.contextInfo?` (${M.contextInfo})`:""]})]})]})]}),e.status==="failed"&&e.error&&t.jsxs("div",{className:"detail-error-alert",children:[t.jsx("span",{className:"detail-error-icon",children:"⚠"}),t.jsxs("div",{className:"detail-error-content",children:[t.jsx("div",{className:"detail-error-title",children:"Task Failed"}),t.jsx("div",{className:"detail-error-message",children:e.error})]})]}),!re&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"detail-tabs",children:[t.jsx("button",{className:`detail-tab${b==="definition"?" detail-tab-active":""}`,onClick:()=>v("definition"),children:"Definition"}),t.jsx("button",{className:`detail-tab${b==="logs"?" detail-tab-active":""}`,onClick:()=>v("logs"),children:"Logs"}),(e.column==="in-progress"||e.column==="in-review"||e.column==="done")&&t.jsx("button",{className:`detail-tab${b==="changes"?" detail-tab-active":""}`,onClick:()=>v("changes"),children:"Changes"}),t.jsx("button",{className:`detail-tab${b==="comments"?" detail-tab-active":""}`,onClick:()=>v("comments"),children:"Comments"}),t.jsx("button",{className:`detail-tab${b==="documents"?" detail-tab-active":""}`,onClick:()=>v("documents"),children:"Documents"}),t.jsx("button",{className:`detail-tab${b==="model"?" detail-tab-active":""}`,onClick:()=>v("model"),children:"Model"}),t.jsx("button",{className:`detail-tab${b==="workflow"?" detail-tab-active":""}`,onClick:()=>v("workflow"),children:"Workflow"}),t.jsx("button",{className:`detail-tab${b==="stats"?" detail-tab-active":""}`,onClick:()=>v("stats"),children:"Stats"}),t.jsx("button",{className:`detail-tab${b==="routing"?" detail-tab-active":""}`,onClick:()=>v("routing"),children:"Routing"}),Pn.map((Y,qe)=>{const lt=`plugin-${qe}`;return t.jsx("button",{className:`detail-tab${b===lt?" detail-tab-active":""}`,onClick:()=>v(lt),children:Y.slot.label},`plugin-tab-${Y.pluginId}`)})]}),b==="workflow"?t.jsx("div",{className:"detail-section",children:t.jsx(tA,{taskId:e.id,results:Ne,loading:fn,enabledWorkflowSteps:In,canEdit:ht,projectId:n,isTaskInProgress:e.column==="in-progress"&&e.status!=="paused",onWorkflowStepsChange:Vn})}):b==="model"?t.jsx("div",{className:"detail-section",children:t.jsx(DM,{task:e,addToast:f,onTaskUpdated:h,settings:Yt})}):b==="logs"?t.jsxs("div",{className:`detail-section${N==="agent-log"?" detail-section--agent-log":""}`,children:[t.jsxs("div",{className:"log-subview-toggle",children:[t.jsx("button",{className:`log-subview-btn${N==="activity"?" log-subview-btn-active":""}`,onClick:()=>D("activity"),children:"Activity"}),t.jsx("button",{className:`log-subview-btn${N==="agent-log"?" log-subview-btn-active":""}`,onClick:()=>D("agent-log"),children:"Agent Log"})]}),N==="agent-log"?t.jsx(RM,{entries:ns,loading:cn,executorModel:hA(e,Yt),validatorModel:pA(e,Yt),planningModel:gA(e,ns,Yt),hasMore:G,onLoadMore:vt,loadingMore:tt,totalCount:Fe}):t.jsxs("div",{className:"detail-activity",children:[t.jsx("h4",{children:"Activity"}),S.activityLogTruncatedCount?t.jsxs("div",{className:"detail-log-truncated",children:["Showing the most recent ",S.log.length," activity entries."]}):null,S.log&&S.log.length>0?t.jsx("div",{className:"detail-activity-list",children:[...S.log].reverse().map((Y,qe)=>t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-timestamp",children:xA(Y.timestamp)}),t.jsx("span",{className:"detail-log-action",children:Y.action})]}),Y.outcome&&t.jsx("div",{className:"detail-log-outcome",children:Y.outcome})]},qe))}):t.jsx("div",{className:"detail-log-empty",children:"(no activity)"})]})]}):b==="changes"?t.jsx(WM,{taskId:e.id,worktree:e.worktree,projectId:n,column:e.column,mergeDetails:e.mergeDetails,modifiedFiles:e.modifiedFiles}):b==="comments"?t.jsx(UM,{task:e,addToast:f,projectId:n,onTaskUpdated:h}):b==="documents"?t.jsx(cA,{taskId:e.id,addToast:f,projectId:n,onTaskUpdated:h,canEdit:ht}):typeof b=="string"&&b.startsWith("plugin-")?t.jsx("div",{className:"detail-section",children:t.jsx(Jo,{slotId:"task-detail-tab",projectId:n})}):b==="stats"?t.jsx("div",{className:"detail-section",children:t.jsx(uA,{tokenUsage:S.tokenUsage,loading:k,task:S})}):b==="routing"?t.jsx("div",{className:"detail-section",children:t.jsx(aA,{task:e,settings:Yt,addToast:f,onTaskUpdated:h})}):t.jsxs(t.Fragment,{children:[e.column==="done"&&e.summary&&t.jsxs("div",{className:"detail-section detail-summary",children:[t.jsx("h4",{children:"Summary"}),t.jsx("div",{className:"markdown-body",children:t.jsx(ai,{remarkPlugins:[ri],children:e.summary})})]}),t.jsx(HM,{task:e}),e.sourceIssue&&t.jsxs("div",{className:"detail-section detail-source-section",children:[t.jsxs("div",{className:"detail-source-header",children:[t.jsxs("div",{className:"detail-source-summary",children:[t.jsx("span",{className:"detail-source-label",children:"Source issue"}),e.sourceIssue.url?t.jsx("a",{className:"detail-source-link detail-source-number",href:e.sourceIssue.url,target:"_blank",rel:"noopener noreferrer",children:`(#${e.sourceIssue.issueNumber})`}):t.jsx("span",{className:"detail-source-number",children:`(#${e.sourceIssue.issueNumber})`})]}),t.jsx("button",{type:"button",className:"detail-source-toggle","aria-expanded":ze,"aria-label":ze?"Collapse source issue details":"Expand source issue details",onClick:()=>mt(Y=>!Y),children:t.jsx(vn,{size:16,className:ze?"detail-source-chevron--expanded":void 0})})]}),ze&&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:[$r.length>0&&t.jsx("span",{className:"detail-provider-icons","data-testid":"detail-provider-icons",children:$r.map(Y=>t.jsx(On,{provider:Y,size:"sm"},Y))}),t.jsxs("span",{className:"detail-meta-label",children:[t.jsx(Nn,{size:14,style:{verticalAlign:"middle",marginRight:6}}),"Agent"]})]}),t.jsxs("div",{className:"detail-agent-actions",children:[Pa?t.jsxs("span",{className:"detail-agent-chip",children:[t.jsx(Nn,{size:14}),Pa,t.jsx("button",{className:"detail-agent-clear",onClick:()=>void Wn(),title:"Unassign agent",children:t.jsx(Wt,{size:12})})]}):t.jsx("button",{className:"btn btn-sm",onClick:()=>{ge?be(!1):ps()},children:"Assign Agent"}),ge&&t.jsxs("div",{className:"agent-picker-dropdown",children:[se&&t.jsx("div",{className:"agent-picker-loading",children:"Loading agents..."}),!se&&O.filter(Y=>Y.state!=="terminated").map(Y=>t.jsxs("button",{className:`agent-picker-item${e.assignedAgentId===Y.id?" selected":""}`,onClick:()=>void Rn(Y.id),children:[t.jsx(Nn,{size:14}),t.jsx("span",{className:"agent-picker-name",children:Y.name}),t.jsx("span",{className:"agent-picker-role",children:Y.role})]},Y.id)),!se&&O.filter(Y=>Y.state!=="terminated").length===0&&t.jsx("div",{className:"agent-picker-empty",children:"No agents available"})]})]})]})}),t.jsxs("div",{className:"detail-section detail-step-progress",children:[t.jsx("h4",{children:"Progress"}),S.steps&&S.steps.length>0?t.jsxs("div",{className:"step-progress-wrapper",children:[t.jsx("div",{className:"step-progress-bar",children:S.steps.map((Y,qe)=>t.jsx("div",{className:`step-progress-segment step-progress-segment--${Y.status}`,"data-tooltip":`${Y.name} (${Y.status})`,style:{backgroundColor:bA(Y.status)}},qe))}),t.jsxs("span",{className:"step-progress-label",children:[S.steps.filter(Y=>Y.status==="done").length,"/",S.steps.length," step",S.steps.length===1?"":"s"]})]}):t.jsx("div",{className:"step-progress-empty",children:"(no steps defined)"})]}),t.jsxs("div",{className:"detail-section",children:[!oe&&t.jsx("div",{className:"detail-spec-edit-trigger",children:t.jsx("button",{className:"btn btn-sm",onClick:zs,children:"Edit"})}),oe?t.jsxs("div",{className:"spec-editor-edit-mode",children:[t.jsx("textarea",{className:"spec-editor-textarea",value:ae,onChange:Y=>je(Y.target.value),onKeyDown:Js,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:di,disabled:F,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void bi(),disabled:ae===(S.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 planning for replanning."}),t.jsx("textarea",{className:"spec-editor-feedback",value:Ae,onChange:Y=>Oe(Y.target.value),placeholder:"e.g., 'Add more details about error handling', 'Split this into smaller steps', 'Include tests for the API endpoints'...",disabled:ne,rows:4,maxLength:2e3}),t.jsxs("div",{className:"spec-editor-revision-actions",children:[t.jsxs("span",{className:"spec-editor-char-count",children:[Ae.length,"/2000"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void al(),disabled:!Ae.trim()||ne,children:ne?"Requesting…":"Request AI Revision"})]})]})]}):k?t.jsx("div",{className:"spec-loading",children:"Loading specification…"}):S.prompt?t.jsx("div",{className:"markdown-body",children:t.jsx(ai,{remarkPlugins:[ri],children:S.prompt.replace(/^#\s+[^\n]*\n+/,"")})}):t.jsx("div",{className:"detail-prompt",children:"(no prompt)"})]}),t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Attachments"}),U.length>0?t.jsx("div",{className:"detail-attachments-grid",children:U.map(Y=>{const qe=ii(`/api/tasks/${e.id}/attachments/${Y.filename}`);return t.jsxs("div",{className:"detail-attachment-card",children:[t.jsx("a",{className:"detail-attachment-link",href:qe,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{src:qe,alt:Y.originalName,className:"detail-attachment-image"})}),t.jsxs("div",{className:"detail-attachment-meta",children:[Y.originalName," (",vA(Y.size),")"]}),t.jsx("button",{className:"detail-attachment-delete",onClick:()=>es(Y.filename),title:"Delete attachment",children:"×"})]},Y.filename)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no attachments)"}),t.jsx("input",{className:"detail-hidden-file-input",ref:An,type:"file",accept:"image/*",onChange:Xn}),t.jsx("button",{className:"btn btn-sm",onClick:()=>An.current?.click(),disabled:$,children:$?"Uploading…":"Attach Screenshot"})]}),t.jsxs("div",{className:"detail-deps",children:[t.jsx("h4",{children:"Dependencies"}),z.length>0?t.jsx("ul",{className:"detail-dep-list",children:z.map(Y=>{const qe=s.find(It=>It.id===Y),lt=qe?.title||qe?.description||Y;return t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>ss(Y),onKeyDown:It=>{(It.key==="Enter"||It.key===" ")&&(It.preventDefault(),ss(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:ih(lt,40)})]}),t.jsx("button",{className:"dep-remove-btn",onClick:It=>Ls(It,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:()=>{J&&L(""),Q(Y=>!Y)},children:"Add Dependency"}),J&&(()=>{const Y=C.toLowerCase(),qe=Y?Ta.filter(lt=>lt.id.toLowerCase().includes(Y)||lt.title&<.title.toLowerCase().includes(Y)||lt.description&<.description.toLowerCase().includes(Y)):Ta;return t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:C,onChange:lt=>L(lt.target.value),onClick:lt=>lt.stopPropagation()}),qe.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):qe.map(lt=>t.jsxs("div",{className:"dep-dropdown-item",onClick:()=>{fs(lt.id),Q(!1)},children:[t.jsx("span",{className:"dep-dropdown-id",children:lt.id}),t.jsx("span",{className:"dep-dropdown-title",children:ih(lt.title||lt.description||lt.id,30)})]},lt.id))]})})()]})]}),e.column==="in-review"&&t.jsx(zM,{taskId:e.id,projectId:n,prInfo:e.prInfo,automationStatus:e.status??null,autoMerge:Yt?.autoMerge??!1,prAuthAvailable:p??!1,onPrCreated:Y=>{e.prInfo=Y,f(`PR #${Y.number} created`,"success")},onPrUpdated:Y=>{e.prInfo=Y},addToast:f})]})]})]}),t.jsx("div",{className:"modal-actions",children:re?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:ln,disabled:Gt,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:En,disabled:Gt,children:Gt?"Saving…":"Save"})]}):t.jsxs(t.Fragment,{children:[e.column==="triage"&&e.status==="awaiting-approval"&&S.prompt&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Gs,children:"Approve Plan"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:ie,children:"Reject Plan"})]}),e.column==="triage"&&e.status!=="awaiting-approval"&&!w&&t.jsx("button",{className:"btn btn-sm btn-danger",onClick:St,"aria-label":"Delete task",title:"Delete task",children:"Delete"}),(e.column!=="triage"||e.status==="awaiting-approval"||w||e.paused)&&t.jsxs("div",{className:"detail-actions-dropdown",ref:_t,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>{ee(Y=>!Y),$e(!1)},"aria-haspopup":"menu","aria-expanded":A,children:["Actions",t.jsx(Xt,{size:12})]}),A&&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:()=>sn(St),children:"Delete"}),m&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>sn(ci),children:"Duplicate"}),(e.column==="done"||e.column==="in-review")&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>sn(Me),children:"Refine"}),t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>sn(Ee),children:"Respecify"}),w&&u&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>sn(qn),children:"Retry"}),d&&e.column!=="done"&&e.column!=="archived"&&t.jsx("button",{className:"detail-actions-menu-item detail-actions-menu-item-danger",role:"menuitem",onClick:()=>sn(Ds),children:"Reset"}),e.column!=="done"&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>sn(Cs),children:e.paused?"Unpause":"Pause"})]})]}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("div",{className:"detail-move-dropdown",ref:jt,children:e.column==="in-review"?t.jsxs("div",{className:"detail-move-actions-in-review",children:[t.jsxs("div",{children:[t.jsxs("button",{ref:Lt,className:"btn btn-primary btn-sm detail-move-btn",onClick:Lr,onKeyDown:Ia,disabled:!Tn,"aria-label":Tn?`Move to ${Fn[Tn]}`:void 0,"aria-haspopup":ls?"menu":void 0,"aria-expanded":ls?pe:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",Tn?Fn[Tn]:""]}),ls&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(Xt,{size:12})})]}),pe&&ls&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:Mi,children:xi.map(Y=>t.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>gt(Y),onKeyDown:Mi,children:Y==="in-progress"?"Back to In Progress":`Move to ${Fn[Y]}`},Y))})]}),Fr?t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!0,children:Fr}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:mn,children:"Merge & Close"})]}):t.jsxs("div",{children:[t.jsxs("button",{ref:Lt,className:"btn btn-primary btn-sm detail-move-btn",onClick:Lr,onKeyDown:Ia,disabled:!Tn,"aria-label":Tn?`Move to ${Fn[Tn]}`:void 0,"aria-haspopup":ls?"menu":void 0,"aria-expanded":ls?pe:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",Tn?Fn[Tn]:""]}),ls&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(Xt,{size:12})})]}),pe&&ls&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:Mi,children:xi.map(Y=>t.jsxs("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>gt(Y),onKeyDown:Mi,children:["Move to ",Fn[Y]]},Y))})]})})]})}),Qe&&t.jsx("div",{className:"modal-overlay open detail-refine-overlay",onClick:dn,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:dn,"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:Ye,onChange:Y=>it(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:[Ye.length,"/2000 characters"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:gn,disabled:!Ye.trim()||Be,children:Be?"Creating...":"Create Refinement Task"})]})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:dn,disabled:Be,children:"Cancel"})})]})})]})})}const CA=640;function EA({isOpen:e,onClose:n,onImport:s,tasks:i,projectId:r}){const[o,l]=a.useState(""),[c,u]=a.useState(""),[d,m]=a.useState(""),[h,f]=a.useState(!1),[p,g]=a.useState("issues"),[b,v]=a.useState([]),[x,y]=a.useState(null),[k,_]=a.useState([]),[S,w]=a.useState(null),[M,N]=a.useState(null),[D,E]=a.useState(!1),[T,U]=a.useState([]),[K,$]=a.useState(!1),[R,z]=a.useState(""),B=a.useRef(!1),J=a.useRef(null);oi(J,e,"fusion:github-modal-size");const Q=Ei(n),[C,L]=a.useState(!1),[P,j]=a.useState("list"),O=a.useRef(null),H=new Set;for(const fe of i){const _e=fe.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);_e&&H.add(_e[1]);const Ue=fe.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);Ue&&H.add(Ue[1])}a.useEffect(()=>{if(e)return l(""),u(""),m(""),v([]),y(null),_([]),w(null),g("issues"),N(null),E(!1),U([]),$(!0),z(""),O.current=null,B.current=!0,Sy().then(fe=>{if(B.current)if(U(fe),$(!1),fe.length===1){const _e=fe[0];l(_e.owner),u(_e.repo),z(_e.name)}else fe.length>1&&(l(""),u(""),z(""))}).catch(()=>{B.current&&$(!1)}),()=>{B.current=!1}},[e]);const ge=a.useCallback(fe=>{if(z(fe),fe==="")l(""),u("");else{const _e=T.find(Ue=>Ue.name===fe);_e&&(l(_e.owner),u(_e.repo))}},[T]),be=a.useCallback(async()=>{if(!o.trim()||!c.trim()){N("Repository must be selected");return}f(!0),N(null),v([]),y(null);try{const fe=d.split(",").map(Ue=>Ue.trim()).filter(Boolean),_e=await jy(o.trim(),c.trim(),30,fe.length>0?fe:void 0);v(_e),_e.length===0&&N("No open issues found")}catch(fe){N(ye(fe)||"Failed to fetch issues")}finally{f(!1)}},[o,c,d]),se=a.useCallback(async()=>{if(!o.trim()||!c.trim()){N("Repository must be selected");return}f(!0),N(null),_([]),w(null);try{const fe=await wy(o.trim(),c.trim(),30);_(fe),fe.length===0&&N("No open pull requests found")}catch(fe){N(ye(fe)||"Failed to fetch pull requests")}finally{f(!1)}},[o,c]);a.useEffect(()=>{if(!e||!o.trim()||!c.trim()||h||D)return;const fe={owner:o.trim(),repo:c.trim(),labels:d.trim(),tab:p};O.current?.owner===fe.owner&&O.current?.repo===fe.repo&&O.current?.labels===fe.labels&&O.current?.tab===fe.tab||(O.current=fe,p==="issues"?be():se())},[o,c,d,p,e,h,D,be,se]),a.useEffect(()=>{if(!e)return;const fe=_e=>{_e.key==="Escape"&&n()};return document.addEventListener("keydown",fe),()=>document.removeEventListener("keydown",fe)},[e,n]),a.useEffect(()=>{if(!e)return;const fe=()=>{L(window.innerWidth<=CA)};return fe(),window.addEventListener("resize",fe),()=>window.removeEventListener("resize",fe)},[e]);const me=a.useCallback(fe=>{y(fe),C&&j("preview")},[C]),F=a.useCallback(fe=>{w(fe),C&&j("preview")},[C]),de=a.useCallback(()=>{j("list")},[]),ne=a.useCallback(async()=>{if(p==="issues"){if(x===null)return;E(!0),N(null);try{const fe=await ky(o.trim(),c.trim(),x,r);s(fe),y(null),C&&P==="preview"&&j("list")}catch(fe){const _e=ye(fe);_e?.includes("already imported")?N(_e):N(_e||"Failed to import issue")}finally{E(!1)}}else{if(S===null)return;E(!0),N(null);try{const fe=await Ny(o.trim(),c.trim(),S,r);s(fe),w(null),C&&P==="preview"&&j("list")}catch(fe){const _e=ye(fe);_e?.includes("already imported")?N(_e):N(_e||"Failed to import pull request")}finally{E(!1)}}},[p,x,S,o,c,s,C,P]),xe=b.find(fe=>fe.number===x),oe=k.find(fe=>fe.number===S);if(!e)return null;const he=T.length>0,ae=T.length===1,je=b.filter(fe=>H.has(fe.html_url)).length,Ae=k.filter(fe=>H.has(fe.html_url)).length,Oe=M==="No open issues found",Qe=M==="No open pull requests found",Xe=p==="issues"?Oe:Qe,Ye=!!M&&!Oe&&b.length===0&&!h,it=!!M&&!Qe&&k.length===0&&!h,Be=p==="issues"?Ye:it,Ge=h||b.length>0||Oe||Ye,re=h||k.length>0||Qe||it,ke=p==="issues"?Ge:re,X=!!M&&b.length>0&&!Oe,Te=!!M&&k.length>0&&!Qe,Le=p==="issues"?X:Te;return t.jsx("div",{className:"modal-overlay open",...Q,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg github-import-modal",ref:J,children:[t.jsxs("div",{className:"modal-header github-import-modal__header",children:[t.jsxs("div",{children:[t.jsx("h3",{children:"Import from GitHub"}),t.jsx("p",{className:"github-import-modal__subtitle",children:"Choose a detected remote, load open issues or pull requests, and import one into the board."})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close import modal",children:"×"})]}),t.jsxs("div",{className:"modal-body github-import-modal__body",children:[t.jsxs("div",{className:"github-import-tabs",role:"tablist","aria-label":"Import type",children:[t.jsxs("button",{role:"tab","aria-selected":p==="issues","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="issues"?"active":""}`,onClick:()=>{g("issues"),w(null)},disabled:h||D,children:[t.jsx(Oo,{size:16}),t.jsx("span",{children:"Issues"})]}),t.jsxs("button",{role:"tab","aria-selected":p==="pulls","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="pulls"?"active":""}`,onClick:()=>{g("pulls"),y(null)},disabled:h||D,children:[t.jsx(ks,{size:16}),t.jsx("span",{children:"Pull Requests"})]})]}),t.jsxs("div",{className:"github-import-toolbar","data-testid":"github-import-toolbar",role:"toolbar","aria-label":"GitHub import controls",children:[t.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--remote",children:K?t.jsxs("div",{className:"github-import-toolbar__loading",role:"status","aria-live":"polite",children:[t.jsx(ot,{size:16,className:"spin"}),t.jsx("span",{children:"Detecting…"})]}):he?ae?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:T[0].name}),t.jsxs("span",{className:"github-import-remote-pill__repo",children:[T[0].owner,"/",T[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:R,onChange:fe=>ge(fe.target.value),disabled:h||D,"aria-label":"Select Git remote",children:[t.jsx("option",{value:"",children:"Select remote…"}),T.map(fe=>t.jsxs("option",{value:fe.name,children:[fe.name," (",fe.owner,"/",fe.repo,")"]},fe.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:fe=>m(fe.target.value),onKeyDown:fe=>fe.key==="Enter"&&be(),disabled:h||D||!he,"aria-label":"Filter issues by labels"})]}):t.jsxs("span",{className:"github-import-filter-hint",children:["Open pull requests from ",o||"selected remote"]})}),t.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--action",children:t.jsxs("button",{id:"gh-load",className:"btn btn-primary github-import-load-button",onClick:p==="issues"?be:se,disabled:h||D||!o.trim()||!c.trim(),"aria-label":h?`Loading ${p}`:`Load ${p} from repository`,title:h?"Loading…":`Load ${p}`,children:[h?t.jsx(ot,{size:14,className:"spin"}):t.jsx($n,{size:14}),t.jsx("span",{children:h?"Loading…":"Load"})]})})]}),!K&&!he&&t.jsxs("div",{className:"github-import-state github-import-state--warning",role:"alert",children:[t.jsxs("div",{children:[t.jsx("strong",{children:"No GitHub remotes detected"}),t.jsx("span",{children:"Add a GitHub remote to this repository, then reopen the modal."})]}),t.jsx("code",{className:"github-import-command",children:"git remote add origin https://github.com/owner/repo.git"})]}),Le&&t.jsx("div",{className:"form-error github-import-banner",role:"alert",children:M}),t.jsxs("div",{className:"github-import-workspace",children:[t.jsxs("section",{className:`github-import-list-pane ${C?"mobile":""} ${P==="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:[je," imported"]})]}),p==="pulls"&&k.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[k.length," pull request",k.length===1?"":"s"]}),t.jsxs("span",{children:[Ae," imported"]})]})]}),t.jsxs("div",{className:"github-import-pane-content",children:[!ke&&t.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-results-idle",children:t.jsxs("div",{children:[t.jsx("strong",{children:"Nothing loaded yet"}),t.jsx("span",{children:"Select a repository and click Load to start reviewing import candidates."})]})}),h&&t.jsxs("div",{className:"github-import-state github-import-state--loading",role:"status","aria-live":"polite",children:[t.jsx(ot,{size:16,className:"spin"}),t.jsxs("div",{children:[t.jsxs("strong",{children:["Loading open ",p==="issues"?"issues":"pull requests","…"]}),t.jsx("span",{children:"Fetching the latest list from GitHub."})]})]}),Be&&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:M})]})}),Xe&&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(fe=>{const _e=H.has(fe.html_url);return t.jsxs("div",{className:`issue-item ${x===fe.number?"selected":""} ${_e?"imported":""}`,onClick:()=>!_e&&me(fe.number),children:[t.jsx("input",{type:"radio",name:"issue",checked:x===fe.number,onChange:()=>me(fe.number),disabled:_e,"aria-label":`Select issue #${fe.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",fe.number]}),t.jsx("span",{className:"issue-title",children:fe.title})]}),fe.labels.length>0&&t.jsx("span",{className:"issue-labels",children:fe.labels.map(Ue=>t.jsx("span",{className:"label-chip",children:Ue.name},Ue.name))})]}),_e&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},fe.number)})}),p==="pulls"&&k.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:k.map(fe=>{const _e=H.has(fe.html_url);return t.jsxs("div",{className:`issue-item ${S===fe.number?"selected":""} ${_e?"imported":""}`,onClick:()=>!_e&&F(fe.number),children:[t.jsx("input",{type:"radio",name:"pull",checked:S===fe.number,onChange:()=>F(fe.number),disabled:_e,"aria-label":`Select pull request #${fe.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",fe.number]}),t.jsx("span",{className:"issue-title",children:fe.title})]}),t.jsxs("span",{className:"pull-branch-info",children:[fe.headBranch," → ",fe.baseBranch]})]}),_e&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},fe.number)})})]})]}),t.jsxs("section",{className:`github-import-preview-pane ${C?"mobile":""} ${P==="preview"?"active":""}`,"data-testid":"github-import-preview-pane","aria-labelledby":"github-import-preview-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[C&&t.jsxs("button",{className:"github-import-back-button",onClick:de,"data-testid":"github-import-back-button","aria-label":`Back to ${p==="issues"?"issues":"pull requests"} list`,children:[t.jsx(Sa,{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"&&xe?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Issue #",xe.number]}),t.jsx("div",{className:"preview-title",children:xe.title}),t.jsx("div",{className:"preview-body",children:xe.body?xe.body.slice(0,200)+(xe.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"&&oe?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Pull Request #",oe.number]}),t.jsx("div",{className:"preview-title",children:oe.title}),t.jsxs("div",{className:"preview-branch",children:[t.jsx("strong",{children:"Branch:"})," ",oe.headBranch," → ",oe.baseBranch]}),t.jsx("div",{className:"preview-body",children:oe.body?oe.body.slice(0,200)+(oe.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:D,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:ne,disabled:(p==="issues"?x===null:S===null)||D,children:D?t.jsx(ot,{size:14,className:"spin"}):"Import"})]})]})})}const _A=["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 MA(e,n){return e&&n?`${e}/${n}`:""}function AA(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 RA({isOpen:e,onClose:n,onTaskCreated:s,onTasksCreated:i,tasks:r,initialPlan:o,projectId:l,resumeSessionId:c}){const[u,d]=a.useState(""),[m,h]=a.useState({type:"initial"}),[f,p]=a.useState(null),[g,b]=a.useState([]),[v,x]=a.useState([]),[y,k]=a.useState(null),_=a.useRef(!1),S=a.useRef(!1),[w,M]=a.useState(""),[N,D]=a.useState(!0),[E,T]=a.useState(!1),[U,K]=a.useState(!1),[$,R]=a.useState(null),[z,B]=a.useState(0),J=a.useRef(null),Q=a.useRef(null),C=a.useRef(null),L=a.useRef(null),[P,j]=a.useState(c??null),O=a.useMemo(()=>Ji(),[]),{isLockedByOther:H,takeControl:ge,isLoading:be}=Zo(e?P:null),{activeTabMap:se,broadcastUpdate:me,broadcastCompleted:F,broadcastLock:de,broadcastUnlock:ne,broadcastHeartbeat:xe}=Ma(),[oe,he]=a.useState(void 0),[ae,je]=a.useState(void 0),[Ae,Oe]=a.useState([]),[Qe,Xe]=a.useState(!1),[Ye,it]=a.useState(null),[Be,Ge]=a.useState([]),[re,ke]=a.useState([]),X=a.useRef(null),[Te,Le]=a.useState([]),[fe,_e]=a.useState(!1),[Ue,nt]=a.useState(c??null),[ve,ce]=a.useState(!!c),[De,ue]=a.useState(null),Re=a.useRef(!1),Ke=a.useRef(null);oi(Q,e,"fusion:planning-modal-size"),a.useEffect(()=>{const q=Ke.current;if(!q)return;q.scrollHeight-q.scrollTop-q.clientHeight<32&&(q.scrollTop=q.scrollHeight)},[w]),a.useEffect(()=>{if(m.type!=="loading"){R(null),B(0);return}const q=Date.now();R(q),B(0);const pe=setInterval(()=>{B(Math.max(0,Math.floor((Date.now()-q)/1e3)))},1e3);return()=>clearInterval(pe)},[m.type]);const Pe=a.useCallback(()=>{d(""),h({type:"initial"}),p(null),b([]),x([]),k(null),M(""),T(!1),K(!1),he(void 0),je(void 0),L.current=null,j(null)},[]),ft=MA(oe,ae),Z=a.useCallback((q,pe)=>{if(!q||!pe)return"Using default";const $e=Ae.find(A=>A.provider===q&&A.id===pe);return $e?`${$e.provider}/${$e.id}`:`${q}/${pe}`},[Ae]),le=a.useCallback(async()=>{Xe(!0),it(null);try{const q=await ms();Oe(q.models),Ge(q.favoriteProviders),ke(q.favoriteModels)}catch(q){it(ye(q)||"Failed to load models")}finally{Xe(!1)}},[]),we=a.useCallback(q=>{Ge(pe=>{const $e=pe,ee=$e.includes(q)?$e.filter(ze=>ze!==q):[q,...$e];return hn({favoriteProviders:ee,favoriteModels:re}).catch(()=>{Ge($e)}),ee})},[re]),Ze=a.useCallback(q=>{ke(pe=>{const $e=pe,ee=$e.includes(q)?$e.filter(ze=>ze!==q):[q,...$e];return hn({favoriteProviders:Be,favoriteModels:ee}).catch(()=>{ke($e)}),ee})},[Be]),te=a.useCallback(q=>{C.current?.close();const pe=Nj(q,l,{onThinking:$e=>{M(A=>A+$e),me({sessionId:q,status:"generating",needsInput:!1,owningTabId:O,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onQuestion:$e=>{T(!1),K(!1),sa(l),h({type:"question",session:{sessionId:q,currentQuestion:$e,summary:null}}),M(""),me({sessionId:q,status:"awaiting_input",needsInput:!0,owningTabId:O,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onSummary:$e=>{T(!1),K(!1),sa(l),h({type:"summary",session:{sessionId:q,currentQuestion:null,summary:$e},summary:$e}),k($e),M(""),me({sessionId:q,status:"complete",needsInput:!1,owningTabId:O,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onError:$e=>{const A=$e||"Session failed while contacting the AI.";T(!0),(async()=>{try{const ee=await hi(q);if(ee&&(ee.status==="generating"||ee.status==="awaiting_input")){te(q);return}}catch{}T(!1),K(!1),p(null),h(ee=>ee.type==="question"||ee.type==="summary"||ee.type==="error"?{type:"error",session:ee.session,errorMessage:A}:{type:"error",session:{sessionId:q,currentQuestion:null,summary:null},errorMessage:A}),M(""),L.current=q,me({sessionId:q,status:"error",needsInput:!1,owningTabId:O,type:"planning",title:u.trim()||"Planning session",projectId:l??null}),F({sessionId:q,status:"error"})})()},onComplete:()=>{T(!1),K(!1),L.current=null,F({sessionId:q,status:"complete"})},onConnectionStateChange:$e=>{T($e==="reconnecting")}});C.current=pe},[F,me,u,l,O]),Je=a.useCallback(async q=>{const pe=q??u;if(pe.trim()){p(null),M(""),x([]),b([]),T(!1),h({type:"loading"});try{const $e=oe&&ae?{planningModelProvider:oe,planningModelId:ae}:void 0,{sessionId:A}=await oj(pe.trim(),l,$e);L.current=A,j(A),nt(A),te(A),b([])}catch($e){T(!1),p(ye($e)||"Failed to start planning session"),h({type:"initial"}),L.current=null,j(null)}}},[te,u,ae,oe,l]);a.useEffect(()=>{e&&m.type==="initial"&&J.current?.focus()},[e,m.type]),a.useEffect(()=>{e&&le()},[e,le]),a.useEffect(()=>{if(e&&o&&!_.current&&m.type==="initial"){d(o);const q=setTimeout(()=>{_.current=!0,Je(o)},0);return()=>clearTimeout(q)}else if(e&&!o&&!_.current&&!S.current&&m.type==="initial"){S.current=!0;const q=y1(l);q&&d(q)}},[e,o,m.type,Je,l]);const dt=a.useCallback(async q=>{C.current?.close(),C.current=null,p(null),M(""),b([]),x([]),k(null),K(!1),h({type:"loading"});try{const pe=await hi(q);if(!pe){nt(null),ce(!1),h({type:"initial"});return}L.current=q,j(q);const $e=ba(pe.conversationHistory);if(x($e),b($e.map(A=>A.response).filter(A=>!!(A&&typeof A=="object"&&!Array.isArray(A)))),pe.status==="awaiting_input"&&pe.currentQuestion){sa(l);const A=JSON.parse(pe.currentQuestion);h({type:"question",session:{sessionId:q,currentQuestion:A,summary:null}}),pe.thinkingOutput&&M(pe.thinkingOutput),te(q)}else if(pe.status==="complete"&&pe.result){sa(l);const A=JSON.parse(pe.result);h({type:"summary",session:{sessionId:q,currentQuestion:null,summary:A},summary:A}),k(A)}else pe.status==="generating"?(h({type:"loading"}),pe.thinkingOutput&&M(pe.thinkingOutput),te(q)):pe.status==="error"&&h({type:"error",session:{sessionId:q,currentQuestion:null,summary:null},errorMessage:pe.error||"Session failed"})}catch{p("Failed to load session"),h({type:"initial"})}},[te,l]);a.useEffect(()=>{!e||!c||L.current!==c&&(nt(c),ce(!0),dt(c))},[e,c,dt]),a.useEffect(()=>{e&&Ue&&(c&&c===Ue||C.current?.isConnected()||dt(Ue))},[e]);const ut=a.useCallback(async()=>{_e(!0);try{const pe=(await ld(l)).filter($e=>$e.type==="planning").sort(($e,A)=>Date.parse(A.updatedAt)-Date.parse($e.updatedAt));Le(pe)}catch{}finally{_e(!1)}},[l]);a.useEffect(()=>{e&&ut()},[e,ut]),a.useEffect(()=>{if(!e)return;const q=l?`?projectId=${encodeURIComponent(l)}`:"",pe=A=>{try{const ee=JSON.parse(A.data);if(ee.type!=="planning")return;Le(ze=>{const mt=ze.findIndex(Lt=>Lt.id===ee.id);return(mt>=0?[...ze.slice(0,mt),ee,...ze.slice(mt+1)]:[ee,...ze]).sort((Lt,_t)=>Date.parse(_t.updatedAt)-Date.parse(Lt.updatedAt))})}catch{}},$e=A=>{try{const ee=JSON.parse(A.data);Le(ze=>ze.filter(mt=>mt.id!==ee))}catch{}};return Ks(`/api/events${q}`,{events:{"ai_session:updated":pe,"ai_session:deleted":$e},onReconnect:()=>{ut()}})},[e,l,ut]);const Ct=a.useCallback(q=>{if(Ue===q){ce(!0);return}nt(q),ce(!0),dt(q)},[dt,Ue]),yt=a.useCallback(()=>{C.current?.close(),C.current=null,Pe(),nt(null),ce(!0)},[Pe]),bt=a.useCallback(()=>{ce(!1)},[]),At=a.useCallback(async q=>{const pe=A=>A==="generating"||A==="awaiting_input",$e=Te.find(A=>A.id===q);if($e&&pe($e.status))try{await pp(q,l,O)}catch{}try{await wp(q)}catch{}F({sessionId:q,status:"complete",timestamp:Date.now()}),Le(A=>A.filter(ee=>ee.id!==q)),Ue===q&&(C.current?.close(),C.current=null,Pe(),nt(null),ce(!1)),ue(null)},[F,Te,l,Pe,Ue,O]);a.useEffect(()=>{e||(_.current=!1,S.current=!1,T(!1),K(!1),j(null))},[e]),a.useEffect(()=>{if(!e){X.current&&(ne(X.current,O),X.current=null);return}if(P&&X.current!==P){X.current&&ne(X.current,O),de(P,O),X.current=P;return}!P&&X.current&&(ne(X.current,O),X.current=null)},[de,ne,e,P,O]),a.useEffect(()=>{if(!e||!P||X.current!==P)return;xe(O);const q=setInterval(()=>{xe(O)},3e4);return()=>{clearInterval(q)}},[xe,e,P,O]),a.useEffect(()=>()=>{C.current?.close(),C.current=null,X.current&&(ne(X.current,O),X.current=null)},[ne,O]),a.useEffect(()=>{if(!e)return;const q=()=>{C.current?.close(),C.current=null};return window.addEventListener("beforeunload",q),()=>window.removeEventListener("beforeunload",q)},[e]);const Rt=a.useCallback(()=>{u&&m.type==="initial"&&v1(u,l),C.current?.close(),C.current=null,T(!1),K(!1),n()},[u,n,l,m.type]);a.useEffect(()=>{if(!e)return;const q=pe=>{pe.key==="Escape"&&Rt()};return document.addEventListener("keydown",q),()=>document.removeEventListener("keydown",q)},[e,Rt]);const Ht=a.useCallback(async q=>{if(m.type!=="question")return;const{session:pe}=m,$e=pe.sessionId,A=pe.currentQuestion;if(!A){p("No active question in session");return}p(null),b(ee=>[...ee,q]),x(ee=>[...ee,{question:A,response:q}]),h({type:"loading"}),M("");try{await lj($e,q,l,O)}catch(ee){p(ye(ee)||"Failed to submit response"),h({type:"question",session:pe})}},[l,O,m]),Et=a.useCallback(async()=>{const q=L.current;if(q){try{await dj(q,l,O)}catch{}C.current?.close(),C.current=null,T(!1),K(!1),h({type:"error",session:{sessionId:q,currentQuestion:null,summary:null},errorMessage:"Generation stopped by user. You can retry or start a new session."}),M("")}},[l,O]),Dt=a.useCallback(async()=>{if(m.type!=="error")return;const q=m.session;p(null),K(!0),M(""),h({type:"loading"}),te(q.sessionId);try{L.current=q.sessionId,j(q.sessionId),await cj(q.sessionId,l,O)}catch(pe){let $e=pe;if((ye(pe)||"").includes("not in an error state"))try{const ee=await hi(q.sessionId);if(!ee)throw new Error("Failed to refresh planning session.");if(L.current=ee.id,j(ee.id),ee.status==="generating")M(ee.thinkingOutput??""),h({type:"loading"});else if(ee.status==="awaiting_input"){if(!ee.currentQuestion)throw new Error("Planning session is awaiting input but has no current question.");const ze=JSON.parse(ee.currentQuestion);sa(l),h({type:"question",session:{sessionId:ee.id,currentQuestion:ze,summary:null}}),C.current?.isConnected()||te(ee.id)}else if(ee.status==="complete"){if(!ee.result)throw new Error("Planning session is complete but has no result.");const ze=JSON.parse(ee.result);sa(l),h({type:"summary",session:{sessionId:ee.id,currentQuestion:null,summary:ze},summary:ze}),k(ze)}else ee.status==="error"&&h({type:"error",session:{sessionId:ee.id,currentQuestion:null,summary:null},errorMessage:ee.error||"Retry failed. Please try again."});T(!1);return}catch(ee){$e=ee}C.current?.close(),C.current=null,h({type:"error",session:q,errorMessage:ye($e)||"Retry failed. Please try again."}),T(!1)}finally{K(!1)}},[te,l,O,m]),Kt=a.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const q=m.session.sessionId,pe=await uj(q,y??void 0,l);s(pe),nt(null),Le($e=>$e.filter(A=>A.id!==q)),F({sessionId:q,status:"complete",timestamp:Date.now()}),Rt()}catch(q){p(ye(q)||"Failed to create task"),h({type:"summary",session:m.session,summary:m.summary})}}},[F,y,m,l,s,Rt]),$t=a.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const q=await mj(m.session.sessionId,y??void 0,l);j(q.sessionId),h({type:"breakdown",sessionId:q.sessionId,subtasks:q.subtasks,dirty:!1})}catch(q){p(ye(q)||"Failed to start breakdown"),h({type:"summary",session:m.session,summary:m.summary})}}},[y,m,l]),Ft=a.useCallback(async()=>{if(m.type==="breakdown"){p(null),h({type:"creating"});try{const q=m.sessionId,pe=await hj(q,m.subtasks,l);i(pe.tasks),Le($e=>$e.filter(A=>A.id!==q)),F({sessionId:q,status:"complete",timestamp:Date.now()}),d(""),h({type:"initial"}),p(null),b([]),x([]),k(null),M(""),he(void 0),je(void 0),L.current=null,j(null),nt(null),n()}catch(q){p(ye(q)||"Failed to create tasks"),h({type:"breakdown",sessionId:m.sessionId,subtasks:m.subtasks,dirty:m.dirty})}}},[F,m,i,n,l]),Ot=a.useCallback(()=>{if(m.type==="question"&&g.length>0){const q=g.slice(0,-1);b(q),h({type:"question",session:m.session})}},[m,g]),Tt=()=>m.type==="question"?Math.min(g.length+1,3):3,Pt=P?se.get(P):null,wt=Pt&&Pt.tabId!==O,Gt=!!(wt&&!Pt.stale),Ut=H&&(!wt||Pt.stale);return e?t.jsx("div",{className:"modal-overlay open",onMouseDown:q=>{Re.current=q.target===q.currentTarget},onClick:q=>{q.target===q.currentTarget&&Re.current&&Rt(),Re.current=!1},role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",ref:Q,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[ve&&t.jsx("button",{className:"modal-back planning-mobile-back",onClick:bt,"aria-label":"Back to sessions",title:"Back to sessions",children:t.jsx(Fo,{size:18})}),t.jsx(si,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Planning Mode"})]}),t.jsx("div",{className:"modal-header-actions",children:t.jsx("button",{className:"modal-close",onClick:Rt,"aria-label":"Close",children:t.jsx(Wt,{size:20})})})]}),t.jsxs("div",{className:`planning-modal-body planning-modal-body--split ${ve?"planning-modal-body--show-detail":"planning-modal-body--show-list"}`,children:[t.jsx(DA,{sessions:Te,loading:fe,selectedSessionId:Ue,pendingDeleteId:De,onSelectSession:Ct,onNewSession:yt,onRequestDelete:ue,onConfirmDelete:q=>void At(q),onCancelDelete:()=>ue(null)}),t.jsxs("div",{className:"planning-detail",children:[f&&t.jsx("div",{className:"form-error planning-error",children:f}),E&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Gt&&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(rs,{size:32,className:"icon-triage-lg"}),t.jsx("h4",{children:"Transform your idea into a detailed task"}),t.jsx("p",{className:"text-muted",children:"Describe what you want to build in plain language. The AI will ask clarifying questions and help you structure a well-defined task."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"initial-plan",children:"What do you want to build?"}),t.jsx("textarea",{ref:J,id:"initial-plan",rows:4,className:"planning-textarea",placeholder:"e.g., Build a user authentication system with login, signup, and password reset...",value:u,onChange:q=>d(q.target.value),onKeyDown:q=>{q.key==="Enter"&&!q.shiftKey&&u.trim()&&(q.preventDefault(),Je())}})]}),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:_A.map((q,pe)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>d(q),children:q.length>40?q.slice(0,40)+"...":q},pe))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"planning-modal-model",className:"form-label",children:["Planning Model",Qe&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(Yn,{id:"planning-modal-model",label:"Planning Model",value:ft,onChange:q=>{const{provider:pe,modelId:$e}=AA(q);he(pe),je($e)},models:Ae,disabled:Qe,favoriteProviders:Be,onToggleFavorite:we,favoriteModels:re,onToggleModelFavorite:Ze}),Ye&&t.jsxs("div",{className:"form-hint form-hint-error",children:[Ye," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{le()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${oe&&ae?"model-badge-custom":"model-badge-default"}`,children:Z(oe,ae)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>Je(),disabled:!u.trim(),children:[t.jsx(si,{size:16,className:"icon-mr-8"}),"Start Planning"]})})]}),m.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(ot,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:w?"AI is thinking...":"Generating next question..."}),$&&t.jsxs("div",{className:"planning-elapsed",children:["Thinking… (",z,"s)"]}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>D(!N),type:"button",children:N?"Hide thinking":"Show thinking"}),t.jsx("div",{className:"planning-loading-actions",children:t.jsxs("button",{className:"btn planning-stop-btn",type:"button",onClick:()=>void Et(),children:[t.jsx(cb,{size:14}),t.jsx("span",{className:"icon-ml-6",children:"Stop"})]})}),N&&w&&t.jsx("div",{className:"planning-thinking-output",ref:Ke,children:t.jsx("pre",{children:w})})]})]}),m.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[v.length>0&&t.jsxs(t.Fragment,{children:[t.jsx($s,{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 Dt(),disabled:U,children:[U?t.jsx(ot,{size:14,className:"spin"}):t.jsx($n,{size:14}),t.jsx("span",{className:"icon-ml-6",children:U?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Rt,disabled:U,children:"Dismiss"})]})]})]})}),m.type==="creating"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(ot,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:"Creating tasks..."})]}),m.type==="question"&&m.session.currentQuestion&&t.jsx("div",{className:"planning-question",children:t.jsx(TA,{question:m.session.currentQuestion,progress:Tt(),historyEntries:v,onSubmit:Ht,onBack:g.length>0?Ot:void 0})}),m.type==="summary"&&y&&t.jsx(PA,{summary:y,historyEntries:v,onSummaryChange:k,tasks:r,onCreateTask:Kt,onBreakIntoTasks:$t,onRefine:()=>{h({type:"question",session:m.session})},isLoading:!1}),m.type==="breakdown"&&t.jsx($A,{subtasks:m.subtasks,dirty:m.dirty,isLoading:!1,onUpdateSubtasks:q=>h({...m,subtasks:q,dirty:!0}),onCreateTasks:Ft,onBack:()=>{const pe={sessionId:m.sessionId,currentQuestion:null,summary:y??null};y&&h({type:"summary",session:pe,summary:y})}})]}),H&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Ho,{size:16}),t.jsx("span",{children:Ut?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),Ut&&t.jsx("button",{type:"button",onClick:()=>{ge()},disabled:be,className:"btn btn-primary session-lock-take-control",children:be?"Taking control...":"Take Control"})]})})]})]})}):null}function TA({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($s,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3].map(h=>t.jsx("div",{className:`planning-progress-step ${h<=n?"active":""}`},h))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~3"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:c,onChange:h=>u(h.target.value),onKeyDown:h=>{h.key==="Enter"&&!h.shiftKey&&c.trim()&&(h.preventDefault(),d())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(h=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:h.id,checked:o[e.id]===h.id,onChange:()=>l({[e.id]:h.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:h.label}),h.description&&t.jsx("span",{className:"planning-option-desc",children:h.description})]})]},h.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(h=>{const f=o[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:h.id,checked:f.includes(h.id),onChange:p=>{const g=p.target.checked?[...f,h.id]:f.filter(b=>b!==h.id);l({[e.id]:g})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:h.label}),h.description&&t.jsx("span",{className:"planning-option-desc",children:h.description})]})]},h.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!0?"selected":""}`,onClick:()=>l({[e.id]:!0}),children:[t.jsx(yn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!1?"selected":""}`,onClick:()=>l({[e.id]:!1}),children:[t.jsx(Wt,{size:18}),"No"]})]})]})]})]})]}),t.jsxs("div",{className:"planning-actions",children:[r&&t.jsxs("button",{className:"btn",onClick:r,children:[t.jsx(Sa,{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(kr,{size:16,className:"icon-ml-4"})]})]})]})}function PA({summary:e,historyEntries:n,onSummaryChange:s,tasks:i,onCreateTask:r,onBreakIntoTasks:o,onRefine:l,isLoading:c}){const[u,d]=a.useState(!1),[m,h]=a.useState(e.suggestedDependencies),f=p=>{const g=m.includes(p)?m.filter(b=>b!==p):[...m,p];h(g),s({...e,suggestedDependencies:g})};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx($s,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(yn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Planning Complete!"}),t.jsx("p",{className:"text-muted",children:"Review and refine your task before creating it."})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{children:["Description",t.jsx("button",{type:"button",className:"planning-expand-btn",onClick:()=>d(!u),children:u?"Collapse":"Expand"})]}),t.jsx("textarea",{className:`planning-textarea ${u?"expanded":""}`,rows:u?10:4,value:e.description,onChange:p=>s({...e,description:p.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Suggested Size"}),t.jsxs("select",{className:"planning-size-select",value:e.suggestedSize,onChange:p=>s({...e,suggestedSize:p.target.value}),disabled:c,children:[t.jsx("option",{value:"S",children:"S (Small)"}),t.jsx("option",{value:"M",children:"M (Medium)"}),t.jsx("option",{value:"L",children:"L (Large)"})]})]}),i.length>0&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Suggested Dependencies"}),t.jsx("div",{className:"planning-deps-list",children:i.map(p=>t.jsxs("label",{className:`planning-dep-chip ${m.includes(p.id)?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:m.includes(p.id),onChange:()=>f(p.id)}),t.jsx("span",{className:"planning-dep-id",children:p.id}),t.jsx("span",{className:"planning-dep-title",children:p.title||p.description.slice(0,30)})]},p.id))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Key Deliverables"}),t.jsx("ul",{className:"planning-deliverables",children:e.keyDeliverables.map((p,g)=>t.jsx("li",{children:p},g))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:l,disabled:c,children:[t.jsx(Sa,{size:16,className:"icon-mr-4"}),"Refine Further"]}),t.jsxs("div",{className:"planning-summary-actions-right",children:[t.jsx("button",{className:"btn",onClick:o,disabled:c,title:"Break the plan into multiple tasks with dependencies",children:c?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:16,className:"spin icon-mr-8"}),"Breaking down..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Bo,{size:16,className:"icon-mr-8"}),"Break into Tasks"]})}),t.jsx("button",{className:"btn btn-primary",onClick:r,disabled:c,children:c?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:16,className:"spin icon-mr-8"}),"Creating..."]}):t.jsxs(t.Fragment,{children:[t.jsx(yn,{size:16,className:"icon-mr-8"}),"Create Task"]})})]})]})]})}function rh(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 IA(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function $A({subtasks:e,dirty:n,isLoading:s,onUpdateSubtasks:i,onCreateTasks:r,onBack:o}){const[l,c]=a.useState(null),[u,d]=a.useState(null),[m,h]=a.useState(null),f=a.useRef([]),p=a.useMemo(()=>e.length===0||e.some(M=>!M.title.trim())?!0:rh(e),[e]),g=a.useCallback((M,N)=>{i(e.map(D=>D.id===M?{...D,...N}:D))},[e,i]),b=a.useCallback(()=>{i([...e,IA(e.length+1)])},[e,i]),v=a.useCallback(M=>{i(e.filter(N=>N.id!==M).map(N=>({...N,dependsOn:N.dependsOn.filter(D=>D!==M)})))},[e,i]),x=a.useCallback((M,N)=>{if(N<0||N>=e.length)return;const D=[...e],[E]=D.splice(M,1);D.splice(N,0,E),i(D)},[e,i]),y=a.useCallback(M=>N=>{c(M),N.dataTransfer.setData("text/plain",M),N.dataTransfer.effectAllowed="move"},[]),k=a.useCallback(()=>{c(null),d(null),h(null)},[]),_=a.useCallback(M=>N=>{if(N.preventDefault(),M===l)return;const D=N.currentTarget.getBoundingClientRect(),E=D.top+D.height/2,T=N.clientY<E?"before":"after";d(M),h(T)},[l]),S=a.useCallback(M=>N=>{N.preventDefault();const D=N.dataTransfer.getData("text/plain");if(!D||D===M){k();return}const E=e.findIndex(R=>R.id===D),T=e.findIndex(R=>R.id===M);if(E===-1||T===-1){k();return}const U=[...e],[K]=U.splice(E,1);let $=T;m==="after"&&E<T&&$--,m==="after"&&$++,U.splice($,0,K),i(U),k()},[e,m,i,k]),w=a.useCallback(M=>{const N=M.currentTarget.getBoundingClientRect(),D=M.clientX,E=M.clientY;(D<N.left||D>N.right||E<N.top||E>N.bottom)&&(d(null),h(null))},[]);return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Bo,{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((M,N)=>{const D=l===M.id,E=u===M.id,T=["task-detail-section","subtask-item",D?"subtask-item-dragging":"",E?"subtask-item-drop-target":"",E&&m==="before"?"subtask-item-drop-before":"",E&&m==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:T,"data-testid":`subtask-item-${N}`,draggable:!s,onDragStart:y(M.id),onDragEnd:k,onDragOver:_(M.id),onDrop:S(M.id),onDragLeave:w,children:[t.jsxs("div",{className:"detail-title-row subtask-item-header subtask-item-header--between",children:[t.jsxs("div",{className:"subtask-drag-handle",title:"Drag to reorder",children:[t.jsx(id,{size:16}),t.jsx("strong",{children:M.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>x(N,N-1),disabled:s||N===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(zi,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>x(N,N+1),disabled:s||N===e.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(jr,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>v(M.id),disabled:s,children:[t.jsx(rn,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:U=>{f.current[N]=U},value:M.title,onChange:U=>g(M.id,{title:U.target.value}),onKeyDown:U=>{U.key==="Enter"&&(U.preventDefault(),N<e.length-1&&f.current[N+1]?.focus())},disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:M.description,onChange:U=>g(M.id,{description:U.target.value}),disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Size"}),t.jsxs("select",{className:"planning-size-select",value:M.suggestedSize,onChange:U=>g(M.id,{suggestedSize:U.target.value}),disabled:s,children:[t.jsx("option",{value:"S",children:"S"}),t.jsx("option",{value:"M",children:"M"}),t.jsx("option",{value:"L",children:"L"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"planning-deps-list",children:[e.slice(0,N).filter(U=>U.id!==M.id).map(U=>{const K=M.dependsOn.includes(U.id);return t.jsxs("label",{className:`planning-dep-chip ${K?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:K,onChange:()=>{const $=K?M.dependsOn.filter(R=>R!==U.id):[...M.dependsOn,U.id];g(M.id,{dependsOn:$})},disabled:s}),t.jsx("span",{className:"planning-dep-id",children:U.id}),t.jsx("span",{className:"planning-dep-title",children:U.title||"Untitled"})]},U.id)}),N===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),N>0&&e.slice(0,N).filter(U=>U.id!==M.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},M.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:b,disabled:s,children:[t.jsx(on,{size:16,className:"icon-mr-6"})," Add subtask"]}),rh(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(Sa,{size:16,className:"icon-mr-4"}),"Back to Summary"]}),t.jsx("button",{className:"btn btn-primary",onClick:r,disabled:s||p,children:s?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]})}function DA({sessions:e,loading:n,selectedSessionId:s,pendingDeleteId:i,onSelectSession:r,onNewSession:o,onRequestDelete:l,onConfirmDelete:c,onCancelDelete:u}){return t.jsxs("aside",{className:"planning-sidebar","aria-label":"Planning sessions",children:[t.jsx("div",{className:"planning-sidebar-header",children:t.jsxs("button",{className:`planning-sidebar-new ${s===null?"active":""}`,onClick:o,type:"button",children:[t.jsx(kx,{size:16}),t.jsx("span",{children:"New session"})]})}),t.jsxs("div",{className:"planning-sidebar-list",children:[e.length===0&&!n&&t.jsx("div",{className:"planning-sidebar-empty text-muted",children:"No saved sessions yet. Start one on the right to see it here."}),e.map(d=>{const m=d.id===s,h=i===d.id;return t.jsxs("div",{className:`planning-sidebar-item ${m?"selected":""} ${h?"pending-delete":""}`,children:[t.jsxs("button",{type:"button",className:"planning-sidebar-item-button",onClick:()=>r(d.id),children:[t.jsx(LA,{status:d.status}),t.jsxs("span",{className:"planning-sidebar-item-body",children:[t.jsx("span",{className:"planning-sidebar-item-title",children:d.title||"Untitled session"}),t.jsxs("span",{className:"planning-sidebar-item-meta",children:[t.jsx(zA,{status:d.status}),t.jsx("span",{"aria-hidden":!0,children:" · "}),t.jsx("span",{children:FA(d.updatedAt)})]})]})]}),h?t.jsxs("div",{className:"planning-sidebar-confirm",children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-danger",onClick:()=>c(d.id),children:"Delete"}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:u,children:"Cancel"})]}):t.jsx("button",{type:"button",className:"planning-sidebar-item-delete",onClick:f=>{f.stopPropagation(),l(d.id)},"aria-label":"Delete session",title:"Delete session",children:t.jsx(rn,{size:14})})]},d.id)})]})]})}function LA({status:e}){switch(e){case"generating":return t.jsx(ot,{size:14,className:"spin planning-sidebar-status-icon planning-sidebar-status-generating"});case"awaiting_input":return t.jsx(kc,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-awaiting"});case"complete":return t.jsx(yn,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-complete"});case"error":return t.jsx(us,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-error"});default:return t.jsx(Si,{size:14,className:"planning-sidebar-status-icon"})}}function zA({status:e}){switch(e){case"generating":return t.jsx("span",{children:"Generating"});case"awaiting_input":return t.jsx("span",{children:"Needs input"});case"complete":return t.jsx("span",{children:"Complete"});case"error":return t.jsx("span",{children:"Error"});default:return t.jsx("span",{children:e})}}function FA(e){const n=Date.now()-Date.parse(e);if(!Number.isFinite(n)||n<0)return"";const s=Math.floor(n/1e3);if(s<60)return"just now";const i=Math.floor(s/60);if(i<60)return`${i}m ago`;const r=Math.floor(i/60);if(r<24)return`${r}h ago`;const o=Math.floor(r/24);if(o<7)return`${o}d ago`;const l=Math.floor(o/7);return l<4?`${l}w ago`:new Date(e).toLocaleDateString()}function OA(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function oh(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 UA({isOpen:e,onClose:n,initialDescription:s,onTasksCreated:i,parentTaskId:r,projectId:o,resumeSessionId:l}){const[c,u]=a.useState({type:"initial"}),[d,m]=a.useState([]),[h,f]=a.useState([]),[p,g]=a.useState(""),[b,v]=a.useState(!0),[x,y]=a.useState(!1),[k,_]=a.useState(!1),[S,w]=a.useState(s),[M,N]=a.useState(null),[D,E]=a.useState(!1),[T,U]=a.useState(null),[K,$]=a.useState(null),[R,z]=a.useState(null),B=a.useRef(null),J=a.useRef([]),Q=a.useRef(!1),C=a.useRef(null),L=c.type==="generating"||c.type==="editing"||c.type==="creating"||c.type==="error"?c.sessionId:null,P=a.useMemo(()=>Ji(),[]),{isLockedByOther:j,takeControl:O,isLoading:H}=Zo(e?L:null),{activeTabMap:ge,broadcastUpdate:be,broadcastCompleted:se,broadcastLock:me,broadcastUnlock:F,broadcastHeartbeat:de}=Ma(),ne=a.useMemo(()=>d.length===0||d.some(ce=>!ce.title.trim())?!0:oh(d),[d]),xe=c.type==="generating"||c.type==="editing"||c.type==="error",oe=L?ge.get(L):null,{confirm:he}=Ws(),ae=oe&&oe.tabId!==P,je=!!(ae&&!oe.stale),Ae=j&&(!ae||oe.stale),Oe=a.useCallback(()=>{S&&j1(S,o),B.current?.close(),B.current=null,u({type:"initial"}),m([]),f([]),g(""),v(!0),y(!1),_(!1),N(null),E(!1),Q.current=!1},[S,o]),Qe=a.useCallback(()=>{B.current?.close(),B.current=null,n()},[n]),Xe=a.useCallback(async()=>{if(!((D||c.type==="editing"||c.type==="creating")&&!await he({title:"Discard Changes",message:"Close subtask breakdown? Unsaved changes will be lost.",danger:!0}))){if(L)try{await bp(L,o,P)}catch{}Oe(),n()}},[D,n,Oe,L,P,c.type,o,he]),Ye=a.useCallback(ce=>{B.current?.close(),B.current=Oj(ce,o,{onThinking:De=>{g(ue=>ue+De),be({sessionId:ce,status:"generating",needsInput:!1,owningTabId:P,type:"subtask",title:S.trim()||"Subtask breakdown",projectId:o??null})},onSubtasks:De=>{y(!1),_(!1),El(o),m(De),u({type:"editing",sessionId:ce}),E(!1),be({sessionId:ce,status:"awaiting_input",needsInput:!0,owningTabId:P,type:"subtask",title:S.trim()||"Subtask breakdown",projectId:o??null})},onError:De=>{const ue=De||"Session failed while contacting the AI.";y(!1),_(!1),N(null),u({type:"error",sessionId:ce,errorMessage:ue}),be({sessionId:ce,status:"error",needsInput:!1,owningTabId:P,type:"subtask",title:S.trim()||"Subtask breakdown",projectId:o??null}),se({sessionId:ce,status:"error"})},onComplete:()=>{se({sessionId:ce,status:"complete"})},onConnectionStateChange:De=>{y(De==="reconnecting")}})},[se,be,S,o,P]),it=a.useCallback(async()=>{if(S.trim()){N(null),f([]),g(""),y(!1);try{const{sessionId:ce}=await Lj(S.trim(),o);u({type:"generating",sessionId:ce}),Ye(ce)}catch(ce){N(ye(ce)||"Failed to start subtask breakdown"),u({type:"initial"})}}},[Ye,S,o]);a.useEffect(()=>{if(!e){Oe();return}if(e&&s&&!Q.current)w(s),Q.current=!0,it();else if(e&&!s&&!Q.current){const ce=k1(o);ce&&w(ce)}},[e,s,it,Oe]),a.useEffect(()=>{!e||!l||c.type!=="initial"||(async()=>{try{const ce=await hi(l);if(!ce)return;const De=ba(ce.conversationHistory);if(f(De),ce.status==="generating"||ce.status==="awaiting_input")g(ce.thinkingOutput??""),u({type:"generating",sessionId:l}),Ye(l);else if(ce.status==="complete"&&ce.result){El(o);const ue=JSON.parse(ce.result);m(ue),u({type:"editing",sessionId:l})}else ce.status==="error"&&(N(null),u({type:"error",sessionId:l,errorMessage:ce.error??"Session encountered an error"}))}catch(ce){N(ye(ce)||"Failed to resume session")}})()},[Ye,e,l,c.type,o]),a.useEffect(()=>{if(!e){C.current&&(F(C.current,P),C.current=null);return}if(L&&C.current!==L){C.current&&F(C.current,P),me(L,P),C.current=L;return}!L&&C.current&&(F(C.current,P),C.current=null)},[me,F,e,L,P]),a.useEffect(()=>{if(!e||!L||C.current!==L)return;de(P);const ce=setInterval(()=>{de(P)},3e4);return()=>{clearInterval(ce)}},[de,e,L,P]),a.useEffect(()=>()=>{B.current?.close(),C.current&&(F(C.current,P),C.current=null)},[F,P]),a.useEffect(()=>{if(!e)return;const ce=De=>{De.key==="Escape"&&(De.preventDefault(),Xe())};return document.addEventListener("keydown",ce),()=>document.removeEventListener("keydown",ce)},[e,Xe]);const Be=a.useCallback((ce,De)=>{m(ue=>ue.map(Re=>Re.id===ce?{...Re,...De}:Re)),E(!0)},[]),Ge=a.useCallback(()=>{m(ce=>[...ce,OA(ce.length+1)]),E(!0)},[]),re=a.useCallback(ce=>{m(De=>De.filter(ue=>ue.id!==ce).map(ue=>({...ue,dependsOn:ue.dependsOn.filter(Re=>Re!==ce)}))),E(!0)},[]),ke=a.useCallback(ce=>De=>{U(ce),De.dataTransfer.setData("text/plain",ce),De.dataTransfer.effectAllowed="move"},[]),X=a.useCallback(()=>{U(null),$(null),z(null)},[]),Te=a.useCallback(ce=>De=>{if(De.preventDefault(),ce===T)return;const ue=De.currentTarget.getBoundingClientRect(),Re=ue.top+ue.height/2,Ke=De.clientY<Re?"before":"after";$(ce),z(Ke)},[T]),Le=a.useCallback(ce=>De=>{De.preventDefault();const ue=De.dataTransfer.getData("text/plain");if(!ue||ue===ce){U(null),$(null),z(null);return}m(Re=>{const Ke=Re.findIndex(we=>we.id===ue),Pe=Re.findIndex(we=>we.id===ce);if(Ke===-1||Pe===-1)return Re;const ft=[...Re],[Z]=ft.splice(Ke,1);let le=Pe;return R==="after"&&Ke<Pe&&le--,R==="after"&&le++,ft.splice(le,0,Z),ft}),E(!0),U(null),$(null),z(null)},[R]),fe=a.useCallback(ce=>{const De=ce.currentTarget.getBoundingClientRect(),ue=ce.clientX,Re=ce.clientY;(ue<De.left||ue>De.right||Re<De.top||Re>De.bottom)&&($(null),z(null))},[]),_e=a.useCallback((ce,De)=>{De<0||De>=d.length||(m(ue=>{const Re=[...ue],[Ke]=Re.splice(ce,1);return Re.splice(De,0,Ke),Re}),E(!0))},[d.length]),Ue=a.useCallback(ce=>{J.current[ce+1]?.focus()},[]),nt=a.useCallback(async()=>{if(!(!L||ne)){N(null),u({type:"creating",sessionId:L});try{const ce=await Uj(L,d,r,o);i(ce.tasks),Oe(),n()}catch(ce){N(ye(ce)||"Failed to create tasks"),u({type:"editing",sessionId:L})}}},[ne,n,i,r,o,Oe,L,d]),ve=a.useCallback(async()=>{if(c.type!=="error")return;const ce=c.sessionId;N(null),_(!0),g(""),u({type:"generating",sessionId:ce}),Ye(ce);try{await zj(ce,o,P)}catch(De){let ue=De;if((ye(De)||"").includes("not in an error state"))try{const Ke=await hi(ce);if(!Ke)throw new Error("Failed to refresh subtask session.");if(f(ba(Ke.conversationHistory)),Ke.status==="generating"||Ke.status==="awaiting_input")g(Ke.thinkingOutput??""),u({type:"generating",sessionId:Ke.id}),B.current?.isConnected()||Ye(Ke.id);else if(Ke.status==="complete"){if(!Ke.result)throw new Error("Subtask session is complete but has no result.");El(o);const Pe=JSON.parse(Ke.result);m(Pe),u({type:"editing",sessionId:Ke.id}),E(!1)}else Ke.status==="error"&&u({type:"error",sessionId:Ke.id,errorMessage:Ke.error??"Retry failed. Please try again."});y(!1);return}catch(Ke){ue=Ke}B.current?.close(),B.current=null,u({type:"error",sessionId:ce,errorMessage:ye(ue)||"Retry failed. Please try again."}),y(!1)}finally{_(!1)}},[Ye,o,P,c]);return e?t.jsx("div",{className:"modal-overlay open",onClick:ce=>ce.target===ce.currentTarget&&void Xe(),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(Bo,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Subtask Breakdown"})]}),t.jsxs("div",{className:"modal-header-actions",children:[xe&&t.jsx("button",{className:"modal-send-to-background",onClick:Qe,title:"Send to background","aria-label":"Send to background",children:t.jsx(Sr,{size:16})}),t.jsx("button",{className:"modal-close",onClick:()=>void Xe(),"aria-label":"Close",children:t.jsx(Wt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[M&&t.jsx("div",{className:"form-error planning-error",children:M}),x&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),je&&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:S})]})}),c.type==="generating"&&t.jsxs("div",{className:"planning-loading",children:[h.length>0&&t.jsxs(t.Fragment,{children:[t.jsx($s,{entries:h,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsx(ot,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:"AI is generating subtasks..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>v(!b),type:"button",children:b?"Hide thinking":"Show thinking"}),b&&p&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:p})})]})]}),c.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[h.length>0&&t.jsxs(t.Fragment,{children:[t.jsx($s,{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 ve(),disabled:k,children:[k?t.jsx(ot,{size:14,className:"spin"}):t.jsx($n,{size:14}),t.jsx("span",{className:"icon-ml-6",children:k?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:()=>void Xe(),disabled:k,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($s,{entries:h}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(yn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Review your subtasks"}),t.jsx("p",{className:"text-muted",children:"Edit titles, descriptions, sizes, and dependencies before creating all tasks at once."})]}),t.jsxs("div",{className:"planning-summary-form",children:[d.map((ce,De)=>{const ue=T===ce.id,Re=K===ce.id,Ke=["task-detail-section","subtask-item",ue?"subtask-item-dragging":"",Re?"subtask-item-drop-target":"",Re&&R==="before"?"subtask-item-drop-before":"",Re&&R==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:Ke,"data-testid":`subtask-item-${De}`,draggable:c.type!=="creating",onDragStart:ke(ce.id),onDragEnd:X,onDragOver:Te(ce.id),onDrop:Le(ce.id),onDragLeave:fe,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(id,{size:16}),t.jsx("strong",{children:ce.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>_e(De,De-1),disabled:c.type==="creating"||De===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(zi,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>_e(De,De+1),disabled:c.type==="creating"||De===d.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(jr,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>re(ce.id),disabled:c.type==="creating",children:[t.jsx(rn,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:Pe=>{J.current[De]=Pe},value:ce.title,onChange:Pe=>Be(ce.id,{title:Pe.target.value}),onKeyDown:Pe=>{Pe.key==="Enter"&&(Pe.preventDefault(),Ue(De))},disabled:c.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:8,value:ce.description,onChange:Pe=>Be(ce.id,{description:Pe.target.value}),disabled:c.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Size"}),t.jsxs("select",{className:"planning-size-select",value:ce.suggestedSize,onChange:Pe=>Be(ce.id,{suggestedSize:Pe.target.value}),disabled:c.type==="creating",children:[t.jsx("option",{value:"S",children:"S"}),t.jsx("option",{value:"M",children:"M"}),t.jsx("option",{value:"L",children:"L"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"planning-deps-list",children:[d.slice(0,De).filter(Pe=>Pe.id!==ce.id).map(Pe=>{const ft=ce.dependsOn.includes(Pe.id);return t.jsxs("label",{className:`planning-dep-chip ${ft?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:ft,onChange:()=>{const Z=ft?ce.dependsOn.filter(le=>le!==Pe.id):[...ce.dependsOn,Pe.id];Be(ce.id,{dependsOn:Z})},disabled:c.type==="creating"}),t.jsx("span",{className:"planning-dep-id",children:Pe.id}),t.jsx("span",{className:"planning-dep-title",children:Pe.title||"Untitled"})]},Pe.id)}),De===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),De>0&&d.slice(0,De).filter(Pe=>Pe.id!==ce.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},ce.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:Ge,disabled:c.type==="creating",children:[t.jsx(on,{size:16,className:"icon-mr-6"})," Add subtask"]}),oh(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 Xe(),disabled:c.type==="creating",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:()=>void nt(),disabled:c.type==="creating"||ne,children:c.type==="creating"?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]}),j&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Ho,{size:16}),t.jsx("span",{children:Ae?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),Ae&&t.jsx("button",{type:"button",onClick:()=>{O()},disabled:H,className:"btn btn-primary session-lock-take-control",children:H?"Taking control...":"Take Control"})]})})]})]})}):null}const BA=5,HA=1e3,qA=45e3;function co(){return{scrollback:null,connected:null,data:[]}}function VA(e,n){const[s,i]=a.useState("disconnected"),r=a.useRef(0),o=a.useRef(e),l=a.useRef(n),c=o.current!==e||l.current!==n;c&&(o.current=e,l.current=n,r.current++);const u=a.useRef(null),d=a.useRef(0),m=a.useRef(null),h=a.useRef(null),f=a.useRef(!1),p=a.useRef(new Set),g=a.useRef(new Set),b=a.useRef(new Set),v=a.useRef(new Set),x=a.useRef(new Set),y=a.useRef(co()),k=a.useCallback($=>{p.current.add($);const R=y.current;return R.data.length>0&&(R.data.forEach(z=>$(z)),R.data=[]),()=>p.current.delete($)},[]),_=a.useCallback($=>(g.current.add($),()=>g.current.delete($)),[]),S=a.useCallback($=>{b.current.add($);const R=y.current;return R.connected&&($(R.connected),R.connected=null),()=>b.current.delete($)},[]),w=a.useCallback($=>{v.current.add($);const R=y.current;return R.scrollback&&($(R.scrollback),R.scrollback=null),()=>v.current.delete($)},[]),M=a.useCallback($=>(x.current.add($),()=>x.current.delete($)),[]),N=a.useCallback($=>{const R=u.current;R?.readyState===WebSocket.OPEN&&R.send(JSON.stringify({type:"input",data:$}))},[]),D=a.useCallback(($,R)=>{const z=u.current;z?.readyState===WebSocket.OPEN&&z.send(JSON.stringify({type:"resize",cols:$,rows:R}))},[]),E=a.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.current=null),u.current&&(u.current.onopen=null,u.current.onmessage=null,u.current.onclose=null,u.current.onerror=null,u.current.close(),u.current=null),y.current=co()},[]),T=a.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.current=null),u.current&&(f.current=!0,u.current.close(),u.current=null),y.current=co()},[]),U=a.useCallback(()=>{if(!e){i("disconnected");return}if(u.current?.readyState===WebSocket.OPEN)return;u.current&&(f.current=!0,u.current.close()),f.current=!1,i("connecting");const $=r.current;let z=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/terminal/ws?sessionId=${encodeURIComponent(e)}`;n&&(z+=`&projectId=${encodeURIComponent(n)}`);const B=new WebSocket(ii(z));u.current=B,B.onopen=()=>{if(r.current!==$){B.close();return}y.current=co(),i("connected"),d.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{r.current===$&&B.readyState===WebSocket.OPEN&&B.send(JSON.stringify({type:"ping"}))},qA)},B.onmessage=J=>{if(r.current===$)try{const Q=JSON.parse(J.data),C=y.current;switch(Q.type){case"data":Q.data&&(p.current.size===0&&C.data.push(Q.data),p.current.forEach(L=>L(Q.data)));break;case"scrollback":Q.data&&(C.scrollback=Q.data,v.current.forEach(L=>L(Q.data)));break;case"connected":Q.shell&&Q.cwd&&(C.connected={shell:Q.shell,cwd:Q.cwd},b.current.forEach(L=>L({shell:Q.shell,cwd:Q.cwd})));break;case"exit":Q.exitCode!==void 0&&g.current.forEach(L=>L(Q.exitCode));break;case"ping":B.readyState===WebSocket.OPEN&&B.send(JSON.stringify({type:"pong"}));break;case"pong":break}}catch{}},B.onclose=J=>{if(r.current!==$)return;if(u.current=null,h.current&&(clearInterval(h.current),h.current=null),f.current){i("disconnected");return}if(J.code===4e3||J.code===4004){i("disconnected"),J.code===4004&&x.current.forEach(L=>L());return}if(d.current++,d.current>BA){i("disconnected");return}const Q=HA*Math.pow(2,d.current-1);i("reconnecting");const C=r.current;m.current=setTimeout(()=>{r.current===C&&(f.current||U())},Math.min(Q,16e3))},B.onerror=()=>{}},[e,n]),K=a.useCallback(()=>{d.current=0,T(),U()},[T,U]);return a.useEffect(()=>(c&&(E(),d.current=0,i("disconnected")),e?U():i("disconnected"),T),[e,n,c,U,T,E]),{connectionStatus:s,sendInput:N,resize:D,onData:k,onExit:_,onConnect:S,onScrollback:w,reconnect:K,onSessionInvalid:M}}const ag="kb-terminal-tabs",WA=15e3,KA=15e3;function lh(){return`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function ch(e){if(typeof window>"u")return[];try{const n=Qn(ag,e);if(n)return JSON.parse(n)}catch{}return[]}function rc(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return n.includes("Failed to parse URL")||n.includes("Invalid URL")}function dh(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 GA(e){const[n,s]=a.useState(()=>ch(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(ch(e)),r(!1),l(!0),u(null)},[e]),a.useEffect(()=>{try{bs(ag,JSON.stringify(n),e)}catch{}},[e,n]),a.useEffect(()=>{let S=!1;const w=h.current;return(async()=>{if(!S)try{const N=await dh(Iy(e),WA,"listTerminalSessions");if(S||w!==h.current)return;const D=new Set(N.map(E=>E.id));l(!0),s(E=>{if(S||w!==h.current)return E;const U=E.map(R=>({...R,_verified:D.has(R.sessionId)})).filter(R=>R._verified);if(U.length===0)return[];const K=U.map(({_verified:R,...z})=>z);return K.find(R=>R.isActive)?K:K.map((R,z)=>({...R,isActive:z===0}))}),r(!0)}catch(N){if(S||w!==h.current)return;const D=rc(N);D||console.warn("Failed to validate terminal sessions with server:",N),l(!D),r(!0)}})(),()=>{S=!0}},[e]),a.useEffect(()=>{if(n.length===0&&i&&o){const S=h.current,w=setTimeout(()=>{dh(qr(void 0,void 0,void 0,e),KA,"createTerminalSession").then(M=>{if(S!==h.current)return;const N={id:lh(),sessionId:M.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};s(D=>D.length>0?D:[...D.map(T=>({...T,isActive:!1})),N]),u(null)}).catch(M=>{if(S!==h.current)return;rc(M)||console.error(M);const N=M instanceof Error?M.message:typeof M=="string"?M:"Failed to create terminal session";u(N)})},0);return()=>clearTimeout(w)}},[i,o,n.length,d]);const f=a.useCallback(async()=>{const S=await qr(void 0,void 0,void 0,e),w={id:lh(),sessionId:S.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};return s(M=>[...M.map(D=>({...D,isActive:!1})),w]),w},[n.length]),p=a.useCallback(async()=>f(),[f]),g=a.useCallback(S=>{s(w=>{const M=w.find(T=>T.id===S);if(!M)return w;Jd(M.sessionId,e).catch(T=>{console.warn(`Failed to kill terminal session ${M.sessionId}:`,T)});const N=w.findIndex(T=>T.id===S),D=M.isActive,E=w.filter(T=>T.id!==S);if(E.length===0)return[];if(D){const T=Math.min(N,E.length-1);return E.map((U,K)=>({...U,isActive:K===T}))}return E})},[]),b=a.useCallback(S=>{s(w=>{let M=!1;const N=w.map(D=>D.id===S?(M=!0,{...D,isActive:!0}):{...D,isActive:!1});return M?N:w})},[]),v=a.useCallback((S,w)=>{s(M=>M.map(N=>N.id===S?{...N,title:w}:N))},[]),x=a.useCallback(async()=>{s(M=>{const N=M.find(D=>D.isActive);return N&&Jd(N.sessionId,e).catch(D=>{console.warn(`Failed to kill old session ${N.sessionId}:`,D)}),M});const S=n.find(M=>M.isActive);if(!S)return;const w=await qr(void 0,void 0,void 0,e);s(M=>M.map(N=>N.id===S.id?{...N,sessionId:w.sessionId}:N))},[n]),y=a.useCallback(async()=>{const S=n.find(w=>w.isActive);if(S)try{const w=await qr(void 0,void 0,void 0,e);s(M=>M.map(N=>N.id===S.id?{...N,sessionId:w.sessionId}:N)),u(null)}catch(w){rc(w)||console.error(w);const M=w instanceof Error?w.message:typeof w=="string"?w:"Failed to create terminal session";u(M)}},[n]),k=n.find(S=>S.isActive)??null,_=a.useCallback(()=>{u(null),h.current+=1,m(S=>S+1)},[]);return{tabs:n,activeTab:k,isReady:i,bootstrapError:c,createTab:p,closeTab:g,setActiveTab:b,updateTabTitle:v,restartActiveTab:x,retryBootstrap:_,replaceActiveTabSession:y}}const JA=1e4,YA=[500,1500,3e3],rg="kb-terminal-font-size",ir=14,QA=8,XA=32,ZA='"MesloLGS NF", "MesloLGM Nerd Font", "JetBrainsMono Nerd Font", "FiraCode Nerd Font", "Hack Nerd Font", ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace';function eR(e){if(!e)return"";const n=e.slice(0,1).toUpperCase();return n==="["?"\x1B":n>="A"&&n<="Z"?String.fromCharCode(n.charCodeAt(0)-64):e}function tR(e){return`\x1B${e}`}const nR=[{label:"C",key:"c",description:"SigInt"},{label:"D",key:"d",description:"EOF"},{label:"Z",key:"z",description:"Suspend"},{label:"L",key:"l",description:"Clear"},{label:"R",key:"r",description:"Reverse search"},{label:"A",key:"a",description:"Home"},{label:"E",key:"e",description:"End"},{label:"U",key:"u",description:"Kill line"},{label:"K",key:"k",description:"Kill to EOL"},{label:"W",key:"w",description:"Del word"},{label:".",key:".",description:"Last argument"}];function ar(e){return Math.min(XA,Math.max(QA,e))}function sR(){if(typeof window>"u")return ir;try{const e=window.localStorage.getItem(rg);if(!e)return ir;const n=Number.parseInt(e,10);return Number.isFinite(n)?ar(n):ir}catch{return ir}}function iR(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 aR(e){return new Promise(n=>setTimeout(n,e))}async function rR(e,n=YA){let s;for(let i=0;i<=n.length;i+=1)try{return await e()}catch(r){if(!iR(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 aR(o)}throw s??new Error("Dynamic import failed")}function uh(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}function oR(){if(typeof window>"u"||!window.visualViewport)return 0;const e=window.visualViewport,n=Math.max(0,window.innerHeight-e.offsetTop-e.height);if(n>0)return n;const i=lR()-e.offsetTop-e.height;return i>=30&&i>80?i:0}let oc=null;function lR(){return oc===null&&(oc=window.innerHeight),oc}function cR({isOpen:e,onClose:n,initialCommand:s,projectId:i}){const[r,o]=a.useState(null),[l,c]=a.useState(null),[u,d]=a.useState(!1),[m,h]=a.useState(null),[f,p]=a.useState(0),[g,b]=a.useState(0),[v,x]=a.useState(null),[y,k]=a.useState(()=>sR()),[_,S]=a.useState(!1),[w,M]=a.useState(null),N=a.useRef(null),D=a.useRef(null),E=a.useRef(!1);oi(D,e,"fusion:terminal-modal-size");const T=a.useRef(null),U=a.useRef(null),K=a.useRef(!1),$=a.useRef(!1),R=a.useRef(null),z=a.useRef(()=>{}),B=a.useRef(null),J=a.useRef(0),Q=a.useRef(y),C=a.useRef(null),L=a.useRef(i);J.current=g,Q.current=y;const P=a.useCallback(ue=>{if(ue&&$.current!==ue)return;const Re=U.current,Ke=T.current,Pe=R.current;if(!(!Re||!Ke)&&!(ue&&$.current!==ue))try{Re.fit(),Pe&&Pe(Ke.cols,Ke.rows)}catch{}},[]);a.useEffect(()=>{e&&p(ue=>ue+1)},[e]),a.useEffect(()=>{if(!e||!uh())return;const ue=window.visualViewport;if(!ue)return;const Re=()=>{const Ke=oR();b(Ke),x(ue.height),Ke>0&&D.current?.scrollIntoView&&D.current.scrollIntoView({block:"end",behavior:"smooth"}),C.current!==null&&(cancelAnimationFrame(C.current),C.current=null);const Pe=typeof $.current=="string"?$.current:void 0;C.current=requestAnimationFrame(()=>{C.current=null,P(Pe)})};return Re(),ue.addEventListener("resize",Re),ue.addEventListener("scroll",Re),()=>{ue.removeEventListener("resize",Re),ue.removeEventListener("scroll",Re),C.current!==null&&(cancelAnimationFrame(C.current),C.current=null),b(0),x(null)}},[P,e]),a.useEffect(()=>{if(!e)return;const ue=D.current;if(!ue||typeof ResizeObserver>"u")return;let Re=null;const Ke=new ResizeObserver(()=>{Re!==null&&cancelAnimationFrame(Re),Re=requestAnimationFrame(()=>{Re=null;const Pe=typeof $.current=="string"?$.current:void 0;P(Pe)})});return Ke.observe(ue),()=>{Ke.disconnect(),Re!==null&&cancelAnimationFrame(Re)}},[P,e]);const{tabs:j,activeTab:O,isReady:H,bootstrapError:ge,createTab:be,closeTab:se,setActiveTab:me,updateTabTitle:F,restartActiveTab:de,retryBootstrap:ne,replaceActiveTabSession:xe}=GA(i),{connectionStatus:oe,sendInput:he,resize:ae,onData:je,onConnect:Ae,onExit:Oe,onScrollback:Qe,reconnect:Xe,onSessionInvalid:Ye}=VA(O?.sessionId??null,i);R.current=ae,z.current=he,a.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(rg,String(y))}catch{}},[y]);const it=a.useCallback(()=>{const ue=T.current;if(ue)try{U.current?.fit(),ae(ue.cols,ue.rows)}catch{}},[ae]);a.useEffect(()=>{if(!e||!H)return;const ue=O?.sessionId;if(!ue)return;const Re=L.current!==i;if(Re&&(L.current=i),$.current===ue&&T.current&&!Re)return;T.current&&($.current!==ue||Re)&&(T.current.dispose(),T.current=null,U.current=null,$.current=!1,B.current&&(window.removeEventListener("resize",B.current),B.current=null),d(!1),h(null));let Ke=!0,Pe;return(async()=>{const Z=rR(()=>Promise.all([un(()=>import("./vendor-xterm-DzcZoU0P.js").then(te=>te.x),__vite__mapDeps([0,1,2])),un(()=>import("./addon-fit-C7jRorKK.js").then(te=>te.a),__vite__mapDeps([3,1])),un(()=>import("./addon-web-links-CkJwd4cQ.js").then(te=>te.a),__vite__mapDeps([4,1]))])),le=new Promise((te,Je)=>{Pe=setTimeout(()=>{Je(new Error("xterm initialization timed out"))},JA)});let we,Ze;try{const[{Terminal:te},{FitAddon:Je},{WebLinksAddon:dt}]=await Promise.race([Z,le]);if(!Ke||!N.current||T.current)return;we=new te({cursorBlink:!0,cursorStyle:"block",fontSize:Q.current,fontFamily:ZA,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}),Ze=new Je,we.loadAddon(Ze);const ut=new dt;if(we.loadAddon(ut),!uh())try{const{WebglAddon:bt}=await un(async()=>{const{WebglAddon:Rt}=await import("./addon-webgl-BjvOw43o.js").then(Ht=>Ht.a);return{WebglAddon:Rt}},__vite__mapDeps([5,1])),At=new bt;At.onContextLoss(()=>{At.dispose()}),we.loadAddon(At)}catch{}we.open(N.current),Pe&&clearTimeout(Pe);const Ct=N.current?.querySelector(".xterm-helper-textarea");if(Ct&&Ct.focus(),N.current)try{N.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}setTimeout(()=>{Ze.fit();const bt=N.current?.querySelector(".xterm-helper-textarea");bt&&bt.focus()},50),T.current=we,U.current=Ze,$.current=ue,J.current>0&&(C.current!==null&&(cancelAnimationFrame(C.current),C.current=null),C.current=requestAnimationFrame(()=>{C.current=null,P(ue)})),we.onData(bt=>{$.current===ue&&z.current(bt)});const yt=()=>{if($.current===ue&&U.current&&T.current)try{U.current.fit();const{cols:bt,rows:At}=T.current;R.current?.(bt,At)}catch{}};window.addEventListener("resize",yt),B.current&&window.removeEventListener("resize",B.current),B.current=yt,d(!0),h(null)}catch(te){if(Pe&&clearTimeout(Pe),!Ke)return;const Je=te instanceof Error?te.message:"xterm initialization failed";h(Je)}})(),()=>{Ke=!1,Pe&&clearTimeout(Pe)}},[P,e,H,O?.sessionId,i]),a.useEffect(()=>{e||(T.current&&(T.current.dispose(),T.current=null),U.current=null,$.current=!1,B.current&&(window.removeEventListener("resize",B.current),B.current=null),d(!1),h(null),K.current=!1,o(null),c(null),S(!1),M(null))},[e]),a.useEffect(()=>{if(!u||!T.current||!O)return;const ue=O.sessionId,Re=le=>{$.current===ue&&T.current?.write(le)},Ke=je(le=>{Re(le)}),Pe=Qe(le=>{Re(le)}),ft=Ae(le=>{F(O.id,ud(le.shell)||le.shell)}),Z=Oe(le=>{$.current===ue&&(c(le),T.current?.write(`\r
|
|
653
|
-
\x1B[33m[Process exited with code ${le}]\x1B[0m\r
|
|
654
|
-
`))});return()=>{Ke(),Pe(),ft(),Z()}},[u,O?.sessionId,O?.id,O,oe,je,Qe,Ae,Oe,F]),a.useEffect(()=>{oe==="connected"&&s&&K.current!==s&&O&&(K.current=s,setTimeout(()=>{he(s+`
|
|
655
|
-
`)},500))},[oe,s,he,O,f]),a.useEffect(()=>{if(!u||!T.current)return;T.current.options.fontSize=y,C.current!==null&&(cancelAnimationFrame(C.current),C.current=null);const ue=requestAnimationFrame(()=>{C.current=null,it()});return C.current=ue,()=>{C.current===ue&&(cancelAnimationFrame(ue),C.current=null)}},[y,u,it]),a.useEffect(()=>{if(!e)return;const ue=Re=>{if(!(!Re.ctrlKey&&!Re.metaKey)){if(Re.code==="Equal"||Re.code==="NumpadAdd"){Re.preventDefault(),k(Ke=>ar(Ke+1));return}if(Re.code==="Minus"||Re.code==="NumpadSubtract"){Re.preventDefault(),k(Ke=>ar(Ke-1));return}if(Re.code==="Digit0"||Re.code==="Numpad0"){Re.preventDefault(),k(ir);return}}};return window.addEventListener("keydown",ue),()=>window.removeEventListener("keydown",ue)},[e,it]),a.useEffect(()=>{if(!e)return;const ue=Re=>{Re.key==="Escape"&&n()};return document.addEventListener("keydown",ue),()=>document.removeEventListener("keydown",ue)},[e,n]),a.useEffect(()=>{oe==="connected"&&T.current&&setTimeout(()=>{if(!T.current||!N.current)return;const ue=N.current.querySelector(".xterm-helper-textarea");ue&&ue.focus();try{N.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[oe]);const Be=a.useCallback(()=>{if(!N.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;T.current?.focus();const Re=N.current.querySelector(".xterm-helper-textarea");if(!Re)return;Re.autocapitalize="off",Re.autocomplete="off",Re.autocorrect="off",Re.spellcheck=!1,Re.setAttribute("inputmode","text");try{Re.focus({preventScroll:!0})}catch{Re.focus()}const Ke=Re.value.length;Re.setSelectionRange(Ke,Ke)},[]);a.useEffect(()=>Ye(()=>{T.current?.clear(),c(null),K.current=!1,T.current&&(T.current.dispose(),T.current=null),U.current=null,$.current=!1,B.current&&(window.removeEventListener("resize",B.current),B.current=null),d(!1),h(null),xe().catch(Re=>{console.error("Failed to replace invalid terminal session:",Re)})}),[Ye,xe]);const Ge=a.useCallback(ue=>{ue.target===ue.currentTarget&&(E.current=!0)},[]),re=a.useCallback(ue=>{E.current&&ue.target===ue.currentTarget&&n(),E.current=!1},[n]),ke=a.useCallback(()=>{T.current?.clear()},[]),X=a.useCallback(async()=>{T.current?.clear(),c(null),K.current=!1;try{await de()}catch(ue){o(ye(ue)||"Failed to restart terminal session")}},[de]),Te=a.useCallback(()=>{T.current&&(T.current.dispose(),T.current=null),U.current=null,$.current=!1,B.current&&(window.removeEventListener("resize",B.current),B.current=null),h(null),d(!1)},[]),Le=a.useCallback(()=>{window.location.reload()},[]),fe=a.useCallback(()=>{k(ue=>ar(ue+1))},[]),_e=a.useCallback(()=>{k(ue=>ar(ue-1))},[]),Ue=a.useCallback(ue=>{M(Re=>Re===ue?null:ue)},[]),nt=a.useCallback(ue=>{if(w==="ctrl"){he(eR(ue)),M(null);return}if(w==="alt"){he(tR(ue)),M(null);return}he(ue)},[he,w]),ve=a.useCallback(ue=>{he(ue),M(null)},[he]);if(!e)return null;const ce=()=>{switch(oe){case"connected":return t.jsx("span",{className:"terminal-status connected",title:"Connected"});case"connecting":case"reconnecting":return t.jsx("span",{className:"terminal-status connecting",title:"Connecting..."});case"disconnected":return t.jsx("span",{className:"terminal-status disconnected",title:"Disconnected"});default:return null}},De=!H||!O&&!ge;return t.jsx("div",{className:"modal-overlay open",onMouseDown:Ge,onMouseUp:re,role:"dialog","aria-modal":"true","data-testid":"terminal-modal-overlay",style:g>0?{"--overlay-padding-top":"0px"}:void 0,children:t.jsxs("div",{ref:D,className:"modal terminal-modal","data-testid":"terminal-modal",style:g>0?{"--keyboard-overlap":`${g}px`,"--vv-height":v?`${v}px`:void 0}:void 0,children:[t.jsxs("div",{className:"terminal-header",children:[t.jsxs("div",{className:"terminal-tabs","data-testid":"terminal-tabs",children:[j.map(ue=>t.jsxs("div",{className:`terminal-tab ${ue.isActive?"terminal-tab--active":""}`,onClick:()=>me(ue.id),title:ue.title,role:"tab","aria-selected":ue.isActive,children:[t.jsx("span",{className:"terminal-tab-label",children:ue.title}),j.length>1&&t.jsx("button",{className:"terminal-tab-close",onClick:Re=>{Re.stopPropagation(),se(ue.id)},title:"Close tab",children:"×"})]},ue.id)),t.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:be,title:"New terminal",children:"+"})]}),t.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[t.jsx(mi,{size:16}),ce()]}),t.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[oe==="disconnected"&&O&&t.jsxs("button",{className:"terminal-reconnect-btn",onClick:Xe,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[t.jsx($n,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),l!==null&&t.jsxs("button",{className:"terminal-restart-btn",onClick:X,title:"New Session","data-testid":"terminal-restart-btn",children:[t.jsx($n,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:ke,"data-testid":"terminal-clear-btn",title:"Clear terminal",children:[t.jsx(rn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Clear"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:()=>S(ue=>!ue),"data-testid":"terminal-shortcut-toggle",title:"Shortcuts","aria-pressed":_,children:[t.jsx(ox,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Shortcuts"})]}),t.jsx("button",{className:"terminal-close",onClick:n,"data-testid":"terminal-close-btn",title:"Close terminal",children:t.jsx(Wt,{size:20})})]})]}),r&&t.jsx("div",{className:"terminal-error","data-testid":"terminal-error",children:r}),t.jsxs("div",{className:"terminal-container","data-testid":"terminal-container",children:[De&&!ge&&t.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[t.jsx("div",{className:"terminal-spinner"}),t.jsx("span",{children:"Starting terminal..."})]}),ge&&!O&&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: ",ge]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:ne,"data-testid":"terminal-retry-btn",children:[t.jsx($n,{size:14}),"Retry"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Le,"data-testid":"terminal-bootstrap-refresh-btn",children:[t.jsx($n,{size:14}),"Refresh page"]})]})]})}),m&&O&&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:Te,"data-testid":"terminal-reinit-btn",children:[t.jsx($n,{size:14}),"Reinitialize"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Le,"data-testid":"terminal-xterm-refresh-btn",children:[t.jsx($n,{size:14}),"Refresh page"]})]})]})}),t.jsx("div",{ref:N,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:Be,onTouchStart:Be},O?.sessionId)]}),_&&t.jsxs("div",{className:"terminal-shortcut-panel","data-testid":"terminal-shortcut-panel",children:[t.jsxs("div",{className:"terminal-shortcut-modifier-row",children:[t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${w==="ctrl"?"is-active":""}`,"data-testid":"terminal-modifier-ctrl",onClick:()=>Ue("ctrl"),"aria-pressed":w==="ctrl",children:"Ctrl"}),t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${w==="alt"?"is-active":""}`,"data-testid":"terminal-modifier-alt",onClick:()=>Ue("alt"),"aria-pressed":w==="alt",children:"Alt"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>ve("\x1B"),children:"ESC"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>ve(" "),children:"Tab"})]}),nR.map(ue=>t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>nt(ue.key),title:ue.description,children:ue.label},ue.label))]}),t.jsxs("div",{className:"terminal-status-bar","data-testid":"terminal-status-bar",children:[t.jsxs("span",{className:`terminal-connection-status ${oe}`,children:[oe==="connected"&&"Connected",oe==="connecting"&&"Connecting...",oe==="reconnecting"&&"Reconnecting...",oe==="disconnected"&&"Disconnected"]}),l!==null&&t.jsxs("span",{className:"terminal-exit-code","data-testid":"terminal-exit-code",children:["Exit: ",l]}),t.jsxs("span",{className:"terminal-font-size-controls",children:[t.jsx("button",{type:"button",className:"terminal-font-size-btn",onClick:_e,"data-testid":"terminal-font-size-decrease","aria-label":"Decrease terminal font size",children:t.jsx(Cx,{size:14})}),t.jsxs("span",{className:"terminal-font-size-value","data-testid":"terminal-font-size-value",children:[y,"px"]}),t.jsx("button",{type:"button",className:"terminal-font-size-btn",onClick:fe,"data-testid":"terminal-font-size-increase","aria-label":"Increase terminal font size",children:t.jsx(on,{size:14})})]}),t.jsx("span",{className:"terminal-shortcuts",children:"Ctrl++/- zoom • ⌨ Shortcuts panel • Esc close"})]})]})})}const Ja={name:"",command:""};function mh(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function dR(e,n=60){return e.length<=n?e:e.slice(0,n-3)+"..."}function uR({isOpen:e,onClose:n,addToast:s,projectId:i,onRunScript:r}){const[o,l]=a.useState({}),[c,u]=a.useState(!0),[d,m]=a.useState(!1),[h,f]=a.useState(null),[p,g]=a.useState(Ja),[b,v]=a.useState(!1),[x,y]=a.useState(null),[k,_]=a.useState(null),S=Ei(n),w=a.useCallback(async()=>{try{u(!0);const z=await br(i);l(z)}catch(z){s(ye(z)||"Failed to load scripts","error")}finally{u(!1)}},[s,i]);a.useEffect(()=>{e&&w()},[e,w]);const M=a.useCallback(()=>{m(!0),f(null),g(Ja),_(null)},[]),N=a.useCallback((z,B)=>{f(z),m(!1),g({name:z,command:B}),_(null)},[]),D=a.useCallback(()=>{f(null),m(!1),g(Ja),_(null)},[]),E=a.useCallback(z=>{g(B=>({...B,name:z})),z&&!mh(z)?_("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):_(null)},[]),T=a.useCallback(async()=>{const z=p.name.trim(),B=p.command.trim();if(!z){s("Script name is required","error");return}if(!mh(z)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!B){s("Script command is required","error");return}v(!0);try{await $j(z,B,i),s(h?"Script updated":"Script created","success"),f(null),m(!1),g(Ja),_(null),await w()}catch(J){const Q=ye(J);Q?.includes("already exists")?s("A script with this name already exists","error"):s(Q||"Failed to save script","error")}finally{v(!1)}},[p,h,s,w,i]),U=a.useCallback(async z=>{try{await Dj(z,i),s("Script deleted","success"),y(null),h===z&&(f(null),g(Ja)),await w()}catch(B){s(ye(B)||"Failed to delete script","error")}},[h,s,w,i]),K=a.useCallback((z,B)=>{r&&r(z,B)},[r]);if(!e)return null;const $=d||h!==null,R=Object.entries(o).map(([z,B])=>({name:z,command:B}));return t.jsx("div",{className:"modal-overlay open",...S,"data-testid":"scripts-modal",children:t.jsxs("div",{className:"modal scripts-modal",role:"dialog","aria-modal":"true","aria-label":"Scripts",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{children:[t.jsx(mi,{size:18,style:{marginRight:"8px",verticalAlign:"middle"}}),"Scripts"]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]}),t.jsx("div",{className:"modal-body scripts-modal-body",children:c?t.jsxs("div",{style:{textAlign:"center",padding:"32px",color:"var(--text-muted)"},children:[t.jsx(ot,{size:24,className:"spin",style:{margin:"0 auto 8px",display:"block"}}),"Loading scripts..."]}):$?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:z=>E(z.target.value),placeholder:"e.g., build, test, lint",disabled:b||h!==null,"data-testid":"script-name-input",style:{width:"100%",borderColor:k?"var(--color-error)":void 0}}),k&&t.jsx("div",{style:{fontSize:"12px",color:"var(--color-error)",marginTop:"4px"},"data-testid":"script-name-error",children:k}),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:z=>g(B=>({...B,command:z.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:D,disabled:b,"data-testid":"script-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:T,disabled:b||!!k,"data-testid":"script-save-btn",children:b?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:14,className:"spin",style:{marginRight:"6px"}}),"Saving..."]}):h?"Update":"Create"})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"scripts-modal-list-header",style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[t.jsx("div",{style:{fontSize:"13px",color:"var(--text-muted)"},children:R.length===0?"No scripts defined":`${R.length} script${R.length===1?"":"s"}`}),t.jsxs("button",{className:"btn btn-primary",onClick:M,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx(on,{size:14}),"Add Script"]})]}),R.length===0?t.jsxs("div",{style:{textAlign:"center",padding:"32px",color:"var(--text-muted)",fontSize:"14px",border:"1px dashed var(--border)",borderRadius:"8px"},"data-testid":"empty-state",children:[t.jsx(mi,{size:32,style:{margin:"0 auto 12px",opacity:.5}}),t.jsx("div",{children:"No scripts defined yet."}),t.jsx("div",{style:{marginTop:"4px",fontSize:"12px"},children:"Add scripts to quickly run common commands from the dashboard."})]}):t.jsx("div",{className:"scripts-modal-list",style:{display:"flex",flexDirection:"column",gap:"8px"},children:R.map(z=>t.jsx("div",{className:"script-card","data-testid":`script-${z.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:z.name})}),t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:z.command,children:dR(z.command)})]}),t.jsxs("div",{className:"script-card-actions",style:{display:"flex",gap:"4px",marginLeft:"8px",flexShrink:0},children:[t.jsxs("button",{className:"btn btn-secondary",onClick:()=>K(z.name,z.command),title:"Run script","aria-label":`Run ${z.name}`,"data-testid":`run-script-${z.name}`,style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 10px",fontSize:"12px"},children:[t.jsx(Sn,{size:12}),"Run"]}),t.jsx("button",{className:"btn-icon",onClick:()=>N(z.name,z.command),title:"Edit","aria-label":`Edit ${z.name}`,"data-testid":`edit-script-${z.name}`,children:t.jsx(on,{size:14,style:{transform:"rotate(45deg)"}})}),x===z.name?t.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[t.jsx("button",{className:"btn-icon",onClick:()=>U(z.name),title:"Confirm delete","aria-label":`Confirm delete ${z.name}`,"data-testid":`confirm-delete-script-${z.name}`,style:{color:"var(--color-error)"},children:t.jsx(rn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>y(null),title:"Cancel delete","aria-label":"Cancel delete","data-testid":`cancel-delete-script-${z.name}`,children:t.jsx(Wt,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>y(z.name),title:"Delete","aria-label":`Delete ${z.name}`,"data-testid":`delete-script-${z.name}`,children:t.jsx(rn,{size:14})})]})]})},z.name))})]})})]})})}function mR(e,n,s){const[i,r]=a.useState([]),[o,l]=a.useState("."),[c,u]=a.useState(!1),[d,m]=a.useState(null),[h,f]=a.useState(0),p=a.useCallback(()=>{f(b=>b+1)},[]),g=a.useCallback(b=>{l(b),m(null)},[]);return a.useEffect(()=>{l("."),m(null),r([])},[e]),a.useEffect(()=>{if(!n||!e)return;let b=!1;async function v(){u(!0),m(null);try{const x=await Xy(e,o==="."?void 0:o,s);b||r(x.entries)}catch(x){b||(m(ye(x)||"Failed to load files"),r([]))}finally{b||u(!1)}}return v(),()=>{b=!0}},[e,o,n,h,s]),{entries:i,currentPath:o,setPath:g,loading:c,error:d,refresh:p}}function hR(e,n,s,i){const[r,o]=a.useState(""),[l,c]=a.useState(""),[u,d]=a.useState(null),[m,h]=a.useState(!1),[f,p]=a.useState(!1),[g,b]=a.useState(null),v=a.useCallback(k=>{o(k),b(null)},[]);a.useEffect(()=>{if(!e||!n){o(""),c(""),d(null),b(null);return}let k=!1;async function _(){h(!0),b(null);try{const S=await Zy(e,n,i);k||(o(S.content),c(S.content),d(S.mtime))}catch(S){k||(b(ye(S)||"Failed to load file"),o(""),c(""),d(null))}finally{k||h(!1)}}return _(),()=>{k=!0}},[e,n,s,i]);const x=r!==l,y=a.useCallback(async()=>{if(!(!e||!n||!x)){p(!0),b(null);try{const k=await ej(e,n,r,i);c(r),d(k.mtime)}catch(k){throw b(ye(k)||"Failed to save file"),k}finally{p(!1)}}},[e,n,r,x,i]);return{content:r,setContent:v,originalContent:l,loading:m,saving:f,error:g,save:y,hasChanges:x,mtime:u}}const pR=1e4;function fR(e){const s=e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||e||"Project Root"}function gR(e){return{id:e.id,label:e.id,title:e.title,worktree:e.worktree,kind:"task"}}function bR(e){const[n,s]=a.useState("Project Root"),[i,r]=a.useState([]),[o,l]=a.useState(!0),[c,u]=a.useState(null);return a.useEffect(()=>{let d=!1;async function m(){try{const f=await Qy(e);if(d)return;s(fR(f.project)),r(f.tasks.map(gR)),u(null)}catch(f){d||u(ye(f)||"Failed to load workspaces")}finally{d||l(!1)}}m();const h=window.setInterval(()=>{m()},pR);return()=>{d=!0,window.clearInterval(h)}},[e]),{projectName:n,workspaces:i,loading:o,error:c}}function xR(e){return e===void 0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function vR(e){return e?new Date(e).toLocaleDateString():""}function hh(e,n){return kw(e,n)}const Ya={visible:!1,x:0,y:0,entry:null,entryFullPath:""},lc={type:null,entry:null,entryFullPath:""},yR=200,jR=500,ph=10;function kR({x:e,y:n,entry:s,onAction:i,onClose:r}){const o=a.useRef(null),[l,c]=a.useState({x:e,y:n});a.useEffect(()=>{const m=o.current;if(!m)return;const h=m.getBoundingClientRect(),f=window.visualViewport,p=f?.width&&f.width>0?f.width:window.innerWidth,g=f?.height&&f.height>0?f.height:window.innerHeight,b=f?.offsetLeft??0,v=f?.offsetTop??0,x=8;let y=e-b,k=n-v;y+h.width>p-x&&(y=p-x-h.width),k+h.height>g-x&&(k=g-x-h.height),y<x&&(y=x),k<x&&(k=x),c({x:y+b,y:k+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:Oi,disabled:!1},{id:"move",label:"Move",icon:Mx,disabled:!1},{id:"rename",label:"Rename",icon:cs,disabled:!1},...u?[{id:"download-zip",label:"Download as ZIP",icon:zo,disabled:!1}]:[{id:"download",label:"Download",icon:jb,disabled:!1}],{id:"divider",label:"",icon:Oi,disabled:!0},{id:"delete",label:"Delete",icon:rn,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 wR({type:e,entry:n,entryFullPath:s,onConfirm:i,onCancel:r,loading:o,error:l}){const c=a.useRef(null),u=e==="rename"?n.name:"",[d,m]=a.useState(u);a.useEffect(()=>{setTimeout(()=>c.current?.focus(),50)},[]),a.useEffect(()=>{if(e==="rename"&&c.current){const g=n.name.lastIndexOf(".");g>0?c.current.setSelectionRange(0,g):c.current.select()}},[e,n.name]);const h=g=>{g.key==="Enter"&&d.trim()&&i(d.trim()),g.key==="Escape"&&r()};if(e==="delete")return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsxs("div",{className:"file-browser-dialog",onClick:g=>g.stopPropagation(),children:[t.jsxs("div",{className:"file-browser-dialog-title",children:["Delete ",n.type==="directory"?"Folder":"File"]}),t.jsxs("div",{className:"file-browser-dialog-message",children:["Are you sure you want to delete ",t.jsx("strong",{children:n.name}),"?",n.type==="directory"&&" This will delete all contents recursively."]}),l&&t.jsx("div",{className:"file-browser-dialog-error",children:l}),t.jsxs("div",{className:"file-browser-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:r,disabled:o,children:"Cancel"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>i(""),disabled:o,children:o?"Deleting...":"Delete"})]})]})});const p={copy:{title:"Copy",placeholder:"Destination path",confirm:"Copy"},move:{title:"Move",placeholder:"Destination path",confirm:"Move"},rename:{title:"Rename",placeholder:"New name",confirm:"Rename"}}[e];return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsxs("div",{className:"file-browser-dialog",onClick:g=>g.stopPropagation(),children:[t.jsx("div",{className:"file-browser-dialog-title",children:p.title}),t.jsx("div",{className:"file-browser-dialog-info",children:e==="rename"?n.name:s}),t.jsx("input",{ref:c,className:"file-browser-dialog-input",type:"text",value:d,onChange:g=>m(g.target.value),placeholder:p.placeholder,onKeyDown:h,disabled:o}),l&&t.jsx("div",{className:"file-browser-dialog-error",children:l}),t.jsxs("div",{className:"file-browser-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:r,disabled:o,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>i(d.trim()),disabled:o||!d.trim(),children:o?`${p.confirm}ing...`:p.confirm})]})]})})}function NR({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(Ya),[f,p]=a.useState(lc),[g,b]=a.useState(!1),[v,x]=a.useState(null),[y,k]=a.useState(!1),[_,S]=a.useState(null),w=a.useRef(null),M=a.useRef(null),N=a.useRef(null),D=a.useRef(!1),E=a.useCallback(()=>{w.current!==null&&(window.clearTimeout(w.current),w.current=null),M.current!==null&&(window.clearTimeout(M.current),M.current=null)},[]),T=a.useCallback(()=>{E(),N.current=null,k(!1),S(null)},[E]);a.useEffect(()=>()=>{E()},[E]);const U=a.useCallback((L,P,j,O)=>{h({visible:!0,x:L,y:P,entry:j,entryFullPath:O})},[]),K=a.useCallback((L,P,j)=>{if(L.touches.length!==1)return;const O=L.touches[0];O&&(T(),N.current={x:O.clientX,y:O.clientY},M.current=window.setTimeout(()=>{k(!0),S(j)},yR),w.current=window.setTimeout(()=>{const H=N.current;H&&(D.current=!0,k(!1),S(null),E(),U(H.x,H.y,P,j))},jR))},[T,E,U]),$=a.useCallback(L=>{const P=N.current,j=L.touches[0];!P||!j||(Math.abs(j.clientX-P.x)>ph||Math.abs(j.clientY-P.y)>ph)&&T()},[T]),R=a.useCallback(()=>{T()},[T]);a.useEffect(()=>{if(!m.visible)return;const L=document.querySelector(".file-browser-list"),P=()=>{D.current=!1,T(),h(Ya)};return L?.addEventListener("scroll",P),()=>L?.removeEventListener("scroll",P)},[T,m.visible]),a.useEffect(()=>{if(!m.visible)return;const L=P=>{P.key==="Escape"&&(D.current=!1,h(Ya))};return document.addEventListener("keydown",L),()=>document.removeEventListener("keydown",L)},[m.visible]);const z=a.useCallback((L,P)=>{L.preventDefault(),L.stopPropagation(),T(),D.current=!1,U(L.clientX,L.clientY,P,hh(n,P.name))},[T,n,U]),B=a.useCallback(L=>{if(!m.entry)return;D.current=!1;const P=m.entry,j=m.entryFullPath;if(h(Ya),L==="download"){if(!c)return;const O=hp(c,j,d);window.open(ii(O),"_blank");return}if(L==="download-zip"){if(!c)return;const O=rj(c,j,d);window.open(ii(O),"_blank");return}p({type:L,entry:P,entryFullPath:j}),x(null)},[m,c,d]),J=a.useCallback(async L=>{if(!(!f.type||!f.entry||!c)){b(!0),x(null);try{switch(f.type){case"copy":await nj(c,f.entryFullPath,L,d);break;case"move":await sj(c,f.entryFullPath,L,d);break;case"rename":await aj(c,f.entryFullPath,L,d);break;case"delete":await ij(c,f.entryFullPath,d);break}p(lc),u?.()}catch(P){x(ye(P)||"Operation failed")}finally{b(!1)}}},[f,c,u,d]),Q=a.useCallback(()=>{p(lc),x(null)},[]),C=a.useCallback((L,P)=>{if(D.current){D.current=!1;return}m.visible||(L.type==="directory"?i(P):s(P))},[m.visible,i,s]);return r?t.jsxs("div",{className:"file-browser-loading",children:[t.jsx(ot,{className:"spin",size:24}),t.jsx("span",{children:"Loading files..."})]}):o?t.jsxs("div",{className:"file-browser-error",children:[t.jsxs("p",{children:["Error: ",o]}),l&&t.jsx("button",{className:"btn btn-sm",onClick:l,children:"Retry"})]}):t.jsxs("div",{className:"file-browser",children:[t.jsxs("div",{className:"file-browser-header",children:[n!=="."&&t.jsxs("button",{className:"file-browser-up",onClick:()=>{i(ww(n))},children:[t.jsx(vn,{size:16,style:{transform:"rotate(-90deg)"}}),"Up one level"]}),t.jsx("span",{className:"file-browser-path",children:n==="."?"Root":_a(n)})]}),t.jsx("div",{className:"file-browser-list",children:e.length===0?t.jsx("div",{className:"file-browser-empty",children:"(empty directory)"}):e.map(L=>{const P=hh(n,L.name),j=y&&_===P;return t.jsxs("div",{className:`file-node file-node--${L.type} ${j?"file-node--long-pressing":""}`,onClick:()=>C(L,P),onContextMenu:O=>z(O,L),onTouchStart:O=>K(O,L,P),onTouchMove:$,onTouchEnd:R,onTouchCancel:R,children:[t.jsx("div",{className:"file-node-icon",children:L.type==="directory"?t.jsx(Jn,{size:16}):t.jsx(Zh,{size:16})}),t.jsx("div",{className:"file-node-name",children:L.name}),L.type==="file"&&L.size!==void 0&&t.jsx("div",{className:"file-node-size",children:xR(L.size)}),L.mtime&&t.jsx("div",{className:"file-node-time",children:vR(L.mtime)})]},L.name)})}),m.visible&&m.entry&&t.jsx(kR,{x:m.x,y:m.y,entry:m.entry,onAction:B,onClose:()=>{D.current=!1,h(Ya)}}),f.type&&f.entry&&t.jsx(wR,{type:f.type,entry:f.entry,entryFullPath:f.entryFullPath,onConfirm:J,onCancel:Q,loading:g,error:v})]})}function SR(e){if(!e)return!1;const n=e.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function CR({content:e,onChange:n,readOnly:s,filePath:i}){const[r,o]=a.useState(!1),[l,c]=a.useState(!0),u=SR(i),d=u&&(s?!0:r),m=a.useCallback(()=>{o(!1)},[]),h=a.useCallback(()=>{o(!0)},[]),f=a.useCallback(()=>{c(p=>!p)},[]);return t.jsxs("div",{className:"file-editor-container",children:[u?t.jsxs("div",{className:"file-editor-toolbar",children:[t.jsxs("div",{className:"file-editor-mode-toggle",children:[!s&&t.jsxs("button",{className:`btn btn-sm ${d?"":"btn-primary"}`,onClick:m,disabled:!d,"aria-label":"Edit mode",children:[t.jsx(Xh,{size:14}),"Edit"]}),t.jsxs("button",{className:`btn btn-sm ${d?"btn-primary":""}`,onClick:h,disabled:d,"aria-label":"Preview mode",children:[t.jsx(Ca,{size:14}),"Preview"]})]}),!s&&t.jsx("button",{className:`btn btn-sm ${l?"btn-primary":""}`,onClick:f,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(ko,{size:14})})]}):!s&&t.jsxs("div",{className:"file-editor-toolbar",children:[t.jsx("div",{className:"file-editor-mode-toggle"}),t.jsx("button",{className:`btn btn-sm ${l?"btn-primary":""}`,onClick:f,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(ko,{size:14})})]}),d?t.jsx("div",{className:"file-editor-preview markdown-body",children:t.jsx(ai,{remarkPlugins:[ri],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 ER(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function _R({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(Fd,{size:14}):t.jsx(Sc,{size:14}),t.jsx("span",{className:"workspace-selector-trigger-label",children:l}),t.jsx(Xt,{size:14,className:`workspace-selector-trigger-icon${r?" open":""}`})]}),r&&t.jsxs("div",{className:"workspace-selector-menu",role:"listbox","aria-label":"Select workspace",children:[t.jsxs("button",{type:"button",className:`workspace-selector-option${e==="project"?" active":""}`,onClick:()=>{i("project"),o(!1)},children:[t.jsxs("div",{className:"workspace-selector-option-main",children:[t.jsx(Fd,{size:14}),t.jsx("span",{children:"Project Root"})]}),t.jsx("span",{className:"workspace-selector-option-meta",children:n})]}),s.length>0&&t.jsxs("div",{className:"workspace-selector-group",children:[t.jsx("div",{className:"workspace-selector-group-label",children:"Task Worktrees"}),s.map(c=>t.jsxs("button",{type:"button",className:`workspace-selector-option${e===c.id?" active":""}`,onClick:()=>{i(c.id),o(!1)},children:[t.jsxs("div",{className:"workspace-selector-option-main",children:[t.jsx(Sc,{size:14}),t.jsx("span",{children:c.id})]}),c.title&&t.jsx("span",{className:"workspace-selector-option-meta",title:c.title,children:ER(c.title)})]},c.id))]})]})]})}const MR=768,AR=280,uo=180,mo=500,fh="fusion:file-browser-sidebar-width",og=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),RR=new Set([...og,".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 gh(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return RR.has(n)}function TR(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return og.has(n)}function PR({initialWorkspace:e="project",onClose:n,onWorkspaceChange:s,projectId:i}){const{projectName:r,workspaces:o}=bR(i),l=a.useRef(null);oi(l,!0,"fusion:files-modal-size");const c=Ei(n),[u,d]=a.useState(e),[m,h]=a.useState(null),[f,p]=a.useState(!1),[g,b]=a.useState("list"),[v,x]=a.useState(AR),{entries:y,currentPath:k,setPath:_,loading:S,error:w,refresh:M}=mR(u,!0,i),{content:N,setContent:D,originalContent:E,loading:T,saving:U,error:K,save:$,hasChanges:R,mtime:z}=hR(u,m,!0,i);a.useEffect(()=>{d(e)},[e]),a.useEffect(()=>{const se=()=>{p(window.innerWidth<=MR)};return se(),window.addEventListener("resize",se),()=>window.removeEventListener("resize",se)},[]),a.useEffect(()=>{m||b("list")},[m]),a.useEffect(()=>{try{const se=localStorage.getItem(fh);if(!se)return;const me=Number.parseInt(se,10);if(!Number.isNaN(me)){const F=Math.max(uo,Math.min(mo,me));x(F)}}catch{}},[]),a.useEffect(()=>{const se=me=>{me.key==="Escape"&&n(),(me.metaKey||me.ctrlKey)&&me.key==="s"&&(me.preventDefault(),R&&!U&&$())};return document.addEventListener("keydown",se),()=>document.removeEventListener("keydown",se)},[n,R,U,$]);const B=a.useCallback(se=>{h(se),f&&b("editor")},[f]),J=a.useCallback(()=>{b("list")},[]),Q=a.useCallback(()=>{D(E)},[E,D]),C=a.useCallback(se=>{d(se),h(null),b("list"),s?.(se)},[s]),L=a.useCallback(se=>{try{localStorage.setItem(fh,String(se))}catch{}},[]),P=a.useCallback(se=>{if(f)return;se.preventDefault(),se.stopPropagation();const me=se.currentTarget;typeof me.setPointerCapture=="function"&&me.setPointerCapture(se.pointerId);const F=se.clientX,de=v;let ne=de;document.body.style.userSelect="none";const xe=he=>{const ae=he.clientX-F,je=Math.max(uo,Math.min(mo,de+ae));ne=je,x(je)},oe=he=>{typeof me.releasePointerCapture=="function"&&me.releasePointerCapture(he.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",xe),document.removeEventListener("pointerup",oe),L(ne)};document.addEventListener("pointermove",xe),document.addEventListener("pointerup",oe)},[f,L,v]),j=a.useCallback(se=>{if(f)return;const me=20;if(se.key!=="ArrowLeft"&&se.key!=="ArrowRight")return;se.preventDefault();const F=se.key==="ArrowLeft"?-me:me,de=Math.max(uo,Math.min(mo,v+F));x(de),L(de)},[f,L,v]),H=`Files — ${a.useMemo(()=>u==="project"?"Project":o.find(se=>se.id===u)?.id??u,[u,o])}`,ge=a.useMemo(()=>!m||!TR(m)?null:hp(u,m,i),[m,u,i]),be=se=>{const me=new Blob([se]).size;return me<1024?`${me} B`:`${(me/1024).toFixed(1)} KB`};return t.jsx("div",{className:"modal-overlay open",...c,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal file-browser-modal",ref:l,children:[t.jsxs("div",{className:"modal-header file-browser-modal-header",children:[t.jsxs("div",{className:"file-browser-header-title",children:[t.jsx(Jn,{size:18}),t.jsx("span",{children:H}),m&&t.jsx("span",{className:"file-browser-header-path",children:m})]}),t.jsxs("div",{className:"file-browser-header-actions",children:[t.jsx(_R,{currentWorkspace:u,projectName:r,workspaces:o,onSelect:C}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Wt,{size:20})})]})]}),t.jsxs("div",{className:"file-browser-body",children:[t.jsx("div",{className:`file-browser-sidebar ${f?"mobile":""} ${g==="list"?"active":""}`,style:f?void 0:{width:`${v}px`},children:t.jsx(NR,{entries:y,currentPath:k,onSelectFile:B,onNavigate:_,loading:S,error:w,onRetry:M,workspace:u,onRefresh:M,projectId:i})}),!f&&t.jsx("div",{className:"file-browser-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":uo,"aria-valuemax":mo,"aria-valuenow":v,"aria-label":"Resize sidebar",tabIndex:0,onPointerDown:P,onKeyDown:j}),t.jsx("div",{className:`file-browser-content ${f?"mobile":""} ${g==="editor"?"active":""}`,children:m?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"file-browser-toolbar",children:[t.jsxs("div",{className:"file-browser-file-info",children:[f&&g==="editor"&&t.jsxs("button",{className:"file-browser-back-button",onClick:J,"aria-label":"Back to file list",children:[t.jsx(Sa,{size:16}),t.jsx("span",{children:"Back"})]}),m,gh(m)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(Ob,{size:12}),"Binary file — read only"]}),z&&t.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date(z).toLocaleString()]}),T&&t.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),t.jsx("div",{className:"file-browser-actions",children:!ge&&R&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:Q,disabled:U,children:[t.jsx(Ox,{size:14}),"Discard"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void $(),disabled:U,children:[t.jsx(ap,{size:14}),U?"Saving...":"Save"]})]})})]}),K&&!ge&&t.jsx("div",{className:"file-browser-error-banner",children:K}),ge?t.jsx("div",{className:"file-browser-image-preview",children:t.jsx("img",{src:ge,alt:m??"",className:"file-browser-image"})}):t.jsx("div",{className:"file-editor-wrapper",children:t.jsx(CR,{content:N,onChange:D,filePath:m,readOnly:gh(m)})}),!ge&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:be(N)}),R&&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 IR(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 uy();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:ye(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 $R(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 DR(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}const lg="kb-usage-hidden-windows";function bh(e){const n=Qn(lg,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 LR(e,n){bs(lg,JSON.stringify(e),n)}function cg(e,n,s){return s[e]?.includes(n)??!1}function zR({window:e,viewMode:n,isHidden:s,onToggleHidden:i}){const r=DR(e.percentUsed),o=n==="remaining",l=Math.round(o?e.percentLeft:e.percentUsed),c=o?`${Math.round(e.percentLeft)}% remaining`:`${Math.round(e.percentUsed)}% used`,u=o?`${Math.round(e.percentUsed)}% used`:`${Math.round(e.percentLeft)}% left`;let d=e.resetText;if(!d&&e.resetAt){const v=new Date(e.resetAt).getTime()-Date.now();if(v>0){const x=Math.floor(v/36e5),y=Math.floor(x/24),k=x%24;y>0&&k>0?d=`resets in ${y}d ${k}h`:y>0?d=`resets in ${y}d`:x>0?d=`resets in ${x}h`:d=`resets in ${Math.floor(v/6e4)}m`}}const m=e.pace,h=m!==void 0;let f=0;h&&(f=o?100-m.percentElapsed:m.percentElapsed);const p=m?.status==="ahead",g=m?.status==="behind",b=m?.status==="on-track";return t.jsxs("div",{className:`usage-window ${s?"usage-window--hidden":""}`,children:[t.jsxs("div",{className:"usage-window-header",children:[t.jsx("span",{className:"usage-window-label",children:e.label}),t.jsxs("div",{className:"usage-window-header-controls",children:[!s&&t.jsx("span",{className:"usage-window-percentage",children:c}),!s&&t.jsx("button",{className:"btn-icon usage-window-hide-btn",onClick:i,"aria-label":`Hide ${e.label}`,"data-testid":"usage-window-hide-btn",children:t.jsx(Ca,{size:14})})]})]}),t.jsxs("div",{className:"usage-progress-wrapper",children:[t.jsx("div",{className:"usage-progress-bar",children:t.jsx("div",{className:`usage-progress-fill ${r}`,style:{width:`${l}%`},role:"progressbar","aria-valuenow":l,"aria-valuemin":0,"aria-valuemax":100,"aria-label":`${e.label}: ${c}`})}),h&&t.jsx("div",{className:"usage-pace-marker",style:{left:`${f}%`},"aria-hidden":"true","data-testid":"pace-marker"})]}),t.jsxs("div",{className:"usage-window-footer",children:[t.jsx("span",{className:"usage-window-left",children:u}),t.jsxs("span",{className:"usage-window-reset-group",children:[d&&t.jsx("span",{className:"usage-window-reset",children:d}),e.resetAt&&t.jsx("span",{className:"usage-window-reset-at",children:$R(e.resetAt)})]})]}),h&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[p&&t.jsxs(t.Fragment,{children:[t.jsx(ad,{size:14,className:"pace-icon pace-ahead"}),t.jsx("span",{className:"pace-text pace-ahead",children:m.message})]}),g&&t.jsxs(t.Fragment,{children:[t.jsx(lv,{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(yn,{size:14,className:"pace-icon pace-ontrack"}),t.jsx("span",{className:"pace-text pace-ontrack",children:m.message})]})]})]})}function FR(e){const n=e.toLowerCase();return n.includes("claude")||n.includes("anthropic")?"anthropic":n.includes("codex")||n.includes("openai")||n.includes("gpt")?"openai":n.includes("gemini")||n.includes("google")||n.includes("antigravity")?"google":n.includes("ollama")?"ollama":n.includes("minimax")?"minimax":n.includes("zai")||n.includes("zhipu")?"zai":n.includes("kimi")||n.includes("moonshot")?"kimi":n.includes("bedrock")||n.includes("amazon")?"bedrock":n.includes("xai")||n.includes("grok")?"xai":n.includes("opencode")?"opencode":n.includes("copilot")||n==="github copilot"?"github-copilot":e}function OR({provider:e,viewMode:n,hiddenWindows:s,onToggleWindow:i,onShowAllHidden:r}){const o=s[e.name]?.length??0,l=()=>{switch(e.status){case"ok":return null;case"error":return t.jsx("span",{className:"usage-status-badge usage-status-badge--error",children:"Error"});case"no-auth":default:return t.jsx("span",{className:"usage-status-badge usage-status-badge--not-configured",children:"Not configured"})}};return t.jsxs("div",{className:"usage-provider","data-provider":e.name,"data-status":e.status,children:[t.jsxs("div",{className:"usage-provider-header",children:[t.jsxs("div",{className:"usage-provider-info",children:[t.jsx(On,{provider:FR(e.name),size:"md"}),t.jsx("span",{className:"usage-provider-name",children:e.name}),o>0&&t.jsxs("button",{className:"btn btn-sm usage-show-hidden-btn",onClick:()=>r(e.name),"data-testid":"usage-show-hidden-btn",children:["Show hidden (",o,")"]})]}),t.jsx("div",{className:"usage-provider-actions",children:l()})]}),e.error&&t.jsx("div",{className:"usage-provider-error",children:e.error}),e.plan&&t.jsx("div",{className:"usage-provider-meta",children:t.jsx("span",{className:"usage-provider-plan",children:e.plan})}),e.windows.length>0?t.jsx("div",{className:"usage-provider-windows",children:e.windows.map((c,u)=>{const d=cg(e.name,c.label,s);return t.jsx(zR,{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 UR(){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 BR({isOpen:e,onClose:n,projectId:s,anchorRect:i}){const{providers:r,loading:o,error:l,lastUpdated:c,refresh:u}=IR({autoRefresh:e}),[d,m]=a.useState(!1),[h,f]=a.useState(()=>typeof window<"u"?window.innerWidth>=769:!1),[p,g]=a.useState("used"),[b,v]=a.useState(()=>bh(s)),x=a.useRef(null),y=a.useRef(e),k=a.useRef(!1);a.useEffect(()=>{e||(k.current=!1)},[e]),a.useEffect(()=>{r.length>0&&(k.current=!0)},[r.length]),a.useEffect(()=>{if(typeof window>"u")return;const R=()=>{f(window.innerWidth>=769)};return window.addEventListener("resize",R),()=>window.removeEventListener("resize",R)},[]),a.useEffect(()=>{!y.current&&e&&(!c||Date.now()-c.getTime()>5e3)&&u(),y.current=e},[e,c,u]),a.useEffect(()=>{const R=Qn("kb-usage-view-mode",s);if(R==="used"||R==="remaining"){g(R);return}g("used")},[s]);const _=a.useCallback(R=>{g(R),bs("kb-usage-view-mode",R,s)},[s]);a.useEffect(()=>{v(bh(s))},[s]),a.useEffect(()=>{LR(b,s)},[b,s]);const S=a.useCallback((R,z)=>{v(B=>{if(cg(R,z,B)){const J=(B[R]??[]).filter(Q=>Q!==z);if(J.length===0){const{[R]:Q,...C}=B;return C}return{...B,[R]:J}}return{...B,[R]:[...B[R]??[],z]}})},[]),w=a.useCallback(R=>{v(z=>{if(!z[R])return z;const{[R]:B,...J}=z;return J})},[]),M=a.useCallback(async()=>{m(!0),await u(),m(!1)},[u]);a.useEffect(()=>{if(!e)return;const R=z=>{z.key==="Escape"&&n()};return document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)},[e,n]);const N=a.useCallback(R=>{R.target===R.currentTarget&&n()},[n]);if(!e)return null;const D=!!(i&&h),U=D?Math.min((i?.bottom??0)+8,window.innerHeight-12):void 0,K=D?Math.max(window.innerWidth-(i?.right??0),0):void 0,$=t.jsxs("div",{className:`usage-modal${D?" usage-modal--popover":" modal"}`,"data-testid":"usage-modal",style:D?{position:"fixed",top:U,right:K}:void 0,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"usage-header",children:[t.jsx(Is,{size:18,className:"usage-header-icon"}),t.jsx("h3",{children:"Usage"})]}),t.jsxs("div",{className:"usage-header-actions",children:[t.jsxs("div",{className:"usage-view-toggle",role:"group","aria-label":"Usage view mode",children:[t.jsx("button",{className:`usage-view-toggle-btn ${p==="used"?"active":""}`,onClick:()=>_("used"),"aria-pressed":p==="used","data-testid":"usage-view-toggle-used",children:"Used"}),t.jsx("button",{className:`usage-view-toggle-btn ${p==="remaining"?"active":""}`,onClick:()=>_("remaining"),"aria-pressed":p==="remaining","data-testid":"usage-view-toggle-remaining",children:"Remaining"})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close usage modal","data-testid":"usage-modal-close",children:t.jsx(Wt,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:x,children:(o||!k.current&&!l)&&r.length===0?t.jsx(UR,{}):l&&r.length===0?t.jsxs("div",{className:"usage-error",children:[t.jsx("p",{children:"Failed to load usage data"}),t.jsx("p",{className:"usage-error-message",children:l}),t.jsx("button",{className:"btn btn-sm",onClick:M,children:"Retry"})]}):r.length===0?t.jsxs("div",{className:"usage-empty",children:[t.jsx("p",{children:"No AI providers configured"}),t.jsx("p",{className:"usage-empty-hint",children:"Configure authentication in Settings to see usage data."})]}):t.jsx("div",{className:"usage-providers",children:r.map(R=>t.jsx(OR,{provider:R,viewMode:p,hiddenWindows:b,onToggleWindow:S,onShowAllHidden:w},R.name))})}),t.jsxs("div",{className:"modal-actions usage-actions",children:[t.jsx("div",{className:"modal-actions-left usage-actions-left",children:t.jsx("div",{className:"usage-last-updated",children:c&&t.jsxs("span",{children:["Last updated: ",c.toLocaleTimeString()]})})}),t.jsxs("div",{className:"modal-actions-right usage-actions-right",children:[t.jsxs("button",{className:"btn btn-sm",onClick:M,disabled:o||d,"data-testid":"usage-refresh-btn",children:[t.jsx($n,{size:14,className:d?"spin":"",style:{marginRight:6}}),"Refresh"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]});return D?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"usage-popover-backdrop",onClick:n,"data-testid":"usage-modal-overlay"}),$]}):t.jsx("div",{className:"modal-overlay open",onClick:N,"data-testid":"usage-modal-overlay",children:$})}function dg(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 Io(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 HR={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},ug={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},qR={cron:Yh,webhook:op,api:Qh,manual:Gn},VR={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},WR={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function KR({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(yn,{size:12}):t.jsx(wr,{size:12}),t.jsx("span",{children:e.success?"Success":"Failed"}),n>0&&t.jsx("span",{className:"schedule-run-duration",children:dg(n)})]})}function GR({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"} ${Io(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx(yn,{size:12}):t.jsx(wr,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:Io(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:ug[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:dg(r)}),s?t.jsx(pi,{size:12}):t.jsx(Xt,{size:12})]}),s&&t.jsxs("div",{className:"schedule-history-detail",children:[e.output&&t.jsx("pre",{className:"schedule-history-output",children:e.output}),e.error&&t.jsx("div",{className:"schedule-history-error",children:e.error})]})]})}function JR({routine:e,onEdit:n,onDelete:s,onRun:i,onToggle:r,running:o,lastRunOutput:l}){const[c,u]=a.useState(!1),{confirm:d}=Ws(),m=a.useCallback(async()=>{await d({title:"Delete Routine",message:`Delete routine "${e.name}"? This cannot be undone.`,danger:!0})&&s(e)},[e,s,d]),h=HR[e.trigger.type],f=qR[e.trigger.type],p=e.trigger.type==="cron"?("cronExpression"in e.trigger?e.trigger.cronExpression:void 0)||e.cronExpression||"":e.cronExpression||"";return t.jsxs("div",{className:`routine-card${e.enabled?"":" disabled"}${o?" running":""}`,children:[t.jsxs("div",{className:"routine-card-header",children:[t.jsxs("div",{className:"routine-card-info",children:[t.jsxs("div",{className:"routine-card-name-row",children:[t.jsx("span",{className:"routine-card-name",children:e.name}),t.jsxs("span",{className:"routine-trigger-badge",style:{borderColor:h,color:h},children:[t.jsx(f,{size:10}),ug[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(Uo,{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:o?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(Sn,{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(Hs,{size:14}):t.jsx(Sn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:"Edit","aria-label":`Edit ${e.name}`,children:t.jsx(cs,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:m,title:"Delete","aria-label":`Delete ${e.name}`,children:t.jsx(rn,{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(Bi,{size:12}),t.jsxs("span",{className:"routine-policy-badge",children:[e.steps.length," step",e.steps.length===1?"":"s"]})]}):e.command?t.jsx("div",{className:"routine-meta-item routine-meta-command-preview",title:e.command,children:t.jsx("code",{className:"routine-cron",children:e.command})}):null,e.trigger.type==="cron"&&p&&t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(Si,{size:12}),t.jsx("code",{className:"routine-cron",children:p})]}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Execution policy: ${e.executionPolicy}`,children:VR[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:WR[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:Io(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:Io(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(KR,{result:e.lastRunResult}),t.jsxs("div",{className:"routine-meta-item",children:[t.jsx("span",{className:"routine-meta-label",children:"Runs:"}),t.jsx("span",{children:e.runCount})]})]}),l&&t.jsxs("div",{className:`routine-run-output ${l.success?"success":"failure"}`,children:[l.output&&t.jsx("pre",{className:"routine-run-output-text",children:l.output}),l.error&&t.jsx("div",{className:"routine-run-output-error",children:l.error})]}),e.runHistory.length>0&&t.jsxs("div",{className:"routine-card-history",children:[t.jsxs("button",{className:"schedule-history-toggle",onClick:()=>u(g=>!g),"aria-expanded":c,children:[c?t.jsx(pi,{size:12}):t.jsx(Xt,{size:12}),t.jsxs("span",{children:["Run History (",e.runHistory.length,")"]})]}),c&&t.jsxs("div",{className:"schedule-history-list",children:[e.runHistory.slice(0,10).map((g,b)=>t.jsx(GR,{result:g,index:b},`${g.startedAt}-${b}`)),e.runHistory.length>10&&t.jsxs("div",{className:"schedule-history-more",children:["…and ",e.runHistory.length-10," more"]})]})]})]})}function YR({type:e,size:n=12}){return e==="command"?t.jsxs("span",{className:"step-type-badge step-type-command",title:"Command step",children:[t.jsx(mi,{size:n}),t.jsx("span",{children:"Command"})]}):e==="create-task"?t.jsxs("span",{className:"step-type-badge step-type-create-task",title:"Create Task step",children:[t.jsx(hx,{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(rs,{size:n}),t.jsx("span",{children:"AI Prompt"})]})}function cc(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function QR(e){return e==="command"?{id:cc(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:cc(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:cc(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function XR({step:e,onSave:n,onCancel:s}){const[i,r]=a.useState(e.name),[o,l]=a.useState(e.type),[c,u]=a.useState(e.command??""),[d,m]=a.useState(e.prompt??""),[h,f]=a.useState(e.modelProvider??""),[p,g]=a.useState(e.modelId??""),[b,v]=a.useState(e.taskTitle??""),[x,y]=a.useState(e.taskDescription??""),[k,_]=a.useState(e.taskColumn??"triage"),[S,w]=a.useState(e.timeoutMs),[M,N]=a.useState(e.continueOnFailure??!1),[D,E]=a.useState({}),[T,U]=a.useState([]),[K,$]=a.useState(!1),[R,z]=a.useState(null);a.useEffect(()=>{let L=!1;return $(!0),z(null),ms().then(P=>{L||U(P.models)}).catch(P=>{L||z(P instanceof Error?P.message:"Failed to load models")}).finally(()=>{L||$(!1)}),()=>{L=!0}},[]);const B=a.useCallback(()=>{const L={};return i.trim()||(L.name="Step name is required"),o==="command"&&!c.trim()&&(L.command="Command is required"),o==="ai-prompt"&&!d.trim()&&(L.prompt="Prompt is required"),o==="create-task"&&!x.trim()&&(L.taskDescription="Task description is required"),(o==="ai-prompt"||o==="create-task")&&(h||p)&&(!h||!p)&&(L.modelProvider="Both model provider and model ID must be set together"),S!==void 0&&S<1e3&&(L.timeoutMs="Timeout must be at least 1 second (1000ms)"),E(L),Object.keys(L).length===0},[i,o,c,d,x,h,p,S]),J=h&&p?`${h}/${p}`:"",Q=a.useCallback(L=>{if(!L)f(""),g("");else{const P=L.indexOf("/");P!==-1&&(f(L.slice(0,P)),g(L.slice(P+1)))}},[]),C=a.useCallback(()=>{if(!B())return;const L={...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"?k: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:S||void 0,continueOnFailure:M};o!=="ai-prompt"&&delete L.prompt,o!=="create-task"&&(delete L.taskTitle,delete L.taskDescription,delete L.taskColumn),n(L)},[B,n,e,i,o,c,d,b,x,k,h,p,S,M]);return t.jsxs("div",{className:"step-editor",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-name-${e.id}`,children:"Step Name"}),t.jsx("input",{id:`step-name-${e.id}`,type:"text",placeholder:"e.g. Run tests",value:i,onChange:L=>r(L.target.value),"aria-invalid":!!D.name}),D.name&&t.jsx("small",{className:"field-error",children:D.name})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-type-${e.id}`,children:"Step Type"}),t.jsxs("select",{id:`step-type-${e.id}`,value:o,onChange:L=>l(L.target.value),children:[t.jsx("option",{value:"command",children:"Command"}),t.jsx("option",{value:"ai-prompt",children:"AI Prompt"}),t.jsx("option",{value:"create-task",children:"Create Task"})]})]}),o==="command"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-command-${e.id}`,children:"Command"}),t.jsx("textarea",{id:`step-command-${e.id}`,placeholder:"e.g. npm test",value:c,onChange:L=>u(L.target.value),rows:2,"aria-invalid":!!D.command}),D.command&&t.jsx("small",{className:"field-error",children:D.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:L=>m(L.target.value),rows:3,"aria-invalid":!!D.prompt}),D.prompt&&t.jsx("small",{className:"field-error",children:D.prompt})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-model-${e.id}`,children:"Model (optional)"}),t.jsx(Yn,{id:`step-model-${e.id}`,label:"Model",models:T,value:J,onChange:Q,placeholder:"Use default",disabled:K}),R&&t.jsx("small",{className:"field-error",children:R}),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:L=>v(L.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:L=>y(L.target.value),rows:4,"aria-invalid":!!D.taskDescription}),D.taskDescription&&t.jsx("small",{className:"field-error",children:D.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:k,onChange:L=>_(L.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(Yn,{id:`step-task-model-${e.id}`,label:"Model",models:T,value:J,onChange:Q,placeholder:"Use default",disabled:K}),R&&t.jsx("small",{className:"field-error",children:R}),D.modelProvider&&t.jsx("small",{className:"field-error",children:D.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:S??"",onChange:L=>w(L.target.value?Number(L.target.value):void 0),"aria-invalid":!!D.timeoutMs}),D.timeoutMs&&t.jsx("small",{className:"field-error",children:D.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:M,onChange:L=>N(L.target.checked)}),"Continue on failure"]}),t.jsx("small",{children:"If checked, the next step will run even if this one fails"})]}),t.jsxs("div",{className:"step-editor-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:C,children:"Save Step"})]})]})}function ZR({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=QR(d);n([...e,m]),r(m.id)},[e,n]),l=a.useCallback(d=>{n(e.filter(m=>m.id!==d)),i===d&&r(null)},[e,n,i]),c=a.useCallback((d,m)=>{const h=e.findIndex(g=>g.id===d);if(h<0)return;const f=m==="up"?h-1:h+1;if(f<0||f>=e.length)return;const p=[...e];[p[h],p[f]]=[p[f],p[h]],n(p)},[e,n]),u=a.useCallback(d=>{n(e.map(m=>m.id===d.id?d:m)),r(null)},[e,n]);return t.jsxs("div",{className:"steps-editor",children:[t.jsx("div",{className:"steps-editor-header",children:t.jsxs("span",{className:"steps-editor-title",children:["Steps (",e.length,")"]})}),e.length===0&&t.jsx("div",{className:"steps-empty-state",children:t.jsx("p",{children:"No steps added yet. Add a command or AI prompt step to get started."})}),t.jsx("div",{className:"steps-list",children:e.map((d,m)=>t.jsx("div",{className:"step-card",children:i===d.id?t.jsx(XR,{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(id,{size:14})}),t.jsx("span",{className:"step-card-index",children:m+1}),t.jsx(YR,{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(pi,{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(Xt,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(d.id),title:"Edit","aria-label":`Edit ${d.name}`,children:t.jsx(cs,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>l(d.id),title:"Delete","aria-label":`Delete ${d.name}`,children:t.jsx(rn,{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(on,{size:14}),"Add Command Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ai-prompt"),children:[t.jsx(on,{size:14}),"Add AI Prompt Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("create-task"),children:[t.jsx(on,{size:14}),"Add Create Task Step"]})]})]})}const mg={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},eT={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function tT(e){const n=e.trim();for(const[s,i]of Object.entries(mg))if(i===n)return s;return"custom"}function nT(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function sT(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 iT(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 aT=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],rT=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function xh(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function vh({routine:e,onSubmit:n,onCancel:s,scope:i,projectId:r,onScopeChange:o}){const l=!!e,c=e?iT(e):{triggerType:"cron",cronExpression:"0 * * * *",webhookPath:"",webhookSecret:"",endpoint:""},[u,d]=a.useState(e?.name??""),[m,h]=a.useState(e?.description??""),[f,p]=a.useState(c.triggerType),[g,b]=a.useState(c.cronExpression),[v,x]=a.useState(()=>c.triggerType!=="cron"?"custom":tT(c.cronExpression)),[y,k]=a.useState(c.webhookPath),[_,S]=a.useState(c.webhookSecret),[w,M]=a.useState(c.endpoint),[N,D]=a.useState(e?.executionPolicy??"queue"),[E,T]=a.useState(e?.catchUpPolicy??"run_one"),[U,K]=a.useState(e?.enabled??!0),$=e?.steps&&e.steps.length===1&&e.steps[0].type==="ai-prompt"&&!e.command,R=e?.steps&&e.steps.length===1&&e.steps[0].type==="create-task"&&!e.command,[z,B]=a.useState(e?.steps&&e.steps.length>0&&!$&&!R?"advanced":"simple"),[J,Q]=a.useState(()=>$?"ai-prompt":R?"create-task":"command"),[C,L]=a.useState(e?.command??""),[P,j]=a.useState(e?.steps??[]),[O,H]=a.useState(!1),[ge,be]=a.useState(e?.timeoutMs??3e5),[se,me]=a.useState($?e.steps?.[0]?.prompt??"":""),[F,de]=a.useState(R?e.steps?.[0]?.taskTitle??"":""),[ne,xe]=a.useState(R?e.steps?.[0]?.taskDescription??"":""),[oe,he]=a.useState(R?e.steps?.[0]?.taskColumn??"triage":"triage"),[ae,je]=a.useState($||R?e.steps?.[0]?.modelProvider??"":""),[Ae,Oe]=a.useState($||R?e.steps?.[0]?.modelId??"":""),[Qe,Xe]=a.useState([]),[Ye,it]=a.useState(!1),[Be,Ge]=a.useState(null),[re,ke]=a.useState(i??"global"),[X,Te]=a.useState({}),[Le,fe]=a.useState(!1),_e=a.useRef(!0);a.useEffect(()=>()=>{_e.current=!1},[]),a.useEffect(()=>{i&&ke(i)},[i]),a.useEffect(()=>{let te=!1;return it(!0),Ge(null),ms().then(Je=>{te||Xe(Je.models)}).catch(Je=>{te||Ge(Je instanceof Error?Je.message:"Failed to load models")}).finally(()=>{te||it(!1)}),()=>{te=!0}},[]);const Ue=ae&&Ae?`${ae}/${Ae}`:"",nt=a.useCallback(te=>{if(!te){je(""),Oe("");return}const Je=te.indexOf("/");Je!==-1&&(je(te.slice(0,Je)),Oe(te.slice(Je+1)))},[]),ve=a.useCallback(()=>{const te={};if(u.trim()||(te.name="Name is required"),re==="project"&&!r&&(te.scope="Project-specific entries require an active project."),f==="cron"&&v==="custom"&&(g.trim()?nT(g)||(te.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):te.cronExpression="Cron expression is required"),f==="webhook"&&!y.trim()&&(te.webhookPath="Webhook path is required"),f==="api"&&!w.trim()&&(te.endpoint="API endpoint is required"),z==="simple")J==="command"&&!C.trim()&&(te.command="Command is required"),J==="ai-prompt"&&!se.trim()&&(te.prompt="Prompt is required"),J==="create-task"&&!ne.trim()&&(te.taskDescription="Task description is required"),(ae.trim()&&!Ae.trim()||!ae.trim()&&Ae.trim())&&(te.model="Both model provider and model ID must be set, or both must be empty");else{P.length===0&&(te.steps="At least one step is required"),O&&(te.stepsEditing="Please save or cancel all step edits before saving the routine");const Je=[];P.forEach((dt,ut)=>{dt.name?.trim()||Je.push(`Step ${ut+1}: Name is required`),dt.type==="command"&&!dt.command?.trim()&&Je.push(`Step ${ut+1}: Command is required`),dt.type==="ai-prompt"&&!dt.prompt?.trim()&&Je.push(`Step ${ut+1}: Prompt is required`),dt.type==="create-task"&&!dt.taskDescription?.trim()&&Je.push(`Step ${ut+1}: Task description is required`)}),Je.length>0&&(te.steps=Je.join("; "))}return ge<1e3&&(te.timeoutMs="Timeout must be at least 1 second (1000ms)"),Te(te),Object.keys(te).length===0},[u,f,g,v,y,w,re,r,z,J,C,se,ne,ae,Ae,P,O,ge]),ce=a.useCallback(async te=>{if(te.preventDefault(),!!ve()){fe(!0);try{let Je=e?.scope??re??(r?"project":"global");Je==="project"&&!r&&(Je="global");const dt=sT(f,g,y,_,w);let ut,Ct;z==="simple"?J==="command"?ut=C.trim()||void 0:J==="ai-prompt"?Ct=[{id:xh(),type:"ai-prompt",name:u.trim(),prompt:se.trim(),modelProvider:ae.trim()||void 0,modelId:Ae.trim()||void 0}]:Ct=[{id:xh(),type:"create-task",name:u.trim(),taskTitle:F.trim()||void 0,taskDescription:ne.trim(),taskColumn:oe,modelProvider:ae.trim()||void 0,modelId:Ae.trim()||void 0}]:Ct=P;const yt={name:u.trim(),agentId:e?.agentId??"",description:m.trim()||void 0,trigger:dt,command:ut,steps:Ct,timeoutMs:ge,executionPolicy:N,catchUpPolicy:E,enabled:U,scope:Je};await n(yt)}finally{_e.current&&fe(!1)}}},[ve,n,u,m,f,g,y,_,w,z,J,C,se,ae,Ae,F,ne,oe,P,ge,N,E,U,re,r,e?.scope,e?.agentId]),De="routine-name-error",ue="routine-cron-error",Re="routine-webhook-error",Ke="routine-endpoint-error",Pe="routine-command-error",ft="routine-prompt-error",Z="routine-task-description-error",le="routine-model-error",we="routine-timeout-error",Ze=a.useCallback(te=>{x(te),te!=="custom"&&b(mg[te])},[]);return t.jsxs("form",{className:"routine-form",onSubmit:ce,noValidate:!0,children:[t.jsx("h4",{className:"settings-section-heading",children:l?"Edit Routine":"New Routine"}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-name",children:"Name"}),t.jsx("input",{id:"routine-name",type:"text",placeholder:"e.g. Daily standup reminder",value:u,onChange:te=>d(te.target.value),"aria-invalid":!!X.name,"aria-describedby":X.name?De:void 0}),X.name&&t.jsx("small",{id:De,className:"field-error",children:X.name})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-description",children:"Description (optional)"}),t.jsx("textarea",{id:"routine-description",placeholder:"What does this routine do?",value:m,onChange:te=>h(te.target.value),rows:2})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Scope"}),t.jsxs("div",{className:"routine-scope-toggle",role:"radiogroup","aria-label":"Routine scope",children:[t.jsxs("button",{type:"button",className:`routine-scope-btn${re==="global"?" active":""}`,onClick:()=>{ke("global"),o?.("global")},role:"radio","aria-checked":re==="global"?"true":"false",disabled:!!e?.scope,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:"Global scope",children:[t.jsx(Uo,{size:12}),"Global"]}),t.jsxs("button",{type:"button",className:`routine-scope-btn${re==="project"?" active":""}`,onClick:()=>{ke("project"),o?.("project")},role:"radio","aria-checked":re==="project"?"true":"false",disabled:!!e?.scope||!r,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:r?"Project scope":"Select a project to enable project scope",children:[t.jsx(Jn,{size:12}),"Project"]})]}),t.jsx("small",{children:!r&&!e?.scope?"No active project. Routines will be created at global scope.":re==="project"&&r?"This routine will be scoped to the current project.":"This routine will be created at global scope."}),X.scope&&t.jsx("small",{className:"field-error",children:X.scope})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Trigger Type"}),t.jsxs("div",{className:"routine-trigger-type-selector",role:"radiogroup","aria-label":"Trigger type",children:[t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="cron"?" active":""}`,onClick:()=>p("cron"),role:"radio","aria-checked":f==="cron",children:[t.jsx(Yh,{size:14}),"Cron"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="webhook"?" active":""}`,onClick:()=>p("webhook"),role:"radio","aria-checked":f==="webhook",children:[t.jsx(op,{size:14}),"Webhook"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="api"?" active":""}`,onClick:()=>p("api"),role:"radio","aria-checked":f==="api",children:[t.jsx(Qh,{size:14}),"API"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="manual"?" active":""}`,onClick:()=>p("manual"),role:"radio","aria-checked":f==="manual",children:[t.jsx(Gn,{size:14}),"Manual"]})]})]}),f==="cron"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-frequency",children:"Frequency"}),t.jsx("select",{id:"routine-frequency",value:v,onChange:te=>Ze(te.target.value),children:Object.entries(eT).map(([te,Je])=>t.jsx("option",{value:te,children:Je},te))}),t.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),t.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:g,onChange:te=>b(te.target.value),disabled:v!=="custom","aria-invalid":!!X.cronExpression,"aria-describedby":X.cronExpression?ue:void 0}),X.cronExpression?t.jsx("small",{id:ue,className:"field-error",children:X.cronExpression}):t.jsx("small",{children:v==="custom"?t.jsxs(t.Fragment,{children:["min hour day month weekday — ",t.jsx("a",{href:"https://crontab.guru",target:"_blank",rel:"noopener noreferrer",children:"crontab.guru"})]}):`Auto-filled from preset: ${g}`})]}),f==="webhook"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-path",children:"Webhook Path"}),t.jsx("input",{id:"routine-webhook-path",type:"text",placeholder:"/trigger/my-routine",value:y,onChange:te=>k(te.target.value),"aria-invalid":!!X.webhookPath,"aria-describedby":X.webhookPath?Re:void 0}),X.webhookPath?t.jsx("small",{id:Re,className:"field-error",children:X.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:_,onChange:te=>S(te.target.value)}),t.jsx("small",{children:"HMAC secret for signature verification. Leave empty for unauthenticated webhooks."})]})]}),f==="api"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-endpoint",children:"API Endpoint"}),t.jsx("input",{id:"routine-endpoint",type:"text",placeholder:"/api/routine/my-routine",value:w,onChange:te=>M(te.target.value),"aria-invalid":!!X.endpoint,"aria-describedby":X.endpoint?Ke:void 0}),X.endpoint?t.jsx("small",{id:Ke,className:"field-error",children:X.endpoint}):t.jsx("small",{children:"API endpoint path that triggers this routine"})]}),f==="manual"&&t.jsx("div",{className:"form-group",children:t.jsx("small",{className:"routine-trigger-info",children:"This routine will be triggered manually via the dashboard or API."})}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Action Mode"}),t.jsxs("div",{className:"schedule-mode-toggle",role:"radiogroup","aria-label":"Action mode",children:[t.jsx("button",{type:"button",className:`schedule-mode-btn${z==="simple"?" active":""}`,onClick:()=>B("simple"),role:"radio","aria-checked":z==="simple",children:"Simple"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${z==="advanced"?" active":""}`,onClick:()=>B("advanced"),role:"radio","aria-checked":z==="advanced",children:"Multi-Step"})]}),t.jsx("small",{children:z==="simple"?"Run one command, prompt, or task creation action":"Run multiple actions sequentially"})]}),z==="simple"?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Action Type"}),t.jsxs("div",{className:"schedule-mode-toggle",role:"radiogroup","aria-label":"Action type",children:[t.jsx("button",{type:"button",className:`schedule-mode-btn${J==="command"?" active":""}`,onClick:()=>Q("command"),role:"radio","aria-checked":J==="command",children:"Command"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${J==="ai-prompt"?" active":""}`,onClick:()=>Q("ai-prompt"),role:"radio","aria-checked":J==="ai-prompt",children:"AI Prompt"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${J==="create-task"?" active":""}`,onClick:()=>Q("create-task"),role:"radio","aria-checked":J==="create-task",children:"Create Task"})]})]}),J==="command"?t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-command",children:"Command"}),t.jsx("input",{id:"routine-command",type:"text",placeholder:"e.g. npx runfusion.ai backup --create",value:C,onChange:te=>L(te.target.value),"aria-invalid":!!X.command,"aria-describedby":X.command?Pe:void 0}),X.command?t.jsx("small",{id:Pe,className:"field-error",children:X.command}):t.jsx("small",{children:"Shell command to execute."})]}):J==="ai-prompt"?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-prompt",children:"Prompt"}),t.jsx("textarea",{id:"routine-prompt",placeholder:"e.g. Summarize recent activity and create action items",value:se,onChange:te=>me(te.target.value),rows:3,"aria-invalid":!!X.prompt,"aria-describedby":X.prompt?ft:void 0}),X.prompt?t.jsx("small",{id:ft,className:"field-error",children:X.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(Yn,{id:"routine-model",label:"Model",models:Qe,value:Ue,onChange:nt,placeholder:"Use default",disabled:Ye}),Be&&t.jsx("small",{className:"field-error",children:Be}),X.model&&t.jsx("small",{id:le,className:"field-error",children:X.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:F,onChange:te=>de(te.target.value)})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-description",children:"Task Description"}),t.jsx("textarea",{id:"routine-task-description",placeholder:"e.g. Check npm dependencies for security vulnerabilities",value:ne,onChange:te=>xe(te.target.value),rows:4,"aria-invalid":!!X.taskDescription,"aria-describedby":X.taskDescription?Z:void 0}),X.taskDescription?t.jsx("small",{id:Z,className:"field-error",children:X.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:oe,onChange:te=>he(te.target.value),children:[t.jsx("option",{value:"triage",children:"Triage"}),t.jsx("option",{value:"todo",children:"To Do"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-model",children:"Executor Model (optional)"}),t.jsx(Yn,{id:"routine-task-model",label:"Executor Model",models:Qe,value:Ue,onChange:nt,placeholder:"Use default",disabled:Ye}),Be&&t.jsx("small",{className:"field-error",children:Be}),X.model&&t.jsx("small",{id:le,className:"field-error",children:X.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(ZR,{steps:P,onChange:j,onEditingChange:H}),X.steps&&t.jsx("small",{className:"field-error",children:X.steps}),X.stepsEditing&&t.jsx("small",{className:"field-error",children:X.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:ge,onChange:te=>be(Number(te.target.value)),"aria-invalid":!!X.timeoutMs,"aria-describedby":X.timeoutMs?we:void 0}),X.timeoutMs?t.jsx("small",{id:we,className:"field-error",children:X.timeoutMs}):t.jsx("small",{children:"Maximum execution time in milliseconds."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-execution-policy",children:"Execution Policy"}),t.jsx("select",{id:"routine-execution-policy",value:N,onChange:te=>D(te.target.value),children:aT.map(te=>t.jsx("option",{value:te.value,children:te.label},te.value))}),t.jsx("small",{children:"How to handle concurrent executions of this routine"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-catchup-policy",children:"Catch-up Policy"}),t.jsx("select",{id:"routine-catchup-policy",value:E,onChange:te=>T(te.target.value),children:rT.map(te=>t.jsx("option",{value:te.value,children:te.label},te.value))}),t.jsx("small",{children:"What to do when a scheduled run is missed"})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:"routine-enabled",className:"checkbox-label",children:[t.jsx("input",{id:"routine-enabled",type:"checkbox",checked:U,onChange:te=>K(te.target.checked)}),"Enabled"]}),t.jsx("small",{children:"When disabled, the routine will not run automatically"})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,disabled:Le,children:"Cancel"}),t.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:Le,children:Le?"Saving…":l?"Save Changes":"Create Routine"})]})]})}const oT=3e4;function lT({onClose:e,addToast:n,projectId:s}){const[i,r]=a.useState(()=>s?"project":"global"),[o,l]=a.useState([]),[c,u]=a.useState("list"),[d,m]=a.useState(),[h,f]=a.useState(null),[p,g]=a.useState({}),b=a.useRef(null);oi(b,!0,"fusion:automation-modal-size");const v=a.useMemo(()=>({scope:i,projectId:i==="project"?s:void 0}),[i,s]),x=a.useCallback(async()=>{try{const $=await Sj(v);l($),g(R=>{const z={...R};for(const B of $){const J=z[B.id];if(!J||!B.lastRunResult)continue;const Q=B.lastRunResult;Q.success===J.success&&(Q.output||"")===J.output&&(Q.error||"")===(J.error||"")&&delete z[B.id]}return z})}catch($){n(ye($)||"Failed to load routines","error")}},[n,v]);a.useEffect(()=>{x()},[x]),a.useEffect(()=>{const $=setInterval(()=>{x()},oT);return()=>clearInterval($)},[x]),a.useEffect(()=>{const $=R=>{R.key==="Escape"&&(c!=="list"?(u("list"),m(void 0)):e())};return document.addEventListener("keydown",$),()=>document.removeEventListener("keydown",$)},[e,c]);const y=Ei(e),k=a.useCallback(async $=>{try{await Cj($,v),n("Routine created","success"),u("list"),await x()}catch(R){n(ye(R)||"Failed to create routine","error")}},[n,x,v]),_=a.useCallback($=>{m($),u("edit")},[]),S=a.useCallback(async $=>{if(d)try{await tu(d.id,$,v),n("Routine updated","success"),u("list"),m(void 0),await x()}catch(R){n(ye(R)||"Failed to update routine","error")}},[d,n,x,v]),w=a.useCallback(async $=>{try{await Ej($.id,v),n(`Deleted "${$.name}"`,"success"),await x()}catch(R){n(ye(R)||"Failed to delete routine","error")}},[n,x,v]),M=a.useCallback(async $=>{f($.id);try{const{result:R}=await _j($.id,v);g(z=>({...z,[$.id]:{output:R.output||"",error:R.error,success:R.success}})),R.success?n(`"${$.name}" completed successfully`,"success"):n(`"${$.name}" failed: ${R.error||"Unknown error"}`,"error"),await x()}catch(R){n(ye(R)||"Failed to run routine","error")}finally{f(null)}},[n,x,v]),N=a.useCallback(async $=>{try{await tu($.id,{enabled:!$.enabled},v),n(`"${$.name}" ${$.enabled?"disabled":"enabled"}`,"success"),await x()}catch(R){n(ye(R)||"Failed to toggle routine","error")}},[n,x,v]),D=a.useCallback(()=>{u("list"),m(void 0)},[]);a.useEffect(()=>{c!=="list"&&g({})},[c]);const E=a.useCallback($=>{r($),u("list"),m(void 0),g({})},[]),T=()=>c==="create"?t.jsx(vh,{onSubmit:k,onCancel:D,scope:i,projectId:s}):c==="edit"&&d?t.jsx(vh,{routine:d,onSubmit:S,onCancel:D,scope:i,projectId:s}):o.length===0?t.jsxs("div",{className:"routine-empty-state",children:[t.jsx(Gn,{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(on,{size:14}),"Create your first automation"]})]}):t.jsx("div",{className:"routine-list",children:o.map($=>t.jsx(JR,{routine:$,onEdit:_,onDelete:w,onRun:M,onToggle:N,running:h===$.id,lastRunOutput:p[$.id]??null},$.id))}),U=()=>T(),K=c==="list"&&o.length>0;return t.jsx("div",{className:"modal-overlay open",...y,children:t.jsxs("div",{ref:b,className:"modal modal-lg automation-modal",role:"dialog","aria-modal":"true","aria-labelledby":"schedules-modal-title",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(Gn,{size:20,className:"icon-triage"}),t.jsx("h3",{id:"schedules-modal-title",children:"Automations"})]}),t.jsx("button",{className:"modal-close",onClick:e,"aria-label":"Close",children:t.jsx(Wt,{size:20})})]}),t.jsxs("div",{className:"scheduling-toolbar","aria-live":"polite",children:[t.jsxs("div",{className:"scheduling-toolbar-left",role:"group","aria-label":"Scheduling scope",children:[t.jsxs("div",{className:"scheduling-scope-selector",children:[t.jsxs("button",{type:"button",className:`scope-btn${i==="global"?" active":""}`,onClick:()=>E("global"),"aria-pressed":i==="global",title:"Global (user-level) automations",children:[t.jsx(Uo,{size:14}),"Global"]}),t.jsxs("button",{type:"button",className:`scope-btn${i==="project"?" active":""}`,onClick:()=>E("project"),"aria-pressed":i==="project",title:"Project-scoped automations",children:[t.jsx(Jn,{size:14}),"Project"]})]}),t.jsxs("span",{className:"scheduling-count",children:[t.jsx(Gn,{size:14}),o.length," automation",o.length===1?"":"s"]})]}),t.jsx("div",{className:"scheduling-toolbar-right",children:K&&t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>u("create"),"aria-label":"Create new automation",children:[t.jsx(on,{size:14}),"New Automation"]})})]}),t.jsx("div",{className:"schedule-modal-content",id:"scheduled-tasks-content",children:U()})]})})}const cT=3e4,Qc=new Map,dc=new Map;function yh(e){return e??"default"}function jh(e){const n=Qc.get(e);return n?Date.now()>=n.expiresAt?(Qc.delete(e),null):n:null}function dT(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 uT(e){const n=dc.get(e);if(n)return n;const s=gr().then(({providers:i,ghCli:r})=>{const l={...dT(i,r),ghCli:r,expiresAt:Date.now()+cT};return Qc.set(e,l),l}).finally(()=>{dc.delete(e)});return dc.set(e,s),s}function hg(e){const n=yh(e),s=jh(n),[i,r]=a.useState(s?.hasAiProvider??!1),[o,l]=a.useState(s?.hasGithub??!1),[,c]=a.useState(s?.ghCli),[u,d]=a.useState(s==null),m=a.useRef(!!s);return a.useEffect(()=>{let h=!1;const f=yh(e),p=jh(f);if(p)return r(p.hasAiProvider),l(p.hasGithub),c(p.ghCli),d(!1),m.current=!0,()=>{h=!0};m.current=!1;async function g(){!m.current&&d(!0);try{const v=await uT(f);if(h)return;r(v.hasAiProvider),l(v.hasGithub),c(v.ghCli)}catch{}finally{h||(m.current=!0,d(!1))}}return g(),()=>{h=!0}},[e]),a.useMemo(()=>({hasAiProvider:i,hasGithub:o,loading:u,hasWarnings:!i||!o}),[i,o,u])}function pg({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(Wt,{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 mT({isOpen:e,onClose:n,projectId:s,tasks:i,onCreateTask:r,addToast:o,onPlanningMode:l,onSubtaskBreakdown:c}){const{confirm:u}=Ws(),[d,m]=a.useState(""),[h,f]=a.useState([]),[p,g]=a.useState([]),[b,v]=a.useState(!1),[x,y]=a.useState(""),[k,_]=a.useState(""),[S,w]=a.useState(""),[M,N]=a.useState(""),[D,E]=a.useState(""),[T,U]=a.useState("default"),[K,$]=a.useState(!1),[R,z]=a.useState([]),[B,J]=a.useState(!1),[Q,C]=a.useState(void 0),[L,P]=a.useState(ws),[j,O]=a.useState(void 0),[H,ge]=a.useState(null),[be,se]=a.useState([]),[me,F]=a.useState(!1),[de,ne]=a.useState(!1),xe=a.useRef(null),[oe,he]=a.useState(!1),[ae,je]=a.useState(""),Ae=a.useRef(null),{hasAiProvider:Oe,hasGithub:Qe,loading:Xe}=hg(s),{nodes:Ye}=Qo(),it=a.useCallback(ve=>{J(!0),z(ve)},[]),Be=a.useCallback(()=>{J(!1)},[]),Ge=a.useCallback(async()=>{if(be.length>0){F(!0);return}ne(!0);try{const ve=await Ea(void 0,s);se(ve),F(!0)}catch(ve){const ce=ye(ve);o(ce?`Failed to load agents: ${ce}`:"Failed to load agents","error"),F(!1)}finally{ne(!1)}},[be.length,s,o]);a.useEffect(()=>{if(!me)return;const ve=ce=>{xe.current&&!xe.current.contains(ce.target)&&F(!1)};return document.addEventListener("mousedown",ve),()=>document.removeEventListener("mousedown",ve)},[me]),a.useEffect(()=>{if(!oe)return;const ve=ce=>{Ae.current&&!Ae.current.contains(ce.target)&&(he(!1),je(""))};return document.addEventListener("mousedown",ve),()=>document.removeEventListener("mousedown",ve)},[oe]);const re=i.filter(ve=>!h.includes(ve.id)).sort((ve,ce)=>{const De=ce.createdAt.localeCompare(ve.createdAt);if(De!==0)return De;const ue=parseInt(ve.id.slice(ve.id.lastIndexOf("-")+1),10)||0;return(parseInt(ce.id.slice(ce.id.lastIndexOf("-")+1),10)||0)-ue}),ke=ae?re.filter(ve=>ve.id.toLowerCase().includes(ae.toLowerCase())||ve.title&&ve.title.toLowerCase().includes(ae.toLowerCase())||ve.description&&ve.description.toLowerCase().includes(ae.toLowerCase())):re,X=(ve,ce)=>ve.length>ce?ve.slice(0,ce)+"…":ve;a.useEffect(()=>{const ve=d.trim()!==""||h.length>0||p.length>0||x!==""||k!==""||S!==""||M!==""||R.length>0||H!==null||Q!==void 0||L!==ws||j!==void 0;$(ve)},[d,h,p,x,k,S,M,R,H,Q,L,j]);const Te=a.useCallback(async()=>{K&&!await u({title:"Discard Changes",message:"You have unsaved changes. Discard them?",danger:!0})||(p.forEach(ve=>URL.revokeObjectURL(ve.previewUrl)),g([]),m(""),f([]),y(""),_(""),w(""),N(""),E(""),U("default"),z([]),J(!1),ge(null),F(!1),C(void 0),P(ws),O(void 0),$(!1),n())},[K,n,p,u]),Le=a.useCallback(async()=>{const ve=d.trim();if(!(!ve||b)){v(!0);try{const ce=x.indexOf("/"),De=k.indexOf("/"),ue=S.indexOf("/"),Re=await r({title:void 0,description:ve,column:"triage",dependencies:h.length?h:void 0,enabledWorkflowSteps:B?R.length>0?R:[]:void 0,...H?{assignedAgentId:H}:{},modelPresetId:T==="preset"&&D||void 0,modelProvider:x&&ce!==-1?x.slice(0,ce):void 0,modelId:x&&ce!==-1?x.slice(ce+1):void 0,validatorModelProvider:k&&De!==-1?k.slice(0,De):void 0,validatorModelId:k&&De!==-1?k.slice(De+1):void 0,planningModelProvider:S&&ue!==-1?S.slice(0,ue):void 0,planningModelId:S&&ue!==-1?S.slice(ue+1):void 0,thinkingLevel:M!==""?M:void 0,reviewLevel:Q,priority:L,nodeId:j});if(p.length>0){const Ke=[];for(const Pe of p)try{await fr(Re.id,Pe.file,s)}catch{Ke.push(Pe.file.name)}Ke.length>0&&o(`Failed to upload: ${Ke.join(", ")}`,"error")}p.forEach(Ke=>URL.revokeObjectURL(Ke.previewUrl)),g([]),m(""),f([]),y(""),_(""),w(""),N(""),E(""),U("default"),z([]),J(!1),ge(null),F(!1),C(void 0),P(ws),O(void 0),o(`Created ${Re.id}`,"success"),n()}catch(ce){o(ye(ce)||"Failed to create task","error")}finally{v(!1)}}},[d,h,p,x,k,S,M,b,r,o,n,s,T,D,R,B,H,Q,L,j]),fe=a.useCallback(ve=>{ve.key==="Escape"&&(ve.preventDefault(),Te())},[Te]),Ue=(H?be.find(ve=>ve.id===H):void 0)?.name??H,nt=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:Ae,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>he(ve=>!ve),disabled:b,"data-testid":"dep-trigger",children:h.length>0?`${h.length} selected`:"Add dependencies"}),oe&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:ae,onChange:ve=>je(ve.target.value),onClick:ve=>ve.stopPropagation()}),ke.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):ke.map(ve=>t.jsxs("div",{className:`dep-dropdown-item${h.includes(ve.id)?" selected":""}`,onClick:()=>{f(h.includes(ve.id)?h.filter(ce=>ce!==ve.id):[...h,ve.id]),he(!1),je("")},onMouseDown:ce=>ce.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:ve.id}),t.jsx("span",{className:"dep-dropdown-title",children:X(ve.title||ve.description||ve.id,30)})]},ve.id))]})]}),h.length>0&&t.jsx("div",{className:"selected-deps",children:h.map(ve=>t.jsxs("span",{className:"dep-chip",children:[ve,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>f(h.filter(ce=>ce!==ve)),disabled:b,children:"×"})]},ve))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Assign Agent"}),t.jsxs("div",{className:"agent-trigger-wrap",ref:xe,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{me?F(!1):Ge()},disabled:b,"data-testid":"new-task-agent-button",children:[t.jsx(Nn,{size:12,style:{verticalAlign:"middle"}}),Ue?` ${Ue}`:" Assign agent"]}),me&&t.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:ve=>ve.preventDefault(),children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),de&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!de&&be.filter(ve=>ve.state!=="terminated").map(ve=>t.jsxs("div",{className:`dep-dropdown-item${H===ve.id?" selected":""}`,onMouseDown:ce=>ce.preventDefault(),onClick:()=>{ge(ve.id===H?null:ve.id),F(!1)},"data-testid":`agent-option-${ve.id}`,children:[t.jsx(Nn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:ve.role}),t.jsx("span",{className:"dep-dropdown-title",children:ve.name})]},ve.id)),!de&&be.filter(ve=>ve.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),H&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:ve=>ve.preventDefault(),onClick:()=>{ge(null),F(!1)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return e?t.jsx("div",{className:"modal-overlay open",onClick:Te,onKeyDown:fe,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:ve=>ve.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:"New Task"}),t.jsx("button",{className:"modal-close",onClick:Te,disabled:b,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!Xe&&t.jsx(pg,{hasAiProvider:Oe,hasGithub:Qe}),t.jsx(ig,{mode:"create",description:d,onDescriptionChange:m,dependencies:h,onDependenciesChange:f,executorModel:x,onExecutorModelChange:y,validatorModel:k,onValidatorModelChange:_,presetMode:T,onPresetModeChange:U,selectedPresetId:D,onSelectedPresetIdChange:E,selectedWorkflowSteps:R,onWorkflowStepsChange:it,onDefaultOnApplied:Be,pendingImages:p,onImagesChange:g,tasks:i,projectId:s,disabled:b,addToast:o,isActive:e,onPlanningMode:l,onSubtaskBreakdown:c,onClose:Te,planningModel:S,onPlanningModelChange:w,thinkingLevel:M,onThinkingLevelChange:N,reviewLevel:Q,onReviewLevelChange:C,priority:L,onPriorityChange:P,nodeId:j,onNodeIdChange:O,nodeOptions:Ye,renderBelowPrimary:nt,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:Te,disabled:b,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Le,disabled:!d.trim()||b,children:b?"Creating...":"Create Task"})]})]})}):null}function Us(e){if(!Number.isFinite(e)||e<0)return"—";const n=e/(1024*1024);return n<1024?`${n.toFixed(0)} MB`:`${(n/1024).toFixed(2)} GB`}function kh(e,n){return!Number.isFinite(e)||!Number.isFinite(n)||n<=0?"—":`${(e/n*100).toFixed(1)}%`}function hT(e,n){if(n<=0)return"normal";const s=e/n;return s>=.85?"critical":s>=.65?"warning":"normal"}function pT(e,n){if(n<=0)return"normal";const s=e/n;return s>=.5?"critical":s>=.25?"warning":"normal"}function fT(e,n){if(n<=0)return"normal";const s=e/n;return s>=.9?"critical":s>=.75?"warning":"normal"}function uc(e){return e==="critical"?"system-stats-modal__value--critical":e==="warning"?"system-stats-modal__value--warning":""}function gT(e){if(!e)return"Not yet";const n=new Date(e);return Number.isNaN(n.getTime())?"Not yet":n.toLocaleString()}function bT({isOpen:e,onClose:n,projectId:s}){const[i,r]=a.useState(null),[o,l]=a.useState(!1),[c,u]=a.useState(null),[d,m]=a.useState(!0),[h,f]=a.useState(90),[p,g]=a.useState(!1),[b,v]=a.useState(!1),[x,y]=a.useState(null),[k,_]=a.useState(null),[S,w]=a.useState(null),M=a.useCallback(async O=>{l(!0);try{const H=await ek(s);r(H),u(null),w(Date.now()),O?.preserveKillResult||y(null)}catch(H){u(H instanceof Error?H.message:"Failed to load system stats")}finally{l(!1)}},[s]);a.useEffect(()=>{if(!e)return;M();const O=window.setInterval(()=>{M()},5e3);return()=>{window.clearInterval(O)}},[e,M]),a.useEffect(()=>{if(!e)return;(async()=>{try{const H=await Gi();m(H.vitestAutoKillEnabled??!0),f(H.vitestKillThresholdPct??90),_(null)}catch(H){_(H instanceof Error?H.message:"Failed to load vitest settings")}})()},[e]),a.useEffect(()=>{if(!e)return;const O=H=>{H.key==="Escape"&&n()};return document.addEventListener("keydown",O),()=>document.removeEventListener("keydown",O)},[e,n]);const N=a.useMemo(()=>{if(!i)return[];const O=i.systemStats,H=uc(hT(O.heapUsed,O.heapLimit)),ge=uc(pT(O.rss,O.systemTotalMem));return[{label:"RSS",value:Us(O.rss),detail:kh(O.rss,O.systemTotalMem),className:ge},{label:"Heap Used",value:Us(O.heapUsed),detail:`of ${Us(O.heapTotal)}`,className:H},{label:"Heap Limit",value:Us(O.heapLimit),detail:"V8 limit"},{label:"External",value:Us(O.external)},{label:"Array Buffers",value:Us(O.arrayBuffers)}]},[i]),D=a.useCallback(async O=>{m(O);try{await hn({vitestAutoKillEnabled:O}),_(null)}catch(H){_(H instanceof Error?H.message:"Failed to save vitest settings")}},[]),E=a.useCallback(async O=>{const H=Math.min(99,Math.max(50,Number.isFinite(O)?Math.round(O):90));f(H);try{await hn({vitestKillThresholdPct:H}),_(null)}catch(ge){_(ge instanceof Error?ge.message:"Failed to save vitest settings")}},[]),T=a.useCallback(async()=>{if(!p){if(!b){v(!0);return}g(!0);try{const O=await tk(s);y(O),v(!1),await M({preserveKillResult:!0})}catch(O){u(O instanceof Error?O.message:"Failed to kill vitest processes")}finally{g(!1)}}},[b,p,M,s]);if(!e)return null;const U=i?.systemStats,K=o&&!!i,$=S?`Updated ${new Date(S).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`:"Waiting for first update",R=i?.taskStats,z=U?U.systemTotalMem-U.systemFreeMem:0,B=U?fT(z,U.systemTotalMem):"normal",J=U?uc(B):"",Q=U&&Number.isFinite(U.systemTotalMem)&&U.systemTotalMem>0?Math.max(0,Math.min(100,z/U.systemTotalMem*100)):0,C=U?`System memory used: ${Q.toFixed(1)}% (${Us(z)} of ${Us(U.systemTotalMem)})`:"System memory usage unavailable",L=i?.vitestProcessCount,P=x?x.killed>0?"system-stats-modal__kill-result system-stats-modal__kill-result--success":"system-stats-modal__kill-result system-stats-modal__kill-result--error":"",j=gT(i?.vitestLastAutoKillAt);return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"system-stats-modal-title",onClick:O=>{O.target===O.currentTarget&&n()},"data-testid":"system-stats-modal-overlay",children:t.jsxs("div",{className:"modal modal-lg system-stats-modal","data-testid":"system-stats-modal",children:[t.jsxs("div",{className:"modal-header system-stats-modal__header",children:[t.jsxs("h2",{id:"system-stats-modal-title",className:"system-stats-modal__title",children:[t.jsx(mr,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("div",{className:"system-stats-modal__header-actions",children:[t.jsxs("span",{className:"system-stats-modal__auto-refresh","aria-live":"polite",children:[t.jsx("span",{children:"Auto-refresh · 5s"}),t.jsx("span",{className:"system-stats-modal__auto-refresh-time",children:$})]}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>void M(),title:"Refresh","aria-label":"Refresh system stats",children:t.jsx($n,{size:16,className:K?"system-stats-modal__refresh--spinning":void 0})}),t.jsx("button",{type:"button",className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Wt,{})})]})]}),o&&!i&&t.jsx("div",{className:"system-stats-modal__state",children:"Loading system stats…"}),c&&!i&&t.jsx("div",{className:"system-stats-modal__state system-stats-modal__state--error",role:"alert",children:c}),i&&t.jsxs("div",{className:"system-stats-modal__content",children:[t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Process stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Process"}),t.jsx("dl",{className:"system-stats-modal__grid",children:N.map(O=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:O.label}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${O.className}`.trim(),children:O.value}),O.detail?t.jsx("span",{className:"system-stats-modal__detail",children:O.detail}):null]})]},O.label))})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"CPU and load stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"CPU & Load"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Load Avg"}),t.jsx("dd",{children:U?.loadAvg.map(O=>O.toFixed(2)).join(" ")??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Cores"}),t.jsx("dd",{children:U?.cpuCount??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Platform"}),t.jsx("dd",{children:U?.platform??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Node"}),t.jsx("dd",{children:U?.nodeVersion??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"PID"}),t.jsx("dd",{children:U?.pid??"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"System memory stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"System"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row system-stats-modal__row--memory-used",children:[t.jsx("dt",{children:"Memory Used"}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${J}`.trim(),children:U?Us(z):"—"}),t.jsx("span",{className:"system-stats-modal__detail",children:U?`${kh(z,U.systemTotalMem)} of ${Us(U.systemTotalMem)}`:""})]}),t.jsx("div",{className:"system-stats-modal__memory-progress-wrapper",children:t.jsx("div",{className:`system-stats-modal__memory-progress-track system-stats-modal__memory-progress-track--${B}`,role:"progressbar","aria-valuenow":Math.round(Q),"aria-valuemin":0,"aria-valuemax":100,"aria-label":C,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${B}`,style:{width:`${Q}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Memory Free"}),t.jsx("dd",{children:U?Us(U.systemFreeMem):"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Task stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Tasks"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Total"}),t.jsx("dd",{children:R?.total??0})]}),Object.entries(R?.byColumn??{}).map(([O,H])=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:O}),t.jsx("dd",{children:H})]},O))]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Agent stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Agents"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"idle"}),t.jsx("dd",{children:R?.agents.idle??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"active"}),t.jsx("dd",{children:R?.agents.active??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"running"}),t.jsx("dd",{children:R?.agents.running??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"error"}),t.jsx("dd",{children:R?.agents.error??0})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Vitest controls",children:[t.jsxs("h3",{className:"system-stats-modal__section-title system-stats-modal__section-title--with-icon",children:[t.jsx(Jx,{}),t.jsx("span",{children:"Vitest Controls"})]}),t.jsx("dl",{className:"system-stats-modal__grid system-stats-modal__vitest-controls",children:t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Vitest Processes"}),t.jsx("dd",{children:L??"—"})]})}),t.jsxs("div",{className:"system-stats-modal__vitest-controls",children:[t.jsx("div",{className:"system-stats-modal__kill-row",children:t.jsxs("button",{type:"button",className:"btn btn-danger",onClick:()=>void T(),disabled:p||L===0,children:[t.jsx(Zx,{}),t.jsx("span",{children:b?"Confirm Kill?":"Kill Vitest Processes"})]})}),t.jsxs("label",{className:"system-stats-modal__toggle-row",children:[t.jsx("input",{type:"checkbox",checked:d,onChange:O=>{D(O.target.checked)}}),t.jsx("span",{children:"Auto-kill vitest on memory pressure"})]}),t.jsxs("div",{className:"system-stats-modal__threshold-row",children:[t.jsx("label",{htmlFor:"vitest-threshold-number",children:"Kill threshold (%)"}),t.jsxs("div",{className:"system-stats-modal__threshold-controls",children:[t.jsx("input",{id:"vitest-threshold-range",type:"range",min:50,max:99,value:h,"aria-label":"Kill threshold slider (%)",onChange:O=>{const H=Number.parseInt(O.target.value,10);E(Number.isNaN(H)?90:H)}}),t.jsx("input",{id:"vitest-threshold-number",type:"number",className:"input",min:50,max:99,value:h,"aria-label":"Kill threshold (%)",onChange:O=>{const H=Number.parseInt(O.target.value,10);E(Number.isNaN(H)?90:H)},onBlur:()=>{E(h)}})]})]}),x&&t.jsxs("p",{className:P,children:["Killed ",x.killed," processes"]}),t.jsxs("p",{className:"system-stats-modal__last-kill",children:["Last auto-kill: ",j]}),k&&t.jsx("p",{className:"system-stats-modal__kill-result system-stats-modal__kill-result--error",children:k})]})]})]}),c&&i&&t.jsxs("div",{className:"system-stats-modal__footer-error",children:["Latest refresh failed: ",c]})]})})}const xT=5e3;function vT(e={}){const{projectId:n,type:s,limit:i=50,autoRefresh:r=!0,useCentralFeed:o=!1}=e,[l,c]=a.useState([]),[u,d]=a.useState(!1),[m,h]=a.useState(null),[f,p]=a.useState(!1),g=a.useRef(null),b=a.useRef(void 0),v=a.useCallback(async()=>{try{d(!0),h(null);let k;o?k=await lu({limit:i,projectId:n,type:s}):k=(await nu({limit:i,type:s,projectId:n})).map(S=>({...S,projectId:n??"",projectName:""})),c(k),p(k.length===i),k.length>0&&(b.current=k[k.length-1].timestamp)}catch(k){h(k instanceof Error?k.message:"Failed to load activity log")}finally{d(!1)}},[i,n,s,o]),x=a.useCallback(async()=>{if(b.current)try{d(!0);let k;o?k=await lu({limit:i,projectId:n,type:s,since:b.current}):k=(await nu({limit:i,type:s,since:b.current,projectId:n})).map(S=>({...S,projectId:n??"",projectName:""})),c(_=>[..._,...k]),p(k.length===i),k.length>0&&(b.current=k[k.length-1].timestamp)}catch(k){h(k instanceof Error?k.message:"Failed to load more entries")}finally{d(!1)}},[i,n,s,o]),y=a.useCallback(()=>{c([]),p(!1),b.current=void 0},[]);return a.useEffect(()=>{v()},[v]),a.useEffect(()=>{if(r)return g.current=setInterval(()=>{v()},xT),()=>{g.current&&(clearInterval(g.current),g.current=null)}},[r,v]),{entries:l,loading:u,error:m,refresh:v,clear:y,hasMore:f,loadMore:x}}const mc={"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"},yT={"task:created":t.jsx(on,{size:14,className:"activity-icon created"}),"task:moved":t.jsx(kr,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx($n,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(Wt,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx(yn,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(wr,{size:14,className:"activity-icon failed"}),"settings:updated":t.jsx(rr,{size:14,className:"activity-icon settings"})};function jT(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 kT({isOpen:e,onClose:n,tasks:s,onOpenTaskDetail:i,projectId:r,projects:o=[],onProjectFilterChange:l,currentProject:c}){const[u,d]=a.useState("all"),[m,h]=a.useState(r||"all"),[f,p]=a.useState(!1);a.useEffect(()=>{h(r||"all")},[r]);const g=u==="all"?void 0:u,b=m==="all"?void 0:m,v=!c&&o.length>0,{entries:x,loading:y,error:k,refresh:_,hasMore:S}=vT({projectId:b,type:g,limit:100,autoRefresh:e,useCentralFeed:v}),w=x.map(T=>({id:T.id,timestamp:T.timestamp,type:T.type,taskId:T.taskId,taskTitle:T.taskTitle,details:T.details,metadata:T.metadata,projectId:T.projectId,projectName:T.projectName})),M=async()=>{try{await Mj(),_(),p(!1)}catch{p(!1)}},N=T=>{i&&i(T)},D=T=>{h(T),l?.(T==="all"?void 0:T)};a.useEffect(()=>{if(!e)return;const T=U=>{U.key==="Escape"&&(f?p(!1):n())};return document.addEventListener("keydown",T),()=>document.removeEventListener("keydown",T)},[e,n,f]);const E=u!=="all"||m!=="all";return e?t.jsx("div",{className:"modal-overlay open",onClick:T=>{T.target===T.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(ur,{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:T=>D(T.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[t.jsx("option",{value:"all",children:"All Projects"}),o.map(T=>t.jsx("option",{value:T.id,children:T.name},T.id))]})]}),t.jsxs("div",{className:"activity-log-filter",children:[t.jsx(jo,{size:14}),t.jsxs("select",{value:u,onChange:T=>d(T.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:"All Events"}),Object.entries(mc).map(([T,U])=>t.jsx("option",{value:T,children:U},T))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>_(),title:"Refresh","data-testid":"activity-refresh",children:y?t.jsx(ot,{size:14,className:"spin"}):t.jsx($n,{size:14})}),w.length>0&&t.jsx("button",{className:"activity-log-clear",onClick:()=>p(!0),title:"Clear Log","data-testid":"activity-clear",children:t.jsx(rn,{size:14})})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",title:"Close","data-testid":"activity-close",children:"×"})]}),E&&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(T=>T.id===m)?.name||m]}),u!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",mc[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:[k&&t.jsxs("div",{className:"activity-log-error","data-testid":"activity-error",children:[t.jsx(us,{size:16}),t.jsx("span",{children:k})]}),w.length===0&&!y&&!k&&t.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[t.jsx(ur,{size:48,className:"activity-log-empty-icon"}),t.jsx("p",{children:E?"No activity matches the current filters":"No activity recorded yet"}),E&&t.jsx("button",{className:"btn btn-secondary",onClick:()=>{d("all"),h("all"),l?.(void 0)},children:"Clear Filters"})]}),t.jsx("div",{className:"activity-log-list",children:w.map(T=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:yT[T.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:mc[T.type]}),t.jsx("span",{className:"activity-log-entry-time",children:jT(T.timestamp)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[T.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>N(T.taskId),"data-testid":"activity-task-link",children:T.taskId}),T.taskTitle&&t.jsx("span",{className:"activity-log-task-title",children:T.taskTitle}),t.jsx("span",{className:"activity-log-entry-text",children:T.details})]}),T.metadata&&Object.keys(T.metadata).length>0&&t.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof T.metadata.from=="string"&&typeof T.metadata.to=="string"&&t.jsxs("span",{className:"activity-log-metadata-item",children:[T.metadata.from," → ",T.metadata.to]}),typeof T.metadata.merged=="boolean"&&t.jsx("span",{className:`activity-log-metadata-item ${T.metadata.merged?"success":"error"}`,children:T.metadata.merged?"Merged":"Not merged"})]})]})]},T.id))}),S&&!y&&t.jsx("button",{className:"activity-log-load-more",onClick:_,"data-testid":"activity-load-more",children:"Load More"}),y&&w.length>0&&t.jsx("div",{className:"activity-log-loading",children:t.jsx(ot,{size:20,className:"spin"})})]}),f&&t.jsx("div",{className:"activity-log-confirm-overlay",children:t.jsxs("div",{className:"activity-log-confirm-dialog",children:[t.jsx("h3",{children:"Clear Activity Log?"}),t.jsx("p",{children:"This will permanently delete all activity log entries. This action cannot be undone."}),t.jsxs("div",{className:"activity-log-confirm-actions",children:[t.jsx("button",{className:"activity-log-confirm-cancel",onClick:()=>p(!1),children:"Cancel"}),t.jsx("button",{className:"activity-log-confirm-clear",onClick:M,children:"Clear Log"})]})]})})]})}):null}const Qa=[{id:"status",label:"Status",icon:ip},{id:"changes",label:"Changes",icon:Nc},{id:"commits",label:"Commits",icon:Nr},{id:"branches",label:"Branches",icon:Vs},{id:"worktrees",label:"Worktrees",icon:ex},{id:"stashes",label:"Stashes",icon:zo},{id:"remotes",label:"Remotes",icon:ep}];function wh({status:e}){switch(e){case"added":case"untracked":return t.jsx($b,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(Xh,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(Tb,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return t.jsx(Ui,{size:14,className:"gm-file-icon gm-file-renamed"});default:return t.jsx(Lb,{size:14,className:"gm-file-icon"})}}function Nh({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 wT(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 ya(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 NT({isOpen:e,onClose:n,tasks:s,addToast:i,projectId:r}){const o=Ws(),[l,c]=a.useState("status"),[u,d]=a.useState(!1),[m,h]=a.useState(null),f=a.useRef(null);oi(f,e,"fusion:git-modal-size");const p=Ei(n),g=wT(i),[b,v]=a.useState(null),[x,y]=a.useState([]),[k,_]=a.useState(new Set),[S,w]=a.useState(""),[M,N]=a.useState(!1),[D,E]=a.useState(null),[T,U]=a.useState(!1),[K,$]=a.useState(null),[R,z]=a.useState(null),B=a.useRef(0),[J,Q]=a.useState([]),[C,L]=a.useState(null),[P,j]=a.useState(null),[O,H]=a.useState(!1),[ge,be]=a.useState(20),[se,me]=a.useState(""),[F,de]=a.useState([]),[ne,xe]=a.useState(""),[oe,he]=a.useState(""),[ae,je]=a.useState(""),[Ae,Oe]=a.useState(null),[Qe,Xe]=a.useState([]),[Ye,it]=a.useState(!1),[Be,Ge]=a.useState(null),[re,ke]=a.useState(null),[X,Te]=a.useState(!1),[Le,fe]=a.useState([]),[_e,Ue]=a.useState([]),[nt,ve]=a.useState(""),[ce,De]=a.useState(null),[ue,Re]=a.useState(null),[Ke,Pe]=a.useState(null),ft=a.useCallback(async()=>{if(e){d(!0),h(null);try{switch(l){case"status":{const q=await Os(r);v(q);break}case"changes":{const[q,pe]=await Promise.all([Os(r),ta(r)]);v(q),y(pe),_(new Set),z(null),E(null),$(null);break}case"commits":{const q=await $y(ge,r);Q(q);break}case"branches":{const[q,pe]=await Promise.all([La(r),Os(r)]);de(q),v(pe);break}case"worktrees":{const q=await Fy(r);fe(q);break}case"stashes":{const q=await Vr(r);Ue(q);break}case"remotes":{const q=await Os(r);v(q);break}}}catch(q){h(ye(q)||"Failed to fetch git data"),i(ye(q)||"Failed to fetch git data","error")}finally{d(!1)}}},[l,e,ge,i,r]);a.useEffect(()=>{e&&ft()},[ft,e]),a.useEffect(()=>{if(!e)return;const q=pe=>{if(pe.key==="Escape"){n();return}if((pe.key==="ArrowUp"||pe.key==="ArrowDown")&&pe.altKey){pe.preventDefault();const $e=Qa.findIndex(A=>A.id===l);pe.key==="ArrowUp"&&$e>0?c(Qa[$e-1].id):pe.key==="ArrowDown"&&$e<Qa.length-1&&c(Qa[$e+1].id)}};return document.addEventListener("keydown",q),()=>document.removeEventListener("keydown",q)},[e,n,l]);const Z=a.useCallback(async q=>{try{await Qd(q,r),i(`Staged ${q.length} file(s)`,"success");const pe=await ta(r);y(pe),_(new Set),z(null),E(null),$(null)}catch(pe){i(ye(pe)||"Failed to stage files","error")}},[i,r]),le=a.useCallback(async q=>{try{await Jy(q,r),i(`Unstaged ${q.length} file(s)`,"success");const pe=await ta(r);y(pe),_(new Set),z(null),E(null),$(null)}catch(pe){i(ye(pe)||"Failed to unstage files","error")}},[i,r]),we=a.useCallback(async q=>{if(await o.confirm({title:"Discard Changes",message:`Discard changes to ${q.length} file(s)? This cannot be undone.`,danger:!0}))try{await Yy(q,r),i(`Discarded changes to ${q.length} file(s)`,"success");const[$e,A]=await Promise.all([ta(r),Os(r)]);y($e),v(A),_(new Set),z(null),E(null),$(null)}catch($e){i(ye($e)||"Failed to discard changes","error")}},[i,r,confirm]),Ze=a.useCallback(async q=>{if(q.preventDefault(),!!S.trim()){N(!0);try{const pe=await Xd(S.trim(),r);i(`Committed: ${pe.hash}`,"success"),w("");const[$e,A]=await Promise.all([ta(r),Os(r)]);y($e),v(A),z(null),E(null),$(null)}catch(pe){i(ye(pe)||"Failed to commit","error")}finally{N(!1)}}},[S,i,r]),te=a.useCallback(async()=>{if(S.trim()){N(!0);try{const q=x.filter(ee=>!ee.staged).map(ee=>ee.file);q.length>0&&await Qd(q,r);const pe=await Xd(S.trim(),r);i(`Committed: ${pe.hash}`,"success"),w("");const[$e,A]=await Promise.all([ta(r),Os(r)]);y($e),v(A),z(null),E(null),$(null)}catch(q){i(ye(q)||"Failed to commit","error")}finally{N(!1)}}},[S,x,i,r]),Je=a.useCallback(async(q,pe)=>{z({file:q,staged:pe}),U(!0),$(null);const $e=B.current+1;B.current=$e;try{const A=await Gy(q,pe,r);if(B.current!==$e)return;E(A)}catch(A){if(B.current!==$e)return;const ee=ye(A)||"Failed to load file diff";E(null),$(ee),i(ee,"error")}finally{B.current===$e&&U(!1)}},[i,r]),dt=a.useCallback(q=>{_(pe=>{const $e=new Set(pe);return $e.has(q)?$e.delete(q):$e.add(q),$e})},[]),ut=a.useCallback(async q=>{if(C===q){L(null),j(null);return}L(q),H(!0);try{const pe=await No(q,r);j(pe)}catch(pe){i(ye(pe)||"Failed to load diff","error"),j(null)}finally{H(!1)}},[C,i,r]),Ct=a.useCallback(()=>{be(q=>Math.min(q+20,100))},[]),yt=a.useMemo(()=>{if(!se.trim())return J;const q=se.toLowerCase();return J.filter(pe=>pe.message.toLowerCase().includes(q)||pe.author.toLowerCase().includes(q)||pe.shortHash.toLowerCase().includes(q))},[J,se]),bt=a.useCallback(async q=>{if(q.preventDefault(),!!ne.trim()){d(!0);try{await Oy(ne.trim(),oe.trim()||void 0,r),i(`Created branch ${ne}`,"success"),xe(""),he("");const pe=await La(r);de(pe)}catch(pe){i(ye(pe)||"Failed to create branch","error")}finally{d(!1)}}},[ne,oe,i,r]),At=a.useCallback(async q=>{d(!0);try{await Uy(q,r),i(`Switched to ${q}`,"success");const[pe,$e]=await Promise.all([Os(r),La(r)]);v(pe),de($e)}catch(pe){i(ye(pe)||"Failed to checkout branch","error")}finally{d(!1)}},[i,r]),Rt=a.useCallback(async q=>{if(await o.confirm({title:"Delete Branch",message:`Delete branch "${q}"?`,danger:!0})){d(!0);try{await Yd(q,void 0,r),i(`Deleted branch ${q}`,"success");const $e=await La(r);de($e)}catch($e){if(ye($e).includes("not fully merged")){if(await o.confirm({title:"Force Delete Branch",message:"Branch has unmerged commits. Force delete?",danger:!0}))try{await Yd(q,!0,r),i(`Force deleted branch ${q}`,"success");const ee=await La(r);de(ee)}catch(ee){i(ye(ee)||"Failed to delete branch","error")}}else i(ye($e)||"Failed to delete branch","error")}finally{d(!1)}}},[i,r,confirm]),Ht=a.useMemo(()=>{if(!ae.trim())return F;const q=ae.toLowerCase();return F.filter(pe=>pe.name.toLowerCase().includes(q))},[F,ae]),Et=a.useCallback(async q=>{if(Ae===q){Oe(null),Xe([]),Ge(null),ke(null);return}Oe(q),Xe([]),Ge(null),ke(null),it(!0);try{const pe=await zy(q,10,r);Xe(pe)}catch{Xe([])}finally{it(!1)}},[Ae,r]),Dt=a.useCallback(async q=>{if(Be===q){Ge(null),ke(null);return}Ge(q),ke(null),Te(!0);try{const pe=await No(q,r);ke(pe)}catch{ke(null)}finally{Te(!1)}},[Be,r]),Kt=a.useCallback(()=>{Oe(null),Xe([]),Ge(null),ke(null)},[]),$t=a.useCallback(async q=>{q.preventDefault(),De("create");try{await Vy(nt.trim()||void 0,r),i("Changes stashed","success"),ve("");const pe=await Vr(r);Ue(pe)}catch(pe){i(ye(pe)||"Failed to stash changes","error")}finally{De(null)}},[nt,i,r]),Ft=a.useCallback(async(q,pe=!1)=>{De(`apply-${q}`);try{await Wy(q,pe,r),i(pe?"Stash popped":"Stash applied","success");const $e=await Vr(r);Ue($e)}catch($e){i(ye($e)||"Failed to apply stash","error")}finally{De(null)}},[i,r]),Ot=a.useCallback(async q=>{if(await o.confirm({title:"Drop Stash",message:`Drop stash@{${q}}? This cannot be undone.`,danger:!0})){De(`drop-${q}`);try{await Ky(q,r),i("Stash dropped","success");const $e=await Vr(r);Ue($e)}catch($e){i(ye($e)||"Failed to drop stash","error")}finally{De(null)}}},[i,r,confirm]),Tt=a.useCallback(async()=>{Re("fetch");try{const q=await By(void 0,r);Pe(q),i(q.message||"Fetch completed",q.fetched?"success":"info");const pe=await Os(r);v(pe)}catch(q){i(ye(q)||"Fetch failed","error")}finally{Re(null)}},[i,r]),Pt=a.useCallback(async()=>{Re("pull");try{const q=await Hy(r);Pe(q),q.conflict?i("Merge conflict detected. Resolve manually.","error"):i(q.message||"Pull completed","success");const pe=await Os(r);v(pe)}catch(q){i(ye(q)||"Pull failed","error")}finally{Re(null)}},[i,r]),wt=a.useCallback(async()=>{Re("push");try{const q=await qy(r);Pe(q),i(q.message||"Push completed","success");const pe=await Os(r);v(pe)}catch(q){i(ye(q)||"Push failed","error")}finally{Re(null)}},[i,r]),Gt=a.useMemo(()=>x.filter(q=>q.staged),[x]),Ut=a.useMemo(()=>x.filter(q=>!q.staged),[x]);return e?t.jsx("div",{className:"modal-overlay open",...p,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal gm-modal",ref:f,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h3",{children:[t.jsx(Sc,{size:18,style:{marginRight:8,verticalAlign:"middle"}}),"Git Manager"]}),t.jsxs("div",{className:"gm-header-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:ft,disabled:u,title:"Refresh",children:t.jsx($n,{size:14,className:u?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Wt,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:Qa.map(q=>{const pe=q.icon;return t.jsxs("button",{role:"tab","aria-selected":l===q.id,className:`gm-nav-item${l===q.id?" active":""}`,onClick:()=>c(q.id),children:[t.jsx(pe,{size:16}),t.jsx("span",{className:"gm-nav-label",children:q.label})]},q.id)})}),t.jsxs("div",{className:"gm-content",role:"tabpanel",children:[u&&t.jsxs("div",{className:"gm-loading",children:[t.jsx(ot,{size:24,className:"spin"}),t.jsx("span",{children:"Loading..."})]}),m&&!u&&t.jsxs("div",{className:"gm-error",children:[t.jsx(us,{size:18}),t.jsx("span",{children:m}),t.jsx("button",{className:"btn btn-sm",onClick:ft,children:"Retry"})]}),l==="status"&&!u&&b&&t.jsx(ST,{status:b,copyToClipboard:g}),l==="changes"&&!u&&t.jsx(CT,{status:b,stagedFiles:Gt,unstagedFiles:Ut,selectedFiles:k,toggleFileSelection:dt,onStageFiles:Z,onUnstageFiles:le,onDiscardChanges:we,onSelectDiffFile:Je,selectedDiffTarget:R,changeDiff:D,loadingChangeDiff:T,changeDiffError:K,commitMessage:S,setCommitMessage:w,onCommit:Ze,onStageAllAndCommit:te,committing:M}),l==="commits"&&!u&&t.jsx(ET,{commits:yt,commitSearch:se,setCommitSearch:me,selectedCommit:C,commitDiff:P,loadingDiff:O,onCommitClick:ut,onLoadMore:Ct,canLoadMore:J.length>=ge&&ge<100,copyToClipboard:g}),l==="branches"&&!u&&t.jsx(_T,{branches:Ht,branchSearch:ae,setBranchSearch:je,newBranchName:ne,setNewBranchName:xe,branchBase:oe,setBranchBase:he,onCreateBranch:bt,onCheckoutBranch:At,onDeleteBranch:Rt,loading:u,allBranches:F,selectedBranch:Ae,branchCommits:Qe,loadingBranchCommits:Ye,expandedBranchCommit:Be,branchCommitDiff:re,loadingBranchCommitDiff:X,onSelectBranch:Et,onBranchCommitClick:Dt,onCloseBranchDetails:Kt}),l==="worktrees"&&!u&&t.jsx(MT,{worktrees:Le}),l==="stashes"&&!u&&t.jsx(AT,{stashes:_e,stashMessage:nt,setStashMessage:ve,onCreateStash:$t,onApplyStash:Ft,onDropStash:Ot,stashLoading:ce}),l==="remotes"&&!u&&t.jsx(RT,{status:b,remoteLoading:ue,lastRemoteResult:Ke,onFetch:Tt,onPull:Pt,onPush:wt,addToast:i,projectId:r,copyToClipboard:g})]})]})]})}):null}function ST({status:e,copyToClipboard:n}){return t.jsxs("div",{className:"gm-panel","data-testid":"status-panel",children:[t.jsx("div",{className:"gm-panel-header",children:t.jsx("h4",{children:"Repository Status"})}),t.jsxs("div",{className:"gm-status-grid",children:[t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Branch"}),t.jsxs("span",{className:"gm-status-value",children:[t.jsx(Vs,{size:14}),t.jsx("span",{children:e.branch})]})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Commit"}),t.jsxs("span",{className:"gm-status-value",children:[t.jsx("code",{className:"gm-hash",children:e.commit}),t.jsx("button",{className:"gm-icon-btn",onClick:()=>n(e.commit,"commit hash"),title:"Copy commit hash",children:t.jsx(Oi,{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(us,{size:12}),"Modified"]}):t.jsxs(t.Fragment,{children:[t.jsx(yn,{size:12}),"Clean"]})})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Remote Sync"}),t.jsxs("span",{className:"gm-status-value",children:[e.ahead>0&&t.jsxs("span",{className:"gm-ahead",title:`${e.ahead} commit(s) ahead`,children:[t.jsx(zi,{size:12}),e.ahead]}),e.behind>0&&t.jsxs("span",{className:"gm-behind",title:`${e.behind} commit(s) behind`,children:[t.jsx(jr,{size:12}),e.behind]}),e.ahead===0&&e.behind===0&&t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(yn,{size:12}),"Up to date"]})]})]})]})]})}function CT({status:e,stagedFiles:n,unstagedFiles:s,selectedFiles:i,toggleFileSelection:r,onStageFiles:o,onUnstageFiles:l,onDiscardChanges:c,onSelectDiffFile:u,selectedDiffTarget:d,changeDiff:m,loadingChangeDiff:h,changeDiffError:f,commitMessage:p,setCommitMessage:g,onCommit:b,onStageAllAndCommit:v,committing:x}){const y=s.filter(_=>i.has(`unstaged:${_.file}`)),k=n.filter(_=>i.has(`staged:${_.file}`));return t.jsxs("div",{className:"gm-panel","data-testid":"changes-panel",children:[e&&t.jsxs("div",{className:"gm-changes-header",children:[t.jsxs("span",{className:"gm-branch-indicator",children:[t.jsx(Vs,{size:14}),e.branch]}),e.isDirty&&t.jsx("span",{className:"gm-dirty-badge",children:"Modified"})]}),t.jsxs("div",{className:"gm-changes-split",children:[t.jsxs("div",{className:"gm-changes-lists",children:[t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Unstaged Changes (",s.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[y.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>o(y.map(_=>_.file)),title:"Stage selected",children:[t.jsx(on,{size:12})," Stage (",y.length,")"]}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>c(y.map(_=>_.file)),title:"Discard selected",children:t.jsx(wr,{size:12})})]}),s.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>o(s.map(_=>_.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(_=>{const S=d?.file===_.file&&d.staged===!1;return t.jsxs("div",{className:`gm-file-item${S?" active":""}`,onClick:()=>u(_.file,!1),role:"button",tabIndex:0,onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),u(_.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:w=>w.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`unstaged:${_.file}`),onChange:()=>r(`unstaged:${_.file}`)})}),t.jsx(wh,{status:_.status}),t.jsx("span",{className:"gm-file-name",title:_.file,children:t.jsx("bdo",{dir:"ltr",children:_.file})}),t.jsx(Nh,{status:_.status}),t.jsx("button",{className:"gm-icon-btn",onClick:w=>{w.stopPropagation(),o([_.file])},title:"Stage file",children:t.jsx(on,{size:12})})]},`unstaged:${_.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:[k.length>0&&t.jsxs("button",{className:"btn btn-sm",onClick:()=>l(k.map(_=>_.file)),title:"Unstage selected",children:["Unstage (",k.length,")"]}),n.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(n.map(_=>_.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(_=>{const S=d?.file===_.file&&d.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${S?" active":""}`,onClick:()=>u(_.file,!0),role:"button",tabIndex:0,onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),u(_.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:w=>w.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`staged:${_.file}`),onChange:()=>r(`staged:${_.file}`)})}),t.jsx(wh,{status:_.status}),t.jsx("span",{className:"gm-file-name",title:_.file,children:t.jsx("bdo",{dir:"ltr",children:_.file})}),t.jsx(Nh,{status:_.status}),t.jsx("button",{className:"gm-icon-btn",onClick:w=>{w.stopPropagation(),l([_.file])},title:"Unstage file",children:t.jsx(Wt,{size:12})})]},`staged:${_.file}`)})})]})]}),t.jsx("div",{className:"gm-changes-diff",children:d||h||m||f?t.jsxs("div",{className:"gm-diff-section",children:[d&&t.jsxs("div",{className:"gm-diff-target",children:[t.jsx(Nc,{size:14}),t.jsxs("span",{children:[d.staged?"Staged":"Unstaged"," diff: "]}),t.jsx("code",{children:d.file})]}),h&&t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(ot,{size:16,className:"spin"}),"Loading diff..."]}),f&&!h&&t.jsx("div",{className:"gm-diff-error",children:f}),m&&!h&&t.jsxs("div",{className:"gm-diff-viewer",children:[m.stat&&t.jsx("pre",{className:"gm-diff-stat",children:m.stat}),t.jsx("pre",{className:"gm-diff-patch",children:m.patch})]})]}):t.jsxs("div",{className:"gm-diff-empty",children:[t.jsx(Nc,{size:20}),t.jsx("span",{children:"Select a file to view its diff"})]})})]}),t.jsxs("form",{className:"gm-commit-form",onSubmit:b,children:[t.jsx("textarea",{className:"gm-commit-input",placeholder:"Commit message...",value:p,onChange:_=>g(_.target.value),rows:3,disabled:x}),t.jsxs("div",{className:"gm-commit-actions",children:[t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:x||!p.trim()||n.length===0,title:n.length===0?"No staged changes to commit":"Commit staged changes",children:[x?t.jsx(ot,{size:14,className:"spin"}):t.jsx(Li,{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 ET({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(ki,{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:ya(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(Oi,{size:12})})}),i===m.hash&&t.jsx("div",{className:"gm-commit-diff",children:o?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(ot,{size:16,className:"spin"}),"Loading diff..."]}):r?t.jsxs(t.Fragment,{children:[r.stat&&t.jsx("pre",{className:"gm-diff-stat",children:r.stat}),t.jsx("pre",{className:"gm-diff-patch",children:r.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]})]},m.hash))}),u&&t.jsx("button",{className:"gm-load-more",onClick:c,children:"Load more commits"})]})}function _T({branches:e,branchSearch:n,setBranchSearch:s,newBranchName:i,setNewBranchName:r,branchBase:o,setBranchBase:l,onCreateBranch:c,onCheckoutBranch:u,onDeleteBranch:d,loading:m,allBranches:h,selectedBranch:f,branchCommits:p,loadingBranchCommits:g,expandedBranchCommit:b,branchCommitDiff:v,loadingBranchCommitDiff:x,onSelectBranch:y,onBranchCommitClick:k,onCloseBranchDetails:_}){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(ki,{size:14}),t.jsx("input",{type:"text",placeholder:"Filter branches...",value:n,onChange:S=>s(S.target.value)})]})]}),t.jsxs("form",{className:"gm-create-form",onSubmit:c,children:[t.jsx("input",{type:"text",placeholder:"New branch name",value:i,onChange:S=>r(S.target.value),disabled:m}),t.jsxs("select",{value:o,onChange:S=>l(S.target.value),disabled:m,className:"gm-branch-select",children:[t.jsx("option",{value:"",children:"Base: HEAD"}),h.map(S=>t.jsx("option",{value:S.name,children:S.name},S.name))]}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:m||!i.trim(),children:[t.jsx(on,{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(S=>t.jsxs("div",{children:[t.jsxs("div",{className:`gm-branch-item${S.isCurrent?" current":""}${f===S.name?" selected":""}`,onClick:()=>y(S.name),children:[t.jsxs("div",{className:"gm-branch-info",children:[t.jsxs("span",{className:"gm-branch-name",children:[S.isCurrent&&t.jsx(Hn,{size:14,className:"gm-current-icon"}),S.name]}),S.remote&&t.jsxs("span",{className:"gm-branch-remote",children:["→ ",S.remote]}),S.lastCommitDate&&t.jsx("span",{className:"gm-branch-date",children:ya(S.lastCommitDate)})]}),t.jsx("div",{className:"gm-branch-actions",children:!S.isCurrent&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:w=>{w.stopPropagation(),u(S.name)},disabled:m,title:"Checkout",children:t.jsx(Vs,{size:14})}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:w=>{w.stopPropagation(),d(S.name)},disabled:m,title:"Delete",children:t.jsx(rn,{size:14})})]})})]}),f===S.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(Nr,{size:14}),"Commits on ",S.name]}),t.jsx("button",{className:"gm-icon-btn",onClick:_,title:"Close","data-testid":"close-branch-details",children:t.jsx(Wt,{size:14})})]}),g?t.jsxs("div",{className:"gm-branch-details-loading",children:[t.jsx(ot,{size:16,className:"spin"}),"Loading commits..."]}):p.length===0?t.jsx("div",{className:"gm-empty",children:"No commits found"}):t.jsx("div",{className:"gm-branch-commits-list",children:p.map(w=>t.jsxs("div",{className:"gm-branch-commit",children:[t.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>k(w.hash),"data-testid":`branch-commit-${w.shortHash}`,children:[t.jsx("span",{className:"gm-commit-hash",children:w.shortHash}),t.jsx("span",{className:"gm-commit-message",title:w.message,children:w.message}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:w.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:ya(w.date)}),w.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),b===w.hash&&t.jsx("div",{className:"gm-commit-diff",children:x?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(ot,{size:16,className:"spin"}),"Loading diff..."]}):v?t.jsxs(t.Fragment,{children:[v.stat&&t.jsx("pre",{className:"gm-diff-stat",children:v.stat}),t.jsx("pre",{className:"gm-diff-patch",children:v.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},w.hash))})]})]},S.name))})]})}function MT({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:ud(n.path)||n.path})]}),t.jsxs("div",{className:"gm-worktree-detail",children:[n.branch&&t.jsxs("span",{className:"gm-worktree-branch",children:[t.jsx(Vs,{size:12}),n.branch]}),n.taskId&&t.jsx("span",{className:"gm-worktree-task",children:n.taskId})]})]})},n.path))})]})}function AT({stashes:e,stashMessage:n,setStashMessage:s,onCreateStash:i,onApplyStash:r,onDropStash:o,stashLoading:l}){return t.jsxs("div",{className:"gm-panel","data-testid":"stashes-panel",children:[t.jsx("div",{className:"gm-panel-header",children:t.jsx("h4",{children:"Stashes"})}),t.jsxs("form",{className:"gm-create-form",onSubmit:i,children:[t.jsx("input",{type:"text",placeholder:"Stash message (optional)",value:n,onChange:c=>s(c.target.value),disabled:l!==null}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:l!==null,children:[l==="create"?t.jsx(ot,{size:14,className:"spin"}):t.jsx(zo,{size:14}),"Stash"]})]}),t.jsx("div",{className:"gm-stash-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:"No stashes"}):e.map(c=>t.jsxs("div",{className:"gm-stash-item",children:[t.jsxs("div",{className:"gm-stash-info",children:[t.jsxs("span",{className:"gm-stash-ref",children:["stash@",`{${c.index}}`]}),t.jsx("span",{className:"gm-stash-message",children:c.message}),t.jsxs("div",{className:"gm-stash-meta",children:[c.branch&&t.jsxs("span",{className:"gm-stash-branch",children:[t.jsx(Vs,{size:12}),c.branch]}),t.jsx("span",{children:ya(c.date)})]})]}),t.jsxs("div",{className:"gm-stash-actions",children:[t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>r(c.index,!1),disabled:l!==null,title:"Apply stash (keep)",children:l===`apply-${c.index}`?t.jsx(ot,{size:14,className:"spin"}):"Apply"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>r(c.index,!0),disabled:l!==null,title:"Pop stash (apply and drop)",children:"Pop"}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>o(c.index),disabled:l!==null,title:"Drop stash",children:l===`drop-${c.index}`?t.jsx(ot,{size:14,className:"spin"}):t.jsx(rn,{size:14})})]})]},c.index))})]})}function RT({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:i,onPull:r,onPush:o,addToast:l,projectId:c,copyToClipboard:u}){const d=X=>{try{return new URL(X).hostname}catch{return X.replace(/^git@/,"").split(":")[0]||X}},[m,h]=a.useState([]),[f,p]=a.useState(!1),[g,b]=a.useState(null),[v,x]=a.useState(""),[y,k]=a.useState(""),[_,S]=a.useState(null),[w,M]=a.useState(""),[N,D]=a.useState(""),[E,T]=a.useState(!1),[U,K]=a.useState([]),[$,R]=a.useState(!1),[z,B]=a.useState(null),[J,Q]=a.useState([]),[C,L]=a.useState(!1),[P,j]=a.useState(null),O=m.find(X=>X.name===z),[H,ge]=a.useState(null),[be,se]=a.useState(null),[me,F]=a.useState(!1),[de,ne]=a.useState(null),[xe,oe]=a.useState(null),[he,ae]=a.useState(!1);a.useEffect(()=>{je()},[]),a.useEffect(()=>{e&&e.ahead>0?Ae():e&&e.ahead===0&&K([])},[e?.ahead]),a.useEffect(()=>{m.length>0&&!z&&B(m[0].name)},[m]),a.useEffect(()=>{z?Oe(z):(Q([]),j(null))},[z]),a.useEffect(()=>{z&&!m.find(X=>X.name===z)&&B(m.length>0?m[0].name:null)},[m,z]);const je=async()=>{p(!0);try{const X=await Cy(c);h(X)}catch(X){l(ye(X)||"Failed to load remotes","error")}finally{p(!1)}},Ae=async()=>{R(!0);try{const X=await Dy(c);K(X)}catch{K([])}finally{R(!1)}},Oe=async X=>{L(!0),j(null);try{const Te=await Ly(X,void 0,10,c);Q(Te)}catch(Te){j(ye(Te)||"Failed to load remote commits"),Q([])}finally{L(!1)}},Qe=Ws(),Xe=async X=>{if(X.preventDefault(),!(!v.trim()||!y.trim())){b("add");try{await Ey(v.trim(),y.trim(),c),l(`Remote '${v}' added successfully`,"success"),x(""),k(""),T(!1),await je()}catch(Te){l(ye(Te)||"Failed to add remote","error")}finally{b(null)}}},Ye=async X=>{if(await Qe.confirm({title:"Remove Remote",message:`Are you sure you want to remove remote '${X}'?`,danger:!0})){b(`remove-${X}`);try{await _y(X,c),l(`Remote '${X}' removed`,"success"),await je()}catch(Le){l(ye(Le)||"Failed to remove remote","error")}finally{b(null)}}},it=async X=>{if(N.trim()){b(`rename-${X}`);try{await My(X,N.trim(),c),l(`Remote renamed to '${N.trim()}'`,"success"),S(null),D(""),await je()}catch(Te){l(ye(Te)||"Failed to rename remote","error")}finally{b(null)}}},Be=async X=>{if(w.trim()){b(`url-${X}`);try{await Ay(X,w.trim(),c),l("Remote URL updated","success"),S(null),M(""),await je()}catch(Te){l(ye(Te)||"Failed to update remote URL","error")}finally{b(null)}}},Ge=a.useCallback(async(X,Te)=>{if(Te==="ahead"){if(H===X){ge(null),se(null);return}ge(X),se(null),F(!0);try{const Le=await No(X);se(Le)}catch{se(null)}finally{F(!1)}}else{if(de===X){ne(null),oe(null);return}ne(X),oe(null),ae(!0);try{const Le=await No(X);oe(Le)}catch{oe(null)}finally{ae(!1)}}},[H,de]),re=X=>{S(`url-${X.name}`),M(X.pushUrl||X.fetchUrl)},ke=X=>{S(`name-${X.name}`),D(X.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(!E),disabled:g!==null,title:E?"Cancel":"Add Remote",children:E?t.jsx(Wt,{size:14}):t.jsx(on,{size:14})})]}),E&&t.jsxs("form",{className:"gm-remote-form",onSubmit:Xe,children:[t.jsx("input",{type:"text",placeholder:"Remote name",value:v,onChange:X=>x(X.target.value),disabled:g==="add",className:"gm-input"}),t.jsx("input",{type:"text",placeholder:"Repository URL",value:y,onChange:X=>k(X.target.value),disabled:g==="add",className:"gm-input gm-input-url"}),t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:!v.trim()||!y.trim()||g==="add",children:[g==="add"?t.jsx(ot,{size:12,className:"spin"}):t.jsx(on,{size:12}),"Add"]})]}),f?t.jsxs("div",{className:"gm-loading",children:[t.jsx(ot,{size:16,className:"spin"}),"Loading..."]}):m.length===0?t.jsx("div",{className:"gm-empty",children:"No remotes"}):m.map(X=>t.jsxs("div",{className:`gm-remote-selector-item${z===X.name?" selected":""}`,onClick:()=>B(X.name),role:"button",tabIndex:0,children:[t.jsxs("div",{className:"gm-remote-selector-info",children:[t.jsxs("span",{className:"gm-remote-selector-name",children:[X.name,X.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),t.jsx("span",{className:"gm-remote-selector-host",children:d(X.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:Te=>{Te.stopPropagation(),Ye(X.name)},disabled:g!==null,title:"Remove remote",children:t.jsx(rn,{size:14})})]},X.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[z&&O?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:z}),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(zi,{size:14}),e.ahead," to push"]}),e.behind>0&&t.jsxs("div",{className:"gm-remote-indicator behind",children:[t.jsx(jr,{size:14}),e.behind," to pull"]})]})]}),t.jsxs("div",{className:"gm-remote-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:i,disabled:n!==null||f,children:[n==="fetch"?t.jsx(ot,{size:14,className:"spin"}):t.jsx($n,{size:14}),"Fetch"]}),t.jsxs("button",{className:"btn btn-primary",onClick:r,disabled:n!==null||f,children:[n==="pull"?t.jsx(ot,{size:14,className:"spin"}):t.jsx(ks,{size:14}),"Pull"]}),t.jsxs("button",{className:"btn btn-primary",onClick:o,disabled:n!==null||f,children:[n==="push"?t.jsx(ot,{size:14,className:"spin"}):t.jsx(zi,{size:14}),"Push"]})]})]}),t.jsxs("div",{className:"gm-remote-detail-card","data-testid":"remote-detail-card",children:[t.jsxs("div",{className:"gm-remote-detail-urls",children:[t.jsxs("div",{className:"gm-remote-detail-url-row",children:[t.jsx("span",{className:"gm-url-label",children:"Fetch:"}),_===`url-${z}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:w,onChange:X=>M(X.target.value),className:"gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Be(z),disabled:g===`url-${z}`,children:g===`url-${z}`?t.jsx(ot,{size:12,className:"spin"}):t.jsx(Hn,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{S(null),M("")},title:"Cancel",children:t.jsx(Wt,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:O.fetchUrl,children:O.fetchUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>u(O.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:t.jsx(Oi,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>re(O),disabled:g!==null,title:"Edit remote URL",children:t.jsx(cs,{size:14})})]})]}),O.pushUrl&&O.pushUrl!==O.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:O.pushUrl,children:O.pushUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>u(O.pushUrl,"push URL"),title:"Copy push URL",children:t.jsx(Oi,{size:14})})]})]}),t.jsx("div",{className:"gm-remote-detail-name-row",children:_===`name-${z}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:N,onChange:X=>D(X.target.value),className:"gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>it(z),disabled:g===`rename-${z}`,children:g===`rename-${z}`?t.jsx(ot,{size:12,className:"spin"}):t.jsx(Hn,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{S(null),D("")},title:"Cancel",children:t.jsx(Wt,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>ke(O),disabled:g!==null,title:"Edit remote name",children:t.jsx(cs,{size:14})})})]}),e&&e.ahead>0&&t.jsxs("div",{className:"gm-remote-section","data-testid":"commits-to-push",children:[t.jsx("div",{className:"gm-section-subheader",children:t.jsxs("h5",{children:[t.jsx(zi,{size:14}),"Commits to Push (",e.ahead,")"]})}),$?t.jsxs("div",{className:"gm-loading",children:[t.jsx(ot,{size:14,className:"spin"}),"Loading..."]}):U.length>0?t.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:U.map(X=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>Ge(X.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:X.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:X.message,children:X.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:X.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:ya(X.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:H===X.hash?t.jsx(Xt,{size:14}):t.jsx(vn,{size:14})})]}),H===X.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:me?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(ot,{size:16,className:"spin"}),"Loading diff..."]}):be?t.jsxs(t.Fragment,{children:[X.message&&t.jsx("div",{className:"gm-commit-message-full",children:X.message}),be.stat&&t.jsx("pre",{className:"gm-diff-stat",children:be.stat}),t.jsx("pre",{className:"gm-diff-patch",children:be.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},X.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(ip,{size:14}),"Recent commits on ",z]})}),C?t.jsxs("div",{className:"gm-loading",children:[t.jsx(ot,{size:14,className:"spin"}),"Loading commits..."]}):P?t.jsxs("div",{className:"gm-error",children:[t.jsx(us,{size:14}),P]}):J.length===0?t.jsxs("div",{className:"gm-empty",children:["No commits found on ",z,". Try fetching first."]}):t.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:J.map(X=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>Ge(X.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:X.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:X.message,children:X.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:X.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:ya(X.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:de===X.hash?t.jsx(Xt,{size:14}):t.jsx(vn,{size:14})})]}),de===X.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:he?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(ot,{size:16,className:"spin"}),"Loading diff..."]}):xe?t.jsxs(t.Fragment,{children:[X.message&&t.jsx("div",{className:"gm-commit-message-full",children:X.message}),xe.stat&&t.jsx("pre",{className:"gm-diff-stat",children:xe.stat}),t.jsx("pre",{className:"gm-diff-patch",children:xe.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},X.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 Xa={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function TT(e,n){return e&&n?`${e}/${n}`:""}function PT(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 IT(e){switch(e){case"file-text":return Ui;case"check-circle":return yn;case"shield":return Qx;case"zap":return Gn;case"eye":return Ca;case"globe":return Uo;case"layout-grid":return Hi;default:return yn}}function $T(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 DT({isOpen:e,onClose:n,addToast:s,projectId:i}){const[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState(!0),[m,h]=a.useState(!0),[f,p]=a.useState("my-steps"),[g,b]=a.useState(null),[v,x]=a.useState(!1),[y,k]=a.useState(Xa),[_,S]=a.useState(!1),[w,M]=a.useState(!1),[N,D]=a.useState(null),[E,T]=a.useState(null),[U,K]=a.useState({}),[$,R]=a.useState([]),z=a.useRef(null);oi(z,e,"fusion:workflow-steps-modal-size");const B=a.useCallback(async()=>{try{d(!0);const F=await Ko(i);o(F)}catch(F){s(ye(F)||"Failed to load workflow steps","error")}finally{d(!1)}},[s,i]),J=a.useCallback(async()=>{try{const F=await br(i);K(F||{})}catch{}},[i]),Q=a.useCallback(async()=>{try{const F=await ms();R(F.models||[])}catch{}},[]),C=a.useCallback(async()=>{try{h(!0);const F=await Pj();c(F.templates)}catch(F){s(ye(F)||"Failed to load templates","error")}finally{h(!1)}},[s]);a.useEffect(()=>{e&&(B(),C(),J(),Q())},[e,B,C,J,Q]);const L=a.useCallback(()=>{x(!0),b(null),k(Xa)},[]),P=a.useCallback(F=>{b(F.id),x(!1),k({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||""})},[]),j=a.useCallback(()=>{b(null),x(!1),k(Xa)},[]),O=a.useCallback(async()=>{if(!y.name.trim()||!y.description.trim()){s("Name and description are required","error");return}S(!0);try{const F=y.mode==="prompt"&&y.modelProvider&&y.modelId?{modelProvider:y.modelProvider,modelId:y.modelId}:y.mode==="prompt"?{modelProvider:void 0,modelId:void 0}:{};if(v){const de={name:y.name.trim(),description:y.description.trim(),mode:y.mode,phase:y.phase,prompt:y.mode==="prompt"&&y.prompt.trim()||void 0,scriptName:y.mode==="script"?y.scriptName.trim():void 0,enabled:y.enabled,defaultOn:y.defaultOn||void 0,...F};await su(de,i),s("Workflow step created","success")}else g&&(await Aj(g,{name:y.name.trim(),description:y.description.trim(),mode:y.mode,phase:y.phase,prompt:y.mode==="prompt"?y.prompt:"",scriptName:y.mode==="script"?y.scriptName.trim():void 0,enabled:y.enabled,defaultOn:y.defaultOn,...F},i),s("Workflow step updated","success"));x(!1),b(null),k(Xa),await B()}catch(F){s(ye(F)||"Failed to save workflow step","error")}finally{S(!1)}},[y,v,g,s,B]),H=a.useCallback(async F=>{try{await Rj(F,i),s("Workflow step deleted","success"),D(null),g===F&&(b(null),k(Xa)),await B()}catch(de){s(ye(de)||"Failed to delete workflow step","error")}},[g,s,B]),ge=a.useCallback(async()=>{if(!(!g&&!v)&&y.mode==="prompt"){if(v){if(!y.name.trim()||!y.description.trim()){s("Name and description are required before refining","error");return}S(!0);try{const F=y.modelProvider&&y.modelId?{modelProvider:y.modelProvider,modelId:y.modelId}:{},de={name:y.name.trim(),description:y.description.trim(),mode:"prompt",prompt:y.prompt.trim()||void 0,enabled:y.enabled,defaultOn:y.defaultOn||void 0,...F},ne=await su(de,i);x(!1),b(ne.id),M(!0);const xe=await iu(ne.id,i);k(oe=>({...oe,prompt:xe.prompt})),s("Prompt refined with AI","success"),await B()}catch(F){s(ye(F)||"Failed to refine prompt","error")}finally{S(!1),M(!1)}return}if(g){M(!0);try{const F=await iu(g,i);k(de=>({...de,prompt:F.prompt})),s("Prompt refined with AI","success"),await B()}catch(F){s(ye(F)||"Failed to refine prompt","error")}finally{M(!1)}}}},[g,v,y,s,B]),be=a.useCallback(async F=>{T(F.id);try{await Ij(F.id,i),s(`Added ${F.name} workflow step`,"success"),await B(),p("my-steps")}catch(de){const ne=ye(de);ne?.includes("already exists")?s(`A workflow step named '${F.name}' already exists`,"error"):s(ne||"Failed to add workflow step from template","error")}finally{T(null)}},[s,B]),se=Ei(n);if(!e)return null;const me=v||g!==null;return t.jsx("div",{className:"modal-overlay open",...se,"data-testid":"workflow-step-manager",children:t.jsxs("div",{ref:z,className:"modal workflow-step-manager-modal",role:"dialog","aria-modal":"true","aria-label":"Workflow Steps",children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h2",{children:"Workflow Steps"}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]}),t.jsx("div",{className:"wfm-body",children:u?t.jsx("div",{className:"wfm-loading",children:"Loading..."}):t.jsxs(t.Fragment,{children:[!me&&t.jsxs("div",{className:"wfm-tab-row",children:[t.jsxs("button",{className:`btn ${f==="my-steps"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>p("my-steps"),"data-testid":"tab-my-steps",children:[t.jsx(Wg,{size:14}),"My Workflow Steps (",r.length,")"]}),t.jsxs("button",{className:`btn ${f==="templates"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>p("templates"),"data-testid":"tab-templates",children:[t.jsx(Hi,{size:14}),"Templates (",l.length,")"]})]}),f==="my-steps"&&!me&&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:()=>P(F),title:"Edit","aria-label":`Edit ${F.name}`,children:t.jsx(cs,{size:14})}),N===F.id?t.jsxs("div",{className:"wfm-delete-confirm",children:[t.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>H(F.id),title:"Confirm delete","aria-label":`Confirm delete ${F.name}`,children:t.jsx(Hn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>D(null),title:"Cancel delete","aria-label":"Cancel delete",children:t.jsx(Wt,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>D(F.id),title:"Delete","aria-label":`Delete ${F.name}`,children:t.jsx(rn,{size:14})})]})]})},F.id))})]}),f==="templates"&&!me&&t.jsx(t.Fragment,{children:m?t.jsxs("div",{className:"wfm-loading",children:[t.jsx(ot,{size:24,className:"spin wfm-spinner"}),"Loading templates..."]}):l.length===0?t.jsx("div",{className:"wfm-empty","data-testid":"no-templates-state",children:"No templates available."}):t.jsx("div",{className:"wfm-template-list",children:l.map(F=>{const de=IT(F.icon),ne=$T(F.category),xe=E===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(de,{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:ne,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:()=>be(F),disabled:xe,"data-testid":`add-template-${F.id}`,children:xe?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(on,{size:12}),"Add"]})})]})]})},F.id)})})}),me&&t.jsxs("div",{className:"wfm-form","data-testid":"workflow-step-form",children:[t.jsx("h3",{className:"wfm-form-title",children:v?"New Workflow Step":"Edit Workflow Step"}),t.jsxs("div",{className:"wfm-form-fields",children:[t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Name"}),t.jsx("input",{type:"text",value:y.name,onChange:F=>k(de=>({...de,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:y.description,onChange:F=>k(de=>({...de,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 ${y.mode==="prompt"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>k(F=>({...F,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[t.jsx(wi,{size:14}),"AI Prompt"]}),t.jsxs("button",{className:`btn ${y.mode==="script"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>k(F=>({...F,mode:"script",prompt:"",modelProvider:"",modelId:""})),"data-testid":"mode-script",children:[t.jsx(mi,{size:14}),"Run Script"]})]})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Execution Phase"}),t.jsxs("div",{className:"wfm-mode-selector","data-testid":"workflow-step-phase-selector",children:[t.jsx("button",{className:`btn ${y.phase==="pre-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>k(F=>({...F,phase:"pre-merge"})),"data-testid":"phase-pre-merge",children:"Pre-merge"}),t.jsx("button",{className:`btn ${y.phase==="post-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>k(F=>({...F,phase:"post-merge"})),"data-testid":"phase-post-merge",children:"Post-merge"})]}),t.jsx("div",{className:"wfm-field-hint",children:y.phase==="pre-merge"?"Runs before merge — can block merge on failure":"Runs after merge success — failures are logged but do not block"})]}),y.mode==="prompt"&&t.jsxs("div",{className:"wfm-field",children:[t.jsxs("div",{className:"wfm-prompt-header",children:[t.jsx("label",{children:"Agent Prompt"}),t.jsxs("button",{className:"btn-icon wfm-refine-btn",onClick:ge,disabled:!y.description.trim()||w,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[w?t.jsx(ot,{size:12,className:"spin"}):t.jsx(rs,{size:12}),t.jsx("span",{children:"Refine with AI"})]})]}),t.jsx("textarea",{value:y.prompt,onChange:F=>k(de=>({...de,prompt:F.target.value})),placeholder:"Leave empty to use AI refinement",rows:6,className:"wfm-prompt-textarea","data-testid":"workflow-step-prompt"})]}),y.mode==="prompt"&&t.jsxs("div",{className:"wfm-field","data-testid":"workflow-step-model-field",children:[t.jsxs("div",{className:"wfm-model-header",children:[t.jsx("label",{children:"Model Override"}),y.modelProvider&&y.modelId&&t.jsxs("button",{type:"button",className:"btn-icon wfm-model-clear-btn",onClick:()=>k(F=>({...F,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[t.jsx(Wt,{size:12}),t.jsx("span",{children:"Use default"})]})]}),t.jsx("span",{className:"wfm-model-hint",children:y.modelProvider&&y.modelId?`Using ${y.modelProvider}/${y.modelId}`:"Using global default model"}),t.jsx("div",{"data-testid":"workflow-step-model-select",children:t.jsx(Yn,{models:$,value:TT(y.modelProvider,y.modelId),onChange:F=>{const de=PT(F);k(ne=>({...ne,modelProvider:de.provider,modelId:de.modelId}))},placeholder:"Select a model override…",label:"Model override for this workflow step"})})]}),y.mode==="script"&&t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Script"}),Object.keys(U).length===0?t.jsx("div",{className:"wfm-no-scripts","data-testid":"no-scripts-message",children:"No scripts configured. Add scripts in Settings → Scripts first."}):t.jsxs("select",{value:y.scriptName,onChange:F=>k(de=>({...de,scriptName:F.target.value})),"data-testid":"workflow-step-script-select",children:[t.jsx("option",{value:"",children:"Select a script…"}),Object.entries(U).map(([F,de])=>t.jsxs("option",{value:F,children:[F," (",de,")"]},F))]})]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:y.enabled,onChange:F=>k(de=>({...de,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:y.defaultOn,onChange:F=>k(de=>({...de,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:j,disabled:_,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:O,disabled:_||!y.name.trim()||!y.description.trim()||y.mode==="script"&&!y.scriptName.trim(),"data-testid":"save-workflow-step",children:_?"Saving...":v?"Create":"Save"})]})]})]})]})}),!me&&t.jsx("div",{className:"wfm-footer",children:t.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:L,"data-testid":"add-workflow-step",children:[t.jsx(on,{size:14}),"Add Workflow Step"]})})]})})}const LT=36e5,zT=3e5,hc=[{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 FT(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 OT(e){return typeof e!="number"||!Number.isFinite(e)?LT:Math.max(zT,Math.round(e))}function NL(e){if(hc.some(s=>s.value===e))return[...hc];const n={value:e,label:`${FT(e)} (custom)`};return[...hc,n].sort((s,i)=>s.value-i.value)}const UT=4,BT=5*6e4;function HT(e){const n=OT(e?.heartbeatIntervalMs);return Math.max(n*UT,BT)}function qT(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 VT(e){const{state:n,lastHeartbeatAt:s,lastError:i,pauseReason:r,runtimeConfig:o}=e,l=qT(e),c=l||o?.enabled!==!1;if(n==="terminated")return{label:"Terminated",icon:t.jsx(js,{size:14}),color:"var(--state-error-text)",stateDerived:!0};if(n==="error")return{label:i??"Error",icon:t.jsx(Is,{size:14}),color:"var(--state-error-text)",stateDerived:!i};if(n==="paused")return{label:r?`Paused: ${r}`:"Paused",icon:t.jsx(Hs,{size:14}),color:"var(--state-paused-text)",stateDerived:!r};if(n==="running"||l&&n==="active")return{label:"Running",icon:t.jsx(Is,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!c)return{label:"Heartbeat Disabled",icon:t.jsx(Hs,{size:14}),color:"var(--state-paused-text)",stateDerived:!1};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:t.jsx(Nn,{size:14}),color:"var(--text-secondary)",stateDerived:!1};const u=new Date(s).getTime(),d=Date.now()-u,m=HT(o);return d>m?{label:"Unresponsive",icon:t.jsx(Is,{size:14}),color:"var(--state-error-text)",stateDerived:!1}:{label:"Healthy",icon:t.jsx(nx,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}const Za=[{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 WT({isOpen:e,onClose:n,addToast:s,projectId:i}){const[r,o]=a.useState([]),[l,c]=a.useState(!1),[u,d]=a.useState(!1),[m,h]=a.useState(""),[f,p]=a.useState("custom"),[g,b]=a.useState("all"),[v,x]=a.useState(()=>{if(typeof window>"u")return"list";const P=Qn("fn-agent-view",i);return P==="board"||P==="list"?P:"list"});a.useEffect(()=>{const P=Qn("fn-agent-view",i);if(P==="board"||P==="list"){x(P);return}x("list")},[i]),a.useEffect(()=>{bs("fn-agent-view",v,i)},[i,v]);const[y,k]=a.useState(null),_=a.useRef(null),[S,w]=a.useState(new Set),[M,N]=a.useState(new Map),{confirm:D}=Ws(),E=a.useMemo(()=>M.size===0?r:r.map(P=>{const j=M.get(P.id);return j?{...P,state:j}:P}),[r,M]),T=a.useMemo(()=>g==="all"?E.filter(P=>P.state!=="terminated"):E,[E,g]),U=a.useCallback(async()=>{c(!0);try{const j=await Ea(g!=="all"?{state:g}:void 0,i);o(j)}catch(P){s(`Failed to load agents: ${ye(P)}`,"error")}finally{c(!1)}},[g,s,i]);a.useEffect(()=>{e&&U()},[e,U]),a.useEffect(()=>{if(!e)return;const P=setInterval(()=>{U()},3e4);return()=>{clearInterval(P)}},[e,U]);const K=async()=>{if(m.trim())try{await Hj({name:m.trim(),role:f},i),s(`Agent "${m}" created`,"success"),h(""),d(!1),U()}catch(P){s(`Failed to create agent: ${ye(P)}`,"error")}},$=async(P,j)=>{if(!S.has(P)){w(O=>new Set(O).add(P)),N(O=>{const H=new Map(O);return H.set(P,j),H});try{await Vj(P,j,i),s(`Agent state updated to ${j}`,"success"),await U(),N(O=>{const H=new Map(O);return H.delete(P),H})}catch(O){N(H=>{const ge=new Map(H);return ge.delete(P),ge}),s(`Failed to update state: ${ye(O)}`,"error")}finally{w(O=>{const H=new Set(O);return H.delete(P),H})}}},R=async(P,j)=>{if(await D({title:"Delete Agent",message:`Delete agent "${j}"? This cannot be undone.`,danger:!0}))try{await Wj(P,i),s(`Agent "${j}" deleted`,"success"),U()}catch(H){s(`Failed to delete agent: ${ye(H)}`,"error")}},z=async(P,j)=>{const O=r.find(H=>H.id===P);if(O){if(O.role===j){k(null);return}try{await qj(P,{role:j},i),s(`Agent role updated to ${Za.find(H=>H.value===j)?.label??j}`,"success"),k(null),U()}catch(H){s(`Failed to update role: ${ye(H)}`,"error")}}},B=(P,j)=>{P.key==="Escape"&&k(null)},J=P=>Za.find(j=>j.value===P)?.label??P,Q=P=>Za.find(j=>j.value===P)?.icon??"◆",C=P=>VT(P),L=P=>P.color==="var(--state-active-text)"?"active":P.color==="var(--state-paused-text)"?"paused":P.color==="var(--state-error-text)"?"error":"muted";return e?t.jsx("div",{className:"modal-overlay open",onClick:P=>P.target===P.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(Nn,{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(Hi,{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(Cc,{size:16})})]}),t.jsx("button",{className:"btn-icon",onClick:()=>void U(),title:"Refresh",disabled:l,children:t.jsx($n,{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(jo,{size:14}),t.jsxs("select",{className:"agent-state-filter-select",value:g,onChange:P=>b(P.target.value),"aria-label":"Filter agents by state",children:[t.jsx("option",{value:"all",children:"All States"}),t.jsx("option",{value:"idle",children:"Idle"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"running",children:"Running"}),t.jsx("option",{value:"paused",children:"Paused"}),t.jsx("option",{value:"error",children:"Error"}),t.jsx("option",{value:"terminated",children:"Terminated"})]})]}),t.jsxs("button",{className:"btn btn-task-create btn-sm",onClick:()=>d(!u),children:[t.jsx(on,{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:P=>h(P.target.value),onKeyDown:P=>P.key==="Enter"&&K(),className:"input",autoFocus:!0}),t.jsx("select",{className:"select",value:f,onChange:P=>p(P.target.value),children:Za.map(P=>t.jsxs("option",{value:P.value,children:[P.icon," ",P.label]},P.value))}),t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:()=>void K(),children:"Create"})]}),t.jsx("div",{className:v==="board"?"agent-board":"agent-list",children:T.length===0?t.jsxs("div",{className:"agent-empty",children:[t.jsx(Nn,{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"?T.map(P=>{const j=C(P),O=L(j);return t.jsxs("div",{className:"agent-board-card","data-state":P.state,children:[t.jsxs("div",{className:"agent-board-header",children:[t.jsx("span",{className:"agent-board-icon",children:Q(P.role)}),t.jsx("span",{className:"agent-board-badge","data-state":P.state,children:P.state}),t.jsx("span",{className:"agent-board-health","data-health":O,title:j.label,children:j.icon})]}),t.jsx("div",{className:"agent-board-name",title:P.name,children:P.name}),t.jsx("div",{className:"agent-board-id",children:P.id}),t.jsxs("div",{className:"agent-board-actions",children:[P.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void $(P.id,"active"),disabled:S.has(P.id),title:"Activate",children:t.jsx(Sn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void R(P.id,P.name),title:"Delete",children:t.jsx(rn,{size:14})})]}),P.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void $(P.id,"paused"),disabled:S.has(P.id),title:"Pause",children:t.jsx(Hs,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(P.id,"terminated"),disabled:S.has(P.id),title:"Stop",children:t.jsx(js,{size:14})})]}),P.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void $(P.id,"active"),disabled:S.has(P.id),title:"Resume",children:t.jsx(Sn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(P.id,"terminated"),disabled:S.has(P.id),title:"Stop",children:t.jsx(js,{size:14})})]}),P.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void $(P.id,"paused"),disabled:S.has(P.id),title:"Pause",children:t.jsx(Hs,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(P.id,"terminated"),disabled:S.has(P.id),title:"Stop",children:t.jsx(js,{size:14})})]}),P.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void $(P.id,"active"),disabled:S.has(P.id),title:"Retry",children:t.jsx(Sn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(P.id,"terminated"),disabled:S.has(P.id),title:"Stop",children:t.jsx(js,{size:14})})]}),P.state==="terminated"&&t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void R(P.id,P.name),title:"Delete",children:t.jsx(rn,{size:14})})]})]},P.id)}):T.map(P=>{const j=C(P),O=L(j);return t.jsxs("div",{className:"agent-card","data-state":P.state,children:[t.jsxs("div",{className:"agent-card-header",children:[t.jsxs("div",{className:"agent-info",children:[y===P.id?t.jsx("select",{ref:_,className:"select agent-role-select",value:P.role,onChange:H=>void z(P.id,H.target.value),onKeyDown:H=>B(H,P.id),onBlur:()=>k(null),autoFocus:!0,children:Za.map(H=>t.jsxs("option",{value:H.value,children:[H.icon," ",H.label]},H.value))}):t.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>k(P.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:H=>{(H.key==="Enter"||H.key===" ")&&k(P.id)},children:Q(P.role)}),t.jsxs("div",{className:"agent-meta",children:[t.jsx("span",{className:"agent-name",children:P.name}),t.jsx("span",{className:"agent-id text-secondary",children:P.id})]})]}),t.jsxs("div",{className:"agent-badges",children:[t.jsx("span",{className:"badge agent-list-state-badge","data-state":P.state,children:P.state}),t.jsxs("span",{className:"badge agent-list-health-badge","data-health":O,title:j.label,children:[j.icon,!j.stateDerived&&` ${j.label}`]}),t.jsx("span",{className:"badge text-secondary",children:J(P.role)})]})]}),t.jsxs("div",{className:"agent-card-body",children:[P.taskId&&t.jsxs("div",{className:"agent-task",children:[t.jsx("span",{className:"text-secondary",children:"Working on:"}),t.jsx("span",{className:"badge",children:P.taskId})]}),P.lastHeartbeatAt&&t.jsxs("div",{className:"agent-heartbeat",children:[t.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),t.jsx("span",{children:new Date(P.lastHeartbeatAt).toLocaleString()})]})]}),t.jsxs("div",{className:"agent-card-actions",children:[P.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void $(P.id,"active"),disabled:S.has(P.id),title:"Activate",children:[t.jsx(Sn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void R(P.id,P.name),title:"Delete",children:[t.jsx(rn,{size:14})," Delete"]})]}),P.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void $(P.id,"paused"),disabled:S.has(P.id),title:"Pause",children:[t.jsx(Hs,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(P.id,"terminated"),disabled:S.has(P.id),title:"Stop",children:[t.jsx(js,{size:14})," Stop"]})]}),P.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void $(P.id,"active"),disabled:S.has(P.id),title:"Resume",children:[t.jsx(Sn,{size:14})," Resume"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(P.id,"terminated"),disabled:S.has(P.id),title:"Stop",children:[t.jsx(js,{size:14})," Stop"]})]}),P.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void $(P.id,"paused"),disabled:S.has(P.id),title:"Pause",children:[t.jsx(Hs,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(P.id,"terminated"),disabled:S.has(P.id),title:"Stop",children:[t.jsx(js,{size:14})," Stop"]})]}),P.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void $(P.id,"active"),disabled:S.has(P.id),title:"Retry",children:[t.jsx(Sn,{size:14})," Retry"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(P.id,"terminated"),disabled:S.has(P.id),title:"Stop",children:[t.jsx(js,{size:14})," Stop"]})]}),P.state==="terminated"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm btn-task-create",onClick:()=>void $(P.id,"active"),disabled:S.has(P.id),title:"Start",children:[t.jsx(Sn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void R(P.id,P.name),title:"Delete",children:[t.jsx(rn,{size:14})," Delete"]})]})]})]},P.id)})})]})]})}):null}function KT({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 my();return d.current&&r(x),x}catch(x){return d.current&&u({kind:"error",message:x instanceof Error?x.message:String(x)}),null}},[]);a.useEffect(()=>{m()},[m]);const h=a.useCallback(async()=>{l("testing"),u(null),await m(),d.current&&l(null)},[m]),f=a.useCallback(async x=>{l(x?"enabling":"disabling"),u(null);try{const y=await hy(x);d.current&&u({kind:y.enabled?"enabled":"disabled",restartRequired:y.restartRequired}),n?.(y.enabled),await m()}catch(y){d.current&&u({kind:"error",message:y instanceof Error?y.message:String(y)})}finally{d.current&&l(null)}},[n,m]),p=i?.binary.available??!1,g=i?.enabled??e,b=t.jsxs("span",{className:"onboarding-provider-card__description",children:["Route AI calls through your locally-installed ",t.jsx("code",{children:"claude"})," CLI. Uses your existing Claude subscription / quota instead of an API key."]}),v=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:12,className:"animate-spin"}),"Testing…"]}):"Test"}),g?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void f(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void f(!0),disabled:o!==null||!p,title:p?void 0:"`claude` binary not detected on PATH — install Claude CLI first.",children:o==="enabling"?"Enabling…":"Enable"})]});return s?t.jsxs("div",{className:`auth-provider-card auth-provider-card--cli${e?" auth-provider-card--authenticated":""}`,"data-testid":"claude-cli-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(On,{provider:"claude-cli",size:"sm"}),t.jsx("strong",{children:"Anthropic — via Claude CLI"}),t.jsx(GT,{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(Sh,{status:i,authenticated:e}),c&&t.jsx(Ch,{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(On,{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(Sh,{status:i,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(Ch,{action:c})]})}function GT({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 Sh({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(ot,{size:10,className:"animate-spin"})," Probing local CLI…"]});const{binary:s,enabled:i,extension:r,ready:o}=e;return s.available?i?r&&r.status!=="ok"?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--warning",children:["⚠ Extension load failed: ",r.reason??r.status]}):o||n?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--connected",children:["✓ Connected",s.version?` — ${s.version}`:""]}):t.jsx("small",{className:"settings-muted",children:"Enabled. Validating…"}):t.jsxs("small",{className:"settings-muted",children:[t.jsx("code",{children:"claude"})," ",s.version?`(${s.version})`:""," detected",s.binaryPath?` at ${s.binaryPath}`:"",". Click Enable to route AI calls through it."]}):t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--error",children:["✗ ",s.reason??"`claude` not found on PATH"]})}function Ch({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 JT(e){const n="([A-Z0-9]{2,}(?:-[A-Z0-9]{2,})+|[A-Z0-9]{6,9})",s=new RegExp(`\\b(?:device\\s+code|your\\s+code|code)\\s*(?:is|:)?\\s*${n}\\b`,"i"),i=new RegExp(`\\b(?:enter|use)\\s+${n}\\b`,"i"),r=/\b([A-Z0-9]{2,}(?:-[A-Z0-9]{2,})+)\b/,o=e.match(s);if(o?.[1])return o[1];const l=e.match(i);if(l?.[1])return l[1];const c=e.match(r);return c?.[1]?c[1]:null}function pc({instructions:e,"data-testid":n}){const[s,i]=a.useState(!1),r=JT(e),o=a.useRef(null),l=a.useCallback(()=>{i(!0),setTimeout(()=>i(!1),2e3)},[]),c=a.useCallback(async()=>{const u=r??e;try{await navigator.clipboard.writeText(u),l()}catch{}},[r,e,l]);return a.useEffect(()=>{const u=o.current===null&&r!==null;if(o.current=r,!u)return;(async()=>{try{await navigator.clipboard.writeText(r),l()}catch{}})()},[r,l]),t.jsx("p",{className:"auth-login-instructions","data-testid":n,children:r?t.jsx(t.Fragment,{children:e.split(r).map((u,d,m)=>t.jsxs("span",{children:[u,d<m.length-1&&t.jsxs("span",{className:"device-code-wrapper",children:[t.jsx("code",{className:"device-code",children:r}),t.jsx("button",{className:"device-code-copy-btn",onClick:c,title:s?"Copied!":"Copy code","aria-label":s?"Copied to clipboard":"Copy device code",type:"button",children:s?t.jsx(Hn,{size:12}):t.jsx(Oi,{size:12})})]})]},d))}):e})}const YT=new Set(["anthropic","claude-cli","pi-claude-cli","openai","openai-codex","google","gemini","google-antigravity","antigravity","google-vertex","vertex","google-cloud-code","cloud-code","google-gemini-cli","google-generative-ai","ollama","github","github-copilot","openrouter","minimax","minimax-cn","zai","kimi","moonshot","kimi-coding","bedrock","amazon-bedrock","xai","grok","opencode","opencode-go","qwen","qwen-ai","qwen-coder","alibaba","tongyi","lmstudio","lm-studio","huggingface","hugging-face","hf","mistral","mistral-ai","azure","azure-openai","azure-openai-responses","fireworks","fireworks-ai","fireworksai","cerebras","groq","vercel","vercel-ai-gateway","hermes","hermes-agent","hermesagent","openclaw","open-claw","paperclip","paperclipai","paperclip-ai"]),QT=/^[a-z][a-z0-9-]*$/,Eh=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function _h(){return{id:"",name:"",reasoning:!1}}function XT({initialConfig:e,onSave:n,onCancel:s,saving:i=!1,error:r}){const o=!!e,[l,c]=a.useState(e?.id??""),[u,d]=a.useState(e?.name??""),[m,h]=a.useState(e?.baseUrl??""),[f,p]=a.useState(e?.api??"openai-completions"),[g,b]=a.useState(e?.apiKey??""),[v,x]=a.useState(e?.models?.length?e.models:[_h()]),[y,k]=a.useState(null),_=v.length>1,S=a.useMemo(()=>y??r??null,[y,r]);function w(E,T){x(U=>U.map((K,$)=>$===E?{...K,...T}:K))}function M(E){x(T=>T.length<=1?T:T.filter((U,K)=>K!==E))}function N(){if(!l.trim())return"Provider ID is required.";if(!QT.test(l.trim()))return"Provider ID must be kebab-case.";if(!o&&YT.has(l.trim()))return"Provider ID conflicts with a built-in provider.";if(!m.trim())return"Base URL is required.";try{const E=new URL(m.trim());if(E.protocol!=="http:"&&E.protocol!=="https:")return"Base URL must use http or https."}catch{return"Base URL must be a valid URL."}return Eh.includes(f)?v.length===0?"At least one model is required.":v.some(E=>!E.id?.trim())?"Each model must have a model ID.":null:"API type is required."}async function D(E){E.preventDefault();const T=N();k(T),!T&&await n({id:l.trim(),name:u.trim()||void 0,baseUrl:m.trim(),api:f,apiKey:g.trim()||void 0,models:v.map(U=>({id:U.id.trim(),name:U.name?.trim()||void 0,reasoning:!!U.reasoning,contextWindow:U.contextWindow,maxTokens:U.maxTokens}))})}return t.jsxs("form",{onSubmit:D,className:"custom-provider-form","aria-label":"custom-provider-form",children:[t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-id",children:"Provider ID"}),t.jsx("input",{id:"custom-provider-id",className:"input",value:l,onChange:E=>c(E.target.value),disabled:o||i})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-name",children:"Display Name"}),t.jsx("input",{id:"custom-provider-name",className:"input",value:u,onChange:E=>d(E.target.value),disabled:i})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-base-url",children:"Base URL"}),t.jsx("input",{id:"custom-provider-base-url",className:"input",value:m,onChange:E=>h(E.target.value),disabled:i})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-api",children:"API Type"}),t.jsx("select",{id:"custom-provider-api",className:"select",value:f,onChange:E=>p(E.target.value),disabled:i,children:Eh.map(E=>t.jsx("option",{value:E,children:E},E))})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-api-key",children:"API Key"}),t.jsx("input",{id:"custom-provider-api-key",className:"input",placeholder:"sk-..., MY_API_KEY, or !command",value:g,onChange:E=>b(E.target.value),disabled:i})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{children:"Models"}),t.jsx("div",{className:"custom-provider-form__models",children:v.map((E,T)=>t.jsxs("div",{className:"custom-provider-form__model-row",children:[t.jsx("input",{className:"input","aria-label":`Model ID ${T+1}`,placeholder:"Model ID",value:E.id,onChange:U=>w(T,{id:U.target.value}),disabled:i}),t.jsx("input",{className:"input","aria-label":`Model name ${T+1}`,placeholder:"Display name",value:E.name??"",onChange:U=>w(T,{name:U.target.value}),disabled:i}),t.jsxs("label",{className:"checkbox-label custom-provider-form__toggle",children:[t.jsx("input",{type:"checkbox",checked:!!E.reasoning,onChange:U=>w(T,{reasoning:U.target.checked}),disabled:i}),"Reasoning"]}),t.jsx("input",{className:"input","aria-label":`Context window ${T+1}`,placeholder:"Context window",type:"number",value:E.contextWindow??"",onChange:U=>w(T,{contextWindow:U.target.value?Number(U.target.value):void 0}),disabled:i}),t.jsx("input",{className:"input","aria-label":`Max tokens ${T+1}`,placeholder:"Max tokens",type:"number",value:E.maxTokens??"",onChange:U=>w(T,{maxTokens:U.target.value?Number(U.target.value):void 0}),disabled:i}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>M(T),disabled:i||!_,"aria-label":`Remove model ${T+1}`,children:"×"})]},`${T}-model`))}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>x(E=>[...E,_h()]),disabled:i,children:"+ Add model"})]}),S?t.jsx("div",{className:"form-error",children:S}):null,t.jsxs("div",{className:"custom-provider-form__actions",children:[s?t.jsx("button",{type:"button",className:"btn",onClick:s,disabled:i,children:"Cancel"}):null,t.jsx("button",{type:"submit",className:"btn btn-primary",disabled:i,children:i?"Saving...":"Save Provider"})]})]})}const Ki="fusion_model_onboarding_state",ja=[],ka=[],$o=!1,Do=!1,wa={},ZT=void 0,ji=["ai-setup","github","project-setup","first-task"],eP={"ai-setup":"AI Setup",github:"GitHub","project-setup":"Project","first-task":"First Task",complete:"Complete"};function Ss(){if(typeof window>"u")return null;try{const e=localStorage.getItem(Ki);if(!e)return null;const n=JSON.parse(e);return n&&typeof n=="object"&&"currentStep"in n&&typeof n.currentStep=="string"?tP(n):null}catch{return null}}function tP(e){const n=e.postOnboardingDismissedAt??ZT;return{...e,completedSteps:e.completedSteps??ja,skippedSteps:e.skippedSteps??ka,dismissed:e.dismissed??$o,completed:e.completed??Do,stepData:e.stepData??wa,...n?{postOnboardingDismissedAt:n}:{}}}function ho(e,n){if(!(typeof window>"u")){if(!n){const s={currentStep:e,updatedAt:new Date().toISOString(),completedSteps:ja,skippedSteps:ka,dismissed:$o,completed:Do,stepData:wa};try{localStorage.setItem(Ki,JSON.stringify(s))}catch{}return}try{const s=Ss(),i=new Date().toISOString(),r=n.completed??Do;let o=n.dismissed??$o;r&&(o=!1);const l=n.completedSteps??s?.completedSteps??ja,c=n.skippedSteps??s?.skippedSteps??ka,u={...s?.stepData??wa};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(Ki,JSON.stringify(d))}catch{}}}function nP(e){if(!(typeof window>"u"))try{const n=Ss(),s=new Date().toISOString();if(!n){const o={currentStep:e,updatedAt:s,completedSteps:ja,skippedSteps:[e],dismissed:$o,completed:Do,stepData:wa};localStorage.setItem(Ki,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(Ki,JSON.stringify(r))}catch{}}function Mh(){if(!(typeof window>"u"))try{const e=Ss(),n=new Date().toISOString(),s=e?{...e,completedAt:n,completed:!0,dismissed:!1,updatedAt:n}:{currentStep:"complete",updatedAt:n,completedAt:n,completedSteps:ja,skippedSteps:ka,dismissed:!1,completed:!0,stepData:wa};localStorage.setItem(Ki,JSON.stringify(s))}catch{}}function Na(){const e=Ss();return e?e.completed===!0?!0:typeof e.completedAt=="string"&&e.completedAt.length>0:!1}function sP(){if(!(typeof window>"u"))try{const e=Ss(),n=new Date().toISOString(),s=e?{...e,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:ja,skippedSteps:ka,dismissed:!1,completed:!1,stepData:wa,postOnboardingDismissedAt:n};localStorage.setItem(Ki,JSON.stringify(s))}catch{}}function fg(){const e=Ss();return e?typeof e.postOnboardingDismissedAt=="string"&&e.postOnboardingDismissedAt.length>0:!1}function iP(){const e=Ss();return!e||Na()?!1:e.currentStep!=="complete"}function aP(){const e=Ss();if(!e||Na()||e.currentStep==="complete")return null;const n=e.currentStep,s=eP[n]??lP(e.currentStep);return{currentStep:e.currentStep,label:s,completedSteps:e.completedSteps}}function rP(){const e=Ss();return e?e.skippedSteps:ka}function oP(e){const n=Ss();return!n||!n.stepData?null:n.stepData[e]??null}function lP(e){return e.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const gg="fusion_onboarding_events",Ah="fusion_onboarding_session_id",cP=200,dP=50;function Rs(e,n={}){if(!(typeof window>"u"))try{const s=mP(),i=fP(n.step),r={type:e,timestamp:new Date().toISOString(),...i?{step:i}:{},metadata:n,sessionId:uP()},o=pP([...s,r]);hP(o)}catch{}}function uP(){if(typeof window>"u")return"server-session";try{const e=sessionStorage.getItem(Ah);if(e)return e;const n=Rh();return sessionStorage.setItem(Ah,n),n}catch{return Rh()}}function Rh(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function mP(){try{const e=localStorage.getItem(gg);if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(gP):[]}catch{return[]}}function hP(e){try{localStorage.setItem(gg,JSON.stringify(e))}catch{}}function pP(e){const n=[...e];for(;n.length>cP;)n.splice(0,dP);return n}function fP(e){if(e==="ai-setup"||e==="github"||e==="first-task"||e==="complete")return e}function gP(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 bP=e=>({id:e.id,name:e.name,baseUrl:e.baseUrl,api:"api"in e?e.api:e.apiType==="anthropic-compatible"?"anthropic-messages":"openai-responses",apiKey:e.apiKey,models:e.models?.map(n=>({id:n.id,name:n.name}))??[]}),xP={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"}}},bg={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:"..."}},vP={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},Th={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 Xc(e){if(Th[e])return Th[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 fc=["anthropic","openai","google","gemini","ollama"],yP=["anthropic","claude-cli","openai-codex","gemini","minimax","kimi","zai"],jP={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"},kP={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function Zc(e){return jP[e]??e}function Ph(e){const n=Zc(e),s=yP.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function Ih(e,n){if(e.authenticated!==n.authenticated)return e.authenticated?-1:1;const s=Ph(e.id),i=Ph(n.id);if(s!==i)return s-i;const r=Zc(e.id),o=Zc(n.id);if(r!==o)return r.localeCompare(o);const l=kP[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 wP(e,n){const s=n.trim();if(!s)return"API key is required";const i=bg[e]??vP;return i.pattern.test(s)?null:`${Xc(e)} keys should follow this format: ${i.hint} (e.g. ${i.example})`}const xg={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"},NP={description:"AI provider — connect to start using AI models",apiKeyInfo:xg};function ed(e){return xP[e]??NP}function SP(e){return ed(e.id).apiKeyInfo??xg}function ti({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(vn,{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 CP({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 EP({provider:e,apiKeyInfo:n,inputValue:s,isSaving:i,error:r,success:o,isConnected:l,onInputChange:c,onSave:u,onClear:d}){const m=`onboarding-apikey-input-${e.id}`,h=i||!s.trim(),f=bg[e.id],p=`input onboarding-apikey-input${r?" onboarding-apikey-input--error":""}${o?" onboarding-apikey-input--success":""}`,g=t.jsxs(t.Fragment,{children:[f&&t.jsxs("small",{className:"onboarding-apikey-hint",children:["Format: ",f.hint]}),t.jsx("p",{className:"onboarding-apikey-instructions",children:n.setupInstructions}),n.dashboardUrl&&t.jsx("a",{href:n.dashboardUrl,target:"_blank",rel:"noreferrer",className:"onboarding-apikey-dashboard-link",children:"Get your API key →"}),t.jsx("p",{className:"onboarding-apikey-usage",children:n.usageDescription})]});return l?t.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${e.id}`,children:[t.jsxs("div",{className:"onboarding-apikey-connected-header",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:n.fieldLabel}),t.jsx("span",{className:"auth-status-badge connected",children:"✓ API key saved"})]}),t.jsx("button",{className:"btn btn-sm",onClick:()=>d(e.id),disabled:i,children:i?"Removing…":"Remove Key"}),t.jsx(ti,{summary:"Advanced setup details",children:g}),r&&t.jsx("small",{className:"field-error",children:r})]}):t.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${e.id}`,children:[t.jsx("label",{htmlFor:m,className:"onboarding-apikey-field-label",children:n.fieldLabel}),t.jsxs("div",{className:"onboarding-apikey-input-row",children:[t.jsx("input",{id:m,type:"password",className:p,placeholder:n.inputPlaceholder??"Enter API key",value:s,onChange:b=>c(e.id,b.target.value),onKeyDown:b=>{b.key==="Enter"&&u(e.id,s)},"data-testid":m}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>u(e.id,s),disabled:h,"data-testid":`onboarding-apikey-save-${e.id}`,children:i?"Saving…":"Save"})]}),r&&t.jsx("small",{className:"field-error",children:r}),o&&!r&&t.jsx("small",{className:"onboarding-apikey-success","data-testid":`onboarding-apikey-success-${e.id}`,children:o}),t.jsx(ti,{summary:"Advanced setup details",children:g})]})}const _P=150;function MP({onComplete:e,addToast:n,projectId:s,onOpenSetupWizard:i,onOpenNewTask:r,onOpenGitHubImport:o,firstCreatedTask:l,onViewTask:c}){const u=Ss(),d=u?.currentStep,m=d==="complete"?"ai-setup":ji.includes(d)?d:"ai-setup",h=u?.completedSteps??[],f=u?.skippedSteps??rP(),[p,g]=a.useState(!0),[b,v]=a.useState(m),[x,y]=a.useState(h),[k,_]=a.useState(f),[S,w]=a.useState(!1),[M,N]=a.useState(""),[D,E]=a.useState(!1),[T,U]=a.useState(null),[K,$]=a.useState(null),[R,z]=a.useState([]),[B,J]=a.useState(void 0),[Q,C]=a.useState(!0),[L,P]=a.useState(null),[j,O]=a.useState({}),[H,ge]=a.useState([]),[be,se]=a.useState(""),[me,F]=a.useState(!1),[de,ne]=a.useState({}),[xe,oe]=a.useState({}),[he,ae]=a.useState({}),[je,Ae]=a.useState([]),[Oe,Qe]=a.useState(!1),[Xe,Ye]=a.useState(!1),[it,Be]=a.useState(),Ge=a.useRef({}),re=a.useRef(null),ke=a.useRef(null),X=a.useRef(null),[Te,Le]=a.useState({}),[fe,_e]=a.useState(()=>Ss()?.stepData?.github?.skipped===!0),Ue=a.useRef(0),nt=a.useRef(l),ve=a.useRef(!1),ce=u?.currentStep,De=!!u&&u.currentStep!=="complete";oi(ke,p,"fusion:model-onboarding-modal-size"),a.useEffect(()=>{const G=re.current;G&&(G.scrollTop=0)},[b]);const[ue,Re]=a.useState(()=>Ss()?.stepData?.["ai-setup"]?.skippedProviders??{}),Ke=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"project-setup",label:"Project"},{key:"first-task",label:"First Task"}],Pe=Ke.findIndex(G=>G.key===b),ft=b==="complete"?Ke.length:Pe;a.useEffect(()=>{b!=="complete"&&ho(b,{completedSteps:x,skippedSteps:k})},[b,x,k]),a.useEffect(()=>{ve.current||(ve.current=!0,Rs("onboarding:wizard-opened",{source:De?"resume":"initial",resumedFromStep:ce}))},[De,ce]),a.useEffect(()=>{const G=nt.current!=null,Fe=l!=null;!G&&Fe&&w(!0),Fe||w(!1),nt.current=l},[l]);const Z=a.useRef(m);a.useEffect(()=>{if(Z.current==="ai-setup"&&b!=="ai-setup"&&!R.some(Fe=>Fe.id!=="github"&&Fe.authenticated)){const Fe={};for(const tt of R)tt.id!=="github"&&!tt.authenticated&&!ue[tt.id]&&(Fe[tt.id]=!0);if(Object.keys(Fe).length>0){const tt={...ue,...Fe};Re(tt),ho(b,{stepData:{"ai-setup":{skippedProviders:tt}}})}}Z.current=b},[b,R,ue]);const le=a.useCallback(async()=>{try{const{providers:G,ghCli:Fe}=await gr();z(G),J(Fe),O(tt=>{const rt={};for(const[kt,St]of Object.entries(tt)){const zt=G.find(qn=>qn.id===kt);zt&&!zt.authenticated&&(rt[kt]=St)}return Object.keys(rt).length===Object.keys(tt).length?tt:rt}),Re(tt=>{const rt={...tt};for(const kt of G)kt.authenticated&&rt[kt.id]&&delete rt[kt.id];return Object.keys(rt).length===Object.keys(tt).length?tt:rt})}catch{}},[]),we=a.useCallback(async()=>{try{const G=await py();Ae((G.providers??[]).map(bP))}catch{}},[]),Ze=a.useCallback(async G=>{Ye(!0),Be(void 0);try{await gy(G),await we(),await ms().then(Fe=>ge(Fe.models??[])),Qe(!1)}catch(Fe){Be(ye(Fe)||"Failed to create custom provider")}finally{Ye(!1)}},[we]),te=a.useRef(!1);a.useEffect(()=>{b==="ai-setup"&&we(),te.current&&le(),te.current=b!=="ai-setup"},[b,le,we]);const Je=R.find(G=>G.id==="github"),dt=!!Je,ut=Je?.authenticated??!1,Ct=B?.authenticated??!1,yt=ut||Ct,bt=!ut&&Ct,At=a.useCallback(G=>{if(G.authenticated)return"connected";const Fe=Te?.[G.id];return Fe==="timeout"||Fe==="failed"?"retry":ue[G.id]?"skipped":"not-connected"},[Te,ue]);function Rt({status:G}){const Fe={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:rt}=Fe[G];return t.jsx("span",{"data-testid":"provider-status-badge",className:rt,"data-status":G,children:tt})}const Ht=a.useCallback(()=>{if(yt)return"connected";const G=Te.github;return G==="pending"?"pending":G==="failed"||G==="timeout"?"failed":fe?"skipped":"not-connected"},[yt,Te,fe]);function Et({status:G}){const Fe={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:rt}=Fe[G];return t.jsx("span",{"data-testid":"github-status-badge",className:rt,"data-status":G,children:tt})}const Dt=a.useCallback(async()=>{try{const G=await ms();ge(G.models)}catch{}},[]),Kt=a.useCallback(async()=>{try{const G=await Gi();if(G.defaultProvider&&G.defaultModelId){const Fe=`${G.defaultProvider}/${G.defaultModelId}`;se(Fe)}}catch{}},[]);a.useEffect(()=>{Promise.all([le(),Dt(),Kt()]).finally(()=>C(!1))},[le,Dt,Kt]),a.useEffect(()=>{const G=oP("ai-setup");if(G?.loginOutcomes){const Fe=G.loginOutcomes,tt={};for(const[rt,kt]of Object.entries(Fe))kt!=="pending"&&(tt[rt]=kt);Object.keys(tt).length>0&&Le(tt)}},[]);const $t=a.useCallback((G,Fe)=>{ho(b,{completedSteps:x,stepData:{"ai-setup":{loginOutcomes:{[G]:Fe}}}})},[b,x]);a.useEffect(()=>{const G=Object.entries(Te).filter(([Fe,tt])=>tt!=="pending");for(const[Fe,tt]of G)$t(Fe,tt)},[Te,$t]),a.useEffect(()=>()=>{X.current&&clearInterval(X.current),Object.values(Ge.current).forEach(clearTimeout),Ge.current={}},[]);const Ft=a.useCallback(G=>{_e(G),ho(b,{completedSteps:x,stepData:{github:{skipped:G}}})},[b,x]),Ot=a.useCallback(G=>G==="complete"?-1:ji.indexOf(G),[]),Tt=a.useCallback(()=>{y(Fe=>[...new Set([...Fe,b])]),_(Fe=>Fe.filter(tt=>tt!==b)),Rs("onboarding:step-completed",{step:b}),b==="github"&&!ut&&Ft(!1);const G=Ot(b);G>=0&&G<ji.length-1&&v(ji[G+1])},[b,ut,Ft,Ot]),Pt=a.useCallback(()=>{_(Fe=>[...new Set([...Fe,b])]),nP(b),Rs("onboarding:step-skipped",{step:b}),b==="github"&&!ut&&Ft(!0);const G=Ot(b);G>=0&&G<ji.length-1&&v(ji[G+1])},[b,ut,Ft,Ot]),wt=a.useCallback(()=>{const G=b;y(tt=>tt.filter(rt=>rt!==G)),_(tt=>tt.filter(rt=>rt!==G)),G==="github"&&!ut&&Ft(!1);const Fe=Ot(b);Fe>0&&v(ji[Fe-1])},[b,ut,Ft,Ot]),Gt=a.useCallback(()=>{Pt()},[Pt]),Ut=a.useCallback(async G=>{Le(Fe=>{const tt=Fe[G];if(tt&&tt!=="pending"){const{[G]:rt,...kt}=Fe;return kt}return Fe}),O(Fe=>{if(!(G in Fe))return Fe;const tt={...Fe};return delete tt[G],tt}),Le(Fe=>({...Fe,[G]:"pending"})),P(G),Ue.current=0;try{const{url:Fe,instructions:tt}=await by(G);tt?.trim()&&O(rt=>({...rt,[G]:tt})),window.open(ii(Fe),"_blank"),X.current=setInterval(async()=>{if(Ue.current++,Ue.current>=_P){X.current&&(clearInterval(X.current),X.current=null),P(null),Le(rt=>({...rt,[G]:"timeout"})),O(rt=>{if(!(G in rt))return rt;const kt={...rt};return delete kt[G],kt}),n("Login timed out. Please try again.","warning");return}try{const{providers:rt,ghCli:kt}=await gr();z(rt),J(kt),rt.find(zt=>zt.id===G)?.authenticated&&(X.current&&(clearInterval(X.current),X.current=null),P(null),Le(zt=>({...zt,[G]:"success"})),O(zt=>{if(!(G in zt))return zt;const qn={...zt};return delete qn[G],qn}),G==="github"&&Ft(!1),n("Login successful","success"))}catch{}},2e3)}catch(Fe){Fe instanceof Error&&Fe.message.includes("already in progress")||Fe&&typeof Fe=="object"&&"status"in Fe&&Fe.status===409?(n("Login already in progress. Please wait or cancel the current attempt.","warning"),Le(rt=>({...rt,[G]:"failed"}))):(n(Fe instanceof Error?Fe.message:"Login failed","error"),Le(rt=>({...rt,[G]:"failed"}))),P(null),O(rt=>{if(!(G in rt))return rt;const kt={...rt};return delete kt[G],kt})}},[n,Ft]),q=a.useCallback(G=>{X.current&&(clearInterval(X.current),X.current=null),P(null),Ue.current=0,Le(Fe=>({...Fe,[G]:"cancelled"})),O(Fe=>{if(!(G in Fe))return Fe;const tt={...Fe};return delete tt[G],tt})},[]),pe=a.useCallback((G,Fe)=>{ne(rt=>({...rt,[G]:Fe}));const tt=Ge.current[G];tt&&(clearTimeout(tt),delete Ge.current[G]),oe(rt=>{if(!rt[G])return rt;const kt={...rt};return delete kt[G],kt}),ae(rt=>{if(!rt[G])return rt;const kt={...rt};return delete kt[G],kt})},[]),$e=a.useCallback(()=>{const G=re.current;if(!G)return;const Fe=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof G.scrollTo=="function"){G.scrollTo({top:0,behavior:Fe?"auto":"smooth"});return}}catch{}G.scrollTop=0},[]),A=a.useCallback(async(G,Fe)=>{const tt=(Fe??de[G]??"").trim(),rt=wP(G,tt);if(rt){oe(St=>({...St,[G]:rt}));return}const kt=Ge.current[G];kt&&(clearTimeout(kt),delete Ge.current[G]),P(G),oe(St=>{const zt={...St};return delete zt[G],zt}),ae(St=>{if(!St[G])return St;const zt={...St};return delete zt[G],zt});try{await vy(G,tt),await le(),$e(),ne(St=>{const zt={...St};return delete zt[G],zt}),oe(St=>{if(!St[G])return St;const zt={...St};return delete zt[G],zt}),ae(St=>({...St,[G]:"✓ Key saved"})),Ge.current[G]=setTimeout(()=>{ae(St=>{if(!St[G])return St;const zt={...St};return delete zt[G],zt}),delete Ge.current[G]},3e3),n("API key saved","success")}catch(St){const zt=St instanceof TypeError&&St.message.includes("Failed to fetch")?"Could not reach the server. Check your connection and try again.":St instanceof Error?St.message:"Failed to save API key";oe(qn=>({...qn,[G]:zt})),ae(qn=>{if(!qn[G])return qn;const Ds={...qn};return delete Ds[G],Ds}),n(zt,"error")}finally{P(null)}},[de,n,le,$e]),ee=a.useCallback(async G=>{P(G);try{await yy(G),await le(),n("API key removed","success")}catch(Fe){n(Fe instanceof Error?Fe.message:"Failed to clear API key","error")}finally{P(null)}},[n,le]),ze=a.useCallback(async G=>{P(G);try{await xy(G),await le(),n("Logged out","success")}catch(Fe){n(Fe instanceof Error?Fe.message:"Logout failed","error")}finally{P(null)}},[n,le]),mt=a.useCallback(G=>{se(G)},[]),jt=a.useCallback(async()=>{try{const G={modelOnboardingComplete:!0};if(be){const Fe=be.indexOf("/"),tt=Fe!==-1?be.slice(0,Fe):void 0,rt=Fe!==-1?be.slice(Fe+1):be,kt=H.find(St=>St.id===rt);kt?(G.defaultProvider=kt.provider,G.defaultModelId=kt.id):tt&&rt&&(G.defaultProvider=tt,G.defaultModelId=rt)}await hn(G),Mh()}catch{}},[be,H,hn,Mh]),Lt=a.useCallback(async()=>{const G=[...new Set([...x,"first-task"])];F(!0);try{await jt(),Rs("onboarding:completed",{completedSteps:G,skippedSteps:k}),y(G),_(Fe=>Fe.filter(tt=>tt!=="first-task")),v("complete")}finally{F(!1)}},[jt,x,k]),_t=a.useCallback(async()=>{if(!s)return;const G=M.trim();if(!G){U("Please enter a task description.");return}U(null),E(!0);let Fe=!1;try{const tt=await dp({description:G,source:{sourceType:"dashboard_ui"}},s);$(tt),w(!0),Rs("onboarding:first-task-created",{taskId:tt?.id}),n("Task created","success"),Fe=!0}catch(tt){const rt=tt instanceof Error?tt.message:"Something went wrong creating your task. Please try again.";U(rt),n(rt,"error")}finally{E(!1)}Fe&&jt()},[s,M,n,jt]),Jt=a.useCallback(async()=>{F(!0);try{await jt()}finally{F(!1)}Rs("onboarding:open-new-task",{}),r?.()},[jt,r]),Dn=a.useCallback(async()=>{if(yt){F(!0);try{await jt()}finally{F(!1)}g(!1),e(),Rs("onboarding:open-github-import",{}),o?.()}},[jt,yt,e,o]),Pn=a.useCallback(async()=>{Rs("onboarding:dismissed",{currentStep:b,completedSteps:x,skippedSteps:k}),F(!0);try{await hn({modelOnboardingComplete:!0})}catch{}g(!1),e()},[b,x,k,e]),Yt=a.useCallback(()=>{Rs("onboarding:finished",{}),g(!1),e()},[e]),Cn=a.useCallback(()=>{const G=l??K;G&&(jt(),c?.(G),e())},[l,K,jt,c,e]),Ne=a.useCallback(()=>{jt(),e()},[jt,e]);if(!p)return null;const at=Ht(),fn=R.filter(G=>G.id!=="github"),jn=[...fn].sort(Ih),In=jn.some(G=>!G.type||G.type==="oauth"),Ce=jn.some(G=>G.type==="api_key"),st=fn.filter(G=>G.authenticated),ht=st.length>0,Mt=!!s,ln=b==="github"&&!ht,En=(()=>{if(!be)return"";const G=be.indexOf("/"),Fe=G===-1?void 0:be.slice(0,G),tt=G===-1?be:be.slice(G+1),rt=H.find(kt=>kt.id===tt&&(!Fe||kt.provider===Fe));return rt?.name?rt.name:Fe?`${Xc(Fe)} ${tt}`:be})(),tn=[];if(Mt?tn.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):tn.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),ht){const G=Xc(st[0]?.id??"");tn.push({label:"AI Provider",status:"connected",detail:`${G} connected — AI agents can work on tasks`})}else fn.length>0&&fn.some(G=>ue[G.id])?tn.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):tn.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});yt?tn.push({label:"GitHub",status:"connected",detail:bt?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!dt||fe?tn.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):tn.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),En&&tn.push({label:"Default Model",status:"connected",detail:En});const nn=l??K,An=nn?.description?.split(`
|
|
656
|
-
`)[0]?.trim()||nn?.title||"",Un=new Set(fc),kn=jn.filter(G=>Un.has(G.id)).sort((G,Fe)=>{const tt=fc.indexOf(G.id),rt=fc.indexOf(Fe.id);return tt!==rt?tt-rt:Ih(G,Fe)}),ns=jn.filter(G=>G.authenticated&&!Un.has(G.id)),cn=jn.filter(G=>!G.authenticated&&!Un.has(G.id)),vt=G=>{if(G.id==="claude-cli"&&G.type==="cli")return t.jsx(KT,{authenticated:G.authenticated,onToggled:()=>{le()}},G.id);if(G.type==="api_key"){const Fe=ed(G.id),tt=SP(G);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${G.id}`,className:`onboarding-provider-card${G.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${G.id}`,"aria-hidden":"true",children:t.jsx(On,{provider:G.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(np,{size:14,className:"onboarding-provider-key-icon"}),G.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:Fe.description}),t.jsx(Rt,{status:At(G)}),G.authenticated&&G.keyHint&&t.jsxs("span",{className:"auth-key-hint",children:["Key: ",G.keyHint]})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx(EP,{provider:G,apiKeyInfo:tt,inputValue:de[G.id]??"",isSaving:L===G.id,error:xe[G.id],success:he[G.id],isConnected:G.authenticated,onInputChange:pe,onSave:A,onClear:ee})})]},G.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${G.id}`,className:`onboarding-provider-card${G.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${G.id}`,"aria-hidden":"true",children:t.jsx(On,{provider:G.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:G.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:ed(G.id).description}),t.jsx(Rt,{status:At(G)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:L===G.id?t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:G.authenticated?"Logging out…":"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>q(G.id),children:"Cancel"})]}):G.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>ze(G.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>Ut(G.id),children:"Login"})}),L===G.id&&j[G.id]&&t.jsx(pc,{instructions:j[G.id],"data-testid":`onboarding-login-instructions-${G.id}`}),Te[G.id]==="timeout"&&L!==G.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),Te[G.id]==="failed"&&L!==G.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},G.id)};return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"onboarding-title",children:t.jsxs("div",{className:"modal model-onboarding-modal",ref:ke,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(Gn,{size:24})," Set Up AI ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),b==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(ks,{size:24})," Connect GitHub ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),b==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(Od,{size:24})," Set Up Your Project"]}),b==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(Od,{size:24})," Create Your First Task"]}),b==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx(yn,{size:24})," All Set!"]})]}),b!=="complete"&&t.jsx("button",{className:"modal-close",onClick:Pn,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(Wt,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:Ke.map((G,Fe)=>{const tt=ft>Fe,rt=x.includes(G.key)&&tt,kt=k.includes(G.key)&&!x.includes(G.key)&&tt,St=rt||kt;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[Fe>0&&t.jsx("div",{className:`model-onboarding-step-connector ${Fe<=ft?"done":""}`}),St?t.jsxs("button",{className:`model-onboarding-step-indicator ${b===G.key?"active":""} ${rt?"done":""} ${kt?"skipped":""}`,onClick:()=>v(G.key),"aria-label":`Go back to ${G.label}`,title:`Review ${G.label}`,children:[t.jsx("span",{className:"step-number",children:rt?t.jsx(yn,{size:14}):kt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Fe+1}),t.jsx("span",{className:"step-label",children:G.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${b===G.key?"active":""} ${rt?"done":""} ${kt?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:rt?t.jsx(yn,{size:14}):kt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Fe+1}),t.jsx("span",{className:"step-label",children:G.label})]})]},G.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:re,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."}),!Q&&R.length>0&&(()=>{const G=R.filter(St=>St.id!=="github"&&St.authenticated).length,Fe=R.filter(St=>St.id!=="github").length,tt=Object.keys(ue).filter(St=>!R.find(zt=>zt.id===St)?.authenticated).length;if(Fe===0)return null;let rt="onboarding-provider-summary",kt="";return G>0?(rt+=" onboarding-provider-summary--connected",kt=`✓ ${G} of ${Fe} provider${Fe!==1?"s":""} connected`):tt>0?(rt+=" onboarding-provider-summary--skipped",kt=`${tt} provider${tt!==1?"s":""} skipped`):(rt+=" onboarding-provider-summary--none",kt="No providers connected yet"),t.jsx("div",{className:rt,"data-testid":"provider-summary",children:kt})})(),t.jsx(ti,{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."})}),R.length>0&&!R.some(G=>G.authenticated)&&t.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),Q?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(ot,{size:24,className:"animate-spin"}),t.jsx("span",{children:"Loading providers…"})]}):R.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"}),kn.length>0?t.jsx("div",{className:"model-onboarding-providers",children:kn.map(G=>vt(G))}):t.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),ns.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:ns.map(G=>vt(G))})]}),t.jsxs("div",{className:"onboarding-model-section",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Default Model (Optional)"}),t.jsx("p",{className:"model-onboarding-description",children:"Pick a default model for AI tasks, or leave this blank to choose later. Models vary in speed, capability, and cost."}),t.jsx(ti,{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."})}),H.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(Yn,{models:H,value:be,onChange:mt,placeholder:"Select a default model…",label:"Default model"})}),be&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",H.find(G=>G.id===be)?.name??be]})})]}),t.jsx(ti,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:t.jsxs("div",{"data-testid":"onboarding-advanced-provider-settings",children:[cn.length>0?t.jsx("div",{className:"model-onboarding-providers",children:cn.map(G=>vt(G))}):t.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."}),je.length>0?t.jsx("div",{className:"onboarding-custom-provider-list",children:je.map(G=>t.jsxs("div",{className:"onboarding-custom-provider-item",children:[t.jsx(On,{provider:G.id,size:"sm"}),t.jsx("span",{children:G.name||G.id})]},G.id))}):null,Oe?t.jsx(XT,{onSave:Ze,onCancel:()=>{Qe(!1),Be(void 0)},saving:Xe,error:it}):t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>Qe(!0),children:"Add custom provider"})]})}),In&&t.jsx(ti,{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."})}),Ce&&t.jsx(ti,{summary:"What is an API key?",children:t.jsx("p",{className:"onboarding-helper-text",children:"An API key is a secret token that authenticates Fusion with the provider. You can find your key in the provider's dashboard under API settings. Keys are stored securely on your machine."})})]})]}),b==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[yt?t.jsx("p",{className:"model-onboarding-description",children:bt?"GitHub CLI is already authenticated — issue imports and pull request tracking work right now. You're all set; no further action needed.":"GitHub is connected — issue imports and pull request tracking are available. You're all set; no further action needed."}):t.jsx("p",{className:"model-onboarding-description",children:"Connecting GitHub unlocks issue imports and pull request tracking. You can skip this — task creation works without it."}),!yt&&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"})]})}),ln&&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(ti,{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."})}),dt?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(ks,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(Et,{status:at})})]}),ut&&(L==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>ze("github"),children:"Disconnect"}))]}),(at==="not-connected"||at==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[L==="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:()=>q("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>Ut("github"),children:[t.jsx(ks,{size:16}),"Connect"]}),L==="github"&&j.github&&t.jsx(pc,{instructions:j.github,"data-testid":"onboarding-login-instructions-github"})]}),at==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:bt?"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."}),at==="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:()=>Ut("github"),children:"Retry"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Gt,children:"Skip for now"})]})]}),at==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),at==="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:()=>Ut("github"),children:"Connect anyway"})})]}),at==="not-connected"&&t.jsx("p",{className:"onboarding-helper-text",children:"No worries if you're not ready — connect GitHub anytime from Settings → Authentication."})]}):t.jsxs("div",{className:"model-onboarding-github-optional",children:[t.jsx("div",{className:"optional-icon optional-icon--github","aria-hidden":"true",children:t.jsx(On,{provider:"github",size:"lg"})}),bt?t.jsx("p",{children:"GitHub CLI is already authenticated, so imports and PR tracking work now. OAuth from the dashboard is optional and only controls dashboard-managed connect/disconnect."}):t.jsx("p",{children:"GitHub OAuth isn't connected yet. You can set it up in Settings → Authentication, or continue now and connect later."}),t.jsxs("div",{className:"model-onboarding-github-optional__actions",children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>v("project-setup"),children:bt?"Continue with gh CLI auth →":"Continue without GitHub →"}),bt&&(L==="github"?t.jsxs("button",{className:"btn btn-sm",disabled:!0,children:[t.jsx(ot,{size:14,className:"onboarding-spinner"}),"Waiting for OAuth login…"]}):t.jsxs("button",{className:"btn btn-sm",onClick:()=>Ut("github"),children:[t.jsx(On,{provider:"github",size:"sm"}),"Connect OAuth (optional)"]}))]}),bt&&L==="github"&&j.github&&t.jsx(pc,{instructions:j.github,"data-testid":"onboarding-login-instructions-github"})]})]}),b==="project-setup"&&t.jsxs("div",{className:"model-onboarding-project-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Choose your first project before creating or importing tasks. You can register an existing local directory or clone a GitHub repository URL through the setup wizard."}),Mt?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(ti,{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."}),S&&nn?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx(yn,{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:nn.id}),An&&t.jsx("p",{className:"onboarding-task-created__description",children:An}),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:Cn,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:Ne,children:"Go to Dashboard"})]})]}):t.jsxs(t.Fragment,{children:[Mt?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:M,onChange:G=>{N(G.target.value),U(null)},placeholder:"Example: Build a login page with email and password",rows:4}),t.jsx("div",{className:"onboarding-first-task-form__actions",children:t.jsx("button",{type:"button",className:"btn btn-primary",onClick:_t,disabled:D,"data-testid":"onboarding-first-task-submit",children:D?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),T&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:T}),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(CP,{items:tn}),Mt&&t.jsxs(t.Fragment,{children:[t.jsx(ti,{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:Jt,disabled:me,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(on,{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${yt?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:Dn,disabled:me||!yt,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(ks,{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"}),!yt&&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(yn,{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:Pn,disabled:me,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Pt,children:"Skip setup →"}),t.jsx("button",{className:"btn btn-primary",onClick:Tt,children:"Next →"})]}),b==="github"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:wt,children:"← Back"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Pt,children:"Skip GitHub →"}),t.jsx("button",{className:"btn btn-primary",onClick:Tt,children:"Next →"})]}),b==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:wt,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:Tt,disabled:!Mt,children:"Next →"})]}),b==="first-task"&&!S&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:wt,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:Lt,disabled:me,children:me?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),b==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:Yt,children:[t.jsx(yn,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function vg({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 AP=a.lazy(()=>un(()=>import("./SetupWizardModal-tF8B_aG_.js"),__vite__mapDeps([6,1,7,8,9,0,2,10])).then(e=>({default:e.SetupWizardModal}))),RP=a.lazy(()=>un(()=>import("./SettingsModal-D1xq0WZm.js"),__vite__mapDeps([11,1,12,13,14,15,0,2,16])).then(e=>({default:e.SettingsModal})));function TP(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{un(()=>import("./SettingsModal-D1xq0WZm.js"),__vite__mapDeps([11,1,12,13,14,15,0,2,16]))},{timeout:1500})}function PP({projectId:e,tasks:n,projects:s,currentProject:i,addToast:r,toasts:o,removeToast:l,modalManager:c,projectActions:u,taskHandlers:d,taskOperations:m,deepLink:h,settings:f,onSettingsClose:p,onReopenOnboarding:g}){const[b,v]=a.useState(null),x=c.detailTask?(()=>{const M=n.find(N=>N.id===c.detailTask?.id);return M?"prompt"in c.detailTask?{...c.detailTask,...M,prompt:c.detailTask.prompt,log:c.detailTask.log}:M:c.detailTask})():null,y=p??c.closeSettings,k=a.useCallback(()=>{c.openNewTask()},[c]),_=a.useCallback(()=>{c.openGitHubImport()},[c]),S=a.useCallback(M=>{v(null),c.closeModelOnboarding(),c.openDetailTask(M)},[c]),w=a.useCallback(async M=>{const N=await d.handleModalCreate(M);return c.modelOnboardingOpen&&v(N),N},[d.handleModalCreate,c.modelOnboardingOpen]);return a.useEffect(()=>{!c.modelOnboardingOpen&&b&&v(null)},[c.modelOnboardingOpen,b]),a.useEffect(()=>{TP()},[]),t.jsxs(t.Fragment,{children:[x&&t.jsx(Pi,{children:t.jsx(SA,{task:x,projectId:e,tasks:n,onClose:h.handleDetailClose,onOpenDetail:c.openDetailTask,onMoveTask:m.moveTask,onDeleteTask:m.deleteTask,onMergeTask:m.mergeTask,onRetryTask:m.retryTask,onResetTask:m.resetTask,onDuplicateTask:m.duplicateTask,onTaskUpdated:c.updateDetailTask,addToast:r,prAuthAvailable:f.prAuthAvailable,initialTab:c.detailTaskInitialTab})}),c.settingsOpen&&t.jsx(Pi,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(RP,{onClose:y,addToast:r,initialSection:c.settingsInitialSection,projectId:e,themeMode:f.themeMode,colorTheme:f.colorTheme,onThemeModeChange:f.setThemeMode,onColorThemeChange:f.setColorTheme,onReopenOnboarding:g})})}),t.jsx(EA,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:d.handleGitHubImport,tasks:n,projectId:e}),t.jsx(Pi,{children:t.jsx(RA,{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(Pi,{children:t.jsx(UA,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:d.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx(cR,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx(uR,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx(PR,{initialWorkspace:c.fileBrowserWorkspace,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),t.jsx(BR,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e,anchorRect:c.usageAnchorRect}),t.jsx(bT,{isOpen:c.systemStatsOpen,onClose:c.closeSystemStats,projectId:e}),c.schedulesOpen&&t.jsx(lT,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx(Pi,{children:t.jsx(mT,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:w,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan,onSubtaskBreakdown:c.openSubtaskBreakdown})}),t.jsx(kT,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:i,onOpenTaskDetail:M=>{const N=n.find(D=>D.id===M);N&&c.openDetailTask(N)}}),t.jsx(Pi,{children:t.jsx(NT,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx(Pi,{children:t.jsx(DT,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(WT,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(a.Suspense,{fallback:null,children:t.jsx(AP,{onProjectRegistered:u.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(MP,{onComplete:u.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:u.handleAddProject,onOpenNewTask:k,onOpenGitHubImport:_,firstCreatedTask:b,onViewTask:S}),t.jsx(vg,{toasts:o,onRemove:l})]})}function IP({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 td=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function $P(e,n){if(n==="ready")return"done";const s=td.findIndex(r=>r.id===n),i=td.findIndex(r=>r.id===e);return i<s?"done":i===s?"active":"pending"}function DP({stage:e}){const[n]=a.useState(()=>bv());return t.jsx("div",{className:"dashboard-loader",role:"status","aria-live":"polite","aria-label":n?"Updating Fusion dashboard":"Loading Fusion dashboard","data-stage":e,"data-version-update":n?"true":void 0,children:t.jsxs("div",{className:"dashboard-loader__content",children:[t.jsx("h1",{className:"dashboard-loader__logo",children:"Fusion"}),n?t.jsx("p",{className:"dashboard-loader__message dashboard-loader__message--update",children:"Updating to a new frontend version..."}):t.jsx("p",{className:"dashboard-loader__message",children:"Initializing dashboard..."}),t.jsx("ol",{className:"dashboard-loader__steps","aria-label":"Dashboard loading progress",children:td.map(s=>{const i=$P(s.id,e);return t.jsxs("li",{className:`dashboard-loader__step dashboard-loader__step--${i}`,"data-testid":`dashboard-loader-step-${s.id}`,children:[t.jsx("span",{className:"dashboard-loader__step-icon","aria-hidden":"true",children:i==="done"?"✓":i==="active"?t.jsx(ot,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:s.label})]},s.id)})})]})})}const LP=5e3;function zP(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function FP(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++,Eo(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 OP(e,n,s,i){const[r,o]=a.useState({globalPause:!1,enginePaused:!1,maxConcurrent:2}),[l,c]=a.useState(!0),[u,d]=a.useState(null),m=a.useRef(null),h=a.useRef(null),f=a.useCallback(async()=>{h.current&&h.current.abort(),h.current=new AbortController;try{c(!0),d(null);const v=await Zj(n);o(v)}catch(v){if(v instanceof Error&&v.name==="AbortError")return;d(v instanceof Error?v.message:"Failed to fetch executor stats")}finally{c(!1)}},[n]);a.useEffect(()=>(f(),()=>{h.current&&h.current.abort()}),[f]),a.useEffect(()=>(m.current&&clearInterval(m.current),m.current=setInterval(()=>{f()},LP),()=>{m.current&&(clearInterval(m.current),m.current=null)}),[f]);const p=FP(e,s,i),g=zP(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:g,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:u,refresh:f}}const UP={planning:si,subtask:Bi,mission_interview:xs,milestone_interview:xs,slice_interview:xs},BP={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function HP({sessions:e,generating:n,needsInput:s,onOpenSession:i,onDismissSession:r}){const{confirm:o}=Ws(),[l,c]=a.useState(!1),[u,d]=a.useState(new Set),m=a.useRef(null),h=a.useRef(new Map),f=a.useRef(null),{activeTabMap:p}=Ma(),g=a.useMemo(()=>Ji(),[]);if(a.useEffect(()=>{if(!l)return;const x=y=>{m.current&&!m.current.contains(y.target)&&c(!1)};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[l]),a.useEffect(()=>{const x=new Set,y=new Map;for(const k of e){const _=p.get(k.id),S=[k.status,k.updatedAt,_?.tabId??k.lockedByTab??"",_?.stale?"stale":"fresh"].join("|"),w=h.current.get(k.id);w&&w!==S&&x.add(k.id),y.set(k.id,S)}if(h.current=y,x.size!==0)return d(x),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{d(new Set),f.current=null},500),()=>{f.current&&(clearTimeout(f.current),f.current=null)}},[p,e]),e.length===0)return null;const b=e.length,v=s>0;return t.jsxs("div",{ref:m,className:"background-tasks-indicator",children:[t.jsxs("button",{className:`background-tasks-indicator__pill${v?" background-tasks-indicator__pill--attention":""}`,onClick:()=>c(x=>!x),title:`${b} background AI task${b!==1?"s":""}${s>0?` (${s} need${s!==1?"":"s"} input)`:""}`,children:[n>0&&t.jsx(ot,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&t.jsx(kc,{size:12}),t.jsxs("span",{children:["AI ",b]})]}),l&&t.jsxs("div",{className:"background-tasks-indicator__popover",children:[t.jsx("div",{className:"background-tasks-indicator__popover-header",children:"Background Tasks"}),t.jsx("div",{className:"background-tasks-indicator__popover-list",children:e.map(x=>{const y=UP[x.type],k=x.status==="generating",_=x.status==="awaiting_input",S=x.status==="error",w=p.get(x.id),M=w?.tabId??x.lockedByTab??null,N=!!(M&&M!==g&&!w?.stale),D=u.has(x.id);return t.jsxs("div",{className:`background-tasks-indicator__item${D?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:D?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:D?"translateY(-1px)":void 0},onClick:async()=>{N&&!await o({title:"Open Active Session",message:"This session is active in another tab. Open anyway?"})||(i(x),c(!1))},children:[S?t.jsx(us,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--color-error)"}}):t.jsx(y,{size:14,className:"background-tasks-indicator__session-icon"}),t.jsxs("div",{className:"background-tasks-indicator__session-content",children:[t.jsx("div",{className:"background-tasks-indicator__session-title",children:x.title}),t.jsxs("div",{className:"background-tasks-indicator__session-meta",children:[S?"Failed":BP[x.type],k&&" — generating...",_&&!N&&" — needs input",_&&N&&" — active in another tab"]})]}),k&&t.jsx(ot,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),_&&!N&&t.jsx(kc,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),_&&N&&t.jsx(Ho,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),t.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:E=>{E.stopPropagation(),r(x.id)},title:"Dismiss",children:t.jsx(Wt,{size:12})})]},x.id)})})]})]})}function qP(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 VP(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:Sn};case"paused":return{label:"Paused",color:"var(--triage)",icon:Hs};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:Gn}}}function WP({tasks:e,projectId:n,taskStuckTimeoutMs:s,backgroundSessions:i,backgroundGenerating:r,backgroundNeedsInput:o,onOpenBackgroundSession:l,onDismissBackgroundSession:c,lastFetchTimeMs:u,currentProjectPath:d,onOpenProjectDirectory:m}){const{stats:h,loading:f,error:p}=OP(e,n,s,u),[g,b]=a.useState(!1),v=a.useMemo(()=>VP(h.executorState),[h.executorState]),x=a.useMemo(()=>qP(h.lastActivityAt),[h.lastActivityAt]),y=v.icon;return p?t.jsx("div",{className:"executor-status-bar executor-status-bar--error",role:"status","aria-label":"Executor status",children:t.jsxs("span",{className:"executor-status-bar__error",children:[t.jsx(ad,{size:14}),p]})}):f&&h.runningTaskCount===0?t.jsx("div",{className:"executor-status-bar executor-status-bar--loading",role:"status","aria-label":"Executor status",children:t.jsx("span",{className:"executor-status-bar__loading-text",children:"Loading..."})}):t.jsxs("div",{className:`executor-status-bar ${h.executorState==="running"?"executor-status-bar--running":""}`,role:"status","aria-label":"Executor status",children:[i&&i.length>0&&l&&c&&t.jsxs(t.Fragment,{children:[t.jsx(HP,{sessions:i,generating:r??0,needsInput:o??0,onOpenSession:l,onDismissSession:c}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--queued","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Queued"}),t.jsx("span",{className:"executor-status-bar__count",children:h.queuedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--running ${h.runningTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Running"}),t.jsx("span",{className:"executor-status-bar__count",children:h.runningTaskCount}),t.jsx("span",{className:"executor-status-bar__separator","aria-hidden":"true",children:"/"}),t.jsx("span",{className:"executor-status-bar__max",children:h.maxConcurrent})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),h.stuckTaskCount>0&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--stuck",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--stuck executor-status-bar__indicator--active","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Stuck"}),t.jsx("span",{className:"executor-status-bar__count executor-status-bar__count--error",children:h.stuckTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--blocked ${h.blockedTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Blocked"}),t.jsx("span",{className:`executor-status-bar__count ${h.blockedTaskCount>0?"executor-status-bar__count--warning":""}`,children:h.blockedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--review","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"In Review"}),t.jsx("span",{className:"executor-status-bar__count",children:h.inReviewCount})]}),d&&m&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--project-directory",children:[t.jsx("button",{className:`executor-status-bar__folder-toggle${g?" executor-status-bar__folder-toggle--active":""}`,onClick:()=>b(k=>!k),"aria-label":g?"Hide project directory":"Show project directory","aria-expanded":g,"data-testid":"executor-project-path-toggle",title:g?"Hide project directory":"Show project directory",children:t.jsx(Jn,{size:12,"aria-hidden":"true"})}),g&&t.jsx("button",{className:"executor-status-bar__project-path",onClick:m,title:d,"data-testid":"executor-project-path-link",children:d})]})]}),t.jsx("div",{className:"executor-status-bar__spacer"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--time",children:[t.jsx(Si,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__time",children:x})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx(y,{size:12,style:{color:v.color},"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__state",style:{color:v.color},children:v.label})]})]})}const KP={planning:si,subtask:Bi,mission_interview:xs,milestone_interview:xs,slice_interview:xs},GP={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},Di=new Set;function JP({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:i}){const[r,o]=a.useState(0),l=()=>o(g=>g+1);a.useEffect(()=>{if(Di.size===0)return;const g=new Map(e.map(v=>[v.id,v]));let b=!1;for(const v of Di){const x=g.get(v);x&&x.status!=="awaiting_input"&&x.status!=="error"&&(Di.delete(v),b=!0)}b&&l()},[e]);const c=a.useMemo(()=>e.filter(g=>(g.status==="awaiting_input"||g.status==="error")&&!Di.has(g.id)),[e,r]);if(c.length===0)return null;const u=c.filter(g=>g.status==="awaiting_input").length,d=c.filter(g=>g.status==="error").length;let m="";u>0&&d>0?m=`${u} AI session${u===1?"":"s"} need${u===1?"s":""} your input, ${d} failed`:u>0?m=`${u} AI session${u===1?"":"s"} need${u===1?"s":""} your input`:d>0&&(m=`${d} AI session${d===1?"":"s"} failed`);const h=g=>{Di.add(g),l()},f=g=>{Di.delete(g.id),l(),n(g)},p=()=>{for(const g of c)Di.add(g.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(us,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:m})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[t.jsx(Wt,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Dismiss all"})]})]}),t.jsx("div",{className:"session-notification-banner__list",children:c.map(g=>{const b=KP[g.type],v=g.status==="error";return t.jsxs("article",{className:`session-notification-banner__item${v?" session-notification-banner__item--error":""}`,"data-session-type":g.type,"data-session-status":g.status,children:[t.jsxs("div",{className:"session-notification-banner__item-main",children:[v?t.jsx(us,{size:16,className:"session-notification-banner__type-icon session-notification-banner__type-icon--error","aria-hidden":"true"}):t.jsx(b,{size:16,className:"session-notification-banner__type-icon","aria-hidden":"true"}),t.jsxs("div",{className:"session-notification-banner__text",children:[t.jsx("p",{className:"session-notification-banner__title",title:g.title,children:g.title}),t.jsx("p",{className:"session-notification-banner__meta",children:v?"Failed":GP[g.type]})]})]}),t.jsxs("div",{className:"session-notification-banner__actions",children:[t.jsx("button",{className:"session-notification-banner__resume",onClick:()=>f(g),children:v?"Retry":"Resume"}),t.jsx("button",{className:"session-notification-banner__dismiss",onClick:()=>{h(g.id),s(g.id)},"aria-label":`Dismiss ${g.title}`,children:t.jsx(Wt,{size:14,"aria-hidden":"true"})})]})]},g.id)})})]})}function YP({latestVersion:e,currentVersion:n,onDismiss:s}){return t.jsxs("div",{className:"update-available-banner",role:"status","aria-live":"polite",children:[t.jsxs("p",{className:"update-available-banner__text",children:["Update available: v",e," (current: v",n,"). Run ",t.jsx("code",{children:"npm i -g @runfusion/fusion"})," to update. "," ",t.jsx("a",{className:"update-available-banner__link",href:"https://github.com/Runfusion/Fusion/blob/main/CHANGELOG.md",target:"_blank",rel:"noreferrer",children:"Release notes"})," ","·"," ",t.jsx("a",{className:"update-available-banner__link",href:"https://runfusion.ai",target:"_blank",rel:"noreferrer",children:"Learn more"})]}),t.jsx("button",{type:"button",className:"update-available-banner__dismiss touch-target","aria-label":"Dismiss update notice",onClick:s,children:t.jsx(Wt,{size:16,"aria-hidden":"true"})})]})}function QP({onResume:e}){const n=aP();if(!n)return null;const s=n.completedSteps.length,i=ji.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(rs,{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:()=>{Rs("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),e()},children:[t.jsx(Sn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function XP({onOpenSettings:e,onOpenModelOnboarding:n}){const s=Na(),i=fg(),[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[k,_]=await Promise.all([gr(),Gi()]);if(x)return;const S=k.providers??[],w=S.find(T=>T.id==="github"),N=!S.some(T=>T.id!=="github"&&T.authenticated),D=!_.defaultProvider&&!_.defaultModelId,E=w?!w.authenticated:!1;h({needsAiProvider:N,needsDefaultModel:D,needsGitHub:E})}catch{x||c(!0)}finally{x||o(!1)}})(),()=>{x=!0}},[s,i]);const f=a.useCallback(()=>{sP(),d(!0)},[]),p=a.useCallback(()=>{n()},[n]),g=a.useCallback(()=>{e("global-models")},[e]),b=a.useCallback(()=>{e("authentication")},[e]),v=a.useMemo(()=>{const x=[];return m.needsAiProvider&&x.push({id:"ai-provider",title:"Connect AI Provider",description:"Connect an AI provider to enable AI agents for task planning and code generation",actionLabel:"Set Up AI",onAction:p,icon:Gn}),m.needsDefaultModel&&x.push({id:"default-model",title:"Select Default Model",description:"Choose a default AI model for task execution",actionLabel:"Choose Model",onAction:g,icon:np}),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:ks}),x},[m.needsAiProvider,m.needsDefaultModel,m.needsGitHub,b,g,p]);return!s||i||u||r||l||v.length===0?null:t.jsxs("section",{className:"post-onboarding-recommendations",role:"region","aria-label":"Setup recommendations",children:[t.jsxs("div",{className:"post-onboarding-recommendations__main",children:[t.jsx("div",{className:"post-onboarding-recommendations__icon","aria-hidden":"true",children:t.jsx(si,{size:18,"aria-hidden":!0})}),t.jsxs("div",{className:"post-onboarding-recommendations__content",children:[t.jsx("h2",{className:"post-onboarding-recommendations__title",children:"Recommended Next Steps"}),t.jsx("p",{className:"post-onboarding-recommendations__description",children:"Complete these setup items to get the most out of Fusion."}),t.jsx("ul",{className:"post-onboarding-recommendations__list",children:v.map(x=>{const y=x.icon;return t.jsxs("li",{className:"post-onboarding-recommendations__item",children:[t.jsxs("span",{className:"post-onboarding-recommendations__item-icon","aria-hidden":"true",children:[t.jsx(us,{size:14,"aria-hidden":!0}),t.jsx(y,{size:14,"aria-hidden":!0})]}),t.jsxs("span",{className:"post-onboarding-recommendations__item-text",children:[t.jsx("strong",{children:x.title}),t.jsx("span",{children:x.description})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-primary",onClick:x.onAction,children:x.actionLabel})]},x.id)})})]})]}),t.jsx("button",{type:"button",className:"post-onboarding-recommendations__dismiss",onClick:f,"aria-label":"Dismiss recommendations",children:t.jsx(Wt,{size:16,"aria-hidden":!0})})]})}function ZP({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 gc(e){return e>99?"99+":String(e)}function eI({view:e,onChangeView:n,footerVisible:s,modalOpen:i=!1,keyboardOpen:r=!1,onOpenSettings:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:u,mailboxUnreadCount:d=0,onOpenGitManager:m,onOpenWorkflowSteps:h,onOpenSchedules:f,onOpenScripts:p,onToggleTerminal:g,onOpenFiles:b,onOpenGitHubImport:v,onOpenPlanning:x,onResumePlanning:y,activePlanningSessionCount:k=0,onOpenUsage:_,onRunScript:S,projectId:w,onViewAllProjects:M,showSkillsTab:N,experimentalFeatures:D}){const E=Rr(),[T,U]=a.useState(!1),[K,$]=a.useState(!1),[R,z]=a.useState({}),[B,J]=a.useState(!1),Q=a.useMemo(()=>Object.entries(R).sort(([F],[de])=>F.localeCompare(de)),[R]);a.useEffect(()=>{if(!K)return;let F=!1;return J(!0),br(w).then(de=>{F||z(de)}).catch(()=>{F||z({})}).finally(()=>{F||J(!1)}),()=>{F=!0}},[K,w]);const C=a.useCallback(()=>U(!1),[]),L=a.useCallback(F=>{C(),F?.()},[C]);if(a.useEffect(()=>{if(!T)return;const F=de=>{de.key==="Escape"&&U(!1)};return document.addEventListener("keydown",F),()=>document.removeEventListener("keydown",F)},[T]),E!=="mobile"||i||r)return null;const P=k>0&&y?y:x,j=!!D?.roadmap,O=!!N,H=!!D?.todoView,ge=j&&(!O||e==="roadmaps"),be=O&&(!j||e!=="roadmaps"),se=O&&!be,me=e==="documents"||e==="research"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||e==="todos"&&H||e==="roadmaps"&&!ge||e==="skills"&&!be;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(Hi,{}),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(Nn,{}),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(xs,{}),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(wi,{}),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(pa,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),d>0&&t.jsx("span",{className:"mobile-nav-tab-badge",children:gc(d)})]}),be&&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(Gn,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),ge&&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(Ec,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Roadmaps"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${me?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>U(F=>!F),children:[t.jsx(wc,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),T&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mobile-more-sheet-backdrop",onClick:C}),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:()=>L(u),children:[t.jsx(pa,{}),t.jsx("span",{children:"Mailbox"}),d>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:gc(d)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>L(l),children:[t.jsx(Is,{}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-system-stats",onClick:()=>L(c),children:[t.jsx(mr,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>L(m),children:[t.jsx(Vs,{}),t.jsx("span",{children:"Git Manager"})]}),t.jsxs("div",{className:"mobile-more-split-row",children:[t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-split-primary","data-testid":"mobile-more-item-terminal",onClick:()=>L(g),children:[t.jsx(mi,{}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>$(F=>!F),"aria-expanded":K,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(vn,{size:14,className:`mobile-more-chevron${K?" mobile-more-chevron--open":""}`})})]}),K&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:B?t.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[t.jsx(ot,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):Q.length>0?t.jsxs(t.Fragment,{children:[Q.map(([F,de])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${F}`,onClick:()=>{S&&S(F,de),C(),$(!1)},children:[t.jsx(Sn,{size:14}),t.jsx("span",{children:F})]},F)),p&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{C(),$(!1),p()},children:[t.jsx(Bs,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):p&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":"mobile-more-scripts-manage",onClick:()=>{C(),$(!1),p()},children:[t.jsx(Bs,{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:()=>L(b),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:()=>L(P),children:[t.jsx(si,{}),t.jsx("span",{children:"Planning"}),k>0&&t.jsx("span",{className:"mobile-more-item-badge",children:gc(k)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>L(h),children:[t.jsx(Mc,{}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>L(f),children:[t.jsx(Si,{}),t.jsx("span",{children:"Automation"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>L(v),children:[t.jsx(ZP,{}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>L(_),children:[t.jsx(Is,{}),t.jsx("span",{children:"Usage"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>L(M),children:[t.jsx(tp,{}),t.jsx("span",{children:"Projects"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>L(()=>n("documents")),children:[t.jsx(Ui,{}),t.jsx("span",{children:"Documents"})]}),se&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>L(()=>n("skills")),children:[t.jsx(Gn,{}),t.jsx("span",{children:"Skills"})]}),j&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-roadmaps",onClick:()=>L(()=>n("roadmaps")),children:[t.jsx(Ec,{}),t.jsx("span",{children:"Roadmaps"})]}),D?.researchView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-research",onClick:()=>L(()=>n("research")),children:[t.jsx(ki,{}),t.jsx("span",{children:"Research"})]}),D?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>L(()=>n("insights")),children:[t.jsx(rs,{}),t.jsx("span",{children:"Insights"})]}),D?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>L(()=>n("memory")),children:[t.jsx(yo,{}),t.jsx("span",{children:"Memory"})]}),D?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{L(()=>n("dev-server"))},children:[t.jsx(mr,{size:14}),t.jsx("span",{children:"Dev Server"})]}),H&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-todos",onClick:()=>L(()=>n("todos")),children:[t.jsx(rp,{size:14}),t.jsx("span",{children:"Todos"})]}),t.jsx("div",{className:"mobile-more-separator"}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-settings",onClick:()=>L(o),children:[t.jsx(rr,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function tI({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(Nn,{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 Ld="__fn_agent__";function yg(e,n){const s=typeof e=="string"?e.trim():"",i=typeof n=="string"?n.trim():"";return!s||!i?{}:{modelProvider:s,modelId:i}}function $h(e,n,s){const i=typeof e=="string"?e.trim():"",r=yg(n,s),o=i||(r.modelProvider&&r.modelId?Ld:"");return o?{agentId:o,...r}:null}function bc(e,n,s){const i=yg(n,s),r=i.modelProvider??"",o=i.modelId??"";return`${e}::${r}/${o}`}function nI(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 Dh(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:nI(e.metadata),createdAt:e.createdAt}}function sI(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),[f,p]=a.useState(""),[g,b]=a.useState(""),[v,x]=a.useState([]),[y,k]=a.useState(""),_=a.useRef(null),S=a.useRef(!1),w=a.useRef(null),M=a.useRef(""),N=a.useRef(null),D=a.useRef(""),E=a.useRef(null);a.useEffect(()=>{M.current=y},[y]);const T=a.useCallback(async L=>{const P={agentId:L.agentId};return L.modelProvider&&L.modelId&&(P.modelProvider=L.modelProvider,P.modelId=L.modelId),(await hw(P,e)).session},[e]),U=a.useCallback(async(L,P,j)=>{const O=$h(L,P,j);if(!O)return;const H=bc(O.agentId,O.modelProvider,O.modelId);o(!0);try{const{session:ge}=await mw({agentId:O.agentId,modelProvider:O.modelProvider,modelId:O.modelId},e);if(ge)i(ge),D.current=H;else{const be=await T(O);i(be),D.current=H}}catch(ge){console.error("[useQuickChat] Failed to initialize session:",ge),n?.("Failed to initialize chat","error")}finally{o(!1)}},[e,n,T]),K=a.useCallback(async()=>{if(s){d(!0);try{const L=await uu(s.id,{limit:50},e);c(L.messages.map(Dh))}catch(L){console.error("[useQuickChat] Failed to load messages:",L)}finally{d(!1)}}},[s,e]);a.useEffect(()=>{s?K():c([])},[s,K]);const $=a.useCallback(async()=>{if(s){d(!0);try{const L=await uu(s.id,{limit:50},e);c(L.messages.map(Dh))}catch(L){console.error("[useQuickChat] Failed to reload messages:",L)}finally{d(!1)}}},[s,e]),R=a.useCallback(async(L,P,j)=>{const O=$h(L,P,j);if(!O)return;const H=bc(O.agentId,O.modelProvider,O.modelId);E.current=O;const ge=H===D.current&&s;if(ge||(_.current&&(_.current.close(),_.current=null),p(""),b(""),x([]),h(!1)),ge){await $();return}i(null),c([]),D.current=H,await U(O.agentId,O.modelProvider,O.modelId)},[U,$,s]),z=a.useCallback(async(L,P)=>{await R(Ld,L,P)},[R]),B=a.useCallback(async()=>{const L=E.current;if(!L)return;const P=bc(L.agentId,L.modelProvider,L.modelId);_.current&&(_.current.close(),_.current=null),p(""),b(""),x([]),h(!1),c([]),i(null),o(!0);try{const j=await T(L);i(j),D.current=P}catch(j){console.error("[useQuickChat] Failed to start a fresh session:",j),n?.("Failed to start a new chat","error")}finally{o(!1)}},[n,T]),J=a.useCallback(()=>{s&&(S.current=!0,w.current?.(),w.current=null,_.current?.close(),_.current=null,pw(s.id,e).catch(()=>{}),h(!1),p(""),b(""),x([]))},[s,e]),Q=a.useCallback(()=>{M.current="",k("")},[]),C=a.useCallback((L,P)=>{if(!s||!L.trim()&&(!P||P.length===0))return Promise.resolve();if(m)return P&&P.length>0?Promise.reject(new Error("Cannot send attachments while a response is streaming")):(M.current=L,k(L),Promise.resolve());const j=new Promise((O,H)=>{N.current={resolve:O,reject:H},S.current=!1,_.current&&(_.current.close(),_.current=null);const be={id:`temp-${Date.now()}`,sessionId:s.id,role:"user",content:L,createdAt:new Date().toISOString()};c(je=>[...je,be]),p(""),b(""),x([]),h(!0);let se="",me="",F=[],de=null,ne=null;const xe=()=>{de=null,p(se)},oe=()=>{ne=null,b(me)},he=()=>{de!==null&&(cancelAnimationFrame(de),de=null),ne!==null&&(cancelAnimationFrame(ne),ne=null)};w.current=he;const ae={onThinking:je=>{me+=je,ne===null&&(ne=requestAnimationFrame(oe))},onText:je=>{se+=je,de===null&&(de=requestAnimationFrame(xe))},onToolStart:je=>{F=[...F,{toolName:je.toolName,args:je.args,isError:!1,status:"running"}],x(F)},onToolEnd:je=>{const Ae=[...F];for(let Oe=Ae.length-1;Oe>=0;Oe--){const Qe=Ae[Oe];if(Qe?.toolName===je.toolName&&Qe.status==="running"){Ae[Oe]={...Qe,status:"completed",isError:je.isError,result:je.result},F=Ae,x(Ae);return}}F=[...Ae,{toolName:je.toolName,isError:je.isError,result:je.result,status:"completed"}],x(F)},onDone:je=>{he();const Ae={id:je.messageId||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:se,thinkingOutput:me||void 0,toolCalls:F.length>0?F:void 0,createdAt:new Date().toISOString()};c(Qe=>[...Qe,Ae]),p(""),b(""),x([]),h(!1),_.current=null,N.current?.resolve(),N.current=null;const Oe=M.current.trim();Oe&&(M.current="",k(""),C(Oe))},onError:je=>{if(he(),p(""),b(""),x([]),h(!1),_.current=null,console.error("[useQuickChat] Stream error:",je),n?.("Failed to get response","error"),N.current?.reject(new Error(typeof je=="string"?je:"Failed to get response")),N.current=null,!S.current){const Ae=M.current.trim();Ae&&(M.current="",k(""),C(Ae))}$()}};_.current=fw(s.id,L,ae,P,e)});return j.catch(()=>{}),j},[s,m,e,n,$]);return a.useEffect(()=>()=>{_.current&&(_.current.close(),_.current=null)},[]),a.useMemo(()=>({activeSession:s,sessionsLoading:r,messages:l,messagesLoading:u,isStreaming:m,streamingText:f,streamingThinking:g,streamingToolCalls:v,pendingMessage:y,sendMessage:C,stopStreaming:J,clearPendingMessage:Q,switchSession:R,startModelChat:z,startFreshSession:B,loadMessages:K,reloadMessages:$}),[s,r,l,u,m,f,g,v,y,C,J,Q,R,z,B,K,$])}function iI(e,n){const[s,i]=a.useState([]),[r,o]=a.useState(null),[l,c]=a.useState(!1),u=a.useCallback(async f=>{c(!0);try{const p=n?.filterState,g=p&&p!=="all"?{state:p}:void 0,b=n?.showSystemAgents??!1,v=await Ea({...g,...f,includeEphemeral:f?.includeEphemeral??b},e),x=Array.from(new Map(v.map(y=>[y.id,y])).values());i(x)}catch(p){console.error("Failed to load agents:",p)}finally{c(!1)}},[e,n?.filterState,n?.showSystemAgents]),d=a.useCallback(async()=>{try{const f=await Kj(e);o(f)}catch(f){console.error("Failed to load agent stats:",f)}},[e]);a.useEffect(()=>{u(),d()},[u,d]),a.useEffect(()=>{const f=e?`?projectId=${encodeURIComponent(e)}`:"",p=()=>{u(),d()};return Ks(`/api/events${f}`,{events:{"agent:created":p,"agent:updated":p,"agent:deleted":p,"agent:stateChanged":p}})},[e,u,d]);const m=n?.showSystemAgents??!1,h=s.filter(f=>f.state!=="active"&&f.state!=="running"?!1:m||!Dw(f));return{agents:s,activeAgents:h,stats:r,isLoading:l,loadAgents:u,loadStats:d}}function aI({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=jw(l.path),d=l.name;return t.jsxs("li",{className:`file-mention-popup-item${c===i?" file-mention-popup-item--selected":""}`,onClick:()=>r(l),onMouseEnter:()=>{},role:"option","aria-selected":c===i,"data-testid":`file-mention-item-${c}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(Zh,{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 rI=200;function oI(e={}){const{projectId:n,workspace:s="project"}=e,[i,r]=a.useState(!1),[o,l]=a.useState(""),[c,u]=a.useState(-1),[d,m]=a.useState([]),[h,f]=a.useState(!1),[p,g]=a.useState(0),b=a.useRef(null),v=a.useRef(null);a.useEffect(()=>()=>{b.current&&clearTimeout(b.current),v.current?.abort()},[]);const x=a.useCallback((w,M)=>{if(M<0||M>w.length){r(!1);return}const N=D=>/[a-zA-Z0-9/_.-]/.test(D);for(let D=M-1;D>=0;D--){if(w[D]==="#")if(D===0){const E=w.slice(D+1,M);u(D),l(E),g(0),r(!0);return}else{const E=w[D-1];if(/[\s,.;:!?'"()[\]{}]/.test(E)){const T=w.slice(D+1,M);u(D),l(T),g(0),r(!0);return}r(!1);return}if(!N(w[D])){r(!1);return}}r(!1)},[]),y=a.useCallback(()=>{r(!1),l(""),u(-1),m([]),g(0),f(!1)},[]),k=a.useCallback(async w=>{if(!w.trim()){m([]),f(!1);return}v.current?.abort(),v.current=new AbortController;try{f(!0);const M=await tj(w,s,n);m(M.files),g(0)}catch(M){M.name!=="AbortError"&&m([])}finally{f(!1)}},[s,n]);a.useEffect(()=>{if(i)return b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{k(o)},rI),()=>{b.current&&clearTimeout(b.current)}},[o,i,k]);const _=a.useCallback((w,M)=>{if(!i||c<0)return M;const N=M.slice(0,c),D=M.slice(c+1),E=D.match(/[\s]|$/),T=E?E.index:D.length,U=D.slice(T);return`${N}#${w.path}${U}`},[i,c]),S=a.useCallback((w,M)=>{if(!i||d.length===0)return!1;switch(w.key){case"ArrowDown":return w.preventDefault(),g(N=>Math.min(N+1,d.length-1)),!0;case"ArrowUp":return w.preventDefault(),g(N=>Math.max(N-1,0)),!0;case"Enter":case"Tab":return d[p]?(w.preventDefault(),!0):!1;case"Escape":return w.preventDefault(),y(),!0;default:return!1}},[i,d,p,y]);return{mentionActive:i,files:d,loading:h,mentionQuery:o,selectedIndex:p,setSelectedIndex:g,detectMention:x,selectFile:_,dismissMention:y,handleKeyDown:S}}const lI=30,cI=16,dI=16;function uI(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let bo=null;function jg(){return bo===null&&(bo=window.visualViewport?.height??window.innerHeight),bo}function mI(e){const n=jg();e>n&&(bo=e)}function hI(e){return e?e instanceof HTMLTextAreaElement?!0:e instanceof HTMLInputElement?!new Set(["checkbox","radio","button","submit","reset","file","range","color","hidden"]).has(e.type):e instanceof HTMLElement&&e.isContentEditable:!1}function pI(){if(typeof window>"u"||!window.visualViewport)return{overlap:0,open:!1,vvHeight:null};const e=window.visualViewport,n=hI(document.activeElement);n||mI(e.height);const s=Math.max(0,window.innerHeight-e.offsetTop-e.height);if(s>0)return{overlap:s,open:!0,vvHeight:e.height};const i=jg(),r=Math.max(0,i-e.offsetTop-e.height);if(r>=lI)return{overlap:r,open:!0,vvHeight:e.height};if(r>=cI&&n)return{overlap:r,open:!0,vvHeight:e.height};const o=Math.max(0,i-e.height);return n&&o>=dI?{overlap:0,open:!0,vvHeight:e.height}:{overlap:0,open:!1,vvHeight:null}}function kg({enabled:e=!0}={}){const[n,s]=a.useState(0),[i,r]=a.useState(null),[o,l]=a.useState(!1);return a.useEffect(()=>{if(!e||!uI()){s(0),r(null),l(!1);return}const c=window.visualViewport;if(!c){s(0),r(null),l(!1);return}const u=()=>{const d=pI();s(d.overlap),r(d.vvHeight),l(d.open)};return u(),c.addEventListener("resize",u),c.addEventListener("scroll",u),document.addEventListener("focusin",u),document.addEventListener("focusout",u),()=>{c.removeEventListener("resize",u),c.removeEventListener("scroll",u),document.removeEventListener("focusin",u),document.removeEventListener("focusout",u),s(0),r(null),l(!1)}},[e]),{keyboardOverlap:n,viewportHeight:i,keyboardOpen:o}}function fI(e){return`${e.name?.trim()||e.id} (${e.role})`}function gI(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 bI(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 xo(e,n){return e.length<=n?e:`${e.slice(0,n)}…`}function xI(e){if(!e)return null;const n=Object.entries(e);return n.length===0?null:n.map(([s,i])=>{const r=typeof i=="string"?i:(()=>{try{return JSON.stringify(i)}catch{return String(i)}})();return`${s}=${xo(r,50)}`}).join(", ")}function vI(e){if(e===void 0)return null;if(typeof e=="string")return xo(e,200);try{return xo(JSON.stringify(e),200)}catch{return xo(String(e),200)}}function wg(e,n=!1){if(!e||e.length===0)return null;const s=(f,p)=>{const g=f.status==="running",b=f.status==="completed"&&f.isError,v=xI(f.args),x=vI(f.result),y=g?v:x?`result: ${x}`:v?`args: ${v}`:null,k=n?null:y,_=g?"running":b?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${g?" chat-tool-call--running":""}${b?" chat-tool-call--error":""}`,open:g,children:[t.jsxs("summary",{children:[t.jsx("span",{className:"chat-tool-call-status-dot","aria-hidden":"true"}),t.jsx("span",{className:"chat-tool-call-name",title:f.toolName,children:f.toolName}),k&&t.jsx("span",{className:"chat-tool-call-preview",title:k,children:k}),t.jsx("span",{className:"chat-tool-call-status-text",children:_})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[v&&t.jsxs("div",{className:"chat-tool-call-row",children:[t.jsx("span",{className:"chat-tool-call-label",children:"args"}),t.jsx("span",{className:"chat-tool-call-value",children:v})]}),x&&t.jsxs("div",{className:`chat-tool-call-row${b?" chat-tool-call-row--error":""}`,children:[t.jsx("span",{className:"chat-tool-call-label",children:"result"}),t.jsx("span",{className:"chat-tool-call-value",children:x})]})]})]},`${f.toolName}-${p}`)},i=`chat-tool-calls${n?" chat-tool-calls--compact":""}`;if(e.length===1)return t.jsxs("div",{className:i,"data-testid":"chat-tool-calls",children:[t.jsxs("div",{className:"chat-tool-calls-header",children:[t.jsx(Bd,{size:12,"aria-hidden":"true"}),t.jsx("span",{children:"Tool calls"})]}),s(e[0],0)]});const r=e.filter(f=>f.status==="running").length,o=e.filter(f=>f.status==="completed"&&f.isError).length,l=r>0,c=Array.from(new Set(e.map(f=>f.toolName))),u=c.slice(0,5),d=Math.max(0,c.length-u.length),m=d>0?`${u.join(", ")}, +${d} more`:u.join(", "),h=l?`(${r} running)`:o>0?`(${o} ${o===1?"error":"errors"})`:null;return t.jsx("div",{className:i,"data-testid":"chat-tool-calls",children:t.jsxs("details",{className:`chat-tool-calls-group${n?" chat-tool-calls-group--compact":""}`,"data-testid":"chat-tool-calls-group",open:l,children:[t.jsxs("summary",{className:"chat-tool-calls-group-summary",children:[t.jsx(Bd,{size:12,"aria-hidden":"true"}),t.jsxs("span",{className:"chat-tool-calls-count",children:[e.length," tool calls"]}),t.jsx("span",{className:"chat-tool-calls-names",title:m,children:m}),h&&t.jsx("span",{className:"chat-tool-calls-group-status",children:h})]}),e.map((f,p)=>s(f,p))]})})}const Ng={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 yI(e,n){const s=e.slice(0,n),i=/(^|[\s])@([\w-]*)$/.exec(s);if(!i)return null;const r=i[2]??"",o=s.length-r.length-1;return{filter:r,start:o,end:n}}const po={width:320,height:400},jI=new Set(["image/png","image/jpeg","image/gif","image/webp","text/plain","application/json","text/yaml","text/x-log","text/csv","application/xml","text/markdown"]),kI=[".png",".jpg",".jpeg",".gif",".webp",".txt",".json",".yaml",".yml",".log",".csv",".xml",".md"];function wI(e){return e.type.startsWith("image/")}function NI(e){if(jI.has(e.type))return!0;const n=e.name.toLowerCase();return kI.some(s=>n.endsWith(s))}const oa={width:280,height:260},Lo=768,la=8;function SI(e,n){const s=a.useCallback(()=>{if(typeof window>"u")return 0;const b=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return b&&parseFloat(b)||0},[]),i=a.useCallback(()=>typeof window<"u"&&window.innerWidth<=768?{x:4,y:4+s()}:{x:24,y:24+s()},[s]),[r,o]=a.useState(()=>{if(typeof window>"u")return i();const b=`fusion-quick-chat-position-${e||"default"}`;try{const v=localStorage.getItem(b);if(v){const x=JSON.parse(v);if(typeof x.x=="number"&&typeof x.y=="number"&&!isNaN(x.x)&&!isNaN(x.y))return x}}catch{}return i()}),[l,c]=a.useState(!1),u=a.useRef(null),d=n??a.useRef(!1),m=a.useCallback(b=>{if(typeof window>"u")return b;const v=48,x=window.innerWidth<=768?4:8,y=window.innerWidth<=768?44:0,k=window.innerWidth>768?s():0,_=window.innerWidth-v-x,S=window.innerHeight-v-x-y-k;return{x:Math.max(x,Math.min(_,b.x)),y:Math.max(x,Math.min(S,b.y))}},[s]),h=a.useCallback(b=>{if(typeof window>"u")return;const v=`fusion-quick-chat-position-${e||"default"}`;try{localStorage.setItem(v,JSON.stringify(b))}catch{}},[e]),f=a.useCallback(b=>{if(b.button!==0&&b.pointerType==="mouse")return;const x=b.target.closest(".quick-chat-fab");x&&(b.preventDefault(),typeof x.setPointerCapture=="function"&&x.setPointerCapture(b.pointerId),u.current={x:r.x,y:r.y,pointerX:b.clientX,pointerY:b.clientY},d.current=!1,c(!0),document.body.style.userSelect="none")},[r]),p=a.useCallback(b=>{if(!u.current||!l)return;const v=b.clientX-u.current.pointerX,x=b.clientY-u.current.pointerY;if((Math.abs(v)>=5||Math.abs(x)>=5)&&(d.current=!0),d.current){const y=u.current.x-v,k=u.current.y-x,_=m({x:y,y:k});o(_)}},[l,m]),g=a.useCallback(b=>{if(!u.current)return;const v=b.target.closest(".quick-chat-fab");if(v&&typeof v.releasePointerCapture=="function"&&v.releasePointerCapture(b.pointerId),c(!1),document.body.style.userSelect="",!d.current){u.current=null;return}h(r),u.current=null,d.current=!1},[r,h]);return{position:r,isDragging:l,handlePointerDown:f,handlePointerMove:p,handlePointerUp:g}}function CI(e,n,s){const i=`fusion:quick-chat-size-${e||"default"}`,r=a.useCallback(()=>typeof window<"u"&&window.innerWidth>Lo,[]),o=a.useCallback((f,p,g)=>{if(typeof window>"u")return f;const b=Math.max(oa.width,window.innerWidth-p-la),v=Math.max(oa.height,window.innerHeight-g-la);return{width:Math.max(oa.width,Math.min(b,f.width)),height:Math.max(oa.height,Math.min(v,f.height))}},[]),l=a.useCallback(()=>{if(typeof window>"u"||window.innerWidth<=Lo)return po;try{const f=localStorage.getItem(i);if(!f)return po;const p=JSON.parse(f);return typeof p.width!="number"||typeof p.height!="number"?po:{width:p.width,height:p.height}}catch{return po}},[i]),[c,u]=a.useState(l),[d,m]=a.useState({right:0,bottom:0});a.useEffect(()=>{if(!r())return;const f={right:n+d.right,bottom:s+d.bottom};u(p=>o(p,f.right,f.bottom))},[o,r,n,s,d]),a.useEffect(()=>{if(r())try{localStorage.setItem(i,JSON.stringify(c))}catch{}},[r,c,i]);const h=a.useCallback(f=>{if(!r())return;const p=f.currentTarget.dataset.resizeDirection;if(!p)return;f.preventDefault(),f.stopPropagation();const g=f.currentTarget;typeof g.setPointerCapture=="function"&&g.setPointerCapture(f.pointerId);const b={pointerX:f.clientX,pointerY:f.clientY,width:c.width,height:c.height,anchorRight:d.right,anchorBottom:d.bottom};document.body.style.userSelect="none";const v=y=>{const k=y.clientX-b.pointerX,_=y.clientY-b.pointerY;let S=b.width,w=b.height,M=b.anchorRight,N=b.anchorBottom;if(p.includes("w")&&(S=b.width-k),p.includes("e")){const $=k;S=b.width+$,M=b.anchorRight-$}if(p.includes("n")&&(w=b.height-_),p.includes("s")){const $=_;w=b.height+$,N=b.anchorBottom-$}const D=n+M,E=s+N,T=o({width:S,height:w},D,E),U=Math.max(la-n,Math.min(window.innerWidth-n-oa.width-la,M)),K=Math.max(la-s,Math.min(window.innerHeight-s-oa.height-la,N));u(T),m({right:U,bottom:K})},x=y=>{typeof g.releasePointerCapture=="function"&&g.releasePointerCapture(y.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",x);try{localStorage.setItem(i,JSON.stringify({width:c.width,height:c.height}))}catch{}};document.addEventListener("pointermove",v),document.addEventListener("pointerup",x)},[d.bottom,d.right,o,s,n,r,c.height,c.width,i]);return{panelSize:c,anchorOffset:d,handleResizeStart:h}}const EI=a.memo(function({message:n,forcePlain:s,mentionAgentsByName:i,onToggleRender:r}){const o=n.role==="user",l=a.useMemo(()=>{if(!o)return null;const u=n.content,d=/@([\w-]+)/g,m=[];let h=0,f=d.exec(u);for(;f;){const[p,g=""]=f,b=f.index;b>h&&m.push(u.slice(h,b));const v=g.replace(/_/g," ").toLowerCase(),x=i.get(v);x?m.push(t.jsxs("span",{className:"chat-mention-chip",children:["@",x.name.replace(/\s+/g,"_")]},`${x.id}-${b}`)):m.push(p),h=b+p.length,f=d.exec(u)}return h<u.length&&m.push(u.slice(h)),m.length===0?u:m},[o,n.content,i]),c=a.useMemo(()=>o?null:s?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:n.content}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(ai,{remarkPlugins:[ri],components:Ng,children:n.content})}),[o,s,n.content]);return t.jsxs("div",{className:`quick-chat-panel-message ${o?"quick-chat-panel-message--sent":"quick-chat-panel-message--received"}`,"data-testid":`quick-chat-message-${n.id}`,children:[o?t.jsx("p",{children:l}):t.jsxs(t.Fragment,{children:[c,t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${s?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":s?"Show rendered markdown":"Show plain text",onClick:()=>r(n.id),children:s?t.jsx(sd,{size:14}):t.jsx(Ca,{size:14})})]}),wg(n.toolCalls,!0)]})});function _I({projectId:e,addToast:n,showFAB:s=!0,open:i,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:c,onToggleModelFavorite:u}){const{agents:d}=iI(e),[m,h]=a.useState(!1),f=i!==void 0,p=f?i:m,g=f?Ce=>{r?.(typeof Ce=="function"?Ce(p):Ce)}:h,{keyboardOverlap:b,viewportHeight:v,keyboardOpen:x}=kg({enabled:p}),y=x?{"--keyboard-overlap":`${b}px`,...v!==null?{"--vv-height":`${v}px`}:{}}:{},[k,_]=a.useState("agent"),[S,w]=a.useState(""),[M,N]=a.useState([]),[D,E]=a.useState(!1),[T,U]=a.useState(""),[K,$]=a.useState(""),[R,z]=a.useState(""),[B,J]=a.useState(""),[Q,C]=a.useState(!1),[L,P]=a.useState(0),[j,O]=a.useState(-1),[H,ge]=a.useState(()=>new Set),[be,se]=a.useState([]),[me,F]=a.useState(!1),[,de]=a.useState(!1),[ne,xe]=a.useState({top:0,left:0}),oe=oI({projectId:e}),he=a.useCallback(Ce=>{if(!Ce||!oe.mentionActive)return;const st=Ce.getBoundingClientRect();xe({top:st.top-260,left:st.left+8})},[oe.mentionActive]),ae=a.useRef(!1),je=a.useRef(!1),Ae=a.useRef(""),Oe=a.useRef(0),Qe=a.useRef(null),Xe=a.useRef(0),{position:Ye,isDragging:it,handlePointerDown:Be,handlePointerMove:Ge,handlePointerUp:re}=SI(e,ae),ke=Ye.y+60,{panelSize:X,anchorOffset:Te,handleResizeStart:Le}=CI(e,Ye.x,ke),fe=typeof window<"u"&&window.innerWidth>Lo,{activeSession:_e,messages:Ue,isStreaming:nt,streamingText:ve,streamingThinking:ce,streamingToolCalls:De,sessionsLoading:ue,messagesLoading:Re,sendMessage:Ke,stopStreaming:Pe,pendingMessage:ft,clearPendingMessage:Z,switchSession:le,startModelChat:we,startFreshSession:Ze}=sI(e,n),te=a.useRef(null),Je=a.useRef(null),dt=a.useRef(null),ut=a.useRef(null),Ct=a.useRef(null),yt=a.useRef([]),bt=a.useRef(!1),At=T||K,Rt=a.useMemo(()=>gI(At),[At]),Ht=a.useMemo(()=>M.find(Ce=>`${Ce.provider}/${Ce.id}`===At)??null,[M,At]),Et=a.useMemo(()=>bI(Ht,Rt),[Ht,Rt]),Dt=a.useMemo(()=>k==="model"?Rt?`${Ld}::${Rt.modelProvider}/${Rt.modelId}`:"":S?`${S}::`:"",[k,Rt,S]),Kt=k==="agent"?!!S:!!Rt,$t=!Kt||!_e;a.useEffect(()=>{if(d.length===0){w(""),_("model");return}d.some(st=>st.id===S)||w(d[0]?.id??"")},[d,S]),a.useEffect(()=>{!p||je.current||(je.current=!0,E(!0),ms().then(Ce=>{const st=Ce.models??[];if(N(st),T||st.length===0)return;const ht=Ce.defaultProvider,Mt=Ce.defaultModelId;if(ht&&Mt){const En=`${ht}/${Mt}`;if(st.some(nn=>`${nn.provider}/${nn.id}`===En)){$(En),U(En),_("model");return}}$("");const ln=st[0];ln&&U(`${ln.provider}/${ln.id}`)}).catch(Ce=>{console.error("[QuickChatFAB] Failed to load models:",Ce),N([]),$("")}).finally(()=>{E(!1)}))},[p,d.length,T]),a.useEffect(()=>{if(!p){Ae.current="";return}if(!Dt){Ae.current="";return}const Ce=Dt===Ae.current&&!_e&&!ue;if(!(Dt===Ae.current&&!Ce)){if(Ae.current=Dt,k==="model"&&Rt){we(Rt.modelProvider,Rt.modelId);return}k==="agent"&&S&&le(S)}},[p,k,Rt,S,Dt,_e,ue,we,le]),a.useEffect(()=>{p||(C(!1),J(""),O(-1),yt.current.forEach(Ce=>{Ce.previewUrl&&URL.revokeObjectURL(Ce.previewUrl)}),se([]))},[p]),a.useEffect(()=>{yt.current=be},[be]),a.useEffect(()=>{if(!p){bt.current=!1;return}typeof window>"u"||(bt.current=window.innerWidth<=Lo)},[p]),a.useEffect(()=>{if(!p||$t||!bt.current)return;const Ce=ut.current;if(!Ce)return;const st=document.activeElement,ht=st?te.current?.contains(st):!1,Mt=st===document.body;if(!ht&&!Mt){bt.current=!1;return}const ln=requestAnimationFrame(()=>{Ce.focus(),bt.current=!1});return()=>cancelAnimationFrame(ln)},[p,$t]),a.useEffect(()=>()=>{yt.current.forEach(Ce=>{Ce.previewUrl&&URL.revokeObjectURL(Ce.previewUrl)})},[]);const Ft=a.useCallback(Ce=>{w(Ce)},[]),Ot=a.useCallback(Ce=>{U(Ce)},[]),Tt=a.useCallback(()=>{!Kt||ue||Ze()},[Kt,ue,Ze]),Pt=a.useMemo(()=>d.find(Ce=>Ce.id===S)??null,[d,S]),wt=a.useMemo(()=>{const Ce=B.trim().toLowerCase();return Ce?d.filter(st=>st.name.toLowerCase().includes(Ce)):d},[d,B]),Gt=a.useMemo(()=>{const Ce=new Map;for(const st of d)Ce.set(st.name.toLowerCase(),st);return Ce},[d]);a.useEffect(()=>{P(0)},[B,Q]),a.useEffect(()=>()=>{Qe.current!==null&&(window.clearTimeout(Qe.current),Qe.current=null)},[]),a.useEffect(()=>{if(!p)return;const Ce=ht=>{const Mt=ht.target;te.current?.contains(Mt)||Je.current?.contains(Mt)||Mt.closest(".model-combobox-dropdown--portal")||g(!1)},st=ht=>{ht.key==="Escape"&&g(!1)};return document.addEventListener("mousedown",Ce),document.addEventListener("keydown",st),()=>{document.removeEventListener("mousedown",Ce),document.removeEventListener("keydown",st)}},[p,g]),a.useEffect(()=>{if(!p)return;const Ce=dt.current;Ce&&(Ce.scrollTop=Ce.scrollHeight)},[Ue,ve,ce,p]);const Ut=a.useMemo(()=>k==="agent"?Pt?`Message ${Pt.name||Pt.id}`:"Select an agent to start chatting":Et?`Message ${Et}`:"Select a model to start chatting",[k,Pt,Et]),q=ft.length>50?`${ft.slice(0,50)}…`:ft,pe=a.useCallback(Ce=>{if(!Ce||Ce.length===0)return;const st=[];for(let ht=0;ht<Ce.length;ht+=1){const Mt=Ce[ht];NI(Mt)&&st.push({file:Mt,previewUrl:wI(Mt)?URL.createObjectURL(Mt):""})}st.length>0&&se(ht=>[...ht,...st])},[]),$e=a.useCallback(Ce=>{se(st=>{const ht=st[Ce];return ht?.previewUrl&&URL.revokeObjectURL(ht.previewUrl),st.filter((Mt,ln)=>ln!==Ce)})},[]),A=a.useCallback(Ce=>{pe(Ce.clipboardData?.files)},[pe]),ee=a.useCallback(async()=>{const Ce=R.trim(),st=yt.current;if(!(!Ce&&st.length===0)&&!$t){z(""),C(!1),J(""),O(-1);try{await Ke(Ce,st.map(ht=>ht.file)),st.forEach(ht=>{ht.previewUrl&&URL.revokeObjectURL(ht.previewUrl)}),se(ht=>ht.filter(Mt=>!st.includes(Mt)))}catch{}}},[Ke,$t,R]),ze=a.useCallback(Ce=>{Ce.preventDefault(),Xe.current+=1,F(!0)},[]),mt=a.useCallback(Ce=>{Ce.preventDefault(),Ce.dataTransfer.dropEffect="copy",F(!0)},[]),jt=a.useCallback(Ce=>{Ce.preventDefault(),Xe.current=Math.max(0,Xe.current-1),Xe.current===0&&F(!1)},[]),Lt=a.useCallback(Ce=>{Ce.preventDefault(),Xe.current=0,F(!1),pe(Ce.dataTransfer?.files)},[pe]),_t=a.useCallback((Ce,st)=>{const ht=yI(Ce,st);if(ht){C(!0),J(ht.filter),O(ht.start);return}C(!1),J(""),O(-1)},[]),Jt=a.useCallback(Ce=>{const st=ut.current;if(!st||j<0)return;const ht=st.selectionStart??Oe.current,Mt=st.selectionEnd??ht,ln=Math.max(ht,Mt),En=Math.min(j,ln),nn=`${`@${Ce.name.replace(/\s+/g,"_")}`} `,An=R.slice(0,En)+nn+R.slice(ln),Un=En+nn.length;z(An),C(!1),J(""),P(0),O(-1),window.requestAnimationFrame(()=>{ut.current&&(ut.current.focus(),ut.current.setSelectionRange(Un,Un))})},[j,R]),Dn=a.useCallback(Ce=>{const st=Ce.target.value,ht=Ce.target.selectionStart??st.length;Oe.current=ht,z(st),_t(st,ht),oe.detectMention(st,ht),de(oe.mentionActive),oe.mentionActive&&he(Ce.target)},[_t,oe,he]),Pn=a.useCallback(()=>{Qe.current!==null&&window.clearTimeout(Qe.current),Qe.current=window.setTimeout(()=>{C(!1),J(""),O(-1),de(!1),oe.dismissMention(),Qe.current=null},120)},[oe]),Yt=a.useCallback(()=>{Qe.current!==null&&(window.clearTimeout(Qe.current),Qe.current=null)},[]),Cn=a.useCallback(Ce=>{const st=Ce.currentTarget,ht=st.selectionStart??st.value.length;Oe.current=ht,_t(st.value,ht),oe.detectMention(st.value,ht),de(oe.mentionActive),oe.mentionActive&&he(st)},[_t,oe,he]),Ne=a.useCallback(Ce=>{Ce.key!=="Escape"&&Cn(Ce)},[Cn]),at=a.useCallback(Ce=>{ge(st=>{const ht=new Set(st);return ht.has(Ce)?ht.delete(Ce):ht.add(Ce),ht})},[]),fn=a.useCallback((Ce,st=!1)=>st?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:Ce}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(ai,{remarkPlugins:[ri],components:Ng,children:Ce})}),[]),jn=a.useCallback(Ce=>{if(Oe.current=Ce.currentTarget.selectionStart??Oe.current,oe.mentionActive&&oe.files.length>0){if(oe.handleKeyDown(Ce,R),Ce.key==="Enter"||Ce.key==="Tab"){const st=oe.files[oe.selectedIndex];if(st){const ht=oe.selectFile(st,R);z(ht),oe.dismissMention(),de(!1)}}return}if(Q&&Ce.key==="ArrowDown"){Ce.preventDefault(),wt.length>0&&P(st=>(st+1)%wt.length);return}if(Q&&Ce.key==="ArrowUp"){Ce.preventDefault(),wt.length>0&&P(st=>st===0?wt.length-1:st-1);return}if(Q&&Ce.key==="Enter"){Ce.preventDefault();const st=wt[L]??wt[0];st&&Jt(st);return}if(Q&&Ce.key==="Escape"){Ce.preventDefault(),Ce.stopPropagation(),C(!1),J(""),O(-1);return}Ce.key!=="Enter"||Ce.shiftKey||(Ce.preventDefault(),ee())},[Q,wt,L,Jt,ee,oe,R]),In=a.useCallback(()=>{if(ae.current){ae.current=!1;return}g(Ce=>!Ce)},[g]);return t.jsxs(t.Fragment,{children:[s&&t.jsx("button",{ref:Je,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":it?"true":"false",style:{right:Ye.x,bottom:Ye.y},onPointerDown:Be,onPointerMove:Ge,onPointerUp:re,onClick:In,children:t.jsx(wi,{size:24})}),p&&t.jsxs("div",{className:"quick-chat-panel",ref:te,"data-testid":"quick-chat-panel",style:{right:Ye.x+Te.right,bottom:ke+Te.bottom,...fe?{width:X.width,height:X.height}:{},...y},children:[fe&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"n","data-testid":"quick-chat-resize-n",onPointerDown:Le,role:"separator","aria-orientation":"horizontal","aria-label":"Resize panel from top"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"s","data-testid":"quick-chat-resize-s",onPointerDown:Le,role:"separator","aria-orientation":"horizontal","aria-label":"Resize panel from bottom"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"e","data-testid":"quick-chat-resize-e",onPointerDown:Le,role:"separator","aria-orientation":"vertical","aria-label":"Resize panel from right"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"w","data-testid":"quick-chat-resize-w",onPointerDown:Le,role:"separator","aria-orientation":"vertical","aria-label":"Resize panel from left"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"nw","data-testid":"quick-chat-resize-nw",onPointerDown:Le,role:"separator","aria-label":"Resize panel from top-left corner"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"ne","data-testid":"quick-chat-resize-ne",onPointerDown:Le,role:"separator","aria-label":"Resize panel from top-right corner"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"sw","data-testid":"quick-chat-resize-sw",onPointerDown:Le,role:"separator","aria-label":"Resize panel from bottom-left corner"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"se","data-testid":"quick-chat-resize-se",onPointerDown:Le,role:"separator","aria-label":"Resize panel from bottom-right corner"})]}),t.jsxs("div",{className:"quick-chat-panel-header",children:[t.jsxs("div",{className:"quick-chat-panel-title-wrap",children:[t.jsx("h3",{children:"Quick Chat"}),k==="model"&&Et&&t.jsx("span",{className:"quick-chat-model-tag","data-testid":"quick-chat-model-tag",title:Et,children:Et})]}),t.jsxs("div",{className:"quick-chat-panel-header-actions",children:[d.length>0&&t.jsxs("div",{className:"quick-chat-header-mode-toggle","data-testid":"quick-chat-mode-toggle",children:[t.jsx("button",{type:"button",className:`quick-chat-mode-btn${k==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-mode-agent",onClick:()=>{_("agent"),U("")},"aria-label":"Switch to agent mode",title:"Agent mode",children:"Agent"}),t.jsx("button",{type:"button",className:`quick-chat-mode-btn${k==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-mode-model",onClick:()=>{_("model"),w("")},"aria-label":"Switch to model mode",title:"Model mode",children:"Model"})]}),t.jsx("button",{type:"button",className:"btn-icon quick-chat-new-chat-btn","data-testid":"quick-chat-new-thread","aria-label":"Start a new chat",onClick:Tt,disabled:!Kt||ue,children:t.jsx(on,{size:16})}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":"Close quick chat","data-testid":"quick-chat-close",onClick:()=>g(!1),children:t.jsx(Wt,{size:16})})]})]}),k==="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:S,onChange:Ce=>Ft(Ce.target.value),"data-testid":"quick-chat-agent-select",children:d.map(Ce=>t.jsx("option",{value:Ce.id,children:fI(Ce)},Ce.id))})]}),k==="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(Yn,{id:"quick-chat-model-override",models:M,value:T,onChange:Ot,label:"Select model override",placeholder:D?"Loading models…":"Select a model",disabled:D||M.length===0,favoriteProviders:o,favoriteModels:l,onToggleFavorite:c,onToggleModelFavorite:u})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:dt,"data-testid":"quick-chat-messages",children:ue||Re?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):Ue.length===0&&!ve&&!ce&&!nt?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[Ue.map(Ce=>t.jsx(EI,{message:Ce,forcePlain:Ce.role!=="user"&&H.has(Ce.id),mentionAgentsByName:Gt,onToggleRender:at},Ce.id)),nt&&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:[ve?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:fn(ve,H.has("__streaming__"))}),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${H.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":H.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>at("__streaming__"),children:H.has("__streaming__")?t.jsx(sd,{size:14}):t.jsx(Ca,{size:14})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:"Thinking…"}),wg(De,!0),ce&&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:ce})]})]})]})}),be.length>0&&t.jsx("div",{className:"quick-chat-attachment-previews","data-testid":"quick-chat-attachment-previews",children:be.map((Ce,st)=>t.jsxs("div",{className:"quick-chat-attachment-preview","data-testid":`quick-chat-attachment-preview-${st}`,children:[Ce.previewUrl?t.jsx("img",{src:Ce.previewUrl,alt:Ce.file.name}):t.jsx("span",{className:"quick-chat-attachment-preview-name",children:Ce.file.name}),t.jsx("button",{type:"button",className:"quick-chat-attachment-remove","data-testid":`quick-chat-attachment-remove-${st}`,"aria-label":`Remove ${Ce.file.name}`,onClick:()=>$e(st),children:"×"})]},`${Ce.file.name}-${st}`))}),t.jsx("div",{className:"quick-chat-panel-input",children:t.jsxs("div",{className:`quick-chat-input-wrapper${me?" quick-chat-input-wrapper--dragover":""}`,onDragEnter:ze,onDragOver:mt,onDragLeave:jt,onDrop:Lt,children:[t.jsx("input",{ref:Ct,type:"file",accept:"image/*,.txt,.json,.yaml,.yml,.log,.csv,.xml,.md",multiple:!0,tabIndex:-1,"aria-hidden":"true",className:"quick-chat-attachment-input",onChange:Ce=>{pe(Ce.target.files),Ce.target.value=""}}),t.jsxs("div",{className:"quick-chat-input-row","data-testid":"quick-chat-input-row",children:[t.jsx("button",{type:"button",className:"btn-icon quick-chat-attach-btn","data-testid":"quick-chat-attach-btn","aria-label":"Attach files",onClick:()=>Ct.current?.click(),children:t.jsx(sp,{size:16})}),t.jsx("input",{ref:ut,type:"text",value:R,onChange:Dn,onKeyDown:jn,onKeyUp:Ne,onClick:Cn,onBlur:Pn,onFocus:Yt,onPaste:A,placeholder:Ut,disabled:$t,"data-testid":"quick-chat-input"}),nt?t.jsx("button",{type:"button",className:"chat-input-stop quick-chat-send-btn",onClick:Pe,"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:t.jsx(js,{size:14})}):t.jsx("button",{type:"button",className:"quick-chat-send-btn",onClick:()=>{ee()},disabled:$t||R.trim().length===0&&be.length===0,"data-testid":"quick-chat-send",children:t.jsx(Li,{size:16})})]}),t.jsx(tI,{agents:d,filter:B,highlightedIndex:L,visible:Q,onSelect:Jt,position:"above"}),t.jsx(aI,{visible:oe.mentionActive&&!Q,position:ne,files:oe.files,selectedIndex:oe.selectedIndex,onSelect:Ce=>{const st=oe.selectFile(Ce,R);z(st),oe.dismissMention(),de(!1),ut.current?.focus()},loading:oe.loading}),ft&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${q}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:Z,children:"×"})]})]})})]})]})}function er(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function Lh(e){return e.status==="generating"||e.status==="awaiting_input"}function tr(e){return e==="complete"||e==="error"}function MI(e){const[n,s]=a.useState([]),i=a.useRef(new Map),r=a.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:c,requestSync:u}=Ma(),d=a.useCallback(()=>{ld(e).then(p=>{const g=p.filter(v=>{const x=er(v.updatedAt),y=r.current.get(v.id);return y===void 0?!0:x<=y?!1:(r.current.delete(v.id),!0)}),b=new Map;for(const v of g)b.set(v.id,er(v.updatedAt));i.current=b,s(g)}).catch(p=>{console.warn("[useBackgroundSessions] Failed to fetch AI sessions:",p)})},[e]);a.useEffect(()=>{u(),d()},[d,u]),a.useEffect(()=>{s(p=>{if(o.size===0)return p;let g=!1;const b=new Map(p.map(v=>[v.id,v]));for(const v of o.values()){if(e&&v.projectId&&v.projectId!==e)continue;const x=v.lastEventTimestamp,y=i.current.get(v.sessionId)??0;if(x<y)continue;const k=r.current.get(v.sessionId);if(k!==void 0&&x<=k)continue;if(k!==void 0&&x>k&&!tr(v.status)&&r.current.delete(v.sessionId),tr(v.status)){b.delete(v.sessionId)&&(g=!0),i.current.set(v.sessionId,x);continue}const _=b.get(v.sessionId),S=v.type??_?.type,w=v.title??_?.title;if(!_&&(!S||!w))continue;const M={id:v.sessionId,type:S??"planning",status:v.status,title:w??"AI Session",projectId:v.projectId??_?.projectId??e??null,lockedByTab:v.owningTabId??_?.lockedByTab??null,updatedAt:v.updatedAt??_?.updatedAt??new Date(x).toISOString()},N=b.get(v.sessionId);(!N||N.status!==M.status||N.title!==M.title||N.type!==M.type||N.projectId!==M.projectId||N.lockedByTab!==M.lockedByTab||N.updatedAt!==M.updatedAt)&&(b.set(v.sessionId,M),i.current.set(v.sessionId,x),g=!0)}return g?[...b.values()].sort((v,x)=>er(x.updatedAt)-er(v.updatedAt)):p})},[e,o]),a.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",g=v=>{try{const x=JSON.parse(v.data),y=er(x.updatedAt)||Date.now();s(k=>{const _=i.current.get(x.id)??0;if(y<_)return k;const S=r.current.get(x.id);if(S!==void 0&&y<=S)return k;if(S!==void 0&&y>S&&!tr(x.status)&&r.current.delete(x.id),i.current.set(x.id,y),tr(x.status))return k.filter(M=>M.id!==x.id);const w=k.findIndex(M=>M.id===x.id);if(w>=0){const M=[...k];return M[w]=x,M}return Lh(x)?[x,...k]:k}),l({sessionId:x.id,status:x.status,needsInput:x.status==="awaiting_input",type:x.type,title:x.title,projectId:x.projectId,owningTabId:x.lockedByTab,updatedAt:x.updatedAt,timestamp:y}),tr(x.status)&&c({sessionId:x.id,status:x.status,timestamp:y})}catch{}},b=v=>{try{const x=JSON.parse(v.data),y=Date.now();r.current.set(x,y),i.current.set(x,Math.max(i.current.get(x)??0,y)),c({sessionId:x,status:"complete",timestamp:y}),s(k=>k.filter(_=>_.id!==x))}catch{}};return Ks(`/api/events${p}`,{events:{"ai_session:updated":g,"ai_session:deleted":b},onReconnect:()=>{d()}})},[c,l,e,d]);const m=a.useCallback(async p=>{const b=n.find(k=>k.id===p)?.type,v=Ji();let x=!1;if(b==="planning")try{await pp(p,e,v)}catch(k){x=!0,k instanceof Error&&k.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of planning session ${p} despite lock by another tab`)}else if(b==="subtask")try{await bp(p,e,v)}catch(k){x=!0,k instanceof Error&&k.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of subtask session ${p} despite lock by another tab`)}else if(b==="mission_interview")try{await kp(p,e,v)}catch(k){x=!0,k instanceof Error&&k.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of mission interview session ${p} despite lock by another tab`)}x&&console.warn(`[useBackgroundSessions] Cancellation failed for session ${p}, attempting delete anyway`);const y=Date.now();r.current.set(p,y),i.current.set(p,Math.max(i.current.get(p)??0,y)),c({sessionId:p,status:"complete",timestamp:y});try{await wp(p)}catch{}s(k=>k.filter(_=>_.id!==p))},[c,e,n]),h=a.useMemo(()=>n.filter(p=>Lh(p)),[n]),f=a.useMemo(()=>h.filter(p=>p.type==="planning"),[h]);return{sessions:h,generating:h.filter(p=>p.status==="generating").length,needsInput:h.filter(p=>p.status==="awaiting_input").length,planningSessions:f,dismissSession:m,refresh:d}}function Kn(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 zh(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function AI(e,n){return{...n,columnMovedAt:e.columnMovedAt??n.columnMovedAt,executionStartedAt:e.executionStartedAt??n.executionStartedAt,executionCompletedAt:e.executionCompletedAt??n.executionCompletedAt,worktree:n.worktree??e.worktree,modifiedFiles:n.modifiedFiles??e.modifiedFiles,timedExecutionMs:n.timedExecutionMs??e.timedExecutionMs,workflowStepResults:n.workflowStepResults??e.workflowStepResults,tokenUsage:n.tokenUsage??e.tokenUsage,mergeDetails:n.mergeDetails??e.mergeDetails}}function xc(e,n){if(zh(n.updatedAt,e.updatedAt)<0)return e;if(e.column===n.column)return AI(e,n);const i=zh(e.columnMovedAt,n.columnMovedAt);return e.columnMovedAt&&!n.columnMovedAt?{...n,column:e.column,columnMovedAt:e.columnMovedAt}:i>0?{...n,column:e.column,columnMovedAt:e.columnMovedAt}:n}function RI(e){const n=e?.projectId,s=e?.searchQuery,i=e?.sseEnabled??!0,[r,o]=a.useState([]),[l,c]=a.useState(!1),u=a.useRef(l);u.current=l;const d=a.useRef(r),m=a.useRef(0),h=a.useRef(0),f=a.useRef(s),p=a.useRef(null),g=a.useRef(void 0),b=a.useRef(0),v=a.useRef(n);d.current=r,f.current=s,v.current!==n&&(v.current=n,b.current++);const x=1e3,y=a.useCallback(async B=>{const J=++m.current,Q=n,C=B?.searchQueryOverride??f.current,L=B?.includeArchivedOverride??u.current;try{const P=await Fv(void 0,void 0,Q,C,L);if(m.current!==J||n!==Q)return;o(P.map(Kn)),g.current=Date.now()}catch{if(m.current!==J||n!==Q)return;if(B?.clearOnError){o([]);return}o(P=>P)}},[n]);p.current=y;const k=a.useCallback(async()=>{u.current||(c(!0),u.current=!0,await p.current({includeArchivedOverride:!0}))},[]);a.useEffect(()=>{if(s===void 0)return;const B=setTimeout(()=>{y({searchQueryOverride:s})},300);return()=>clearTimeout(B)},[s]),a.useEffect(()=>{y({clearOnError:!0});const B=()=>{if(document.visibilityState!=="visible")return;const J=Date.now();J-h.current<x||(h.current=J,y())};return document.addEventListener("visibilitychange",B),()=>{document.removeEventListener("visibilitychange",B)}},[y]),a.useEffect(()=>{if(i===!1)return;const B=b.current,J=n?`?projectId=${encodeURIComponent(n)}`:"",Q=()=>b.current!==B;let C=!0;const L=be=>{if(Q())return;const se=Kn(JSON.parse(be.data));if(f.current){p.current({searchQueryOverride:f.current});return}o(me=>{const F=me.findIndex(oe=>oe.id===se.id);if(F===-1)return[...me,se];const de=me[F],ne=xc(de,se);if(ne===de)return me;const xe=[...me];return xe[F]=ne,xe}),g.current=Date.now()},P=be=>{if(Q())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:se,to:me}=JSON.parse(be.data),F=Kn(se);o(de=>de.map(ne=>ne.id===F.id?{...F,column:me}:ne)),g.current=Date.now()},j=be=>{if(Q())return;if(f.current){p.current({searchQueryOverride:f.current});return}const se=Kn(JSON.parse(be.data));o(me=>me.map(F=>F.id!==se.id?F:xc(F,se))),g.current=Date.now()},O=be=>{if(Q())return;if(f.current){p.current({searchQueryOverride:f.current});return}const se=Kn(JSON.parse(be.data));o(me=>me.filter(F=>F.id!==se.id))},H=be=>{if(Q())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:se}=JSON.parse(be.data),me=Kn(se);o(F=>F.map(de=>de.id===me.id?{...me,column:"done"}:de))},ge=Ks(`/api/events${J}`,{events:{"task:created":L,"task:moved":P,"task:updated":j,"task:deleted":O,"task:merged":H},onReconnect:()=>{C&&(Q()||p.current())}});return()=>{C=!1,ge()}},[n,i]);const _=a.useCallback(async B=>{const J=Kn(await dp(B,n));return o(Q=>Q.some(C=>C.id===J.id)?Q:[...Q,J]),J},[n]),S=a.useCallback(async(B,J)=>Kn(await Uv(B,J,n)),[n]),w=a.useCallback(async B=>Kn(await up(B,n)),[n]),M=a.useCallback(async B=>Kn(await Bv(B,n)),[n]),N=a.useCallback(async B=>Hv(B,n),[n]),D=a.useCallback(async B=>Kn(await qv(B,n)),[n]),E=a.useCallback(async B=>Kn(await Vv(B,n)),[n]),T=a.useCallback(async B=>{const J=Kn(await Wv(B,n));return o(Q=>Q.some(C=>C.id===J.id)?Q:[...Q,J]),J},[n]),U=a.useCallback(async(B,J)=>{const Q=d.current.find(L=>L.id===B),C=Q?{...Q,...J,updatedAt:new Date().toISOString()}:void 0;C&&o(L=>L.map(P=>P.id===B?C:P));try{const L=Kn(await ni(B,J,n));return o(P=>P.map(j=>j.id===B?L:j)),L}catch(L){throw Q&&o(P=>P.map(j=>j.id===B?Q:j)),L}},[n]),K=a.useCallback(async B=>{const J=Kn(await Gv(B,n));return o(Q=>Q.map(C=>C.id===B?J:C)),J},[n]),$=a.useCallback(async B=>{const J=Kn(await Jv(B,n));return o(Q=>Q.map(C=>C.id===B?J:C)),J},[n]),R=a.useCallback(async()=>{const J=(await Yv(n)).map(Kn);return o(Q=>Q.map(C=>J.find(P=>P.id===C.id)||C)),J},[n]),z=a.useCallback(B=>{if(B.length===0)return;if(f.current){p.current({searchQueryOverride:f.current});return}const J=B.map(Kn);o(Q=>{let C=Q;for(const L of J){const P=C.findIndex(H=>H.id===L.id);if(P===-1){C===Q&&(C=[...Q]),C.push(L);continue}const j=C[P],O=xc(j,L);O!==j&&(C===Q&&(C=[...Q]),C[P]=O)}return C}),g.current=Date.now()},[]);return{tasks:r,createTask:_,moveTask:S,pauseTask:w,deleteTask:M,mergeTask:N,retryTask:D,resetTask:E,duplicateTask:T,updateTask:U,archiveTask:K,unarchiveTask:$,archiveAllDone:R,loadArchivedTasks:k,includeArchived:l,ingestCreatedTasks:z,lastFetchTimeMs:g.current}}const TI=5e3,PI=1e3;function II(){const[e,n]=a.useState([]),[s,i]=a.useState(!0),[r,o]=a.useState(null),l=a.useRef(null),c=a.useRef(0),u=a.useCallback(async()=>{try{o(null);const f=await ru();n(f)}catch(f){o(f instanceof Error?f.message:"Failed to fetch projects")}},[]);a.useEffect(()=>{let f=!1;async function p(){i(!0);const b=performance.now();try{const v=await ru(),y=`initial fetchProjectsAcrossNodes took ${Math.round(performance.now()-b)}ms (${v.length} projects)`;console.log(`[useProjects] ${y}`),or("[useProjects]",y),f||(n(v),o(null))}catch(v){const y=`initial fetch failed after ${Math.round(performance.now()-b)}ms: ${v instanceof Error?v.message:String(v)}`;console.warn(`[useProjects] ${y}`),or("[useProjects]",y),f||o(v instanceof Error?v.message:"Failed to fetch projects")}finally{f||i(!1)}}p();const g=()=>{if(document.visibilityState!=="visible")return;const b=Date.now();b-c.current<PI||(c.current=b,u())};return document.addEventListener("visibilitychange",g),()=>{f=!0,document.removeEventListener("visibilitychange",g)}},[u]),a.useEffect(()=>{if(!s)return l.current=setInterval(()=>{u()},TI),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async f=>{const p=await Xj(f);return n(g=>[...g,p]),p},[]),m=a.useCallback(async(f,p)=>{const g=await ik(f,p);return n(b=>b.map(v=>v.id===f?g:v)),g},[]),h=a.useCallback(async f=>{await vp(f),n(p=>p.filter(g=>g.id!==f))},[]);return{projects:e,loading:s,error:r,refresh:u,register:d,update:m,unregister:h}}const $I="kb-dashboard-current-project";function DI(e){return e??"local"}function LI(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=DI(s);a.useEffect(()=>{let p=!1;async function g(){try{const b=await Gi();if(p)return;d.current=b.dashboardCurrentProjectIdByNode??{};const v=d.current[m];if(v){const x=e.find(y=>y.id===v);x&&(r(x),c.current=!0)}if(!v)try{const x=localStorage.getItem($I);if(x){const y=JSON.parse(x);y?.id&&e.some(_=>_.id===y.id)&&(r(y),c.current=!0,d.current={...d.current,[m]:y.id},await hn({dashboardCurrentProjectIdByNode:d.current}).catch(()=>{}))}}catch{}}catch{}finally{p||l(!1)}}return g(),()=>{p=!0}},[m,e]),a.useEffect(()=>{if(!o){if(i){if(!e.some(b=>b.id===i.id)&&e.length>0){const b=e.find(v=>v.status==="active");r(b||e[0]||null);return}const g={...d.current,[m]:i.id};d.current=g,hn({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}else if(e.length>0&&!u.current){const p=e.find(g=>g.status==="active");p&&r(p)}}},[i,e,o,m]);const h=a.useCallback(p=>{if(u.current=!1,r(p),p){const g={...d.current,[m]:p.id};d.current=g,hn({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}},[m]),f=a.useCallback(()=>{u.current=!0,r(null);const p={...d.current};delete p[m],d.current=p,hn({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[m]);return{currentProject:i,setCurrentProject:h,clearCurrentProject:f,loading:o}}const Sg=a.createContext(null);function zI({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()},[]),vo.createElement(Sg.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function FI(){const e=a.useContext(Sg);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const Cg="kb-dashboard-theme-mode",Eg="kb-dashboard-color-theme",_g=[...Iw],nd="theme-data",vc="theme-data.css";function OI(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.endsWith("/")?e.slice(0,-1)+`/${vc}`:e.replace(/\/[^/]+$/,`/${vc}`):`/${vc}`}const Ps=typeof window<"u",UI=Ps?a.useLayoutEffect:a.useEffect;function Mg(e){return e==="dark"||e==="light"||e==="system"}function Fh(){if(!Ps)return"dark";try{const e=localStorage.getItem(Cg);if(Mg(e))return e}catch{}return"dark"}function Oh(){if(!Ps)return"default";try{const e=localStorage.getItem(Eg);if(e&&_g.includes(e))return e}catch{}return"default"}function Uh(e){if(Ps)try{localStorage.setItem(Cg,e)}catch{}}function Bh(e){if(Ps)try{localStorage.setItem(Eg,e)}catch{}}function BI(e,n){return e==="system"?n?"dark":"light":e}function HI(e,n,s){if(!Ps)return;const i=BI(e,s);document.documentElement.setAttribute("data-theme",i),document.documentElement.setAttribute("data-color-theme",n)}function Hh(){if(!Ps)return;const e=OI(),n=document.getElementById(nd);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=nd,document.head.appendChild(s)}function qh(){if(!Ps)return;const e=document.getElementById(nd);e&&e.remove()}function qI(){const[e,n]=a.useState(()=>Fh()),[s,i]=a.useState(()=>Oh()),[r,o]=a.useState(!0),[l,c]=a.useState(()=>Ps?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(!Ps||!r)return;let g=!1;return Gi().then(b=>{g||(Mg(b.themeMode)&&!m.current&&(u.current!==b.themeMode&&(u.current=b.themeMode,n(b.themeMode)),Fh()!==b.themeMode&&Uh(b.themeMode)),b.colorTheme&&_g.includes(b.colorTheme)&&!h.current&&(d.current!==b.colorTheme&&(d.current=b.colorTheme,i(b.colorTheme)),Oh()!==b.colorTheme&&Bh(b.colorTheme)))}).catch(b=>{console.warn("[useTheme] Failed to hydrate theme from global settings",b)}).finally(()=>{g||o(!1)}),()=>{g=!0}},[r]),a.useEffect(()=>{if(!Ps)return;const g=window.matchMedia("(prefers-color-scheme: dark)"),b=v=>{c(v.matches)};return g.addEventListener("change",b),()=>g.removeEventListener("change",b)},[]),UI(()=>{HI(e,s,l)},[e,s,l]),a.useEffect(()=>{!Ps||r||(s!=="default"?Hh():qh())},[s,r]);const f=a.useCallback(g=>{m.current=!0,u.current=g,n(g),Uh(g),hn({themeMode:g}).catch(b=>{console.warn("[useTheme] Failed to persist themeMode to global settings",b)})},[]),p=a.useCallback(g=>{h.current=!0,d.current=g,i(g),Bh(g),g!=="default"?Hh():qh(),hn({colorTheme:g}).catch(b=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",b)})},[]);return{themeMode:e,colorTheme:s,setThemeMode:f,setColorTheme:p,isSystemDark:l}}function VI(e){const{planningSessions:n}=e,[s,i]=a.useState(!1),[r,o]=a.useState(!1),[l,c]=a.useState(null),[u,d]=a.useState(void 0),[m,h]=a.useState(!1),[f,p]=a.useState(null),[g,b]=a.useState(void 0),[v,x]=a.useState(null),[y,k]=a.useState("definition"),[_,S]=a.useState(!1),[w,M]=a.useState(void 0),[N,D]=a.useState(!1),[E,T]=a.useState(!1),[U,K]=a.useState(!1),[$,R]=a.useState(null),[z,B]=a.useState(!1),[J,Q]=a.useState(!1),[C,L]=a.useState(void 0),[P,j]=a.useState(!1),[O,H]=a.useState("project"),[ge,be]=a.useState(!1),[se,me]=a.useState(!1),[F,de]=a.useState(!1),[ne,xe]=a.useState(!1),[oe,he]=a.useState(!1),[ae,je]=a.useState(!1),[Ae,Oe]=a.useState(!1),Qe=!!(v||_||s||r||m||J||P||ge||se||F||oe||ne||U||z||N||E||ae||Ae),Xe=a.useCallback(()=>i(!0),[]),Ye=a.useCallback(()=>i(!1),[]),it=a.useCallback(()=>o(!0),[]),Be=a.useCallback(q=>{c(q),o(!0)},[]),Ge=a.useCallback(()=>{const q=n[0];q&&(d(q.id),o(!0))},[n]),re=a.useCallback(q=>{d(q),o(!0)},[]),ke=a.useCallback(()=>{o(!1),c(null),d(void 0)},[]),X=a.useCallback(q=>{p(q),h(!0)},[]),Te=a.useCallback(q=>{b(q),h(!0)},[]),Le=a.useCallback(()=>{h(!1),p(null),b(void 0)},[]),fe=a.useCallback((q,pe="definition")=>{x(q),k(pe)},[]),_e=a.useCallback(q=>{x(q),k("changes")},[]),Ue=a.useCallback(q=>{x(pe=>pe&&{...pe,...q})},[]),nt=a.useCallback(()=>{x(null)},[]),ve=a.useCallback(q=>{M(q),S(!0)},[]),ce=a.useCallback(()=>{S(!1),M(void 0)},[]),De=a.useCallback(()=>D(!0),[]),ue=a.useCallback(()=>D(!1),[]),Re=a.useCallback(()=>T(!0),[]),Ke=a.useCallback(()=>T(!1),[]),Pe=a.useCallback(q=>{R(q??null),K(!0)},[]),ft=a.useCallback(()=>{K(!1),R(null)},[]),Z=a.useCallback(()=>B(!0),[]),le=a.useCallback(()=>B(!1),[]),we=a.useCallback(()=>{Q(q=>!q)},[]),Ze=a.useCallback(()=>{Q(!1),L(void 0)},[]),te=a.useCallback(()=>j(!0),[]),Je=a.useCallback(()=>j(!1),[]),dt=a.useCallback(q=>{H(q)},[]),ut=a.useCallback(()=>be(!0),[]),Ct=a.useCallback(()=>be(!1),[]),yt=a.useCallback(()=>me(!0),[]),bt=a.useCallback(()=>me(!1),[]),At=a.useCallback(()=>de(!0),[]),Rt=a.useCallback(()=>de(!1),[]),Ht=a.useCallback(()=>xe(!0),[]),Et=a.useCallback(()=>xe(!1),[]),Dt=a.useCallback(()=>he(!0),[]),Kt=a.useCallback(()=>he(!1),[]),$t=a.useCallback(async(q,pe)=>{he(!1),L(pe),Q(!0)},[]),Ft=a.useCallback(()=>je(!0),[]),Ot=a.useCallback(()=>je(!1),[]),Tt=a.useCallback(()=>Oe(!0),[]),Pt=a.useCallback(()=>Oe(!1),[]),wt=a.useCallback((q,pe)=>{pe(`Created ${q.id} from planning mode`,"success"),o(!1),c(null)},[]),Gt=a.useCallback((q,pe)=>{const $e=q.map(A=>A.id).join(", ");pe(`Created ${$e} from planning mode`,"success"),o(!1),c(null)},[]),Ut=a.useCallback((q,pe)=>{const $e=q.map(A=>A.id).join(", ");pe(`Created ${$e} from subtask breakdown`,"success"),h(!1),p(null)},[]);return{newTaskModalOpen:s,isPlanningOpen:r,planningInitialPlan:l,planningResumeSessionId:u,isSubtaskOpen:m,subtaskInitialDescription:f,subtaskResumeSessionId:g,detailTask:v,detailTaskInitialTab:y,settingsOpen:_,settingsInitialSection:w,schedulesOpen:N,githubImportOpen:E,usageOpen:U,usageAnchorRect:$,systemStatsOpen:z,terminalOpen:J,terminalInitialCommand:C,filesOpen:P,fileBrowserWorkspace:O,activityLogOpen:ge,gitManagerOpen:se,workflowStepsOpen:F,agentsOpen:ne,scriptsOpen:oe,setupWizardOpen:ae,modelOnboardingOpen:Ae,anyModalOpen:Qe,openNewTask:Xe,closeNewTask:Ye,openPlanning:it,openPlanningWithInitialPlan:Be,resumePlanning:Ge,openPlanningWithSession:re,closePlanning:ke,openSubtaskBreakdown:X,openSubtaskWithSession:Te,closeSubtask:Le,openDetailTask:fe,openDetailWithChangesTab:_e,updateDetailTask:Ue,closeDetailTask:nt,openSettings:ve,closeSettings:ce,openSchedules:De,closeSchedules:ue,openGitHubImport:Re,closeGitHubImport:Ke,openUsage:Pe,closeUsage:ft,openSystemStats:Z,closeSystemStats:le,toggleTerminal:we,closeTerminal:Ze,openFiles:te,closeFiles:Je,setFileWorkspace:dt,openActivityLog:ut,closeActivityLog:Ct,openGitManager:yt,closeGitManager:bt,openWorkflowSteps:At,closeWorkflowSteps:Rt,openAgents:Ht,closeAgents:Et,openScripts:Dt,closeScripts:Kt,runScript:$t,openSetupWizard:Ft,closeSetupWizard:Ot,openModelOnboarding:Tt,closeModelOnboarding:Pt,onPlanningTaskCreated:wt,onPlanningTasksCreated:Gt,onSubtaskTasksCreated:Ut}}function WI(e){const[n,s]=a.useState(2),[i,r]=a.useState("."),[o,l]=a.useState(!0),[c,u]=a.useState(!1),[d,m]=a.useState(!1),[h,f]=a.useState(void 0),[p,g]=a.useState(!1),[b,v]=a.useState(!1),[x,y]=a.useState(!1),[k,_]=a.useState({}),[S,w]=a.useState(!1),[M,N]=a.useState(!1),[D,E]=a.useState(!1),[T,U]=a.useState(!1),[K,$]=a.useState(!1),R=a.useCallback(async()=>{const[C,L]=await Promise.allSettled([Zv(e),Wo(e)]);if(C.status==="fulfilled"&&(s(C.value.maxConcurrent),r(C.value.rootDir)),L.status==="fulfilled"){const P=L.value;l(!!P.autoMerge),u(!!P.globalPause),m(!!P.enginePaused),v(!!P.prAuthAvailable),f(P.taskStuckTimeoutMs),g(P.showQuickChatFAB===!0),_(P.experimentalFeatures??{});const j=P.experimentalFeatures??{};w(j.insights===!0),N(j.roadmap===!0),E(j.memoryView===!0),U(j.devServerView===!0||j.devServer===!0),$(j.todoView===!0)}y(!0)},[e]);a.useEffect(()=>{y(!1),_({}),w(!1),N(!1),E(!1),U(!1),$(!1),R()},[R]);const z=a.useCallback(async()=>{const C=!o;l(C);try{await Hr({autoMerge:C},e)}catch{l(!C)}},[o,e]),B=a.useCallback(async()=>{const C=!c;u(C);try{await Hr({globalPause:C,globalPauseReason:C?"manual":void 0},e)}catch{u(!C)}},[c,e]),J=a.useCallback(async()=>{const C=!d;m(C);try{await Hr({enginePaused:C},e)}catch{m(!C)}},[d,e]),Q=a.useCallback(async()=>{const C=!p;g(C);try{await Hr({showQuickChatFAB:C},e)}catch{g(!C)}},[p,e]);return{maxConcurrent:n,rootDir:i,autoMerge:o,globalPaused:c,enginePaused:d,taskStuckTimeoutMs:h,showQuickChatFAB:p,prAuthAvailable:b,settingsLoaded:x,experimentalFeatures:k,insightsEnabled:S,roadmapEnabled:M,memoryEnabled:D,devServerEnabled:T,todosEnabled:K,toggleAutoMerge:z,toggleGlobalPause:B,toggleEnginePause:J,toggleShowQuickChatFAB:Q,refresh:R}}function KI(e){const{projectId:n,projects:s,projectsLoading:i,currentProject:r,setCurrentProject:o,addToast:l,openTaskDetail:c,closeTaskDetail:u}=e,d=a.useRef(!1),m=a.useRef(null);return a.useEffect(()=>{const f=new URLSearchParams(window.location.search),p=f.get("project"),g=f.get("task");if(!g||i)return;if(p){const v=s.find(x=>x.id===p);if(!v){l(`Project '${p}' not found`,"error");return}r?.id!==v.id&&o(v)}if(d.current)return;d.current=!0,pr(g,p??n).then(v=>{c(v),m.current=g}).catch(()=>{l(`Task ${g} not found`,"error")})},[n,s,i,r,o,l,c]),{handleDetailClose:a.useCallback(()=>{if(m.current){const f=new URLSearchParams(window.location.search);f.delete("task");const p=f.toString();window.history.replaceState(null,"",p?`${window.location.pathname}?${p}`:window.location.pathname),m.current=null}u()},[u])}}function GI(){const[e,n]=a.useState([]),[s,i]=a.useState([]),[r,o]=a.useState([]),l=a.useRef(s),c=a.useRef(r);a.useEffect(()=>{ms().then(m=>{n(m.models),l.current=m.favoriteProviders,c.current=m.favoriteModels,i(m.favoriteProviders),o(m.favoriteModels)}).catch(()=>{})},[]),a.useEffect(()=>{l.current=s},[s]),a.useEffect(()=>{c.current=r},[r]);const u=a.useCallback(async m=>{const h=l.current,p=h.includes(m)?h.filter(g=>g!==m):[m,...h];l.current=p,i(()=>p);try{await hn({favoriteProviders:p,favoriteModels:c.current})}catch(g){throw l.current=h,i(()=>h),g}},[]),d=a.useCallback(async m=>{const h=c.current,p=h.includes(m)?h.filter(g=>g!==m):[m,...h];c.current=p,o(()=>p);try{await hn({favoriteProviders:l.current,favoriteModels:p})}catch(g){throw c.current=h,o(()=>h),g}},[]);return{availableModels:e,favoriteProviders:s,favoriteModels:r,toggleFavoriteProvider:u,toggleFavoriteModel:d}}function JI({projectId:e,setupWizardOpen:n,openModelOnboarding:s,openSettings:i}){const r=a.useRef(!1),o=a.useRef(n);o.current=n,a.useEffect(()=>{if(n||!e||r.current)return;r.current=!0;let l=!1,c=!1;gr().then(({providers:u})=>{const d=u.some(h=>h.authenticated);if(u.length>0&&!d||u.length>0&&d)return Gi().then(h=>{const f=!!(h.defaultProvider&&h.defaultModelId);(h.modelOnboardingComplete===!1||h.modelOnboardingComplete===void 0)&&(!d||!f)&&!Na()?l=!0:!d&&!Na()&&(c=!0)})}).then(()=>{if(o.current){r.current=!1;return}l?(Rs("onboarding:auto-triggered",{trigger:"first-run"}),s()):c&&(Rs("onboarding:auto-triggered",{trigger:"missing-provider"}),i("authentication"))}).catch(()=>{})},[e,n,s,i])}const Vh="kb-update-banner-dismissed";function YI(){const[e,n]=a.useState(!0),[s,i]=a.useState(!1),[r,o]=a.useState(null),[l,c]=a.useState(null),[u,d]=a.useState(!1);a.useEffect(()=>{const h=sessionStorage.getItem(Vh)==="true";d(h);let f=!1;return ey().then(p=>{f||p.disabled||(i(p.updateAvailable===!0),o(typeof p.latestVersion=="string"?p.latestVersion:null),c(typeof p.currentVersion=="string"?p.currentVersion:null))}).catch(()=>{}).finally(()=>{f||n(!1)}),()=>{f=!0}},[]);const m=a.useCallback(()=>{d(!0),sessionStorage.setItem(Vh,"true")},[]);return{updateAvailable:s,latestVersion:r,currentVersion:l,loading:e,dismissed:u,dismiss:m}}const QI=["board","list","agents","missions","chat","documents","research","roadmaps","skills","mailbox","insights","memory","devserver","dev-server","todos"];function Wh(e){return e!==null&&QI.includes(e)}function XI(e){return e==="devserver"?"dev-server":e}function ZI(e){const{projectsLoading:n,projectsError:s,currentProjectLoading:i,currentProject:r,projectsLength:o,setupWizardOpen:l,openSetupWizard:c,themeMode:u,setThemeMode:d}=e,[m,h]=a.useState(()=>{if(typeof window<"u"){const x=window.localStorage.getItem("kb-dashboard-view-mode");if(x==="overview"||x==="project")return x}return"overview"}),[f,p]=a.useState(()=>{const x=Qn("kb-dashboard-task-view");return Wh(x)?x:"board"}),g=a.useRef(!1);a.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",m)},[m]),a.useEffect(()=>{const x=Qn("kb-dashboard-task-view",r?.id);if(Wh(x)){const y=!g.current&&x==="devserver";p(y?"devserver":XI(x))}else p("board");r?.id&&(g.current=!0)},[r?.id]),a.useEffect(()=>{bs("kb-dashboard-task-view",f,r?.id)},[r?.id,f]),a.useEffect(()=>{n||i||r&&m==="overview"&&h("project")},[n,i,r,m]),a.useEffect(()=>{if(n||i||l||s||o>0||r)return;const x=window.setTimeout(()=>{c()},500);return()=>window.clearTimeout(x)},[n,s,o,i,r,l,c]);const b=a.useCallback(x=>{p(x)},[]),v=a.useCallback(()=>{const x=["dark","light","system"],y=x.indexOf(u),k=x[(y+1)%x.length];d(k)},[u,d]);return{viewMode:m,setViewMode:h,taskView:f,setTaskView:p,handleChangeTaskView:b,handleToggleTheme:v}}function e4(e){const{setCurrentProject:n,clearCurrentProject:s,setViewMode:i,currentProject:r,refreshProjects:o,toggleFavoriteProvider:l,toggleFavoriteModel:c,addToast:u,openSettings:d,openSetupWizard:m,closeSetupWizard:h,closeModelOnboarding:f}=e,p=a.useCallback(N=>{n(N),i("project")},[n,i]),g=a.useCallback(()=>{s(),i("overview")},[s,i]),b=a.useCallback(()=>{d()},[d]),v=a.useCallback(()=>{m()},[m]),x=a.useCallback(N=>{h(),n(N),i("project"),u(`Project ${N.name} registered successfully`,"success"),o()},[h,n,i,u,o]),y=a.useCallback(()=>{f()},[f]),k=a.useCallback(async N=>{try{await nk(N.id),u(`Project ${N.name} paused`,"success"),await o()}catch{u(`Failed to pause project ${N.name}`,"error")}},[u,o]),_=a.useCallback(async N=>{try{await sk(N.id),u(`Project ${N.name} resumed`,"success"),await o()}catch{u(`Failed to resume project ${N.name}`,"error")}},[u,o]),S=a.useCallback(async N=>{try{await vp(N.id),u(`Project ${N.name} removed`,"success"),r?.id===N.id&&(s(),i("overview")),await o()}catch{u(`Failed to remove project ${N.name}`,"error")}},[r,s,i,u,o]),w=a.useCallback(async N=>{try{await l(N)}catch{u("Failed to update favorites","error")}},[l,u]),M=a.useCallback(async N=>{try{await c(N)}catch{u("Failed to update model favorites","error")}},[c,u]);return{handleSelectProject:p,handleViewAllProjects:g,handleOpenSettings:b,handleAddProject:v,handleSetupComplete:x,handleModelOnboardingComplete:y,handlePauseProject:k,handleResumeProject:_,handleRemoveProject:S,handleToggleFavorite:w,handleToggleModelFavorite:M}}function t4(e){const{createTask:n,ingestCreatedTasks:s,onPlanningTaskCreated:i,onPlanningTasksCreated:r,onSubtaskTasksCreated:o,addToast:l}=e,c=a.useCallback(async p=>n({...p,column:"triage",source:{sourceType:"dashboard_ui"}}),[n]),u=a.useCallback(async p=>await n({...p,column:"triage",source:{sourceType:"dashboard_ui"}}),[n]),d=a.useCallback(p=>{s([p]),i(p,l)},[l,s,i]),m=a.useCallback(p=>{s(p),r(p,l)},[l,s,r]),h=a.useCallback(p=>{s(p),o(p,l)},[l,s,o]),f=a.useCallback(p=>{l(`Imported ${p.id} from GitHub`,"success")},[l]);return{handleBoardQuickCreate:c,handleModalCreate:u,handlePlanningTaskCreated:d,handlePlanningTasksCreated:m,handleSubtaskTasksCreated:h,handleGitHubImport:f}}async function n4(e){return Go("/health",{nodeId:e})}async function s4(e){return Go("/projects",{nodeId:e})}async function i4(e,n,s){const i=new URLSearchParams({projectId:n});return s&&s.trim()&&i.set("q",s.trim()),Go(`/tasks?${i.toString()}`,{nodeId:e})}async function a4(e,n){return Go(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:e})}async function SL(e){return I(`/nodes/${encodeURIComponent(e)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function CL(e){return I(`/nodes/${encodeURIComponent(e)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function EL(e){return I(`/nodes/${encodeURIComponent(e)}/settings/sync-status`)}async function _L(e){return I(`/nodes/${encodeURIComponent(e)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}function r4(e,n){const{projectId:s,searchQuery:i}=n??{},[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState(null),[m,h]=a.useState(!1),[f,p]=a.useState(null),g=a.useRef(null),b=a.useCallback(async()=>{if(!e){o([]),c([]),d(null),h(!1),p(null);return}g.current?.abort();const x=new AbortController;g.current=x,h(!0),p(null);try{const y=[n4(e),s4(e)];s&&(y.push(i4(e,s,i)),y.push(a4(e,s)));const k=await Promise.allSettled(y);if(x.signal.aborted)return;const _=k[0],S=k[1];if(_.status==="rejected"){p(`Failed to fetch node health: ${_.reason}`),h(!1);return}if(d(_.value),S.status==="rejected"){p(`Failed to fetch projects: ${S.reason}`),h(!1);return}if(o(S.value),s&&k[2]){const w=k[2];if(w.status==="rejected"){p(`Failed to fetch tasks: ${w.reason}`),h(!1);return}w.status==="fulfilled"&&c(w.value)}h(!1)}catch(y){x.signal.aborted||(p(y instanceof Error?y.message:"Unknown error"),h(!1))}},[e,s,i]);a.useEffect(()=>(b(),()=>{g.current?.abort()}),[b]);const v=a.useCallback(()=>{b()},[b]);return{projects:r,tasks:l,health:u,loading:m,error:f,refresh:v}}function o4(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 Ks(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 l4="fusion-dashboard-current-node",Ag=a.createContext(null);function c4({children:e}){const[n,s]=a.useState(null),[i,r]=a.useState(!0),o=a.useRef(!1),l=a.useRef(void 0);a.useEffect(()=>{let m=!1;async function h(){try{const f=await Gi();if(m)return;l.current=f.dashboardCurrentNodeId;const p=f.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const g=localStorage.getItem(l4);if(g){const b=JSON.parse(g);b?.id&&b?.type==="remote"&&(l.current=b.id,await hn({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,hn({dashboardCurrentNodeId:m}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,hn({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,i]);const c=a.useCallback(m=>{s(m)},[]),u=a.useCallback(()=>{s(null),l.current=void 0,hn({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),d={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:u};return t.jsx(Ag.Provider,{value:d,children:e})}function d4(){const e=a.useContext(Ag);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}function u4({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&&(_v(l),window.location.reload())},[n]),o=a.useCallback(()=>{Mv(),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 m4=200,h4=a.lazy(()=>un(()=>import("./AgentsView-Dxdtt0Bm.js").then(e=>e.A),__vite__mapDeps([17,1,18,8,19])).then(e=>({default:e.AgentsView}))),p4=a.lazy(()=>un(()=>import("./DocumentsView-BRBUPFVA.js"),__vite__mapDeps([20,1,0,2,21])).then(e=>({default:e.DocumentsView}))),f4=a.lazy(()=>un(()=>import("./InsightsView-BRDqHCLb.js"),__vite__mapDeps([22,1,14,0,2,23])).then(e=>({default:e.InsightsView}))),g4=a.lazy(()=>un(()=>import("./ResearchView-fmEOm4A2.js"),__vite__mapDeps([24,1,0,2,25])).then(e=>({default:e.ResearchView}))),b4=a.lazy(()=>un(()=>import("./NodesView-C4Ffl_o0.js"),__vite__mapDeps([26,1,18,0,2,27])).then(e=>({default:e.NodesView}))),x4=a.lazy(()=>un(()=>import("./ChatView-Bra9fNAG.js"),__vite__mapDeps([28,1,0,2])).then(e=>({default:e.ChatView}))),v4=a.lazy(()=>un(()=>import("./RoadmapsView-DNb4x75S.js"),__vite__mapDeps([29,1,0,2,30])).then(e=>({default:e.RoadmapsView}))),y4=a.lazy(()=>un(()=>import("./SkillsView-uyl47gSf.js"),__vite__mapDeps([31,1,0,2,32])).then(e=>({default:e.SkillsView}))),j4=a.lazy(()=>un(()=>import("./MemoryView-DvTrwFnQ.js"),__vite__mapDeps([33,1,12,13,0,2,34])).then(e=>({default:e.MemoryView}))),k4=a.lazy(()=>un(()=>import("./DevServerView-UkgjEw9-.js"),__vite__mapDeps([35,1,0,2,36])).then(e=>({default:e.DevServerView}))),w4=a.lazy(()=>un(()=>import("./TodoView-CbzDtV53.js"),__vite__mapDeps([37,1,38,0,2,39])).then(e=>({default:e.TodoView})));function N4(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{un(()=>import("./AgentsView-Dxdtt0Bm.js").then(n=>n.A),__vite__mapDeps([17,1,18,8,19])),un(()=>import("./DocumentsView-BRBUPFVA.js"),__vite__mapDeps([20,1,0,2,21])),un(()=>import("./InsightsView-BRDqHCLb.js"),__vite__mapDeps([22,1,14,0,2,23])),un(()=>import("./ResearchView-fmEOm4A2.js"),__vite__mapDeps([24,1,0,2,25])),un(()=>import("./NodesView-C4Ffl_o0.js"),__vite__mapDeps([26,1,18,0,2,27])),un(()=>import("./ChatView-Bra9fNAG.js"),__vite__mapDeps([28,1,0,2])),un(()=>import("./RoadmapsView-DNb4x75S.js"),__vite__mapDeps([29,1,0,2,30])),un(()=>import("./SkillsView-uyl47gSf.js"),__vite__mapDeps([31,1,0,2,32])),un(()=>import("./MemoryView-DvTrwFnQ.js"),__vite__mapDeps([33,1,12,13,0,2,34])),un(()=>import("./DevServerView-UkgjEw9-.js"),__vite__mapDeps([35,1,0,2,36])),un(()=>import("./TodoView-CbzDtV53.js"),__vite__mapDeps([37,1,38,0,2,39]))})}const yc="kb-setup-warning-dismissed";function S4(){const{toasts:e,addToast:n,removeToast:s}=FI(),i=typeof window<"u"&&!!window.electronAPI;a.useEffect(()=>{N4()},[]);const{projects:r,loading:o,error:l,refresh:c}=II(),{nodes:u}=Qo(),{currentNode:d,currentNodeId:m,isRemote:h,setCurrentNode:f,clearCurrentNode:p}=d4(),{currentProject:g,setCurrentProject:b,clearCurrentProject:v,loading:x}=LI(r,{nodeId:m}),{hasAiProvider:y,hasGithub:k,loading:_,hasWarnings:S}=hg(g?.id),{updateAvailable:w,latestVersion:M,currentVersion:N,dismissed:D,dismiss:E}=YI();a.useEffect(()=>{if(m&&!d&&u.length>0){const Me=u.find(ct=>ct.id===m);if(Me){f(Me);return}}m&&u.length>0&&(u.some(ct=>ct.id===m)||p())},[m,d,u,f,p]);const[T,U]=a.useState(""),K=r4(m,{projectId:g?.id,searchQuery:T||void 0});o4(m);const $=h&&K.projects.length>0?K.projects:r,{themeMode:R,colorTheme:z,setThemeMode:B,setColorTheme:J}=qI(),{sessions:Q,generating:C,needsInput:L,planningSessions:P,dismissSession:j}=MI(g?.id),O=Q.filter(Me=>Me.status==="awaiting_input"||Me.status==="error"),H=VI({projectId:g?.id,planningSessions:P}),{viewMode:ge,setViewMode:be,taskView:se,handleChangeTaskView:me}=ZI({projectsLoading:o,projectsError:l,currentProjectLoading:x,currentProject:g,projectsLength:r.length,setupWizardOpen:H.setupWizardOpen,openSetupWizard:H.openSetupWizard,themeMode:R,setThemeMode:B}),F=a.useCallback(Me=>{Me==="missions"&&(Ze(void 0),Je(void 0),ut(void 0)),me(Me)},[me]),de=se==="board"||se==="list",{tasks:ne,createTask:xe,moveTask:oe,pauseTask:he,deleteTask:ae,mergeTask:je,retryTask:Ae,resetTask:Oe,updateTask:Qe,duplicateTask:Xe,archiveTask:Ye,unarchiveTask:it,archiveAllDone:Be,loadArchivedTasks:Ge,ingestCreatedTasks:re,lastFetchTimeMs:ke}=RI({...g?{projectId:g.id}:{},searchQuery:T||void 0,sseEnabled:de}),[X,Te]=a.useState(!1),Le=a.useRef(performance.now()),fe=a.useRef(!1),_e=a.useRef(!1),Ue=a.useMemo(()=>o?"projects":x?"project":"tasks",[o,x]);a.useEffect(()=>{if(!o&&!fe.current){fe.current=!0;const Me=`projects loaded at ${Math.round(performance.now()-Le.current)}ms from mount`;console.log(`[App] ${Me}`),or("[App]",Me)}if(!x&&!_e.current){_e.current=!0;const Me=`current-project resolved at ${Math.round(performance.now()-Le.current)}ms from mount`;console.log(`[App] ${Me}`),or("[App]",Me)}},[o,x]),a.useEffect(()=>{if(X||o||x)return;const Me=performance.now(),ct=window.setTimeout(()=>{const gt=`dashboard ready at ${Math.round(performance.now()-Le.current)}ms from mount (settle delay=${Math.round(performance.now()-Me)}ms)`;console.log(`[App] ${gt}`),or("[App]",gt),Te(!0)},m4);return()=>{window.clearTimeout(ct)}},[X,o,x]);const ve=Rr()==="mobile",{keyboardOpen:ce}=kg({enabled:ve}),De=ve&&ce,[ue,Re]=a.useState(0),Ke=a.useCallback(()=>{Np(g?.id).then(Me=>{Re(Me.unreadCount)}).catch(Me=>{console.warn("[App] Failed to fetch mailbox unread count:",Me)})},[g?.id]);a.useEffect(()=>{Ke();const Me=new URLSearchParams;g?.id&&Me.set("projectId",g.id);const ct=Me.size>0?`?${Me.toString()}`:"";return Ks(`/api/events${ct}`,{events:{"message:sent":Ke,"message:received":Ke,"message:read":Ke,"message:deleted":Ke}})},[g?.id,Ke]);const[Pe,ft]=a.useState(!1),[Z,le]=a.useState(!1),[we,Ze]=a.useState(void 0),[te,Je]=a.useState(void 0),[dt,ut]=a.useState(void 0),[Ct,yt]=a.useState(!1),[bt,At]=a.useState(!1),[Rt,Ht]=a.useState(()=>Qn(yc,g?.id)==="true");a.useEffect(()=>{Ht(Qn(yc,g?.id)==="true")},[g?.id]),a.useEffect(()=>{const Me=()=>{At(!0)};return window.addEventListener(Tc,Me),()=>{window.removeEventListener(Tc,Me)}},[]);const Et=a.useCallback(()=>{bs(yc,"true",g?.id),Ht(!0)},[g?.id]),{maxConcurrent:Dt,autoMerge:Kt,globalPaused:$t,enginePaused:Ft,taskStuckTimeoutMs:Ot,showQuickChatFAB:Tt,prAuthAvailable:Pt,settingsLoaded:wt,experimentalFeatures:Gt,insightsEnabled:Ut,roadmapEnabled:q,memoryEnabled:pe,devServerEnabled:$e,todosEnabled:A,toggleAutoMerge:ee,toggleGlobalPause:ze,toggleEnginePause:mt,refresh:jt}=WI(g?.id),Lt=Gt.skillsView===!0,_t=Gt.nodesView===!0,Jt=Gt.researchView===!0,Dn=!0;a.useEffect(()=>{wt&&(se==="skills"&&!Lt&&me("board"),se==="insights"&&!Ut&&me("board"),se==="roadmaps"&&!q&&me("board"),se==="memory"&&!pe&&me("board"),(se==="devserver"||se==="dev-server")&&!$e&&me("board"),se==="todos"&&!A&&me("board"),se==="research"&&!Jt&&me("board"))},[se,wt,Lt,Ut,q,me,Dn,pe,$e,A,Jt]),a.useEffect(()=>{Pe&&!_t&&ft(!1)},[Pe,_t]);const{availableModels:Pn,favoriteProviders:Yt,favoriteModels:Cn,toggleFavoriteProvider:Ne,toggleFavoriteModel:at}=GI();JI({projectId:g?.id,setupWizardOpen:H.setupWizardOpen,openModelOnboarding:H.openModelOnboarding,openSettings:H.openSettings});const{handleSelectProject:fn,handleViewAllProjects:jn,handleOpenSettings:In,handleAddProject:Ce,handleSetupComplete:st,handleModelOnboardingComplete:ht,handlePauseProject:Mt,handleResumeProject:ln,handleRemoveProject:En,handleToggleFavorite:tn,handleToggleModelFavorite:nn}=e4({setCurrentProject:b,clearCurrentProject:v,setViewMode:be,currentProject:g,refreshProjects:c,toggleFavoriteProvider:Ne,toggleFavoriteModel:at,addToast:n,openSettings:H.openSettings,openSetupWizard:H.openSetupWizard,closeSetupWizard:H.closeSetupWizard,closeModelOnboarding:H.closeModelOnboarding}),{handleDetailClose:An}=KI({projectId:g?.id,projects:r,projectsLoading:o,currentProject:g,setCurrentProject:b,addToast:n,openTaskDetail:H.openDetailTask,closeTaskDetail:H.closeDetailTask}),{handleBoardQuickCreate:Un,handleModalCreate:kn,handlePlanningTaskCreated:ns,handlePlanningTasksCreated:cn,handleSubtaskTasksCreated:vt,handleGitHubImport:G}=t4({createTask:xe,ingestCreatedTasks:re,onPlanningTaskCreated:H.onPlanningTaskCreated,onPlanningTasksCreated:H.onPlanningTasksCreated,onSubtaskTasksCreated:H.onSubtaskTasksCreated,addToast:n}),Fe=a.useCallback((Me,ct)=>{if(ct==="changes"){H.openDetailWithChangesTab(Me);return}H.openDetailTask(Me,ct)},[H]),tt=a.useCallback(async Me=>{try{const ct=await pr(Me,g?.id);H.openDetailTask(ct,"logs")}catch(ct){n(`Failed to open task logs: ${ct.message}`,"error")}},[H,g?.id,n]),rt=a.useCallback(()=>{_t&&ft(Me=>!Me)},[_t]),kt=a.useCallback(()=>{H.setFileWorkspace("project"),H.openFiles()},[H]),St=a.useCallback(async()=>{le(!0);try{await c()}finally{le(!1)}},[c]),zt=a.useCallback(Me=>{Je(Me),Ze(void 0),me("missions")},[me]),qn=a.useCallback(Me=>{Me.type==="planning"?H.openPlanningWithSession(Me.id):Me.type==="subtask"?H.openSubtaskWithSession(Me.id):Me.type==="mission_interview"?(Je(void 0),Ze(Me.id),ut(void 0),me("missions")):(Me.type==="milestone_interview"||Me.type==="slice_interview")&&(Ze(void 0),Je(void 0),ut(Me.id),me("missions"))},[me,H]),Ds=a.useCallback(()=>{},[]),ci=a.useCallback(()=>{},[]),Cs=!o&&!x&&r.length===0&&!g&&!!l,Gs=()=>Cs?t.jsx(IP,{errorMessage:l??"Failed to fetch projects",isRetrying:Z,onRetry:St}):Pe?t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(b4,{addToast:n,onClose:()=>ft(!1)})})})}):ge==="overview"?t.jsx(is,{children:t.jsx(d1,{projects:r,loading:o,onSelectProject:fn,onAddProject:Ce,onPauseProject:Mt,onResumeProject:ln,onRemoveProject:En,nodes:u})}):se==="skills"?!wt||!Lt?null:t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(y4,{addToast:n,projectId:g?.id,onClose:()=>me("board")})})}):se==="chat"?t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(x4,{addToast:n,projectId:g?.id})})}):se==="mailbox"?t.jsx(is,{children:t.jsx(n0,{projectId:g?.id,addToast:n,onUnreadCountChange:Re})}):se==="roadmaps"?!wt||!q?null:t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(v4,{addToast:n,projectId:g?.id})})}):se==="missions"?t.jsx(is,{children:t.jsx(X1,{isInline:!0,isOpen:!0,onClose:()=>{Je(void 0),Ze(void 0),ut(void 0),me("board")},addToast:n,projectId:g?.id,onSelectTask:Me=>{const ct=ne.find(gt=>gt.id===Me);ct&&H.openDetailTask(ct)},availableTasks:ne.map(Me=>({id:Me.id,title:Me.title})),resumeSessionId:we,targetMissionId:te,milestoneSliceResumeSessionId:dt,onMilestoneSliceResumeFetchError:()=>ut(void 0)})}):se==="agents"&&Dn?t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(h4,{addToast:n,projectId:g?.id,onOpenTaskLogs:tt})})}):se==="documents"?t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(p4,{projectId:g?.id,addToast:n,onOpenDetail:H.openDetailTask})})}):se==="insights"?!wt||!Ut?null:t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(f4,{projectId:g?.id,addToast:n,onClose:()=>me("board")})})}):se==="research"?!wt||!Jt?null:t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(g4,{projectId:g?.id,addToast:n})})}):se==="memory"?!wt||!pe?null:t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(j4,{addToast:n,projectId:g?.id})})}):se==="todos"?!wt||!A?null:t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(w4,{addToast:n,projectId:g?.id})})}):se==="devserver"||se==="dev-server"?!wt||!$e?null:t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(k4,{addToast:n,projectId:g?.id})})}):se==="board"?t.jsx(is,{children:t.jsx(YN,{tasks:h&&K.tasks.length>0?K.tasks:ne,projectId:g?.id,maxConcurrent:Dt,onMoveTask:oe,onPauseTask:he,onOpenDetail:H.openDetailTask,addToast:n,onQuickCreate:Un,onNewTask:H.openNewTask,onPlanningMode:H.openPlanningWithInitialPlan,onSubtaskBreakdown:H.openSubtaskBreakdown,autoMerge:Kt,onToggleAutoMerge:ee,globalPaused:$t,onUpdateTask:Qe,onRetryTask:Ae,onArchiveTask:Ye,onUnarchiveTask:it,onDeleteTask:ae,onArchiveAllDone:Be,onLoadArchivedTasks:Ge,searchQuery:T,availableModels:Pn,onOpenDetailWithTab:Fe,favoriteProviders:Yt,favoriteModels:Cn,onToggleFavorite:tn,onToggleModelFavorite:nn,taskStuckTimeoutMs:Ot,onOpenMission:zt,lastFetchTimeMs:ke})}):t.jsx(is,{children:t.jsx(e1,{tasks:h&&K.tasks.length>0?K.tasks:ne,projectId:g?.id,onMoveTask:oe,onRetryTask:Ae,onOpenDetail:H.openDetailTask,addToast:n,globalPaused:$t,onNewTask:H.openNewTask,onQuickCreate:Un,onPlanningMode:H.openPlanningWithInitialPlan,onSubtaskBreakdown:H.openSubtaskBreakdown,availableModels:Pn,favoriteProviders:Yt,favoriteModels:Cn,onToggleFavorite:tn,onToggleModelFavorite:nn,taskStuckTimeoutMs:Ot,searchQuery:T,lastFetchTimeMs:ke})});if(!X)return t.jsxs(t.Fragment,{children:[t.jsx(DP,{stage:Ue}),t.jsx(vg,{toasts:e,onRemove:s})]});const ie=!H.modelOnboardingOpen&&iP(),Ee=!H.modelOnboardingOpen&&!ie&&Na()&&!fg();return t.jsxs(t.Fragment,{children:[t.jsx(Sw,{isElectron:i,onOpenSettings:In,onOpenGitHubImport:H.openGitHubImport,onOpenPlanning:H.openPlanning,onResumePlanning:H.resumePlanning,activePlanningSessionCount:P.length,onOpenUsage:H.openUsage,onOpenActivityLog:H.openActivityLog,onOpenSystemStats:H.openSystemStats,onOpenMailbox:()=>F("mailbox"),mailboxUnreadCount:ue,onOpenSchedules:H.openSchedules,onOpenGitManager:H.openGitManager,onOpenNodes:rt,showNodesButton:_t,onOpenWorkflowSteps:H.openWorkflowSteps,onOpenScripts:H.openScripts,onRunScript:H.runScript,onToggleTerminal:H.toggleTerminal,onOpenFiles:H.openFiles,filesOpen:H.filesOpen,globalPaused:$t,enginePaused:Ft,onToggleGlobalPause:ze,onToggleEnginePause:mt,view:se,onChangeView:ge==="project"&&g?F:void 0,showSkillsTab:Lt,showAgentsTab:Dn,searchQuery:T,onSearchChange:U,projects:$,currentProject:g,onSelectProject:fn,onViewAllProjects:jn,projectId:g?.id,mobileNavEnabled:ve,availableNodes:u,currentNode:d,onSelectNode:Me=>{Me===null?p():f(Me)},isRemote:h,experimentalFeatures:{insights:Ut,roadmap:q,memoryView:pe,devServer:$e,devServerView:$e,todoView:A,researchView:Jt}}),ge==="project"&&g&&!Pe&&se!=="missions"&&!H.isPlanningOpen&&t.jsx(JP,{sessions:O,onResumeSession:qn,onDismissSession:Ds,onDismissAll:ci}),ge==="project"&&g&&ie&&t.jsx(QP,{onResume:H.openModelOnboarding}),ge==="project"&&g&&Ee&&t.jsx(XP,{onOpenModelOnboarding:H.openModelOnboarding,onOpenSettings:Me=>H.openSettings(Me)}),ge==="project"&&g&&w&&M&&N&&!D&&t.jsx(YP,{latestVersion:M,currentVersion:N,onDismiss:E}),ge==="project"&&g&&!_&&S&&!Rt&&t.jsx(pg,{hasAiProvider:y,hasGithub:k,onDismiss:Et}),t.jsx("div",{className:`project-content${ge==="project"&&g?" project-content--with-footer":""}${ve&&!De?" project-content--with-mobile-nav":""}`,children:Gs()}),ge==="project"&&g&&!Pe&&t.jsx(WP,{tasks:h&&K.tasks.length>0?K.tasks:ne,projectId:g.id,taskStuckTimeoutMs:Ot,backgroundSessions:Q,backgroundGenerating:C,backgroundNeedsInput:L,onOpenBackgroundSession:qn,onDismissBackgroundSession:j,lastFetchTimeMs:ke,currentProjectPath:g.path,onOpenProjectDirectory:kt}),t.jsx(eI,{view:se,onChangeView:ge==="project"&&g?F:()=>{},footerVisible:ge==="project"&&!!g,modalOpen:H.anyModalOpen,keyboardOpen:De,onOpenSettings:In,onOpenActivityLog:H.openActivityLog,onOpenSystemStats:H.openSystemStats,onOpenMailbox:()=>F("mailbox"),mailboxUnreadCount:ue,onOpenGitManager:H.openGitManager,onOpenWorkflowSteps:H.openWorkflowSteps,onOpenSchedules:H.openSchedules,onOpenScripts:H.openScripts,onToggleTerminal:H.toggleTerminal,onOpenFiles:H.openFiles,onOpenGitHubImport:H.openGitHubImport,onOpenPlanning:H.openPlanning,onResumePlanning:H.resumePlanning,activePlanningSessionCount:P.length,onOpenUsage:()=>H.openUsage(null),onViewAllProjects:jn,onRunScript:H.runScript,projectId:g?.id,showSkillsTab:Lt,experimentalFeatures:{insights:Ut,roadmap:q,memoryView:pe,devServer:$e,devServerView:$e,todoView:A,researchView:Jt}}),ge==="project"&&g&&se!=="chat"&&se!=="mailbox"&&se!=="insights"&&se!=="devserver"&&se!=="dev-server"&&t.jsx(_I,{projectId:g.id,addToast:n,showFAB:Tt,open:Ct,onOpenChange:yt,favoriteProviders:Yt,favoriteModels:Cn,onToggleFavorite:tn,onToggleModelFavorite:nn}),t.jsx(PP,{projectId:g?.id,tasks:ne,projects:r,currentProject:g,addToast:n,toasts:e,removeToast:s,modalManager:H,projectActions:{handleAddProject:Ce,handleSetupComplete:st,handleModelOnboardingComplete:ht},taskHandlers:{handleModalCreate:kn,handlePlanningTaskCreated:ns,handlePlanningTasksCreated:cn,handleSubtaskTasksCreated:vt,handleGitHubImport:G},taskOperations:{moveTask:oe,deleteTask:ae,mergeTask:je,retryTask:Ae,resetTask:Oe,duplicateTask:Xe},deepLink:{handleDetailClose:An},settings:{prAuthAvailable:Pt,themeMode:R,colorTheme:z,setThemeMode:B,setColorTheme:J},onSettingsClose:()=>{H.closeSettings(),jt()},onReopenOnboarding:()=>{H.closeSettings(),H.openModelOnboarding()}}),t.jsx(u4,{open:bt})]})}function C4(){return t.jsx(zI,{children:t.jsx(c4,{children:t.jsx(Fw,{children:t.jsx(S4,{})})})})}Dv();jv();Rg.createRoot(document.getElementById("root")).render(t.jsx(a.StrictMode,{children:t.jsx(kv,{children:t.jsx(C4,{})})}));"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{Wj as $,Is as A,Nn as B,yn as C,on as D,jo as E,Ui as F,Uo as G,NL as H,vn as I,hc as J,Sn as K,ot as L,Hs as M,rn as N,Xt as O,On as P,VT as Q,$n as R,ki as S,ad as T,qj as U,zT as V,FT as W,Wt as X,Vj as Y,Gn as Z,W$ as _,bs as a,uD as a$,un as a0,u$ as a1,m$ as a2,Zy as a3,sd as a4,Ca as a5,Sa as a6,ai as a7,ri as a8,pi as a9,rr as aA,jb as aB,cs as aC,ap as aD,Qo as aE,II as aF,nL as aG,uu as aH,xr as aI,hw as aJ,sL as aK,iL as aL,pw as aM,fw as aN,oI as aO,Rr as aP,kg as aQ,Fo as aR,sp as aS,tI as aT,aI as aU,js as aV,Li as aW,wi as aX,Zh as aY,Bd as aZ,cD as a_,aL as aa,lL as ab,oL as ac,rL as ad,cL as ae,rs as af,us as ag,lv as ah,si as ai,Cb as aj,zo as ak,Si as al,dL as am,mL as an,bL as ao,gL as ap,fL as aq,pL as ar,hL as as,uL as at,EL as au,SL as av,CL as aw,_L as ax,hr as ay,Qx as az,tD as b,PD as b$,dD as b0,mD as b1,hD as b2,pD as b3,fD as b4,gD as b5,bD as b6,xD as b7,vD as b8,yD as b9,M$ as bA,_$ as bB,$$ as bC,E$ as bD,A$ as bE,R$ as bF,T$ as bG,P$ as bH,kj as bI,I$ as bJ,od as bK,vj as bL,yj as bM,jj as bN,xj as bO,C$ as bP,Sr as bQ,qo as bR,Jx as bS,mr as bT,Bx as bU,ED as bV,_D as bW,MD as bX,AD as bY,RD as bZ,TD as b_,jD as ba,kD as bb,ND as bc,SD as bd,wD as be,Hn as bf,id as bg,Oi as bh,eL as bi,ZD as bj,tL as bk,V4 as bl,q4 as bm,H4 as bn,W4 as bo,t$ as bp,n$ as bq,X4 as br,J4 as bs,Y4 as bt,Q4 as bu,G4 as bv,K4 as bw,B4 as bx,Z4 as by,CR as bz,He as c,qi as c$,CD as c0,dp as c1,fa as c2,Xj as c3,_v as c4,Mv as c5,GD as c6,p$ as c7,h$ as c8,JD as c9,Cy as cA,by as cB,ii as cC,xy as cD,vy as cE,yy as cF,r$ as cG,sD as cH,iD as cI,aD as cJ,Ei as cK,vL as cL,yL as cM,lD as cN,I4 as cO,kc as cP,Jn as cQ,NR as cR,KT as cS,pc as cT,Jo as cU,D4 as cV,T4 as cW,L4 as cX,$4 as cY,z4 as cZ,F4 as c_,f$ as ca,w$ as cb,y$ as cc,g$ as cd,j$ as ce,b$ as cf,k$ as cg,x$ as ch,v$ as ci,Wg as cj,py as ck,N$ as cl,fy as cm,S$ as cn,oi as co,mR as cp,s$ as cq,oD as cr,M4 as cs,A4 as ct,gr as cu,nD as cv,R4 as cw,P4 as cx,U4 as cy,O4 as cz,Z$ as d,Tw as d0,Yo as d1,jL as d2,eh as d3,kL as d4,wL as d5,e$ as d6,ID as d7,DD as d8,FD as d9,B$ as dA,BD as dB,D$ as dC,HD as dD,Ox as dE,_c as dF,YD as dG,WD as dH,VD as dI,KD as dJ,qD as dK,rD as dL,xL as dM,o$ as dN,i$ as dO,a$ as dP,c$ as dQ,d$ as dR,l$ as dS,LD as da,$D as db,zD as dc,OD as dd,xp as de,Kd as df,nx as dg,UD as dh,G$ as di,H$ as dj,V$ as dk,q$ as dl,Q$ as dm,Y$ as dn,Xh as dp,U$ as dq,O$ as dr,LT as ds,K$ as dt,wr as du,RM as dv,z$ as dw,L$ as dx,ej as dy,F$ as dz,eD as e,pr as f,Qn as g,XD as h,ms as i,Ea as j,QD as k,Yn as l,Hj as m,X$ as n,iI as o,Ws as p,Wo as q,OT as r,Ks as s,Hr as t,hn as u,ye as v,Dw as w,J$ as x,Cc as y,Vs as z};
|