@runfusion/fusion 0.8.2 → 0.8.4
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 +1714 -840
- package/dist/client/assets/{AgentDetailView-B6wfIQ9j.js → AgentDetailView-C_DD03d6.js} +1 -1
- package/dist/client/assets/{AgentsView-Fcym0XCw.js → AgentsView-CsEX_Fsi.js} +3 -3
- package/dist/client/assets/ChatView-DhudD-jT.js +1 -0
- package/dist/client/assets/{DevServerView-CmMS4D6V.js → DevServerView-CNItMoga.js} +1 -1
- package/dist/client/assets/DirectoryPicker-BqcVbDZX.js +1 -0
- package/dist/client/assets/{DocumentsView-C4HDkN_0.js → DocumentsView-zpHkjZdf.js} +1 -1
- package/dist/client/assets/{InsightsView-Egu71gmh.css → InsightsView-6LHF7OdE.css} +1 -1
- package/dist/client/assets/InsightsView-CgguV1au.js +11 -0
- package/dist/client/assets/{MemoryView-DPYGW09y.js → MemoryView-BWXP8uGT.js} +1 -1
- package/dist/client/assets/{NodesView-DsM-c8RF.js → NodesView-DP_O4ae0.js} +1 -1
- package/dist/client/assets/{PiExtensionsManager-DHgMjjRE.js → PiExtensionsManager-DGEPbF0y.js} +3 -3
- package/dist/client/assets/{PluginManager-N-7Sw_tE.js → PluginManager-4TehPpcf.js} +1 -1
- package/dist/client/assets/{RoadmapsView-BgX79uYM.js → RoadmapsView-DNaToPqN.js} +2 -2
- package/dist/client/assets/SettingsModal-BluRnKGd.js +31 -0
- package/dist/client/assets/{SettingsModal-BIKEMPwb.js → SettingsModal-C-RjolQ5.js} +1 -1
- package/dist/client/assets/SettingsModal-C7gPLBaR.css +1 -0
- package/dist/client/assets/{SetupWizardModal-D2m0i9Io.js → SetupWizardModal-BQoo_AvX.js} +1 -1
- package/dist/client/assets/{SkillsView-Eb1Mngnt.js → SkillsView-AS8Cr_Md.js} +1 -1
- package/dist/client/assets/{TodoView-BN8FQYyp.js → TodoView-nWOpOg3R.js} +2 -2
- package/dist/client/assets/{folder-open-BqZBHfoZ.js → folder-open-D0LfE0ZP.js} +1 -1
- package/dist/client/assets/index-D6xr8Oa2.css +1 -0
- package/dist/client/assets/index-heCcln3Z.js +656 -0
- package/dist/client/assets/{list-checks-D2EURsP0.js → list-checks-D1faMe1o.js} +1 -1
- package/dist/client/assets/{star-CNQlAD8p.js → star-B_uA5YGG.js} +1 -1
- package/dist/client/assets/{upload-uoxlYkig.js → upload-DPQ3hWf0.js} +1 -1
- package/dist/client/assets/{users-BLvidusm.js → users-CEcYlrZO.js} +1 -1
- package/dist/client/index.html +2 -2
- package/dist/client/version.json +1 -1
- package/dist/extension.js +1033 -372
- package/dist/pi-claude-cli/package.json +1 -1
- package/dist/pi-claude-cli/src/__tests__/control-handler.test.ts +39 -66
- package/dist/pi-claude-cli/src/__tests__/process-manager.test.ts +7 -9
- package/dist/pi-claude-cli/src/__tests__/provider.test.ts +73 -148
- package/dist/pi-claude-cli/src/__tests__/setup-test-isolation.test.ts +2 -0
- package/dist/pi-claude-cli/src/__tests__/setup-test-isolation.ts +8 -0
- package/dist/pi-claude-cli/src/control-handler.ts +22 -8
- package/dist/pi-claude-cli/src/process-manager.ts +10 -3
- package/dist/pi-claude-cli/src/prompt-builder.ts +2 -1
- package/dist/pi-claude-cli/src/provider.ts +10 -2
- package/package.json +1 -1
- package/dist/client/assets/ChatView-DEckS3f3.js +0 -1
- package/dist/client/assets/DirectoryPicker-CQtE-YyA.js +0 -1
- package/dist/client/assets/InsightsView-oNQ7h5e8.js +0 -11
- package/dist/client/assets/SettingsModal-C4EwtN6K.js +0 -31
- package/dist/client/assets/SettingsModal-D5hLoLXp.css +0 -1
- package/dist/client/assets/index-D2fXOwWF.css +0 -1
- package/dist/client/assets/index-DlHPhpDu.js +0 -656
|
@@ -0,0 +1,656 @@
|
|
|
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-BQoo_AvX.js","assets/DirectoryPicker-BqcVbDZX.js","assets/folder-open-D0LfE0ZP.js","assets/DirectoryPicker-DzKVmxOf.css","assets/SetupWizardModal-DRF5fOoR.css","assets/SettingsModal-BluRnKGd.js","assets/SettingsModal-C-RjolQ5.js","assets/SettingsModal-C7gPLBaR.css","assets/users-CEcYlrZO.js","assets/star-B_uA5YGG.js","assets/SettingsModal-YjpwLH2V.css","assets/AgentsView-CsEX_Fsi.js","assets/upload-DPQ3hWf0.js","assets/AgentsView-C2f7esMv.css","assets/DocumentsView-zpHkjZdf.js","assets/DocumentsView-BrhyOdeE.css","assets/InsightsView-CgguV1au.js","assets/InsightsView-6LHF7OdE.css","assets/NodesView-DP_O4ae0.js","assets/NodesView-DCoS6iYh.css","assets/ChatView-DhudD-jT.js","assets/RoadmapsView-DNaToPqN.js","assets/RoadmapsView-BOYnyMCh.css","assets/SkillsView-AS8Cr_Md.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-BWXP8uGT.js","assets/MemoryView-DiajLXby.css","assets/DevServerView-CNItMoga.js","assets/DevServerView-DlZpuAnj.css","assets/TodoView-nWOpOg3R.js","assets/list-checks-D1faMe1o.js","assets/TodoView-C1g65hJo.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as a,j as t,R as mo,a as da,g as Fh,c as vg}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 Oh=(...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 yg=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 jg=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 Td=e=>{const n=jg(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 rl={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 kg=e=>{for(const n in e)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},wg=a.createContext({}),Ng=()=>a.useContext(wg),Sg=a.forwardRef(({color:e,size:n,strokeWidth:s,absoluteStrokeWidth:i,className:r="",children:o,iconNode:l,...c},u)=>{const{size:d=24,strokeWidth:m=2,absoluteStrokeWidth:h=!1,color:g="currentColor",className:p=""}=Ng()??{},f=i??h?Number(s??m)*24/Number(n??d):s??m;return a.createElement("svg",{ref:u,...rl,width:n??d??rl.width,height:n??d??rl.height,stroke:e??g,strokeWidth:f,className:Oh("lucide",p,r),...!o&&!kg(c)&&{"aria-hidden":"true"},...c},[...l.map(([x,v])=>a.createElement(x,v)),...Array.isArray(o)?o:[o]])});/**
|
|
33
|
+
* @license lucide-react v1.7.0 - ISC
|
|
34
|
+
*
|
|
35
|
+
* This source code is licensed under the ISC license.
|
|
36
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
37
|
+
*/const Oe=(e,n)=>{const s=a.forwardRef(({className:i,...r},o)=>a.createElement(Sg,{ref:o,iconNode:n,className:Oh(`lucide-${yg(Td(e))}`,`lucide-${e}`,i),...r}));return s.displayName=Td(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 Cg=[["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"}]],Ps=Oe("activity",Cg);/**
|
|
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 Eg=[["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"}]],Ro=Oe("archive",Eg);/**
|
|
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 _g=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],wr=Oe("arrow-down",_g);/**
|
|
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 Mg=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],_a=Oe("arrow-left",Mg);/**
|
|
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 Ag=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],Nr=Oe("arrow-right",Ag);/**
|
|
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 Rg=[["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"}]],Bh=Oe("arrow-up-down",Rg);/**
|
|
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 Tg=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Fi=Oe("arrow-up",Tg);/**
|
|
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 Pg=[["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"}]],Ig=Oe("book-open",Pg);/**
|
|
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 $g=[["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"}]],yn=Oe("bot",$g);/**
|
|
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 Dg=[["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"}]],hc=Oe("box",Dg);/**
|
|
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 Lg=[["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"}]],ho=Oe("brain",Lg);/**
|
|
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 zg=[["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"}]],Uh=Oe("calendar",zg);/**
|
|
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 Fg=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],Og=Oe("check-check",Fg);/**
|
|
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 Bg=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],$n=Oe("check",Bg);/**
|
|
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 Ug=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Vt=Oe("chevron-down",Ug);/**
|
|
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 Hg=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],To=Oe("chevron-left",Hg);/**
|
|
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 qg=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],pn=Oe("chevron-right",qg);/**
|
|
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 Vg=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],ui=Oe("chevron-up",Vg);/**
|
|
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 Wg=[["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"}]],as=Oe("circle-alert",Wg);/**
|
|
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 Kg=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],fn=Oe("circle-check-big",Kg);/**
|
|
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 Gg=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],Po=Oe("circle-dot",Gg);/**
|
|
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 Jg=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]],pc=Oe("circle-question-mark",Jg);/**
|
|
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 Yg=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],Qg=Oe("circle-stop",Yg);/**
|
|
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 Xg=[["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"}]],Sr=Oe("circle-x",Xg);/**
|
|
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 Zg=[["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"}]],ex=Oe("clipboard-list",Zg);/**
|
|
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 tx=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],wi=Oe("clock",tx);/**
|
|
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 nx=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Hh=Oe("code",nx);/**
|
|
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 sx=[["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"}]],ix=Oe("columns-3",sx);/**
|
|
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 ax=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],Bi=Oe("copy",ax);/**
|
|
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 rx=[["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"}]],ox=Oe("cpu",rx);/**
|
|
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 lx=[["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"}]],cx=Oe("download",lx);/**
|
|
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 dx=[["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"}]],ux=Oe("ellipsis-vertical",dx);/**
|
|
198
|
+
* @license lucide-react v1.7.0 - ISC
|
|
199
|
+
*
|
|
200
|
+
* This source code is licensed under the ISC license.
|
|
201
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
202
|
+
*/const mx=[["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"}]],fc=Oe("ellipsis",mx);/**
|
|
203
|
+
* @license lucide-react v1.7.0 - ISC
|
|
204
|
+
*
|
|
205
|
+
* This source code is licensed under the ISC license.
|
|
206
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
207
|
+
*/const hx=[["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"}]],px=Oe("external-link",hx);/**
|
|
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 fx=[["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"}]],gc=Oe("eye-off",fx);/**
|
|
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 gx=[["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"}]],fa=Oe("eye",gx);/**
|
|
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 xx=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}]],Bs=Oe("file-code",xx);/**
|
|
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 bx=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M9 10h6",key:"9gxzsh"}],["path",{d:"M12 13V7",key:"h0r20n"}],["path",{d:"M9 17h6",key:"r8uit2"}]],qh=Oe("file-diff",bx);/**
|
|
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 vx=[["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"}]],yx=Oe("file-minus",vx);/**
|
|
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 jx=[["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"}]],Vh=Oe("file-pen",jx);/**
|
|
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 kx=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],wx=Oe("file-plus",kx);/**
|
|
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 Nx=[["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"}]],Sx=Oe("file-question-mark",Nx);/**
|
|
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 Cx=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"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=Oe("file-text",Cx);/**
|
|
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 Ex=[["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"}]],_x=Oe("file-type",Ex);/**
|
|
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 Mx=[["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"}]],Wh=Oe("file",Mx);/**
|
|
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 Ax=[["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"}]],xc=Oe("folder-git-2",Ax);/**
|
|
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 Rx=[["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"}]],Pd=Oe("folder-root",Rx);/**
|
|
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 Tx=[["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"}]],Un=Oe("folder",Tx);/**
|
|
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 Px=[["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"}]],po=Oe("funnel",Px);/**
|
|
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 Ix=[["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"}]],Zs=Oe("git-branch",Ix);/**
|
|
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 $x=[["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"}]],mr=Oe("git-commit-horizontal",$x);/**
|
|
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 Dx=[["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"}]],Kh=Oe("git-merge",Dx);/**
|
|
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 Lx=[["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"}]],vs=Oe("git-pull-request",Lx);/**
|
|
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 zx=[["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"}]],Io=Oe("globe",zx);/**
|
|
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 Fx=[["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"}]],Gh=Oe("grid-3x3",Fx);/**
|
|
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 Ox=[["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"}]],Qc=Oe("grip-vertical",Ox);/**
|
|
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 Bx=[["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"}]],Ux=Oe("hard-drive",Bx);/**
|
|
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 Hx=[["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"}]],qx=Oe("heart",Hx);/**
|
|
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 Vx=[["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"}]],hr=Oe("history",Vx);/**
|
|
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 Wx=[["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"}]],sr=Oe("inbox",Wx);/**
|
|
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 Kx=[["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"}]],Jh=Oe("key",Kx);/**
|
|
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 Gx=[["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"}]],Jx=Oe("keyboard",Gx);/**
|
|
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 Yx=[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]],Hi=Oe("layers",Yx);/**
|
|
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 Qx=[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]],qi=Oe("layout-grid",Qx);/**
|
|
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 Xx=[["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"}]],ei=Oe("lightbulb",Xx);/**
|
|
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 Zx=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]],ga=Oe("link",Zx);/**
|
|
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 eb=[["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"}]],tb=Oe("list-plus",eb);/**
|
|
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 nb=[["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"}]],$o=Oe("list-tree",nb);/**
|
|
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 sb=[["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"}]],bc=Oe("list",sb);/**
|
|
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 ib=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],rt=Oe("loader-circle",ib);/**
|
|
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 ab=[["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"}]],Do=Oe("lock",ab);/**
|
|
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 rb=[["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"}]],xa=Oe("mail",rb);/**
|
|
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 ob=[["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"}]],vc=Oe("map",ob);/**
|
|
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 lb=[["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"}]],Lo=Oe("maximize-2",lb);/**
|
|
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 cb=[["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"}]],db=Oe("message-square-plus",cb);/**
|
|
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 ub=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],ji=Oe("message-square",ub);/**
|
|
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 mb=[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]],Cr=Oe("minimize-2",mb);/**
|
|
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 hb=[["path",{d:"M5 12h14",key:"1ays0h"}]],pb=Oe("minus",hb);/**
|
|
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 fb=[["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"}]],pr=Oe("monitor",fb);/**
|
|
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 gb=[["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"}]],xb=Oe("move",gb);/**
|
|
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 bb=[["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"}]],yc=Oe("package",bb);/**
|
|
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 vb=[["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"}]],yb=Oe("paperclip",vb);/**
|
|
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 jb=[["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"}]],Xs=Oe("pause",jb);/**
|
|
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 kb=[["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"}]],ss=Oe("pencil",kb);/**
|
|
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 wb=[["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"}]],jn=Oe("play",wb);/**
|
|
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 Nb=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],en=Oe("plus",Nb);/**
|
|
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 Sb=[["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"}]],Yh=Oe("radio",Sb);/**
|
|
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 Cb=[["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"}]],En=Oe("refresh-cw",Cb);/**
|
|
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 Eb=[["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"}]],Id=Oe("rocket",Eb);/**
|
|
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 _b=[["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"}]],Mb=Oe("rotate-ccw",_b);/**
|
|
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 Ab=[["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"}]],Rb=Oe("rotate-cw",Ab);/**
|
|
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 Tb=[["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"}]],Qh=Oe("save",Tb);/**
|
|
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 Pb=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],ma=Oe("search",Pb);/**
|
|
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 Ib=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],zi=Oe("send",Ib);/**
|
|
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 $b=[["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"}]],fr=Oe("server",$b);/**
|
|
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 Db=[["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"}]],or=Oe("settings",Db);/**
|
|
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 Lb=[["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"}]],zb=Oe("shield-alert",Lb);/**
|
|
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 Fb=[["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"}]],Ob=Oe("shield",Fb);/**
|
|
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 Bb=[["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"}]],Ub=Oe("skull",Bb);/**
|
|
533
|
+
* @license lucide-react v1.7.0 - ISC
|
|
534
|
+
*
|
|
535
|
+
* This source code is licensed under the ISC license.
|
|
536
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
537
|
+
*/const Hb=[["path",{d:"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"}]],Xn=Oe("sparkles",Hb);/**
|
|
538
|
+
* @license lucide-react v1.7.0 - ISC
|
|
539
|
+
*
|
|
540
|
+
* This source code is licensed under the ISC license.
|
|
541
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
542
|
+
*/const qb=[["path",{d:"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"}]],Xh=Oe("square-check-big",qb);/**
|
|
543
|
+
* @license lucide-react v1.7.0 - ISC
|
|
544
|
+
*
|
|
545
|
+
* This source code is licensed under the ISC license.
|
|
546
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
547
|
+
*/const Vb=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],bs=Oe("square",Vb);/**
|
|
548
|
+
* @license lucide-react v1.7.0 - ISC
|
|
549
|
+
*
|
|
550
|
+
* This source code is licensed under the ISC license.
|
|
551
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
552
|
+
*/const Wb=[["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"}]],us=Oe("target",Wb);/**
|
|
553
|
+
* @license lucide-react v1.7.0 - ISC
|
|
554
|
+
*
|
|
555
|
+
* This source code is licensed under the ISC license.
|
|
556
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
557
|
+
*/const Kb=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],ci=Oe("terminal",Kb);/**
|
|
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 Gb=[["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"}]],fo=Oe("text-wrap",Gb);/**
|
|
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 Jb=[["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"}]],Zt=Oe("trash-2",Jb);/**
|
|
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 Yb=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],Qb=Oe("trending-up",Yb);/**
|
|
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 Xb=[["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"}]],Xc=Oe("triangle-alert",Xb);/**
|
|
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 Zb=[["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"}]],$d=Oe("unlink",Zb);/**
|
|
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 ev=[["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"}]],ta=Oe("user",ev);/**
|
|
588
|
+
* @license lucide-react v1.7.0 - ISC
|
|
589
|
+
*
|
|
590
|
+
* This source code is licensed under the ISC license.
|
|
591
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
592
|
+
*/const tv=[["path",{d:"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"}]],Zh=Oe("webhook",tv);/**
|
|
593
|
+
* @license lucide-react v1.7.0 - ISC
|
|
594
|
+
*
|
|
595
|
+
* This source code is licensed under the ISC license.
|
|
596
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
597
|
+
*/const nv=[["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"}]],jc=Oe("workflow",nv);/**
|
|
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 sv=[["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"}]],Dd=Oe("wrench",sv);/**
|
|
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 iv=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Ut=Oe("x",iv);/**
|
|
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 av=[["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"}]],Bn=Oe("zap",av),kc="fusion:version-reload",wc="fusion:version-update";function rv(){try{if(sessionStorage.getItem(wc))return sessionStorage.removeItem(wc),!0}catch{}return!1}function ep(e){if(sessionStorage.getItem(kc)){console.warn("[versionCheck] reload already attempted, suppressing",e);return}sessionStorage.setItem(kc,"1"),console.info("[versionCheck] reloading:",e),window.location.reload()}function ov(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 lv(e){return ov(e)?(ep(`chunk load error: ${e?.message??e}`),!0):!1}async function cv(){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 ol=!1;async function ll(){if(!(ol||document.visibilityState!=="visible")){ol=!0;try{const e=await cv();if(e&&e!=="mok8qhv3-349667bf"){try{sessionStorage.setItem(wc,"1")}catch{}ep(`build version changed: mok8qhv3-349667bf -> ${e}`)}}finally{ol=!1}}}function dv(){window.setTimeout(()=>sessionStorage.removeItem(kc),5e3),document.addEventListener("visibilitychange",()=>{ll()}),window.addEventListener("focus",()=>{ll()}),window.setTimeout(()=>void ll(),2e3)}class zo 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),!lv(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(Xc,{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 ns({children:e,onError:n}){return t.jsx(zo,{level:"page",onError:n,children:e})}function Ii({children:e,onError:n}){return t.jsx(zo,{level:"modal",onError:n,children:e})}function uv({children:e,onError:n}){return t.jsx(zo,{level:"root",onError:n,children:e})}const mv="modulepreload",hv=function(e){return"/"+e},Ld={},on=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=hv(d),d in Ld)return;Ld[d]=!0;const m=d.endsWith(".css"),h=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${h}`))return;const g=document.createElement("link");if(g.rel=m?"stylesheet":mv,m||(g.as="script"),g.crossOrigin="",g.href=d,u&&g.setAttribute("nonce",u),document.head.appendChild(g),m)return new Promise((p,f)=>{g.addEventListener("load",p),g.addEventListener("error",()=>f(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return r.then(l=>{for(const c of l||[])c.status==="rejected"&&o(c.reason);return n().catch(o)})},Zc="fn.authToken",zd="token",pv="fn_token";let ha,Fd=!1,go=!1;const Nc="fn:auth-token-recovery-required";function fv(){try{const e=window.localStorage.getItem(Zc);return e&&e.length>0?e:void 0}catch{return}}function tp(e){try{window.localStorage.setItem(Zc,e)}catch{}}function gv(){if(!(Fd||typeof window>"u")){Fd=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(zd);if(!n)return;tp(n),e.searchParams.delete(zd);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function ba(){if(ha!==void 0)return ha;const e=gv();if(e)return ha=e,e;const n=fv();if(n)return ha=n,n}function xv(e){ha=e,go=!1,tp(e)}function bv(){ha=void 0,go=!1;try{window.localStorage.removeItem(Zc)}catch{}}function Od(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function vv(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function yv(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!vv(e.protocol))return!1;const s=e.hostname===n.hostname,i=e.port===n.port,r=Od(e.protocol)===Od(n.protocol);return s&&i&&r}function jv(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 ti(e){const n=ba();if(!n||typeof window>"u")return e;const s=jv(e);return!s||!yv(s.parsed)?e:(s.parsed.searchParams.set(pv,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function mi(e){const n=ba();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function kv(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function wv(){typeof window>"u"||go||(go=!0,window.dispatchEvent(new CustomEvent(Nc)))}async function Nv(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();kv(i)&&wv()}catch{}}function Sv(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,ba();const e=window.fetch.bind(window);window.fetch=function(s,i){const r=ba(),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=>(Nv(u),u))}}class Cv extends Error{status;details;constructor(n,s,i){super(n),this.name="ApiRequestError",this.status=s,this.details=i}}function Ev(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function rs(e){return`/api${e}`}async function z(e,n={}){const s=rs(e),i=ba(),r=(()=>{if(i){const g=new Headers(n.headers??{});return g.has("Content-Type")||g.set("Content-Type","application/json"),mi(g)}if(!n.headers)return{"Content-Type":"application/json"};const h=new Headers(n.headers);return h.has("Content-Type")||h.set("Content-Type","application/json"),Object.fromEntries(h.entries())})(),o=await fetch(s,{...n,headers:r});if(o.status===204){if(!o.ok)throw new Error(`Request failed for ${s}: ${o.status} ${o.statusText}`);return}const l=o.headers.get("content-type")??"",c=await o.text(),u=l.includes("application/json");if(l.includes("text/html")||Ev(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 Cv(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return m}function XP(){return z("/health")}function ZP(){return z("/updates/check")}function _v(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 z(`/tasks${l}`)}async function xo(e,n){const i=rs(K(`/tasks/${e}`,n));for(let r=1;r<=2;r++){const o=await fetch(i,{headers:mi({"Content-Type":"application/json"})}),l=await o.json();if(o.ok)return l;if(r===2)throw new Error(l.error||"Request failed")}throw new Error("Request failed")}function np(e,n){const{title:s,description:i,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:u,modelPresetId:d,modelProvider:m,modelId:h,validatorModelProvider:g,validatorModelId:p,planningModelProvider:f,planningModelId:x,thinkingLevel:v,summarize:b,reviewLevel:y,executionMode:S,priority:j}=e;return z(K("/tasks",n),{method:"POST",body:JSON.stringify({title:s,description:i,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:u,modelPresetId:d,modelProvider:m,modelId:h,validatorModelProvider:g,validatorModelId:p,planningModelProvider:f,planningModelId:x,thinkingLevel:v,summarize:b,reviewLevel:y,executionMode:S,priority:j})})}function Qs(e,n,s){return z(K(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Mv(e,n,s,i,r,o,l,c,u){return z(K("/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 Av(e,n,s){return z(K(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n})})}function Rv(e,n,s){const i=new URLSearchParams,r=i.size>0?`?${i.toString()}`:"";return z(K(`/tasks/${e}${r}`,n),{method:"DELETE"})}function Tv(e,n){return z(K(`/tasks/${e}/merge`,n),{method:"POST"})}function Pv(e,n){return z(K(`/tasks/${e}/retry`,n),{method:"POST"})}function Iv(e,n){return z(K(`/tasks/${e}/duplicate`,n),{method:"POST"})}function sp(e,n){return z(K(`/tasks/${e}/pause`,n),{method:"POST"})}function $v(e,n){return z(K(`/tasks/${e}/unpause`,n),{method:"POST"})}function Dv(e,n){return z(K(`/tasks/${e}/archive`,n),{method:"POST"})}function Lv(e,n){return z(K(`/tasks/${e}/unarchive`,n),{method:"POST"})}function zv(e){return z(K("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function Fv(e,n){return z(K(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function Ov(e,n){return z(K(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function Bv(e){return z(K("/config",e))}function Fo(e){return z(K("/settings",e))}function Br(e,n){return z(K("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function Uv(e){return z(K("/update-check",e))}function eI(e){return z(K("/remote/settings",e))}function tI(e,n){return z(K("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function nI(e){return z(K("/remote/status",e))}function sI(e){return z(K("/remote/tunnel/start",e),{method:"POST"})}function iI(e){return z(K("/remote/tunnel/stop",e),{method:"POST"})}function aI(e){return z(K("/remote/token/persistent/regenerate",e),{method:"POST"})}function rI(e,n){return z(K("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function ip(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 oI(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:i}=e,r=ip(null,s,i);return z(K(`/remote/url${r}`,n))}function lI(e="text",n={}){const{projectId:s,tokenType:i="persistent",ttlMs:r}=n,o=ip(e,i,r);return z(K(`/remote/qr${o}`,s))}function cI(e){return z(K("/memory",e))}function dI(e,n){return z(K("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function uI(e){return z(K("/memory/files",e))}function mI(e,n){const s=`path=${encodeURIComponent(e)}`;return z(K(`/memory/file?${s}`,n))}function hI(e,n,s){return z(K("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function pI(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 z(K("/memory/compact",i),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function fI(e){return z(K("/memory/dream",e),{method:"POST"})}function gI(e){return z(K("/memory/insights",e))}function xI(e,n){return z(K("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function bI(e){return z(K("/memory/extract",e),{method:"POST"})}function vI(e){return z(K("/memory/audit",e))}function yI(e){return z(K("/memory/stats",e))}function jI(e){return z(K("/memory/backend",e))}function kI(e){return z(K("/memory/install-qmd",e),{method:"POST"})}function wI(e,n){return z(K("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function Gi(){return z("/settings/global")}function ln(e){return z("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function NI(e){return z(K("/settings/scopes",e))}function SI(e){return z(K("/settings/pi-extensions",e))}function CI(e,n){return z(K("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function EI(e,n,s){return z(K("/settings/test-notification",s),{method:"POST",body:JSON.stringify({providerId:e,...n??{}})})}function _I(){return z("/pi-settings")}async function MI(e){return z("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function AI(e){return z("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function RI(e){return z(K("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function gr(e,n,s){const i=new FormData;i.append("file",n);const r=await fetch(rs(K(`/tasks/${e}/attachments`,s)),{method:"POST",headers:mi(),body:i}),o=await r.json();if(!r.ok)throw new Error(o.error||"Upload failed");return o}async function Hv(e,n,s){return z(K(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function Bd(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=K(`/tasks/${e}/logs${r}`,n),l=await fetch(rs(o),{headers:mi()});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 qv(e,n,s,i){return z(K(`/tasks/${e}/comments/${n}`,i),{method:"PATCH",body:JSON.stringify({text:s})})}function Vv(e,n,s){return z(K(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function Wv(e,n){return z(K(`/tasks/${e}/documents`,n))}function Kv(e,n,s){return z(K(`/tasks/${e}/documents/${n}/revisions`,s))}async function TI(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 z(K(r,n))}function PI(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const i=s.toString(),r=`/files/markdown-list${i?`?${i}`:""}`;return z(K(r,e))}function Ud(e,n,s,i,r){return z(K(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:i?.author,metadata:i?.metadata})})}function Gv(e,n,s){return z(K(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function Jv(e,n,s){return z(K(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function Yv(e,n,s){return z(K(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Qv(e,n){return z(K(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function Xv(e,n,s){return z(K(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function ms(){return z("/models")}function Zv(){return z("/usage")}function ey(){return z("/providers/claude-cli/status")}async function II(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return z(`/providers/hermes/status${n}`)}async function $I(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return(await z(`/providers/hermes/profiles${n}`)).profiles??[]}async function DI(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return z(`/providers/openclaw/status${n}`)}async function LI(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),z(`/providers/paperclip/status?${n.toString()}`)}async function zI(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),(await z(`/providers/paperclip/companies?${n.toString()}`)).companies??[]}async function FI(e){const n=new URLSearchParams({apiUrl:e.apiUrl,companyId:e.companyId});return e.apiKey&&n.set("apiKey",e.apiKey),(await z(`/providers/paperclip/agents?${n.toString()}`)).agents??[]}async function OI(e){return z("/providers/paperclip/cli-mint-key",{method:"POST",body:JSON.stringify(e)})}async function BI(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return z(`/providers/paperclip/cli-status${s?`?${s}`:""}`)}async function UI(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 z(`/providers/paperclip/cli-companies${s?`?${s}`:""}`)).companies??[]}async function HI(e){const n=new URLSearchParams({companyId:e.companyId});return e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath),(await z(`/providers/paperclip/cli-agents?${n.toString()}`)).agents??[]}async function qI(e={}){const n=new URLSearchParams;e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return z(`/providers/paperclip/cli-discovery${s?`?${s}`:""}`)}function ty(e){return z("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function xr(){return z("/auth/status")}function ny(e){return z("/auth/login",{method:"POST",body:JSON.stringify({provider:e,origin:window.location.origin})})}function sy(e){return z("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function iy(e,n){return z("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function ay(e){return z("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function ry(e,n,s,i){return z("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:i})})}function oy(e,n,s,i){return z(K("/github/issues/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function ly(e,n,s){return z("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function cy(e,n,s,i){return z(K("/github/pulls/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function dy(e){return z(K("/git/remotes",e))}function uy(e){return z(K("/git/remotes/detailed",e))}function my(e,n,s){return z(K("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function hy(e,n){return z(K(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function py(e,n,s){return z(K(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function fy(e,n,s){return z(K(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function gy(e,n,s){return z(K(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function xy(e,n){return z(K(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}async function by(e,n){return(await z(K("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:e})})).results}function Ur(e,n,s,i){return z(K("/terminal/sessions",i),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function Hd(e,n){return z(K(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function vy(e){return z(K("/terminal/sessions",e))}function Os(e){return z(K("/git/status",e))}function yy(e,n){const s=e?`?limit=${e}`:"";return z(K(`/git/commits${s}`,n))}function bo(e,n){return z(K(`/git/commits/${e}/diff`,n))}function jy(e){return z(K("/git/commits/ahead",e))}function ky(e,n,s,i){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return z(K(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,i))}function za(e){return z(K("/git/branches",e))}function wy(e,n,s){const i=`?limit=${n}`;return z(K(`/git/branches/${encodeURIComponent(e)}/commits${i}`,s))}function Ny(e){return z(K("/git/worktrees",e))}function Sy(e,n,s){return z(K("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function Cy(e,n){return z(K(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function qd(e,n,s){const i=n?"?force=true":"";return z(K(`/git/branches/${encodeURIComponent(e)}${i}`,s),{method:"DELETE"})}function Ey(e,n){return z(K("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function _y(e){return z(K("/git/pull",e),{method:"POST"})}function My(e){return z(K("/git/push",e),{method:"POST"})}function Hr(e){return z(K("/git/stashes",e))}function Ay(e,n){return z(K("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function Ry(e,n,s){return z(K(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function Ty(e,n){return z(K(`/git/stashes/${e}`,n),{method:"DELETE"})}function Py(e,n,s){const i=new URLSearchParams;return i.set("path",e),i.set("staged",String(n)),z(K(`/git/diff/file?${i.toString()}`,s))}function na(e){return z(K("/git/changes",e))}function Vd(e,n){return z(K("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function Iy(e,n){return z(K("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function Wd(e,n){return z(K("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function $y(e,n){return z(K("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function Dy(e){return z(K("/workspaces",e))}function Ly(e,n,s){const i=new URLSearchParams({workspace:e});return n&&i.set("path",n),s&&i.set("projectId",s),z(`/files?${i.toString()}`)}function zy(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),z(`/files/${encodeURIComponent(n)}?${i.toString()}`)}function Fy(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),z(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function Oy(e,n,s){const i=new URLSearchParams({q:e});return n&&i.set("workspace",n),s&&i.set("projectId",s),z(`/files/search?${i.toString()}`)}function By(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),z(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function Uy(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),z(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function Hy(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),z(`/files/${encodeURIComponent(n)}/delete?${i.toString()}`,{method:"POST"})}function qy(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),z(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function ap(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${i.toString()}`}function Vy(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${i.toString()}`}function Wy(e,n,s){return z(K("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function Ky(e,n,s,i){return z(K("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Gy(e,n,s){return z(K(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Jy(e,n,s){return z(K(`/planning/${encodeURIComponent(e)}/stop`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function rp(e,n,s){return z(K("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function Yy(e,n,s){return z(K("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Qy(e,n,s){return z(K("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Xy(e,n,s){return z(K("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const Sc=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(Sc))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function Zy(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function Er(e,n,s={}){const i=s.maxReconnectAttempts??10;let r=null,o=!1,l=0,c=null,u=null,d=!1;const m=p=>{const f=p.lastEventId;if(!f)return!0;const x=Number.parseInt(f,10);return Number.isFinite(x)?u!==null&&x<=u?!1:(u=x,!0):!0},h=()=>{if(o)return;const p=Zy(e,u),f=new EventSource(ti(p));r=f,f.onopen=()=>{l=0,d=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},f.onmessage=x=>{const v=x;m(v)&&n.onMessage?.(v)};for(const[x,v]of Object.entries(n.events??{}))f.addEventListener(x,b=>{const y=b;m(y)&&v(y)});f.onerror=()=>{if(o||r!==f)return;if(f.readyState===EventSource.CONNECTING){d||(d=!0,s.onConnectionStateChange?.("reconnecting"));return}if(f.close(),l>=i){s.onFatalError?.("Connection lost");return}d=!0,s.onConnectionStateChange?.("reconnecting"),l+=1;const v=Math.min(1e3*2**(l-1),3e4);c=setTimeout(()=>{c=null,h()},v)}};h();const g={close:()=>{o=!0,c&&(clearTimeout(c),c=null),r?.close(),Sc.delete(g)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return Sc.add(g),g}function Kd(e){const n=typeof e.source=="string"&&e.source.trim().length>0?e.source.trim():"root",s=n==="root"?".":n,i=e.name,r=typeof e.packagePath=="string"&&e.packagePath.trim().length>0?e.packagePath.trim():s,o=typeof e.confidence=="number"?e.confidence:1,l=n==="root"?"root":n,c=typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():"project";return{name:e.name,command:e.command,scriptName:i,packagePath:r,confidence:o,cwd:s,source:n,workspaceName:typeof e.packageName=="string"?e.packageName:void 0,label:`${c} · ${i} (${l})`}}function va(e){const n=e.status,s=n==="starting"||n==="running"||n==="failed"||n==="stopped"?n:"stopped",i=typeof e.previewUrl=="string"?e.previewUrl:e.detectedUrl,r=typeof e.manualPreviewUrl=="string"?e.manualPreviewUrl:e.manualUrl;return{id:typeof e.id=="string"?e.id:"",name:typeof e.name=="string"&&e.name.length>0?e.name:"default",status:s,command:typeof e.command=="string"?e.command:"",scriptName:typeof e.scriptId=="string"?e.scriptId:"",cwd:typeof e.cwd=="string"?e.cwd:"",pid:e.pid,startedAt:e.startedAt,previewUrl:i,detectedUrl:typeof e.detectedUrl=="string"?e.detectedUrl:i,detectedPort:e.detectedPort,manualPreviewUrl:r,manualUrl:typeof e.manualUrl=="string"?e.manualUrl:r,logs:Array.isArray(e.logHistory)?e.logHistory:[],exitCode:e.exitCode}}function ej(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 tj(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((i,r)=>ej(i,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function nj(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 Gd(e){return Array.isArray(e)?e.map(Kd):(e.candidates??[]).map(Kd)}async function sj(e){try{const n=await z(K("/dev-server/candidates",e));return Gd(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await z(K("/dev-server/detect",e));return Gd(s)}throw n}}function ed(e){return z(K("/dev-server/status",e)).then(va)}async function VI(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 z(K(`/dev-server/logs/history${i}`,n));return tj(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await ed(n);return nj(o.logs,e)}throw r}}function ij(e,n){const s=e.cwd??e.packagePath??".",i=e.scriptName;return z(K("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:i,scriptId:i,cwd:s,packagePath:e.packagePath})}).then(va)}function aj(e){return z(K("/dev-server/stop",e),{method:"POST"}).then(va)}function rj(e){return z(K("/dev-server/restart",e),{method:"POST"}).then(va)}async function oj(e,n){const s=typeof e=="string"?{url:e}:e;try{const i=await z(K("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return va(i)}catch(i){if(i instanceof Error&&/\/dev-server\/preview-url/.test(i.message)){const r=await z(K("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return va(r)}throw i}}function WI(e){return rs(K("/dev-server/logs/stream",e))}async function KI(e){try{return(await z(K("/devserver",e))).sessions??[]}catch{try{const n=await ed(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 GI(e,n){try{return await z(K(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await ed(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 JI(e,n){try{return await z(K(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await ij({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 YI(e,n){try{return await z(K(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await aj(n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}}}async function QI(e,n){try{return await z(K(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await rj(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 XI(e,n,s){try{const i=await z(K(`/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 oj({url:n},s);return{url:i.previewUrl??i.manualUrl??null,source:"manual"}}}async function ZI(e){try{return(await z(K("/devserver/detect",e))).candidates??[]}catch{try{return(await sj(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function e$(e,n){return rs(K(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function _r(e,n,s=25e3){const i=setInterval(()=>{Bk(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(i)}}}function lj(e,n){return rs(K(`/planning/${encodeURIComponent(e)}/stream`,n))}function cj(e,n,s,i){const r=lj(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Er(r,{onOpen:()=>{c(),o=_r(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 Mr(e,n){const s=new URLSearchParams;n?.scope&&s.set("scope",n.scope),n?.projectId&&s.set("projectId",n.projectId);const i=s.toString();return i?`${e}?${i}`:e}function dj(e){return z(Mr("/routines",e))}function uj(e,n){return z(Mr("/routines",n),{method:"POST",body:JSON.stringify(e)})}function Jd(e,n,s){return z(Mr(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function mj(e,n){await z(Mr(`/routines/${e}`,n),{method:"DELETE"})}function hj(e,n){return z(Mr(`/routines/${e}/trigger`,n),{method:"POST"})}function Yd(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 z(`/activity${s}`)}function pj(e){const n=K("/activity",e);return z(n,{method:"DELETE"})}function Oo(e){return z(K("/workflow-steps",e))}function Qd(e,n){return z(K("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function fj(e,n,s){return z(K(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function gj(e,n){return z(K(`/workflow-steps/${e}`,n),{method:"DELETE"})}function Xd(e,n){return z(K(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function xj(e,n){return z(K(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function bj(){return z("/workflow-step-templates")}function vj(e,n){return z(K(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function br(e){return z(K("/scripts",e))}function yj(e,n,s){return z(K("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function jj(e,n){return z(K(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function op(e,n,s){return(await z(K("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const qr={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 lp(e){if(!(e instanceof Error))return qr.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?qr.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?qr.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:qr.NETWORK}function kj(e,n){return z(K("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function wj(e,n,s){return z(K(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Nj(e,n){return rs(K(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function Sj(e,n,s,i){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=Er(Nj(e,n),{onOpen:()=>{l(),r=_r(e,n)},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},subtasks:u=>{try{s.onSubtasks?.(JSON.parse(u.data))}catch(d){console.error("[subtasks] Failed to parse subtasks event:",d)}},error:u=>{try{const d=JSON.parse(u.data),m=typeof d=="string"&&d.length>0?d:null;s.onError?.(m||"Stream error")}catch{s.onError?.("Stream error")}o?.close()},complete:()=>{s.onComplete?.(),o?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{l(),s.onError?.(u)}});return o={close:()=>{l(),c.close()},isConnected:c.isConnected},o}function Cj(e,n,s,i){return z(K("/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 cp(e,n,s){return z(K("/subtasks/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function K(e,n){if(!n)return e;const s=e.includes("?")?"&":"?";return`${e}${s}projectId=${encodeURIComponent(n)}`}function Ej(e,n,s){if(!n||n===s)return e;const i="/api",r=e.startsWith(i)?e.slice(i.length):e;return`/proxy/${encodeURIComponent(n)}${r}`}function Bo(e,n){const{nodeId:s,localNodeId:i,...r}=n??{},o=Ej(e,s,i);return z(o,r)}function Ma(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 z(`/agents${i}`)}function dp(e,n){return z(K(`/agents/${encodeURIComponent(e)}`,n))}function _j(e,n){return z(K("/agents",n),{method:"POST",body:JSON.stringify(e)})}function Mj(e,n,s){return z(K(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function t$(e,n,s){return z(K(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function n$(e,n,s){return z(K(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function s$(e,n,s){return z(K(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function i$(e,n){return z(K(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function a$(e,n,s){const i=`path=${encodeURIComponent(n)}`;return z(K(`/agents/${encodeURIComponent(e)}/memory/file?${i}`,s))}function r$(e,n,s,i){return z(K(`/agents/${encodeURIComponent(e)}/memory/file`,i),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function Aj(e,n,s){return z(K(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function Rj(e,n){return z(K(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function o$(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 z(`/agents/${encodeURIComponent(e)}/runs${r}`)}function l$(e,n,s){return z(K(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function c$(e,n,s){return z(K(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function d$(e,n,s){const i=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return z(K(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:i,triggerDetail:r})})}function u$(e,n){return z(K(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function Tj(e){return z(K("/agents/stats",e))}function m$(e,n){return z(K(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function h$(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeEphemeral&&s.set("includeEphemeral","true");const i=s.toString();return z(`/agents/org-tree${i?`?${i}`:""}`)}function p$(e,n){return z(K(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function Zd(e,n,s){return z(K(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function f$(e,n){return z(K(`/agents/${encodeURIComponent(e)}/tasks`,n))}function g$(){return z("/agents/companies")}function x$(e,n){return z(K("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function b$(e,n){return z(K("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function v$(e,n){return z(K(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function y$(e){return z(K("/backups",e))}function j$(e){return z(K("/backups",e),{method:"POST"})}function k$(e,n){const s=K("/settings/export",n),i=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return z(i)}function w$(e,n,s){return z(K("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}function eu(){return z("/projects/across-nodes")}function lr(e,n){z("/_perf/dashboard-load",{method:"POST",body:JSON.stringify({source:e,message:n})}).catch(()=>{})}function vo(){return z("/nodes")}function Pj(e){return z("/nodes",{method:"POST",body:JSON.stringify(e)})}function Ij(e,n){return z(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function $j(e){return z(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Dj(e){const n=await z(`/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 N$(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=ba();l&&o.set("fn_token",l);const c=o.toString(),u=`/browse-directory${c?`?${c}`:""}`;return z(u)}function Lj(e){return z("/projects",{method:"POST",body:JSON.stringify(e)})}function up(e){return z(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function tu(e){return z(`/projects/${encodeURIComponent(e)}/health`)}function zj(e){return z(K("/executor/stats",e))}function Fj(e){return z(K("/system-stats",e))}function Oj(e){return z(K("/kill-vitest",e),{method:"POST"})}function nu(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 z(`/activity-feed${s}`)}function Bj(e){return z(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function Uj(e){return z(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function S$(){return z("/global-concurrency")}function C$(e){return z("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function Hj(e,n){return z(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function mp(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 z(`/tasks/${encodeURIComponent(e)}/diff${r}`)}function qj(e){return z(K("/missions",e))}function Vj(e,n){return z(K("/missions",n),{method:"POST",body:JSON.stringify(e)})}function hp(e,n){return z(K(`/missions/${encodeURIComponent(e)}`,n))}function Wj(e,n,s){return z(K(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Kj(e,n){return z(K(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Gj(e,n,s){const i=new URLSearchParams;i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset));const r=i.size>0?`?${i.toString()}`:"";return z(K(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function Jj(e){return z(K("/missions/health",e))}function Yj(e,n,s){return z(K(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function Qj(e,n,s){return z(K(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Xj(e,n){return z(K(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Zj(e,n,s){return z(K(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function ek(e,n,s){return z(K(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function tk(e,n){return z(K(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function nk(e,n){return z(K(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function sk(e,n,s){return z(K(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function ik(e,n,s){return z(K(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function ak(e,n){return z(K(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function rk(e,n,s){return z(K(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function ok(e,n){return z(K(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function lk(e,n,s,i){return z(K(`/missions/features/${encodeURIComponent(e)}/triage`,i),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s})})}function ck(e,n){return z(K(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST"})}function cl(e,n){return z(K(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function dk(e,n,s){return z(K(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function uk(e,n,s){return z(K(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function mk(e,n,s){return z(K(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function hk(e,n,s){return z(K(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function pk(e,n){return z(K(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function dl(e,n){return z(K(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function su(e,n){return z(K(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function fk(e,n){return z(K(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function iu(e,n){return z(K(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function gk(e,n,s){const i=new URLSearchParams;i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset));const r=i.size>0?`?${i.toString()}`:"";return z(K(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function xk(e,n){return z(K(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function bk(e,n){return z(K(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function vk(e,n){return z(K(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function yk(e,n){return z(K(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function jk(e,n,s){return z(K(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function kk(e,n,s){return z(K("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function wk(e,n,s,i){return z(K("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Nk(e,n,s){return z(K(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function pp(e,n,s){return z(K("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function Sk(e,n,s){return z(K("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function Ck(e,n,s,i){const r=rs(K(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Er(r,{onOpen:()=>{c(),o=_r(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 Ar(e,n,s){return K(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function Rr(e,n,s){return K(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function Ek(e,n){return z(Ar(e,"/start",n),{method:"POST"})}function _k(e,n,s,i){return z(Ar(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Mk(e,n,s,i){const r=rs(Ar(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Er(r,{onOpen:()=>{c(),o=_r(e,n)},onMessage:d=>{d.data.startsWith(":")},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},question:d=>{try{s.onQuestion?.(JSON.parse(d.data))}catch(m){console.error("[milestone-interview] Failed to parse question event:",m)}},summary:d=>{try{s.onSummary?.(JSON.parse(d.data))}catch(m){console.error("[milestone-interview] Failed to parse summary event:",m)}},error:d=>{try{const m=JSON.parse(d.data);s.onError?.(m.message||m)}catch{s.onError?.(d.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{c(),s.onError?.(d)}});return l={close:()=>{c(),u.close()},isConnected:u.isConnected},l}function Ak(e,n,s){return z(Ar(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function Rk(e,n){return z(Ar(e,"/skip",n),{method:"POST"})}function Tk(e,n){return z(Rr(e,"/start",n),{method:"POST"})}function Pk(e,n,s,i){return z(Rr(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Ik(e,n,s,i){const r=rs(Rr(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Er(r,{onOpen:()=>{c(),o=_r(e,n)},onMessage:d=>{d.data.startsWith(":")},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},question:d=>{try{s.onQuestion?.(JSON.parse(d.data))}catch(m){console.error("[slice-interview] Failed to parse question event:",m)}},summary:d=>{try{s.onSummary?.(JSON.parse(d.data))}catch(m){console.error("[slice-interview] Failed to parse summary event:",m)}},error:d=>{try{const m=JSON.parse(d.data);s.onError?.(m.message||m)}catch{s.onError?.(d.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{c(),s.onError?.(d)}});return l={close:()=>{c(),u.close()},isConnected:u.isConnected},l}function $k(e,n,s){return z(Rr(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function Dk(e,n){return z(Rr(e,"/skip",n),{method:"POST"})}async function Lk(e,n){try{return await z(K(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function E$(e){return z(K("/roadmaps",e))}function _$(e,n){return z(K("/roadmaps",n),{method:"POST",body:JSON.stringify(e)})}function M$(e,n){return z(K(`/roadmaps/${encodeURIComponent(e)}`,n))}function A$(e,n,s){return z(K(`/roadmaps/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function R$(e,n){return z(K(`/roadmaps/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function T$(e,n,s){return z(K(`/roadmaps/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function P$(e,n,s){return z(K(`/roadmaps/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function I$(e,n){return z(K(`/roadmaps/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function $$(e,n,s){return z(K(`/roadmaps/milestones/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function D$(e,n,s){return z(K(`/roadmaps/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function L$(e,n){return z(K(`/roadmaps/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function z$(e,n,s){return z(K(`/roadmaps/${encodeURIComponent(e)}/milestones/reorder`,s),{method:"POST",body:JSON.stringify({orderedMilestoneIds:n})})}function F$(e,n,s){return z(K(`/roadmaps/milestones/${encodeURIComponent(e)}/features/reorder`,s),{method:"POST",body:JSON.stringify({orderedFeatureIds:n})})}function O$(e,n,s,i){return z(K(`/roadmaps/features/${encodeURIComponent(e)}/move`,i),{method:"POST",body:JSON.stringify({targetMilestoneId:n,targetIndex:s})})}function B$(e,n){return z(K(`/roadmaps/${encodeURIComponent(e)}/handoff`,n))}function U$(e,n,s,i){return z(K(`/roadmaps/${encodeURIComponent(e)}/suggestions/milestones`,i),{method:"POST",body:JSON.stringify({goalPrompt:n.trim(),...s!==void 0?{count:s}:{}})})}function H$(e,n,s){return z(K(`/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 q$(e){return z(K("/todos",e))}function V$(e,n){const s={title:e};return z(K("/todos",n),{method:"POST",body:JSON.stringify(s)})}function W$(e,n,s){const i={title:n};return z(K(`/todos/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(i)})}function K$(e,n){return z(K(`/todos/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function G$(e,n,s){const i={text:n};return z(K(`/todos/${encodeURIComponent(e)}/items`,s),{method:"POST",body:JSON.stringify(i)})}function J$(e,n,s){const i=n;return z(K(`/todos/items/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(i)})}function Y$(e,n){return z(K(`/todos/items/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Q$(e,n,s){return z(K(`/todos/${encodeURIComponent(e)}/items/reorder`,s),{method:"POST",body:JSON.stringify({itemIds:n})})}function ya(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function td(e){const n=e?`?projectId=${encodeURIComponent(e)}`:"",s=await fetch(rs(`/ai-sessions${n}`),{headers:mi()});return s.ok?(await s.json()).sessions??[]:[]}async function di(e){const n=await fetch(rs(`/ai-sessions/${encodeURIComponent(e)}`),{headers:mi()});return n.ok?n.json():null}async function zk(e,n){const s=await z(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function Fk(e,n){return z(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function Ok(e,n){return z(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function fp(e){await fetch(rs(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:mi()})}function Bk(e,n){return z(K(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function Uk(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 z(`/messages/inbox${i}`)}function Hk(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 z(`/messages/outbox${i}`)}function gp(e){return z(K("/messages/unread-count",e))}function qk(e,n){return z(K("/messages",n),{method:"POST",body:JSON.stringify(e)})}function Vk(e,n){return z(K(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function Wk(e){return z(K("/messages/read-all",e),{method:"POST"})}function Kk(e,n){return z(K(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Gk(e,n,s){const i=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return z(K(i,s))}function Jk(e,n){return z(K(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function X$(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 z(`/agents/${encodeURIComponent(e)}/reflections${r}`)}function Z$(e,n){return z(K(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function eD(e,n,s){const i=new URLSearchParams;s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return z(`/agents/${encodeURIComponent(e)}/performance${r}`)}function tD(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 z(`/agents/${encodeURIComponent(e)}/ratings${r}`)}function nD(e,n,s){return z(K(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function sD(e,n){return z(K(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function iD(e,n,s){return z(K(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function aD(e,n){return z(K(`/agents/${encodeURIComponent(e)}/budget`,n))}function rD(e,n){return z(K(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function oD(e){return z(K("/plugins",e))}async function lD(e,n){return z(K("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function cD(e,n){return z(K(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function dD(e,n){return z(K(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function uD(e,n){return z(K(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function mD(e,n){return z(K(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function hD(e,n,s){return z(K(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function pD(e,n){return z(K(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function Yk(e){return z(K("/plugins/ui-slots",e))}async function fD(e){return z(K("/plugins/runtimes",e))}async function gD(e){return(await z(K("/skills/discovered",e))).skills}async function xD(e,n,s){return z(K("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function bD(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 z(K(`/skills/catalog${r}`,s))}async function vD(e,n){return(await z(K(`/skills/${encodeURIComponent(e)}/content`,n))).content}function yD(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const i=s.toString();return z(`/chat/sessions${i?`?${i}`:""}`)}async function Qk(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 z(`/chat/sessions?${o.toString()}`)).sessions[0]??null}}function Xk(e,n){return z(K("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function jD(e,n,s){return z(K(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function kD(e,n){return z(K(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function au(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 z(K(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function Zk(e,n){return z(K(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function ew(e,n,s,i,r,o){const l=rs(K(`/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 g=JSON.parse(h);s.onError?.(g.message||g)}catch{s.onError?.(h||"Stream error")}break}};return(async()=>{try{const m=Array.isArray(i)&&i.length>0,h=m?(()=>{const S=new FormData;return S.append("content",n),i.forEach(j=>S.append("attachments",j)),S})():JSON.stringify({content:n}),g=await fetch(l,{method:"POST",headers:m?mi():mi({"Content-Type":"application/json"}),body:h,signal:c.signal});if(!g.ok){const S=await g.text();let j=`Request failed: ${g.status}`;try{j=JSON.parse(S).error||j}catch{}s.onError?.(j);return}if(!g.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected");const p=g.body.getReader(),f=new TextDecoder;let x="",v="",b=[];const y=(S,j=!1)=>{x+=S;const R=x.split(`
|
|
613
|
+
`);x=R.pop()||"",j&&x.length>0&&(R.push(x),x="");for(const k of R){const M=k.endsWith("\r")?k.slice(0,-1):k;if(M.startsWith("event:"))v=M.slice(6).trim();else if(M.startsWith("data:")){const C=M.slice(5);b.push(C.startsWith(" ")?C.slice(1):C)}else if(M===""){const C=b.join(`
|
|
614
|
+
`);d(v,C),v="",b=[]}}if(j&&v&&b.length>0){const k=b.join(`
|
|
615
|
+
`);d(v,k),v="",b=[]}};for(;;){const{done:S,value:j}=await p.read();if(S){y(f.decode(),!0);break}y(f.decode(j,{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 wD(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 z(K(`/insights${i}`,n))}function ND(e,n){return z(K(`/insights/${encodeURIComponent(e)}/dismiss`,n),{method:"POST"})}function SD(e="manual",n,s){return z(K("/insights/run",s),{method:"POST",body:JSON.stringify({trigger:e,inputMetadata:n})})}function CD(e){return z(K("/insights/runs",e))}function ED(e,n){return z(K(`/insights/${encodeURIComponent(e)}/create-task`,n),{method:"POST"})}function tw(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 nw({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}=tw(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 sw(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Vi({status:e,showLabel:n=!1,className:s,compact:i=!1}){const r=sw(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 ru=new Map,iw=6e4;function xp(e){const[n,s]=a.useState([]),[i,r]=a.useState(!0),[o,l]=a.useState(null),c=a.useRef(!1),u=a.useRef(!1),d=a.useCallback(m=>n.filter(h=>h.slot.slotId===m),[n]);return a.useEffect(()=>{const m=e??"default";let h=!1;async function g(){const p=ru.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 x=await Yk(e);if(h||u.current)return;ru.set(m,{slots:x,expiresAt:Date.now()+iw}),s(x),c.current=!0}catch(x){if(h||u.current)return;l(x instanceof Error?x.message:"Failed to fetch UI slots"),c.current=!0}finally{!h&&!u.current&&r(!1)}}return g(),()=>{h=!0}},[e]),a.useEffect(()=>{c.current=!1,u.current=!1},[e]),a.useEffect(()=>()=>{u.current=!0},[]),a.useMemo(()=>({slots:n,getSlotsForId:d,loading:i,error:o}),[n,d,i,o])}function Uo({slotId:e,projectId:n}){const{getSlotsForId:s,loading:i,error:r}=xp(n);if(i||r||!e)return null;const o=s(e);return o.length===0?null:t.jsx(zo,{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 aw(){return typeof window>"u"?"desktop":window.matchMedia("(max-width: 768px)").matches?"mobile":window.matchMedia("(min-width: 769px) and (max-width: 1024px)").matches?"tablet":"desktop"}function Tr(){const[e,n]=a.useState(aw);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 Aa(e){return e.replace(/\\/g,"/")}function nd(e){return e.replace(/[\\/]+$/g,"")}function sd(e){const n=Aa(nd(e));return n?n.split("/").filter(Boolean):[]}function id(e){const n=Aa(nd(e));if(!n)return e;const s=n.split("/").filter(Boolean);return s[s.length-1]||n}function bp(e,n){const s=sd(e);return s.length===0?Aa(e):s.slice(-2).join("/")}function rw(e){const n=Aa(nd(e)),s=n.lastIndexOf("/");return s<0?"":n.slice(0,s+1)}function ow(e,n){return!e||e==="."?n:[...sd(e),n].join("/")}function lw(e){const n=sd(e);return n.length===0?".":(n.pop(),n.length===0?".":n.join("/"))}function _D(e){const n=Aa(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 vp={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function cw({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(Vt,{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=vp[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:bp(u.path)})]}),d&&t.jsx($n,{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 ou({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 dw({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:g,showNodesButton:p,onOpenWorkflowSteps:f,onOpenScripts:x,onRunScript:v,onToggleTerminal:b,onOpenFiles:y,filesOpen:S,globalPaused:j,enginePaused:R,onToggleGlobalPause:k,onToggleEnginePause:M,view:C="board",onChangeView:L,showSkillsTab:A,showAgentsTab:P,searchQuery:O="",onSearchChange:V,projects:$=[],currentProject:E,onSelectProject:D,onViewAllProjects:U,projectId:Y,isElectron:X=!1,mobileNavEnabled:_,availableNodes:I=[],currentNode:T,onSelectNode:w,isRemote:q=!1,experimentalFeatures:G}){const me=Tr(),ue=me==="mobile",Se=ue||me==="tablet",F=ue&&_,[ge,se]=a.useState(!1),[fe,de]=a.useState(!1),[xe,ie]=a.useState(!1),[Ee,De]=a.useState(!1),[qe,Qe]=a.useState(!1),[Je,Ke]=a.useState(!1),[it,Pe]=a.useState(!1),[Ve,ae]=a.useState(!1),[ye,te]=a.useState(!1),[Ae,Le]=a.useState(!1),[pe,_e]=a.useState(!1),[Fe,tt]=a.useState({}),[Ne,oe]=a.useState(!1),[Te,he]=a.useState(-1),[Me,We]=a.useState(null),[Re,ot]=a.useState({}),[J,ce]=a.useState(!1),ve=a.useRef(null),Xe=a.useRef(null),ee=a.useRef(null),Ge=a.useRef(null),ct=a.useRef(null),vt=a.useRef(null),bt=a.useRef(!1),ft=a.useRef(null),gt=a.useRef(null),_t=a.useRef(null),Rt=a.useRef(null),Ft=a.useRef(null),wt=a.useRef(null),At=a.useRef(null),qt=a.useRef(null),zt=a.useRef(!1),Wt=a.useMemo(()=>I.filter(ke=>ke.type==="remote"),[I]),Ot=Wt.length>0,Nt=a.useMemo(()=>Object.entries(Fe).sort(([ke],[at])=>ke.localeCompare(at)),[Fe]),Mt=Nt.length>0,Ct=Nt.length+(Mt?1:0),Gt=a.useMemo(()=>Object.entries(Re).sort(([ke],[at])=>ke.localeCompare(at)),[Re]),Et=a.useMemo(()=>!!(G?.todoView||G?.insights||G?.roadmap||A||G?.memoryView||G?.devServerView),[G,A]),H=a.useCallback(()=>{const ke=window.visualViewport;return ke&&ke.width>0&&ke.height>0?{width:ke.width,height:ke.height,offsetTop:ke.offsetTop,offsetLeft:ke.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),be=a.useCallback(()=>{const ke=At.current;if(!ke)return;const at=ke.getBoundingClientRect(),gn=qt.current,{width:Tn,height:Pn,offsetTop:Nn,offsetLeft:es}=H(),Sn=16,Yt=16,Q=6,ze=gn?.offsetWidth||Math.max(at.width,260),Ye=Math.min(ze,Math.max(Tn-Sn*2,160)),et=gn?.offsetHeight||280,dt=Math.min(et,Math.max(Pn-Yt*2,160)),St=at.top-Nn,It=at.bottom-Nn,kn=at.right-es,sn=Pn-It,jt=St,os=sn<dt&&jt>sn,ws=Math.min(Math.max(kn-Ye,Sn),Tn-Sn-Ye)+es,Ns=os?Math.max(Yt+Nn,St-dt-Q+Nn):Math.min(It+Q+Nn,Pn+Nn-Yt-dt);We({top:Ns,left:ws,width:Ye})},[H]),re=a.useCallback((ke,at)=>{v?.(ke,at),_e(!1),he(-1)},[v]),N=a.useCallback(()=>{x?.(),_e(!1),he(-1)},[x]),W=a.useCallback(ke=>{switch(ke.key){case"ArrowDown":ke.preventDefault(),Ct>0&&he(at=>at<Ct-1?at+1:0);break;case"ArrowUp":ke.preventDefault(),Ct>0&&he(at=>at>0?at-1:Ct-1);break;case"Enter":if(ke.preventDefault(),Te>=0)if(Te<Nt.length){const[at,gn]=Nt[Te];re(at,gn)}else Mt&&Te===Nt.length&&N();break;case"Home":ke.preventDefault(),Ct>0&&he(0);break;case"End":ke.preventDefault(),Ct>0&&he(Ct-1);break}},[N,re,Te,Nt,Mt,Ct]);a.useEffect(()=>{bt.current=qe},[qe]),a.useEffect(()=>{zt.current=pe},[pe]),a.useEffect(()=>{if(!qe||!Se)return;let ke=!1;return ce(!0),br(Y).then(at=>{ke||ot(at)}).catch(()=>{ke||ot({})}).finally(()=>{ke||ce(!1)}),()=>{ke=!0}},[qe,Se,Y]),a.useEffect(()=>{if(!pe||Se)return;let ke=!1;return oe(!0),br(Y).then(at=>{ke||tt(at)}).catch(()=>{ke||tt({})}).finally(()=>{ke||oe(!1)}),()=>{ke=!0}},[pe,Se,Y]),a.useEffect(()=>{if(!pe)return;const ke=at=>{wt.current&&!wt.current.contains(at.target)&&_e(!1)};return document.addEventListener("mousedown",ke),()=>document.removeEventListener("mousedown",ke)},[pe]),a.useEffect(()=>{if(!pe)return;const ke=at=>{at.key==="Escape"&&(_e(!1),At.current?.focus())};return document.addEventListener("keydown",ke),()=>document.removeEventListener("keydown",ke)},[pe]),a.useEffect(()=>{if(pe){he(-1);const ke=window.setTimeout(()=>qt.current?.focus(),0);return()=>window.clearTimeout(ke)}We(null)},[pe]),a.useEffect(()=>{if(!pe)return;const ke=requestAnimationFrame(()=>{be()});return()=>cancelAnimationFrame(ke)},[pe,Ne,Nt.length,Mt,be]),a.useEffect(()=>{if(!pe)return;const ke=()=>be();window.addEventListener("resize",ke),window.addEventListener("scroll",ke,!0);const at=window.visualViewport;return at&&(at.addEventListener("resize",ke),at.addEventListener("scroll",ke)),()=>{window.removeEventListener("resize",ke),window.removeEventListener("scroll",ke,!0),at&&(at.removeEventListener("resize",ke),at.removeEventListener("scroll",ke))}},[pe,be]),a.useEffect(()=>{Se&&(_e(!1),he(-1))},[Se]);const Ie=ge||O.length>0,nt=(fe||O.length>0)&&!xe,yt=(C==="board"||C==="list")&&!ue&&V&&!xe&&O.length===0,Pt=(C==="board"||C==="list")&&!ue&&V;a.useEffect(()=>{O===""&&ie(!1)},[O]),a.useEffect(()=>{if(!Ee)return;const ke=at=>{Xe.current&&!Xe.current.contains(at.target)&&ve.current&&!ve.current.contains(at.target)&&De(!1)};return document.addEventListener("mousedown",ke),()=>document.removeEventListener("mousedown",ke)},[Ee]),a.useEffect(()=>{if(!ye)return;const ke=at=>{Ge.current&&!Ge.current.contains(at.target)&&ee.current&&!ee.current.contains(at.target)&&te(!1)};return document.addEventListener("mousedown",ke),()=>document.removeEventListener("mousedown",ke)},[ye]),a.useEffect(()=>{if(!Je)return;const ke=at=>{ft.current&&!ft.current.contains(at.target)&&Ke(!1)};return document.addEventListener("mousedown",ke),()=>document.removeEventListener("mousedown",ke)},[Je]),a.useEffect(()=>{const ke=at=>{if(at.key==="Escape"){if(ae(!1),te(!1),bt.current){Qe(!1);return}if(zt.current){_e(!1),At.current?.focus();return}De(!1),se(!1),Ke(!1),Pe(!1)}};return document.addEventListener("keydown",ke),()=>document.removeEventListener("keydown",ke)},[]),a.useEffect(()=>{if(!it)return;const ke=at=>{gt.current&&!gt.current.contains(at.target)&&Pe(!1)};return document.addEventListener("mousedown",ke),()=>document.removeEventListener("mousedown",ke)},[it]),a.useEffect(()=>{if(!Ae)return;const ke=at=>{Ft.current&&!Ft.current.contains(at.target)&&Le(!1)};return document.addEventListener("mousedown",ke),()=>document.removeEventListener("mousedown",ke)},[Ae]),a.useEffect(()=>{if(!Ae)return;const ke=at=>{at.key==="Escape"&&Le(!1)};return document.addEventListener("keydown",ke),()=>document.removeEventListener("keydown",ke)},[Ae]),a.useEffect(()=>{if(!Ve)return;const ke=at=>{_t.current&&!_t.current.contains(at.target)&&Rt.current&&!Rt.current.contains(at.target)&&ae(!1)};return document.addEventListener("mousedown",ke),()=>document.removeEventListener("mousedown",ke)},[Ve]);const Tt=a.useCallback(()=>{se(ke=>!ke)},[]),tn=a.useCallback(()=>{de(!0),ie(!1)},[]),nn=a.useCallback(()=>{de(!1),ie(!0),V&&V("")},[V]),Ln=a.useCallback(()=>{De(ke=>!ke)},[]),Jt=a.useCallback(ke=>{ke&&ke(),De(!1),Qe(!1)},[]),Rn=a.useCallback(()=>{se(!1),V&&V("")},[V]);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"})]}),ue&&$.length>=1&&D&&t.jsxs("div",{className:"mobile-project-switch",ref:gt,children:[t.jsx("button",{className:`mobile-project-switch-trigger${it?" mobile-project-switch-trigger--open":""}`,onClick:()=>Pe(ke=>!ke),title:"Switch project","aria-label":"Switch project","aria-expanded":it,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:t.jsx(Vt,{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(ke=>{const at=E?.id===ke.id,gn=vp[ke.status]?.color;return t.jsxs("button",{className:`mobile-project-switch-item${at?" mobile-project-switch-item--current":""}`,onClick:()=>{D(ke),Pe(!1)},role:"option","aria-selected":at,"data-testid":`mobile-project-switch-item-${ke.id}`,children:[t.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:gn||"var(--text-muted)"}}),t.jsxs("div",{className:"mobile-project-switch-info",children:[t.jsx("span",{className:"mobile-project-switch-name",children:ke.name}),t.jsx("span",{className:"mobile-project-switch-path",children:bp(ke.path)})]}),at&&t.jsx($n,{size:14,className:"mobile-project-switch-check"})]},ke.id)})})]}),!Se&&$.length>=1&&U&&t.jsx(cw,{projects:$,currentProject:E??null,onViewAll:U,onSelectProject:D}),Ot&&t.jsxs("div",{className:`header-node-selector${ue?" header-node-selector--mobile":""}`,ref:ue?void 0:ft,children:[t.jsx(nw,{node:T??null,showDetails:!ue}),!ue&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:`btn-icon node-selector-trigger${Je?" node-selector-trigger--open":""}`,onClick:()=>Ke(ke=>!ke),title:"Switch node","aria-label":"Switch node","aria-expanded":Je,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:t.jsx(pn,{size:12,className:`node-selector-chevron${Je?" node-selector-chevron--open":""}`})}),Je&&t.jsxs("div",{className:"node-selector-dropdown",role:"listbox","aria-label":"Select node",children:[t.jsxs("button",{className:`node-selector-option${q?"":" node-selector-option--active"}`,onClick:()=>{w?.(null),Ke(!1)},role:"option","aria-selected":!q,"data-testid":"node-option-local",children:[t.jsx(Vi,{status:"online",compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:"Local"})]}),Wt.map(ke=>t.jsxs("button",{className:`node-selector-option${T?.id===ke.id?" node-selector-option--active":""}`,onClick:()=>{w?.(ke),Ke(!1)},role:"option","aria-selected":T?.id===ke.id,"data-testid":`node-option-${ke.id}`,children:[t.jsx(Vi,{status:ke.status,compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:ke.name}),t.jsx("span",{className:"node-selector-option-status",children:ke.status})]},ke.id))]})]})]})]}),t.jsxs("div",{className:"header-actions",children:[F&&L&&(C==="board"||C==="list")&&t.jsxs("div",{className:"view-toggle","data-testid":"mobile-view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${C==="board"?" active":""}`,onClick:()=>L("board"),title:"Board view","aria-label":"Board view","aria-pressed":C==="board","data-testid":"mobile-view-toggle-board",children:t.jsx(qi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="list"?" active":""}`,onClick:()=>L("list"),title:"List view","aria-label":"List view","aria-pressed":C==="list","data-testid":"mobile-view-toggle-list",children:t.jsx(bc,{size:16})})]}),V&&ue&&(F||C==="board"||C==="list")&&!Ie&&t.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:Tt,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:t.jsx(ma,{size:16})}),yt&&t.jsx("button",{className:"btn-icon",onClick:tn,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:t.jsx(ma,{size:16})}),ue&&F&&o&&t.jsx("button",{className:"btn-icon",onClick:ke=>o(ke.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"mobile-header-usage-btn",children:t.jsx(Ps,{size:16})}),!F&&L&&t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${C==="board"?" active":""}`,onClick:()=>L("board"),title:"Board view","aria-label":"Board view","aria-pressed":C==="board",children:t.jsx(qi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="list"?" active":""}`,onClick:()=>L("list"),title:"List view","aria-label":"List view","aria-pressed":C==="list",children:t.jsx(bc,{size:16})}),P&&t.jsx("button",{className:`view-toggle-btn${C==="agents"?" active":""}`,onClick:()=>L("agents"),title:"Agents view","aria-label":"Agents view","aria-pressed":C==="agents",children:t.jsx(yn,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="missions"?" active":""}`,onClick:()=>L("missions"),title:"Missions view","aria-label":"Missions view","aria-pressed":C==="missions",children:t.jsx(us,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="chat"?" active":""}`,onClick:()=>L("chat"),title:"Chat view","aria-label":"Chat view","aria-pressed":C==="chat",children:t.jsx(ji,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="documents"?" active":""}`,onClick:()=>L("documents"),title:"Documents view","aria-label":"Documents view","aria-pressed":C==="documents",children:t.jsx(Ui,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="mailbox"?" active":""}`,onClick:()=>L("mailbox"),title:"Mailbox view","aria-label":"Mailbox view","aria-pressed":C==="mailbox",children:t.jsx(xa,{size:16})}),Et&&t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:Rt,className:`view-toggle-btn${["skills","roadmaps","insights","memory","dev-server","devserver"].includes(C)||G?.todoView&&C==="todos"?" active":""}`,onClick:()=>ae(ke=>!ke),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":Ve,"data-testid":"view-toggle-overflow-trigger",children:t.jsx(Vt,{size:12})}),Ve&&t.jsxs("div",{ref:_t,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[G?.insights&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="insights"?" active":""}`,onClick:()=>{L("insights"),ae(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[t.jsx(Xn,{size:14}),t.jsx("span",{children:"Insights"})]}),G?.roadmap&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="roadmaps"?" active":""}`,onClick:()=>{L("roadmaps"),ae(!1)},role:"menuitem","data-testid":"view-overflow-roadmaps",children:[t.jsx(vc,{size:14}),t.jsx("span",{children:"Roadmaps"})]}),A&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="skills"?" active":""}`,onClick:()=>{L("skills"),ae(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[t.jsx(Bn,{size:14}),t.jsx("span",{children:"Skills"})]}),G?.memoryView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="memory"?" active":""}`,onClick:()=>{L("memory"),ae(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[t.jsx(ho,{size:14}),t.jsx("span",{children:"Memory"})]}),G?.devServerView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="dev-server"||C==="devserver"?" active":""}`,onClick:()=>{L("devserver"),ae(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[t.jsx(pr,{size:14}),t.jsx("span",{children:"Dev Server"}),t.jsx("span",{className:"visually-hidden","data-testid":"view-toggle-dev-server"})]}),G?.todoView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="todos"?" active":""}`,onClick:()=>{L("todos"),ae(!1)},role:"menuitem","data-testid":"view-overflow-todos",children:[t.jsx(Xh,{size:14}),t.jsx("span",{children:"Todos"})]})]})]})]}),!Se&&o&&t.jsx("button",{className:"btn-icon",onClick:ke=>o(ke.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"desktop-header-usage-btn",children:t.jsx(Ps,{size:16})}),!Se&&c&&t.jsx("button",{className:"btn-icon",onClick:c,title:"System Stats","data-testid":"desktop-header-system-stats-btn",children:t.jsx(pr,{size:16})}),!Se&&l&&t.jsx("button",{className:"btn-icon",onClick:l,title:"View Activity Log",children:t.jsx(hr,{size:16})}),!Se&&!X&&t.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:t.jsx(ou,{size:16})}),!Se&&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(ei,{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})]}),!Se&&t.jsxs("div",{className:"terminal-split-btn",ref:wt,children:[t.jsx("button",{className:"btn-icon btn-icon--terminal terminal-split-btn__main",onClick:b,title:"Open Terminal","data-testid":"terminal-toggle-btn",children:t.jsx(ci,{size:16})}),x&&v&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"terminal-split-btn__divider"}),t.jsx("button",{ref:At,className:`btn-icon terminal-split-btn__chevron${pe?" btn-icon--active":""}`,onClick:()=>_e(ke=>!ke),title:"Scripts","aria-haspopup":"listbox","aria-expanded":pe,"aria-label":"Quick scripts","data-testid":"scripts-btn",children:t.jsx(Vt,{size:12,className:`quick-scripts-dropdown__trigger-chevron${pe?" rotate":""}`})}),pe&&t.jsx("div",{ref:qt,tabIndex:-1,className:"quick-scripts-dropdown__menu",role:"listbox","aria-label":"Scripts",onKeyDown:W,"data-testid":"quick-scripts-dropdown",style:Me?{position:"fixed",top:`${Me.top}px`,left:`${Me.left}px`,width:`${Me.width}px`,right:"auto"}:void 0,children:Ne?t.jsxs("div",{className:"quick-scripts-dropdown__loading","data-testid":"quick-scripts-loading",children:[t.jsx(rt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts..."})]}):Nt.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(ci,{size:16})}),t.jsx("p",{children:"No scripts configured"}),t.jsx("button",{className:"quick-scripts-dropdown__empty-action btn",onClick:N,children:"Add your first script"})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-scripts-dropdown__list",children:Nt.map(([ke,at],gn)=>t.jsxs("button",{className:`quick-scripts-dropdown__item ${Te===gn?"highlighted":""}`,onClick:()=>re(ke,at),role:"option","aria-selected":Te===gn,"data-testid":`quick-script-item-${ke}`,children:[t.jsx(jn,{size:14,className:"quick-scripts-dropdown__item-icon"}),t.jsxs("div",{className:"quick-scripts-dropdown__item-info",children:[t.jsx("span",{className:"quick-scripts-dropdown__item-name",children:ke}),t.jsx("span",{className:"quick-scripts-dropdown__item-command",title:at,children:at.length>50?`${at.slice(0,50)}...`:at})]})]},ke))}),t.jsx("div",{className:"quick-scripts-dropdown__footer",children:t.jsxs("button",{className:`quick-scripts-dropdown__manage ${Mt&&Te===Nt.length?"highlighted":""}`,onClick:N,"data-testid":"quick-scripts-manage",children:[t.jsx(or,{size:14}),t.jsx("span",{children:"Manage Scripts..."})]})})]})})]})]}),!Se&&y&&t.jsx("button",{className:`btn-icon${S?" btn-icon--active":""}`,onClick:y,title:"Browse files","data-testid":"files-toggle-btn",children:t.jsx(Un,{size:16})}),!Se&&h&&t.jsx("button",{className:"btn-icon",onClick:h,title:"Git Manager","data-testid":"git-manager-btn",children:t.jsx(Zs,{size:16})}),!Se&&f&&t.jsx("button",{className:"btn-icon",onClick:f,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:t.jsx(jc,{size:16})}),!Se&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{ref:ee,className:"btn-icon",onClick:()=>te(ke=>!ke),title:"More actions","aria-label":"More actions","aria-expanded":ye,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:t.jsx(fc,{size:16})}),ye&&t.jsxs("div",{ref:Ge,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[g&&p!==!1&&t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{g(),te(!1)},role:"menuitem","data-testid":"desktop-overflow-nodes-btn",children:[t.jsx(fr,{size:14}),t.jsx("span",{children:"Nodes"})]}),t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{Jt(m),te(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[t.jsx(wi,{size:14}),t.jsx("span",{children:"Automation"})]})]})]}),t.jsxs("div",{className:"engine-control-split-btn",ref:Ft,children:[t.jsx("button",{className:`btn-icon engine-control-split-btn__main${j?" btn-icon--stopped":""}`,onClick:k,title:j?"Start AI engine":"Stop AI engine","data-testid":"engine-control-main-btn",children:j?t.jsx(jn,{size:16}):t.jsx(bs,{size:16})}),t.jsx("span",{className:"engine-control-split-btn__divider"}),t.jsx("button",{className:`btn-icon engine-control-split-btn__chevron${Ae?" btn-icon--active":""}`,onClick:()=>Le(ke=>!ke),title:"Engine options","aria-haspopup":"menu","aria-expanded":Ae,"data-testid":"engine-control-chevron-btn",children:t.jsx(Vt,{size:12})}),Ae&&t.jsx("div",{className:"engine-control-split-btn__menu",role:"menu",children:t.jsxs("button",{className:`engine-control-split-btn__menu-item${R?" engine-control-split-btn__menu-item--active":""}`,onClick:()=>{M?.(),Le(!1)},role:"menuitem",title:R?"Resume scheduling":"Pause triage",disabled:!!j,"data-testid":"engine-control-pause-triage-btn",children:[R?t.jsx(jn,{size:14}):t.jsx(Xs,{size:14}),t.jsx("span",{children:R?"Resume scheduling":"Pause triage"})]})})]}),!Se&&t.jsx("button",{className:"btn-icon",onClick:e,title:"Settings",children:t.jsx(or,{size:16})}),t.jsx(Uo,{slotId:"header-action",projectId:Y}),Se&&!F&&t.jsx("button",{ref:ve,className:"btn-icon compact-overflow-trigger",onClick:Ln,title:"More header actions","aria-label":"More header actions","aria-expanded":Ee,"aria-haspopup":"menu",children:t.jsx(fc,{size:16})}),Se&&!F&&Ee&&t.jsxs("div",{ref:Xe,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[$.length>=1&&U&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Jt(U),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[t.jsx(Gh,{size:16}),t.jsx("span",{children:"Projects"})]}),y&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Jt(y),role:"menuitem","data-testid":"overflow-files-btn",children:[t.jsx(Un,{size:16}),t.jsx("span",{children:"Browse Files"})]}),t.jsxs("button",{className:`mobile-overflow-item${r>0?" mobile-overflow-item--has-indicator":""}`,onClick:()=>Jt(r>0&&i?i:s),role:"menuitem","data-testid":"overflow-planning-btn",children:[t.jsxs("span",{className:"mobile-overflow-icon-wrapper",children:[t.jsx(ei,{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:()=>Jt(h),role:"menuitem","data-testid":"overflow-git-btn",children:[t.jsx(Zs,{size:16}),t.jsx("span",{children:"Git Manager"})]}),g&&p!==!1&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Jt(g),role:"menuitem","data-testid":"overflow-nodes-btn",children:[t.jsx(fr,{size:16}),t.jsx("span",{children:"Nodes"})]}),!X&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Jt(n),role:"menuitem",children:[t.jsx(ou,{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:()=>Jt(b),role:"menuitem","data-testid":"overflow-terminal-primary-btn",children:[t.jsx(ci,{size:16}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{className:"mobile-overflow-split-toggle",onClick:()=>Qe(ke=>!ke),role:"menuitem","aria-expanded":qe,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:t.jsx(pn,{size:14,className:`mobile-overflow-chevron${qe?" mobile-overflow-chevron--open":""}`})})]}),qe&&t.jsx("div",{className:"mobile-overflow-submenu",role:"menu","aria-label":"Scripts submenu",children:J?t.jsxs("div",{className:"mobile-overflow-submenu-loading","data-testid":"overflow-scripts-loading",children:[t.jsx(rt,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):Gt.length>0?t.jsxs(t.Fragment,{children:[Gt.map(([ke,at])=>t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{v&&v(ke,at),De(!1),Qe(!1)},role:"menuitem","data-testid":`overflow-script-item-${ke}`,children:[t.jsx(jn,{size:14}),t.jsx("span",{children:ke})]},ke)),x&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>Jt(x),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(Bs,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):x&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>Jt(x),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:()=>Jt(m),role:"menuitem","data-testid":"overflow-schedules-btn",children:[t.jsx(wi,{size:16}),t.jsx("span",{children:"Automation"})]}),l&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Jt(l),role:"menuitem","data-testid":"overflow-activity-log-btn",children:[t.jsx(hr,{size:16}),t.jsx("span",{children:"View Activity Log"})]}),u&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Jt(u),role:"menuitem","data-testid":"overflow-mailbox-btn",children:[t.jsx(xa,{size:16}),t.jsxs("span",{children:["Mailbox",d>0?` (${d})`:""]})]}),o&&t.jsxs("button",{className:"mobile-overflow-item",onClick:ke=>Jt(()=>o(ke.currentTarget.getBoundingClientRect())),role:"menuitem","data-testid":"overflow-usage-btn",children:[t.jsx(Ps,{size:16}),t.jsx("span",{children:"View Usage"})]}),f&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Jt(f),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[t.jsx(jc,{size:16}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Jt(e),role:"menuitem",children:[t.jsx(or,{size:16}),t.jsx("span",{children:"Settings"})]})]})]})]}),Pt&&nt&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{className:"header-search",children:[t.jsx(ma,{size:14,className:"header-search-icon"}),t.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:O,onChange:ke=>V(ke.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:nn,"aria-label":"Close search",children:t.jsx(Ut,{size:14})})]})}),V&&ue&&Ie&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{ref:ct,className:"header-search mobile-search-expanded",children:[t.jsx(ma,{size:14,className:"header-search-icon"}),t.jsx("input",{ref:vt,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:O,onChange:ke=>V(ke.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:Rn,"aria-label":"Close search",children:t.jsx(Ut,{size:14})})]})})]})}const uw={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:[],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},mw={globalPause:!1,globalPauseReason:void 0,enginePaused:!1,maxConcurrent:2,maxTriageConcurrent:2,globalMaxConcurrent:4,maxWorktrees:4,pollIntervalMs:15e3,heartbeatMultiplier:1,groupOverlappingFiles:!0,overlapIgnorePaths:[],autoMerge:!0,mergeStrategy:"direct",pushAfterMerge:!1,pushRemote:"origin",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,autoCreatePr:!1,githubCommentOnDone:!1,githubCommentTemplate:void 0,autoBackupEnabled:!1,autoBackupSchedule:"0 2 * * *",autoBackupRetention:7,autoBackupDir:".fusion/backups",autoSummarizeTitles:!1,titleSummarizerProvider:void 0,titleSummarizerModelId:void 0,titleSummarizerFallbackProvider:void 0,titleSummarizerFallbackModelId:void 0,scripts:void 0,setupScript:void 0,insightExtractionEnabled:!1,insightExtractionSchedule:"0 2 * * *",insightExtractionMinIntervalMs:864e5,memoryEnabled:!0,memoryBackendType:"qmd",memoryAutoSummarizeEnabled:!1,memoryAutoSummarizeThresholdChars:5e4,memoryAutoSummarizeSchedule:"0 3 * * *",memoryDreamsEnabled:!1,memoryDreamsSchedule:"0 4 * * *",tokenCap:void 0,runStepsInNewSessions:!1,maxParallelSteps:2,missionStaleThresholdMs:6e5,missionMaxTaskRetries:3,missionHealthCheckIntervalMs:3e5,agentPrompts:void 0,promptOverrides:void 0,remoteAccess:{activeProvider:null,providers:{tailscale:{enabled:!1,hostname:"",targetPort:0,acceptRoutes:!1},cloudflare:{enabled:!1,quickTunnel:!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,experimentalFeatures:{}},hw=Object.freeze(Object.keys(uw)),pw=Object.freeze(Object.keys(mw));function MD(e){return hw.includes(e)}function AD(e){return pw.includes(e)}function je(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function fw(e){return!!(e?.provider&&e?.modelId)}function Ni(...e){for(const n of e)if(fw(n))return{provider:n.provider,modelId:n.modelId};return{}}function Ho(e){return Ni({provider:e?.defaultProviderOverride,modelId:e?.defaultModelIdOverride},{provider:e?.defaultProvider,modelId:e?.defaultModelId})}function gw(e){return Ni({provider:e?.executionProvider,modelId:e?.executionModelId},{provider:e?.executionGlobalProvider,modelId:e?.executionGlobalModelId},Ho(e))}function xw(e){return Ni({provider:e?.planningProvider,modelId:e?.planningModelId},{provider:e?.planningGlobalProvider,modelId:e?.planningGlobalModelId},Ho(e))}function bw(e){return Ni({provider:e?.validatorProvider,modelId:e?.validatorModelId},{provider:e?.validatorGlobalProvider,modelId:e?.validatorGlobalModelId},Ho(e))}function RD(e){return Ni({provider:e?.titleSummarizerProvider,modelId:e?.titleSummarizerModelId},{provider:e?.titleSummarizerGlobalProvider,modelId:e?.titleSummarizerGlobalModelId},{provider:e?.planningProvider,modelId:e?.planningModelId},Ho(e))}function yp(e,n){return Ni({provider:e.modelProvider,modelId:e.modelId},gw(n))}function jp(e,n){return Ni({provider:e.validatorModelProvider,modelId:e.validatorModelId},bw(n))}function kp(e,n){return Ni({provider:e.planningModelProvider,modelId:e.planningModelId},xw(n))}const TD=["off","minimal","low","medium","high"],Oi=["triage","todo","in-progress","in-review","done","archived"],ad=["low","normal","high","urgent"],ys="normal",vw=["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"],An={triage:"Planning",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},yw={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"},Cc={triage:["todo"],todo:["in-progress","triage"],"in-progress":["in-review","todo","triage","done"],"in-review":["done","in-progress","todo"],done:["todo","triage","archived"],archived:["done"]};function jw(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 kw(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 ww({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 wp=a.createContext(null);function Nw({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 mo.createElement(wp.Provider,{value:u},e,mo.createElement(ww,{isOpen:c!==null,options:c?.options??null,onConfirm:()=>l(!0),onCancel:()=>l(!1)}))}function Hs(){const e=a.useContext(wp);return e||{confirm:async n=>!1}}function Sw(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 Np({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(vs,{size:12}),t.jsxs("span",{children:["#",e.number]})]}),n&&t.jsxs("span",{className:`card-github-badge ${Sw(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,onClick:r,children:[t.jsx(Po,{size:12}),t.jsxs("span",{children:["#",n.number]})]})]})}function Vr(e,n){return`${e??"default"}:${n}`}class Cw{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=Vr(this.projectId,o);this.subscriptionsByTask.set(l,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const i=Vr(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=Vr(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(ti(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=Vr(this.projectId,l.taskId),u=this.badgeUpdates.get(c);this.badgeUpdates.set(c,{prInfo:lu(l,"prInfo")?l.prInfo??null:u?.prInfo,issueInfo:lu(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 $i=new Cw;let Ew=0;function lu(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function Sp(e){const n=a.useRef(null);n.current===null&&(n.current=`badge-hook-${Ew++}`);const s=a.useSyncExternalStore(o=>$i.subscribe(o),()=>$i.getSnapshot(),()=>$i.getSnapshot()),i=a.useCallback(o=>{$i.subscribeTask(n.current,o)},[]),r=a.useCallback(o=>{$i.unsubscribeTask(n.current,o)},[]);return a.useEffect(()=>{$i.setProjectId(e??null)},[e]),a.useEffect(()=>()=>{$i.cleanupHook(n.current)},[]),{badgeUpdates:s.badgeUpdates,isConnected:s.isConnected,subscribeToBadge:i,unsubscribeFromBadge:r}}function yo(e,n,s,i){return e===void 0||!n?s:!i||n>=i?e??void 0:s}function _w({taskId:e,prInfo:n,issueInfo:s,updatedAt:i,isInViewport:r,projectId:o}){const{badgeUpdates:l,subscribeToBadge:c,unsubscribeFromBadge:u}=Sp(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=yo(m?.prInfo,m?.timestamp,n,n?.lastCheckedAt??i),g=yo(m?.issueInfo,m?.timestamp,s,s?.lastCheckedAt??i);return!h&&!g?null:t.jsx(Np,{prInfo:h,issueInfo:g})}const Mw=a.memo(_w);Mw.displayName="TaskCardBadge";const Aw={sm:16,md:20,lg:24};function Rw({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 cu({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 Ws({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 Tw({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 du({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 Pw({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 ul({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 uu({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 mu({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 hu({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 Fa({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 pu({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 ml({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 fu({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 hl({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 Iw({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 $w({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 gu({size:e,color:n,label:s="Vercel"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"vercel-icon","aria-label":s,children:t.jsx("path",{d:"M12 2 22 21H2z",fill:n})})}function pl({size:e,color:n,label:s="Fireworks AI"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"fireworks-icon","aria-label":s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"2.4",fill:n}),t.jsx("circle",{cx:"12",cy:"3.5",r:"1.4",fill:n}),t.jsx("circle",{cx:"12",cy:"20.5",r:"1.4",fill:n}),t.jsx("circle",{cx:"3.5",cy:"12",r:"1.4",fill:n}),t.jsx("circle",{cx:"20.5",cy:"12",r:"1.4",fill:n}),t.jsx("circle",{cx:"6",cy:"6",r:"1.2",fill:n}),t.jsx("circle",{cx:"18",cy:"6",r:"1.2",fill:n}),t.jsx("circle",{cx:"6",cy:"18",r:"1.2",fill:n}),t.jsx("circle",{cx:"18",cy:"18",r:"1.2",fill:n}),t.jsx("path",{d:"M12 5.5v3M12 15.5v3M5.5 12h3M15.5 12h3",stroke:n,strokeWidth:"1.4",strokeLinecap:"round"})]})}function Dw({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 xu({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 fl({size:e,color:n,label:s="Hermes"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 64 64",fill:"none",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":s,children:[t.jsx("rect",{x:"30",y:"10",width:"4",height:"46",rx:"2",fill:n}),t.jsx("path",{d:"M30 18 C24 14, 14 14, 10 18 C14 16, 22 16, 28 20",fill:n,opacity:"0.9"}),t.jsx("path",{d:"M30 22 C26 19, 18 19, 14 22 C18 20, 24 20, 28 24",fill:n,opacity:"0.7"}),t.jsx("path",{d:"M34 18 C40 14, 50 14, 54 18 C50 16, 42 16, 36 20",fill:n,opacity:"0.9"}),t.jsx("path",{d:"M34 22 C38 19, 46 19, 50 22 C46 20, 40 20, 36 24",fill:n,opacity:"0.7"}),t.jsx("path",{d:"M32 48 C22 44, 20 38, 26 34 C20 36, 18 42, 24 46 C18 40, 22 30, 30 28 C24 32, 22 38, 28 42",fill:"none",stroke:n,strokeWidth:"2.5",strokeLinecap:"round"}),t.jsx("path",{d:"M32 48 C42 44, 44 38, 38 34 C44 36, 46 42, 40 46 C46 40, 42 30, 34 28 C40 32, 42 38, 36 42",fill:"none",stroke:n,strokeWidth:"2.5",strokeLinecap:"round",opacity:"0.8"}),t.jsx("circle",{cx:"32",cy:"10",r:"4",fill:n})]})}function bu({size:e,label:n="OpenClaw"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":n,children:[t.jsx("rect",{width:"16",height:"16",fill:"none"}),t.jsxs("g",{fill:"#3a0a0d",children:[t.jsx("rect",{x:"1",y:"5",width:"1",height:"3"}),t.jsx("rect",{x:"2",y:"4",width:"1",height:"1"}),t.jsx("rect",{x:"2",y:"8",width:"1",height:"1"}),t.jsx("rect",{x:"3",y:"3",width:"1",height:"1"}),t.jsx("rect",{x:"3",y:"9",width:"1",height:"1"}),t.jsx("rect",{x:"4",y:"2",width:"1",height:"1"}),t.jsx("rect",{x:"4",y:"10",width:"1",height:"1"}),t.jsx("rect",{x:"5",y:"2",width:"6",height:"1"}),t.jsx("rect",{x:"11",y:"2",width:"1",height:"1"}),t.jsx("rect",{x:"12",y:"3",width:"1",height:"1"}),t.jsx("rect",{x:"12",y:"9",width:"1",height:"1"}),t.jsx("rect",{x:"13",y:"4",width:"1",height:"1"}),t.jsx("rect",{x:"13",y:"8",width:"1",height:"1"}),t.jsx("rect",{x:"14",y:"5",width:"1",height:"3"}),t.jsx("rect",{x:"5",y:"11",width:"6",height:"1"}),t.jsx("rect",{x:"4",y:"12",width:"1",height:"1"}),t.jsx("rect",{x:"11",y:"12",width:"1",height:"1"}),t.jsx("rect",{x:"3",y:"13",width:"1",height:"1"}),t.jsx("rect",{x:"12",y:"13",width:"1",height:"1"}),t.jsx("rect",{x:"5",y:"14",width:"6",height:"1"})]}),t.jsxs("g",{fill:"#ff4f40",children:[t.jsx("rect",{x:"5",y:"3",width:"6",height:"1"}),t.jsx("rect",{x:"4",y:"4",width:"8",height:"1"}),t.jsx("rect",{x:"3",y:"5",width:"10",height:"1"}),t.jsx("rect",{x:"3",y:"6",width:"10",height:"1"}),t.jsx("rect",{x:"3",y:"7",width:"10",height:"1"}),t.jsx("rect",{x:"4",y:"8",width:"8",height:"1"}),t.jsx("rect",{x:"5",y:"9",width:"6",height:"1"}),t.jsx("rect",{x:"5",y:"12",width:"6",height:"1"}),t.jsx("rect",{x:"6",y:"13",width:"4",height:"1"})]}),t.jsxs("g",{fill:"#ff775f",children:[t.jsx("rect",{x:"1",y:"6",width:"2",height:"1"}),t.jsx("rect",{x:"2",y:"5",width:"1",height:"1"}),t.jsx("rect",{x:"2",y:"7",width:"1",height:"1"}),t.jsx("rect",{x:"13",y:"6",width:"2",height:"1"}),t.jsx("rect",{x:"13",y:"5",width:"1",height:"1"}),t.jsx("rect",{x:"13",y:"7",width:"1",height:"1"})]}),t.jsxs("g",{fill:"#081016",children:[t.jsx("rect",{x:"6",y:"5",width:"1",height:"1"}),t.jsx("rect",{x:"9",y:"5",width:"1",height:"1"})]}),t.jsxs("g",{fill:"#f5fbff",children:[t.jsx("rect",{x:"6",y:"4",width:"1",height:"1"}),t.jsx("rect",{x:"9",y:"4",width:"1",height:"1"})]})]})}function gl({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 vu({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 Lw={anthropic:{component:Rw,color:"var(--provider-anthropic)"},"claude-cli":{component:vu,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"pi-claude-cli":{component:vu,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},openai:{component:cu,color:"var(--provider-openai)"},"openai-codex":{component:cu,color:"var(--provider-openai)",label:"OpenAI Codex"},google:{component:Ws,color:"var(--provider-gemini)"},gemini:{component:Ws,color:"var(--provider-gemini)"},"google-antigravity":{component:Ws,color:"var(--provider-gemini)",label:"Google Gemini"},antigravity:{component:Ws,color:"var(--provider-gemini)",label:"Google Gemini"},"google-vertex":{component:Ws,color:"var(--provider-gemini)",label:"Google Vertex AI"},vertex:{component:Ws,color:"var(--provider-gemini)",label:"Google Vertex AI"},"google-cloud-code":{component:Ws,color:"var(--provider-gemini)",label:"Google Cloud Code"},"cloud-code":{component:Ws,color:"var(--provider-gemini)",label:"Google Cloud Code"},"google-gemini-cli":{component:Ws,color:"var(--provider-gemini)",label:"Google Gemini CLI"},"google-generative-ai":{component:Ws,color:"var(--provider-gemini)",label:"Google Generative AI"},ollama:{component:Tw,color:"var(--text)"},github:{component:xu,color:"var(--text)"},"github-copilot":{component:xu,color:"var(--text)",label:"GitHub Copilot"},openrouter:{component:Dw,color:"var(--provider-openrouter)"},minimax:{component:du,color:"var(--provider-minimax)"},"minimax-cn":{component:du,color:"var(--provider-minimax)",label:"MiniMax (CN)"},zai:{component:Pw,color:"var(--provider-zai)"},kimi:{component:ul,color:"var(--provider-kimi)"},moonshot:{component:ul,color:"var(--provider-kimi)"},"kimi-coding":{component:ul,color:"var(--provider-kimi)",label:"Kimi"},bedrock:{component:uu,color:"var(--provider-bedrock)"},"amazon-bedrock":{component:uu,color:"var(--provider-bedrock)",label:"Amazon Bedrock"},xai:{component:mu,color:"var(--text)"},grok:{component:mu,color:"var(--text)",label:"xAI"},opencode:{component:hu,color:"var(--provider-opencode)"},"opencode-go":{component:hu,color:"var(--provider-opencode)",label:"Opencode (Go)"},qwen:{component:Fa,color:"var(--provider-qwen)"},"qwen-ai":{component:Fa,color:"var(--provider-qwen)",label:"Qwen"},"qwen-coder":{component:Fa,color:"var(--provider-qwen)",label:"Qwen Coder"},alibaba:{component:Fa,color:"var(--provider-qwen)",label:"Qwen"},tongyi:{component:Fa,color:"var(--provider-qwen)",label:"Qwen"},lmstudio:{component:pu,color:"var(--provider-lmstudio)",label:"LM Studio"},"lm-studio":{component:pu,color:"var(--provider-lmstudio)",label:"LM Studio"},huggingface:{component:ml,color:"var(--provider-huggingface)",label:"Hugging Face"},"hugging-face":{component:ml,color:"var(--provider-huggingface)",label:"Hugging Face"},hf:{component:ml,color:"var(--provider-huggingface)",label:"Hugging Face"},mistral:{component:fu,color:"var(--provider-mistral)",label:"Mistral AI"},"mistral-ai":{component:fu,color:"var(--provider-mistral)",label:"Mistral AI"},azure:{component:hl,color:"var(--provider-azure)"},"azure-openai":{component:hl,color:"var(--provider-azure)",label:"Azure OpenAI"},"azure-openai-responses":{component:hl,color:"var(--provider-azure)",label:"Azure OpenAI"},fireworks:{component:pl,color:"var(--provider-fireworks)",label:"Fireworks AI"},"fireworks-ai":{component:pl,color:"var(--provider-fireworks)",label:"Fireworks AI"},fireworksai:{component:pl,color:"var(--provider-fireworks)",label:"Fireworks AI"},cerebras:{component:Iw,color:"var(--provider-cerebras)"},groq:{component:$w,color:"var(--provider-groq)"},vercel:{component:gu,color:"var(--provider-vercel)"},"vercel-ai-gateway":{component:gu,color:"var(--provider-vercel)",label:"Vercel AI Gateway"},hermes:{component:fl,color:"var(--provider-hermes)",label:"Hermes"},"hermes-agent":{component:fl,color:"var(--provider-hermes)",label:"Hermes"},hermesagent:{component:fl,color:"var(--provider-hermes)",label:"Hermes"},openclaw:{component:bu,color:"var(--provider-openclaw)",label:"OpenClaw"},"open-claw":{component:bu,color:"var(--provider-openclaw)",label:"OpenClaw"},paperclip:{component:gl,color:"var(--provider-paperclip)",label:"Paperclip"},paperclipai:{component:gl,color:"var(--provider-paperclip)",label:"Paperclip"},"paperclip-ai":{component:gl,color:"var(--provider-paperclip)",label:"Paperclip"}};function Dn({provider:e,size:n="sm"}){const s=e.toLowerCase(),i=Lw[s],r=i?.component,o=i?.color??"var(--text-muted)",l=i?.label,c=Aw[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(ox,{size:c})})}const Ms={data:new Map,pendingPromise:null,lastFetchTime:null},zw=5e3;function lo(e,n){return n?`${n}::${e}`:e}function Fw(e,n){const s=Ms.data.get(lo(e,n));if(!(!s||Date.now()-s.timestamp>zw))return s}function Ow(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 by(c,e)}catch(h){d=h instanceof Error?h:new Error(String(h));const g=je(h);if(g?.includes("429")||g?.toLowerCase().includes("rate limit")){const p=Math.min(1e3*Math.pow(2,m),3e4);await new Promise(f=>setTimeout(f,p));continue}break}if(d)throw d;return{}},[e]),o=a.useCallback(async c=>{if(c.length===0)return;const d=Date.now()-5e3;if(c.every(g=>{const p=Ms.data.get(lo(g,e));return p&&p.timestamp>d})&&Ms.lastFetchTime&&Ms.lastFetchTime>d)return;if(i.current&&(clearTimeout(i.current),i.current=null),Ms.pendingPromise){s(!0);try{await Ms.pendingPromise}finally{s(!1)}return}s(!0);const h=r(c);Ms.pendingPromise=h;try{const g=await h,p=Date.now();for(const[f,x]of Object.entries(g))Ms.data.set(lo(f,e),{result:x,timestamp:p});Ms.lastFetchTime=p}catch{}finally{Ms.pendingPromise=null,s(!1)}},[r,e]),l=a.useCallback(c=>Ms.data.get(lo(c,e)),[e]);return{fetchBatch:o,isLoading:n,lastFetchTime:Ms.lastFetchTime,getBatchData:l}}const Ec=new Map,Bw=3e4;function Cp(e,n,s,i){return`${e}:${n??""}:${s??""}:${i??""}`}function Uw(e,n,s,i){const r=Cp(e,n,s,i),o=Ec.get(r);return o?Date.now()>o.expiresAt?(Ec.delete(r),null):o.stats:null}function Hw(e,n,s,i,r){const o=Cp(e,n,s,i);Ec.set(o,{stats:r,expiresAt:Date.now()+Bw})}function qw(e,n,s,i,r={}){const o=r.enabled??!0,l=r.worktree,c=r.stepVersion,u=r.pollIntervalMs,[d,m]=a.useState(null),[h,g]=a.useState(!1);return a.useEffect(()=>{if(!o){m(null),g(!1);return}const p=n==="done"&&!!s,f=(n==="in-progress"||n==="in-review")&&!!l;if(!e||!p&&!f){m(null),g(!1);return}const x=f?l:void 0,v=c!==void 0?String(c):void 0;let b=!1;async function y(j=!1){if(!j){const R=Uw(e,i,x,v);if(R){b||(m(R),g(!1));return}}g(!0);try{const R=await mp(e,x,i);b||(m(R.stats),Hw(e,i,x,v,R.stats))}catch{b||m(null)}finally{b||g(!1)}}y();let S;return u&&f&&(S=setInterval(()=>{y(!0)},u)),()=>{b=!0,S&&clearInterval(S)}},[e,n,s,i,o,l,c,u]),{stats:d,loading:h}}const Vw=new Set(["failed","stuck-killed"]);function jo(e,n,s){if(e.column!=="in-progress"||e.status&&Vw.has(e.status)||!n||n<=0)return!1;const i=new Date(e.updatedAt).getTime();return(s??Date.now())-i>n}function Ww(e){switch(e){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function Kw(e){return e==="done"||e==="skipped"}function Gw(e,n,s){const i=s?.get(e)?.trim();if(i)return i;const r=n?.workflowStepName?.trim();return r||e}function Ep(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:Gw(u,d,n),status:d?Ww(d.status):"pending",source:"workflow",phase:d?.phase??"pre-merge"}}),o=[...s,...r],l=o.length,c=o.filter(u=>Kw(u.status)).length;return{total:l,completed:c,items:o}}function Jw(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 _p(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:Jw(n)}})}function Yw(e){if(!e||e.length===0)return null;let n=0,s=0;for(const i of _p(e))typeof i.durationMs=="number"&&(n+=i.durationMs,s+=1);return s>0?n:null}const _c=new Map;async function Qw(e,n){const s=_c.get(e);if(s)return s;try{const i=await hp(e,n);return _c.set(e,i.title),i.title}catch{return e}}const yu=12;function Xw(e){return e.length<=yu?e:e.slice(0,yu-3)+"..."}const Mc=new Map;async function Zw(e,n){const s=Mc.get(e);if(s)return s;try{const i=await dp(e,n);return Mc.set(e,i.name),i.name}catch{return e}}function eN(e){return typeof e=="string"&&ad.includes(e)?e:ys}function tN(e,n){return e.length<=n?e:e.slice(0,n-3)+"..."}const nN=new Set(["triage","todo"]),ju=new Set(["planning","researching","executing","finalizing","merging"]),sN={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"},iN=new Set(["in-progress","in-review","done"]),aN=3e4;function Ac(e){if(!e)return null;const n=Date.parse(e);return Number.isFinite(n)?n:null}function rN(e){const n=Ac(e.columnMovedAt??e.updatedAt);if(n==null)return null;const s=Date.now();return n>s?null:n}function oN(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=Ac(o.startedAt);if(l==null)continue;let c;if(o.completedAt){const u=Ac(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 ku(e,n){const s=typeof e.timedExecutionMs=="number"?e.timedExecutionMs:Yw(e.log),i=oN(e,n);return s==null&&i==null?null:(s??0)+(i??0)}function lN(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 cN(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 wu(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 dN(e,n){return e.length!==n.length?!1:e.every((s,i)=>s.name===n[i]?.name&&s.status===n[i]?.status)}function uN(e,n){return e.length!==n.length?!1:e.every((s,i)=>s===n[i])}function mN(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>s===n[i])}function hN(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 pN(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 fN(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 gN(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 xN(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&&fN(s.attachments,i.attachments)&&gN(s.comments,i.comments)&&uN(s.dependencies,i.dependencies)&&dN(s.steps,i.steps)&&mN(s.enabledWorkflowSteps,i.enabledWorkflowSteps)&&pN(s.workflowStepResults,i.workflowStepResults)&&wu(s.prInfo,i.prInfo)&&wu(s.issueInfo,i.issueInfo)}function bN({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:g,onOpenMission:p,onMoveTask:f,lastFetchTimeMs:x,workflowStepNameLookup:v}){const[b,y]=a.useState(!1),[S,j]=a.useState(!1),[R,k]=a.useState(!1),[M,C]=a.useState(e.description||""),[L,A]=a.useState(!1),[P,O]=a.useState(e.column==="in-progress"||e.column==="triage"&&e.steps.some(N=>N.status==="done"||N.status==="skipped")),[V,$]=a.useState(null),[E,D]=a.useState(null),[U,Y]=a.useState(!1),[X,_]=a.useState(!1),[I,T]=a.useState(()=>Date.now()),w=a.useRef(null),q=a.useRef(!1),G=a.useRef(null),me=a.useRef(null),[ue,le]=a.useState(!1),{badgeUpdates:Se,subscribeToBadge:F,unsubscribeFromBadge:ge}=Sp(n),{confirm:se}=Hs(),fe=a.useRef(null),de=a.useRef(!1),xe=a.useCallback(N=>N instanceof Element?!!N.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);a.useEffect(()=>{C(e.description||"")},[e.id,e.description]),a.useEffect(()=>{if(!U)return;const N=W=>{me.current&&!me.current.contains(W.target)&&Y(!1)};return document.addEventListener("click",N),()=>document.removeEventListener("click",N)},[U]),a.useEffect(()=>{if(!e.missionId){$(null);return}const N=_c.get(e.missionId);if(N){$(N);return}let W=!1;return Qw(e.missionId,n).then(Ie=>{W||$(Ie)}),()=>{W=!0}},[e.missionId,n]),a.useEffect(()=>{if(!e.assignedAgentId){D(null);return}const N=Mc.get(e.assignedAgentId);if(N){D(N);return}D(null);let W=!1;return Zw(e.assignedAgentId,n).then(Ie=>{W||D(Ie)}),()=>{W=!0}},[e.assignedAgentId,n]),a.useEffect(()=>{if(R&&w.current){const N=w.current;N.focus(),N.style.height="auto",N.style.height=N.scrollHeight+"px"}},[R]),a.useEffect(()=>{if(typeof IntersectionObserver>"u"){le(!0);return}const N=G.current;if(!N)return;const W=new IntersectionObserver(([Ie])=>{le(Ie?.isIntersecting??!0)},{rootMargin:"200px"});return W.observe(N),()=>W.disconnect()},[R,e.id]);const ie=a.useCallback(N=>{N.dataTransfer.setData("text/plain",e.id),N.dataTransfer.effectAllowed="move",y(!0)},[e.id]),Ee=a.useCallback(()=>{y(!1)},[]),De=a.useCallback(N=>N.dataTransfer.types.includes("Files"),[]),qe=a.useCallback(N=>{De(N)&&(N.preventDefault(),N.stopPropagation(),N.dataTransfer.dropEffect="copy",j(!0))},[De]),Qe=a.useCallback(N=>{De(N)&&(N.preventDefault(),N.stopPropagation(),j(!1))},[De]),Je=a.useCallback(async N=>{if(!De(N))return;N.preventDefault(),N.stopPropagation(),j(!1);const W=Array.from(N.dataTransfer.files);for(const Ie of W)try{await gr(e.id,Ie,n),r(`Attached ${Ie.name} to ${e.id}`,"success")}catch(nt){r(`Failed to attach ${Ie.name}: ${je(nt)}`,"error")}},[e.id,De,r]),Ke=a.useCallback(()=>{R||i(e)},[e,i,R]),it=a.useCallback(N=>{if(q.current){q.current=!1;return}xe(N.target)||Ke()},[Ke,xe]),Pe=a.useCallback(N=>{const W=N.touches[0];W&&(fe.current={x:W.clientX,y:W.clientY,time:Date.now()},de.current=!1)},[]),Ve=a.useCallback(N=>{if(!fe.current)return;const W=N.touches[0];if(!W)return;const Ie=Math.abs(W.clientX-fe.current.x),nt=Math.abs(W.clientY-fe.current.y);(Ie>Nu||nt>Nu)&&(de.current=!0)},[]),ae=a.useCallback(N=>{if(xe(N.target)||!fe.current)return;const Ie=Date.now()-fe.current.time<vN,nt=!de.current;Ie&&nt&&(q.current=!0,Ke()),fe.current=null,de.current=!1},[Ke,xe]),ye=a.useCallback(async(N,W)=>{N.stopPropagation();try{const Ie=await xo(W,n);i(Ie)}catch{r(`Failed to load dependency ${W}`,"error")}},[i,r]),te=e.status==="failed",Ae=e.paused===!0,Le=eN(e.priority),pe=Le!==ys,_e=jo(e,g,x),Fe=e.column==="triage"&&e.status==="awaiting-approval",tt=e.column==="archived",Ne=!o&&!s&&!te&&!Ae&&!_e&&!Fe&&(e.column==="in-progress"||ju.has(e.status)),oe=!s&&!Ae&&!R&&!tt,Te=nN.has(e.column)&&!Ne&&!Ae&&!s&&l,he=!!(e.prInfo||e.issueInfo),Me=!!(e.assignedAgentId&&E===null),We=a.useMemo(()=>{const N=[];return e.modelProvider&&N.push(e.modelProvider),e.validatorModelProvider&&!N.includes(e.validatorModelProvider)&&N.push(e.validatorModelProvider),e.planningModelProvider&&!N.includes(e.planningModelProvider)&&N.push(e.planningModelProvider),N},[e.modelProvider,e.validatorModelProvider,e.planningModelProvider]),Re=a.useMemo(()=>Ep(e,v),[e.steps,e.enabledWorkflowSteps,e.workflowStepResults,v]),ot=Re.total>0&&(e.status==="executing"||e.column==="in-progress");a.useEffect(()=>{if(e.column!=="in-progress"&&e.column!=="in-review"||e.column==="in-progress"&&!(e.workflowStepResults??[]).some(Ie=>Ie.startedAt&&!Ie.completedAt)||e.column==="in-review"&&ku(e,Date.now())==null)return;T(Date.now());const N=window.setInterval(()=>{T(Date.now())},aN);return()=>window.clearInterval(N)},[e.column,e.workflowStepResults,e.timedExecutionMs]);const J=a.useMemo(()=>{if(!iN.has(e.column))return null;const N=ku(e,I);if(N==null)return null;if(e.column==="in-progress"){const yt=lN(N);return yt?{label:yt,title:`Execution time ${yt}`,ariaLabel:`Execution time ${yt}`}:null}const W=cN(N);if(!W)return null;const Ie=rN(e);if(Ie==null)return{label:W,title:`Execution time ${W}`,ariaLabel:`Execution time ${W}`};const nt=new Date(Ie).toLocaleString();return{label:W,title:`Execution time ${W}. Completed ${nt}`,ariaLabel:`Execution time ${W}. Completed ${nt}`}},[e.column,e.columnMovedAt,e.timedExecutionMs,e.updatedAt,e.workflowStepResults,e.log,I]);a.useEffect(()=>{if(!he||!ue){ge(e.id);return}return F(e.id),()=>{ge(e.id)}},[he,ue,F,e.id,ge]);const ce=Se.get(`${n??"default"}:${e.id}`),ve=e.column==="in-progress"||e.column==="in-review",Xe=a.useMemo(()=>e.steps.map(N=>`${N.name}:${N.status}`).join("|"),[e.steps]),{stats:ee}=qw(e.id,e.column,e.mergeDetails?.commitSha,n,{enabled:ue,worktree:e.worktree,stepVersion:ve?Xe:void 0,pollIntervalMs:ve?3e4:void 0}),Ge=a.useMemo(()=>Fw(e.id,n),[e.id,n]),ct=a.useMemo(()=>{const N=ce?.prInfo,W=ce?.timestamp,Ie=Ge?.result?.prInfo,nt=Ge?.timestamp?new Date(Ge.timestamp).toISOString():void 0,yt=e.prInfo,Pt=e.prInfo?.lastCheckedAt??e.updatedAt;let Tt=yo(N,W,yt,Pt);const tn=W&&W>=Pt?W:Pt;return Ie&&nt&&(!tn||nt>tn)&&(Tt=Ie),Tt},[ce,Ge,e.prInfo,e.updatedAt]),vt=a.useMemo(()=>{const N=ce?.issueInfo,W=ce?.timestamp,Ie=Ge?.result?.issueInfo,nt=Ge?.timestamp?new Date(Ge.timestamp).toISOString():void 0,yt=e.issueInfo,Pt=e.issueInfo?.lastCheckedAt??e.updatedAt;let Tt=yo(N,W,yt,Pt);const tn=W&&W>=Pt?W:Pt;return Ie&&nt&&(!tn||nt>tn)&&(Tt=Ie),Tt},[ce,Ge,e.issueInfo,e.updatedAt]),bt=a.useCallback(N=>{N?.stopPropagation(),!(!Te||L)&&(k(!0),C(e.description||""))},[Te,L,e.description]),ft=a.useCallback(()=>{k(!1),C(e.description||"")},[e.description]),gt=a.useCallback(()=>M!==(e.description||""),[M,e.description]),_t=a.useCallback(async()=>{if(!(!l||L)){if(!gt()){ft();return}A(!0);try{await l(e.id,{description:M.trim()||void 0}),r(`Updated ${e.id}`,"success"),k(!1)}catch(N){r(`Failed to update ${e.id}: ${je(N)}`,"error")}finally{A(!1)}}},[l,e.id,M,L,gt,ft,r]),Rt=a.useCallback(N=>{N.key==="Enter"&&!N.shiftKey?(N.preventDefault(),_t()):N.key==="Escape"&&(N.preventDefault(),ft())},[_t,ft]),Ft=a.useCallback(()=>{setTimeout(()=>{const N=document.activeElement;N===w.current||N?.closest(".card-editing-content")||(gt()?_t():ft())},0)},[gt,_t,ft]),wt=a.useCallback(N=>{Te&&(N.stopPropagation(),bt(N))},[Te,bt]),At=a.useCallback(N=>{N.stopPropagation(),bt(N)},[bt]),qt=a.useCallback(N=>{C(N.target.value);const W=N.target;W.style.height="auto",W.style.height=W.scrollHeight+"px"},[]),zt=a.useCallback(N=>{N.stopPropagation(),c&&c(e.id).then(()=>{r(`Archived ${e.id}`,"success")}).catch(W=>{r(`Failed to archive ${e.id}: ${je(W)}`,"error")})},[r,c,e.id]),Wt=a.useCallback(N=>{N.stopPropagation(),u&&u(e.id).then(()=>{r(`Unarchived ${e.id}`,"success")}).catch(W=>{r(`Failed to unarchive ${e.id}: ${je(W)}`,"error")})},[r,u,e.id]),Ot=a.useCallback(async N=>{if(N.stopPropagation(),!(!d||!await se({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0})))try{await d(e.id),r(`Deleted ${e.id}`,"success")}catch(Ie){const nt=hN(Ie);if(!nt||nt.dependentIds.length===0){r(`Failed to delete ${e.id}: ${je(Ie)}`,"error");return}const yt=nt.dependentIds.join(", ");if(!await se({title:"Force Delete Task",message:`${e.id} is a dependency of ${yt}.
|
|
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(Tt){r(`Failed to delete ${e.id}: ${je(Tt)}`,"error")}}},[r,se,d,e.id]),Nt=a.useCallback(N=>{N.stopPropagation(),h?.(e,"changes")},[e,h]),Mt=a.useCallback(N=>{N.stopPropagation(),O(W=>!W)},[]),Ct=a.useCallback(N=>{N.stopPropagation(),e.missionId&&p&&p(e.missionId)},[e.missionId,p]),Gt=a.useCallback(N=>{N.stopPropagation(),Y(W=>!W)},[]),Et=a.useCallback((N,W)=>{N.stopPropagation(),Y(!1),f&&f(e.id,W).then(()=>{r(`Moved ${e.id} to ${An[W]}`,"success")}).catch(Ie=>{r(`Failed to move ${e.id}: ${je(Ie)}`,"error")})},[r,f,e.id]),H=a.useCallback(async N=>{if(N.stopPropagation(),!(!m||X)){_(!0);try{await m(e.id)}catch(W){r(`Failed to retry ${e.id}: ${je(W)}`,"error")}finally{_(!1)}}},[r,X,m,e.id]),be=`card${b?" dragging":""}${s?" queued":""}${Ne?" agent-active":""}${te?" failed":""}${Ae?" paused":""}${_e?" stuck":""}${Fe?" awaiting-approval":""}${S?" file-drop-target":""}${R?" card-editing":""}${L?" card-saving":""}`,re=(()=>{if(e.worktree&&e.column==="in-progress"){const N=ee?.filesChanged;return N==null||N===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:Nt,disabled:!h,children:[t.jsx(Un,{size:12}),t.jsxs("span",{children:[N," ",N===1?"file":"files"," changed"]})]})}if(e.column==="in-review"){const N=ee?.filesChanged,W=N==null?e.modifiedFiles?.length:void 0,Ie=N??W;return Ie==null||Ie===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:Nt,disabled:!h,children:[t.jsx(Un,{size:12}),t.jsxs("span",{children:[Ie," ",Ie===1?"file":"files"," changed"]})]})}if(e.column==="done"){const N=ee?.filesChanged,W=e.mergeDetails?.filesChanged,Ie=N??W;if(Ie!=null&&Ie>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:Nt,disabled:!h,children:[t.jsx(Un,{size:12}),t.jsxs("span",{children:[Ie," ",Ie===1?"file":"files"," changed"]})]});const nt=e.modifiedFiles?.length;if(nt!=null&&nt>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:Nt,disabled:!h,children:[t.jsx(Un,{size:12}),t.jsxs("span",{children:[nt," ",nt===1?"file":"files"," changed"]})]})}return null})();return R?t.jsx("div",{ref:G,className:be,"data-id":e.id,onDoubleClick:wt,children:t.jsxs("div",{className:"card-editing-content",children:[t.jsx("textarea",{ref:w,className:"card-edit-desc-textarea",placeholder:"Task description",value:M,onChange:qt,onKeyDown:Rt,onBlur:Ft,disabled:L,rows:4}),L&&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:G,className:be,"data-id":e.id,draggable:oe,onDragStart:oe?ie:void 0,onDragEnd:oe?Ee:void 0,onDragOver:qe,onDragLeave:Qe,onDrop:Je,onClick:it,onTouchStart:Pe,onTouchMove:Ve,onTouchEnd:ae,onDoubleClick:wt,children:[t.jsxs("div",{className:"card-header",children:[t.jsx("span",{className:"card-id",children:e.id}),Ae&&t.jsx("span",{className:"card-status-badge paused",children:"paused"}),!Ae&&e.status&&e.status!=="queued"&&t.jsx("span",{className:`card-status-badge card-status-badge--${e.column}${Fe?" awaiting-approval":""}${ju.has(e.status)?" pulsing":""}${te?" failed":""}${_e?" stuck":""}`,children:_e?"Stuck":Fe?"Awaiting Approval":e.status}),_e&&(Ae||!e.status||e.status==="queued")&&t.jsx("span",{className:"card-status-badge stuck",children:"Stuck"}),he&&t.jsx(Np,{prInfo:ct,issueInfo:vt}),pe&&t.jsx("span",{className:`card-priority-badge card-priority-badge--${Le}`,children:Le}),e.executionMode==="fast"&&t.jsx("span",{className:"card-execution-mode-badge card-execution-mode-badge--fast",children:"Fast"}),e.missionId&&t.jsxs("span",{className:"card-mission-badge",onClick:Ct,title:`Mission: ${V??e.missionId}`,role:p?"button":void 0,tabIndex:p?0:void 0,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[t.jsx(us,{size:11}),Xw(V??e.missionId)]}),t.jsxs("div",{className:"card-header-actions",children:[Te&&t.jsx("button",{className:"card-edit-btn",onClick:At,title:"Edit task","aria-label":"Edit task",children:t.jsx(ss,{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(Zt,{size:12})}),e.column==="done"&&c&&t.jsx("button",{className:"card-archive-btn",onClick:zt,title:"Archive task","aria-label":"Archive task",children:"Archive"}),e.column==="archived"&&u&&t.jsx("button",{className:"card-unarchive-btn",onClick:Wt,title:"Unarchive task","aria-label":"Unarchive task",children:"Unarchive"}),e.column==="in-progress"&&f&&t.jsxs("div",{className:"card-send-back",ref:me,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:Gt,title:"Send back","aria-label":"Send back","aria-haspopup":"menu","aria-expanded":U,children:["Send back",t.jsx(Vt,{size:10})]}),U&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:Cc["in-progress"].filter(N=>N!=="in-review").map(N=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:W=>Et(W,N),children:An[N]},N))})]}),e.column==="in-review"&&f&&t.jsxs("div",{className:"card-send-back",ref:me,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:Gt,title:"Move task","aria-label":"Move task","aria-haspopup":"menu","aria-expanded":U,children:["Move",t.jsx(Vt,{size:10})]}),U&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:Cc["in-review"].map(N=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:W=>Et(W,N),children:N==="done"?"Done (no merge)":An[N]},N))})]}),e.size&&t.jsx("span",{className:`card-size-badge size-${e.size.toLowerCase()}`,children:e.size})]})]}),te&&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:H,disabled:X,children:[t.jsx(Rb,{size:12}),X?"Retrying…":"Retry"]})]}),t.jsx("div",{className:"card-title",title:e.title||e.description||void 0,children:Cu(e.title,Su)||Cu(e.description,Su)||e.id}),ot&&(()=>{const N=Re.completed/Re.total*100;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"card-progress",children:[t.jsx("div",{className:"card-progress-bar",children:t.jsx("div",{className:"card-progress-fill",style:{width:`${N}%`,backgroundColor:sN[e.column]}})}),t.jsxs("span",{className:"card-progress-label",children:[Re.completed,"/",Re.total]})]}),t.jsxs("button",{type:"button",className:"card-steps-toggle",onClick:Mt,"aria-expanded":P,"aria-label":P?"Hide steps":"Show steps",children:[t.jsxs("span",{children:[Re.total," step",Re.total===1?"":"s"]}),t.jsx(Vt,{size:14,className:`card-steps-toggle-icon${P?" expanded":""}`})]}),P&&t.jsx("div",{className:"card-steps-list",children:Re.items.map(W=>{const Ie=W.source==="workflow"&&W.status==="failed";return t.jsxs("div",{className:"card-step-item",children:[t.jsx("span",{className:`card-step-dot card-step-dot--${W.status}${Ie?" card-step-dot--workflow-failed":""}`,"aria-hidden":"true"}),t.jsx("span",{className:`card-step-name${W.status==="done"?" completed":""}`,children:W.name}),W.source==="workflow"&&t.jsx("span",{className:`card-step-workflow-badge card-step-workflow-badge--${W.phase}`,title:"Workflow check",children:"workflow"})]},W.id)})})]})})(),(re||J)&&t.jsxs("div",{className:"card-footer-row",children:[re,J&&t.jsxs("span",{className:"card-time-indicator",title:J.title,"aria-label":J.ariaLabel,children:[t.jsx(wi,{size:12}),t.jsx("span",{children:J.label})]})]}),(e.dependencies&&e.dependencies.length>0||s||e.status==="queued"||e.blockedBy)&&t.jsxs("div",{className:"card-meta",children:[e.dependencies&&e.dependencies.length>0&&t.jsx("div",{className:"card-dep-list",children:e.dependencies.map(N=>t.jsxs("span",{className:"card-dep-badge clickable",onClick:W=>void ye(W,N),title:`Click to view ${N}`,children:[t.jsx(ga,{size:12,style:{verticalAlign:"middle"}})," ",N]},N))}),e.blockedBy&&t.jsxs("span",{className:"card-scope-badge","data-tooltip":`Blocked by ${e.blockedBy} (file overlap)`,children:[t.jsx(Hi,{size:12,style:{verticalAlign:"middle"}})," ",e.blockedBy]}),(s||e.status==="queued")&&e.column!=="in-progress"&&t.jsxs("span",{className:"queued-badge",children:[t.jsx(wi,{size:12,style:{verticalAlign:"middle"}})," Queued"]})]}),(e.assignedAgentId||We.length>0)&&t.jsxs("div",{className:"card-agent-row",children:[We.length>0&&t.jsx("span",{className:"card-provider-icons","data-testid":"card-provider-icons",children:We.map(N=>t.jsx(Dn,{provider:N,size:"sm"},N))}),e.assignedAgentId&&t.jsxs("span",{className:`card-agent-badge${Me?" card-agent-badge--loading":""}`,title:`Assigned to ${E??e.assignedAgentId}`,children:[t.jsx(yn,{size:11}),t.jsx("span",{className:"card-agent-badge-text",children:tN(E??e.assignedAgentId,15)})]})]}),t.jsx(Uo,{slotId:"task-card-badge",projectId:n})]})}const Nu=10,vN=300,Su=140;function Cu(e,n){return e?e.length>n?e.slice(0,n)+"…":e:""}const ko=a.memo(bN,xN);ko.displayName="TaskCard";function yN({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:g,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(ex,{size:14}):t.jsx(Zs,{size:14})}),t.jsx("span",{className:"worktree-label",children:e})]}),n.map(f=>t.jsx(ko,{task:f,projectId:i,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:u,onOpenDetailWithTab:d,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:g,workflowStepNameLookup:p},f.id)),s.map(f=>t.jsx(ko,{task:f,projectId:i,queued:!0,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:u,onOpenDetailWithTab:d,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:g,workflowStepNameLookup:p},f.id))]})}const Mp=a.memo(yN);Mp.displayName="WorktreeGroup";function Eu(e){return e.toLowerCase().replace(/[-_./]/g,"")}function jN(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 kN(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 wN(e,n){const s=Eu(e),i=Eu(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&&jN(s,o)||s.length>=4&&kN(s,o,1))return!0;return!1}function NN(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=>wN(o,r))})}function Hn({models:e,value:n,onChange:s,placeholder:i="Select a model…",disabled:r=!1,id:o,label:l,favoriteProviders:c=[],onToggleFavorite:u,favoriteModels:d=[],onToggleModelFavorite:m,noChangeValue:h,noChangeLabel:g="No change"}){const[p,f]=a.useState(!1),[x,v]=a.useState(""),[b,y]=a.useState(0),[S,j]=a.useState(null),[R,k]=a.useState(null),M=a.useRef(null),C=a.useRef(null),L=a.useRef(null),A=a.useRef(null),P=a.useRef(null),O=a.useMemo(()=>NN(e,x),[e,x]),V=a.useMemo(()=>O.reduce((se,fe)=>((se[fe.provider]??=[]).push(fe),se),{}),[O]),$=a.useMemo(()=>{const se=[];for(const fe of d){const de=fe.indexOf("/");if(de===-1)continue;const xe=fe.slice(0,de),ie=fe.slice(de+1),Ee=O.find(De=>De.provider===xe&&De.id===ie);Ee&&se.push({model:Ee,fullId:fe})}return se},[d,O]),E=a.useMemo(()=>{const se=Object.entries(V),fe=new Set(c);return se.sort(([de],[xe])=>{const ie=fe.has(de),Ee=fe.has(xe);if(ie&&!Ee)return-1;if(!ie&&Ee)return 1;if(ie&&Ee){const De=c.indexOf(de),qe=c.indexOf(xe);if(De!==qe)return De-qe}return de.localeCompare(xe)})},[V,c]),D=typeof h=="string"&&h.length>0,U=a.useMemo(()=>{if(!n||D&&n===h)return null;const se=n.indexOf("/");return se===-1?null:n.slice(0,se)},[D,h,n]),Y=a.useMemo(()=>{const se=[];return D&&se.push({type:"no-change",value:h,label:g}),se.push({type:"default",value:"",label:"Use default"}),se},[D,g,h]),X=a.useMemo(()=>{const se=[...Y];for(const{model:fe,fullId:de}of $)se.push({type:"favorite",value:de,label:fe.name,provider:fe.provider});return E.forEach(([fe,de])=>{se.push({type:"provider",value:`__group_${fe}`,label:fe,provider:fe}),de.forEach(xe=>{se.push({type:"model",value:`${xe.provider}/${xe.id}`,label:xe.name,provider:xe.provider})})}),se},[$,E,Y]),_=a.useMemo(()=>{if(D&&n===h)return g;if(!n)return"Use default";const se=n.indexOf("/");if(se===-1)return n;const fe=n.slice(0,se),de=n.slice(se+1);return e.find(ie=>ie.provider===fe&&ie.id===de)?.name||n},[D,g,h,n,e]),I=a.useMemo(()=>X.findIndex(se=>se.value===n),[X,n]),T=a.useCallback(()=>{const se=window.visualViewport;return se&&se.height>0&&se.width>0?{width:se.width,height:se.height,offsetTop:se.offsetTop,offsetLeft:se.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),w=a.useCallback(()=>{const{height:se}=T(),fe=typeof window.matchMedia=="function",de=fe?window.matchMedia("(max-width: 640px)").matches:!1,xe=fe?window.matchMedia("(max-width: 768px)").matches:!1;return se<=0?320:de?Math.min(se*.6,360):xe?Math.min(se*.7,420):320},[T]),q=a.useCallback(()=>{const se=C.current;if(!se)return;const fe=se.getBoundingClientRect(),{width:de,height:xe,offsetTop:ie,offsetLeft:Ee}=T(),De=16,qe=16,Qe=4,Je=w(),Ke=fe.bottom-ie,it=fe.top-ie,Pe=fe.left-Ee,Ve=xe-Ke,ae=it,ye=Math.max(Ve-qe-Qe,160),te=Math.max(ae-qe-Qe,160),Ae=Ve<Je&&ae>Ve,Le=Math.max(Math.min(Ae?te:ye,Je),160),pe=Math.min(fe.width,de-De*2),_e=Math.min(Math.max(Pe,De),de-De-pe)+Ee,Fe=Ae?Math.max(qe+ie,it-Le-Qe+ie):Math.min(Ke+Qe+ie,xe+ie-qe-Le);j({top:Fe,left:_e,width:pe,maxHeight:Le})},[T,w]);a.useEffect(()=>{k(document.body)},[]);const G=a.useRef(!1);a.useEffect(()=>{if(!p){G.current=!1;return}if(G.current||X.length===0)return;const se=X.findIndex((fe,de)=>de>=(I>=0?I:0)&&fe.type!=="provider");y(se>=0?se:0),G.current=!0},[p,X,I]),a.useEffect(()=>{p&&G.current&&(y(0),P.current&&(P.current.scrollTop=0))},[x,p]),a.useEffect(()=>{if(!p)return;q();const se=requestAnimationFrame(()=>A.current?.focus());return()=>cancelAnimationFrame(se)},[p,q]),a.useEffect(()=>{if(!p)return;const se=()=>q();window.addEventListener("resize",se),window.addEventListener("scroll",se,!0);const fe=window.visualViewport;return fe&&(fe.addEventListener("resize",se),fe.addEventListener("scroll",se)),()=>{window.removeEventListener("resize",se),window.removeEventListener("scroll",se,!0),fe&&(fe.removeEventListener("resize",se),fe.removeEventListener("scroll",se))}},[p,q]),a.useEffect(()=>{if(!p)return;const se=fe=>{const de=fe.target,xe=M.current?.contains(de),ie=L.current?.contains(de);!xe&&!ie&&(f(!1),v(""))};return document.addEventListener("mousedown",se),()=>document.removeEventListener("mousedown",se)},[p]);const me=a.useCallback(se=>{switch(se.key){case"ArrowDown":if(se.preventDefault(),!p)f(!0);else{let fe=b;for(let de=1;de<=X.length;de++){const xe=(b+de)%X.length;if(X[xe]?.type!=="provider"){fe=xe;break}}y(fe)}break;case"ArrowUp":if(se.preventDefault(),p){let fe=b;for(let de=1;de<=X.length;de++){const xe=(b-de+X.length)%X.length;if(X[xe]?.type!=="provider"){fe=xe;break}}y(fe)}break;case"Enter":if(se.preventDefault(),p){const fe=X[b];fe&&fe.type!=="provider"&&fe.type!=="favorite"&&(s(fe.value),f(!1),v(""))}else f(!0);break;case"Escape":se.preventDefault(),f(!1),v("");break;case"Tab":p&&(f(!1),v(""));break}},[p,b,X,s]),ue=a.useCallback(se=>{s(se),f(!1),v("")},[s]),le=a.useCallback(()=>{v(""),A.current?.focus()},[]),Se=a.useCallback(()=>{r||f(se=>!se)},[r]);a.useEffect(()=>{if(p&&P.current){const se=P.current.querySelector(`[data-index="${b}"]`);se&&typeof se.scrollIntoView=="function"&&se.scrollIntoView({block:"nearest"})}},[b,p]);const F=x.length>0,ge=p&&S?t.jsxs("div",{ref:L,className:"model-combobox-dropdown model-combobox-dropdown--portal",role:"listbox","data-testid":"model-combobox-portal",onKeyDown:me,style:{top:`${S.top}px`,left:`${S.left}px`,width:`${S.width}px`,maxHeight:`${S.maxHeight}px`},children:[t.jsxs("div",{className:"model-combobox-search-wrapper",children:[t.jsx("input",{ref:A,type:"text",className:"model-combobox-search",placeholder:"Filter models…",value:x,onChange:se=>v(se.target.value),onClick:se=>se.stopPropagation()}),F&&t.jsx("button",{type:"button",className:"model-combobox-clear",onClick:le,"aria-label":"Clear filter",children:"×"})]}),t.jsxs("div",{className:"model-combobox-results-count",children:[O.length," model",O.length!==1?"s":""]}),t.jsxs("div",{ref:P,className:"model-combobox-list",children:[Y.map((se,fe)=>t.jsx("div",{"data-index":fe,className:`model-combobox-option ${b===fe?"model-combobox-option--highlighted":""} ${n===se.value?"model-combobox-option--selected":""}`,onClick:()=>ue(se.value),onMouseEnter:()=>y(fe),role:"option","aria-selected":n===se.value,children:t.jsx("span",{className:"model-combobox-option-text model-combobox-option-text--default",children:se.label})},`${se.type}-${se.value}`)),$.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"model-combobox-divider"}),$.map(({model:se,fullId:fe},de)=>{const xe=de+Y.length,ie=b===xe,Ee=n===fe;return t.jsxs("div",{"data-index":xe,className:`model-combobox-option model-combobox-option--favorite ${ie?"model-combobox-option--highlighted":""} ${Ee?"model-combobox-option--selected":""}`,onClick:()=>ue(fe),onMouseEnter:()=>y(xe),role:"option","aria-selected":Ee,children:[t.jsxs("span",{className:"model-combobox-option-main",children:[t.jsx("span",{className:"model-combobox-option-icon",children:t.jsx(Dn,{provider:se.provider,size:"sm"})}),t.jsx("span",{className:"model-combobox-option-text",children:se.name})]}),t.jsx("span",{className:"model-combobox-option-id",children:se.id}),m&&t.jsx("button",{type:"button",className:"model-combobox-option-favorite model-combobox-option-favorite--active",onClick:De=>{De.stopPropagation(),m(fe)},title:"Remove from favorites","aria-label":`Remove ${se.name} from favorites`,children:"★"})]},fe)}),t.jsx("div",{className:"model-combobox-divider"})]}),E.map(([se,fe])=>{const de=X.findIndex(Ee=>Ee.value===`__group_${se}`),xe=c.includes(se),ie=fe.filter(Ee=>{const De=`${Ee.provider}/${Ee.id}`;return!d.includes(De)});return ie.length===0?null:t.jsxs("div",{className:"model-combobox-group",children:[t.jsxs("div",{className:"model-combobox-optgroup","data-index":de,children:[t.jsx(Dn,{provider:se,size:"sm"}),t.jsx("span",{className:"model-combobox-optgroup-text",children:se}),u&&t.jsx("button",{type:"button",className:`model-combobox-optgroup-favorite ${xe?"model-combobox-optgroup-favorite--active":""}`,onClick:Ee=>{Ee.stopPropagation(),u(se)},title:xe?"Remove from favorites":"Add to favorites","aria-label":xe?`Remove ${se} from favorites`:`Add ${se} to favorites`,children:"★"})]}),ie.map(Ee=>{const De=`${Ee.provider}/${Ee.id}`,qe=X.findIndex(it=>it.value===De),Qe=b===qe,Je=n===De,Ke=d.includes(De);return t.jsxs("div",{"data-index":qe,className:`model-combobox-option ${Qe?"model-combobox-option--highlighted":""} ${Je?"model-combobox-option--selected":""}`,onClick:()=>ue(De),onMouseEnter:()=>y(qe),role:"option","aria-selected":Je,children:[t.jsx("span",{className:"model-combobox-option-text",children:Ee.name}),t.jsx("span",{className:"model-combobox-option-id",children:Ee.id}),m&&t.jsx("button",{type:"button",className:`model-combobox-option-favorite ${Ke?"model-combobox-option-favorite--active":""}`,onClick:it=>{it.stopPropagation(),m(De)},title:Ke?"Remove from favorites":"Add to favorites","aria-label":Ke?`Remove ${Ee.name} from favorites`:`Add ${Ee.name} to favorites`,children:Ke?"★":"☆"})]},De)})]},se)}),O.length===0&&F&&t.jsxs("div",{className:"model-combobox-no-results",children:["No models match '",x,"'"]})]})]}):null;return t.jsxs(t.Fragment,{children:[t.jsx("div",{ref:M,className:"model-combobox",onKeyDown:me,children:t.jsxs("button",{ref:C,type:"button",id:o,className:"model-combobox-trigger",onClick:Se,disabled:r,"aria-haspopup":"listbox","aria-expanded":p,"aria-label":l,children:[U&&t.jsx("span",{className:"model-combobox-trigger-icon",children:t.jsx(Dn,{provider:U,size:"sm"})}),t.jsx("span",{className:"model-combobox-trigger-text",children:_||i}),t.jsx("span",{className:"model-combobox-trigger-arrow",children:"▼"})]})}),R&&ge?da.createPortal(ge,R):null]})}function rd(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(rd(e,n))}function ds(e,n,s){typeof window>"u"||window.localStorage.setItem(rd(e,s),n)}function vr(e,n){typeof window>"u"||window.localStorage.removeItem(rd(e,n))}const SN=1e4,CN=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 vo();n(p)}catch(p){o(p instanceof Error?p.message:"Failed to fetch nodes")}},[]);a.useEffect(()=>{let p=!1;async function f(){i(!0);try{const v=await vo();p||(n(v),o(null))}catch(v){p||o(v instanceof Error?v.message:"Failed to fetch nodes")}finally{p||i(!1)}}f();const x=()=>{if(document.visibilityState!=="visible")return;const v=Date.now();v-c.current<CN||(c.current=v,u())};return document.addEventListener("visibilitychange",x),()=>{p=!0,document.removeEventListener("visibilitychange",x)}},[u]),a.useEffect(()=>{if(!s)return l.current=setInterval(()=>{u()},SN),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async p=>{const f=await Pj(p);return n(x=>[...x,f]),f},[]),m=a.useCallback(async(p,f)=>{const x=await Ij(p,f);return n(v=>v.map(b=>b.id===p?x:b)),x},[]),h=a.useCallback(async p=>{await $j(p),n(f=>f.filter(x=>x.id!==p))},[]),g=a.useCallback(async p=>{const f=await Dj(p);n(x=>x.map(v=>v.id===p?{...v,status:f.status,updatedAt:f.checkedAt}:v))},[]);return{nodes:e,loading:s,error:r,refresh:u,register:d,update:m,unregister:h,healthCheck:g}}const Oa="kb-quick-entry-text",EN=["image/png","image/jpeg","image/gif","image/webp"];function _N(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function xl(e,n){return e&&n?`${e}/${n}`:""}function bl(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 Ap({onCreate:e,addToast:n,tasks:s=[],availableModels:i,onPlanningMode:r,onSubtaskBreakdown:o,projectId:l,autoExpand:c=!0,favoriteProviders:u,favoriteModels:d,onToggleFavorite:m,onToggleModelFavorite:h}){const[g,p]=a.useState(()=>typeof window<"u"&&qn(Oa,l)||""),[f,x]=a.useState(!1),[v,b]=a.useState(!1),[y,S]=a.useState(!1),j=a.useRef(null),R=a.useRef(null),k=a.useRef(!1),M=a.useRef(l),[C,L]=a.useState([]),A=a.useRef([]),[P,O]=a.useState([]),[V,$]=a.useState(!1),[E,D]=a.useState(""),[U,Y]=a.useState(null),[X,_]=a.useState([]),[I,T]=a.useState(void 0),[w,q]=a.useState(!1),[G,me]=a.useState(!1),[ue,le]=a.useState(!1),[Se,F]=a.useState(!1),[ge,se]=a.useState(null),[fe,de]=a.useState(void 0),[xe,ie]=a.useState(void 0),[Ee,De]=a.useState(void 0),[qe,Qe]=a.useState(void 0),[Je,Ke]=a.useState(void 0),[it,Pe]=a.useState(void 0),Ve=a.useRef(null),ae=a.useRef(null),ye=a.useRef(null),te=a.useRef(null),Ae=a.useRef(null),Le=a.useRef(null),[pe,_e]=a.useState(null),[Fe,tt]=a.useState(null),[Ne,oe]=a.useState(null),Te=a.useRef(null),he=a.useRef(null),[Me,We]=a.useState(null),[Re]=a.useState(()=>typeof document<"u"?document.body:null),[ot,J]=a.useState(!1),[ce,ve]=a.useState(null),[Xe,ee]=a.useState(i??[]),[Ge,ct]=a.useState([]),[vt,bt]=a.useState([]),[ft,gt]=a.useState(null),[_t,Rt]=a.useState(void 0),[Ft,wt]=a.useState(!1),[At,qt]=a.useState(void 0),{nodes:zt}=qo(),[Wt,Ot]=a.useState(!1),[Nt,Mt]=a.useState(!1),Ct=a.useRef(null),Gt=a.useRef(null),[Et,H]=a.useState(null),be=u??Ge,re=d??vt,N=!e;a.useEffect(()=>{if(i)ee(i),J(!1),ve(null);else{let ne=!1;return J(!0),ve(null),ms().then(Ce=>{ne||(ee(Ce.models),u||ct(Ce.favoriteProviders),d||bt(Ce.favoriteModels))}).catch(Ce=>{ne||ve(je(Ce)||"Failed to load models")}).finally(()=>{ne||J(!1)}),Fo(l).then(Ce=>{ne||gt(Ce)}).catch(()=>{}),()=>{ne=!0}}},[i,u,d,l]);const W=xl(fe,xe),Ie=xl(Ee,qe),nt=xl(Je,it),yt=!!(fe&&xe),Pt=!!(Ee&&qe),Tt=!!(Je&&it),tn=Number(yt)+Number(Pt)+Number(Tt),nn=_t?ft?.modelPresets?.find(ne=>ne.id===_t)?.name??"Models":tn>0?`${tn} model${tn===1?"":"s"}`:"Models",Ln=a.useCallback((ne,Ce)=>{if(!ne||!Ce)return"Using default";const Ze=Xe.find(xt=>xt.provider===ne&&xt.id===Ce);return Ze?`${Ze.provider}/${Ze.id}`:`${ne}/${Ce}`},[Xe]);a.useEffect(()=>{p(qn(Oa,l)||"")},[l]),a.useEffect(()=>{typeof window<"u"&&ds(Oa,g,l)},[g,l]),a.useEffect(()=>{M.current!==l&&(M.current=l,_([]),T(void 0),Y(null),q(!1),_e(null))},[l]),a.useEffect(()=>{typeof window<"u"&&localStorage.removeItem("kb-quick-entry-expanded")},[]),a.useEffect(()=>{A.current=C},[C]),a.useEffect(()=>()=>{A.current.forEach(ne=>URL.revokeObjectURL(ne.previewUrl))},[]);const Jt=a.useCallback(()=>{const ne=j.current;if(!ne)return;ne.style.height="auto";const Ce=Math.min(ne.scrollHeight,200);ne.style.height=`${Ce}px`},[]);a.useEffect(()=>{v&&Jt()},[g,v,Jt]),a.useEffect(()=>{if(!f&&g===""&&j.current){const ne=setTimeout(()=>{j.current?.focus()},0);return()=>clearTimeout(ne)}},[f,g]),a.useEffect(()=>{V||D("")},[V]),a.useEffect(()=>{if(!Wt)return;const ne=Ce=>{const Ze=Ce.target,xt=Ct.current?.contains(Ze),ht=Gt.current?.contains(Ze);!xt&&!ht&&Ot(!1)};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[Wt]),a.useEffect(()=>{if(!Se)return;const ne=Ce=>{const Ze=Ce.target,xt=Ve.current?.contains(Ze),ht=ae.current?.contains(Ze),xn=Ze instanceof Element&&Ze.closest?.(".model-combobox-dropdown--portal")!=null;!xt&&!ht&&!xn&&(F(!1),se(null))};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[Se]),a.useEffect(()=>{if(!G)return;const ne=Ce=>{const Ze=Ce.target;Ae.current?.contains(Ze)||Le.current?.contains(Ze)||(me(!1),tt(null))};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[G]),a.useEffect(()=>{if(!w)return;const ne=Ce=>{const Ze=Ce.target;ye.current?.contains(Ze)||te.current?.contains(Ze)||(q(!1),_e(null))};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[w]);const Rn=a.useCallback(()=>{C.forEach(ne=>URL.revokeObjectURL(ne.previewUrl)),L([]),R.current&&(R.current.value=""),p(""),O([]),Y(null),q(!1),_e(null),me(!1),tt(null),de(void 0),ie(void 0),De(void 0),Qe(void 0),Ke(void 0),Pe(void 0),Rt(void 0),wt(!1),qt(void 0),$(!1),F(!1),oe(null),se(null),Ot(!1),Mt(!1),b(!1),S(!1),k.current=!0,j.current&&(j.current.style.height="auto"),typeof window<"u"&&vr(Oa,l)},[C,l]),ke=a.useCallback(ne=>{if(!ne||ne.length===0)return;const Ce=[];for(let Ze=0;Ze<ne.length;Ze++){const xt=ne[Ze];EN.includes(xt.type)&&Ce.push({file:xt,previewUrl:URL.createObjectURL(xt)})}Ce.length>0&&L(Ze=>[...Ze,...Ce])},[]),at=a.useCallback(ne=>{f||ke(ne.clipboardData?.files)},[ke,f]),gn=a.useCallback(ne=>{L(Ce=>{const Ze=Ce[ne];return Ze&&URL.revokeObjectURL(Ze.previewUrl),Ce.filter((xt,ht)=>ht!==ne)})},[]),Tn=a.useCallback(async()=>{const ne=g.trim();if(!ne||f||!e)return;const Ce=g;x(!0),p("");try{const Ze=await e({description:ne,column:"triage",dependencies:P.length?P:void 0,...U?{assignedAgentId:U}:{},modelPresetId:_t,modelProvider:yt?fe:void 0,modelId:yt?xe:void 0,validatorModelProvider:Pt?Ee:void 0,validatorModelId:Pt?qe:void 0,planningModelProvider:Tt?Je:void 0,planningModelId:Tt?it:void 0,...Ft?{executionMode:"fast"}:{},nodeId:At});if(Ze&&C.length>0){const xt=[];for(const ht of C)try{await gr(Ze.id,ht.file,l)}catch{xt.push(ht.file.name)}xt.length>0&&n(`Failed to upload: ${xt.join(", ")}`,"error")}Rn()}catch(Ze){p(Ce),n(je(Ze)||"Failed to create task","error")}finally{x(!1)}},[g,f,e,P,U,yt,fe,xe,Pt,Ee,qe,Tt,Je,it,C,l,n,Rn,Ft,At]),Pn=a.useCallback(ne=>{if(ne.key==="Enter"){if(ne.shiftKey&&v)return;ne.preventDefault(),Tn()}else if(ne.key==="Escape"){if(ne.preventDefault(),ge){se(null);return}if(Se){F(!1),oe(null);return}if(V){$(!1);return}if(Wt){Ot(!1);return}if(G){me(!1),tt(null);return}if(w){q(!1),_e(null);return}g.trim()&&(p(""),j.current&&(j.current.style.height="auto"),typeof window<"u"&&vr(Oa,l)),b(!1),S(!1),j.current?.blur()}},[Tn,g,v,V,w,G,Se,ge,Wt,l,S]),Nn=a.useCallback(()=>{k.current&&(k.current=!1)},[]),es=a.useCallback(()=>{c&&b(!0)},[c]),Sn=a.useCallback(ne=>{O(Ce=>Ce.includes(ne)?Ce.filter(Ze=>Ze!==ne):[...Ce,ne])},[]),Yt=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}},[]),Q=a.useCallback(()=>{const ne=Ve.current;if(!ne)return;const Ce=ne.getBoundingClientRect(),{width:Ze,height:xt,offsetTop:ht,offsetLeft:xn}=Yt(),Qt=16,an=16,dn=4,In=Ze<=768,Vn=Math.min(In?xt*.6:xt*.5,360),Wn=In?Math.min(Ze-Qt*2,360):Math.max(Ce.width,240),Cn=Math.min(Wn,Math.max(Ze-Qt*2,200)),Kn=Ce.top-ht,zn=Ce.bottom-ht,fs=Ce.left-xn,vn=xt-zn,Fn=Kn,ls=Math.max(vn-an-dn,160),Ss=Math.max(Fn-an-dn,160),ts=vn<Vn&&Fn>vn,rn=Math.max(Math.min(ts?Ss:ls,Vn),160),On=Math.min(Math.max(fs,Qt),Ze-Qt-Cn)+xn,zs=ts?Math.max(an+ht,Kn-rn-dn+ht):Math.min(zn+dn+ht,xt+ht-an-rn);oe({top:zs,left:On,width:Cn,maxHeight:rn})},[Yt]),ze=a.useCallback(()=>{const ne=Ct.current?.querySelector(".refine-button");if(!ne)return;const Ce=ne.getBoundingClientRect(),{width:Ze,height:xt,offsetTop:ht,offsetLeft:xn}=Yt(),Qt=8,an=12,dn=4,In=Math.min(200,Math.max(xt-an*2,160)),Vn=Math.min(200,Ze-Qt*2),Wn=Ce.top-ht,Cn=Ce.bottom-ht,Kn=Ce.left-xn,zn=xt-Cn,fs=Wn,vn=zn<In&&fs>zn,Fn=Math.min(Math.max(Kn,Qt),Ze-Qt-Vn)+xn,ls=vn?Math.max(an+ht,Wn-In-dn+ht):Math.min(Cn+dn+ht,xt+ht-an-In);H({top:ls,left:Fn})},[Yt]),Ye=a.useCallback(()=>{const ne=Te.current;if(!ne)return;const Ce=ne.getBoundingClientRect(),{width:Ze,height:xt,offsetTop:ht,offsetLeft:xn}=Yt(),Qt=16,an=16,dn=4,In=Ze<=768,Vn=Math.min(In?xt*.6:xt*.5,320),Wn=In?Math.min(Ze-Qt*2,360):Math.max(Ce.width,280),Cn=Math.min(Wn,Math.max(Ze-Qt*2,240)),Kn=Ce.top-ht,zn=Ce.bottom-ht,fs=Ce.left-xn,vn=xt-zn,Fn=Kn,ls=Math.max(vn-an-dn,200),Ss=Math.max(Fn-an-dn,200),ts=vn<Vn&&Fn>vn,rn=Math.max(Math.min(ts?Ss:ls,Vn),200),On=Math.min(Math.max(fs,Qt),Ze-Qt-Cn)+xn,zs=ts?Math.max(an+ht,Kn-rn-dn+ht):Math.min(zn+dn+ht,xt+ht-an-rn);We({top:zs,left:On,width:Cn,maxHeight:rn})},[Yt]),et=a.useCallback(()=>{const ne=ye.current?.querySelector("button");if(!ne)return;const Ce=ne.getBoundingClientRect(),{width:Ze,height:xt,offsetTop:ht,offsetLeft:xn}=Yt(),Qt=16,an=16,dn=4,In=Ze<=768,Vn=Math.min(In?xt*.6:xt*.5,320),Wn=In?Math.min(Ze-Qt*2,280):Math.max(Ce.width,240),Cn=Math.min(Wn,Math.max(Ze-Qt*2,200)),Kn=Ce.top-ht,zn=Ce.bottom-ht,fs=Ce.left-xn,vn=xt-zn,Fn=Kn,ls=Math.max(vn-an-dn,160),Ss=Math.max(Fn-an-dn,160),ts=vn<Vn&&Fn>vn,rn=Math.max(Math.min(ts?Ss:ls,Vn),160),On=Math.min(Math.max(fs,Qt),Ze-Qt-Cn)+xn,zs=ts?Math.max(an+ht,Kn-rn-dn+ht):Math.min(zn+dn+ht,xt+ht-an-rn);_e({top:zs,left:On,width:Cn,maxHeight:rn})},[Yt]),dt=a.useCallback(()=>{const ne=Ae.current?.querySelector("button");if(!ne)return;const Ce=ne.getBoundingClientRect(),{width:Ze,height:xt,offsetTop:ht,offsetLeft:xn}=Yt(),Qt=16,an=16,dn=4,In=Ze<=768,Vn=Math.min(In?xt*.6:xt*.5,320),Wn=In?Math.min(Ze-Qt*2,280):Math.max(Ce.width,240),Cn=Math.min(Wn,Math.max(Ze-Qt*2,200)),Kn=Ce.top-ht,zn=Ce.bottom-ht,fs=Ce.left-xn,vn=xt-zn,Fn=Kn,ls=Math.max(vn-an-dn,160),Ss=Math.max(Fn-an-dn,160),ts=vn<Vn&&Fn>vn,rn=Math.max(Math.min(ts?Ss:ls,Vn),160),On=Math.min(Math.max(fs,Qt),Ze-Qt-Cn)+xn,zs=ts?Math.max(an+ht,Kn-rn-dn+ht):Math.min(zn+dn+ht,xt+ht-an-rn);tt({top:zs,left:On,width:Cn,maxHeight:rn})},[Yt]);a.useEffect(()=>{if(!Se)return;const ne=()=>Q();window.addEventListener("resize",ne),window.addEventListener("scroll",ne,!0);const Ce=window.visualViewport;return Ce&&(Ce.addEventListener("resize",ne),Ce.addEventListener("scroll",ne)),()=>{window.removeEventListener("resize",ne),window.removeEventListener("scroll",ne,!0),Ce&&(Ce.removeEventListener("resize",ne),Ce.removeEventListener("scroll",ne))}},[Se,Q]),a.useEffect(()=>{if(!Wt)return;const ne=()=>ze();window.addEventListener("resize",ne),window.addEventListener("scroll",ne,!0);const Ce=window.visualViewport;return Ce&&(Ce.addEventListener("resize",ne),Ce.addEventListener("scroll",ne)),()=>{window.removeEventListener("resize",ne),window.removeEventListener("scroll",ne,!0),Ce&&(Ce.removeEventListener("resize",ne),Ce.removeEventListener("scroll",ne))}},[Wt,ze]),a.useEffect(()=>{if(!V)return;const ne=()=>Ye();window.addEventListener("resize",ne),window.addEventListener("scroll",ne,!0);const Ce=window.visualViewport;return Ce&&(Ce.addEventListener("resize",ne),Ce.addEventListener("scroll",ne)),()=>{window.removeEventListener("resize",ne),window.removeEventListener("scroll",ne,!0),Ce&&(Ce.removeEventListener("resize",ne),Ce.removeEventListener("scroll",ne))}},[V,Ye]),a.useEffect(()=>{if(!w)return;const ne=()=>et();window.addEventListener("resize",ne),window.addEventListener("scroll",ne,!0);const Ce=window.visualViewport;return Ce&&(Ce.addEventListener("resize",ne),Ce.addEventListener("scroll",ne)),()=>{window.removeEventListener("resize",ne),window.removeEventListener("scroll",ne,!0),Ce&&(Ce.removeEventListener("resize",ne),Ce.removeEventListener("scroll",ne))}},[w,et]),a.useEffect(()=>{if(!G)return;const ne=()=>dt();window.addEventListener("resize",ne),window.addEventListener("scroll",ne,!0);const Ce=window.visualViewport;return Ce&&(Ce.addEventListener("resize",ne),Ce.addEventListener("scroll",ne)),()=>{window.removeEventListener("resize",ne),window.removeEventListener("scroll",ne,!0),Ce&&(Ce.removeEventListener("resize",ne),Ce.removeEventListener("scroll",ne))}},[G,dt]);const St=a.useCallback(ne=>{const Ce=bl(ne);Ke(Ce.provider),Pe(Ce.modelId)},[]),It=a.useCallback(ne=>{const Ce=bl(ne);de(Ce.provider),ie(Ce.modelId)},[]),kn=a.useCallback(ne=>{const Ce=bl(ne);De(Ce.provider),Qe(Ce.modelId)},[]),sn=a.useCallback(async ne=>{if(m){m(ne);return}const Ce=Ge,xt=Ce.includes(ne)?Ce.filter(ht=>ht!==ne):[ne,...Ce];ct(xt);try{await ln({favoriteProviders:xt,favoriteModels:vt})}catch{ct(Ce)}},[Ge,vt,m]),jt=a.useCallback(async ne=>{if(h){h(ne);return}const Ce=vt,xt=Ce.includes(ne)?Ce.filter(ht=>ht!==ne):[ne,...Ce];bt(xt);try{await ln({favoriteProviders:Ge,favoriteModels:xt})}catch{bt(Ce)}},[vt,Ge,h]),os=a.useCallback(()=>{const ne=g.trim();if(!ne){n("Enter a description first","error");return}r?.(ne),Rn()},[g,r,n,Rn]),ws=a.useCallback(()=>{const ne=g.trim();if(!ne){n("Enter a description first","error");return}o?.(ne),Rn()},[g,o,n,Rn]),Ns=a.useCallback(()=>{Tn()},[Tn]),$s=a.useCallback(async ne=>{const Ce=g.trim();if(!(!Ce||Nt)){Ot(!1),Mt(!0);try{const Ze=await op(Ce,ne,l);p(Ze),n("Description refined with AI","success"),j.current&&(j.current.style.height="auto",j.current.style.height=`${Math.min(j.current.scrollHeight,200)}px`)}catch(Ze){const xt=lp(Ze);n(xt,"error")}finally{Mt(!1)}}},[g,Nt,n,l]),ii=(ne,Ce)=>ne.length>Ce?ne.slice(0,Ce)+"…":ne,Ds=a.useCallback(async()=>{if(i){ee(i),ve(null),J(!1);return}J(!0),ve(null);try{const ne=await ms();ee(ne.models),u||ct(ne.favoriteProviders),d||bt(ne.favoriteModels)}catch(ne){ve(je(ne)||"Failed to load models")}finally{J(!1)}},[i,u,d]),Ls=a.useCallback(async()=>{if(X.length>0&&I===l){q(!0),et();return}le(!0);try{const ne=await Ma(void 0,l);_(ne),T(l),q(!0),et()}catch(ne){const Ce=je(ne);n(Ce?`Failed to load agents: ${Ce}`:"Failed to load agents","error"),q(!1)}finally{le(!1)}},[X.length,I,l,n,et]),gi=(U?X.find(ne=>ne.id===U):void 0)?.name??U,ut=At?zt.find(ne=>ne.id===At):void 0,bn=y,ps=a.useCallback(()=>{S(ne=>{const Ce=!ne;return b(Ce),Ce})},[]);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:j,className:`quick-entry-input ${v?"quick-entry-input--expanded":""}`,placeholder:f?"Creating...":"Add a task...",value:g,onChange:ne=>p(ne.target.value),onKeyDown:Pn,onPaste:at,onFocus:es,onBlur:Nn,disabled:f||N,"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:ps,"aria-expanded":y,"aria-controls":"quick-entry-controls","data-testid":"quick-entry-toggle",title:y?"Collapse":"Expand",children:y?t.jsx(ui,{size:14}):t.jsx(Vt,{size:14})})]})}),t.jsxs("div",{id:"quick-entry-controls",className:"quick-entry-controls",hidden:!bn,"aria-hidden":!bn,children:[bn&&!f&&t.jsxs("div",{className:"quick-entry-actions","data-testid":"quick-entry-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:os,onMouseDown:ne=>ne.preventDefault(),disabled:!g.trim(),"data-testid":"plan-button",title:"Open planning mode with current description",children:[t.jsx(ei,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Plan"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:ws,onMouseDown:ne=>ne.preventDefault(),disabled:!g.trim(),"data-testid":"subtask-button",title:"Break down into AI-generated subtasks",children:[t.jsx($o,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Subtask"]}),t.jsxs("div",{className:"refine-trigger-wrap",ref:Ct,children:[t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${Nt?"refine-button--loading":""}`,onClick:()=>{Ot(ne=>{const Ce=!ne;return Ce?ze():H(null),Ce})},disabled:!g.trim()||Nt,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(Xn,{size:12,style:{verticalAlign:"middle"}}),Nt?"Refining...":"Refine"]}),Wt&&Re&&Et&&da.createPortal(t.jsxs("div",{ref:Gt,className:"refine-menu refine-menu--portal",onMouseDown:ne=>ne.preventDefault(),style:{position:"fixed",top:`${Et.top}px`,left:`${Et.left}px`},children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>$s("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:()=>$s("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:()=>$s("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:()=>$s("simplify"),"data-testid":"refine-simplify",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Simplify"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Simplify and make more concise"})]})]}),Re)]}),t.jsx("div",{className:"dep-trigger-wrap",children:t.jsxs("button",{ref:Te,type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-deps",onClick:()=>{$(ne=>{const Ce=!ne;return Ce?(F(!1),oe(null),se(null),q(!1),_e(null),me(!1),tt(null),Ye()):We(null),Ce})},children:[t.jsx(ga,{size:12,style:{verticalAlign:"middle"}}),P.length>0?`${P.length} deps`:"Deps"]})}),V&&Re&&Me&&(()=>{const ne=E.toLowerCase(),Ce=(ne?s.filter(Ze=>Ze.id.toLowerCase().includes(ne)||Ze.title&&Ze.title.toLowerCase().includes(ne)||Ze.description&&Ze.description.toLowerCase().includes(ne)):[...s]).sort((Ze,xt)=>{const ht=xt.createdAt.localeCompare(Ze.createdAt);if(ht!==0)return ht;const xn=parseInt(Ze.id.slice(Ze.id.lastIndexOf("-")+1),10)||0;return(parseInt(xt.id.slice(xt.id.lastIndexOf("-")+1),10)||0)-xn});return da.createPortal(t.jsxs("div",{ref:he,className:"dep-dropdown dep-dropdown--portal",onMouseDown:Ze=>Ze.preventDefault(),style:{position:"fixed",top:`${Me.top}px`,left:`${Me.left}px`,width:`${Me.width}px`,maxHeight:Me.maxHeight?`${Me.maxHeight}px`:void 0,overflowY:Me.maxHeight?"auto":void 0},children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:E,onChange:Ze=>D(Ze.target.value),onClick:Ze=>Ze.stopPropagation()}),Ce.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No existing tasks"}):Ce.map(Ze=>t.jsxs("div",{className:`dep-dropdown-item${P.includes(Ze.id)?" selected":""}`,onMouseDown:xt=>xt.preventDefault(),onClick:()=>Sn(Ze.id),children:[t.jsx("span",{className:"dep-dropdown-id",children:Ze.id}),t.jsx("span",{className:"dep-dropdown-title",children:ii(Ze.title||Ze.description||Ze.id,60)})]},Ze.id))]}),Re)})(),t.jsxs("button",{type:"button",className:"btn btn-sm","data-testid":"quick-entry-attach",onClick:()=>R.current?.click(),children:[t.jsx(yb,{size:12,style:{verticalAlign:"middle"}}),C.length>0?`Attach (${C.length})`:"Attach"]}),t.jsxs("button",{ref:Ve,type:"button",className:"btn btn-sm","data-testid":"quick-entry-models",onClick:()=>{$(!1),q(!1),_e(null),me(!1),tt(null),se(null),F(!0),Q()},children:[t.jsx(ho,{size:12,style:{verticalAlign:"middle"}}),nn]}),t.jsx("div",{className:"node-trigger-wrap",ref:Ae,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-node-button",onClick:()=>{$(!1),q(!1),_e(null),F(!1),oe(null),se(null),me(ne=>{const Ce=!ne;return Ce?dt():tt(null),Ce})},children:[t.jsx(fr,{size:12,style:{verticalAlign:"middle"}}),` ${ut?.name??"Node"}`,ut&&t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(Vi,{status:ut.status,showLabel:!0})})]})}),G&&Re&&Fe&&da.createPortal(t.jsxs("div",{ref:Le,className:"dep-dropdown node-picker-dropdown node-picker-dropdown--portal",onMouseDown:ne=>ne.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 execution node"}),t.jsx("div",{className:`dep-dropdown-item node-picker-item${At==null?" selected":""}`,onMouseDown:ne=>ne.preventDefault(),onClick:()=>{qt(void 0),me(!1),tt(null)},children:t.jsx("span",{className:"node-picker-item-name",children:"Project default / local"})}),zt.map(ne=>t.jsxs("div",{className:`dep-dropdown-item node-picker-item${At===ne.id?" selected":""}`,onMouseDown:Ce=>Ce.preventDefault(),onClick:()=>{qt(ne.id),me(!1),tt(null)},children:[t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(Vi,{status:ne.status})}),t.jsx("span",{className:"node-picker-item-name",children:ne.name}),t.jsx("span",{className:"node-picker-item-status",children:_N(ne.status)})]},ne.id))]}),Re),t.jsx("div",{className:"agent-trigger-wrap",ref:ye,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{w?(q(!1),_e(null)):(me(!1),tt(null),Ls())},"data-testid":"quick-entry-agent-button",children:[t.jsx(yn,{size:12,style:{verticalAlign:"middle"}}),gi?` ${gi}`:" Agent"]})}),w&&Re&&pe&&da.createPortal(t.jsxs("div",{ref:te,className:"dep-dropdown agent-picker-dropdown agent-picker-dropdown--portal",onMouseDown:ne=>ne.preventDefault(),style:{position:"fixed",top:`${pe.top}px`,left:`${pe.left}px`,width:`${pe.width}px`,maxHeight:pe.maxHeight?`${pe.maxHeight}px`:void 0,overflowY:pe.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),ue&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!ue&&X.filter(ne=>ne.state!=="terminated").map(ne=>t.jsxs("div",{className:`dep-dropdown-item${U===ne.id?" selected":""}`,onMouseDown:Ce=>Ce.preventDefault(),onClick:()=>{Y(ne.id===U?null:ne.id),q(!1),_e(null)},children:[t.jsx(yn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:ne.role}),t.jsx("span",{className:"dep-dropdown-title",children:ne.name})]},ne.id)),!ue&&X.filter(ne=>ne.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),U&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:ne=>ne.preventDefault(),onClick:()=>{Y(null),q(!1),_e(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]}),Re),t.jsx("button",{type:"button",className:`btn btn-sm ${Ft?"btn-primary":""}`,onClick:()=>wt(ne=>!ne),onMouseDown:ne=>ne.preventDefault(),"aria-pressed":Ft,"data-testid":"quick-entry-fast-toggle",title:"Toggle fast execution mode",children:"Fast"}),t.jsxs("button",{type:"button",className:"btn btn-task-create btn-sm",onClick:Ns,onMouseDown:ne=>ne.preventDefault(),disabled:!g.trim()||f,"data-testid":"quick-entry-save",title:"Create task",children:[t.jsx(Qh,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Save"]})]}),C.length>0&&t.jsx("div",{className:"inline-create-previews",children:C.map((ne,Ce)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:ne.previewUrl,alt:ne.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>gn(Ce),disabled:f,title:"Remove image","data-testid":`quick-entry-preview-remove-${Ce}`,children:"×"})]},ne.previewUrl))}),Se&&Re&&Ne&&da.createPortal(t.jsx("div",{ref:ae,className:"model-nested-menu model-nested-menu--portal",onMouseDown:ne=>ne.preventDefault(),"data-testid":"model-nested-menu",style:{position:"fixed",top:`${Ne.top}px`,left:`${Ne.left}px`,width:`${Ne.width}px`,maxHeight:Ne.maxHeight?`${Ne.maxHeight}px`:void 0,overflowY:Ne.maxHeight?"auto":void 0},children:ge===null?t.jsxs("div",{className:"model-menu-items",children:[t.jsxs("button",{type:"button",className:`model-menu-item ${Tt?"model-menu-item--active":""}`,onClick:()=>se("plan"),"data-testid":"model-menu-plan",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(ei,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Plan"]}),t.jsx("span",{className:"model-menu-item-value",children:Tt?Ln(Je,it):"Using default"}),t.jsx(pn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${yt?"model-menu-item--active":""}`,onClick:()=>se("executor"),"data-testid":"model-menu-executor",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(Xn,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Executor"]}),t.jsx("span",{className:"model-menu-item-value",children:yt?Ln(fe,xe):"Using default"}),t.jsx(pn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${Pt?"model-menu-item--active":""}`,onClick:()=>se("validator"),"data-testid":"model-menu-validator",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(ho,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Reviewer"]}),t.jsx("span",{className:"model-menu-item-value",children:Pt?Ln(Ee,qe):"Using default"}),t.jsx(pn,{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:()=>se(null),"data-testid":"model-submenu-back",children:[t.jsx(Vt,{size:12,style:{transform:"rotate(90deg)",marginRight:4}}),"Back"]}),t.jsxs("div",{className:"model-submenu-header",children:[ge==="plan"&&"Plan Model",ge==="executor"&&"Executor Model",ge==="validator"&&"Reviewer Model"]}),t.jsx(Hn,{models:Xe,value:ge==="plan"?nt:ge==="executor"?W:Ie,onChange:ge==="plan"?St:ge==="executor"?It:kn,placeholder:"Using default",disabled:ot,id:`model-${ge}-select`,label:`${ge} model`,favoriteProviders:be,onToggleFavorite:sn,favoriteModels:re,onToggleModelFavorite:jt}),ce&&t.jsxs("div",{className:"model-submenu-error",children:[t.jsx("span",{children:ce}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:Ds,children:"Retry"})]})]})}),Re)]}),t.jsx("input",{ref:R,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:ne=>{ke(ne.target.files),ne.currentTarget.value=""},"data-testid":"quick-entry-file-input"}),t.jsx("div",{className:"quick-entry-hint",children:"Enter to create · Esc to cancel"})]})}function MN(e){return id(e)||e}function AN(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 RN(e,n,s){const i=e.filter(f=>f.worktree),r=e.filter(f=>!f.worktree),o=new Map;for(const f of i){const x=f.worktree,v=o.get(x)||[];v.push(f),o.set(x,v)}const l=new Map(n.map(f=>[f.id,f])),u=n.filter(f=>f.column==="todo").filter(f=>!f.paused&&(f.dependencies||[]).every(x=>{const v=l.get(x);return v&&(v.column==="done"||v.column==="in-review"||v.column==="archived")})),m=AN(u).map(f=>l.get(f)).filter(f=>f!==void 0&&u.includes(f)),h=[],g=Array.from(o.keys());for(const f of g)h.push({label:MN(f),activeTasks:o.get(f),queuedTasks:[]});r.length>0&&h.push({label:"Unassigned",activeTasks:r,queuedTasks:[]});const p=m.slice(0,s);return p.length>0&&h.push({label:"Up Next",activeTasks:[],queuedTasks:p}),h}const _u=100,vl=50,Mu=25;function TN({column:e,tasks:n,projectId:s,maxConcurrent:i,onMoveTask:r,onPauseTask:o,onOpenDetail:l,addToast:c,onQuickCreate:u,onNewTask:d,autoMerge:m,onToggleAutoMerge:h,globalPaused:g,onUpdateTask:p,onRetryTask:f,onArchiveTask:x,onUnarchiveTask:v,onDeleteTask:b,onArchiveAllDone:y,collapsed:S,onToggleCollapse:j,allTasks:R,availableModels:k,onPlanningMode:M,onSubtaskBreakdown:C,onOpenDetailWithTab:L,favoriteProviders:A,favoriteModels:P,onToggleFavorite:O,onToggleModelFavorite:V,isSearchActive:$,taskStuckTimeoutMs:E,onOpenMission:D,lastFetchTimeMs:U,workflowStepNameLookup:Y}){const[X,_]=a.useState(!1),[I,T]=a.useState(vl),[w,q]=a.useState(!1),[G,me]=a.useState(!1),[ue,le]=a.useState(!1),[Se,F]=a.useState(!1),ge=a.useRef(null),se=kw(n.length),{confirm:fe}=Hs();a.useEffect(()=>{if(!w)return;function _e(tt){ge.current?.contains(tt.target)||q(!1)}function Fe(tt){tt.key==="Escape"&&q(!1)}return document.addEventListener("mousedown",_e),document.addEventListener("keydown",Fe),()=>{document.removeEventListener("mousedown",_e),document.removeEventListener("keydown",Fe)}},[w]);const de=e==="archived",xe=de&&S,ie=!de&&!$&&e!=="in-progress"&&n.length>_u;a.useEffect(()=>{T(_e=>e==="in-progress"||de||n.length<=_u?vl:Math.min(Math.max(_e,vl),n.length))},[e,de,n.length]);const Ee=a.useCallback(_e=>{de||(_e.preventDefault(),_e.dataTransfer.dropEffect="move",_(!0))},[de]),De=a.useCallback(_e=>{_e.currentTarget.contains(_e.relatedTarget)||_(!1)},[]),qe=a.useCallback(async _e=>{_e.preventDefault(),_(!1);const Fe=_e.dataTransfer.getData("text/plain");if(!Fe)return;const tt=n.find(Ne=>Ne.id===Fe);if(!(tt&&tt.column===e))try{await r(Fe,e)}catch(Ne){c(je(Ne),"error")}},[e,r,c,n]),Qe=a.useMemo(()=>e!=="in-progress"?[]:RN(n,n,i),[e,n,i]),Je=a.useMemo(()=>ie?n.slice(0,I):n,[ie,n,I]),Ke=Math.max(0,n.length-Je.length),it=a.useCallback(()=>{T(_e=>Math.min(_e+Mu,n.length))},[n.length]),Pe=a.useCallback(async()=>{if(q(!1),!(n.length===0||!await fe({title:"Replan All Tasks",message:`Move all ${n.length} todo task${n.length===1?"":"s"} back to planning to be replanned?`}))){me(!0);try{const Fe=await Promise.allSettled(n.map(oe=>r(oe.id,"triage"))),tt=Fe.filter(oe=>oe.status==="rejected").length,Ne=Fe.length-tt;tt===0?c(`Moved ${Ne} task${Ne===1?"":"s"} to planning for replanning`,"success"):c(`Moved ${Ne} of ${Fe.length} tasks; ${tt} failed`,"error")}finally{me(!1)}}},[n,r,c,fe]),Ve=a.useMemo(()=>n.filter(_e=>!_e.paused),[n]),ae=Ve.length,ye=e==="todo"||e==="in-progress"||e==="in-review",te=G||ue||Se,Ae=a.useCallback(async()=>{if(!(!o||(q(!1),ae===0)||!await fe({title:"Stop All Tasks",message:`Stop all ${ae} ${An[e].toLowerCase()} task${ae===1?"":"s"}?`,danger:!0}))){le(!0);try{const Fe=await Promise.allSettled(Ve.map(oe=>o(oe.id))),tt=Fe.filter(oe=>oe.status==="rejected").length,Ne=Fe.length-tt;tt===0?c(`Stopped ${Ne} task${Ne===1?"":"s"}`,"success"):c(`Stopped ${Ne} of ${Fe.length} tasks; ${tt} failed`,"error")}finally{le(!1)}}},[o,ae,e,Ve,c,fe]),Le=a.useCallback(async()=>{if(q(!1),!(n.length===0||!await fe({title:"Move All to Todo",message:`Move all ${n.length} ${An[e].toLowerCase()} task${n.length===1?"":"s"} to Todo?`}))){F(!0);try{const Fe=await Promise.allSettled(n.map(oe=>r(oe.id,"todo"))),tt=Fe.filter(oe=>oe.status==="rejected").length,Ne=Fe.length-tt;tt===0?c(`Moved ${Ne} task${Ne===1?"":"s"} to Todo`,"success"):c(`Moved ${Ne} of ${Fe.length} tasks to Todo; ${tt} failed`,"error")}finally{F(!1)}}},[n,e,r,c,fe]),pe=a.useCallback(async()=>{if(!(!y||n.length===0||!await fe({title:"Archive All Done",message:`Archive all ${n.length} done tasks?`,danger:!0})))try{const Fe=await y();c(`Archived ${Fe.length} tasks`,"success")}catch(Fe){c(je(Fe)||"Failed to archive tasks","error")}},[y,n.length,c,fe]);return t.jsxs("div",{className:`column${X?" drag-over":""}${de?" column-archived":""}${xe?" column-collapsed":""}`,"data-column":e,onDragOver:Ee,onDragLeave:De,onDrop:qe,children:[t.jsxs("div",{className:"column-header",children:[t.jsx("div",{className:`column-dot dot-${e}`}),t.jsx("h2",{children:An[e]}),t.jsx("span",{className:`column-count${se?" count-flash":""}`,children:n.length}),e==="in-review"&&h&&t.jsxs("label",{className:"auto-merge-toggle",title:m?"Auto-merge enabled":"Auto-merge disabled",children:[t.jsx("input",{type:"checkbox",checked:!!m,onChange:h}),t.jsx("span",{className:"toggle-slider"}),t.jsx("span",{className:"toggle-label",children:"Auto-merge"})]}),d&&t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:d,children:"+ New Task"}),e==="done"&&y&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:pe,disabled:n.length===0,title:"Archive all done tasks","aria-label":"Archive all done tasks",children:t.jsx(Ro,{size:16})}),de&&j&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:j,title:S?"Expand archived tasks":"Collapse archived tasks","aria-label":S?"Expand archived tasks":"Collapse archived tasks",children:S?t.jsx(Vt,{size:16}):t.jsx(ui,{size:16})}),ye&&t.jsxs("div",{className:"column-menu",ref:ge,children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>q(_e=>!_e),"aria-haspopup":"menu","aria-expanded":w,"aria-label":`${An[e]} column actions`,title:"Column actions",disabled:te,children:t.jsx(ux,{size:16})}),w&&t.jsxs("div",{className:"column-menu-popover",role:"menu",children:[e==="todo"&&t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Pe(),disabled:n.length===0||G,children:["Replan All",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Planning"]})]}),(e==="in-progress"||e==="in-review")&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Ae(),disabled:ae===0||ue||!o,children:["Stop All",t.jsx("span",{className:"column-menu-item-hint",children:n.length===0?"No tasks in this column":ae===0?"All tasks are already paused":`Pause ${ae} active task${ae===1?"":"s"}`})]}),t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Le(),disabled:n.length===0||Se,children:["Move All to Todo",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Todo"]})]})]})]})]})]}),!xe&&t.jsx("p",{className:"column-desc",children:yw[e]}),!xe&&t.jsxs("div",{className:"column-body",children:[e==="triage"&&u&&t.jsx(Ap,{onCreate:u,addToast:c,tasks:R??[],availableModels:k,onPlanningMode:M,onSubtaskBreakdown:C,projectId:s,autoExpand:!1,favoriteProviders:A,favoriteModels:P,onToggleFavorite:O,onToggleModelFavorite:V}),e==="in-progress"?Qe.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):Qe.map(_e=>t.jsx(Mp,{label:_e.label,activeTasks:_e.activeTasks,queuedTasks:_e.queuedTasks,projectId:s,onOpenDetail:l,addToast:c,globalPaused:g,onUpdateTask:p,onRetryTask:f,onOpenDetailWithTab:L,taskStuckTimeoutMs:E,onOpenMission:D,lastFetchTimeMs:U,workflowStepNameLookup:Y},_e.label)):n.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):t.jsxs(t.Fragment,{children:[Je.map(_e=>t.jsx(ko,{task:_e,projectId:s,onOpenDetail:l,addToast:c,globalPaused:g,onUpdateTask:p,onRetryTask:f,onArchiveTask:x,onUnarchiveTask:v,onDeleteTask:b,onOpenDetailWithTab:L,taskStuckTimeoutMs:E,onOpenMission:D,onMoveTask:r,lastFetchTimeMs:U,workflowStepNameLookup:Y},_e.id)),ie&&Ke>0&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:it,children:["Load ",Math.min(Mu,Ke)," more (",Ke," remaining)"]})]}),t.jsx(Uo,{slotId:"board-column-footer",projectId:s})]})]})}const Rp=a.memo(TN);Rp.displayName="Column";function PN(e){return[...e].sort((n,s)=>n.columnMovedAt&&s.columnMovedAt?s.columnMovedAt.localeCompare(n.columnMovedAt):n.columnMovedAt&&!s.columnMovedAt?-1:!n.columnMovedAt&&s.columnMovedAt?1:n.createdAt.localeCompare(s.createdAt))}function IN(e,n){return e.length!==n.length?!1:e.every((s,i)=>s===n[i])}const Au=new Map;function $N(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 DN({tasks:e,projectId:n,maxConcurrent:s,onMoveTask:i,onPauseTask:r,onOpenDetail:o,addToast:l,onQuickCreate:c,onNewTask:u,autoMerge:d,onToggleAutoMerge:m,globalPaused:h,onUpdateTask:g,onRetryTask:p,onArchiveTask:f,onUnarchiveTask:x,onDeleteTask:v,onArchiveAllDone:b,onLoadArchivedTasks:y,searchQuery:S="",availableModels:j,onPlanningMode:R,onSubtaskBreakdown:k,onOpenDetailWithTab:M,favoriteProviders:C,favoriteModels:L,onToggleFavorite:A,onToggleModelFavorite:P,taskStuckTimeoutMs:O,onOpenMission:V,lastFetchTimeMs:$}){const[E,D]=a.useState(!0),U=a.useRef(!1),{fetchBatch:Y}=Ow(n),X=a.useRef(null),[_,I]=a.useState(Au),T=S.trim()!=="",w=a.useRef({triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]}),q=a.useCallback(()=>{D(ue=>{const le=!ue;return!le&&!U.current&&y&&(U.current=!0,y()),le})},[y]),G=a.useMemo(()=>{const ue=Object.fromEntries(Oi.map(F=>[F,[]]));for(const F of e)ue[F.column].push(F);const le=w.current,Se={};for(const F of Oi){const ge=PN(ue[F]);Se[F]=IN(le[F],ge)?le[F]:ge}return w.current=Se,Se},[e]);a.useEffect(()=>{let ue=!1;return Oo(n).then(le=>{if(ue)return;const Se=new Map(le.map(F=>[F.id,F.name]));I(F=>$N(F,Se)?F:Se)}).catch(()=>{ue||I(le=>le.size===0?le:Au)}),()=>{ue=!0}},[n]);const me=a.useMemo(()=>e.filter(ue=>ue.prInfo||ue.issueInfo).map(ue=>ue.id),[e]);return a.useEffect(()=>{if(me.length!==0)return X.current&&clearTimeout(X.current),X.current=setTimeout(()=>{const ue=[];for(let le=0;le<me.length;le+=50)ue.push(me.slice(le,le+50));ue.forEach(le=>{Y(le)})},500),()=>{X.current&&clearTimeout(X.current)}},[me,Y]),t.jsx(t.Fragment,{children:t.jsx("main",{className:"board",id:"board",children:Oi.map(ue=>t.jsx(Rp,{column:ue,tasks:G[ue],projectId:n,maxConcurrent:s,onMoveTask:i,onPauseTask:r,onOpenDetail:o,addToast:l,globalPaused:h,onUpdateTask:g,onRetryTask:p,onArchiveTask:f,onUnarchiveTask:x,onDeleteTask:v,allTasks:e,availableModels:j,onOpenDetailWithTab:M,favoriteProviders:C,favoriteModels:L,onToggleFavorite:A,onToggleModelFavorite:P,isSearchActive:T,taskStuckTimeoutMs:O,onOpenMission:V,lastFetchTimeMs:$,workflowStepNameLookup:_,...ue==="triage"?{onQuickCreate:c,onNewTask:u,onPlanningMode:R,onSubtaskBreakdown:k}:{},...ue==="in-review"?{autoMerge:d,onToggleAutoMerge:m}:{},...ue==="done"?{onArchiveAllDone:b}:{},...ue==="archived"?{collapsed:E,onToggleCollapse:q}:{}},ue))})})}const Ba={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-secondary)"},Ru=new Set(["planning","researching","executing","finalizing","merging"]),Rc=["id","title","status","column","dependencies","progress"];function LN(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function zN(e){return e==="online"?"●":e==="connecting"?"◐":e==="error"?"✕":"○"}function Tu(e){try{const n=qn("kb-dashboard-list-columns",e);if(n){const i=JSON.parse(n).filter(r=>Rc.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set(Rc)}function Pu(e){try{const n=qn("kb-dashboard-hide-done",e);if(n!==null)return n==="true"}catch{}return!1}function Iu(e){try{const n=qn("kb-dashboard-list-collapsed",e);if(n){const i=JSON.parse(n).filter(r=>Oi.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set}function $u(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 FN(e){return e.status==="executing"||e.column==="in-progress"}function Du(e){const n=Ep(e);return n.total===0||!FN(e)?{label:"-",percent:0,hasProgress:!1}:{label:`${n.completed}/${n.total}`,percent:n.completed/n.total*100,hasProgress:!0}}function ON({tasks:e,onMoveTask:n,onOpenDetail:s,addToast:i,globalPaused:r,onNewTask:o,onQuickCreate:l,availableModels:c,favoriteProviders:u=[],favoriteModels:d=[],onToggleFavorite:m,onToggleModelFavorite:h,onPlanningMode:g,onSubtaskBreakdown:p,onTasksUpdated:f,projectId:x,projectName:v,taskStuckTimeoutMs:b,searchQuery:y="",lastFetchTimeMs:S}){const[j,R]=a.useState("id"),[k,M]=a.useState("desc"),[C,L]=a.useState(null),[A,P]=a.useState(null),[O,V]=a.useState(null),E=Tr()==="mobile",[D,U]=a.useState(()=>Tu(x)),[Y,X]=a.useState(()=>Pu(x)),[_,I]=a.useState(()=>Iu(x));a.useEffect(()=>{typeof window<"u"&&ds("kb-dashboard-list-columns",JSON.stringify([...D]),x)},[x,D]),a.useEffect(()=>{typeof window<"u"&&ds("kb-dashboard-hide-done",Y.toString(),x)},[Y,x]),a.useEffect(()=>{typeof window<"u"&&ds("kb-dashboard-list-collapsed",JSON.stringify([..._]),x)},[_,x]);const[T,w]=a.useState(!1),q=a.useRef(null),[G,me]=a.useState(()=>$u(x));a.useEffect(()=>{U(Tu(x)),X(Pu(x)),I(Iu(x)),me($u(x))},[x]),a.useEffect(()=>{typeof window<"u"&&ds("kb-dashboard-selected-tasks",JSON.stringify([...G]),x)},[x,G]);const ue=a.useCallback(J=>{me(ce=>{const ve=new Set(ce);return ve.has(J)?ve.delete(J):ve.add(J),ve})},[]),le=a.useCallback(()=>{me(new Set)},[]),Se=a.useCallback(J=>{U(ce=>{const ve=new Set(ce);return ve.has(J)?ve.size>1&&ve.delete(J):ve.add(J),ve})},[]);a.useEffect(()=>{if(!T)return;const J=ve=>{q.current&&!q.current.contains(ve.target)&&w(!1)},ce=ve=>{ve.key==="Escape"&&w(!1)};return document.addEventListener("mousedown",J),document.addEventListener("keydown",ce),()=>{document.removeEventListener("mousedown",J),document.removeEventListener("keydown",ce)}},[T]);const F={id:"ID",title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},ge=a.useCallback(J=>{j===J?M(ce=>ce==="asc"?"desc":"asc"):(R(J),M("asc"))},[j]),se=a.useCallback(J=>{V(ce=>ce===J?null:J)},[]),fe=a.useCallback(J=>{I(ce=>{const ve=new Set(ce);return ve.has(J)?ve.delete(J):ve.add(J),ve})},[]),de=a.useCallback(()=>{V(null)},[]),xe=a.useMemo(()=>{let J=y?e.filter(ee=>ee.id.toLowerCase().includes(y.toLowerCase())||ee.title&&ee.title.toLowerCase().includes(y.toLowerCase())||ee.description.toLowerCase().includes(y.toLowerCase())):[...e];Y&&!O&&(J=J.filter(ee=>ee.column!=="done"&&ee.column!=="archived"));const ve=[...O?J.filter(ee=>ee.column===O):J].sort((ee,Ge)=>{let ct=0;switch(j){case"id":ct=ee.id.localeCompare(Ge.id);break;case"title":ct=(ee.title||ee.description).localeCompare(Ge.title||Ge.description);break;case"status":ct=(ee.status||"").localeCompare(Ge.status||"");break;case"column":ct=ee.column.localeCompare(Ge.column);break}return k==="asc"?ct:-ct}),Xe={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};return ve.forEach(ee=>Xe[ee.column].push(ee)),Xe},[e,y,j,k,Y,O]),ie=a.useMemo(()=>Object.values(xe).reduce((J,ce)=>J+ce.length,0),[xe]),Ee=a.useMemo(()=>e.filter(J=>J.column==="done"||J.column==="archived").length,[e]),De=a.useMemo(()=>Y?Ee:0,[Y,Ee]),qe=a.useCallback(()=>{const J=Object.values(xe).flat().filter(ce=>ce.column!=="archived").map(ce=>ce.id);me(ce=>{if(J.every(Xe=>ce.has(Xe))){const Xe=new Set(ce);return J.forEach(ee=>Xe.delete(ee)),Xe}else return new Set([...ce,...J])})},[xe]),Qe=a.useMemo(()=>{const J=Object.values(xe).flat().filter(ce=>ce.column!=="archived");return J.length===0?!1:J.every(ce=>G.has(ce.id))},[xe,G]),Je=a.useMemo(()=>{const J=Object.values(xe).flat().filter(ve=>ve.column!=="archived");if(J.length===0)return!1;const ce=J.filter(ve=>G.has(ve.id)).length;return ce>0&&ce<J.length},[xe,G]),[Ke,it]=a.useState("__no_change__"),[Pe,Ve]=a.useState("__no_change__"),[ae,ye]=a.useState("__no_change__"),[te,Ae]=a.useState([]),[Le,pe]=a.useState(!1),_e=a.useMemo(()=>ae&&ae!=="__no_change__"?te.find(J=>J.id===ae):void 0,[te,ae]),[Fe,tt]=a.useState(!1);a.useEffect(()=>{if(G.size===0)return;let J=!1;return(async()=>{pe(!0);try{const ve=await vo();J||Ae(ve)}catch(ve){console.error("Failed to fetch nodes for bulk edit",ve),J||Ae([])}finally{J||pe(!1)}})(),()=>{J=!0}},[G.size]);const Ne=a.useCallback(async()=>{if(G.size===0)return;const J=Array.from(G).filter(ve=>{const Xe=e.find(ee=>ee.id===ve);return Xe&&Xe.column!=="archived"});if(J.length===0){i("No valid tasks to update (archived tasks cannot be modified)","error");return}const ce={taskIds:J};if(Ke!=="__no_change__")if(Ke==="")ce.modelProvider=null,ce.modelId=null;else{const ve=Ke.indexOf("/");ve!==-1&&(ce.modelProvider=Ke.slice(0,ve),ce.modelId=Ke.slice(ve+1))}if(Pe!=="__no_change__")if(Pe==="")ce.validatorModelProvider=null,ce.validatorModelId=null;else{const ve=Pe.indexOf("/");ve!==-1&&(ce.validatorModelProvider=Pe.slice(0,ve),ce.validatorModelId=Pe.slice(ve+1))}if(ae!=="__no_change__"&&(ae===""?ce.nodeId=null:ce.nodeId=ae),Object.keys(ce).length===1){i("No changes to apply","info");return}tt(!0);try{const ve=await Mv(ce.taskIds,ce.modelProvider,ce.modelId,ce.validatorModelProvider,ce.validatorModelId,void 0,void 0,ce.nodeId,x);f&&f(ve.updated),i(`Updated ${J.length} task${J.length===1?"":"s"}`,"success"),le(),it("__no_change__"),Ve("__no_change__"),ye("__no_change__")}catch(ve){i(je(ve)||"Failed to update models","error")}finally{tt(!1)}},[G,e,Ke,Pe,ae,x,i,le,f]),oe=a.useCallback(J=>{s(J)},[s]),Te=a.useCallback((J,ce)=>{if(ce.paused){J.preventDefault();return}J.dataTransfer.setData("text/plain",ce.id),J.dataTransfer.effectAllowed="move",L(ce.id)},[]),he=a.useCallback(()=>{L(null),P(null)},[]),Me=a.useCallback((J,ce)=>{J.preventDefault(),J.dataTransfer.dropEffect="move",P(ce)},[]),We=a.useCallback(()=>{P(null)},[]),Re=a.useCallback(async(J,ce)=>{J.preventDefault(),P(null);const ve=J.dataTransfer.getData("text/plain");if(ve){if(ce==="archived"){i("Tasks can only be archived via the archive button","error");return}try{await n(ve,ce)}catch(Xe){i(je(Xe),"error")}}},[n,i]),ot=J=>j!==J?t.jsx(Bh,{size:14,className:"sort-icon"}):k==="asc"?t.jsx(Fi,{size:14,className:"sort-icon active"}):t.jsx(wr,{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:q,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>w(J=>!J),"aria-expanded":T,"aria-haspopup":"menu",children:[t.jsx(ix,{size:14}),"Columns"]}),T&&t.jsx("div",{className:"list-column-dropdown",role:"menu",children:Rc.map(J=>{const ce=D.has(J),ve=ce&&D.size===1;return t.jsxs("label",{className:`list-column-dropdown-item${ve?" disabled":""}`,role:"menuitem",title:ve?"At least one column must be visible":"",children:[t.jsx("input",{type:"checkbox",checked:ce,onChange:()=>Se(J),disabled:ve}),t.jsx("span",{children:F[J]})]},J)})})]}),t.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>X(J=>!J),"aria-pressed":Y,title:Y?"Show done tasks":"Hide done tasks",children:[Y?t.jsx(fa,{size:14}):t.jsx(gc,{size:14}),Y?"Show Done":"Hide Done"]}),t.jsxs("div",{className:"list-stats",children:[O?`${ie} of ${e.length} tasks in ${An[O]}`:`${ie} of ${e.length} tasks`,De>0&&!O&&t.jsxs("span",{className:"list-stats-hidden",children:[" (",De," hidden)"]}),O&&t.jsx("button",{className:"btn btn-sm",onClick:de,"aria-label":"Clear column filter",style:{marginLeft:"8px"},children:"Clear"})]}),G.size>0&&t.jsxs("div",{className:"list-selection-stats",children:[t.jsxs("span",{className:"selection-count",children:[G.size," selected"]}),t.jsx("button",{className:"btn btn-sm btn-link",onClick:le,children:"Clear"})]}),G.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(Hn,{models:c,value:Ke,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(Hn,{models:c,value:Pe,onChange:Ve,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:ae,onChange:J=>ye(J.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"}),te.map(J=>t.jsx("option",{value:J.id,children:`${zN(J.status)} ${J.name||J.id} (${LN(J.status)})`},J.id))]}),_e?t.jsx(Vi,{status:_e.status,showLabel:!0}):null]}),t.jsx("button",{className:"btn btn-primary btn-sm bulk-edit-apply-btn",onClick:Ne,disabled:Fe||Ke==="__no_change__"&&Pe==="__no_change__"&&ae==="__no_change__",children:Fe?"Applying...":"Apply"})]}),o?t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:o,children:"+ New Task"}):null]}),t.jsx("div",{className:"list-drop-zones",children:Oi.map(J=>{const ce=e.filter(Ge=>Ge.column===J).length,ve=J==="done"||J==="archived",Xe=Y&&ve?0:ce,ee=Y&&ve&&ce>0;return t.jsxs("div",{className:`list-drop-zone${A===J?" drag-over":""}${O===J?" active":""}`,onClick:()=>se(J),onDragOver:Ge=>Me(Ge,J),onDragLeave:We,onDrop:Ge=>Re(Ge,J),"data-column":J,children:[t.jsx("span",{className:"drop-zone-dot",style:{background:Ba[J]}}),t.jsx("span",{className:"drop-zone-label",children:An[J]}),t.jsx("span",{className:"drop-zone-count",children:ee?`${Xe} of ${ce}`:ce})]},J)})}),t.jsxs("div",{className:"list-table-container",children:[t.jsx("div",{className:"list-quick-entry-above-table",children:t.jsx(Ap,{onCreate:l??(async()=>i("Task creation not available","error")),addToast:i,tasks:e,availableModels:c,onPlanningMode:g,onSubtaskBreakdown:p,projectId:x,autoExpand:!1,favoriteProviders:u,favoriteModels:d,onToggleFavorite:m,onToggleModelFavorite:h})}),ie===0?t.jsx("div",{className:"list-empty",children:y?"No tasks match your filter":"No tasks yet"}):E?t.jsx("div",{className:"list-cards",children:Oi.map(J=>{if(O&&J!==O||Y&&(J==="done"||J==="archived")&&!O)return null;const ce=xe[J],ve=ce.length===0;if(y&&ve)return null;const Xe=_.has(J);return t.jsxs(a.Fragment,{children:[t.jsxs("div",{className:`list-card-section-header${Xe?" list-section-header--collapsed":""}`,onClick:()=>fe(J),"aria-expanded":!Xe,role:"button",tabIndex:0,onKeyDown:ee=>{(ee.key==="Enter"||ee.key===" ")&&(ee.preventDefault(),fe(J))},children:[t.jsx(pn,{size:14,className:`list-section-chevron${Xe?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${J}`}),t.jsx("span",{className:"list-section-title",children:An[J]}),t.jsx("span",{className:"list-section-count",children:ce.length})]}),!Xe&&t.jsx(t.Fragment,{children:ve?t.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):ce.map(ee=>{const Ge=ee.status==="failed",ct=ee.paused===!0,vt=jo(ee,b,S),bt=!r&&!Ge&&!ct&&!vt&&(ee.column==="in-progress"||Ru.has(ee.status)),ft=typeof ee.status=="string"&&ee.status.trim().length>0,gt=!!(ee.dependencies&&ee.dependencies.length>0),_t=Du(ee),Rt=_t.hasProgress,Ft=G.size>0;return t.jsxs("div",{className:`list-card${bt?" agent-active":""}${Ft?" list-card--selectable":""}`,onClick:()=>oe(ee),"data-id":ee.id,children:[Ft&&t.jsx("label",{className:"list-card-checkbox",onClick:wt=>wt.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:G.has(ee.id),onChange:wt=>{wt.stopPropagation(),ue(ee.id)},onClick:wt=>wt.stopPropagation(),disabled:ee.column==="archived","aria-label":`Select ${ee.id}`})}),t.jsxs("div",{className:"list-card-row",children:[t.jsx("span",{className:"list-card-id",children:ee.id}),ee.executionMode==="fast"&&t.jsx("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",children:"Fast"}),t.jsx("span",{className:"list-card-spacer"}),vt?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):ft?t.jsx("span",{className:`list-status-badge list-status-badge--${ee.column}${Ge?" failed":""}${bt?" pulsing":""}`,children:ee.status}):null]}),t.jsx("div",{className:"list-card-row",children:t.jsx("div",{className:"list-card-title",children:ee.title||ee.description})}),(gt||Rt)&&t.jsxs("div",{className:"list-card-row list-card-meta",children:[gt&&t.jsxs("span",{className:"list-dep-badge",title:ee.dependencies.join(", "),children:[t.jsx(ga,{size:12})," ",ee.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:`${_t.percent}%`,backgroundColor:Ba[ee.column]}})}),t.jsx("span",{className:"list-progress-label",children:_t.label})]})]})]},ee.id)})})]},J)})}):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:J=>{J&&(J.indeterminate=Je)},onChange:qe,"aria-label":"Select all visible tasks"})}),D.has("id")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>ge("id"),children:["ID ",ot("id")]}),D.has("title")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>ge("title"),children:["Title ",ot("title")]}),D.has("status")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>ge("status"),children:["Status ",ot("status")]}),D.has("column")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>ge("column"),children:["Column ",ot("column")]}),D.has("dependencies")&&t.jsx("th",{className:"list-header-cell",children:"Dependencies"}),D.has("progress")&&t.jsx("th",{className:"list-header-cell",children:"Progress"})]})}),t.jsx("tbody",{children:Oi.map(J=>{if(O&&J!==O||Y&&(J==="done"||J==="archived")&&!O)return null;const ce=xe[J],ve=ce.length===0;if(y&&ve)return null;const Xe=_.has(J);return t.jsxs(a.Fragment,{children:[t.jsx("tr",{className:`list-section-header${Xe?" list-section-header--collapsed":""}`,onClick:()=>fe(J),"aria-expanded":!Xe,children:t.jsxs("th",{colSpan:D.size+1,className:"list-section-cell",children:[t.jsx(pn,{size:14,className:`list-section-chevron${Xe?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${J}`}),t.jsx("span",{className:"list-section-title",children:An[J]}),t.jsx("span",{className:"list-section-count",children:ce.length})]})}),!Xe&&t.jsx(t.Fragment,{children:ve?t.jsx("tr",{className:"list-section-empty",children:t.jsx("td",{colSpan:D.size+1,className:"list-empty-cell",children:"No tasks"})}):ce.map(ee=>{const Ge=ee.status==="failed",ct=ee.paused===!0,vt=jo(ee,b,S),bt=!r&&!Ge&&!ct&&!vt&&(ee.column==="in-progress"||Ru.has(ee.status)),ft=C===ee.id;return t.jsxs("tr",{className:`list-row${Ge?" failed":""}${ct?" paused":""}${vt?" stuck":""}${bt?" agent-active":""}${ft?" dragging":""}`,onClick:()=>oe(ee),draggable:!ct,onDragStart:gt=>Te(gt,ee),onDragEnd:he,"data-id":ee.id,children:[t.jsx("td",{className:"list-cell list-cell-checkbox",children:t.jsx("input",{type:"checkbox",checked:G.has(ee.id),onChange:gt=>{gt.stopPropagation(),ue(ee.id)},onClick:gt=>gt.stopPropagation(),disabled:ee.column==="archived","aria-label":`Select ${ee.id}`})}),D.has("id")&&t.jsx("td",{className:"list-cell list-cell-id",children:ee.id}),D.has("title")&&t.jsx("td",{className:"list-cell list-cell-title",children:t.jsxs("div",{className:"list-title-content",children:[ee.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:ee.title||ee.description})]})}),D.has("status")&&t.jsx("td",{className:"list-cell",children:vt?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):ee.status?t.jsx("span",{className:`list-status-badge list-status-badge--${ee.column}${Ge?" failed":""}${bt?" pulsing":""}`,children:ee.status}):t.jsx("span",{className:"list-status-badge",children:"-"})}),D.has("column")&&t.jsx("td",{className:"list-cell",children:t.jsx("span",{className:"list-column-badge",style:{background:`${Ba[ee.column]}20`,color:Ba[ee.column]},children:An[ee.column]})}),D.has("dependencies")&&t.jsx("td",{className:"list-cell list-cell-deps",children:ee.dependencies&&ee.dependencies.length>0?t.jsxs("span",{className:"list-dep-badge",title:ee.dependencies.join(", "),children:[t.jsx(ga,{size:12})," ",ee.dependencies.length]}):"-"}),D.has("progress")&&t.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const gt=Du(ee);return gt.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:`${gt.percent}%`,backgroundColor:Ba[ee.column]}})}),t.jsx("span",{className:"list-progress-label",children:gt.label})]}):"-"})()})]},ee.id)})})]},J)})})]})]})]})}const BN={active:{label:"Active",color:"var(--success)",icon:jn},paused:{label:"Paused",color:"var(--warning)",icon:Xs},errored:{label:"Error",color:"var(--color-error)",icon:as},initializing:{label:"Initializing",color:"var(--info)",icon:rt}};function UN(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 HN(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 qN(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 VN({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=BN[e.status],g=h.icon,p=a.useCallback(()=>{s(e)},[s,e]),f=a.useCallback(j=>{j.stopPropagation(),i(e)},[i,e]),x=a.useCallback(j=>{j.stopPropagation(),r(e)},[r,e]),v=a.useCallback(j=>{if(j.stopPropagation(),!d){m(!0);return}o(e),m(!1)},[d,o,e]),b=e.status==="paused",y=e.status==="errored",S=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:j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),p())},children:[t.jsxs("div",{className:"project-card-header",children:[t.jsx("div",{className:"project-card-icon",children:t.jsx(Un,{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:HN(e.path)})]}),t.jsxs("div",{className:"project-card-status-badge",style:{color:h.color,borderColor:h.color},children:[t.jsx(g,{size:12,className:S?"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:UN(e.lastActivityAt||n?.lastActivityAt)})]}),t.jsxs("div",{className:"project-card-actions",children:[b?t.jsxs("button",{className:"project-card-action project-card-action-resume",onClick:x,disabled:u,title:"Resume project","aria-label":"Resume project",children:[t.jsx(jn,{size:14}),t.jsx("span",{children:"Resume"})]}):t.jsxs("button",{className:"project-card-action project-card-action-pause",onClick:f,disabled:u||S,title:S?"Cannot pause while initializing":"Pause project","aria-label":"Pause project",children:[t.jsx(Xs,{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(Nr,{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(Zt,{size:14}),t.jsx("span",{children:d?"Confirm":""})]})]})]})]})}const WN=a.memo(VN,qN);function KN(){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(Un,{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(Ps,{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(fn,{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(as,{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 GN=1e4,Lu=5;function JN(e){const[n,s]=a.useState({}),[i,r]=a.useState(!0),[o,l]=a.useState(null),c=a.useRef(null),u=a.useRef(null),d=a.useRef(!1),m=a.useCallback(async()=>{if(e.length===0){s({}),d.current||(d.current=!0),r(!1);return}u.current&&u.current.abort(),u.current=new AbortController,!d.current&&r(!0),l(null);try{const p={};for(let f=0;f<e.length;f+=Lu){const x=e.slice(f,f+Lu),v=await Promise.allSettled(x.map(async b=>{try{return await tu(b)}catch{return null}}));if(x.forEach((b,y)=>{const S=v[y];p[b]=S.status==="fulfilled"?S.value:null}),u.current?.signal.aborted)return}s(p),d.current=!0}catch(p){if(p instanceof Error&&p.name==="AbortError")return;l(p instanceof Error?p.message:"Failed to fetch health data"),d.current=!0}finally{r(!1)}},[e]),h=a.useCallback(async g=>{try{const p=await tu(g);s(f=>({...f,[g]:p}))}catch(p){console.error(`Failed to fetch health for project ${g}:`,p)}},[]);return a.useEffect(()=>(d.current=!1,m(),()=>{u.current&&u.current.abort()}),[m]),a.useEffect(()=>{if(e.length!==0)return c.current&&clearInterval(c.current),c.current=setInterval(()=>{m()},GN),()=>{c.current&&(clearInterval(c.current),c.current=null)}},[m,e.length]),{healthMap:n,loading:i,error:o,refresh:m,refreshProject:h}}function YN({projects:e,loading:n=!1,onSelectProject:s,onAddProject:i,onPauseProject:r,onResumeProject:o,onRemoveProject:l,nodes:c=[]}){const[u,d]=a.useState("all"),[m,h]=a.useState(null),[g,p]=a.useState("activity"),[f,x]=a.useState("desc");a.useEffect(()=>{if(typeof window>"u")return;const V=localStorage.getItem("kb-dashboard-recent-projects");if(V)try{const $=JSON.parse(V);b($)}catch{}},[]);const[v,b]=a.useState([]),y=a.useMemo(()=>e.map(V=>V.id),[e]),{healthMap:S,loading:j}=JN(y),R=a.useMemo(()=>e.map(V=>({project:V,health:S[V.id]||null})),[e,S]),k=a.useMemo(()=>{let V=[...R];return u!=="all"&&(V=V.filter(({project:$})=>$.status===u)),m!==null&&(V=V.filter(({project:$})=>$.nodeId===m)),V},[R,u,m]),M=a.useMemo(()=>{const V=[...k];return V.sort(($,E)=>{let D=0;switch(g){case"name":D=$.project.name.localeCompare(E.project.name);break;case"activity":{const U=$.project.lastActivityAt||$.health?.lastActivityAt||$.project.updatedAt,Y=E.project.lastActivityAt||E.health?.lastActivityAt||E.project.updatedAt;D=new Date(Y).getTime()-new Date(U).getTime();break}case"status":{const U={errored:0,initializing:1,paused:2,active:3};D=U[$.project.status]-U[E.project.status];break}}return f==="asc"?D:-D}),V},[k,g,f]),C=a.useMemo(()=>{const V=e.length,$=e.filter(I=>I.status==="active").length,E=e.filter(I=>I.status==="errored").length,D=new Set;e.forEach(I=>{I.nodeId&&D.add(I.nodeId)});const U=D.size||(V>0?1:0);let Y=0,X=0,_=0;return Object.values(S).forEach(I=>{I&&(Y+=I.activeTaskCount,X+=I.totalTasksCompleted,_+=I.inFlightAgentCount)}),{totalProjects:V,activeProjects:$,erroredProjects:E,totalNodes:U,totalActiveTasks:Y,totalCompletedTasks:X,totalInFlightAgents:_}},[e,S]),L=a.useMemo(()=>({all:e.length,active:e.filter(V=>V.status==="active").length,paused:e.filter(V=>V.status==="paused").length,errored:e.filter(V=>V.status==="errored").length}),[e]),A=a.useMemo(()=>{const V=new Map;return e.forEach($=>{const E=$.nodeId,D=V.get(E);if(D)D.count++;else{const Y=c.find(X=>X.id===E)?.name??$._sourceNodeName??"Local";V.set(E,{name:Y,count:1})}}),Array.from(V.entries()).map(([$,{name:E,count:D}])=>({nodeId:$??null,name:E,count:D}))},[e,c]),P=a.useCallback(V=>{const $=[V.id,...v.filter(E=>E!==V.id)].slice(0,3);b($),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify($)),s(V)},[s,v]);return n||j&&e.length>0&&Object.keys(S).length===0?t.jsx(KN,{}):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(sr,{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(en,{size:16}),"Add Your First Project"]})]})}):t.jsxs("div",{className:"project-overview",children:[t.jsxs("div",{className:"project-overview__header",children:[t.jsxs("h2",{className:"project-overview__title",children:[t.jsx(qi,{size:20}),"Projects"]}),t.jsxs("div",{className:"project-overview__stats",children:[t.jsxs("div",{className:"project-stat",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Un,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:C.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(Ps,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:C.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(fn,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:C.totalCompletedTasks}),t.jsx("span",{className:"project-stat__label",children:"Completed"})]})]}),C.erroredProjects>0&&t.jsxs("div",{className:"project-stat project-stat--error",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(as,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:C.erroredProjects}),t.jsx("span",{className:"project-stat__label",children:"Errored"})]})]}),C.totalNodes>1&&t.jsxs("div",{className:"project-stat project-stat--nodes",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(fr,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:C.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(en,{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:L.all})]}),t.jsxs("button",{className:`project-filter-tab ${u==="active"?"active":""}`,onClick:()=>d("active"),children:["Active",t.jsx("span",{className:"project-filter-count",children:L.active})]}),t.jsxs("button",{className:`project-filter-tab ${u==="paused"?"active":""}`,onClick:()=>d("paused"),children:["Paused",t.jsx("span",{className:"project-filter-count",children:L.paused})]}),t.jsxs("button",{className:`project-filter-tab ${u==="errored"?"active":""} ${L.errored>0?"has-errors":""}`,onClick:()=>d("errored"),children:["Errored",t.jsx("span",{className:"project-filter-count",children:L.errored})]})]}),A.length>1&&t.jsxs("div",{className:"project-node-filter",children:[t.jsx(fr,{size:14}),t.jsxs("select",{value:m??"",onChange:V=>{h(V.target.value||null)},className:"project-node-filter-select","aria-label":"Filter by node",children:[t.jsx("option",{value:"",children:"All Nodes"}),A.map(({nodeId:V,name:$,count:E})=>t.jsxs("option",{value:V??"",children:[$," (",E,")"]},V??"local"))]})]}),t.jsxs("div",{className:"project-sort",children:[t.jsx(po,{size:14}),t.jsxs("select",{value:`${g}-${f}`,onChange:V=>{const[$,E]=V.target.value.split("-");p($),x(E)},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(Bh,{size:14})]})]}),t.jsx("div",{className:"project-grid",children:M.map(({project:V,health:$})=>{const E=c.find(U=>U.id===V.nodeId),D=E?void 0:V._sourceNodeName;return t.jsx(WN,{project:V,health:$,node:E,nodeNameFallback:D,onSelect:P,onPause:r,onResume:o,onRemove:l},V.id)})}),M.length===0&&t.jsxs("div",{className:"project-overview__no-results",children:[t.jsx(po,{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 QN=45e3,XN=3e3,ZN=2e3,e1=1500,zu="fusion:sse-client-id";let sa=null;const ki=new Map;function Fu(){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 Tp(){if(!(typeof window>"u")){if(sa)return sa;try{const e=window.sessionStorage.getItem(zu);if(e)return sa=e,e;const n=Fu();return window.sessionStorage.setItem(zu,n),sa=n,n}catch{return sa=Fu(),sa}}}function Pp(e){if(!(typeof window>"u"))try{return{parsed:new URL(e,window.location.origin),preserveRelativePath:e.startsWith("/")}}catch{return}}function Ip(e){return e.origin===window.location.origin&&e.pathname==="/api/events"}function t1(e){const n=Tp();if(!n)return e;const s=Pp(e);return!s||!Ip(s.parsed)?e:(s.parsed.searchParams.set("clientId",n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function od(e,n){const s=Tp();if(!s)return;const i=Pp(e);if(!i||!Ip(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),ti(`${r.pathname}${r.search}${r.hash}`)}function n1(e){if(typeof window>"u")return;const n=od(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 Vo(e){e.keepaliveTimer&&(clearInterval(e.keepaliveTimer),e.keepaliveTimer=null)}function Ou(e){if(typeof window>"u"||typeof window.fetch!="function")return;const n=od(e.url,"keepalive");if(!n)return;const s=typeof AbortController<"u"?new AbortController:null,i=s?window.setTimeout(()=>s.abort(),e1):null;window.fetch(n,{method:"POST",cache:"no-store",signal:s?.signal}).catch(()=>{}).finally(()=>{i!==null&&window.clearTimeout(i)})}function s1(e){Vo(e),od(e.url,"keepalive")&&(Ou(e),e.keepaliveTimer=window.setInterval(()=>{Ou(e)},ZN))}if(typeof window<"u"){const e=()=>{for(const s of Array.from(ki.values()))if(!s.closed){if(Vo(s),n1(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(ki.values()))i.subscribers.size!==0&&(i.closed=!1,ld(i))};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e),window.addEventListener("pageshow",n)}function ir(e){e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),e.heartbeatTimer=setTimeout(()=>{$p(e)},QN)}function $p(e){if(e.heartbeatTimer&&(clearTimeout(e.heartbeatTimer),e.heartbeatTimer=null),e.es&&(e.es.close(),e.es=null),Vo(e),e.nativeListeners.clear(),e.closed||e.subscribers.size===0||e.reconnectTimer)return;const n=ki.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=ki.get(e.url);s&&s===e&&e.subscribers.size>0&&ld(e)},XN)}}function ld(e){if(e.es||e.closed)return;e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=null);const n=new EventSource(ti(t1(e.url)));e.es=n,s1(e),n.addEventListener("open",()=>{ir(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);$p(e)}),n.addEventListener("message",()=>ir(e)),n.addEventListener("heartbeat",()=>ir(e)),Dp(e),ir(e)}function Dp(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=>{ir(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 i1(e){e.closed=!0,e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),Vo(e),e.reconnectTimer&&clearTimeout(e.reconnectTimer),e.es&&e.es.close(),e.es=null,e.nativeListeners.clear(),ki.delete(e.url)}function qs(e,n={}){let s=ki.get(e);s||(s={url:e,es:null,subscribers:new Set,nativeListeners:new Map,heartbeatTimer:null,keepaliveTimer:null,reconnectTimer:null,hasOpenedOnce:!1,closed:!1},ki.set(e,s));const i={events:new Map,onOpen:n.onOpen,onReconnect:n.onReconnect,onError:n.onError};if(n.events)for(const[o,l]of Object.entries(n.events)){let c=i.events.get(o);c||(c=new Set,i.events.set(o,c)),c.add(l)}s.subscribers.add(i),ld(s),Dp(s);let r=!0;return()=>{if(!r)return;r=!1;const o=ki.get(e);o&&(o.subscribers.delete(i),o.subscribers.size===0&&i1(o))}}const cd="kb-planning-last-description",dd="kb-subtask-last-description",ud="kb-mission-last-goal";function a1(e,n){ds(cd,e,n)}function r1(e){return qn(cd,e)||""}function ia(e){vr(cd,e)}function o1(e,n){ds(dd,e,n)}function l1(e){return qn(dd,e)||""}function yl(e){vr(dd,e)}function c1(e,n){ds(ud,e,n)}function d1(e){return qn(ud,e)||""}function bi(e){vr(ud,e)}function u1(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 m1(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 h1(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 Is({entries:e,defaultShowThinking:n=!1}){const[s,i]=a.useState({}),r=h1(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?u1(o):void 0,h=o.question&&m!==void 0?m1(o.question,m):"";return t.jsxs("div",{className:"conversation-entry",children:[c?t.jsxs("div",{className:"conversation-entry-question",children:[t.jsxs("span",{className:"conversation-entry-question-label",children:["Q",o.questionNumber]}),t.jsx("p",{children:o.question?.question})]}):t.jsx("div",{className:"conversation-entry-question",children:t.jsx("span",{className:"conversation-entry-question-label",children:"AI Reasoning"})}),c&&t.jsxs("div",{className:"conversation-entry-response",children:[t.jsx("strong",{children:"Your response"}),t.jsx("p",{children:h||"—"})]}),u&&t.jsxs("div",{className:"conversation-entry-thinking",children:[t.jsxs("button",{type:"button",className:"conversation-thinking-toggle",onClick:()=>{i(g=>({...g,[l]:!d}))},"aria-expanded":d,children:[t.jsx("span",{"aria-hidden":"true",children:d?"▾":"▸"}),d?`Hide ${c?"AI thinking":"AI reasoning"}`:`Show ${c?"AI thinking":"AI reasoning"}`]}),d&&t.jsx("pre",{children:o.thinkingOutput})]})]},`${o.question?.id??"thinking"}-${l}`)})})}const Bu="fusion-tab-id";function p1(){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(Bu);if(e)return e;const n=p1();return window.sessionStorage.setItem(Bu,n),n}function Wo(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=Fk(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=ti(`/api/ai-sessions/${encodeURIComponent(e)}/lock/beacon?tabId=${encodeURIComponent(n)}`);navigator.sendBeacon(m)};return window.addEventListener("beforeunload",d),()=>{window.removeEventListener("beforeunload",d)}},[e,n]),a.useEffect(()=>!e||typeof EventSource>"u"?void 0:qs("/api/events",{events:{"ai_session:updated":m=>{try{const h=JSON.parse(m.data);if(h.id!==e)return;const g=h.lockedByTab??null;o(g),i(!!(g&&g!==n))}catch{}}}}),[e,n]);const u=a.useCallback(async()=>{if(e){c(!0);try{await Promise.resolve(Ok(e,n)),i(!1),o(null)}finally{c(!1)}}},[e,n]);return{isLockedByOther:s,currentHolder:r,takeControl:u,isLoading:l}}const f1="fusion:ai-session-sync",Uu="fusion:ai-session-sync",g1=3e4,x1=6e4;function Ks(){return Date.now()}function b1(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Hu(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 v1{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=b1(),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:Ks()})}broadcastUpdate(n){const s=n.timestamp??Ks();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??Ks();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=Ks();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=Ks();this.releaseTabOwnership(n,s,i),this.ownedSessions.delete(n),this.publish({type:"tab:inactive",tabId:s,sessionId:n,timestamp:i})}broadcastHeartbeat(n){const s=Ks();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(f1),this.channel.onmessage=s=>{const i=Hu(s.data);i&&this.handleIncomingMessage(i)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==Uu||!s.newValue))try{const i=JSON.parse(s.newValue),r=Hu(i.message);r&&this.handleIncomingMessage(r)}catch{}};window.addEventListener("storage",n),this.cleanupStorageListener=()=>{window.removeEventListener("storage",n)}}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{const n=Ks();this.updateHeartbeat(this.tabId,n),this.publish({type:"tab:heartbeat",tabId:this.tabId,timestamp:n})},g1)}startStaleSweep(){this.staleSweepInterval=setInterval(()=>{this.emit()},1e4)}setupBeforeUnloadCleanup(){const n=()=>{for(const[s,i]of this.ownedSessions.entries()){const r=Ks();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(Uu,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:Ks()});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=Ks(),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>x1;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 Gs=new v1;function Ra(){const e=a.useSyncExternalStore(c=>Gs.subscribe(c),()=>Gs.getSnapshot(),()=>Gs.getSnapshot());a.useEffect(()=>{Gs.requestSync()},[]);const n=a.useCallback(c=>{Gs.broadcastUpdate(c)},[]),s=a.useCallback(c=>{Gs.broadcastCompleted(c)},[]),i=a.useCallback((c,u)=>{Gs.broadcastLock(c,u)},[]),r=a.useCallback((c,u)=>{Gs.broadcastUnlock(c,u)},[]),o=a.useCallback(c=>{Gs.broadcastHeartbeat(c)},[]),l=a.useCallback(()=>{Gs.requestSync()},[]);return{tabId:e.tabId,sessions:e.sessions,activeTabMap:e.activeTabMap,broadcastUpdate:n,broadcastCompleted:s,broadcastLock:i,broadcastUnlock:r,broadcastHeartbeat:o,requestSync:l}}function y1(e,n){return e&&n?`${e}/${n}`:""}function j1(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 k1=["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 w1({isOpen:e,onClose:n,onMissionCreated:s,projectId:i,initialGoal:r,resumeSessionId:o}){const[l,c]=a.useState(""),[u,d]=a.useState({type:"initial"}),[m,h]=a.useState(null),[g,p]=a.useState([]),[f,x]=a.useState([]),[v,b]=a.useState(null),[y,S]=a.useState(!1),j=a.useRef(!1),[R,k]=a.useState(""),[M,C]=a.useState(!0),[L,A]=a.useState(!1),[P,O]=a.useState(!1),[V,$]=a.useState(!1),E=a.useRef(null),D=a.useRef(null),U=a.useRef(null),Y=a.useRef(null),[X,_]=a.useState(o??null),I=a.useMemo(()=>Ji(),[]),{isLockedByOther:T,takeControl:w,isLoading:q}=Wo(e?X:null),{activeTabMap:G,broadcastUpdate:me,broadcastCompleted:ue,broadcastLock:le,broadcastUnlock:Se,broadcastHeartbeat:F}=Ra(),{confirm:ge}=Hs(),[se,fe]=a.useState(void 0),[de,xe]=a.useState(void 0),[ie,Ee]=a.useState([]),[De,qe]=a.useState(!0),[Qe,Je]=a.useState(null),[Ke,it]=a.useState([]),[Pe,Ve]=a.useState([]),ae=y1(se,de);a.useEffect(()=>{(async()=>{try{qe(!0);const ce=await ms();Ee(ce.models),it(ce.favoriteProviders),Ve(ce.favoriteModels)}catch(ce){Je(je(ce)||"Failed to load models")}finally{qe(!1)}})()},[]);const ye=a.useCallback(J=>{it(ce=>{const ve=ce,ee=ve.includes(J)?ve.filter(Ge=>Ge!==J):[J,...ve];return ln({favoriteProviders:ee,favoriteModels:Pe}).catch(()=>{it(ve)}),ee})},[Pe]),te=a.useCallback(J=>{Ve(ce=>{const ve=ce,ee=ve.includes(J)?ve.filter(Ge=>Ge!==J):[J,...ve];return ln({favoriteProviders:Ke,favoriteModels:ee}).catch(()=>{Ve(ve)}),ee})},[Ke]),Ae=a.useCallback((J,ce)=>{if(!J||!ce)return"Using default";const ve=ie.find(Xe=>Xe.provider===J&&Xe.id===ce);return ve?`${ve.provider}/${ve.id}`:`${J}/${ce}`},[ie]),Le=a.useCallback(J=>{D.current?.close();const ce=Ck(J,i,{onThinking:ve=>{k(Xe=>Xe+ve),me({sessionId:J,status:"generating",needsInput:!1,owningTabId:I,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onQuestion:ve=>{A(!1),O(!1),bi(i),d({type:"question",sessionId:J,question:ve}),k(""),S(!0),me({sessionId:J,status:"awaiting_input",needsInput:!0,owningTabId:I,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onSummary:ve=>{A(!1),O(!1),bi(i),d({type:"summary",sessionId:J,summary:ve}),b(ve),k(""),S(!0),me({sessionId:J,status:"complete",needsInput:!1,owningTabId:I,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onError:ve=>{const Xe=ve||"Session failed while contacting the AI.";A(!1),O(!1),h(null),d({type:"error",sessionId:J,errorMessage:Xe}),k(""),S(!0),U.current=J,me({sessionId:J,status:"error",needsInput:!1,owningTabId:I,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null}),ue({sessionId:J,status:"error"})},onComplete:()=>{A(!1),O(!1),U.current=null,ue({sessionId:J,status:"complete"})},onConnectionStateChange:ve=>{A(ve==="reconnecting")}});D.current=ce},[ue,me,l,i,I]),pe=a.useCallback(async J=>{const ce=J??l;if(ce.trim()){h(null),k(""),p([]),x([]),A(!1),d({type:"loading"});try{const{sessionId:ve}=await kk(ce.trim(),i,se&&de?{modelProvider:se,modelId:de}:void 0);U.current=ve,_(ve),bi(i),Le(ve),p([])}catch(ve){A(!1),h(je(ve)||"Failed to start interview session"),d({type:"initial"}),U.current=null,_(null)}}},[Le,l,se,de,i]);a.useEffect(()=>{e&&u.type==="initial"&&E.current?.focus()},[e,u.type]),a.useEffect(()=>{if(e&&r&&!j.current&&u.type==="initial"){c(r);const J=setTimeout(()=>{j.current=!0,pe(r)},0);return()=>clearTimeout(J)}else if(e&&!r&&!j.current&&u.type==="initial"){const J=d1(i);J&&c(J)}},[e,r,u.type,pe]),a.useEffect(()=>{e||(j.current=!1,A(!1),O(!1),_(null))},[e]),a.useEffect(()=>{if(!e||!o||u.type!=="initial")return;let J=!1;return di(o).then(ce=>{if(J||!ce)return;const ve=ya(ce.conversationHistory);if(x(ve),_(ce.id),p(ve.map(Xe=>Xe.response).filter(Xe=>!!(Xe&&typeof Xe=="object"&&!Array.isArray(Xe)))),ce.status==="awaiting_input"&&ce.currentQuestion)try{bi(i);const Xe=JSON.parse(ce.currentQuestion);U.current=ce.id,S(!0),d({type:"question",sessionId:ce.id,question:Xe})}catch{h("Failed to restore session question.")}else if(ce.status==="complete"&&ce.result)try{bi(i);const Xe=JSON.parse(ce.result);U.current=ce.id,S(!0),b(Xe),d({type:"summary",sessionId:ce.id,summary:Xe})}catch{h("Failed to restore session result.")}else ce.status==="generating"?(U.current=ce.id,S(!0),ce.thinkingOutput&&k(ce.thinkingOutput),d({type:"loading"}),Le(ce.id)):ce.status==="error"&&(U.current=ce.id,S(!0),h(null),d({type:"error",sessionId:ce.id,errorMessage:ce.error??"The session encountered an error."}))}).catch(()=>{J||h("Failed to resume session.")}),()=>{J=!0}},[Le,e,o,u.type,i]),a.useEffect(()=>{if(!e){Y.current&&(Se(Y.current,I),Y.current=null);return}if(X&&Y.current!==X){Y.current&&Se(Y.current,I),le(X,I),Y.current=X;return}!X&&Y.current&&(Se(Y.current,I),Y.current=null)},[le,Se,e,X,I]),a.useEffect(()=>{if(!e||!X||Y.current!==X)return;F(I);const J=setInterval(()=>{F(I)},3e4);return()=>{clearInterval(J)}},[F,e,X,I]),a.useEffect(()=>()=>{D.current?.close(),D.current=null,Y.current&&(Se(Y.current,I),Y.current=null)},[Se,I]),a.useEffect(()=>{if(!e)return;const J=ce=>{(u.type==="question"||u.type==="summary")&&(ce.preventDefault(),ce.returnValue=""),D.current?.close()};return window.addEventListener("beforeunload",J),()=>window.removeEventListener("beforeunload",J)},[e,u]);const _e=a.useCallback(()=>{D.current?.close(),D.current=null,n()},[n]),Fe=a.useCallback(async()=>{if(l&&c1(l,i),!(y&&!await ge({title:"Close Interview",message:"Are you sure you want to close? Your interview progress will be lost.",danger:!0}))){if(D.current?.close(),D.current=null,u.type==="question"||u.type==="summary"||u.type==="error")try{await pp(u.sessionId,i,I)}catch{}c(""),d({type:"initial"}),h(null),p([]),x([]),b(null),k(""),A(!1),O(!1),S(!1),$(!1),fe(void 0),xe(void 0),U.current=null,_(null),n()}},[l,y,u,n,i,I,ge]);a.useEffect(()=>{if(!e)return;const J=ce=>{ce.key==="Escape"&&Fe()};return document.addEventListener("keydown",J),()=>document.removeEventListener("keydown",J)},[e,Fe]);const tt=a.useCallback(async J=>{if(u.type!=="question")return;const{sessionId:ce}=u;h(null),p(ve=>[...ve,J]),x(ve=>[...ve,{question:u.question,response:J}]),d({type:"loading"}),k("");try{Le(ce),await wk(ce,J,i,I),S(!0)}catch(ve){D.current?.close(),D.current=null,h(je(ve)||"Failed to submit response"),d({type:"question",sessionId:ce,question:u.question})}},[u,i,I,Le]),Ne=a.useCallback(async()=>{if(u.type!=="error")return;const J=u.sessionId;h(null),O(!0),k(""),d({type:"loading"}),Le(J);try{U.current=J,_(J),await Nk(J,i,I)}catch(ce){let ve=ce;if((je(ce)||"").includes("not in an error state"))try{const ee=await di(J);if(!ee)throw new Error("Failed to refresh interview session.");const Ge=ya(ee.conversationHistory);if(x(Ge),p(Ge.map(ct=>ct.response).filter(ct=>!!(ct&&typeof ct=="object"&&!Array.isArray(ct)))),U.current=ee.id,_(ee.id),S(!0),ee.status==="generating")k(ee.thinkingOutput??""),d({type:"loading"}),D.current?.isConnected()||Le(ee.id);else if(ee.status==="awaiting_input"){if(!ee.currentQuestion)throw new Error("Interview session is awaiting input but has no current question.");bi(i);const ct=JSON.parse(ee.currentQuestion);d({type:"question",sessionId:ee.id,question:ct}),D.current?.isConnected()||Le(ee.id)}else if(ee.status==="complete"){if(!ee.result)throw new Error("Interview session is complete but has no result.");bi(i);const ct=JSON.parse(ee.result);b(ct),d({type:"summary",sessionId:ee.id,summary:ct})}else ee.status==="error"&&d({type:"error",sessionId:ee.id,errorMessage:ee.error??"Retry failed. Please try again."});A(!1);return}catch(ee){ve=ee}D.current?.close(),D.current=null,d({type:"error",sessionId:J,errorMessage:je(ve)||"Retry failed. Please try again."}),A(!1)}finally{O(!1)}},[Le,i,I,u]),oe=a.useCallback(async()=>{if(u.type==="summary"){h(null),$(!0);try{const J=await Sk(u.sessionId,v||void 0,i);s(J),bi(i),D.current?.close(),D.current=null,c(""),d({type:"initial"}),h(null),p([]),x([]),b(null),k(""),A(!1),O(!1),S(!1),$(!1),U.current=null,_(null),n()}catch(J){h(je(J)||"Failed to create mission"),$(!1)}}},[u,v,s,n,i]),Te=()=>u.type==="question"?Math.min(g.length+1,6):6,he=u.type==="loading"||u.type==="question"||u.type==="summary"||u.type==="error",Me=X?G.get(X):null,We=Me&&Me.tabId!==I,Re=!!(We&&!Me.stale),ot=T&&(!We||Me.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:J=>J.target===J.currentTarget&&Fe(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(us,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Plan Mission with AI"})]}),t.jsxs("div",{className:"modal-header-actions",children:[he&&t.jsx("button",{className:"modal-send-to-background",onClick:_e,title:"Send to background","aria-label":"Send to background",children:t.jsx(Cr,{size:16})}),t.jsx("button",{className:"modal-close",onClick:Fe,"aria-label":"Close",children:t.jsx(Ut,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[m&&t.jsx("div",{className:"form-error planning-error",children:m}),L&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Re&&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(Xn,{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:E,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:J=>c(J.target.value),onKeyDown:J=>{J.key==="Enter"&&!J.shiftKey&&l.trim()&&(J.preventDefault(),pe())}})]}),t.jsxs("div",{className:"planning-examples",children:[t.jsx("span",{className:"planning-examples-label",children:"Try an example:"}),t.jsx("div",{className:"planning-example-chips",children:k1.map((J,ce)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>c(J),children:J.length>45?J.slice(0,45)+"...":J},ce))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"mission-interview-modal-model",className:"form-label",children:["Planning Model",De&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(Hn,{id:"mission-interview-modal-model",label:"Planning Model",value:ae,onChange:J=>{const{provider:ce,modelId:ve}=j1(J);fe(ce),xe(ve)},models:ie,disabled:De,favoriteProviders:Ke,onToggleFavorite:ye,favoriteModels:Pe,onToggleModelFavorite:te}),Qe&&t.jsxs("div",{className:"form-hint form-hint-error",children:[Qe," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{qe(!0);const J=await ms();Ee(J.models),it(J.favoriteProviders),Ve(J.favoriteModels),Je(null)}catch(J){Je(je(J)||"Failed to load models")}finally{qe(!1)}})()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${se&&de?"model-badge-custom":"model-badge-default"}`,children:Ae(se,de)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>pe(),disabled:!l.trim(),children:[t.jsx(us,{size:16,className:"icon-mr-8"}),"Start Interview"]})})]}),u.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(rt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:R?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>C(!M),type:"button",children:M?"Hide thinking":"Show thinking"}),M&&R&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:R})})]})]}),u.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[f.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Is,{entries:f}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:u.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void Ne(),disabled:P,children:[P?t.jsx(rt,{size:14,className:"spin"}):t.jsx(En,{size:14}),t.jsx("span",{className:"icon-ml-6",children:P?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Fe,disabled:P,children:"Cancel"})]})]})]})}),u.type==="question"&&t.jsx(N1,{question:u.question,progress:Te(),historyEntries:f,onSubmit:tt}),u.type==="summary"&&v&&t.jsx(S1,{summary:v,historyEntries:f,onSummaryChange:b,onApprove:oe,onStartOver:()=>{d({type:"initial"}),S(!1),b(null),p([]),x([]),_(null),D.current?.close(),D.current=null},isCreating:V}),T&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Do,{size:16}),t.jsx("span",{children:ot?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),ot&&t.jsx("button",{type:"button",onClick:()=>{w()},disabled:q,className:"btn btn-primary session-lock-take-control",children:q?"Taking control...":"Take Control"})]})})]})]})}):null}function N1({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(Is,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3,4,5,6].map(m=>t.jsx("div",{className:`planning-progress-step ${m<=n?"active":""}`},m))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~6"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:l,onChange:m=>c(m.target.value),onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&l.trim()&&(m.preventDefault(),u())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(m=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:m.id,checked:r[e.id]===m.id,onChange:()=>o({[e.id]:m.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(m=>{const h=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:m.id,checked:h.includes(m.id),onChange:g=>{const p=g.target.checked?[...h,m.id]:h.filter(f=>f!==m.id);o({[e.id]:p})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!0?"selected":""}`,onClick:()=>o({[e.id]:!0}),children:[t.jsx(fn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(Ut,{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(Nr,{size:16,className:"icon-ml-4"})]})})]})}function S1({summary:e,historyEntries:n,onSummaryChange:s,onApprove:i,onStartOver:r,isCreating:o}){const[l,c]=a.useState(()=>new Set(e.milestones.map((j,R)=>R))),[u,d]=a.useState(()=>{const j=new Set;return e.milestones.forEach((R,k)=>{R.slices.forEach((M,C)=>j.add(`${k}-${C}`))}),j}),m=j=>{c(R=>{const k=new Set(R);return k.has(j)?k.delete(j):k.add(j),k})},h=j=>{d(R=>{const k=new Set(R);return k.has(j)?k.delete(j):k.add(j),k})},g=(j,R)=>{const k=[...e.milestones];k[j]={...k[j],...R},s({...e,milestones:k})},p=(j,R,k)=>{const M=[...e.milestones],C=[...M[j].slices];C[R]={...C[R],...k},M[j]={...M[j],slices:C},s({...e,milestones:M})},f=(j,R,k,M)=>{const C=[...e.milestones],L=[...C[j].slices],A=[...L[R].features];A[k]={...A[k],...M},L[R]={...L[R],features:A},C[j]={...C[j],slices:L},s({...e,milestones:C})},x=j=>{const R=e.milestones.filter((k,M)=>M!==j);s({...e,milestones:R})},v=(j,R)=>{const k=[...e.milestones];k[j]={...k[j],slices:k[j].slices.filter((M,C)=>C!==R)},s({...e,milestones:k})},b=(j,R,k)=>{const M=[...e.milestones],C=[...M[j].slices];C[R]={...C[R],features:C[R].features.filter((L,A)=>A!==k)},M[j]={...M[j],slices:C},s({...e,milestones:M})},y=(j,R)=>{const k=[...e.milestones],M=[...k[j].slices];M[R]={...M[R],features:[...M[R].features,{title:"New feature",description:""}]},k[j]={...k[j],slices:M},s({...e,milestones:k})},S=e.milestones.reduce((j,R)=>j+R.slices.reduce((k,M)=>k+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(Is,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(fn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Mission Plan Ready"}),t.jsxs("p",{className:"text-muted",children:[e.milestones.length," milestones, ",S," 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:j=>s({...e,missionTitle:j.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:j=>s({...e,missionDescription:j.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Roadmap"}),t.jsx("div",{className:"roadmap-list",children:e.milestones.map((j,R)=>t.jsxs("div",{className:"roadmap-card",children:[t.jsxs("div",{className:"roadmap-card-header",onClick:()=>m(R),children:[l.has(R)?t.jsx(Vt,{size:16,className:"icon-text-secondary"}):t.jsx(pn,{size:16,className:"icon-text-secondary"}),t.jsx(Hi,{size:16,className:"icon-milestone"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-title",value:j.title,onChange:k=>g(R,{title:k.target.value}),onClick:k=>k.stopPropagation()}),e.milestones.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:k=>{k.stopPropagation(),x(R)},title:"Remove milestone",children:t.jsx(Zt,{size:14,className:"icon-text-secondary"})})]}),l.has(R)&&t.jsxs("div",{className:"roadmap-card-body",children:[t.jsx("textarea",{className:"planning-textarea roadmap-textarea-md",rows:2,placeholder:"Milestone description...",value:j.description||"",onChange:k=>g(R,{description:k.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:j.verification||"",onChange:k=>g(R,{verification:k.target.value})})]}),j.slices.map((k,M)=>{const C=`${R}-${M}`;return t.jsxs("div",{className:"roadmap-slice-card",children:[t.jsxs("div",{className:"roadmap-slice-header",onClick:()=>h(C),children:[u.has(C)?t.jsx(Vt,{size:14,className:"icon-text-secondary"}):t.jsx(pn,{size:14,className:"icon-text-secondary"}),t.jsx(yc,{size:14,className:"icon-slice"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:k.title,onChange:L=>p(R,M,{title:L.target.value}),onClick:L=>L.stopPropagation()}),j.slices.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:L=>{L.stopPropagation(),v(R,M)},title:"Remove slice",children:t.jsx(Zt,{size:12,className:"icon-text-secondary"})})]}),u.has(C)&&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:k.verification||"",onChange:L=>p(R,M,{verification:L.target.value})})]}),k.features.map((L,A)=>t.jsxs("div",{className:"roadmap-feature-row",children:[t.jsx(hc,{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:L.title,onChange:P=>f(R,M,A,{title:P.target.value})}),L.description&&t.jsx("p",{className:"roadmap-feature-text",children:L.description}),L.acceptanceCriteria&&t.jsxs("p",{className:"roadmap-feature-text--italic",children:["AC: ",L.acceptanceCriteria]})]}),t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:()=>b(R,M,A),title:"Remove feature",children:t.jsx(Zt,{size:12,className:"icon-text-secondary"})})]},A)),t.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>y(R,M),children:[t.jsx(en,{size:12}),"Add Feature"]})]})]},M)})]})]},R))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:r,disabled:o,children:[t.jsx(_a,{size:16,className:"icon-mr-4"}),"Start Over"]}),t.jsx("button",{className:"btn btn-primary",onClick:i,disabled:o||e.milestones.length===0,children:o?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:16,className:"spin icon-mr-8"}),"Creating Mission..."]}):t.jsxs(t.Fragment,{children:[t.jsx(fn,{size:16,className:"icon-mr-8"}),"Approve Plan"]})})]})]})}function C1({isOpen:e,onClose:n,onApplied:s,targetType:i,targetId:r,targetTitle:o,missionContext:l,projectId:c,resumeSessionId:u}){const[d,m]=a.useState({type:"initial"}),[h,g]=a.useState(null),[p,f]=a.useState([]),[x,v]=a.useState([]),[b,y]=a.useState(null),[S,j]=a.useState(""),[R,k]=a.useState(!0),[M,C]=a.useState(!1),[L,A]=a.useState(!1),P=a.useRef(null),O=a.useRef(null),V=a.useRef(null),$=a.useRef(null),[E,D]=a.useState(null),U=a.useMemo(()=>Ji(),[]);Wo(e?E:null);const{activeTabMap:Y,broadcastUpdate:X,broadcastCompleted:_,broadcastLock:I,broadcastUnlock:T,broadcastHeartbeat:w}=Ra(),q=i==="milestone"?Ek:Tk,G=i==="milestone"?_k:Pk,me=i==="milestone"?Mk:Ik,ue=i==="milestone"?Ak:$k,le=i==="milestone"?Rk:Dk,Se=i==="milestone"?"Milestone":"Slice",F=i==="milestone"?"milestone_interview":"slice_interview",ge=a.useCallback(Pe=>{O.current?.close();const Ve=me(Pe,c,{onThinking:ae=>{j(ye=>ye+ae),X({sessionId:Pe,status:"generating",needsInput:!1,owningTabId:U,type:F,title:o,projectId:c??null})},onQuestion:ae=>{C(!1),se(),m({type:"question",sessionId:Pe,question:ae}),j(""),X({sessionId:Pe,status:"awaiting_input",needsInput:!0,owningTabId:U,type:F,title:o,projectId:c??null})},onSummary:ae=>{C(!1),se(),m({type:"summary",sessionId:Pe,summary:ae}),y(ae),j(""),X({sessionId:Pe,status:"complete",needsInput:!1,owningTabId:U,type:F,title:o,projectId:c??null})},onError:ae=>{const ye=ae||"Session failed while contacting the AI.";C(!1),g(null),m({type:"error",sessionId:Pe,errorMessage:ye}),j(""),V.current=Pe,X({sessionId:Pe,status:"error",needsInput:!1,owningTabId:U,type:F,title:o,projectId:c??null}),_({sessionId:Pe,status:"error"})},onComplete:()=>{C(!1),V.current=null,_({sessionId:Pe,status:"complete"})},onConnectionStateChange:ae=>{C(ae==="reconnecting")}});O.current=Ve},[_,X,me,F,c,U,o]),se=()=>{y(null),f([]),v([]),j("")},fe=a.useCallback(async()=>{g(null),se(),C(!1),m({type:"loading"});try{const{sessionId:Pe}=await q(r,c);V.current=Pe,D(Pe),ge(Pe)}catch(Pe){C(!1),g(je(Pe)||`Failed to start ${Se.toLowerCase()} interview`),m({type:"initial"}),V.current=null,D(null)}},[ge,c,q,r,Se]),de=a.useCallback(async()=>{g(null),A(!0);try{await le(r,c),s(),m({type:"applied"})}catch(Pe){g(je(Pe)||`Failed to skip ${Se.toLowerCase()} interview`),A(!1)}},[s,c,le,r,Se]);a.useEffect(()=>{e&&d.type==="initial"&&P.current?.focus()},[e,d.type]),a.useEffect(()=>{if(!e||!u||d.type!=="initial")return;let Pe=!1;return di(u).then(Ve=>{if(Pe||!Ve)return;const ae=ya(Ve.conversationHistory);if(v(ae),D(Ve.id),f(ae.map(ye=>ye.response).filter(ye=>!!(ye&&typeof ye=="object"&&!Array.isArray(ye)))),Ve.status==="awaiting_input"&&Ve.currentQuestion)try{const ye=JSON.parse(Ve.currentQuestion);V.current=Ve.id,m({type:"question",sessionId:Ve.id,question:ye})}catch{g("Failed to restore session question.")}else if(Ve.status==="complete"&&Ve.result)try{const ye=JSON.parse(Ve.result);V.current=Ve.id,y(ye),m({type:"summary",sessionId:Ve.id,summary:ye})}catch{g("Failed to restore session result.")}else Ve.status==="generating"?(V.current=Ve.id,Ve.thinkingOutput&&j(Ve.thinkingOutput),m({type:"loading"}),ge(Ve.id)):Ve.status==="error"&&(V.current=Ve.id,g(null),m({type:"error",sessionId:Ve.id,errorMessage:Ve.error??"The session encountered an error."}))}).catch(()=>{Pe||g("Failed to resume session.")}),()=>{Pe=!0}},[ge,e,u,d.type]),a.useEffect(()=>{e||(C(!1),D(null))},[e]),a.useEffect(()=>{if(!(!e||!E)){if($.current!==E){$.current&&T($.current,U),I(E,U),$.current=E;return}!E&&$.current&&(T($.current,U),$.current=null)}},[I,T,e,E,U]),a.useEffect(()=>{if(!e||!E||$.current!==E)return;w(U);const Pe=setInterval(()=>{w(U)},3e4);return()=>{clearInterval(Pe)}},[w,e,E,U]),a.useEffect(()=>()=>{O.current?.close(),O.current=null,$.current&&(T($.current,U),$.current=null)},[T,U]);const xe=a.useCallback(()=>{O.current?.close(),O.current=null,n()},[n]),ie=a.useCallback(async()=>{O.current?.close(),O.current=null,se(),m({type:"initial"}),g(null),V.current=null,D(null),n()},[n]),Ee=a.useCallback(async Pe=>{if(d.type!=="question")return;const{sessionId:Ve}=d;g(null),f(ae=>[...ae,Pe]),v(ae=>[...ae,{question:d.question,response:Pe}]),m({type:"loading"}),j("");try{ge(Ve),await G(Ve,Pe,c,U)}catch(ae){O.current?.close(),O.current=null,g(je(ae)||"Failed to submit response"),m({type:"question",sessionId:Ve,question:d.question})}},[ge,c,G,U,d]),De=a.useCallback(async()=>{if(d.type==="summary"){g(null),A(!0);try{await ue(d.sessionId,b||void 0,c),s(),m({type:"applied"})}catch(Pe){g(je(Pe)||"Failed to apply interview results"),A(!1)}}},[ue,b,s,c,d]),qe=()=>d.type==="question"?Math.min(p.length+1,6):6,Qe=d.type==="loading"||d.type==="question"||d.type==="summary"||d.type==="error",Je=E?Y.get(E):null,it=!!(Je&&Je.tabId!==U&&!Je.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Pe=>Pe.target===Pe.currentTarget&&ie(),role:"dialog","aria-modal":"true","data-testid":"milestone-slice-interview-modal",children:t.jsxs("div",{className:"modal modal-lg planning-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(Xn,{size:20,className:"icon-triage"}),t.jsxs("h3",{children:["Plan ",Se,": ",o]})]}),t.jsxs("div",{className:"modal-header-actions",children:[Qe&&t.jsx("button",{className:"modal-send-to-background",onClick:xe,title:"Send to background","aria-label":"Send to background",children:t.jsx(Cr,{size:16})}),t.jsx("button",{className:"modal-close",onClick:ie,"aria-label":"Close",children:t.jsx(Ut,{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(Xn,{size:32,className:"icon-triage-lg"}),t.jsxs("h4",{children:["Refine ",Se," 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 fe(),children:[t.jsx(Xn,{size:16,className:"icon-mr-8"}),"Start Interview"]}),t.jsxs("button",{className:"btn planning-use-context-btn",onClick:()=>void de(),disabled:L,children:[L?t.jsx(rt,{size:16,className:"spin"}):null,"Use Mission Context"]}),t.jsx("button",{className:"btn",onClick:ie,children:"Cancel"})]})]}),d.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(rt,{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:()=>k(!R),type:"button",children:R?"Hide thinking":"Show thinking"}),R&&S&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:S})})]})]}),d.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[x.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Is,{entries:x}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:d.errorMessage}),t.jsx("div",{className:"ai-error-actions",children:t.jsx("button",{className:"btn",onClick:ie,children:"Cancel"})})]})]})}),d.type==="question"&&t.jsx(E1,{question:d.question,progress:qe(),historyEntries:x,onSubmit:Ee}),d.type==="summary"&&b&&t.jsx(_1,{summary:b,historyEntries:x,onSummaryChange:y,onApply:De,onCancel:ie,isApplying:L}),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(fn,{size:48,className:"icon-success"}),t.jsxs("h4",{children:[Se," 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 E1({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(Is,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3,4,5,6].map(m=>t.jsx("div",{className:`planning-progress-step ${m<=n?"active":""}`},m))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~6"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:l,onChange:m=>c(m.target.value),onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&l.trim()&&(m.preventDefault(),u())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(m=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:m.id,checked:r[e.id]===m.id,onChange:()=>o({[e.id]:m.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(m=>{const h=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:m.id,checked:h.includes(m.id),onChange:g=>{const p=g.target.checked?[...h,m.id]:h.filter(f=>f!==m.id);o({[e.id]:p})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!0?"selected":""}`,onClick:()=>o({[e.id]:!0}),children:[t.jsx(fn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(Ut,{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(Nr,{size:16,className:"icon-ml-4"})]})})]})}function _1({summary:e,historyEntries:n,onSummaryChange:s,onApply:i,onCancel:r,isApplying:o}){const[l,c]=a.useState(e),[u,d]=a.useState(!0),m=(h,g)=>{const p={...l,[h]:g};c(p),s(p)};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Is,{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(Vt,{size:16}):t.jsx(pn,{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(rt,{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)"}},qu={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)"}},Vu={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)"}},Wr={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)"}},Kr={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)"}},Gr={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)"}},Wu={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)"}},M1=3;function A1(e){return e==="completed"?"planned":e==="needs_update"?"needs_update":"not_started"}function Ku({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 Gu(e){return e?e.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const jl={title:"",description:"",status:"planning",autopilotEnabled:!1},kl={title:"",description:"",status:"planning",dependencies:[]},wl={title:"",description:"",status:"pending"},Nl={title:"",description:"",acceptanceCriteria:"",status:"defined"},R1=3600*1e3;function wo(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 T1(e){if(!e)return"healthy";const n=typeof e.lastErrorAt=="string"&&Date.now()-new Date(e.lastErrorAt).getTime()<=R1,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 P1(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 I1(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 Sl(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 Lp=["feature_triaged","feature_completed"],zp=["slice_activated","slice_completed","milestone_completed"],Fp=["mission_started","mission_paused","mission_resumed","mission_completed"],Op=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function Ju(e,n){switch(n){case"errors":return e==="error"||e==="warning";case"state_changes":return Fp.includes(e);case"tasks":return Lp.includes(e);case"slices":return zp.includes(e);case"autopilot":return Op.includes(e);default:return!0}}function $1(e){return e==="error"||e==="warning"?"mission-event__type--error":Fp.includes(e)?"mission-event__type--state":Lp.includes(e)?"mission-event__type--task":zp.includes(e)?"mission-event__type--slice":Op.includes(e)?"mission-event__type--autopilot":"mission-event__type--default"}function D1(e){return e.replace(/_/g," ")}function L1(e,n){return n?e==="watching"?`Watching since ${wo(n)}`:`Last activation ${wo(n)}`:null}function z1({isOpen:e,isInline:n=!1,onClose:s,addToast:i,projectId:r,onSelectTask:o,availableTasks:l=[],resumeSessionId:c,targetMissionId:u,milestoneSliceResumeSessionId:d,onMilestoneSliceResumeFetchError:m}){const h=n||e,[g,p]=a.useState([]),[f,x]=a.useState(null),[v,b]=a.useState(!0),[y,S]=a.useState(!1),[j,R]=a.useState(!1),[k,M]=a.useState(null),[C,L]=a.useState(jl),[A,P]=a.useState(!1),[O,V]=a.useState(new Set),[$,E]=a.useState(new Set),[D,U]=a.useState(null),[Y,X]=a.useState(kl),[_,I]=a.useState(!1),[T,w]=a.useState(null),[q,G]=a.useState(wl),[me,ue]=a.useState(!1),[le,Se]=a.useState(null),[F,ge]=a.useState(null),[se,fe]=a.useState(Nl),[de,xe]=a.useState(!1),[ie,Ee]=a.useState(null),[De,qe]=a.useState(null),[Qe,Je]=a.useState(""),[Ke,it]=a.useState(!1),[Pe,Ve]=a.useState([]),[ae,ye]=a.useState(void 0),te=ae??c,[Ae,Le]=a.useState(null),[pe,_e]=a.useState(null),[Fe,tt]=a.useState(null);a.useEffect(()=>{h&&te&&it(!0)},[h,te]),a.useEffect(()=>{if(!h||te)return;let B=!1;return td(r).then(we=>{if(B)return;const $e=we.filter(mt=>mt.type==="mission_interview"&&(mt.status==="awaiting_input"||mt.status==="error"));Ve($e)}).catch(we=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",we)}),()=>{B=!0}},[h,r,te]),a.useEffect(()=>{if(!h||!d)return;let B=!1;return di(d).then(we=>{if(!(B||!we))try{const $e=JSON.parse(we.inputPayload||"{}");$e.targetId&&$e.targetType&&Le({type:$e.targetType,id:$e.targetId,title:$e.targetTitle||we.title,resumeSessionId:d})}catch{Le({type:"milestone",id:"",title:we.title,resumeSessionId:d})}}).catch(we=>{B||(console.warn("[MissionManager] Failed to fetch session for milestone/slice resume:",we),m?.())}),()=>{B=!0}},[h,d,m]);const[Ne,oe]=a.useState(null),[Te,he]=a.useState(new Map),[Me,We]=a.useState(null),[Re,ot]=a.useState({title:"",assertion:"",status:"pending"}),[J,ce]=a.useState(!1),[ve,Xe]=a.useState(null),[ee,Ge]=a.useState(new Map),[ct,vt]=a.useState(new Set),[bt,ft]=a.useState(new Set),[gt,_t]=a.useState(null),[Rt,Ft]=a.useState(new Map),[wt,At]=a.useState(null),[qt,zt]=a.useState(null),[Wt,Ot]=a.useState(!0),[Nt,Mt]=a.useState(new Set),[Ct,Gt]=a.useState(new Map),[Et,H]=a.useState(null),[be,re]=a.useState(new Map),[N,W]=a.useState(null),[Ie,nt]=a.useState(new Map),[yt,Pt]=a.useState(new Map),[Tt,tn]=a.useState("structure"),[nn,Ln]=a.useState([]),Jt=a.useRef([]),Rn=a.useRef([]),ke=a.useRef(null),at=a.useRef(null),gn=a.useRef("structure"),Tn=a.useRef("all"),[Pn,Nn]=a.useState(!1),[es,Sn]=a.useState(0),[Yt,Q]=a.useState("all"),[ze,Ye]=a.useState(new Set),et=a.useRef(null),dt=a.useRef(null);Rn.current=g,ke.current=f,at.current=wt,gn.current=Tt,Tn.current=Yt;const St=a.useCallback((B="auto")=>{const we=dt.current;if(we&&typeof we.scrollIntoView=="function"){we.scrollIntoView({block:"end",behavior:B});return}const $e=et.current;$e&&($e.scrollTop=$e.scrollHeight)},[]),It=a.useCallback(()=>{const B=et.current;return B?B.scrollHeight-B.scrollTop-B.clientHeight<=100:!0},[]),kn=a.useCallback(async B=>{if(B.length===0){Pt(new Map);return}const we=await Jj(r);Pt($e=>{const mt=new Map($e);for(const[un,Dt]of Object.entries(we))P1(Dt)&&mt.set(un,Dt);return mt})},[r]),sn=a.useCallback(async()=>{try{b(!0);const B=await qj(r);p(B),kn(B)}catch(B){i(je(B)||"Failed to load missions","error")}finally{b(!1)}},[i,r,kn]),jt=a.useCallback(async B=>{try{S(!0);const we=await hp(B,r);if(x(we),we.milestones.length>0){const $e=we.milestones[0].id;At($e),Ot(!0),V(new Set([$e])),cl($e,r).then(mt=>{he(un=>{const Dt=new Map(un);return Dt.set($e,mt),Dt})}).catch(()=>{}),dl($e,r).then(mt=>{Ft(un=>{const Dt=new Map(un);return Dt.set($e,mt),Dt})}).catch(()=>{}),we.milestones[0].slices.length>0&&E(new Set([we.milestones[0].slices[0].id]))}else At(null),zt(null)}catch(we){i(je(we)||"Failed to load mission details","error")}finally{S(!1)}},[i,r]);a.useEffect(()=>{if(!h||!wt){zt(null);return}let B=!1;return zt(null),su(wt,r).then(we=>{if(!B){if(!Sl(we)){zt(null);return}zt(we),Ft($e=>{const mt=new Map($e);return mt.set(wt,we.rollup),mt})}}).catch(()=>{B||zt(null)}),()=>{B=!0}},[h,wt,r]),a.useEffect(()=>{Ot(!0)},[wt]);const os=a.useCallback(B=>{!B||B!==at.current||su(B,r).then(we=>{at.current!==B||!Sl(we)||(zt(we),Ft($e=>{const mt=new Map($e);return mt.set(B,we.rollup),mt}))}).catch(()=>{})},[r]),ws=a.useCallback(async(B,we)=>{const $e=we?.append??!1,mt=$e?Jt.current.length:0;$e||(Nn(!0),Ye(new Set));try{const un=await Gj(B,{limit:50,offset:mt,eventType:void 0},r),Dt=un.events.filter(Xt=>Ju(Xt.eventType,Yt));Ln(Xt=>{if(!$e)return Dt;const Ue=new Set(Xt.map(pt=>pt.id)),He=[...Xt];for(const pt of Dt)Ue.has(pt.id)||He.push(pt);return He}),Sn(un.total),$e||requestAnimationFrame(()=>{St("auto")})}catch(un){i(je(un)||"Failed to load mission activity","error")}finally{$e||Nn(!1)}},[i,Yt,r,St]);a.useEffect(()=>{Jt.current=nn},[nn]),a.useEffect(()=>{h&&(sn(),x(null),At(null),zt(null),Ln([]),Sn(0),tn("structure"),Q("all"),Ye(new Set))},[h,sn]);const Ns=a.useRef(null);a.useEffect(()=>{h&&u&&Ns.current!==u&&g.length>0&&(Ns.current=u,jt(u))},[h,u,g,jt]),a.useEffect(()=>{h||(Ns.current=null)},[h]),a.useEffect(()=>{!h||!f||Tt!=="activity"||ws(f.id)},[Tt,h,ws,f,Yt]),a.useEffect(()=>{if(!h||typeof EventSource>"u")return;const B=new URLSearchParams;r&&B.set("projectId",r);const we=`/api/events${B.size>0?`?${B.toString()}`:""}`,$e=()=>{kn(Rn.current)},mt=Jn=>{$e();const wn=Jn;if(wn.data)try{const Bt=JSON.parse(wn.data);Bt?.id&&p(Pi=>Pi.map(_s=>_s.id===Bt.id?{..._s,...Bt}:_s))}catch{}ke.current&&jt(ke.current.id)},un=Jn=>{$e(),ke.current&&jt(ke.current.id)},Dt=()=>{$e(),ke.current&&jt(ke.current.id)},Xt=Jn=>{$e(),ke.current&&jt(ke.current.id)},Ue=Jn=>{const wn=Jn;if(wn.data)try{const Bt=JSON.parse(wn.data);Bt&&Bt.featureId&&(_n(Bt.featureId),ai(Bt.featureId),Bt.milestoneId&&os(Bt.milestoneId))}catch{}},He=Jn=>{const wn=Jn;if(wn.data)try{const Bt=JSON.parse(wn.data);Bt&&Bt.featureId&&(_n(Bt.featureId),ai(Bt.featureId),Bt.milestoneId&&os(Bt.milestoneId),ke.current&&jt(ke.current.id))}catch{}},pt=Jn=>{const wn=Jn;if(wn.data)try{const Bt=JSON.parse(wn.data);Bt&&Bt.milestoneId&&(On(Bt.milestoneId),os(Bt.milestoneId))}catch{}},mn=Jn=>{const wn=Jn;if(wn.data)try{const Bt=JSON.parse(wn.data);Bt&&Bt.milestoneId&&(rn(Bt.milestoneId),On(Bt.milestoneId),os(Bt.milestoneId))}catch{}};return qs(we,{events:{"mission:updated":mt,"slice:updated":un,"feature:updated":Dt,"milestone:updated":Xt,"mission:event":Jn=>{$e();const wn=ke.current;if(!wn||gn.current!=="activity")return;const Bt=It(),Pi=Jn;if(Pi.data)try{const _s=JSON.parse(Pi.data);if(!I1(_s)||_s.missionId!==wn.id||!Ju(_s.eventType,Tn.current))return;Ln(oi=>{const il=oi.filter(al=>al.id!==_s.id);return[_s,...il].slice(0,100)}),Sn(oi=>oi+1),Bt&&requestAnimationFrame(()=>{const oi=et.current;oi&&(oi.scrollTop=0)})}catch{}},"validator-run:started":Ue,"validator-run:completed":He,"milestone:validation:updated":pt,"assertion:created":mn,"assertion:updated":mn,"assertion:deleted":mn,"assertion:linked":mn,"assertion:unlinked":mn,"fix-feature:created":Jn=>{const wn=Jn;if(wn.data)try{const Bt=JSON.parse(wn.data);if(Bt&&Bt.sourceFeatureId){_n(Bt.sourceFeatureId);const Pi=Bt?.feature?.sliceId,_s=ke.current;if(Pi&&_s){const oi=_s.milestones.find(il=>il.slices.some(al=>al.id===Pi));oi&&os(oi.id)}ke.current&&jt(ke.current.id)}}catch{}}}})},[h,It,jt,kn,r,os]);const $s=a.useCallback(()=>{R(!0),M(null),L(jl)},[]),ii=a.useCallback(B=>{M(B.id),R(!1),L({title:B.title,description:B.description||"",status:B.status,autopilotEnabled:B.autopilotEnabled??!1})},[]),Ds=a.useCallback(()=>{M(null),R(!1),L(jl)},[]),Ls=a.useCallback(async()=>{if(!C.title.trim()){i("Mission title is required","error");return}try{if(P(!0),j)await Vj({title:C.title.trim(),description:C.description.trim()||void 0,autopilotEnabled:C.autopilotEnabled},r),i("Mission created","success");else if(k){const B={title:C.title.trim(),description:C.description.trim()||void 0,status:C.status,autopilotEnabled:C.autopilotEnabled};C.autopilotEnabled&&(B.autoAdvance=!0),await Wj(k,B,r),i("Mission updated","success"),f?.id===k&&await jt(k)}await sn(),Ds()}catch(B){i(je(B)||"Failed to save mission","error")}finally{P(!1)}},[C,j,k,i,sn,jt,f,Ds,r]),Ei=a.useCallback(async B=>{try{await Kj(B,r),i("Mission deleted","success"),f?.id===B&&x(null),await sn(),oe(null)}catch(we){i(je(we)||"Failed to delete mission","error")}},[i,sn,f,r]),gi=a.useCallback(()=>{I(!0),U(null),X(kl)},[]),ut=a.useCallback(B=>{U(B.id),I(!1),X({title:B.title,description:B.description||"",status:B.status,dependencies:B.dependencies})},[]),bn=a.useCallback(()=>{U(null),I(!1),X(kl)},[]),ps=a.useCallback(async()=>{if(!Y.title.trim()){i("Milestone title is required","error");return}try{P(!0),_&&f?(await Yj(f.id,{title:Y.title.trim(),description:Y.description.trim()||void 0,dependencies:Y.dependencies},r),i("Milestone created","success")):D&&(await Qj(D,{title:Y.title.trim(),description:Y.description.trim()||void 0,status:Y.status,dependencies:Y.dependencies},r),i("Milestone updated","success")),await jt(f.id),bn()}catch(B){i(je(B)||"Failed to save milestone","error")}finally{P(!1)}},[Y,_,D,f,i,jt,bn,C.title,r]),ne=a.useCallback(async B=>{try{await Xj(B,r),i("Milestone deleted","success"),await jt(f.id),oe(null)}catch(we){i(je(we)||"Failed to delete milestone","error")}},[i,jt,f,r]),Ce=a.useCallback(B=>{At(B),Ot(!0),V(we=>{const $e=new Set(we);return!$e.has(B)?($e.add(B),cl(B,r).then(un=>{he(Dt=>{const Xt=new Map(Dt);return Xt.set(B,un),Xt})}).catch(()=>{}),dl(B,r).then(un=>{Ft(Dt=>{const Xt=new Map(Dt);return Xt.set(B,un),Xt})}).catch(()=>{})):$e.delete(B),$e})},[r]),Ze=a.useCallback(B=>{Se(B),ue(!0),w(null),G(wl)},[]),xt=a.useCallback(B=>{w(B.id),ue(!1),G({title:B.title,description:B.description||"",status:B.status})},[]),ht=a.useCallback(()=>{w(null),ue(!1),Se(null),G(wl)},[]),xn=a.useCallback(async()=>{if(!q.title.trim()){i("Slice title is required","error");return}try{P(!0),me&&le?(await Zj(le,{title:q.title.trim(),description:q.description.trim()||void 0},r),i("Slice created","success")):T&&(await ek(T,{title:q.title.trim(),description:q.description.trim()||void 0,status:q.status},r),i("Slice updated","success")),await jt(f.id),ht()}catch(B){i(je(B)||"Failed to save slice","error")}finally{P(!1)}},[q,me,T,le,f,i,jt,ht,r]),Qt=a.useCallback(async B=>{try{await tk(B,r),i("Slice deleted","success"),await jt(f.id),oe(null)}catch(we){i(je(we)||"Failed to delete slice","error")}},[i,jt,f,r]),an=a.useCallback(async B=>{try{await nk(B,r),i("Slice activated","success"),await jt(f.id)}catch(we){i(je(we)||"Failed to activate slice","error")}},[i,jt,f,r]),dn=a.useCallback(B=>{E(we=>{const $e=new Set(we);return $e.has(B)?$e.delete(B):$e.add(B),$e})},[]),In=a.useCallback(B=>{Ee(B),xe(!0),ge(null),fe(Nl)},[]),Vn=a.useCallback(B=>{ge(B.id),xe(!1),fe({title:B.title,description:B.description||"",acceptanceCriteria:B.acceptanceCriteria||"",status:B.status})},[]),Wn=a.useCallback(()=>{ge(null),xe(!1),Ee(null),fe(Nl)},[]),Cn=a.useCallback(async()=>{if(!se.title.trim()){i("Feature title is required","error");return}try{P(!0),de&&ie?(await sk(ie,{title:se.title.trim(),description:se.description.trim()||void 0,acceptanceCriteria:se.acceptanceCriteria.trim()||void 0},r),i("Feature created","success")):F&&(await ik(F,{title:se.title.trim(),description:se.description.trim()||void 0,acceptanceCriteria:se.acceptanceCriteria.trim()||void 0,status:se.status},r),i("Feature updated","success")),await jt(f.id),Wn()}catch(B){i(je(B)||"Failed to save feature","error")}finally{P(!1)}},[se,de,F,ie,f,i,jt,Wn,r]),Kn=a.useCallback(async B=>{try{await ak(B,r),i("Feature deleted","success"),await jt(f.id),oe(null)}catch(we){i(je(we)||"Failed to delete feature","error")}},[i,jt,f,r]),zn=a.useCallback(async()=>{if(!De||!Qe.trim()){i("Task ID is required","error");return}try{await rk(De,Qe.trim(),r),i("Feature linked to task","success"),await jt(f.id),qe(null),Je("")}catch(B){i(je(B)||"Failed to link feature to task","error")}},[De,Qe,i,jt,f,r]),fs=a.useCallback(async B=>{try{await ok(B,r),i("Feature unlinked from task","success"),await jt(f.id)}catch(we){i(je(we)||"Failed to unlink feature","error")}},[i,jt,f,r]),vn=a.useCallback(async B=>{try{P(!0),await lk(B,void 0,void 0,r),i("Feature triaged — task created","success"),await jt(f.id)}catch(we){i(je(we)||"Failed to triage feature","error")}finally{P(!1)}},[i,jt,f,r]),Fn=a.useCallback(async B=>{tt(B);try{const we=await Lk(B,r);_e({featureId:B,enrichedDescription:we.description})}catch{await vn(B)}finally{tt(null)}},[vn,r]),ls=a.useCallback(async()=>{pe&&(_e(null),await vn(pe.featureId))},[vn,pe]),Ss=a.useCallback(()=>{_e(null)},[]),ts=a.useCallback(async B=>{try{P(!0);const we=await ck(B,r);i(`Triaged ${we.count} feature${we.count!==1?"s":""}`,"success"),await jt(f.id)}catch(we){i(je(we)||"Failed to triage slice features","error")}finally{P(!1)}},[i,jt,f,r]),rn=a.useCallback(async B=>{try{const we=await cl(B,r);he($e=>{const mt=new Map($e);return mt.set(B,we),mt})}catch{}},[r]),On=a.useCallback(async B=>{try{const we=await dl(B,r);Ft($e=>{const mt=new Map($e);return mt.set(B,we),mt})}catch{}},[r]),zs=a.useCallback(async B=>{if(!Re.title.trim()||!Re.assertion.trim()){i("Title and assertion text are required","error");return}try{P(!0),await dk(B,{title:Re.title.trim(),assertion:Re.assertion.trim(),status:Re.status},r),i("Assertion created","success"),await rn(B),await On(B),ce(!1),ot({title:"",assertion:"",status:"pending"})}catch(we){i(je(we)||"Failed to create assertion","error")}finally{P(!1)}},[Re,i,rn,On,r]),Xo=a.useCallback(B=>{We(B.id),ot({title:B.title,assertion:B.assertion,status:B.status})},[]),_i=a.useCallback(()=>{We(null),ce(!1),ot({title:"",assertion:"",status:"pending"})},[]),Dr=a.useCallback(async(B,we)=>{if(!Re.title.trim()||!Re.assertion.trim()){i("Title and assertion text are required","error");return}try{P(!0),await uk(B,{title:Re.title.trim(),assertion:Re.assertion.trim(),status:Re.status},r),i("Assertion updated","success"),await rn(we),await On(we),_i()}catch($e){i(je($e)||"Failed to update assertion","error")}finally{P(!1)}},[Re,i,rn,On,_i,r]),Fs=a.useCallback(async B=>{try{const we=await pk(B,r);Ge($e=>{const mt=new Map($e);return mt.set(B,we),mt})}catch{}},[r]),Lr=a.useCallback(async B=>{const we=ve!==B;Xe($e=>$e===B?null:B),we&&await Fs(B)},[ve,Fs]),zr=a.useCallback(B=>{Xe(B),Fs(B),requestAnimationFrame(()=>{const we=document.querySelector(`[data-mission-assertion-id="${B}"]`);we instanceof HTMLElement&&typeof we.scrollIntoView=="function"&&we.scrollIntoView({behavior:"smooth",block:"center"})})},[Fs]),Fr=a.useCallback(async(B,we)=>{try{vt($e=>new Set($e).add(we)),await mk(B,we,r),i("Feature linked to assertion","success"),await Fs(we),_t(null)}catch($e){i(je($e)||"Failed to link feature","error")}finally{vt($e=>{const mt=new Set($e);return mt.delete(we),mt})}},[i,Fs,r]),Gn=a.useCallback(async(B,we)=>{const $e=`${B}-${we}`;try{ft(mt=>new Set(mt).add($e)),await hk(B,we,r),i("Feature unlinked from assertion","success"),await Fs(we)}catch(mt){i(je(mt)||"Failed to unlink feature","error")}finally{ft(mt=>{const un=new Set(mt);return un.delete($e),un})}},[i,Fs,r]),Ia=a.useCallback(async B=>{try{Mt($e=>new Set($e).add(B)),await fk(B,r),i("Validation triggered","success");const we=await iu(B,r);Gt($e=>{const mt=new Map($e);return mt.set(B,we),mt})}catch(we){i(je(we)||"Failed to trigger validation","error")}finally{Mt(we=>{const $e=new Set(we);return $e.delete(B),$e})}},[i,r]),_n=a.useCallback(async B=>{try{const we=await iu(B,r);Gt($e=>{const mt=new Map($e);return mt.set(B,we),mt})}catch{}},[r]),ai=a.useCallback(async B=>{try{const we=await gk(B,{limit:10},r);re($e=>{const mt=new Map($e);return mt.set(B,we),mt})}catch{}},[r]),Mi=a.useCallback(B=>{const we=ke.current;if(we){for(const $e of we.milestones)for(const mt of $e.slices)if(mt.features.find(Dt=>Dt.id===B)){V(Dt=>{const Xt=new Set(Dt);return Xt.add($e.id),Xt}),E(Dt=>{const Xt=new Set(Dt);return Xt.add(mt.id),Xt}),H(B),At($e.id),_n(B),ai(B),requestAnimationFrame(()=>{const Dt=document.querySelector(`[data-mission-feature-id="${B}"]`);Dt instanceof HTMLElement&&typeof Dt.scrollIntoView=="function"&&Dt.scrollIntoView({behavior:"smooth",block:"center"})});return}}},[_n,ai]),$a=a.useCallback(async B=>{try{const we=await xk(B,r);nt($e=>{const mt=new Map($e);return mt.set(B,we),mt})}catch{}},[r]),Qi=a.useCallback(async B=>{Et===B?H(null):(H(B),await _n(B),await ai(B))},[Et,_n,ai]),Zo=a.useCallback(async B=>{N===B?W(null):(W(B),await $a(B))},[N,$a]),Da=a.useCallback(async B=>{try{await bk(B,r),i("Mission resumed","success"),await jt(B),sn()}catch(we){i(je(we)||"Failed to resume mission","error")}},[i,jt,sn,r]),Z=a.useCallback(async B=>{try{const $e=(await vk(B,r)).pausedTaskIds?.length??0;i(`Mission stopped (${$e} task${$e!==1?"s":""} paused)`,"success"),await jt(B),sn()}catch(we){i(je(we)||"Failed to stop mission","error")}},[i,jt,sn,r]),Be=a.useCallback(async B=>{try{await yk(B,r),i("Mission started — first slice activated","success"),await jt(B),sn()}catch(we){i(je(we)||"Failed to start mission","error")}},[i,jt,sn,r]),lt=a.useCallback(async(B,we)=>{try{await jk(B,{enabled:we},r),i(we?"Autopilot enabled":"Autopilot disabled","success"),await jt(B),sn()}catch($e){i(je($e)||"Failed to update autopilot","error")}},[i,jt,sn,r]),$t=a.useCallback(B=>{tn("structure"),At(null),zt(null),Ln([]),Sn(0),Q("all"),Ye(new Set),jt(B.id)},[jt]),Vs=a.useCallback(()=>{x(null),At(null),zt(null),tn("structure"),Ln([]),Sn(0),Q("all"),Ye(new Set),sn()},[sn]),gs=nn.length<es,xi=f?.autopilotState??"inactive",La=xi==="watching"||xi==="activating",Or=L1(xi,f?.lastAutopilotActivityAt),Xi=a.useMemo(()=>!qt||!wt||!Sl(qt)?null:qt.rollup.milestoneId===wt?qt:null,[wt,qt]),el=a.useMemo(()=>{const B=new Map;for(const we of Xi?.validationTelemetry.validationRounds??[]){const $e=B.get(we.featureId);(!$e||we.startedAt>$e.startedAt)&&B.set(we.featureId,we)}return B},[Xi]),tl=a.useCallback(()=>{!f||Pn||!gs||ws(f.id,{append:!0})},[Pn,gs,ws,f]),nl=a.useCallback(B=>{Ye(we=>{const $e=new Set(we);return $e.has(B)?$e.delete(B):$e.add(B),$e})},[]),Ai=a.useCallback(B=>{B.key==="Enter"&&!B.shiftKey&&(B.preventDefault(),Ls())},[Ls]),Zi=a.useCallback(B=>{B.key==="Enter"&&!B.shiftKey&&(B.preventDefault(),ps())},[ps]),Ri=a.useCallback(B=>{B.key==="Enter"&&!B.shiftKey&&(B.preventDefault(),xn())},[xn]),ea=a.useCallback(B=>{B.key==="Enter"&&!B.shiftKey&&(B.preventDefault(),Cn())},[Cn]),Rd=a.useRef(null);if(a.useEffect(()=>{if(!h)return;const B=we=>{we.key==="Escape"&&s()};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[h,s]),!h)return null;const sl=t.jsxs("div",{ref:Rd,className:`mission-manager${n?" mission-manager--inline":""}`,role:n?void 0:"dialog","aria-modal":n?void 0:!0,"aria-label":n?void 0:"Mission Manager","data-testid":"mission-manager-dialog",children:[t.jsxs("div",{className:`mission-manager__header${n?" mission-manager__header--inline":""}`,children:[t.jsxs("div",{className:"mission-manager__header-title",children:[f?t.jsx("button",{className:"mission-manager__back-btn",onClick:Vs,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:t.jsx(To,{size:18})}):null,t.jsx(us,{size:18,className:"mission-manager__header-icon"}),t.jsx("h2",{className:"mission-manager__title",children:f?f.title:"Missions"})]}),!n&&t.jsx("button",{className:"modal-close",onClick:s,title:"Close","aria-label":"Close Mission Manager","data-testid":"mission-close-btn",children:t.jsx(Ut,{size:18})})]}),t.jsx("div",{className:"mission-manager__body",children:v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(rt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(rt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):f?t.jsxs("div",{className:"mission-detail",children:[t.jsxs("div",{className:"mission-detail__header",children:[t.jsxs("div",{className:"mission-detail__title-row",children:[t.jsxs("div",{className:"mission-detail__title-text",children:[La&&t.jsx("span",{className:"mission-detail__autopilot-dot",title:"Autopilot watching"}),t.jsx("h3",{className:"mission-detail__title",children:f.title})]}),t.jsx("span",{className:"mission-status-badge",style:{backgroundColor:(Ua[f.status]||Ua.planning).bg,color:(Ua[f.status]||Ua.planning).text},children:f.status})]}),f.description&&t.jsx("p",{className:"mission-detail__description",children:f.description}),t.jsx("div",{className:"mission-detail__meta",children:t.jsxs("span",{className:"mission-detail__meta-info",children:[f.milestones.length," milestones"]})}),t.jsxs("div",{className:"mission-detail__autopilot",children:[t.jsxs("div",{className:"mission-detail__autopilot-toggle",children:[t.jsxs("label",{className:"mission-toggle","data-testid":"mission-autopilot-toggle",children:[t.jsx("input",{type:"checkbox",checked:f.autopilotEnabled??!1,onChange:B=>lt(f.id,B.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(Bn,{size:14,className:"mission-detail__autopilot-icon"}),"Autopilot"]})]}),t.jsxs("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(Kr[xi]||Kr.inactive).bg,color:(Kr[xi]||Kr.inactive).text},"data-testid":"autopilot-state-badge",children:[La&&t.jsx("span",{className:"mission-detail__autopilot-pulse"}),xi]})]}),Or&&t.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:Or})]}),t.jsxs("div",{className:"mission-detail__actions",children:[f.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Z(f.id),title:"Stop mission","aria-label":"Stop mission",children:t.jsx(bs,{size:14})}),f.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Da(f.id),title:"Resume mission","aria-label":"Resume mission",children:t.jsx(jn,{size:14})}),f.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Be(f.id),title:"Start mission","aria-label":"Start mission",children:t.jsx(jn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>ii(f),title:"Edit mission","aria-label":"Edit mission",children:t.jsx(ss,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>oe({type:"mission",id:f.id}),title:"Delete mission","aria-label":"Delete mission",children:t.jsx(Zt,{size:14})})]})]}),k===f.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:C.title,onChange:B=>L({...C,title:B.target.value}),onKeyDown:Ai,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:C.description,onChange:B=>L({...C,description:B.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:C.status,onChange:B=>L({...C,status:B.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:C.autopilotEnabled,onChange:B=>L({...C,autopilotEnabled:B.target.checked})}),t.jsx(Bn,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Ls,disabled:A,children:[A?t.jsx(rt,{size:14,className:"spinner"}):t.jsx($n,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Ds,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-detail__tabs",role:"tablist","aria-label":"Mission detail tabs",children:[t.jsx("button",{className:`mission-btn ${Tt==="structure"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>tn("structure"),role:"tab","aria-selected":Tt==="structure","data-testid":"mission-tab-structure",children:"Structure"}),t.jsxs("button",{className:`mission-btn ${Tt==="activity"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>tn("activity"),role:"tab","aria-selected":Tt==="activity","data-testid":"mission-tab-activity",children:["Activity (",es,")"]})]}),Tt==="structure"?t.jsxs("div",{className:"mission-detail__milestones",children:[f.milestones.map(B=>{const we=Xi?.rollup.milestoneId===B.id?Xi:null,$e=we?.rollup??Rt.get(B.id),mt=we?.validationTelemetry.validationRounds??[],un=we?.fixFeatures??[],Dt=Wu[$e?.state??"not_started"]??Wu.not_started,Xt=$e&&($e.state==="blocked"||$e.state==="failed")?we?.validationTelemetry.validationRounds.find(Ue=>Ue.blockedReason)?.blockedReason:void 0;return t.jsxs("div",{className:"mission-milestone",children:[t.jsxs("div",{className:"mission-milestone__header",onClick:()=>Ce(B.id),children:[t.jsx("button",{className:"mission-milestone__expand",children:O.has(B.id)?t.jsx(Vt,{size:16}):t.jsx(pn,{size:16})}),t.jsx(Hi,{size:16,className:"mission-milestone__icon"}),t.jsx("span",{className:"mission-milestone__title",children:B.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:qu[B.status].bg,color:qu[B.status].text},children:B.status}),t.jsxs("span",{className:"mission-milestone__count",children:[B.slices.length," slices"]}),t.jsx(Ku,{state:A1(B.interviewState)}),$e&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Dt.bg,color:Dt.text},title:"Validation state",children:Gu($e.state)}),$e.totalAssertions>0&&t.jsx("div",{className:"mission-milestone__coverage-bar",title:`${$e.passedAssertions??0} of ${$e.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-milestone__coverage-bar-fill",style:{width:`${($e.passedAssertions??0)/$e.totalAssertions*100}%`,backgroundColor:($e.passedAssertions??0)===$e.totalAssertions?"var(--color-success)":"var(--color-warning)"}})})]}),B.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Le({type:"milestone",id:B.id,title:B.title}),title:"Plan milestone","aria-label":"Plan milestone",children:t.jsx(Ui,{size:14})}),t.jsxs("div",{className:"mission-milestone__actions",onClick:Ue=>Ue.stopPropagation(),children:[t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ze(B.id),title:"Add slice",children:t.jsx(en,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>ut(B),title:"Edit milestone",children:t.jsx(ss,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>oe({type:"milestone",id:B.id}),title:"Delete milestone",children:t.jsx(Zt,{size:14})})]})]}),O.has(B.id)&&t.jsxs("div",{className:"mission-milestone__body",children:[(_||D===B.id)&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:Y.title,onChange:Ue=>X({...Y,title:Ue.target.value}),onKeyDown:Zi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:Y.description,onChange:Ue=>X({...Y,description:Ue.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:ps,disabled:A,children:[A?t.jsx(rt,{size:14,className:"spinner"}):t.jsx($n,{size:14}),D?"Update":"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bn,children:"Cancel"})]})]}),we&&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:[we.validationTelemetry.totalRuns," rounds",we.validationTelemetry.lastValidatorStatus?` · Last ${we.validationTelemetry.lastValidatorStatus}`:""]})]}),Xt&&t.jsxs("div",{className:"mission-blocked-reason",children:[t.jsx("strong",{children:"Blocked reason:"})," ",Xt]}),mt.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(Ue=>!Ue),title:Wt?"Hide validation rounds":"Show validation rounds",children:[Wt?t.jsx(Vt,{size:12}):t.jsx(pn,{size:12}),"Validation rounds (",mt.length,")"]}),Wt&&t.jsx("div",{className:"mission-validation-rounds__list",children:mt.map(Ue=>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--${Ue.validatorStatus}`,children:Ue.validatorStatus}),t.jsx("span",{className:"mission-validation-round__feature",children:Ue.featureTitle}),t.jsxs("span",{className:"mission-validation-round__attempts",children:["impl #",Ue.implementationAttempt," · reviewer #",Ue.validatorAttempt]})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),Ue.failedAssertionIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Ue.failedAssertionIds.map(He=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>zr(He),title:`Jump to assertion ${He}`,children:He},`${Ue.roundId}-${He}`))}):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:"}),Ue.generatedFixFeatureIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Ue.generatedFixFeatureIds.map(He=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Mi(He),title:`Jump to fix feature ${He}`,children:He},`${Ue.roundId}-${He}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),Ue.blockedReason&&t.jsx("div",{className:"mission-validation-round__blocked-reason",children:Ue.blockedReason})]},Ue.roundId))})]}),un.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:un.map(Ue=>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:()=>Mi(Ue.id),title:`Jump to feature ${Ue.id}`,children:Ue.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Wr[Ue.status].bg,color:Wr[Ue.status].text},children:Ue.status}),Ue.loopState&&t.jsx("span",{className:`mission-loop-state mission-loop-state--${Ue.loopState}`,children:Ue.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:()=>Mi(Ue.sourceFeatureId),title:`Jump to source feature ${Ue.sourceFeatureId}`,children:Ue.sourceFeatureId}),t.jsx("span",{children:"Run:"}),t.jsx("span",{className:"mission-fix-feature__run",children:Ue.runId})]}),Ue.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:Ue.failedAssertionIds.map(He=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>zr(He),title:`Jump to assertion ${He}`,children:He},`${Ue.id}-${He}`))})]})]},Ue.id))})]})]}),t.jsxs("div",{className:"mission-slices",children:[B.slices.map(Ue=>t.jsxs("div",{className:"mission-slice",children:[t.jsxs("div",{className:"mission-slice__header",onClick:()=>dn(Ue.id),children:[t.jsx("button",{className:"mission-slice__expand",children:$.has(Ue.id)?t.jsx(Vt,{size:16}):t.jsx(pn,{size:16})}),t.jsx(yc,{size:16,className:"mission-slice__icon"}),t.jsx("span",{className:"mission-slice__title",children:Ue.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Vu[Ue.status].bg,color:Vu[Ue.status].text},children:Ue.status}),t.jsxs("span",{className:"mission-slice__count",children:[Ue.features?.length||0," features"]}),t.jsx(Ku,{state:Ue.planState??"not_started"}),Ue.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Le({type:"slice",id:Ue.id,title:Ue.title}),title:"Plan slice","aria-label":"Plan slice",children:t.jsx(Ui,{size:14})}),t.jsxs("div",{className:"mission-slice__actions",onClick:He=>He.stopPropagation(),children:[Ue.status==="pending"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>an(Ue.id),title:"Activate slice",children:t.jsx(jn,{size:14})}),Ue.status==="active"&&Ue.features?.some(He=>He.status==="defined")&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>ts(Ue.id),title:"Triage all features",disabled:A,children:A?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Bn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>In(Ue.id),title:"Add feature",children:t.jsx(en,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>xt(Ue),title:"Edit slice",children:t.jsx(ss,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>oe({type:"slice",id:Ue.id}),title:"Delete slice",children:t.jsx(Zt,{size:14})})]})]}),$.has(Ue.id)&&t.jsxs("div",{className:"mission-slice__body",children:[me&&le===B.id&&!T&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:q.title,onChange:He=>G({...q,title:He.target.value}),onKeyDown:Ri,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:q.description,onChange:He=>G({...q,description:He.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:xn,disabled:A,children:[A?t.jsx(rt,{size:14,className:"spinner"}):t.jsx($n,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ht,children:"Cancel"})]})]}),T===Ue.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:q.title,onChange:He=>G({...q,title:He.target.value}),onKeyDown:Ri,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:q.description,onChange:He=>G({...q,description:He.target.value}),rows:2}),t.jsxs("select",{value:q.status,onChange:He=>G({...q,status:He.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:xn,disabled:A,children:[A?t.jsx(rt,{size:14,className:"spinner"}):t.jsx($n,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ht,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-features",children:[Ue.features?.map(He=>t.jsxs("div",{className:"mission-feature","data-mission-feature-id":He.id,children:[t.jsxs("div",{className:"mission-feature__header",children:[t.jsx("button",{className:"mission-feature__expand",onClick:()=>Qi(He.id),title:Et===He.id?"Collapse details":"Expand to show run history",children:Et===He.id?t.jsx(Vt,{size:14}):t.jsx(pn,{size:14})}),t.jsx(hc,{size:14,className:"mission-feature__icon"}),t.jsx("span",{className:"mission-feature__title",children:He.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Wr[He.status].bg,color:Wr[He.status].text},children:He.status}),He.loopState&&He.loopState!=="idle"&&t.jsxs("span",{className:`mission-loop-state mission-loop-state--${He.loopState}`,title:`Loop state: ${He.loopState}`,children:[He.loopState==="implementing"&&"⏳",He.loopState==="validating"&&"🔄",He.loopState==="needs_fix"&&"🔧",He.loopState==="passed"&&"✅",He.loopState==="blocked"&&"🚫"]}),He.generatedFromFeatureId&&t.jsx("button",{className:"mission-feature__lineage",onClick:()=>Mi(He.generatedFromFeatureId),title:`Generated from feature: ${He.generatedFromFeatureId}`,children:"🔗 Fix"}),(He.loopState==="validating"||He.loopState==="needs_fix")&&(()=>{const pt=Ct.get(He.id),mn=el.get(He.id),Es=pt?.implementationAttemptCount??mn?.implementationAttempt??He.implementationAttemptCount??0,Ti=pt?.retryBudgetRemaining??Math.max(0,M1-Es);return t.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",Es," · ",Ti," ",Ti===1?"retry":"retries"," left"]})})(),He.loopState==="implementing"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>Ia(He.id),title:"Validate feature",disabled:Nt.has(He.id),children:Nt.has(He.id)?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Xn,{size:14})}),He.taskId&&t.jsx("span",{className:"mission-feature__task-link",onClick:()=>o?.(He.taskId),title:"Click to view task",children:He.taskId}),t.jsxs("div",{className:"mission-feature__actions",children:[He.status==="defined"&&!He.taskId&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Fn(He.id),title:"Triage — create task",disabled:A||Fe===He.id,children:Fe===He.id?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Bn,{size:14})}),He.taskId?t.jsx("button",{className:"mission-icon-btn",onClick:()=>fs(He.id),title:"Unlink task",children:t.jsx($d,{size:14})}):He.status!=="defined"?t.jsx("button",{className:"mission-icon-btn",onClick:()=>qe(He.id),title:"Link to task",children:t.jsx(ga,{size:14})}):null,t.jsx("button",{className:"mission-icon-btn",onClick:()=>Vn(He),title:"Edit feature",children:t.jsx(ss,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>oe({type:"feature",id:He.id}),title:"Delete feature",children:t.jsx(Zt,{size:14})})]})]}),He.description&&t.jsx("p",{className:"mission-feature__description",children:He.description}),He.acceptanceCriteria&&t.jsxs("p",{className:"mission-feature__criteria",children:[t.jsx("strong",{children:"Acceptance:"})," ",He.acceptanceCriteria]}),pe?.featureId===He.id&&t.jsxs("div",{className:"mission-triage-preview",children:[t.jsx("div",{className:"mission-triage-preview__header",children:"Enriched Description Preview"}),t.jsx("div",{className:"mission-triage-preview__content",children:pe.enrichedDescription}),t.jsxs("div",{className:"mission-triage-preview__actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:ls,disabled:A,children:[A?t.jsx(rt,{size:14,className:"spinner"}):null,"Create Task"]}),t.jsx("button",{className:"btn",onClick:Ss,disabled:A,children:"Cancel"})]})]}),F===He.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:se.title,onChange:pt=>fe({...se,title:pt.target.value}),onKeyDown:ea,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:se.description,onChange:pt=>fe({...se,description:pt.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:se.acceptanceCriteria,onChange:pt=>fe({...se,acceptanceCriteria:pt.target.value}),rows:2}),t.jsxs("select",{value:se.status,onChange:pt=>fe({...se,status:pt.target.value}),children:[t.jsx("option",{value:"defined",children:"Defined"}),t.jsx("option",{value:"triaged",children:"Triaged"}),t.jsx("option",{value:"in-progress",children:"In Progress"}),t.jsx("option",{value:"done",children:"Done"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Cn,disabled:A,children:[A?t.jsx(rt,{size:14,className:"spinner"}):t.jsx($n,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Wn,children:"Cancel"})]})]}),Et===He.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"})}),(be.get(He.id)??[]).map(pt=>t.jsxs("div",{className:"mission-run",children:[t.jsxs("div",{className:"mission-run__header",onClick:()=>Zo(pt.id),children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-run__status mission-run__status--${pt.status}`,title:pt.status,children:pt.status}),t.jsx("span",{className:"mission-run__time",children:new Date(pt.startedAt).toLocaleString()}),pt.completedAt&&t.jsxs("span",{className:"mission-run__duration",children:[Math.round((new Date(pt.completedAt).getTime()-new Date(pt.startedAt).getTime())/1e3),"s"]}),pt.triggerType&&t.jsx("span",{className:"mission-run__trigger",children:pt.triggerType}),t.jsx("button",{className:"mission-icon-btn",title:N===pt.id?"Hide details":"Show details",children:N===pt.id?t.jsx(Vt,{size:12}):t.jsx(pn,{size:12})})]}),N===pt.id&&Ie.get(pt.id)&&t.jsxs("div",{className:"mission-run__details",children:[pt.summary&&t.jsx("p",{className:"mission-run__summary",children:pt.summary}),pt.blockedReason&&t.jsxs("p",{className:"mission-run__blocked-reason",children:[t.jsx("strong",{children:"Blocked:"})," ",pt.blockedReason]}),Ie.get(pt.id)?.failures&&Ie.get(pt.id).failures.length>0&&t.jsxs("div",{className:"mission-run__failures",children:[t.jsx("span",{className:"mission-run__failures-title",children:"Failed Assertions:"}),Ie.get(pt.id).failures.map(mn=>t.jsxs("div",{className:"mission-run__failure",children:[t.jsx("span",{className:"mission-run__failure-message",children:mn.message}),mn.expected&&t.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",mn.expected]}),mn.actual&&t.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",mn.actual]})]},mn.id))]}),(!Ie.get(pt.id)?.failures||Ie.get(pt.id).failures.length===0)&&t.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},pt.id)),(!be.get(He.id)||be.get(He.id).length===0)&&t.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},He.id)),de&&ie===Ue.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:se.title,onChange:He=>fe({...se,title:He.target.value}),onKeyDown:ea,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:se.description,onChange:He=>fe({...se,description:He.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:se.acceptanceCriteria,onChange:He=>fe({...se,acceptanceCriteria:He.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Cn,disabled:A,children:[A?t.jsx(rt,{size:14,className:"spinner"}):t.jsx($n,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Wn,children:"Cancel"})]})]}),!de&&(!Ue.features||Ue.features.length===0)&&t.jsxs("div",{className:"mission-manager__empty mission-features__empty",children:[t.jsx(hc,{size:16}),t.jsx("span",{children:"No fix features generated."})]})]})]})]},Ue.id)),B.slices.length===0&&!me&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(yc,{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"}),$e&&t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Dt.bg,color:Dt.text},children:Gu($e.state)}),$e&&$e.totalAssertions>0&&t.jsx("div",{className:"mission-assertions__coverage-bar",title:`${$e.passedAssertions??0} of ${$e.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-assertions__coverage-bar-fill",style:{width:`${($e.passedAssertions??0)/$e.totalAssertions*100}%`,backgroundColor:($e.passedAssertions??0)===$e.totalAssertions?"var(--color-success)":"var(--color-warning)"}})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>{ce(!0),We(null),ot({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:t.jsx(en,{size:14})})]}),J&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:Re.title,onChange:Ue=>ot({...Re,title:Ue.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:Re.assertion,onChange:Ue=>ot({...Re,assertion:Ue.target.value}),rows:2}),t.jsxs("select",{value:Re.status,onChange:Ue=>ot({...Re,status:Ue.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(B.id),disabled:A,children:[A?t.jsx(rt,{size:14,className:"spinner"}):t.jsx($n,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:_i,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-assertions__list",children:[(Array.isArray(Te.get(B.id))?Te.get(B.id):[]).map(Ue=>t.jsxs("div",{className:"mission-assertion","data-mission-assertion-id":Ue.id,children:[t.jsx("div",{className:"mission-assertion__header",children:Me===Ue.id?t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:Re.title,onChange:He=>ot({...Re,title:He.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text",value:Re.assertion,onChange:He=>ot({...Re,assertion:He.target.value}),rows:2}),t.jsxs("select",{value:Re.status,onChange:He=>ot({...Re,status:He.target.value}),children:[t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"passed",children:"Passed"}),t.jsx("option",{value:"failed",children:"Failed"}),t.jsx("option",{value:"blocked",children:"Blocked"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:()=>Dr(Ue.id,B.id),disabled:A,children:[A?t.jsx(rt,{size:14,className:"spinner"}):t.jsx($n,{size:14}),"Save"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:_i,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(Gr[Ue.status]??Gr.pending).bg,color:(Gr[Ue.status]??Gr.pending).text},children:Ue.status}),t.jsx("span",{className:"mission-assertion__title",children:Ue.title}),(()=>{const pt=ee.get(Ue.id)?.length??0;return pt>0?t.jsxs("span",{className:"mission-assertion__linked-count",title:`${pt} linked feature${pt!==1?"s":""}`,children:["(",pt," linked)"]}):null})(),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Lr(Ue.id),title:"Toggle details",children:ve===Ue.id?t.jsx(Vt,{size:14}):t.jsx(pn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Xo(Ue),title:"Edit assertion",children:t.jsx(ss,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>oe({type:"assertion",id:Ue.id}),title:"Delete assertion",children:t.jsx(Zt,{size:14})})]})}),ve===Ue.id&&t.jsxs("div",{className:"mission-assertion__body",children:[t.jsx("p",{className:"mission-assertion__text",children:Ue.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()=>{ve!==Ue.id&&await Lr(Ue.id),_t(gt===Ue.id?null:Ue.id)},title:"Link a feature",children:[t.jsx(ga,{size:12}),"Link Feature"]})]}),gt===Ue.id&&t.jsx("div",{className:"mission-assertion__feature-picker",children:t.jsx("div",{className:"mission-assertion__feature-picker-dropdown",children:(()=>{const He=new Set((ee.get(Ue.id)??[]).map(mn=>mn.id)),pt=[];return f?.milestones.forEach(mn=>mn.slices.forEach(Es=>pt.push(...Es.features.filter(Ti=>!He.has(Ti.id))))),pt.length===0?t.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):pt.map(mn=>t.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>Fr(mn.id,Ue.id),disabled:ct.has(Ue.id),children:[t.jsx("span",{className:"mission-assertion__feature-picker-title",children:mn.title}),ct.has(Ue.id)&&t.jsx(rt,{size:12,className:"spinner"})]},mn.id))})()})}),(()=>{const He=ee.get(Ue.id)??[];return He.length===0?t.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):He.map(pt=>{const mn=`${pt.id}-${Ue.id}`,Es=bt.has(mn);return t.jsxs("div",{className:"mission-assertion__linked-feature",children:[t.jsx("span",{className:"mission-assertion__linked-feature-title",children:pt.title}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Gn(pt.id,Ue.id),disabled:Es,title:"Unlink feature",children:Es?t.jsx(rt,{size:12,className:"spinner"}):t.jsx($d,{size:12})})]},pt.id)})})()]})]})]},Ue.id)),(!Te.get(B.id)||Te.get(B.id)?.length===0)&&!J&&t.jsx("div",{className:"mission-manager__empty mission-assertions__empty",children:t.jsx("span",{children:"No assertions defined. Add one to define completion criteria."})})]})]})]})]})]},B.id)}),f&&!_&&D===null&&t.jsxs("button",{className:"mission-add-btn",onClick:gi,children:[t.jsx(en,{size:16}),"Add Milestone"]}),_&&D===null&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:Y.title,onChange:B=>X({...Y,title:B.target.value}),onKeyDown:Zi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:Y.description,onChange:B=>X({...Y,description:B.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:ps,disabled:A,children:[A?t.jsx(rt,{size:14,className:"spinner"}):t.jsx($n,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bn,children:"Cancel"})]})]}),f.milestones.length===0&&!_&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Hi,{size:24}),t.jsx("span",{children:"No milestones yet. Add one to get started."})]})]}):t.jsxs("div",{className:"mission-detail__activity","data-testid":"mission-activity-tab",children:[t.jsxs("div",{className:"mission-detail__activity-controls",children:[t.jsxs("label",{className:"mission-detail__activity-filter",children:[t.jsx("span",{children:"Filter"}),t.jsxs("select",{value:Yt,onChange:B=>Q(B.target.value),"data-testid":"mission-activity-filter",children:[t.jsx("option",{value:"all",children:"All events"}),t.jsx("option",{value:"errors",children:"Errors & warnings"}),t.jsx("option",{value:"state_changes",children:"State changes"}),t.jsx("option",{value:"tasks",children:"Task events"}),t.jsx("option",{value:"slices",children:"Slice & milestone events"}),t.jsx("option",{value:"autopilot",children:"Autopilot events"})]})]}),t.jsxs("span",{className:"mission-detail__activity-count",children:[nn.length," of ",es]})]}),!Pn&&gs&&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:tl,"data-testid":"mission-activity-load-more",children:"Load more"})}),Pn?t.jsxs("div",{className:"mission-manager__loading mission-detail__activity-loading",children:[t.jsx(rt,{size:18,className:"spinner"}),t.jsx("span",{children:"Loading mission activity..."})]}):nn.length===0?t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Ps,{size:18}),t.jsx("span",{children:"No events yet."})]}):t.jsxs("div",{ref:et,className:"mission-events","data-testid":"mission-activity-events",children:[nn.map(B=>{const we=!!(B.metadata&&Object.keys(B.metadata).length>0),$e=ze.has(B.id);return t.jsxs("div",{className:"mission-event",children:[t.jsxs("div",{className:"mission-event__header",children:[t.jsx("span",{className:`mission-event__type ${$1(B.eventType)}`,children:D1(B.eventType)}),t.jsx("span",{className:"mission-event__time",children:wo(B.timestamp)})]}),t.jsx("p",{className:"mission-event__description",children:B.description}),t.jsx("span",{className:"mission-event__timestamp",children:new Date(B.timestamp).toLocaleString()}),we&&t.jsxs("div",{className:"mission-event__metadata",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>nl(B.id),"data-testid":`mission-event-metadata-${B.id}`,children:[$e?"Hide":"Show"," metadata"]}),$e&&t.jsx("pre",{className:"mission-event__metadata-content",children:JSON.stringify(B.metadata,null,2)})]})]},B.id)}),t.jsx("div",{ref:dt})]})]})]}):t.jsxs("div",{className:"mission-list",children:[j&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:C.title,onChange:B=>L({...C,title:B.target.value}),onKeyDown:Ai,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:C.description,onChange:B=>L({...C,description:B.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Ls,disabled:A,children:[A?t.jsx(rt,{size:14,className:"spinner"}):t.jsx($n,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Ds,children:"Cancel"})]})]}),g.map(B=>{const we=B,$e=f,mt=$e&&$e.id===we.id,un=Ua[we.status]||{bg:"",text:""},Dt=we.summary,Xt=yt.get(we.id),Ue=T1(Xt),He=!!(Dt&&(Dt.totalMilestones>0||Dt.totalFeatures>0)),pt=Xt?.totalTasks??0,mn=Xt?.tasksCompleted??0,Es=Xt?.tasksFailed??0,Ti=Xt?.estimatedCompletionPercent??Dt?.progressPercent??0,Jn=He||pt>0||Es>0||!!Xt?.lastActivityAt,wn=we.status==="active"&&(Xt?.currentMilestoneId||Xt?.currentSliceId)?"Current milestone/slice in progress":null;return t.jsxs("div",{className:`mission-list__item ${mt?"mission-list__item--selected":""}`,onClick:()=>$t(B),children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(us,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{className:"mission-list__item-title",children:we.title}),B.autopilotEnabled&&t.jsx("span",{title:"Autopilot enabled",children:t.jsx(Bn,{size:12,className:"mission-list__item-autopilot-icon"})}),t.jsx("span",{className:`mission-health-badge mission-health-badge--${Ue}`,"data-testid":`mission-health-badge-${we.id}`,"aria-label":`Mission health: ${Ue}`}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:un.bg,color:un.text},children:we.status})]}),we.description&&t.jsx("p",{className:"mission-list__item-description",children:we.description}),wn&&t.jsxs("p",{className:"mission-list__item-active-slice",children:["Active: ",wn]}),Jn&&t.jsxs("div",{className:"mission-list__item-summary",children:[He&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"mission-list__item-stat",children:[Dt.completedMilestones,"/",Dt.totalMilestones," milestones"]}),t.jsxs("span",{className:"mission-list__item-stat",children:[Dt.completedFeatures,"/",Dt.totalFeatures," features"]})]}),t.jsxs("span",{className:"mission-list__item-stat","data-testid":`mission-task-stats-${we.id}`,children:[mn,"/",pt," tasks"]}),Es>0&&t.jsxs("button",{className:"mission-list__item-failed",onClick:Bt=>{Bt.stopPropagation(),$t(B)},"data-testid":`mission-failed-${we.id}`,title:"View mission failures",children:[Es," failed"]}),t.jsxs("span",{className:"mission-relative-time","data-testid":`mission-last-activity-${we.id}`,children:["Activity ",wo(Xt?.lastActivityAt)]}),t.jsx("div",{className:`mission-list__item-progress mission-list__item-progress--${Ue}`,children:t.jsx("div",{className:"mission-list__item-progress-bar",style:{width:`${Ti}%`}})})]})]}),t.jsxs("div",{className:"mission-list__item-actions",onClick:Bt=>Bt.stopPropagation(),children:[we.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Z(we.id),title:"Stop mission",children:t.jsx(bs,{size:14})}),we.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Da(we.id),title:"Resume mission",children:t.jsx(jn,{size:14})}),we.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Be(we.id),title:"Start mission",children:t.jsx(jn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>ii(B),title:"Edit mission",children:t.jsx(ss,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>oe({type:"mission",id:we.id}),title:"Delete mission",children:t.jsx(Zt,{size:14})})]})]},we.id)}),k&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:C.title,onChange:B=>L({...C,title:B.target.value}),onKeyDown:Ai,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:C.description,onChange:B=>L({...C,description:B.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:C.status,onChange:B=>L({...C,status:B.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:C.autopilotEnabled,onChange:B=>L({...C,autopilotEnabled:B.target.checked})}),t.jsx(Bn,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Ls,disabled:A,children:[A?t.jsx(rt,{size:14,className:"spinner"}):t.jsx($n,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Ds,children:"Cancel"})]})]}),g.length===0&&!j&&t.jsxs("div",{className:"mission-manager__empty mission-manager__empty--large",children:[t.jsx(us,{size:32}),t.jsx("span",{children:"No missions yet. Create one to start planning."})]}),!j&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[Pe.length>0&&t.jsxs("div",{className:"mission-resume-prompt",children:[t.jsx(as,{size:16}),t.jsx("span",{children:Pe.length===1?`Resume "${Pe[0].title}"?`:`${Pe.length} interview sessions pending`}),t.jsx("div",{style:{display:"flex",gap:"4px",marginLeft:"auto"},children:Pe.map(B=>t.jsxs("button",{className:"mission-add-btn",onClick:()=>{ye(B.id),it(!0),Ve([])},children:[B.status==="error"?t.jsx(En,{size:14}):t.jsx(Xn,{size:14}),B.status==="error"?"Retry":"Resume"]},B.id))})]}),t.jsxs("div",{style:{display:"flex",gap:"8px"},children:[t.jsxs("button",{className:"mission-add-btn",onClick:()=>it(!0),children:[t.jsx(Xn,{size:16}),"Plan with AI"]}),t.jsxs("button",{className:"mission-add-btn",onClick:$s,children:[t.jsx(en,{size:16}),"New Mission"]})]})]})]})}),Ne&&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 ",Ne.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()=>{Ne.type==="mission"?await Ei(Ne.id):Ne.type==="milestone"?await ne(Ne.id):Ne.type==="slice"?await Qt(Ne.id):Ne.type==="feature"&&await Kn(Ne.id)},children:"Delete"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>oe(null),children:"Cancel"})]})]})}),De&&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:B=>Je(B.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(B=>t.jsxs("button",{className:"mission-task-suggestions__item",onClick:()=>Je(B.id),children:[B.id,": ",B.title||"Untitled"]},B.id))})]}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--primary",onClick:zn,children:"Link"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>{qe(null),Je("")},children:"Cancel"})]})]})})]}),Cs=t.jsx(w1,{isOpen:Ke,onClose:()=>it(!1),onMissionCreated:()=>{sn(),i("Mission created from AI interview","success")},projectId:r,resumeSessionId:te}),ri=Ae?t.jsx(C1,{isOpen:!0,onClose:()=>Le(null),onApplied:()=>{Le(null),f&&jt(f.id)},targetType:Ae.type,targetId:Ae.id,targetTitle:Ae.title,missionContext:f?.title,projectId:r,resumeSessionId:Ae.resumeSessionId}):null;return n?t.jsxs(t.Fragment,{children:[sl,Cs,ri]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mission-manager-overlay open",onClick:B=>B.target===B.currentTarget&&s(),"data-testid":"mission-manager-overlay",role:"dialog","aria-modal":"true",children:sl}),Cs,ri]})}const Jr=2e3;function Yu({recipient:e,replyContext:n,agents:s=[],projectId:i,onSend:r,onCancel:o,addToast:l,isLoadingAgents:c=!1}){const[u,d]=a.useState(e?.id??""),[m,h]=a.useState(e?.type??"agent"),[g,p]=a.useState(""),[f,x]=a.useState(!1),[v,b]=a.useState(null),y=u.trim()!==""&&g.trim().length>0&&g.length<=Jr,S=a.useCallback(async()=>{if(!(!y||f)){x(!0),b(null);try{const R=m==="agent"?"user-to-agent":"system";await qk({toId:u.trim(),toType:m,content:g.trim(),type:R,...n?{metadata:{replyTo:{messageId:n.messageId}}}:{}},i),r()}catch(R){const k=je(R)||"Failed to send message";b(k),l?.(k,"error")}finally{x(!1)}}},[y,f,u,m,g,n,i,r,l]),j=a.useCallback(R=>{d(R),h("agent")},[]);return t.jsxs("div",{className:"message-composer","data-testid":"message-composer",children:[t.jsxs("div",{className:"message-composer-header",children:[t.jsx("span",{children:n?"Reply":"New Message"}),t.jsx("button",{className:"btn-icon",onClick:o,"aria-label":"Cancel","data-testid":"message-composer-cancel",children:t.jsx(Ut,{size:16})})]}),t.jsxs("div",{className:"message-composer-body",children:[!e&&t.jsxs("div",{className:"message-composer-field",children:[t.jsx("label",{className:"message-composer-label",htmlFor:"message-recipient",children:"To:"}),t.jsxs("select",{id:"message-recipient",className:"message-composer-select",value:u,onChange:R=>j(R.target.value),disabled:c||s.length===0,"data-testid":"message-composer-recipient",children:[t.jsx("option",{value:"",children:c?"Loading agents…":s.length===0?"No agents available":"Select agent…"}),s.map(R=>t.jsx("option",{value:R.id,children:R.name||R.id},R.id))]})]}),e&&t.jsxs("div",{className:"message-composer-field",children:[t.jsx("span",{className:"message-composer-label",children:"To:"}),t.jsxs("span",{className:"message-composer-recipient-fixed",children:[t.jsx(yn,{size:14}),e.id]})]}),n&&t.jsxs("div",{className:"message-composer-field","data-testid":"message-composer-reply-context",children:[t.jsx("span",{className:"message-composer-label",children:"Replying to:"}),t.jsx("span",{className:"message-composer-recipient-fixed",children:n.preview?.trim()?n.preview:`Message ${n.messageId}`})]}),t.jsxs("div",{className:"message-composer-field message-composer-field--content",children:[t.jsx("label",{className:"message-composer-label",htmlFor:"message-content",children:"Message:"}),t.jsx("textarea",{id:"message-content",className:"message-composer-textarea",placeholder:"Type your message…",value:g,onChange:R=>p(R.target.value),maxLength:Jr,rows:4,"data-testid":"message-composer-content"}),t.jsx("div",{className:"message-composer-charcount","data-testid":"message-composer-charcount",children:t.jsxs("span",{className:g.length>Jr?"over-limit":"",children:[g.length,"/",Jr]})})]}),v&&t.jsxs("div",{className:"message-composer-error","data-testid":"message-composer-error",children:[t.jsx(as,{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:S,disabled:!y||f,"data-testid":"message-composer-send",children:f?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:14,className:"spin"}),t.jsx("span",{children:"Sending…"})]}):t.jsxs(t.Fragment,{children:[t.jsx(zi,{size:14}),t.jsx("span",{children:"Send"})]})})]})]})}function aa(e){const n=new Date(e),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),o=Math.floor(i/36e5),l=Math.floor(i/864e5);return r<1?"Just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function F1(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 O1(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 Qu(e,n=80){return e.length<=n?e:`${e.slice(0,n)}…`}function B1(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 U1({projectId:e,addToast:n,onUnreadCountChange:s}){const[i,r]=a.useState("inbox"),[o,l]=a.useState(null),[c,u]=a.useState(null),[d,m]=a.useState(0),[h,g]=a.useState(!1),[p,f]=a.useState(null),[x,v]=a.useState([]),[b,y]=a.useState(!1),[S,j]=a.useState(null),[R,k]=a.useState(null),[M,C]=a.useState(null),[L,A]=a.useState("inbox"),[P,O]=a.useState(null),[V,$]=a.useState([]),E=a.useMemo(()=>new Map(V.map(ie=>[ie.id,ie.name??""])),[V]),D=a.useCallback((ie,Ee)=>F1(ie,Ee,E),[E]),Y=Tr()==="mobile",X=!Y,_=a.useCallback(async()=>{g(!0);try{const ie=await Uk({limit:50},e);l(ie),m(ie.unreadCount),s?.(ie.unreadCount)}catch{}finally{g(!1)}},[e,s]),I=a.useCallback(async()=>{g(!0);try{const ie=await Hk({limit:50},e);u(ie)}catch{}finally{g(!1)}},[e]),T=a.useCallback(async ie=>{g(!0);try{const Ee=await Jk(ie,e);O(Ee)}catch{}finally{g(!1)}},[e]),w=a.useCallback(async()=>{try{const ie=await Ma(void 0,e);$(ie)}catch{}},[e]),q=a.useCallback(async()=>{try{const ie=await gp(e);m(ie.unreadCount),s?.(ie.unreadCount)}catch{}},[e,s]);a.useEffect(()=>{i==="inbox"?_():i==="outbox"?I():i==="agents"&&w()},[i,_,I,w]),a.useEffect(()=>{M&&T(M)},[M,T]),a.useEffect(()=>{q()},[q]),a.useEffect(()=>{w()},[w]),a.useEffect(()=>{if(typeof EventSource>"u")return;const ie=e?`?projectId=${encodeURIComponent(e)}`:"",Ee=()=>{q(),i==="inbox"?_():i==="outbox"&&I(),M&&T(M)};return qs(`/api/events${ie}`,{events:{"message:sent":Ee,"message:received":Ee,"message:read":Ee,"message:deleted":Ee}})},[e,i,M,q,_,I,T]);const G=a.useCallback(async ie=>{if(f(ie),!ie.read)try{const Ee=await Vk(ie.id,e);Ee&&l(qe=>qe&&{...qe,messages:qe.messages.map(Qe=>Qe.id===Ee.id?Ee:Qe),unreadCount:Math.max(0,qe.unreadCount-1)});const De=Math.max(0,d-1);m(De),s?.(De)}catch{}try{const Ee=await Gk(ie.fromId,ie.fromType,e);v(Ee)}catch{v([ie])}},[e,d,s]),me=a.useCallback(()=>{f(null),v([])},[]),ue=a.useCallback(async()=>{try{const ie=await Wk(e);m(0),s?.(0),l(Ee=>Ee&&{...Ee,messages:Ee.messages.map(De=>({...De,read:!0})),unreadCount:0}),n?.(`Marked ${ie.markedAsRead} messages as read`,"success")}catch{n?.("Failed to mark messages as read","error")}},[e,n,s]),le=a.useCallback(async ie=>{try{await Kk(ie,e),f(null),v([]),i==="inbox"?_():i==="outbox"?I():M&&T(M),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[e,i,M,_,I,T,n]),Se=a.useCallback(ie=>{j({id:ie.fromId,type:ie.fromType}),k({messageId:ie.id,preview:Qu(ie.content,120)}),y(!0)},[]),F=a.useCallback(()=>{y(!1),j(null),k(null),n?.("Message sent","success"),i==="outbox"?I():i==="agents"&&M&&T(M),q()},[i,I,M,T,n,q]),ge=a.useCallback(()=>{j(i==="agents"&&M?{id:M,type:"agent"}:null),k(null),y(!0)},[i,M]),se=a.useCallback(()=>{y(!1),j(null),k(null)},[]),fe=()=>!p||b?null:t.jsxs("div",{className:"mailbox-message-detail","data-testid":"mailbox-message-detail",children:[t.jsxs("div",{className:"mailbox-message-detail-header",children:[Y&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:me,"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:O1(p.type)}),t.jsx("span",{className:"mailbox-message-time",children:aa(p.createdAt)})]}),t.jsxs("div",{className:"mailbox-message-detail-actions",children:[p.fromType==="agent"&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>Se(p),"data-testid":"mailbox-reply",children:[t.jsx(ji,{size:14}),t.jsx("span",{children:"Reply"})]}),t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>le(p.id),"data-testid":"mailbox-delete",children:[t.jsx(Zt,{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(yn,{size:14}):t.jsx(ta,{size:14}),D(p.fromId,p.fromType)]})]}),t.jsxs("div",{className:"mailbox-participant",children:[t.jsx("span",{className:"mailbox-participant-label",children:"To:"}),t.jsxs("span",{className:"mailbox-participant-value",children:[p.toType==="agent"?t.jsx(yn,{size:14}):t.jsx(ta,{size:14}),D(p.toId,p.toType)]})]})]}),x.length>1&&t.jsxs("div",{className:"mailbox-conversation","data-testid":"mailbox-conversation",children:[t.jsx("div",{className:"mailbox-conversation-label",children:"Conversation"}),x.map(ie=>{const Ee=ie.metadata?.replyTo?.messageId,De=Ee?x.find(qe=>qe.id===Ee):void 0;return t.jsxs("div",{className:`mailbox-conversation-msg ${ie.id===p.id?"current":""}`,children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:D(ie.fromId,ie.fromType)}),t.jsx("span",{className:"mailbox-message-time",children:aa(ie.createdAt)})]}),Ee&&t.jsxs("div",{className:"mailbox-reply-context","data-testid":`mailbox-reply-context-${ie.id}`,children:["↪ Replying to ",De?Qu(De.content,60):`message ${Ee}`]}),t.jsx("div",{className:"mailbox-conversation-msg-body",children:ie.content})]},ie.id)})]}),x.length<=1&&t.jsxs(t.Fragment,{children:[p.metadata?.replyTo?.messageId&&t.jsxs("div",{className:"mailbox-reply-context","data-testid":"mailbox-selected-reply-context",children:["↪ Replying to message ",p.metadata.replyTo.messageId]}),t.jsx("div",{className:"mailbox-message-body","data-testid":"mailbox-message-body",children:p.content})]})]}),de=()=>t.jsxs(t.Fragment,{children:[i==="inbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[h&&!o&&t.jsx(Cl,{}),o&&o.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-inbox-empty",children:[t.jsx(sr,{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:B1(o.messages).map(ie=>t.jsxs("div",{className:`mailbox-conversation-group ${ie.unreadCount>0?"unread":""}`,onClick:()=>G(ie.latestMessage),"data-testid":`mailbox-conversation-${ie.key}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ie.fromType==="agent"?t.jsx(yn,{size:16}):t.jsx(ta,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsx("span",{className:"mailbox-item-from",children:D(ie.fromId,ie.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:aa(ie.latestMessage.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ie.latestMessage.content.slice(0,80),ie.latestMessage.content.length>80?"…":""]})]}),ie.unreadCount>0&&t.jsx("div",{className:"mailbox-group-unread-badge","data-testid":`mailbox-unread-badge-${ie.key}`,children:ie.unreadCount>9?"9+":ie.unreadCount})]},ie.key))})]}),i==="outbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-outbox-list",children:[h&&!c&&t.jsx(Cl,{}),c&&c.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-outbox-empty",children:[t.jsx(zi,{size:32}),t.jsx("p",{children:"No sent messages"})]}),c?.messages.map(ie=>t.jsxs("div",{className:"mailbox-item",onClick:()=>G(ie),"data-testid":`mailbox-item-${ie.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ie.toType==="agent"?t.jsx(yn,{size:16}):t.jsx(ta,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsxs("span",{className:"mailbox-item-to",children:["To: ",D(ie.toId,ie.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:aa(ie.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ie.content.slice(0,80),ie.content.length>80?"…":""]})]})]},ie.id))]}),i==="agents"&&t.jsx("div",{className:"mailbox-agents","data-testid":"mailbox-agents",children:V.length===0?t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(yn,{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:ie=>{C(ie.target.value||null),A("inbox")},"data-testid":"mailbox-agent-select",children:[t.jsx("option",{value:"",children:"Select an agent…"}),V.map(ie=>t.jsx("option",{value:ie.id,children:ie.name||ie.id},ie.id))]})}),t.jsxs("button",{className:"btn btn-sm btn-secondary mailbox-compose-btn",onClick:ge,"data-testid":"mailbox-compose-btn",children:[t.jsx(ji,{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 ${L==="inbox"?"active":""}`,onClick:()=>A("inbox"),"data-testid":"mailbox-agent-subtab-inbox",children:[t.jsx(sr,{size:12}),t.jsx("span",{children:"Inbox"}),P&&P.unreadCount>0&&t.jsx("span",{className:"mailbox-tab-badge",children:P.unreadCount})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${L==="outbox"?"active":""}`,onClick:()=>A("outbox"),"data-testid":"mailbox-agent-subtab-outbox",children:[t.jsx(zi,{size:12}),t.jsx("span",{children:"Outbox"})]})]}),t.jsxs("div",{className:"mailbox-agents-content",children:[!M&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(yn,{size:32}),t.jsx("p",{children:"Select an agent to view their mailbox"})]}),M&&h&&!P&&t.jsx(Cl,{}),M&&P&&L==="inbox"&&P.inbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(sr,{size:32}),t.jsx("p",{children:"No received messages for this agent"})]}),M&&P&&L==="outbox"&&P.outbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(zi,{size:32}),t.jsx("p",{children:"No sent messages for this agent"})]}),M&&P&&L==="inbox"&&P.inbox.map(ie=>t.jsxs("div",{className:`mailbox-item ${ie.read?"":"unread"}`,onClick:()=>G(ie),"data-testid":`mailbox-item-${ie.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ie.fromType==="agent"?t.jsx(yn,{size:16}):t.jsx(ta,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsx("span",{className:"mailbox-item-from",children:D(ie.fromId,ie.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:aa(ie.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ie.content.slice(0,80),ie.content.length>80?"…":""]})]})]},ie.id)),M&&P&&L==="outbox"&&P.outbox.map(ie=>t.jsxs("div",{className:"mailbox-item",onClick:()=>G(ie),"data-testid":`mailbox-item-${ie.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ie.toType==="agent"?t.jsx(yn,{size:16}):t.jsx(ta,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsxs("span",{className:"mailbox-item-to",children:["To: ",D(ie.toId,ie.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:aa(ie.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ie.content.slice(0,80),ie.content.length>80?"…":""]})]})]},ie.id))]})]})})]}),xe=()=>b?t.jsx(Yu,{recipient:S,replyContext:R,agents:V,projectId:e,onSend:F,onCancel:se,addToast:n}):p?fe():t.jsxs("div",{className:"mailbox-split-empty","data-testid":"mailbox-split-empty",children:[t.jsx(xa,{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(xa,{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:ge,title:"Compose message","data-testid":"mailbox-header-compose",children:[t.jsx(ji,{size:14}),t.jsx("span",{children:"Compose"})]}),i==="inbox"&&d>0&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:ue,title:"Mark all as read","data-testid":"mailbox-mark-all-read",children:[t.jsx(Og,{size:14}),t.jsx("span",{children:"Mark all read"})]}),t.jsx("button",{className:"btn-icon",onClick:()=>{i==="inbox"?_():i==="outbox"?I():M&&T(M)},disabled:h,title:"Refresh","data-testid":"mailbox-refresh",children:h?t.jsx(rt,{size:14,className:"spin"}):t.jsx(En,{size:14})})]})]}),t.jsxs("div",{className:"mailbox-tabs","data-testid":"mailbox-tabs",children:[t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="inbox"?"active":""}`,onClick:()=>{r("inbox"),f(null)},"data-testid":"mailbox-tab-inbox",children:[t.jsx(sr,{size:14}),t.jsx("span",{children:"Inbox"}),d>0&&t.jsx("span",{className:"mailbox-tab-badge",children:d})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="outbox"?"active":""}`,onClick:()=>{r("outbox"),f(null)},"data-testid":"mailbox-tab-outbox",children:[t.jsx(zi,{size:14}),t.jsx("span",{children:"Outbox"})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="agents"?"active":""}`,onClick:()=>{r("agents"),f(null)},"data-testid":"mailbox-tab-agents",children:[t.jsx(yn,{size:14}),t.jsx("span",{children:"Agents"})]})]}),t.jsx("div",{className:"mailbox-content","data-testid":"mailbox-content",children:X?t.jsxs("div",{className:"mailbox-split-layout","data-testid":"mailbox-split-layout",children:[t.jsx("div",{className:"mailbox-split-list-pane","data-testid":"mailbox-split-list-pane",children:de()}),t.jsx("div",{className:"mailbox-split-detail-pane","data-testid":"mailbox-split-detail-pane",children:xe()})]}):t.jsxs(t.Fragment,{children:[fe(),b&&t.jsx(Yu,{recipient:S,replyContext:R,agents:V,projectId:e,onSend:F,onCancel:se,addToast:n}),!p&&!b&&de()]})})]})}function Cl(){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 ni(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 Si(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 H1(e,n){const s={};return(e[e.length-1]===""?[...e,""]:e).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const q1=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,V1=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,W1={};function Xu(e,n){return(W1.jsx?V1:q1).test(e)}const K1=/[ \t\n\f\r]/g;function G1(e){return typeof e=="object"?e.type==="text"?Zu(e.value):!1:Zu(e)}function Zu(e){return e.replace(K1,"")===""}class Pr{constructor(n,s,i){this.normal=s,this.property=n,i&&(this.space=i)}}Pr.prototype.normal={};Pr.prototype.property={};Pr.prototype.space=void 0;function Bp(e,n){const s={},i={};for(const r of e)Object.assign(s,r.property),Object.assign(i,r.normal);return new Pr(s,i,n)}function Tc(e){return e.toLowerCase()}class hs{constructor(n,s){this.attribute=s,this.property=n}}hs.prototype.attribute="";hs.prototype.booleanish=!1;hs.prototype.boolean=!1;hs.prototype.commaOrSpaceSeparated=!1;hs.prototype.commaSeparated=!1;hs.prototype.defined=!1;hs.prototype.mustUseProperty=!1;hs.prototype.number=!1;hs.prototype.overloadedBoolean=!1;hs.prototype.property="";hs.prototype.spaceSeparated=!1;hs.prototype.space=void 0;let J1=0;const Lt=Yi(),Mn=Yi(),Pc=Yi(),st=Yi(),hn=Yi(),pa=Yi(),xs=Yi();function Yi(){return 2**++J1}const Ic=Object.freeze(Object.defineProperty({__proto__:null,boolean:Lt,booleanish:Mn,commaOrSpaceSeparated:xs,commaSeparated:pa,number:st,overloadedBoolean:Pc,spaceSeparated:hn},Symbol.toStringTag,{value:"Module"})),El=Object.keys(Ic);class md extends hs{constructor(n,s,i,r){let o=-1;if(super(n,s),em(this,"space",r),typeof i=="number")for(;++o<El.length;){const l=El[o];em(this,El[o],(i&Ic[l])===Ic[l])}}}md.prototype.defined=!0;function em(e,n,s){s&&(e[n]=s)}function Ta(e){const n={},s={};for(const[i,r]of Object.entries(e.properties)){const o=new md(i,e.transform(e.attributes||{},i),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(i)&&(o.mustUseProperty=!0),n[i]=o,s[Tc(i)]=i,s[Tc(o.attribute)]=i}return new Pr(n,s,e.space)}const Up=Ta({properties:{ariaActiveDescendant:null,ariaAtomic:Mn,ariaAutoComplete:null,ariaBusy:Mn,ariaChecked:Mn,ariaColCount:st,ariaColIndex:st,ariaColSpan:st,ariaControls:hn,ariaCurrent:null,ariaDescribedBy:hn,ariaDetails:null,ariaDisabled:Mn,ariaDropEffect:hn,ariaErrorMessage:null,ariaExpanded:Mn,ariaFlowTo:hn,ariaGrabbed:Mn,ariaHasPopup:null,ariaHidden:Mn,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:hn,ariaLevel:st,ariaLive:null,ariaModal:Mn,ariaMultiLine:Mn,ariaMultiSelectable:Mn,ariaOrientation:null,ariaOwns:hn,ariaPlaceholder:null,ariaPosInSet:st,ariaPressed:Mn,ariaReadOnly:Mn,ariaRelevant:null,ariaRequired:Mn,ariaRoleDescription:hn,ariaRowCount:st,ariaRowIndex:st,ariaRowSpan:st,ariaSelected:Mn,ariaSetSize:st,ariaSort:null,ariaValueMax:st,ariaValueMin:st,ariaValueNow:st,ariaValueText:null,role:null},transform(e,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function Hp(e,n){return n in e?e[n]:n}function qp(e,n){return Hp(e,n.toLowerCase())}const Y1=Ta({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:pa,acceptCharset:hn,accessKey:hn,action:null,allow:null,allowFullScreen:Lt,allowPaymentRequest:Lt,allowUserMedia:Lt,alt:null,as:null,async:Lt,autoCapitalize:null,autoComplete:hn,autoFocus:Lt,autoPlay:Lt,blocking:hn,capture:null,charSet:null,checked:Lt,cite:null,className:hn,cols:st,colSpan:null,content:null,contentEditable:Mn,controls:Lt,controlsList:hn,coords:st|pa,crossOrigin:null,data:null,dateTime:null,decoding:null,default:Lt,defer:Lt,dir:null,dirName:null,disabled:Lt,download:Pc,draggable:Mn,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:Lt,formTarget:null,headers:hn,height:st,hidden:Pc,high:st,href:null,hrefLang:null,htmlFor:hn,httpEquiv:hn,id:null,imageSizes:null,imageSrcSet:null,inert:Lt,inputMode:null,integrity:null,is:null,isMap:Lt,itemId:null,itemProp:hn,itemRef:hn,itemScope:Lt,itemType:hn,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:Lt,low:st,manifest:null,max:null,maxLength:st,media:null,method:null,min:null,minLength:st,multiple:Lt,muted:Lt,name:null,nonce:null,noModule:Lt,noValidate:Lt,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:Lt,optimum:st,pattern:null,ping:hn,placeholder:null,playsInline:Lt,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:Lt,referrerPolicy:null,rel:hn,required:Lt,reversed:Lt,rows:st,rowSpan:st,sandbox:hn,scope:null,scoped:Lt,seamless:Lt,selected:Lt,shadowRootClonable:Lt,shadowRootDelegatesFocus:Lt,shadowRootMode:null,shape:null,size:st,sizes:null,slot:null,span:st,spellCheck:Mn,src:null,srcDoc:null,srcLang:null,srcSet:null,start:st,step:null,style:null,tabIndex:st,target:null,title:null,translate:null,type:null,typeMustMatch:Lt,useMap:null,value:Mn,width:st,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:hn,axis:null,background:null,bgColor:null,border:st,borderColor:null,bottomMargin:st,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:Lt,declare:Lt,event:null,face:null,frame:null,frameBorder:null,hSpace:st,leftMargin:st,link:null,longDesc:null,lowSrc:null,marginHeight:st,marginWidth:st,noResize:Lt,noHref:Lt,noShade:Lt,noWrap:Lt,object:null,profile:null,prompt:null,rev:null,rightMargin:st,rules:null,scheme:null,scrolling:Mn,standby:null,summary:null,text:null,topMargin:st,valueType:null,version:null,vAlign:null,vLink:null,vSpace:st,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:Lt,disableRemotePlayback:Lt,prefix:null,property:null,results:st,security:null,unselectable:null},space:"html",transform:qp}),Q1=Ta({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:xs,accentHeight:st,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:st,amplitude:st,arabicForm:null,ascent:st,attributeName:null,attributeType:null,azimuth:st,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:st,by:null,calcMode:null,capHeight:st,className:hn,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:st,diffuseConstant:st,direction:null,display:null,dur:null,divisor:st,dominantBaseline:null,download:Lt,dx:null,dy:null,edgeMode:null,editable:null,elevation:st,enableBackground:null,end:null,event:null,exponent:st,externalResourcesRequired:null,fill:null,fillOpacity:st,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:pa,g2:pa,glyphName:pa,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:st,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:st,horizOriginX:st,horizOriginY:st,id:null,ideographic:st,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:st,k:st,k1:st,k2:st,k3:st,k4:st,kernelMatrix:xs,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:st,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:st,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:st,overlineThickness:st,paintOrder:null,panose1:null,path:null,pathLength:st,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:hn,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:st,pointsAtY:st,pointsAtZ:st,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:xs,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:xs,rev:xs,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:xs,requiredFeatures:xs,requiredFonts:xs,requiredFormats:xs,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:st,specularExponent:st,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:st,strikethroughThickness:st,string:null,stroke:null,strokeDashArray:xs,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:st,strokeOpacity:st,strokeWidth:null,style:null,surfaceScale:st,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:xs,tabIndex:st,tableValues:null,target:null,targetX:st,targetY:st,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:xs,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:st,underlineThickness:st,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:st,values:null,vAlphabetic:st,vMathematical:st,vectorEffect:null,vHanging:st,vIdeographic:st,version:null,vertAdvY:st,vertOriginX:st,vertOriginY:st,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:st,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Hp}),Vp=Ta({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()}}),Wp=Ta({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:qp}),Kp=Ta({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,n){return"xml:"+n.slice(3).toLowerCase()}}),X1={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"},Z1=/[A-Z]/g,tm=/-[a-z]/g,e0=/^data[-\w.:]+$/i;function t0(e,n){const s=Tc(n);let i=n,r=hs;if(s in e.normal)return e.property[e.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&e0.test(n)){if(n.charAt(4)==="-"){const o=n.slice(5).replace(tm,s0);i="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=n.slice(4);if(!tm.test(o)){let l=o.replace(Z1,n0);l.charAt(0)!=="-"&&(l="-"+l),n="data"+l}}r=md}return new r(i,n)}function n0(e){return"-"+e.toLowerCase()}function s0(e){return e.charAt(1).toUpperCase()}const i0=Bp([Up,Y1,Vp,Wp,Kp],"html"),hd=Bp([Up,Q1,Vp,Wp,Kp],"svg");function a0(e){return e.join(" ").trim()}var ra={},_l,nm;function r0(){if(nm)return _l;nm=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="",g="comment",p="declaration";function f(v,b){if(typeof v!="string")throw new TypeError("First argument must be a string");if(!v)return[];b=b||{};var y=1,S=1;function j($){var E=$.match(n);E&&(y+=E.length);var D=$.lastIndexOf(u);S=~D?$.length-D:S+$.length}function R(){var $={line:y,column:S};return function(E){return E.position=new k($),L(),E}}function k($){this.start=$,this.end={line:y,column:S},this.source=b.source}k.prototype.content=v;function M($){var E=new Error(b.source+":"+y+":"+S+": "+$);if(E.reason=$,E.filename=b.source,E.line=y,E.column=S,E.source=v,!b.silent)throw E}function C($){var E=$.exec(v);if(E){var D=E[0];return j(D),v=v.slice(D.length),E}}function L(){C(s)}function A($){var E;for($=$||[];E=P();)E!==!1&&$.push(E);return $}function P(){var $=R();if(!(d!=v.charAt(0)||m!=v.charAt(1))){for(var E=2;h!=v.charAt(E)&&(m!=v.charAt(E)||d!=v.charAt(E+1));)++E;if(E+=2,h===v.charAt(E-1))return M("End of comment missing");var D=v.slice(2,E-2);return S+=2,j(D),v=v.slice(E),S+=2,$({type:g,comment:D})}}function O(){var $=R(),E=C(i);if(E){if(P(),!C(r))return M("property missing ':'");var D=C(o),U=$({type:p,property:x(E[0].replace(e,h)),value:D?x(D[0].replace(e,h)):h});return C(l),U}}function V(){var $=[];A($);for(var E;E=O();)E!==!1&&($.push(E),A($));return $}return L(),V()}function x(v){return v?v.replace(c,h):h}return _l=f,_l}var sm;function o0(){if(sm)return ra;sm=1;var e=ra&&ra.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(ra,"__esModule",{value:!0}),ra.default=s;const n=e(r0());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 ra}var Ha={},im;function l0(){if(im)return Ha;im=1,Object.defineProperty(Ha,"__esModule",{value:!0}),Ha.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 Ha.camelCase=u,Ha}var qa,am;function c0(){if(am)return qa;am=1;var e=qa&&qa.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},n=e(o0()),s=l0();function i(r,o){var l={};return!r||typeof r!="string"||(0,n.default)(r,function(c,u){c&&u&&(l[(0,s.camelCase)(c,o)]=u)}),l}return i.default=i,qa=i,qa}var d0=c0();const u0=Fh(d0),Gp=Jp("end"),pd=Jp("start");function Jp(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 m0(e){const n=pd(e),s=Gp(e);if(n&&s)return{start:n,end:s}}function cr(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?rm(e.position):"start"in e||"end"in e?rm(e):"line"in e||"column"in e?$c(e):""}function $c(e){return om(e&&e.line)+":"+om(e&&e.column)}function rm(e){return $c(e&&e.start)+"-"+$c(e&&e.end)}function om(e){return e&&typeof e=="number"?e:1}class Zn 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=cr(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}}Zn.prototype.file="";Zn.prototype.name="";Zn.prototype.reason="";Zn.prototype.message="";Zn.prototype.stack="";Zn.prototype.column=void 0;Zn.prototype.line=void 0;Zn.prototype.ancestors=void 0;Zn.prototype.cause=void 0;Zn.prototype.fatal=void 0;Zn.prototype.place=void 0;Zn.prototype.ruleId=void 0;Zn.prototype.source=void 0;const fd={}.hasOwnProperty,h0=new Map,p0=/[A-Z]/g,f0=new Set(["table","tbody","thead","tfoot","tr"]),g0=new Set(["td","th"]),Yp="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function x0(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=S0(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=N0(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"?hd:i0,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},o=Qp(r,e,void 0);return o&&typeof o!="string"?o:r.create(e,r.Fragment,{children:o||void 0},void 0)}function Qp(e,n,s){if(n.type==="element")return b0(e,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return v0(e,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return j0(e,n,s);if(n.type==="mdxjsEsm")return y0(e,n);if(n.type==="root")return k0(e,n,s);if(n.type==="text")return w0(e,n)}function b0(e,n,s){const i=e.schema;let r=i;n.tagName.toLowerCase()==="svg"&&i.space==="html"&&(r=hd,e.schema=r),e.ancestors.push(n);const o=Zp(e,n.tagName,!1),l=C0(e,n);let c=xd(e,n);return f0.has(n.tagName)&&(c=c.filter(function(u){return typeof u=="string"?!G1(u):!0})),Xp(e,l,o,n),gd(l,c),e.ancestors.pop(),e.schema=i,e.create(n,o,l,s)}function v0(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)}yr(e,n.position)}function y0(e,n){if(n.data&&n.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(n.data.estree);yr(e,n.position)}function j0(e,n,s){const i=e.schema;let r=i;n.name==="svg"&&i.space==="html"&&(r=hd,e.schema=r),e.ancestors.push(n);const o=n.name===null?e.Fragment:Zp(e,n.name,!0),l=E0(e,n),c=xd(e,n);return Xp(e,l,o,n),gd(l,c),e.ancestors.pop(),e.schema=i,e.create(n,o,l,s)}function k0(e,n,s){const i={};return gd(i,xd(e,n)),e.create(n,e.Fragment,i,s)}function w0(e,n){return n.value}function Xp(e,n,s,i){typeof s!="string"&&s!==e.Fragment&&e.passNode&&(n.node=i)}function gd(e,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(e.children=s)}}function N0(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 S0(e,n){return s;function s(i,r,o,l){const c=Array.isArray(o.children),u=pd(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 C0(e,n){const s={};let i,r;for(r in n.properties)if(r!=="children"&&fd.call(n.properties,r)){const o=_0(e,r,n.properties[r]);if(o){const[l,c]=o;e.tableCellAlignToStyle&&l==="align"&&typeof c=="string"&&g0.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 E0(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 yr(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 yr(e,n.position);else o=i.value===null?!0:i.value;s[r]=o}return s}function xd(e,n){const s=[];let i=-1;const r=e.passKeys?new Map:h0;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=Qp(e,o,l);c!==void 0&&s.push(c)}return s}function _0(e,n,s){const i=t0(e.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=i.commaSeparated?H1(s):a0(s)),i.property==="style"){let r=typeof s=="object"?s:M0(e,String(s));return e.stylePropertyNameCase==="css"&&(r=A0(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&i.space?X1[i.property]||i.property:i.attribute,s]}}function M0(e,n){try{return u0(n,{reactCompat:!0})}catch(s){if(e.ignoreInvalidStyle)return{};const i=s,r=new Zn("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=Yp+"#cannot-parse-style-attribute",r}}function Zp(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=Xu(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=Xu(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(i.type==="Literal"){const r=i.value;return fd.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(i);yr(e)}function yr(e,n){const s=new Zn("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=Yp+"#cannot-handle-mdx-estrees-without-createevaluater",s}function A0(e){const n={};let s;for(s in e)fd.call(e,s)&&(n[R0(s)]=e[s]);return n}function R0(e){let n=e.replace(p0,T0);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function T0(e){return"-"+e.toLowerCase()}const Ml={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"]},P0={};function bd(e,n){const s=P0,i=typeof s.includeImageAlt=="boolean"?s.includeImageAlt:!0,r=typeof s.includeHtml=="boolean"?s.includeHtml:!0;return ef(e,i,r)}function ef(e,n,s){if(I0(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 lm(e.children,n,s)}return Array.isArray(e)?lm(e,n,s):""}function lm(e,n,s){const i=[];let r=-1;for(;++r<e.length;)i[r]=ef(e[r],n,s);return i.join("")}function I0(e){return!!(e&&typeof e=="object")}const cm=document.createElement("i");function vd(e){const n="&"+e+";";cm.innerHTML=n;const s=cm.textContent;return s.charCodeAt(s.length-1)===59&&e!=="semi"||s===n?!1:s}function js(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 Rs(e,n){return e.length>0?(js(e,e.length,0,n),e):n}const dm={}.hasOwnProperty;function tf(e){const n={};let s=-1;for(;++s<e.length;)$0(n,e[s]);return n}function $0(e,n){let s;for(s in n){const r=(dm.call(e,s)?e[s]:void 0)||(e[s]={}),o=n[s];let l;if(o)for(l in o){dm.call(r,l)||(r[l]=[]);const c=o[l];D0(r[l],Array.isArray(c)?c:c?[c]:[])}}}function D0(e,n){let s=-1;const i=[];for(;++s<n.length;)(n[s].add==="after"?e:i).push(n[s]);js(e,0,0,i)}function nf(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 Us(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const is=Ci(/[A-Za-z]/),Qn=Ci(/[\dA-Za-z]/),L0=Ci(/[#-'*+\--9=?A-Z^-~]/);function No(e){return e!==null&&(e<32||e===127)}const Dc=Ci(/\d/),z0=Ci(/[\dA-Fa-f]/),F0=Ci(/[!-/:-@[-`{-~]/);function kt(e){return e!==null&&e<-2}function cn(e){return e!==null&&(e<0||e===32)}function Ht(e){return e===-2||e===-1||e===32}const Ko=Ci(/\p{P}|\p{S}/u),Wi=Ci(/\s/);function Ci(e){return n;function n(s){return s!==null&&s>-1&&e.test(String.fromCharCode(s))}}function Pa(e){const n=[];let s=-1,i=0,r=0;for(;++s<e.length;){const o=e.charCodeAt(s);let l="";if(o===37&&Qn(e.charCodeAt(s+1))&&Qn(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 Kt(e,n,s,i){const r=i?i-1:Number.POSITIVE_INFINITY;let o=0;return l;function l(u){return Ht(u)?(e.enter(s),c(u)):n(u)}function c(u){return Ht(u)&&o++<r?(e.consume(u),c):(e.exit(s),n(u))}}const O0={tokenize:B0};function B0(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"),Kt(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 kt(c)?(e.consume(c),e.exit("chunkText"),o):(e.consume(c),l)}}const U0={tokenize:H0},um={tokenize:q0};function H0(e){const n=this,s=[];let i=0,r,o,l;return c;function c(S){if(i<s.length){const j=s[i];return n.containerState=j[1],e.attempt(j[0].continuation,u,d)(S)}return d(S)}function u(S){if(i++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,r&&y();const j=n.events.length;let R=j,k;for(;R--;)if(n.events[R][0]==="exit"&&n.events[R][1].type==="chunkFlow"){k=n.events[R][1].end;break}b(i);let M=j;for(;M<n.events.length;)n.events[M][1].end={...k},M++;return js(n.events,R+1,0,n.events.slice(j)),n.events.length=M,d(S)}return c(S)}function d(S){if(i===s.length){if(!r)return g(S);if(r.currentConstruct&&r.currentConstruct.concrete)return f(S);n.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return n.containerState={},e.check(um,m,h)(S)}function m(S){return r&&y(),b(i),g(S)}function h(S){return n.parser.lazy[n.now().line]=i!==s.length,l=n.now().offset,f(S)}function g(S){return n.containerState={},e.attempt(um,p,f)(S)}function p(S){return i++,s.push([n.currentConstruct,n.containerState]),g(S)}function f(S){if(S===null){r&&y(),b(0),e.consume(S);return}return r=r||n.parser.flow(n.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:o}),x(S)}function x(S){if(S===null){v(e.exit("chunkFlow"),!0),b(0),e.consume(S);return}return kt(S)?(e.consume(S),v(e.exit("chunkFlow")),i=0,n.interrupt=void 0,c):(e.consume(S),x)}function v(S,j){const R=n.sliceStream(S);if(j&&R.push(null),S.previous=o,o&&(o.next=S),o=S,r.defineSkip(S.start),r.write(R),n.parser.lazy[S.start.line]){let k=r.events.length;for(;k--;)if(r.events[k][1].start.offset<l&&(!r.events[k][1].end||r.events[k][1].end.offset>l))return;const M=n.events.length;let C=M,L,A;for(;C--;)if(n.events[C][0]==="exit"&&n.events[C][1].type==="chunkFlow"){if(L){A=n.events[C][1].end;break}L=!0}for(b(i),k=M;k<n.events.length;)n.events[k][1].end={...A},k++;js(n.events,C+1,0,n.events.slice(M)),n.events.length=k}}function b(S){let j=s.length;for(;j-- >S;){const R=s[j];n.containerState=R[1],R[0].exit.call(n,e)}s.length=S}function y(){r.write([null]),o=void 0,r=void 0,n.containerState._closeFlow=void 0}}function q0(e,n,s){return Kt(e,e.attempt(this.parser.constructs.document,n,s),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function ja(e){if(e===null||cn(e)||Wi(e))return 1;if(Ko(e))return 2}function Go(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 Lc={name:"attention",resolveAll:V0,tokenize:W0};function V0(e,n){let s=-1,i,r,o,l,c,u,d,m;for(;++s<e.length;)if(e[s][0]==="enter"&&e[s][1].type==="attentionSequence"&&e[s][1]._close){for(i=s;i--;)if(e[i][0]==="exit"&&e[i][1].type==="attentionSequence"&&e[i][1]._open&&n.sliceSerialize(e[i][1]).charCodeAt(0)===n.sliceSerialize(e[s][1]).charCodeAt(0)){if((e[i][1]._close||e[s][1]._open)&&(e[s][1].end.offset-e[s][1].start.offset)%3&&!((e[i][1].end.offset-e[i][1].start.offset+e[s][1].end.offset-e[s][1].start.offset)%3))continue;u=e[i][1].end.offset-e[i][1].start.offset>1&&e[s][1].end.offset-e[s][1].start.offset>1?2:1;const h={...e[i][1].end},g={...e[s][1].start};mm(h,-u),mm(g,u),l={type:u>1?"strongSequence":"emphasisSequence",start:h,end:{...e[i][1].end}},c={type:u>1?"strongSequence":"emphasisSequence",start:{...e[s][1].start},end:g},o={type:u>1?"strongText":"emphasisText",start:{...e[i][1].end},end:{...e[s][1].start}},r={type:u>1?"strong":"emphasis",start:{...l.start},end:{...c.end}},e[i][1].end={...l.start},e[s][1].start={...c.end},d=[],e[i][1].end.offset-e[i][1].start.offset&&(d=Rs(d,[["enter",e[i][1],n],["exit",e[i][1],n]])),d=Rs(d,[["enter",r,n],["enter",l,n],["exit",l,n],["enter",o,n]]),d=Rs(d,Go(n.parser.constructs.insideSpan.null,e.slice(i+1,s),n)),d=Rs(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=Rs(d,[["enter",e[s][1],n],["exit",e[s][1],n]])):m=0,js(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 W0(e,n){const s=this.parser.constructs.attentionMarkers.null,i=this.previous,r=ja(i);let o;return l;function l(u){return o=u,e.enter("attentionSequence"),c(u)}function c(u){if(u===o)return e.consume(u),c;const d=e.exit("attentionSequence"),m=ja(u),h=!m||m===2&&r||s.includes(u),g=!r||r===2&&m||s.includes(i);return d._open=!!(o===42?h:h&&(r||!g)),d._close=!!(o===42?g:g&&(m||!h)),n(u)}}function mm(e,n){e.column+=n,e.offset+=n,e._bufferIndex+=n}const K0={name:"autolink",tokenize:G0};function G0(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 is(p)?(e.consume(p),l):p===64?s(p):d(p)}function l(p){return p===43||p===45||p===46||Qn(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||Qn(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||No(p)?s(p):(e.consume(p),u)}function d(p){return p===64?(e.consume(p),m):L0(p)?(e.consume(p),d):s(p)}function m(p){return Qn(p)?h(p):s(p)}function h(p){return p===46?(e.consume(p),i=0,m):p===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.exit("autolink"),n):g(p)}function g(p){if((p===45||Qn(p))&&i++<63){const f=p===45?g:h;return e.consume(p),f}return s(p)}}const Ir={partial:!0,tokenize:J0};function J0(e,n,s){return i;function i(o){return Ht(o)?Kt(e,r,"linePrefix")(o):r(o)}function r(o){return o===null||kt(o)?n(o):s(o)}}const sf={continuation:{tokenize:Q0},exit:X0,name:"blockQuote",tokenize:Y0};function Y0(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 Ht(l)?(e.enter("blockQuotePrefixWhitespace"),e.consume(l),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),n):(e.exit("blockQuotePrefix"),n(l))}}function Q0(e,n,s){const i=this;return r;function r(l){return Ht(l)?Kt(e,o,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l):o(l)}function o(l){return e.attempt(sf,n,s)(l)}}function X0(e){e.exit("blockQuote")}const af={name:"characterEscape",tokenize:Z0};function Z0(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 F0(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),n):s(o)}}const rf={name:"characterReference",tokenize:eS};function eS(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=Qn,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=z0,m):(e.enter("characterReferenceValue"),o=7,l=Dc,m(h))}function m(h){if(h===59&&r){const g=e.exit("characterReferenceValue");return l===Qn&&!vd(i.sliceSerialize(g))?s(h):(e.enter("characterReferenceMarker"),e.consume(h),e.exit("characterReferenceMarker"),e.exit("characterReference"),n)}return l(h)&&r++<o?(e.consume(h),m):s(h)}}const hm={partial:!0,tokenize:nS},pm={concrete:!0,name:"codeFenced",tokenize:tS};function tS(e,n,s){const i=this,r={partial:!0,tokenize:R};let o=0,l=0,c;return u;function u(k){return d(k)}function d(k){const M=i.events[i.events.length-1];return o=M&&M[1].type==="linePrefix"?M[2].sliceSerialize(M[1],!0).length:0,c=k,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),m(k)}function m(k){return k===c?(l++,e.consume(k),m):l<3?s(k):(e.exit("codeFencedFenceSequence"),Ht(k)?Kt(e,h,"whitespace")(k):h(k))}function h(k){return k===null||kt(k)?(e.exit("codeFencedFence"),i.interrupt?n(k):e.check(hm,x,j)(k)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),g(k))}function g(k){return k===null||kt(k)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),h(k)):Ht(k)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),Kt(e,p,"whitespace")(k)):k===96&&k===c?s(k):(e.consume(k),g)}function p(k){return k===null||kt(k)?h(k):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),f(k))}function f(k){return k===null||kt(k)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),h(k)):k===96&&k===c?s(k):(e.consume(k),f)}function x(k){return e.attempt(r,j,v)(k)}function v(k){return e.enter("lineEnding"),e.consume(k),e.exit("lineEnding"),b}function b(k){return o>0&&Ht(k)?Kt(e,y,"linePrefix",o+1)(k):y(k)}function y(k){return k===null||kt(k)?e.check(hm,x,j)(k):(e.enter("codeFlowValue"),S(k))}function S(k){return k===null||kt(k)?(e.exit("codeFlowValue"),y(k)):(e.consume(k),S)}function j(k){return e.exit("codeFenced"),n(k)}function R(k,M,C){let L=0;return A;function A(E){return k.enter("lineEnding"),k.consume(E),k.exit("lineEnding"),P}function P(E){return k.enter("codeFencedFence"),Ht(E)?Kt(k,O,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(E):O(E)}function O(E){return E===c?(k.enter("codeFencedFenceSequence"),V(E)):C(E)}function V(E){return E===c?(L++,k.consume(E),V):L>=l?(k.exit("codeFencedFenceSequence"),Ht(E)?Kt(k,$,"whitespace")(E):$(E)):C(E)}function $(E){return E===null||kt(E)?(k.exit("codeFencedFence"),M(E)):C(E)}}}function nS(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 Al={name:"codeIndented",tokenize:iS},sS={partial:!0,tokenize:aS};function iS(e,n,s){const i=this;return r;function r(d){return e.enter("codeIndented"),Kt(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):kt(d)?e.attempt(sS,l,u)(d):(e.enter("codeFlowValue"),c(d))}function c(d){return d===null||kt(d)?(e.exit("codeFlowValue"),l(d)):(e.consume(d),c)}function u(d){return e.exit("codeIndented"),n(d)}}function aS(e,n,s){const i=this;return r;function r(l){return i.parser.lazy[i.now().line]?s(l):kt(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),r):Kt(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):kt(l)?r(l):s(l)}}const rS={name:"codeText",previous:lS,resolve:oS,tokenize:cS};function oS(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 lS(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function cS(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)):kt(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||kt(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 dS{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&&Va(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),Va(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),Va(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);Va(this.right,s.reverse())}else{const s=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);Va(this.left,s.reverse())}}}function Va(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 of(e){const n={};let s=-1,i,r,o,l,c,u,d;const m=new dS(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,uS(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 js(e,0,Number.POSITIVE_INFINITY,m.slice(0)),!d}function uS(e,n){const s=e.get(n)[1],i=e.get(n)[2];let r=n-1;const o=[];let l=s._tokenizer;l||(l=i.parser[s.contentType](s.start),s._contentTypeTextTrailing&&(l._contentTypeTextTrailing=!0));const c=l.events,u=[],d={};let m,h,g=-1,p=s,f=0,x=0;const v=[x];for(;p;){for(;e.get(++r)[1]!==p;);o.push(r),p._tokenizer||(m=i.sliceStream(p),p.next||m.push(null),h&&l.defineSkip(p.start),p._isInFirstContentOfListItem&&(l._gfmTasklistFirstContentOfListItem=!0),l.write(m),p._isInFirstContentOfListItem&&(l._gfmTasklistFirstContentOfListItem=void 0)),h=p,p=p.next}for(p=s;++g<c.length;)c[g][0]==="exit"&&c[g-1][0]==="enter"&&c[g][1].type===c[g-1][1].type&&c[g][1].start.line!==c[g][1].end.line&&(x=g+1,v.push(x),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(l.events=[],p?(p._tokenizer=void 0,p.previous=void 0):v.pop(),g=v.length;g--;){const b=c.slice(v[g],v[g+1]),y=o.pop();u.push([y,y+b.length-1]),e.splice(y,2,b)}for(u.reverse(),g=-1;++g<u.length;)d[f+u[g][0]]=f+u[g][1],f+=u[g][1]-u[g][0]-1;return d}const mS={resolve:pS,tokenize:fS},hS={partial:!0,tokenize:gS};function pS(e){return of(e),e}function fS(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):kt(c)?e.check(hS,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 gS(e,n,s){const i=this;return r;function r(l){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),Kt(e,o,"linePrefix")}function o(l){if(l===null||kt(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 lf(e,n,s,i,r,o,l,c,u){const d=u||Number.POSITIVE_INFINITY;let m=0;return h;function h(b){return b===60?(e.enter(i),e.enter(r),e.enter(o),e.consume(b),e.exit(o),g):b===null||b===32||b===41||No(b)?s(b):(e.enter(i),e.enter(l),e.enter(c),e.enter("chunkString",{contentType:"string"}),x(b))}function g(b){return b===62?(e.enter(o),e.consume(b),e.exit(o),e.exit(r),e.exit(i),n):(e.enter(c),e.enter("chunkString",{contentType:"string"}),p(b))}function p(b){return b===62?(e.exit("chunkString"),e.exit(c),g(b)):b===null||b===60||kt(b)?s(b):(e.consume(b),b===92?f:p)}function f(b){return b===60||b===62||b===92?(e.consume(b),p):p(b)}function x(b){return!m&&(b===null||b===41||cn(b))?(e.exit("chunkString"),e.exit(c),e.exit(l),e.exit(i),n(b)):m<d&&b===40?(e.consume(b),m++,x):b===41?(e.consume(b),m--,x):b===null||b===32||b===40||No(b)?s(b):(e.consume(b),b===92?v:x)}function v(b){return b===40||b===41||b===92?(e.consume(b),x):x(b)}}function cf(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):kt(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||kt(p)||c++>999?(e.exit("chunkString"),m(p)):(e.consume(p),u||(u=!Ht(p)),p===92?g:h)}function g(p){return p===91||p===92||p===93?(e.consume(p),c++,h):h(p)}}function df(e,n,s,i,r,o){let l;return c;function c(g){return g===34||g===39||g===40?(e.enter(i),e.enter(r),e.consume(g),e.exit(r),l=g===40?41:g,u):s(g)}function u(g){return g===l?(e.enter(r),e.consume(g),e.exit(r),e.exit(i),n):(e.enter(o),d(g))}function d(g){return g===l?(e.exit(o),u(l)):g===null?s(g):kt(g)?(e.enter("lineEnding"),e.consume(g),e.exit("lineEnding"),Kt(e,d,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),m(g))}function m(g){return g===l||g===null||kt(g)?(e.exit("chunkString"),d(g)):(e.consume(g),g===92?h:m)}function h(g){return g===l||g===92?(e.consume(g),m):m(g)}}function dr(e,n){let s;return i;function i(r){return kt(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),s=!0,i):Ht(r)?Kt(e,i,s?"linePrefix":"lineSuffix")(r):n(r)}}const xS={name:"definition",tokenize:vS},bS={partial:!0,tokenize:yS};function vS(e,n,s){const i=this;let r;return o;function o(p){return e.enter("definition"),l(p)}function l(p){return cf.call(i,e,c,s,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function c(p){return r=Us(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 cn(p)?dr(e,d)(p):d(p)}function d(p){return lf(e,m,s,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function m(p){return e.attempt(bS,h,h)(p)}function h(p){return Ht(p)?Kt(e,g,"whitespace")(p):g(p)}function g(p){return p===null||kt(p)?(e.exit("definition"),i.parser.defined.push(r),n(p)):s(p)}}function yS(e,n,s){return i;function i(c){return cn(c)?dr(e,r)(c):s(c)}function r(c){return df(e,o,s,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function o(c){return Ht(c)?Kt(e,l,"whitespace")(c):l(c)}function l(c){return c===null||kt(c)?n(c):s(c)}}const jS={name:"hardBreakEscape",tokenize:kS};function kS(e,n,s){return i;function i(o){return e.enter("hardBreakEscape"),e.consume(o),r}function r(o){return kt(o)?(e.exit("hardBreakEscape"),n(o)):s(o)}}const wS={name:"headingAtx",resolve:NS,tokenize:SS};function NS(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"},js(e,i,s-i+1,[["enter",r,n],["enter",o,n],["exit",o,n],["exit",r,n]])),e}function SS(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||cn(m)?(e.exit("atxHeadingSequence"),c(m)):s(m)}function c(m){return m===35?(e.enter("atxHeadingSequence"),u(m)):m===null||kt(m)?(e.exit("atxHeading"),n(m)):Ht(m)?Kt(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||cn(m)?(e.exit("atxHeadingText"),c(m)):(e.consume(m),d)}}const CS=["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"],fm=["pre","script","style","textarea"],ES={concrete:!0,name:"htmlFlow",resolveTo:AS,tokenize:RS},_S={partial:!0,tokenize:PS},MS={partial:!0,tokenize:TS};function AS(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 RS(e,n,s){const i=this;let r,o,l,c,u;return d;function d(w){return m(w)}function m(w){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(w),h}function h(w){return w===33?(e.consume(w),g):w===47?(e.consume(w),o=!0,x):w===63?(e.consume(w),r=3,i.interrupt?n:_):is(w)?(e.consume(w),l=String.fromCharCode(w),v):s(w)}function g(w){return w===45?(e.consume(w),r=2,p):w===91?(e.consume(w),r=5,c=0,f):is(w)?(e.consume(w),r=4,i.interrupt?n:_):s(w)}function p(w){return w===45?(e.consume(w),i.interrupt?n:_):s(w)}function f(w){const q="CDATA[";return w===q.charCodeAt(c++)?(e.consume(w),c===q.length?i.interrupt?n:O:f):s(w)}function x(w){return is(w)?(e.consume(w),l=String.fromCharCode(w),v):s(w)}function v(w){if(w===null||w===47||w===62||cn(w)){const q=w===47,G=l.toLowerCase();return!q&&!o&&fm.includes(G)?(r=1,i.interrupt?n(w):O(w)):CS.includes(l.toLowerCase())?(r=6,q?(e.consume(w),b):i.interrupt?n(w):O(w)):(r=7,i.interrupt&&!i.parser.lazy[i.now().line]?s(w):o?y(w):S(w))}return w===45||Qn(w)?(e.consume(w),l+=String.fromCharCode(w),v):s(w)}function b(w){return w===62?(e.consume(w),i.interrupt?n:O):s(w)}function y(w){return Ht(w)?(e.consume(w),y):A(w)}function S(w){return w===47?(e.consume(w),A):w===58||w===95||is(w)?(e.consume(w),j):Ht(w)?(e.consume(w),S):A(w)}function j(w){return w===45||w===46||w===58||w===95||Qn(w)?(e.consume(w),j):R(w)}function R(w){return w===61?(e.consume(w),k):Ht(w)?(e.consume(w),R):S(w)}function k(w){return w===null||w===60||w===61||w===62||w===96?s(w):w===34||w===39?(e.consume(w),u=w,M):Ht(w)?(e.consume(w),k):C(w)}function M(w){return w===u?(e.consume(w),u=null,L):w===null||kt(w)?s(w):(e.consume(w),M)}function C(w){return w===null||w===34||w===39||w===47||w===60||w===61||w===62||w===96||cn(w)?R(w):(e.consume(w),C)}function L(w){return w===47||w===62||Ht(w)?S(w):s(w)}function A(w){return w===62?(e.consume(w),P):s(w)}function P(w){return w===null||kt(w)?O(w):Ht(w)?(e.consume(w),P):s(w)}function O(w){return w===45&&r===2?(e.consume(w),D):w===60&&r===1?(e.consume(w),U):w===62&&r===4?(e.consume(w),I):w===63&&r===3?(e.consume(w),_):w===93&&r===5?(e.consume(w),X):kt(w)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(_S,T,V)(w)):w===null||kt(w)?(e.exit("htmlFlowData"),V(w)):(e.consume(w),O)}function V(w){return e.check(MS,$,T)(w)}function $(w){return e.enter("lineEnding"),e.consume(w),e.exit("lineEnding"),E}function E(w){return w===null||kt(w)?V(w):(e.enter("htmlFlowData"),O(w))}function D(w){return w===45?(e.consume(w),_):O(w)}function U(w){return w===47?(e.consume(w),l="",Y):O(w)}function Y(w){if(w===62){const q=l.toLowerCase();return fm.includes(q)?(e.consume(w),I):O(w)}return is(w)&&l.length<8?(e.consume(w),l+=String.fromCharCode(w),Y):O(w)}function X(w){return w===93?(e.consume(w),_):O(w)}function _(w){return w===62?(e.consume(w),I):w===45&&r===2?(e.consume(w),_):O(w)}function I(w){return w===null||kt(w)?(e.exit("htmlFlowData"),T(w)):(e.consume(w),I)}function T(w){return e.exit("htmlFlow"),n(w)}}function TS(e,n,s){const i=this;return r;function r(l){return kt(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 PS(e,n,s){return i;function i(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(Ir,n,s)}}const IS={name:"htmlText",tokenize:$S};function $S(e,n,s){const i=this;let r,o,l;return c;function c(_){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(_),u}function u(_){return _===33?(e.consume(_),d):_===47?(e.consume(_),R):_===63?(e.consume(_),S):is(_)?(e.consume(_),C):s(_)}function d(_){return _===45?(e.consume(_),m):_===91?(e.consume(_),o=0,f):is(_)?(e.consume(_),y):s(_)}function m(_){return _===45?(e.consume(_),p):s(_)}function h(_){return _===null?s(_):_===45?(e.consume(_),g):kt(_)?(l=h,U(_)):(e.consume(_),h)}function g(_){return _===45?(e.consume(_),p):h(_)}function p(_){return _===62?D(_):_===45?g(_):h(_)}function f(_){const I="CDATA[";return _===I.charCodeAt(o++)?(e.consume(_),o===I.length?x:f):s(_)}function x(_){return _===null?s(_):_===93?(e.consume(_),v):kt(_)?(l=x,U(_)):(e.consume(_),x)}function v(_){return _===93?(e.consume(_),b):x(_)}function b(_){return _===62?D(_):_===93?(e.consume(_),b):x(_)}function y(_){return _===null||_===62?D(_):kt(_)?(l=y,U(_)):(e.consume(_),y)}function S(_){return _===null?s(_):_===63?(e.consume(_),j):kt(_)?(l=S,U(_)):(e.consume(_),S)}function j(_){return _===62?D(_):S(_)}function R(_){return is(_)?(e.consume(_),k):s(_)}function k(_){return _===45||Qn(_)?(e.consume(_),k):M(_)}function M(_){return kt(_)?(l=M,U(_)):Ht(_)?(e.consume(_),M):D(_)}function C(_){return _===45||Qn(_)?(e.consume(_),C):_===47||_===62||cn(_)?L(_):s(_)}function L(_){return _===47?(e.consume(_),D):_===58||_===95||is(_)?(e.consume(_),A):kt(_)?(l=L,U(_)):Ht(_)?(e.consume(_),L):D(_)}function A(_){return _===45||_===46||_===58||_===95||Qn(_)?(e.consume(_),A):P(_)}function P(_){return _===61?(e.consume(_),O):kt(_)?(l=P,U(_)):Ht(_)?(e.consume(_),P):L(_)}function O(_){return _===null||_===60||_===61||_===62||_===96?s(_):_===34||_===39?(e.consume(_),r=_,V):kt(_)?(l=O,U(_)):Ht(_)?(e.consume(_),O):(e.consume(_),$)}function V(_){return _===r?(e.consume(_),r=void 0,E):_===null?s(_):kt(_)?(l=V,U(_)):(e.consume(_),V)}function $(_){return _===null||_===34||_===39||_===60||_===61||_===96?s(_):_===47||_===62||cn(_)?L(_):(e.consume(_),$)}function E(_){return _===47||_===62||cn(_)?L(_):s(_)}function D(_){return _===62?(e.consume(_),e.exit("htmlTextData"),e.exit("htmlText"),n):s(_)}function U(_){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(_),e.exit("lineEnding"),Y}function Y(_){return Ht(_)?Kt(e,X,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(_):X(_)}function X(_){return e.enter("htmlTextData"),l(_)}}const yd={name:"labelEnd",resolveAll:FS,resolveTo:OS,tokenize:BS},DS={tokenize:US},LS={tokenize:HS},zS={tokenize:qS};function FS(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&&js(e,0,e.length,s),e}function OS(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=Rs(c,e.slice(o+1,o+i+3)),c=Rs(c,[["enter",m,n]]),c=Rs(c,Go(n.parser.constructs.insideSpan.null,e.slice(o+i+4,l-3),n)),c=Rs(c,[["exit",m,n],e[l-2],e[l-1],["exit",d,n]]),c=Rs(c,e.slice(l+1)),c=Rs(c,[["exit",u,n]]),js(e,o,e.length,c),e}function BS(e,n,s){const i=this;let r=i.events.length,o,l;for(;r--;)if((i.events[r][1].type==="labelImage"||i.events[r][1].type==="labelLink")&&!i.events[r][1]._balanced){o=i.events[r][1];break}return c;function c(g){return o?o._inactive?h(g):(l=i.parser.defined.includes(Us(i.sliceSerialize({start:o.end,end:i.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(g),e.exit("labelMarker"),e.exit("labelEnd"),u):s(g)}function u(g){return g===40?e.attempt(DS,m,l?m:h)(g):g===91?e.attempt(LS,m,l?d:h)(g):l?m(g):h(g)}function d(g){return e.attempt(zS,m,h)(g)}function m(g){return n(g)}function h(g){return o._balanced=!0,s(g)}}function US(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 cn(h)?dr(e,o)(h):o(h)}function o(h){return h===41?m(h):lf(e,l,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function l(h){return cn(h)?dr(e,u)(h):m(h)}function c(h){return s(h)}function u(h){return h===34||h===39||h===40?df(e,d,s,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):m(h)}function d(h){return cn(h)?dr(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 HS(e,n,s){const i=this;return r;function r(c){return cf.call(i,e,o,l,"reference","referenceMarker","referenceString")(c)}function o(c){return i.parser.defined.includes(Us(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)))?n(c):s(c)}function l(c){return s(c)}}function qS(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 VS={name:"labelStartImage",resolveAll:yd.resolveAll,tokenize:WS};function WS(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 KS={name:"labelStartLink",resolveAll:yd.resolveAll,tokenize:GS};function GS(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 Rl={name:"lineEnding",tokenize:JS};function JS(e,n){return s;function s(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),Kt(e,n,"linePrefix")}}const co={name:"thematicBreak",tokenize:YS};function YS(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||kt(d))?(e.exit("thematicBreak"),n(d)):s(d)}function u(d){return d===r?(e.consume(d),i++,u):(e.exit("thematicBreakSequence"),Ht(d)?Kt(e,c,"whitespace")(d):c(d))}}const cs={continuation:{tokenize:eC},exit:nC,name:"list",tokenize:ZS},QS={partial:!0,tokenize:sC},XS={partial:!0,tokenize:tC};function ZS(e,n,s){const i=this,r=i.events[i.events.length-1];let o=r&&r[1].type==="linePrefix"?r[2].sliceSerialize(r[1],!0).length:0,l=0;return c;function c(p){const f=i.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(f==="listUnordered"?!i.containerState.marker||p===i.containerState.marker:Dc(p)){if(i.containerState.type||(i.containerState.type=f,e.enter(f,{_container:!0})),f==="listUnordered")return e.enter("listItemPrefix"),p===42||p===45?e.check(co,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 Dc(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(Ir,i.interrupt?s:m,e.attempt(QS,g,h))}function m(p){return i.containerState.initialBlankLine=!0,o++,g(p)}function h(p){return Ht(p)?(e.enter("listItemPrefixWhitespace"),e.consume(p),e.exit("listItemPrefixWhitespace"),g):s(p)}function g(p){return i.containerState.size=o+i.sliceSerialize(e.exit("listItemPrefix"),!0).length,n(p)}}function eC(e,n,s){const i=this;return i.containerState._closeFlow=void 0,e.check(Ir,r,o);function r(c){return i.containerState.furtherBlankLines=i.containerState.furtherBlankLines||i.containerState.initialBlankLine,Kt(e,n,"listItemIndent",i.containerState.size+1)(c)}function o(c){return i.containerState.furtherBlankLines||!Ht(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(XS,n,l)(c))}function l(c){return i.containerState._closeFlow=!0,i.interrupt=void 0,Kt(e,e.attempt(cs,n,s),"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function tC(e,n,s){const i=this;return Kt(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 nC(e){e.exit(this.containerState.type)}function sC(e,n,s){const i=this;return Kt(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!Ht(o)&&l&&l[1].type==="listItemPrefixWhitespace"?n(o):s(o)}}const gm={name:"setextUnderline",resolveTo:iC,tokenize:aC};function iC(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 aC(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"),Ht(d)?Kt(e,u,"lineSuffix")(d):u(d))}function u(d){return d===null||kt(d)?(e.exit("setextHeadingLine"),n(d)):s(d)}}const rC={tokenize:oC};function oC(e){const n=this,s=e.attempt(Ir,i,e.attempt(this.parser.constructs.flowInitial,r,Kt(e,e.attempt(this.parser.constructs.flow,r,e.attempt(mS,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 lC={resolveAll:mf()},cC=uf("string"),dC=uf("text");function uf(e){return{resolveAll:mf(e==="text"?uC:void 0),tokenize:n};function n(s){const i=this,r=this.parser.constructs[e],o=s.attempt(r,l,c);return l;function l(m){return d(m)?o(m):c(m)}function c(m){if(m===null){s.consume(m);return}return s.enter("data"),s.consume(m),u}function u(m){return d(m)?(s.exit("data"),o(m)):(s.consume(m),u)}function d(m){if(m===null)return!0;const h=r[m];let g=-1;if(h)for(;++g<h.length;){const p=h[g];if(!p.previous||p.previous.call(i,i.previous))return!0}return!1}}}function mf(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 uC(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 mC={42:cs,43:cs,45:cs,48:cs,49:cs,50:cs,51:cs,52:cs,53:cs,54:cs,55:cs,56:cs,57:cs,62:sf},hC={91:xS},pC={[-2]:Al,[-1]:Al,32:Al},fC={35:wS,42:co,45:[gm,co],60:ES,61:gm,95:co,96:pm,126:pm},gC={38:rf,92:af},xC={[-5]:Rl,[-4]:Rl,[-3]:Rl,33:VS,38:rf,42:Lc,60:[K0,IS],91:KS,92:[jS,af],93:yd,95:Lc,96:rS},bC={null:[Lc,lC]},vC={null:[42,95]},yC={null:[]},jC=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:vC,contentInitial:hC,disable:yC,document:mC,flow:fC,flowInitial:pC,insideSpan:bC,string:gC,text:xC},Symbol.toStringTag,{value:"Module"}));function kC(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(R),check:M(k),consume:y,enter:S,exit:j,interrupt:M(k,{interrupt:!0})},d={code:null,containerState:{},defineSkip:x,events:[],now:f,parser:e,previous:null,sliceSerialize:g,sliceStream:p,write:h};let m=n.tokenize.call(d,u);return n.resolveAll&&o.push(n),d;function h(P){return l=Rs(l,P),v(),l[l.length-1]!==null?[]:(C(n,0),d.events=Go(o,d.events,d),d.events)}function g(P,O){return NC(p(P),O)}function p(P){return wC(l,P)}function f(){const{_bufferIndex:P,_index:O,line:V,column:$,offset:E}=i;return{_bufferIndex:P,_index:O,line:V,column:$,offset:E}}function x(P){r[P.line]=P.column,A()}function v(){let P;for(;i._index<l.length;){const O=l[i._index];if(typeof O=="string")for(P=i._index,i._bufferIndex<0&&(i._bufferIndex=0);i._index===P&&i._bufferIndex<O.length;)b(O.charCodeAt(i._bufferIndex));else b(O)}}function b(P){m=m(P)}function y(P){kt(P)?(i.line++,i.column=1,i.offset+=P===-3?2:1,A()):P!==-1&&(i.column++,i.offset++),i._bufferIndex<0?i._index++:(i._bufferIndex++,i._bufferIndex===l[i._index].length&&(i._bufferIndex=-1,i._index++)),d.previous=P}function S(P,O){const V=O||{};return V.type=P,V.start=f(),d.events.push(["enter",V,d]),c.push(V),V}function j(P){const O=c.pop();return O.end=f(),d.events.push(["exit",O,d]),O}function R(P,O){C(P,O.from)}function k(P,O){O.restore()}function M(P,O){return V;function V($,E,D){let U,Y,X,_;return Array.isArray($)?T($):"tokenize"in $?T([$]):I($);function I(me){return ue;function ue(le){const Se=le!==null&&me[le],F=le!==null&&me.null,ge=[...Array.isArray(Se)?Se:Se?[Se]:[],...Array.isArray(F)?F:F?[F]:[]];return T(ge)(le)}}function T(me){return U=me,Y=0,me.length===0?D:w(me[Y])}function w(me){return ue;function ue(le){return _=L(),X=me,me.partial||(d.currentConstruct=me),me.name&&d.parser.constructs.disable.null.includes(me.name)?G():me.tokenize.call(O?Object.assign(Object.create(d),O):d,u,q,G)(le)}}function q(me){return P(X,_),E}function G(me){return _.restore(),++Y<U.length?w(U[Y]):D}}}function C(P,O){P.resolveAll&&!o.includes(P)&&o.push(P),P.resolve&&js(d.events,O,d.events.length-O,P.resolve(d.events.slice(O),d)),P.resolveTo&&(d.events=P.resolveTo(d.events,d))}function L(){const P=f(),O=d.previous,V=d.currentConstruct,$=d.events.length,E=Array.from(c);return{from:$,restore:D};function D(){i=P,d.previous=O,d.currentConstruct=V,d.events.length=$,c=E,A()}}function A(){i.line in r&&i.column<2&&(i.column=r[i.line],i.offset+=r[i.line]-1)}}function wC(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 NC(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 SC(e){const i={constructs:tf([jC,...(e||{}).extensions||[]]),content:r(O0),defined:[],document:r(U0),flow:r(rC),lazy:{},string:r(cC),text:r(dC)};return i;function r(o){return l;function l(c){return kC(i,o,c)}}}function CC(e){for(;!of(e););return e}const xm=/[\0\t\n\r]/g;function EC(){let e=1,n="",s=!0,i;return r;function r(o,l,c){const u=[];let d,m,h,g,p;for(o=n+(typeof o=="string"?o.toString():new TextDecoder(l||void 0).decode(o)),h=0,n="",s&&(o.charCodeAt(0)===65279&&h++,s=void 0);h<o.length;){if(xm.lastIndex=h,d=xm.exec(o),g=d&&d.index!==void 0?d.index:o.length,p=o.charCodeAt(g),!d){n=o.slice(h);break}if(p===10&&h===g&&i)u.push(-3),i=void 0;else switch(i&&(u.push(-5),i=void 0),h<g&&(u.push(o.slice(h,g)),e+=g-h),p){case 0:{u.push(65533),e++;break}case 9:{for(m=Math.ceil(e/4)*4,u.push(-2);e++<m;)u.push(-1);break}case 10:{u.push(-4),e=1;break}default:i=!0,e=1}h=g+1}return c&&(i&&u.push(-5),n&&u.push(n),u.push(null)),u}}const _C=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function MC(e){return e.replace(_C,AC)}function AC(e,n,s){if(n)return n;if(s.charCodeAt(0)===35){const r=s.charCodeAt(1),o=r===120||r===88;return nf(s.slice(o?2:1),o?16:10)}return vd(s)||e}const hf={}.hasOwnProperty;function RC(e,n,s){return n&&typeof n=="object"&&(s=n,n=void 0),TC(s)(CC(SC(s).document().write(EC()(e,n,!0))))}function TC(e){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(qe),autolinkProtocol:L,autolinkEmail:L,atxHeading:o(xe),blockQuote:o(F),characterEscape:L,characterReference:L,codeFenced:o(ge),codeFencedFenceInfo:l,codeFencedFenceMeta:l,codeIndented:o(ge,l),codeText:o(se,l),codeTextData:L,data:L,codeFlowValue:L,definition:o(fe),definitionDestinationString:l,definitionLabelString:l,definitionTitleString:l,emphasis:o(de),hardBreakEscape:o(ie),hardBreakTrailing:o(ie),htmlFlow:o(Ee,l),htmlFlowData:L,htmlText:o(Ee,l),htmlTextData:L,image:o(De),label:l,link:o(qe),listItem:o(Je),listItemValue:g,listOrdered:o(Qe,h),listUnordered:o(Qe),paragraph:o(Ke),reference:w,referenceString:l,resourceDestinationString:l,resourceTitleString:l,setextHeading:o(xe),strong:o(it),thematicBreak:o(Ve)},exit:{atxHeading:u(),atxHeadingSequence:R,autolink:u(),autolinkEmail:Se,autolinkProtocol:le,blockQuote:u(),characterEscapeValue:A,characterReferenceMarkerHexadecimal:G,characterReferenceMarkerNumeric:G,characterReferenceValue:me,characterReference:ue,codeFenced:u(v),codeFencedFence:x,codeFencedFenceInfo:p,codeFencedFenceMeta:f,codeFlowValue:A,codeIndented:u(b),codeText:u(E),codeTextData:A,data:A,definition:u(),definitionDestinationString:j,definitionLabelString:y,definitionTitleString:S,emphasis:u(),hardBreakEscape:u(O),hardBreakTrailing:u(O),htmlFlow:u(V),htmlFlowData:A,htmlText:u($),htmlTextData:A,image:u(U),label:X,labelText:Y,lineEnding:P,link:u(D),listItem:u(),listOrdered:u(),listUnordered:u(),paragraph:u(),referenceString:q,resourceDestinationString:_,resourceTitleString:I,resource:T,setextHeading:u(C),setextHeadingLineSequence:M,setextHeadingText:k,strong:u(),thematicBreak:u()}};pf(n,(e||{}).mdastExtensions||[]);const s={};return i;function i(ae){let ye={type:"root",children:[]};const te={stack:[ye],tokenStack:[],config:n,enter:c,exit:d,buffer:l,resume:m,data:s},Ae=[];let Le=-1;for(;++Le<ae.length;)if(ae[Le][1].type==="listOrdered"||ae[Le][1].type==="listUnordered")if(ae[Le][0]==="enter")Ae.push(Le);else{const pe=Ae.pop();Le=r(ae,pe,Le)}for(Le=-1;++Le<ae.length;){const pe=n[ae[Le][0]];hf.call(pe,ae[Le][1].type)&&pe[ae[Le][1].type].call(Object.assign({sliceSerialize:ae[Le][2].sliceSerialize},te),ae[Le][1])}if(te.tokenStack.length>0){const pe=te.tokenStack[te.tokenStack.length-1];(pe[1]||bm).call(te,void 0,pe[0])}for(ye.position={start:vi(ae.length>0?ae[0][1].start:{line:1,column:1,offset:0}),end:vi(ae.length>0?ae[ae.length-2][1].end:{line:1,column:1,offset:0})},Le=-1;++Le<n.transforms.length;)ye=n.transforms[Le](ye)||ye;return ye}function r(ae,ye,te){let Ae=ye-1,Le=-1,pe=!1,_e,Fe,tt,Ne;for(;++Ae<=te;){const oe=ae[Ae];switch(oe[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{oe[0]==="enter"?Le++:Le--,Ne=void 0;break}case"lineEndingBlank":{oe[0]==="enter"&&(_e&&!Ne&&!Le&&!tt&&(tt=Ae),Ne=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:Ne=void 0}if(!Le&&oe[0]==="enter"&&oe[1].type==="listItemPrefix"||Le===-1&&oe[0]==="exit"&&(oe[1].type==="listUnordered"||oe[1].type==="listOrdered")){if(_e){let Te=Ae;for(Fe=void 0;Te--;){const he=ae[Te];if(he[1].type==="lineEnding"||he[1].type==="lineEndingBlank"){if(he[0]==="exit")continue;Fe&&(ae[Fe][1].type="lineEndingBlank",pe=!0),he[1].type="lineEnding",Fe=Te}else if(!(he[1].type==="linePrefix"||he[1].type==="blockQuotePrefix"||he[1].type==="blockQuotePrefixWhitespace"||he[1].type==="blockQuoteMarker"||he[1].type==="listItemIndent"))break}tt&&(!Fe||tt<Fe)&&(_e._spread=!0),_e.end=Object.assign({},Fe?ae[Fe][1].start:oe[1].end),ae.splice(Fe||Ae,0,["exit",_e,oe[2]]),Ae++,te++}if(oe[1].type==="listItemPrefix"){const Te={type:"listItem",_spread:!1,start:Object.assign({},oe[1].start),end:void 0};_e=Te,ae.splice(Ae,0,["enter",Te,oe[2]]),Ae++,te++,tt=void 0,Ne=!0}}}return ae[ye][1]._spread=pe,te}function o(ae,ye){return te;function te(Ae){c.call(this,ae(Ae),Ae),ye&&ye.call(this,Ae)}}function l(){this.stack.push({type:"fragment",children:[]})}function c(ae,ye,te){this.stack[this.stack.length-1].children.push(ae),this.stack.push(ae),this.tokenStack.push([ye,te||void 0]),ae.position={start:vi(ye.start),end:void 0}}function u(ae){return ye;function ye(te){ae&&ae.call(this,te),d.call(this,te)}}function d(ae,ye){const te=this.stack.pop(),Ae=this.tokenStack.pop();if(Ae)Ae[0].type!==ae.type&&(ye?ye.call(this,ae,Ae[0]):(Ae[1]||bm).call(this,ae,Ae[0]));else throw new Error("Cannot close `"+ae.type+"` ("+cr({start:ae.start,end:ae.end})+"): it’s not open");te.position.end=vi(ae.end)}function m(){return bd(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function g(ae){if(this.data.expectingFirstListItemValue){const ye=this.stack[this.stack.length-2];ye.start=Number.parseInt(this.sliceSerialize(ae),10),this.data.expectingFirstListItemValue=void 0}}function p(){const ae=this.resume(),ye=this.stack[this.stack.length-1];ye.lang=ae}function f(){const ae=this.resume(),ye=this.stack[this.stack.length-1];ye.meta=ae}function x(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function v(){const ae=this.resume(),ye=this.stack[this.stack.length-1];ye.value=ae.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function b(){const ae=this.resume(),ye=this.stack[this.stack.length-1];ye.value=ae.replace(/(\r?\n|\r)$/g,"")}function y(ae){const ye=this.resume(),te=this.stack[this.stack.length-1];te.label=ye,te.identifier=Us(this.sliceSerialize(ae)).toLowerCase()}function S(){const ae=this.resume(),ye=this.stack[this.stack.length-1];ye.title=ae}function j(){const ae=this.resume(),ye=this.stack[this.stack.length-1];ye.url=ae}function R(ae){const ye=this.stack[this.stack.length-1];if(!ye.depth){const te=this.sliceSerialize(ae).length;ye.depth=te}}function k(){this.data.setextHeadingSlurpLineEnding=!0}function M(ae){const ye=this.stack[this.stack.length-1];ye.depth=this.sliceSerialize(ae).codePointAt(0)===61?1:2}function C(){this.data.setextHeadingSlurpLineEnding=void 0}function L(ae){const te=this.stack[this.stack.length-1].children;let Ae=te[te.length-1];(!Ae||Ae.type!=="text")&&(Ae=Pe(),Ae.position={start:vi(ae.start),end:void 0},te.push(Ae)),this.stack.push(Ae)}function A(ae){const ye=this.stack.pop();ye.value+=this.sliceSerialize(ae),ye.position.end=vi(ae.end)}function P(ae){const ye=this.stack[this.stack.length-1];if(this.data.atHardBreak){const te=ye.children[ye.children.length-1];te.position.end=vi(ae.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(ye.type)&&(L.call(this,ae),A.call(this,ae))}function O(){this.data.atHardBreak=!0}function V(){const ae=this.resume(),ye=this.stack[this.stack.length-1];ye.value=ae}function $(){const ae=this.resume(),ye=this.stack[this.stack.length-1];ye.value=ae}function E(){const ae=this.resume(),ye=this.stack[this.stack.length-1];ye.value=ae}function D(){const ae=this.stack[this.stack.length-1];if(this.data.inReference){const ye=this.data.referenceType||"shortcut";ae.type+="Reference",ae.referenceType=ye,delete ae.url,delete ae.title}else delete ae.identifier,delete ae.label;this.data.referenceType=void 0}function U(){const ae=this.stack[this.stack.length-1];if(this.data.inReference){const ye=this.data.referenceType||"shortcut";ae.type+="Reference",ae.referenceType=ye,delete ae.url,delete ae.title}else delete ae.identifier,delete ae.label;this.data.referenceType=void 0}function Y(ae){const ye=this.sliceSerialize(ae),te=this.stack[this.stack.length-2];te.label=MC(ye),te.identifier=Us(ye).toLowerCase()}function X(){const ae=this.stack[this.stack.length-1],ye=this.resume(),te=this.stack[this.stack.length-1];if(this.data.inReference=!0,te.type==="link"){const Ae=ae.children;te.children=Ae}else te.alt=ye}function _(){const ae=this.resume(),ye=this.stack[this.stack.length-1];ye.url=ae}function I(){const ae=this.resume(),ye=this.stack[this.stack.length-1];ye.title=ae}function T(){this.data.inReference=void 0}function w(){this.data.referenceType="collapsed"}function q(ae){const ye=this.resume(),te=this.stack[this.stack.length-1];te.label=ye,te.identifier=Us(this.sliceSerialize(ae)).toLowerCase(),this.data.referenceType="full"}function G(ae){this.data.characterReferenceType=ae.type}function me(ae){const ye=this.sliceSerialize(ae),te=this.data.characterReferenceType;let Ae;te?(Ae=nf(ye,te==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Ae=vd(ye);const Le=this.stack[this.stack.length-1];Le.value+=Ae}function ue(ae){const ye=this.stack.pop();ye.position.end=vi(ae.end)}function le(ae){A.call(this,ae);const ye=this.stack[this.stack.length-1];ye.url=this.sliceSerialize(ae)}function Se(ae){A.call(this,ae);const ye=this.stack[this.stack.length-1];ye.url="mailto:"+this.sliceSerialize(ae)}function F(){return{type:"blockquote",children:[]}}function ge(){return{type:"code",lang:null,meta:null,value:""}}function se(){return{type:"inlineCode",value:""}}function fe(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function de(){return{type:"emphasis",children:[]}}function xe(){return{type:"heading",depth:0,children:[]}}function ie(){return{type:"break"}}function Ee(){return{type:"html",value:""}}function De(){return{type:"image",title:null,url:"",alt:null}}function qe(){return{type:"link",title:null,url:"",children:[]}}function Qe(ae){return{type:"list",ordered:ae.type==="listOrdered",start:null,spread:ae._spread,children:[]}}function Je(ae){return{type:"listItem",spread:ae._spread,checked:null,children:[]}}function Ke(){return{type:"paragraph",children:[]}}function it(){return{type:"strong",children:[]}}function Pe(){return{type:"text",value:""}}function Ve(){return{type:"thematicBreak"}}}function vi(e){return{line:e.line,column:e.column,offset:e.offset}}function pf(e,n){let s=-1;for(;++s<n.length;){const i=n[s];Array.isArray(i)?pf(e,i):PC(e,i)}}function PC(e,n){let s;for(s in n)if(hf.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 bm(e,n){throw e?new Error("Cannot close `"+e.type+"` ("+cr({start:e.start,end:e.end})+"): a different token (`"+n.type+"`, "+cr({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+cr({start:n.start,end:n.end})+") is still open")}function IC(e){const n=this;n.parser=s;function s(i){return RC(i,{...n.data("settings"),...e,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function $C(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 DC(e,n){const s={type:"element",tagName:"br",properties:{},children:[]};return e.patch(n,s),[e.applyData(n,s),{type:"text",value:`
|
|
622
|
+
`}]}function LC(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 zC(e,n){const s={type:"element",tagName:"del",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function FC(e,n){const s={type:"element",tagName:"em",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function OC(e,n){const s=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=String(n.identifier).toUpperCase(),r=Pa(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 BC(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 UC(e,n){if(e.options.allowDangerousHtml){const s={type:"raw",value:n.value};return e.patch(n,s),e.applyData(n,s)}}function ff(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 HC(e,n){const s=String(n.identifier).toUpperCase(),i=e.definitionById.get(s);if(!i)return ff(e,n);const r={src:Pa(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 qC(e,n){const s={src:Pa(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 VC(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 WC(e,n){const s=String(n.identifier).toUpperCase(),i=e.definitionById.get(s);if(!i)return ff(e,n);const r={href:Pa(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 KC(e,n){const s={href:Pa(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 GC(e,n,s){const i=e.all(n),r=s?JC(s):gf(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 JC(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=gf(s[i])}return n}function gf(e){const n=e.spread;return n??e.children.length>1}function YC(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 QC(e,n){const s={type:"element",tagName:"p",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function XC(e,n){const s={type:"root",children:e.wrap(e.all(n))};return e.patch(n,s),e.applyData(n,s)}function ZC(e,n){const s={type:"element",tagName:"strong",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function e2(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=pd(n.children[1]),u=Gp(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 t2(e,n,s){const i=s?s.children:void 0,o=(i?i.indexOf(n):1)===0?"th":"td",l=s&&s.type==="table"?s.align:void 0,c=l?l.length:n.children.length;let u=-1;const d=[];for(;++u<c;){const h=n.children[u],g={},p=l?l[u]:void 0;p&&(g.align=p);let f={type:"element",tagName:o,properties:g,children:[]};h&&(f.children=e.all(h),e.patch(h,f),f=e.applyData(h,f)),d.push(f)}const m={type:"element",tagName:"tr",properties:{},children:e.wrap(d,!0)};return e.patch(n,m),e.applyData(n,m)}function n2(e,n){const s={type:"element",tagName:"td",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}const vm=9,ym=32;function s2(e){const n=String(e),s=/\r?\n|\r/g;let i=s.exec(n),r=0;const o=[];for(;i;)o.push(jm(n.slice(r,i.index),r>0,!0),i[0]),r=i.index+i[0].length,i=s.exec(n);return o.push(jm(n.slice(r),r>0,!1)),o.join("")}function jm(e,n,s){let i=0,r=e.length;if(n){let o=e.codePointAt(i);for(;o===vm||o===ym;)i++,o=e.codePointAt(i)}if(s){let o=e.codePointAt(r-1);for(;o===vm||o===ym;)r--,o=e.codePointAt(r-1)}return r>i?e.slice(i,r):""}function i2(e,n){const s={type:"text",value:s2(String(n.value))};return e.patch(n,s),e.applyData(n,s)}function a2(e,n){const s={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(n,s),e.applyData(n,s)}const r2={blockquote:$C,break:DC,code:LC,delete:zC,emphasis:FC,footnoteReference:OC,heading:BC,html:UC,imageReference:HC,image:qC,inlineCode:VC,linkReference:WC,link:KC,listItem:GC,list:YC,paragraph:QC,root:XC,strong:ZC,table:e2,tableCell:n2,tableRow:t2,text:i2,thematicBreak:a2,toml:Yr,yaml:Yr,definition:Yr,footnoteDefinition:Yr};function Yr(){}const xf=-1,Jo=0,ur=1,So=2,jd=3,kd=4,wd=5,Nd=6,bf=7,vf=8,km=typeof self=="object"?self:globalThis,o2=(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 Jo:case xf:return s(l,r);case ur:{const c=s([],r);for(const u of l)c.push(i(u));return c}case So:{const c=s({},r);for(const[u,d]of l)c[i(u)]=i(d);return c}case jd:return s(new Date(l),r);case kd:{const{source:c,flags:u}=l;return s(new RegExp(c,u),r)}case wd:{const c=s(new Map,r);for(const[u,d]of l)c.set(i(u),i(d));return c}case Nd:{const c=s(new Set,r);for(const u of l)c.add(i(u));return c}case bf:{const{name:c,message:u}=l;return s(new km[c](u),r)}case vf: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 km[o](l),r)};return i},wm=e=>o2(new Map,e)(0),oa="",{toString:l2}={},{keys:c2}=Object,Wa=e=>{const n=typeof e;if(n!=="object"||!e)return[Jo,n];const s=l2.call(e).slice(8,-1);switch(s){case"Array":return[ur,oa];case"Object":return[So,oa];case"Date":return[jd,oa];case"RegExp":return[kd,oa];case"Map":return[wd,oa];case"Set":return[Nd,oa];case"DataView":return[ur,s]}return s.includes("Array")?[ur,s]:s.includes("Error")?[bf,s]:[So,s]},Qr=([e,n])=>e===Jo&&(n==="function"||n==="symbol"),d2=(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]=Wa(l);switch(c){case Jo:{let m=l;switch(u){case"bigint":c=vf,m=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+u);m=null;break;case"undefined":return r([xf],l)}return r([c,m],l)}case ur:{if(u){let g=l;return u==="DataView"?g=new Uint8Array(l.buffer):u==="ArrayBuffer"&&(g=new Uint8Array(l)),r([u,[...g]],l)}const m=[],h=r([c,m],l);for(const g of l)m.push(o(g));return h}case So:{if(u)switch(u){case"BigInt":return r([u,l.toString()],l);case"Boolean":case"Number":case"String":return r([u,l.valueOf()],l)}if(n&&"toJSON"in l)return o(l.toJSON());const m=[],h=r([c,m],l);for(const g of c2(l))(e||!Qr(Wa(l[g])))&&m.push([o(g),o(l[g])]);return h}case jd:return r([c,l.toISOString()],l);case kd:{const{source:m,flags:h}=l;return r([c,{source:m,flags:h}],l)}case wd:{const m=[],h=r([c,m],l);for(const[g,p]of l)(e||!(Qr(Wa(g))||Qr(Wa(p))))&&m.push([o(g),o(p)]);return h}case Nd:{const m=[],h=r([c,m],l);for(const g of l)(e||!Qr(Wa(g)))&&m.push(o(g));return h}}const{message:d}=l;return r([c,{name:u,message:d}],l)};return o},Nm=(e,{json:n,lossy:s}={})=>{const i=[];return d2(!(n||s),!!n,new Map,i)(e),i},Co=typeof structuredClone=="function"?(e,n)=>n&&("json"in n||"lossy"in n)?wm(Nm(e,n)):structuredClone(e):(e,n)=>wm(Nm(e,n));function u2(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 m2(e,n){return"Back to reference "+(e+1)+(n>1?"-"+n:"")}function h2(e){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=e.options.footnoteBackContent||u2,i=e.options.footnoteBackLabel||m2,r=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",l=e.options.footnoteLabelProperties||{className:["sr-only"]},c=[];let u=-1;for(;++u<e.footnoteOrder.length;){const d=e.footnoteById.get(e.footnoteOrder[u]);if(!d)continue;const m=e.all(d),h=String(d.identifier).toUpperCase(),g=Pa(h.toLowerCase());let p=0;const f=[],x=e.footnoteCounts.get(h);for(;x!==void 0&&++p<=x;){f.length>0&&f.push({type:"text",value:" "});let y=typeof s=="string"?s:s(u,p);typeof y=="string"&&(y={type:"text",value:y}),f.push({type:"element",tagName:"a",properties:{href:"#"+n+"fnref-"+g+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof i=="string"?i:i(u,p),className:["data-footnote-backref"]},children:Array.isArray(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(...f)}else m.push(...f);const b={type:"element",tagName:"li",properties:{id:n+"fn-"+g},children:e.wrap(m,!0)};e.patch(d,b),c.push(b)}if(c.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...Co(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 Yo=(function(e){if(e==null)return x2;if(typeof e=="function")return Qo(e);if(typeof e=="object")return Array.isArray(e)?p2(e):f2(e);if(typeof e=="string")return g2(e);throw new Error("Expected function, string, or object as test")});function p2(e){const n=[];let s=-1;for(;++s<e.length;)n[s]=Yo(e[s]);return Qo(i);function i(...r){let o=-1;for(;++o<n.length;)if(n[o].apply(this,r))return!0;return!1}}function f2(e){const n=e;return Qo(s);function s(i){const r=i;let o;for(o in e)if(r[o]!==n[o])return!1;return!0}}function g2(e){return Qo(n);function n(s){return s&&s.type===e}}function Qo(e){return n;function n(s,i,r){return!!(b2(s)&&e.call(this,s,typeof i=="number"?i:void 0,r||void 0))}}function x2(){return!0}function b2(e){return e!==null&&typeof e=="object"&&"type"in e}const yf=[],v2=!0,zc=!1,y2="skip";function jf(e,n,s,i){let r;typeof n=="function"&&typeof s!="function"?(i=s,s=n):r=n;const o=Yo(r),l=i?-1:1;c(e,void 0,[])();function c(u,d,m){const h=u&&typeof u=="object"?u:{};if(typeof h.type=="string"){const p=typeof h.tagName=="string"?h.tagName:typeof h.name=="string"?h.name:void 0;Object.defineProperty(g,"name",{value:"node ("+(u.type+(p?"<"+p+">":""))+")"})}return g;function g(){let p=yf,f,x,v;if((!n||o(u,d,m[m.length-1]||void 0))&&(p=j2(s(u,m)),p[0]===zc))return p;if("children"in u&&u.children){const b=u;if(b.children&&p[0]!==y2)for(x=(i?b.children.length:-1)+l,v=m.concat(b);x>-1&&x<b.children.length;){const y=b.children[x];if(f=c(y,x,v)(),f[0]===zc)return f;x=typeof f[1]=="number"?f[1]:x+l}}return p}}}function j2(e){return Array.isArray(e)?e:typeof e=="number"?[v2,e]:e==null?yf:[e]}function Sd(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),jf(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 Fc={}.hasOwnProperty,k2={};function w2(e,n){const s=n||k2,i=new Map,r=new Map,o=new Map,l={...r2,...s.handlers},c={all:d,applyData:S2,definitionById:i,footnoteById:r,footnoteCounts:o,footnoteOrder:[],handlers:l,one:u,options:s,patch:N2,wrap:E2};return Sd(e,function(m){if(m.type==="definition"||m.type==="footnoteDefinition"){const h=m.type==="definition"?i:r,g=String(m.identifier).toUpperCase();h.has(g)||h.set(g,m)}}),c;function u(m,h){const g=m.type,p=c.handlers[g];if(Fc.call(c.handlers,g)&&p)return p(c,m,h);if(c.options.passThrough&&c.options.passThrough.includes(g)){if("children"in m){const{children:x,...v}=m,b=Co(v);return b.children=c.all(m),b}return Co(m)}return(c.options.unknownHandler||C2)(c,m,h)}function d(m){const h=[];if("children"in m){const g=m.children;let p=-1;for(;++p<g.length;){const f=c.one(g[p],m);if(f){if(p&&g[p-1].type==="break"&&(!Array.isArray(f)&&f.type==="text"&&(f.value=Sm(f.value)),!Array.isArray(f)&&f.type==="element")){const x=f.children[0];x&&x.type==="text"&&(x.value=Sm(x.value))}Array.isArray(f)?h.push(...f):h.push(f)}}}return h}}function N2(e,n){e.position&&(n.position=m0(e))}function S2(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,Co(o)),"children"in s&&s.children&&r!==null&&r!==void 0&&(s.children=r)}return s}function C2(e,n){const s=n.data||{},i="value"in n&&!(Fc.call(s,"hProperties")||Fc.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 E2(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 Sm(e){let n=0,s=e.charCodeAt(n);for(;s===9||s===32;)n++,s=e.charCodeAt(n);return e.slice(n)}function Cm(e,n){const s=w2(e,n),i=s.one(e,void 0),r=h2(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 _2(e,n){return e&&"run"in e?async function(s,i){const r=Cm(s,{file:i,...n});await e.run(r,i)}:function(s,i){return Cm(s,{file:i,...e||n})}}function Em(e){if(e)throw e}var Tl,_m;function M2(){if(_m)return Tl;_m=1;var e=Object.prototype.hasOwnProperty,n=Object.prototype.toString,s=Object.defineProperty,i=Object.getOwnPropertyDescriptor,r=function(d){return typeof Array.isArray=="function"?Array.isArray(d):n.call(d)==="[object Array]"},o=function(d){if(!d||n.call(d)!=="[object Object]")return!1;var m=e.call(d,"constructor"),h=d.constructor&&d.constructor.prototype&&e.call(d.constructor.prototype,"isPrototypeOf");if(d.constructor&&!m&&!h)return!1;var g;for(g in d);return typeof g>"u"||e.call(d,g)},l=function(d,m){s&&m.name==="__proto__"?s(d,m.name,{enumerable:!0,configurable:!0,value:m.newValue,writable:!0}):d[m.name]=m.newValue},c=function(d,m){if(m==="__proto__")if(e.call(d,m)){if(i)return i(d,m).value}else return;return d[m]};return Tl=function u(){var d,m,h,g,p,f,x=arguments[0],v=1,b=arguments.length,y=!1;for(typeof x=="boolean"&&(y=x,x=arguments[1]||{},v=2),(x==null||typeof x!="object"&&typeof x!="function")&&(x={});v<b;++v)if(d=arguments[v],d!=null)for(m in d)h=c(x,m),g=c(d,m),x!==g&&(y&&g&&(o(g)||(p=r(g)))?(p?(p=!1,f=h&&r(h)?h:[]):f=h&&o(h)?h:{},l(x,{name:m,newValue:u(y,f,g)})):typeof g<"u"&&l(x,{name:m,newValue:g}));return x},Tl}var A2=M2();const Pl=Fh(A2);function Oc(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 R2(){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?T2(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 T2(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 Js={basename:P2,dirname:I2,extname:$2,join:D2,sep:"/"};function P2(e,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');$r(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 I2(e){if($r(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 $2(e){$r(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 D2(...e){let n=-1,s;for(;++n<e.length;)$r(e[n]),e[n]&&(s=s===void 0?e[n]:s+"/"+e[n]);return s===void 0?".":L2(s)}function L2(e){$r(e);const n=e.codePointAt(0)===47;let s=z2(e,!n);return s.length===0&&!n&&(s="."),s.length>0&&e.codePointAt(e.length-1)===47&&(s+="/"),n?"/"+s:s}function z2(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 $r(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const F2={cwd:O2};function O2(){return"/"}function Bc(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function B2(e){if(typeof e=="string")e=new URL(e);else if(!Bc(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 U2(e)}function U2(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 Il=["history","path","basename","stem","extname","dirname"];class kf{constructor(n){let s;n?Bc(n)?s={path:n}:typeof n=="string"||H2(n)?s={value:n}:s=n:s={},this.cwd="cwd"in s?"":F2.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let i=-1;for(;++i<Il.length;){const o=Il[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)Il.includes(r)||(this[r]=s[r])}get basename(){return typeof this.path=="string"?Js.basename(this.path):void 0}set basename(n){Dl(n,"basename"),$l(n,"basename"),this.path=Js.join(this.dirname||"",n)}get dirname(){return typeof this.path=="string"?Js.dirname(this.path):void 0}set dirname(n){Mm(this.basename,"dirname"),this.path=Js.join(n||"",this.basename)}get extname(){return typeof this.path=="string"?Js.extname(this.path):void 0}set extname(n){if($l(n,"extname"),Mm(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=Js.join(this.dirname,this.stem+(n||""))}get path(){return this.history[this.history.length-1]}set path(n){Bc(n)&&(n=B2(n)),Dl(n,"path"),this.path!==n&&this.history.push(n)}get stem(){return typeof this.path=="string"?Js.basename(this.path,this.extname):void 0}set stem(n){Dl(n,"stem"),$l(n,"stem"),this.path=Js.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 Zn(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 $l(e,n){if(e&&e.includes(Js.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+Js.sep+"`")}function Dl(e,n){if(!e)throw new Error("`"+n+"` cannot be empty")}function Mm(e,n){if(!e)throw new Error("Setting `"+n+"` requires `path` to be set too")}function H2(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const q2=(function(e){const i=this.constructor.prototype,r=i[e],o=function(){return r.apply(o,arguments)};return Object.setPrototypeOf(o,i),o}),V2={}.hasOwnProperty;class Cd extends q2{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=R2()}copy(){const n=new Cd;let s=-1;for(;++s<this.attachers.length;){const i=this.attachers[s];n.use(...i)}return n.data(Pl(!0,{},this.namespace)),n}data(n,s){return typeof n=="string"?arguments.length===2?(Fl("data",this.frozen),this.namespace[n]=s,this):V2.call(this.namespace,n)&&this.namespace[n]||void 0:n?(Fl("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=Xr(n),i=this.parser||this.Parser;return Ll("parse",i),i(String(s),s)}process(n,s){const i=this;return this.freeze(),Ll("process",this.parser||this.Parser),zl("process",this.compiler||this.Compiler),s?r(void 0,s):new Promise(r);function r(o,l){const c=Xr(n),u=i.parse(c);i.run(u,c,function(m,h,g){if(m||!h||!g)return d(m);const p=h,f=i.stringify(p,g);G2(f)?g.value=f:g.result=f,d(m,g)});function d(m,h){m||!h?l(m):o?o(h):s(void 0,h)}}}processSync(n){let s=!1,i;return this.freeze(),Ll("processSync",this.parser||this.Parser),zl("processSync",this.compiler||this.Compiler),this.process(n,r),Rm("processSync","process",s),i;function r(o,l){s=!0,Em(o),i=l}}run(n,s,i){Am(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=Xr(s);r.run(n,u,d);function d(m,h,g){const p=h||n;m?c(m):l?l(p):i(void 0,p,g)}}}runSync(n,s){let i=!1,r;return this.run(n,s,o),Rm("runSync","run",i),r;function o(l,c){Em(l),r=c,i=!0}}stringify(n,s){this.freeze();const i=Xr(s),r=this.compiler||this.Compiler;return zl("stringify",r),Am(n),r(n,i)}use(n,...s){const i=this.attachers,r=this.namespace;if(Fl("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=Pl(!0,r.settings,d.settings))}function c(d){let m=-1;if(d!=null)if(Array.isArray(d))for(;++m<d.length;){const h=d[m];o(h)}else throw new TypeError("Expected a list of plugins, not `"+d+"`")}function u(d,m){let h=-1,g=-1;for(;++h<i.length;)if(i[h][0]===d){g=h;break}if(g===-1)i.push([d,...m]);else if(m.length>0){let[p,...f]=m;const x=i[g][1];Oc(x)&&Oc(p)&&(p=Pl(!0,x,p)),i[g]=[d,p,...f]}}}}const W2=new Cd().freeze();function Ll(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function zl(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Fl(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 Am(e){if(!Oc(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Rm(e,n,s){if(!s)throw new Error("`"+e+"` finished async. Use `"+n+"` instead")}function Xr(e){return K2(e)?e:new kf(e)}function K2(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function G2(e){return typeof e=="string"||J2(e)}function J2(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const Y2="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Tm=[],Pm={allowDangerousHtml:!0},Q2=/^(https?|ircs?|mailto|xmpp)$/i,X2=[{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 hi(e){const n=Z2(e),s=eE(e);return tE(n.runSync(n.parse(s),s),e)}function Z2(e){const n=e.rehypePlugins||Tm,s=e.remarkPlugins||Tm,i=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Pm}:Pm;return W2().use(IC).use(s).use(_2,i).use(n)}function eE(e){const n=e.children||"",s=new kf;return typeof n=="string"&&(s.value=n),s}function tE(e,n){const s=n.allowedElements,i=n.allowElement,r=n.components,o=n.disallowedElements,l=n.skipHtml,c=n.unwrapDisallowed,u=n.urlTransform||nE;for(const m of X2)Object.hasOwn(n,m.from)&&(""+m.from+(m.to?"use `"+m.to+"` instead":"remove it")+Y2+m.id,void 0);return Sd(e,d),x0(e,{Fragment:t.Fragment,components:r,ignoreInvalidStyle:!0,jsx:t.jsx,jsxs:t.jsxs,passKeys:!0,passNode:!0});function d(m,h,g){if(m.type==="raw"&&g&&typeof h=="number")return l?g.children.splice(h,1):g.children[h]={type:"text",value:m.value},h;if(m.type==="element"){let p;for(p in Ml)if(Object.hasOwn(Ml,p)&&Object.hasOwn(m.properties,p)){const f=m.properties[p],x=Ml[p];(x===null||x.includes(m.tagName))&&(m.properties[p]=u(String(f||""),p,m))}}if(m.type==="element"){let p=s?!s.includes(m.tagName):o?o.includes(m.tagName):!1;if(!p&&i&&typeof h=="number"&&(p=!i(m,h,g)),p&&g&&typeof h=="number")return c&&m.children?g.children.splice(h,1,...m.children):g.children.splice(h,1),h}}}function nE(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||Q2.test(e.slice(0,n))?e:""}function Im(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 sE(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function iE(e,n,s){const r=Yo((s||{}).ignore||[]),o=aE(n);let l=-1;for(;++l<o.length;)jf(e,"text",c);function c(d,m){let h=-1,g;for(;++h<m.length;){const p=m[h],f=g?g.children:void 0;if(r(p,f?f.indexOf(p):void 0,g))return;g=p}if(g)return u(d,m)}function u(d,m){const h=m[m.length-1],g=o[l][0],p=o[l][1];let f=0;const v=h.children.indexOf(d);let b=!1,y=[];g.lastIndex=0;let S=g.exec(d.value);for(;S;){const j=S.index,R={index:S.index,input:S.input,stack:[...m,d]};let k=p(...S,R);if(typeof k=="string"&&(k=k.length>0?{type:"text",value:k}:void 0),k===!1?g.lastIndex=j+1:(f!==j&&y.push({type:"text",value:d.value.slice(f,j)}),Array.isArray(k)?y.push(...k):k&&y.push(k),f=j+S[0].length,b=!0),!g.global)break;S=g.exec(d.value)}return b?(f<d.value.length&&y.push({type:"text",value:d.value.slice(f)}),h.children.splice(v,1,...y)):y=[d],v+y.length}}function aE(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([rE(r[0]),oE(r[1])])}return n}function rE(e){return typeof e=="string"?new RegExp(sE(e),"g"):e}function oE(e){return typeof e=="function"?e:function(){return e}}const Ol="phrasing",Bl=["autolink","link","image","label"];function lE(){return{transforms:[fE],enter:{literalAutolink:dE,literalAutolinkEmail:Ul,literalAutolinkHttp:Ul,literalAutolinkWww:Ul},exit:{literalAutolink:pE,literalAutolinkEmail:hE,literalAutolinkHttp:uE,literalAutolinkWww:mE}}}function cE(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Ol,notInConstruct:Bl},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Ol,notInConstruct:Bl},{character:":",before:"[ps]",after:"\\/",inConstruct:Ol,notInConstruct:Bl}]}}function dE(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function Ul(e){this.config.enter.autolinkProtocol.call(this,e)}function uE(e){this.config.exit.autolinkProtocol.call(this,e)}function mE(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 hE(e){this.config.exit.autolinkEmail.call(this,e)}function pE(e){this.exit(e)}function fE(e){iE(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,gE],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,xE]],{ignore:["link","linkReference"]})}function gE(e,n,s,i,r){let o="";if(!wf(r)||(/^w/i.test(n)&&(s=n+s,n="",o="http://"),!bE(s)))return!1;const l=vE(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 xE(e,n,s,i){return!wf(i,!0)||/[-\d_]$/.test(s)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+s,children:[{type:"text",value:n+"@"+s}]}}function bE(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 vE(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=Im(e,"(");let o=Im(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 wf(e,n){const s=e.input.charCodeAt(e.index-1);return(e.index===0||Wi(s)||Ko(s))&&(!n||s!==47)}Nf.peek=_E;function yE(){this.buffer()}function jE(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function kE(){this.buffer()}function wE(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function NE(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=Us(this.sliceSerialize(e)).toLowerCase(),s.label=n}function SE(e){this.exit(e)}function CE(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=Us(this.sliceSerialize(e)).toLowerCase(),s.label=n}function EE(e){this.exit(e)}function _E(){return"["}function Nf(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 ME(){return{enter:{gfmFootnoteCallString:yE,gfmFootnoteCall:jE,gfmFootnoteDefinitionLabelString:kE,gfmFootnoteDefinition:wE},exit:{gfmFootnoteCallString:NE,gfmFootnoteCall:SE,gfmFootnoteDefinitionLabelString:CE,gfmFootnoteDefinition:EE}}}function AE(e){let n=!1;return e&&e.firstLineBlank&&(n=!0),{handlers:{footnoteDefinition:s,footnoteReference:Nf},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?Sf:RE))),d(),u}}function RE(e,n,s){return n===0?e:Sf(e,n,s)}function Sf(e,n,s){return(s?"":" ")+e}const TE=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Cf.peek=LE;function PE(){return{canContainEols:["delete"],enter:{strikethrough:$E},exit:{strikethrough:DE}}}function IE(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:TE}],handlers:{delete:Cf}}}function $E(e){this.enter({type:"delete",children:[]},e)}function DE(e){this.exit(e)}function Cf(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 LE(){return"~"}function zE(e){return e.length}function FE(e,n){const s=n||{},i=(s.align||[]).concat(),r=s.stringLength||zE,o=[],l=[],c=[],u=[];let d=0,m=-1;for(;++m<e.length;){const x=[],v=[];let b=-1;for(e[m].length>d&&(d=e[m].length);++b<e[m].length;){const y=OE(e[m][b]);if(s.alignDelimiters!==!1){const S=r(y);v[b]=S,(u[b]===void 0||S>u[b])&&(u[b]=S)}x.push(y)}l[m]=x,c[m]=v}let h=-1;if(typeof i=="object"&&"length"in i)for(;++h<d;)o[h]=$m(i[h]);else{const x=$m(i);for(;++h<d;)o[h]=x}h=-1;const g=[],p=[];for(;++h<d;){const x=o[h];let v="",b="";x===99?(v=":",b=":"):x===108?v=":":x===114&&(b=":");let y=s.alignDelimiters===!1?1:Math.max(1,u[h]-v.length-b.length);const S=v+"-".repeat(y)+b;s.alignDelimiters!==!1&&(y=v.length+y+b.length,y>u[h]&&(u[h]=y),p[h]=y),g[h]=S}l.splice(1,0,g),c.splice(1,0,p),m=-1;const f=[];for(;++m<l.length;){const x=l[m],v=c[m];h=-1;const b=[];for(;++h<d;){const y=x[h]||"";let S="",j="";if(s.alignDelimiters!==!1){const R=u[h]-(v[h]||0),k=o[h];k===114?S=" ".repeat(R):k===99?R%2?(S=" ".repeat(R/2+.5),j=" ".repeat(R/2-.5)):(S=" ".repeat(R/2),j=S):j=" ".repeat(R)}s.delimiterStart!==!1&&!h&&b.push("|"),s.padding!==!1&&!(s.alignDelimiters===!1&&y==="")&&(s.delimiterStart!==!1||h)&&b.push(" "),s.alignDelimiters!==!1&&b.push(S),b.push(y),s.alignDelimiters!==!1&&b.push(j),s.padding!==!1&&b.push(" "),(s.delimiterEnd!==!1||h!==d-1)&&b.push("|")}f.push(s.delimiterEnd===!1?b.join("").replace(/ +$/,""):b.join(""))}return f.join(`
|
|
633
|
+
`)}function OE(e){return e==null?"":String(e)}function $m(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 BE(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()),UE);return r(),l}function UE(e,n,s){return">"+(s?"":" ")+e}function HE(e,n){return Dm(e,n.inConstruct,!0)&&!Dm(e,n.notInConstruct,!1)}function Dm(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 Lm(e,n,s,i){let r=-1;for(;++r<s.unsafe.length;)if(s.unsafe[r].character===`
|
|
634
|
+
`&&HE(s.stack,s.unsafe[r]))return/[ \t]/.test(i.before)?"":" ";return`\\
|
|
635
|
+
`}function qE(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 VE(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 WE(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 KE(e,n,s,i){const r=WE(s),o=e.value||"",l=r==="`"?"GraveAccent":"Tilde";if(VE(e,s)){const h=s.enter("codeIndented"),g=s.indentLines(o,GE);return h(),g}const c=s.createTracker(i),u=r.repeat(Math.max(qE(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 GE(e,n,s){return(s?"":" ")+e}function Ed(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 JE(e,n,s,i){const r=Ed(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 YE(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 jr(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Eo(e,n,s){const i=ja(e),r=ja(n);return i===void 0?r===void 0?s==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:r===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:i===1?r===void 0?{inside:!1,outside:!1}:r===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:r===void 0?{inside:!1,outside:!1}:r===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}Ef.peek=QE;function Ef(e,n,s,i){const r=YE(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=Eo(i.before.charCodeAt(i.before.length-1),d,r);m.inside&&(u=jr(d)+u.slice(1));const h=u.charCodeAt(u.length-1),g=Eo(i.after.charCodeAt(0),h,r);g.inside&&(u=u.slice(0,-1)+jr(h));const p=l.move(r);return o(),s.attentionEncodeSurroundingInfo={after:g.outside,before:m.outside},c+u+p}function QE(e,n,s){return s.options.emphasis||"*"}function XE(e,n){let s=!1;return Sd(e,function(i){if("value"in i&&/\r?\n|\r/.test(i.value)||i.type==="break")return s=!0,zc}),!!((!e.depth||e.depth<3)&&bd(e)&&(n.options.setext||s))}function ZE(e,n,s,i){const r=Math.max(Math.min(6,e.depth||1),1),o=s.createTracker(i);if(XE(e,s)){const m=s.enter("headingSetext"),h=s.enter("phrasing"),g=s.containerPhrasing(e,{...o.current(),before:`
|
|
640
|
+
`,after:`
|
|
641
|
+
`});return h(),m(),g+`
|
|
642
|
+
`+(r===1?"=":"-").repeat(g.length-(Math.max(g.lastIndexOf("\r"),g.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=jr(d.charCodeAt(0))+d.slice(1)),d=d?l+" "+d:l,s.options.closeAtx&&(d+=" "+l),u(),c(),d}_f.peek=e_;function _f(e){return e.value||""}function e_(){return"<"}Mf.peek=t_;function Mf(e,n,s,i){const r=Ed(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 t_(){return"!"}Af.peek=n_;function Af(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 n_(){return"!"}Rf.peek=s_;function Rf(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 s_(){return"`"}function Tf(e,n){const s=bd(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))}Pf.peek=i_;function Pf(e,n,s,i){const r=Ed(s),o=r==='"'?"Quote":"Apostrophe",l=s.createTracker(i);let c,u;if(Tf(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 i_(e,n,s){return Tf(e,s)?"<":"["}If.peek=a_;function If(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 a_(){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 r_(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 o_(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 $f(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 l_(e,n,s,i){const r=s.enter("list"),o=s.bulletCurrent;let l=e.ordered?o_(s):_d(s);const c=e.ordered?l==="."?")":".":r_(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),$f(s)===l&&m){let h=-1;for(;++h<e.children.length;){const g=e.children[h];if(g&&g.type==="listItem"&&g.children&&g.children[0]&&g.children[0].type==="thematicBreak"){u=!0;break}}}}u&&(l=c),s.bulletCurrent=l;const d=s.containerFlow(e,i);return s.bulletLastUsed=l,s.bulletCurrent=o,r(),d}function c_(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 d_(e,n,s,i){const r=c_(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,g,p){return g?(p?"":" ".repeat(l))+h:(p?o:o+" ".repeat(l-o.length))+h}}function u_(e,n,s,i){const r=s.enter("paragraph"),o=s.enter("phrasing"),l=s.containerPhrasing(e,i);return o(),r(),l}const m_=Yo(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function h_(e,n,s,i){return(e.children.some(function(l){return m_(l)})?s.containerPhrasing:s.containerFlow).call(s,e,i)}function p_(e){const n=e.options.strong||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize strong with `"+n+"` for `options.strong`, expected `*`, or `_`");return n}Df.peek=f_;function Df(e,n,s,i){const r=p_(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=Eo(i.before.charCodeAt(i.before.length-1),d,r);m.inside&&(u=jr(d)+u.slice(1));const h=u.charCodeAt(u.length-1),g=Eo(i.after.charCodeAt(0),h,r);g.inside&&(u=u.slice(0,-1)+jr(h));const p=l.move(r+r);return o(),s.attentionEncodeSurroundingInfo={after:g.outside,before:m.outside},c+u+p}function f_(e,n,s){return s.options.strong||"*"}function g_(e,n,s,i){return s.safe(e.value,i)}function x_(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 b_(e,n,s){const i=($f(s)+(s.options.ruleSpaces?" ":"")).repeat(x_(s));return s.options.ruleSpaces?i.slice(0,-1):i}const Lf={blockquote:BE,break:Lm,code:KE,definition:JE,emphasis:Ef,hardBreak:Lm,heading:ZE,html:_f,image:Mf,imageReference:Af,inlineCode:Rf,link:Pf,linkReference:If,list:l_,listItem:d_,paragraph:u_,root:h_,strong:Df,text:g_,thematicBreak:b_};function v_(){return{enter:{table:y_,tableData:zm,tableHeader:zm,tableRow:k_},exit:{codeText:w_,table:j_,tableData:Hl,tableHeader:Hl,tableRow:Hl}}}function y_(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 j_(e){this.exit(e),this.data.inTable=void 0}function k_(e){this.enter({type:"tableRow",children:[]},e)}function Hl(e){this.exit(e)}function zm(e){this.enter({type:"tableCell",children:[]},e)}function w_(e){let n=this.resume();this.data.inTable&&(n=n.replace(/\\([\\|])/g,N_));const s=this.stack[this.stack.length-1];s.type,s.value=n,this.exit(e)}function N_(e,n){return n==="|"?n:e}function S_(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:g,table:l,tableCell:u,tableRow:c}};function l(p,f,x,v){return d(m(p,x,v),p.align)}function c(p,f,x,v){const b=h(p,x,v),y=d([b]);return y.slice(0,y.indexOf(`
|
|
646
|
+
`))}function u(p,f,x,v){const b=x.enter("tableCell"),y=x.enter("phrasing"),S=x.containerPhrasing(p,{...v,before:o,after:o});return y(),b(),S}function d(p,f){return FE(p,{align:f,alignDelimiters:i,padding:s,stringLength:r})}function m(p,f,x){const v=p.children;let b=-1;const y=[],S=f.enter("table");for(;++b<v.length;)y[b]=h(v[b],f,x);return S(),y}function h(p,f,x){const v=p.children;let b=-1;const y=[],S=f.enter("tableRow");for(;++b<v.length;)y[b]=u(v[b],p,f,x);return S(),y}function g(p,f,x){let v=Lf.inlineCode(p,f,x);return x.stack.includes("tableCell")&&(v=v.replace(/\|/g,"\\$&")),v}}function C_(){return{exit:{taskListCheckValueChecked:Fm,taskListCheckValueUnchecked:Fm,paragraph:__}}}function E_(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:M_}}}function Fm(e){const n=this.stack[this.stack.length-2];n.type,n.checked=e.type==="taskListCheckValueChecked"}function __(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 M_(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=Lf.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 A_(){return[lE(),ME(),PE(),v_(),C_()]}function R_(e){return{extensions:[cE(),AE(e),IE(),S_(e),E_()]}}const T_={tokenize:z_,partial:!0},zf={tokenize:F_,partial:!0},Ff={tokenize:O_,partial:!0},Of={tokenize:B_,partial:!0},P_={tokenize:U_,partial:!0},Bf={name:"wwwAutolink",tokenize:D_,previous:Hf},Uf={name:"protocolAutolink",tokenize:L_,previous:qf},fi={name:"emailAutolink",tokenize:$_,previous:Vf},si={};function I_(){return{text:si}}let Di=48;for(;Di<123;)si[Di]=fi,Di++,Di===58?Di=65:Di===91&&(Di=97);si[43]=fi;si[45]=fi;si[46]=fi;si[95]=fi;si[72]=[fi,Uf];si[104]=[fi,Uf];si[87]=[fi,Bf];si[119]=[fi,Bf];function $_(e,n,s){const i=this;let r,o;return l;function l(h){return!Uc(h)||!Vf.call(i,i.previous)||Md(i.events)?s(h):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(h))}function c(h){return Uc(h)?(e.consume(h),c):h===64?(e.consume(h),u):s(h)}function u(h){return h===46?e.check(P_,m,d)(h):h===45||h===95||Qn(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&&is(i.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),n(h)):s(h)}}function D_(e,n,s){const i=this;return r;function r(l){return l!==87&&l!==119||!Hf.call(i,i.previous)||Md(i.events)?s(l):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(T_,e.attempt(zf,e.attempt(Ff,o),s),s)(l))}function o(l){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),n(l)}}function L_(e,n,s){const i=this;let r="",o=!1;return l;function l(h){return(h===72||h===104)&&qf.call(i,i.previous)&&!Md(i.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),r+=String.fromCodePoint(h),e.consume(h),c):s(h)}function c(h){if(is(h)&&r.length<5)return r+=String.fromCodePoint(h),e.consume(h),c;if(h===58){const g=r.toLowerCase();if(g==="http"||g==="https")return e.consume(h),u}return s(h)}function u(h){return h===47?(e.consume(h),o?d:(o=!0,u)):s(h)}function d(h){return h===null||No(h)||cn(h)||Wi(h)||Ko(h)?s(h):e.attempt(zf,e.attempt(Ff,m),s)(h)}function m(h){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),n(h)}}function z_(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 F_(e,n,s){let i,r,o;return l;function l(d){return d===46||d===95?e.check(Of,u,c)(d):d===null||cn(d)||Wi(d)||d!==45&&Ko(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 O_(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(Of,n,o)(l):l===null||cn(l)||Wi(l)?n(l):(e.consume(l),r)}function o(l){return l===41&&i++,e.consume(l),r}}function B_(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||cn(c)||Wi(c)?n(c):s(c)}function r(c){return c===null||c===40||c===91||cn(c)||Wi(c)?n(c):i(c)}function o(c){return is(c)?l(c):s(c)}function l(c){return c===59?(e.consume(c),i):is(c)?(e.consume(c),l):s(c)}}function U_(e,n,s){return i;function i(o){return e.consume(o),r}function r(o){return Qn(o)?s(o):n(o)}}function Hf(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||cn(e)}function qf(e){return!is(e)}function Vf(e){return!(e===47||Uc(e))}function Uc(e){return e===43||e===45||e===46||e===95||Qn(e)}function Md(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 H_={tokenize:Q_,partial:!0};function q_(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:G_,continuation:{tokenize:J_},exit:Y_}},text:{91:{name:"gfmFootnoteCall",tokenize:K_},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:V_,resolveTo:W_}}}}function V_(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=Us(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 W_(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 K_(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||cn(h))return s(h);if(h===93){e.exit("chunkString");const g=e.exit("gfmFootnoteCallString");return r.includes(Us(i.sliceSerialize(g)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),n):s(h)}return cn(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 G_(e,n,s){const i=this,r=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);let o,l=0,c;return u;function u(f){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionLabelMarker"),d}function d(f){return f===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",m):s(f)}function m(f){if(l>999||f===93&&!c||f===null||f===91||cn(f))return s(f);if(f===93){e.exit("chunkString");const x=e.exit("gfmFootnoteDefinitionLabelString");return o=Us(i.sliceSerialize(x)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),g}return cn(f)||(c=!0),l++,e.consume(f),f===92?h:m}function h(f){return f===91||f===92||f===93?(e.consume(f),l++,m):m(f)}function g(f){return f===58?(e.enter("definitionMarker"),e.consume(f),e.exit("definitionMarker"),r.includes(o)||r.push(o),Kt(e,p,"gfmFootnoteDefinitionWhitespace")):s(f)}function p(f){return n(f)}}function J_(e,n,s){return e.check(Ir,n,e.attempt(H_,n,s))}function Y_(e){e.exit("gfmFootnoteDefinition")}function Q_(e,n,s){const i=this;return Kt(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 X_(e){let s=(e||{}).singleTilde;const i={name:"strikethrough",tokenize:o,resolveAll:r};return s==null&&(s=!0),{text:{126:i},insideSpan:{null:[i]},attentionMarkers:{null:[126]}};function r(l,c){let u=-1;for(;++u<l.length;)if(l[u][0]==="enter"&&l[u][1].type==="strikethroughSequenceTemporary"&&l[u][1]._close){let d=u;for(;d--;)if(l[d][0]==="exit"&&l[d][1].type==="strikethroughSequenceTemporary"&&l[d][1]._open&&l[u][1].end.offset-l[u][1].start.offset===l[d][1].end.offset-l[d][1].start.offset){l[u][1].type="strikethroughSequence",l[d][1].type="strikethroughSequence";const m={type:"strikethrough",start:Object.assign({},l[d][1].start),end:Object.assign({},l[u][1].end)},h={type:"strikethroughText",start:Object.assign({},l[d][1].end),end:Object.assign({},l[u][1].start)},g=[["enter",m,c],["enter",l[d][1],c],["exit",l[d][1],c],["enter",h,c]],p=c.parser.constructs.insideSpan.null;p&&js(g,g.length,0,Go(p,l.slice(d+1,u),c)),js(g,g.length,0,[["exit",h,c],["enter",l[u][1],c],["exit",l[u][1],c],["exit",m,c]]),js(l,d-1,u-d+3,g),u=d+g.length-2;break}}for(u=-1;++u<l.length;)l[u][1].type==="strikethroughSequenceTemporary"&&(l[u][1].type="data");return l}function o(l,c,u){const d=this.previous,m=this.events;let h=0;return g;function g(f){return d===126&&m[m.length-1][1].type!=="characterEscape"?u(f):(l.enter("strikethroughSequenceTemporary"),p(f))}function p(f){const x=ja(d);if(f===126)return h>1?u(f):(l.consume(f),h++,p);if(h<2&&!s)return u(f);const v=l.exit("strikethroughSequenceTemporary"),b=ja(f);return v._open=!b||b===2&&!!x,v._close=!x||x===2&&!!b,c(f)}}}class Z_{constructor(){this.map=[]}add(n,s,i){eM(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 eM(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 tM(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 nM(){return{flow:{null:{name:"table",tokenize:sM,resolveAll:iM}}}}function sM(e,n,s){const i=this;let r=0,o=0,l;return c;function c(A){let P=i.events.length-1;for(;P>-1;){const $=i.events[P][1].type;if($==="lineEnding"||$==="linePrefix")P--;else break}const O=P>-1?i.events[P][1].type:null,V=O==="tableHead"||O==="tableRow"?k:u;return V===k&&i.parser.lazy[i.now().line]?s(A):V(A)}function u(A){return e.enter("tableHead"),e.enter("tableRow"),d(A)}function d(A){return A===124||(l=!0,o+=1),m(A)}function m(A){return A===null?s(A):kt(A)?o>1?(o=0,i.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(A),e.exit("lineEnding"),p):s(A):Ht(A)?Kt(e,m,"whitespace")(A):(o+=1,l&&(l=!1,r+=1),A===124?(e.enter("tableCellDivider"),e.consume(A),e.exit("tableCellDivider"),l=!0,m):(e.enter("data"),h(A)))}function h(A){return A===null||A===124||cn(A)?(e.exit("data"),m(A)):(e.consume(A),A===92?g:h)}function g(A){return A===92||A===124?(e.consume(A),h):h(A)}function p(A){return i.interrupt=!1,i.parser.lazy[i.now().line]?s(A):(e.enter("tableDelimiterRow"),l=!1,Ht(A)?Kt(e,f,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(A):f(A))}function f(A){return A===45||A===58?v(A):A===124?(l=!0,e.enter("tableCellDivider"),e.consume(A),e.exit("tableCellDivider"),x):R(A)}function x(A){return Ht(A)?Kt(e,v,"whitespace")(A):v(A)}function v(A){return A===58?(o+=1,l=!0,e.enter("tableDelimiterMarker"),e.consume(A),e.exit("tableDelimiterMarker"),b):A===45?(o+=1,b(A)):A===null||kt(A)?j(A):R(A)}function b(A){return A===45?(e.enter("tableDelimiterFiller"),y(A)):R(A)}function y(A){return A===45?(e.consume(A),y):A===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(A),e.exit("tableDelimiterMarker"),S):(e.exit("tableDelimiterFiller"),S(A))}function S(A){return Ht(A)?Kt(e,j,"whitespace")(A):j(A)}function j(A){return A===124?f(A):A===null||kt(A)?!l||r!==o?R(A):(e.exit("tableDelimiterRow"),e.exit("tableHead"),n(A)):R(A)}function R(A){return s(A)}function k(A){return e.enter("tableRow"),M(A)}function M(A){return A===124?(e.enter("tableCellDivider"),e.consume(A),e.exit("tableCellDivider"),M):A===null||kt(A)?(e.exit("tableRow"),n(A)):Ht(A)?Kt(e,M,"whitespace")(A):(e.enter("data"),C(A))}function C(A){return A===null||A===124||cn(A)?(e.exit("data"),M(A)):(e.consume(A),A===92?L:C)}function L(A){return A===92||A===124?(e.consume(A),C):C(A)}}function iM(e,n){let s=-1,i=!0,r=0,o=[0,0,0,0],l=[0,0,0,0],c=!1,u=0,d,m,h;const g=new Z_;for(;++s<e.length;){const p=e[s],f=p[1];p[0]==="enter"?f.type==="tableHead"?(c=!1,u!==0&&(Om(g,n,u,d,m),m=void 0,u=0),d={type:"table",start:Object.assign({},f.start),end:Object.assign({},f.end)},g.add(s,0,[["enter",d,n]])):f.type==="tableRow"||f.type==="tableDelimiterRow"?(i=!0,h=void 0,o=[0,0,0,0],l=[0,s+1,0,0],c&&(c=!1,m={type:"tableBody",start:Object.assign({},f.start),end:Object.assign({},f.end)},g.add(s,0,[["enter",m,n]])),r=f.type==="tableDelimiterRow"?2:m?3:1):r&&(f.type==="data"||f.type==="tableDelimiterMarker"||f.type==="tableDelimiterFiller")?(i=!1,l[2]===0&&(o[1]!==0&&(l[0]=l[1],h=Zr(g,n,o,r,void 0,h),o=[0,0,0,0]),l[2]=s)):f.type==="tableCellDivider"&&(i?i=!1:(o[1]!==0&&(l[0]=l[1],h=Zr(g,n,o,r,void 0,h)),o=l,l=[o[1],s,0,0])):f.type==="tableHead"?(c=!0,u=s):f.type==="tableRow"||f.type==="tableDelimiterRow"?(u=s,o[1]!==0?(l[0]=l[1],h=Zr(g,n,o,r,s,h)):l[1]!==0&&(h=Zr(g,n,l,r,s,h)),r=0):r&&(f.type==="data"||f.type==="tableDelimiterMarker"||f.type==="tableDelimiterFiller")&&(l[3]=s)}for(u!==0&&Om(g,n,u,d,m),g.consume(n.events),s=-1;++s<n.events.length;){const p=n.events[s];p[0]==="enter"&&p[1].type==="table"&&(p[1]._align=tM(n.events,s))}return e}function Zr(e,n,s,i,r,o){const l=i===1?"tableHeader":i===2?"tableDelimiter":"tableData",c="tableContent";s[0]!==0&&(o.end=Object.assign({},ua(n.events,s[0])),e.add(s[0],0,[["exit",o,n]]));const u=ua(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=ua(n.events,s[2]),m=ua(n.events,s[3]),h={type:c,start:Object.assign({},d),end:Object.assign({},m)};if(e.add(s[2],0,[["enter",h,n]]),i!==2){const g=n.events[s[2]],p=n.events[s[3]];if(g[1].end=Object.assign({},p[1].end),g[1].type="chunkText",g[1].contentType="text",s[3]>s[2]+1){const f=s[2]+1,x=s[3]-s[2]-1;e.add(f,x,[])}}e.add(s[3]+1,0,[["exit",h,n]])}return r!==void 0&&(o.end=Object.assign({},ua(n.events,r)),e.add(r,0,[["exit",o,n]]),o=void 0),o}function Om(e,n,s,i,r){const o=[],l=ua(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 ua(e,n){const s=e[n],i=s[0]==="enter"?"start":"end";return s[1][i]}const aM={name:"tasklistCheck",tokenize:oM};function rM(){return{text:{91:aM}}}function oM(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 cn(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 kt(u)?n(u):Ht(u)?e.check({tokenize:lM},n,s)(u):s(u)}}function lM(e,n,s){return Kt(e,i,"whitespace");function i(r){return r===null?s(r):n(r)}}function cM(e){return tf([I_(),q_(),X_(e),nM(),rM()])}const dM={};function pi(e){const n=this,s=e||dM,i=n.data(),r=i.micromarkExtensions||(i.micromarkExtensions=[]),o=i.fromMarkdownExtensions||(i.fromMarkdownExtensions=[]),l=i.toMarkdownExtensions||(i.toMarkdownExtensions=[]);r.push(cM(s)),o.push(A_()),l.push(R_(s))}const Bm=500,Um=100;function ql(e){return e.length>Bm?e.slice(-Bm):e}function Wf(e,n,s){const[i,r]=a.useState([]),[o,l]=a.useState(!1),[c,u]=a.useState(!1),[d,m]=a.useState(null),[h,g]=a.useState(!1),p=a.useRef(null),f=a.useRef(!1),x=a.useRef(0),v=a.useRef(e),b=a.useRef(s),y=a.useRef(n),S=a.useRef(0);(v.current!==e||b.current!==s||y.current!==n)&&(v.current=e,b.current=s,y.current=n,x.current++,f.current=!0,r([]),l(!1),u(!1),m(null),g(!1),p.current&&(p.current(),p.current=null)),a.useEffect(()=>{if(!e||!n){p.current&&(p.current(),p.current=null);return}const M=x.current,C=++S.current;f.current=!1;const L=e,A=s;async function P(){if(!L)return;l(!0),g(!1);try{const V=await Bd(L,A,{limit:Um});if(f.current||x.current!==M||S.current!==C)return;r(ql(V.entries)),u(V.hasMore),m(V.total)}catch{if(f.current||x.current!==M||S.current!==C)return;r([]),u(!1),m(null)}finally{!f.current&&x.current===M&&S.current===C&&l(!1)}const O=A?`?projectId=${encodeURIComponent(A)}`:"";p.current=qs(`/api/tasks/${L}/logs/stream${O}`,{events:{"agent:log":V=>{if(!(f.current||x.current!==M))try{const $=JSON.parse(V.data);r(E=>ql([...E,$])),m(E=>E!==null?E+1:null)}catch{}}}})}return P(),()=>{f.current=!0,p.current&&(p.current(),p.current=null)}},[e,n,s]);const R=a.useCallback(async()=>{if(!e||h)return;const M=x.current,C=i.length,L=e;g(!0);try{const A=await Bd(L,s,{limit:Um,offset:C});if(f.current||x.current!==M)return;r(P=>{const O=[...A.entries,...P];return ql(O)}),u(A.hasMore),m(A.total)}catch{}finally{g(!1)}},[e,s,i.length,h]),k=a.useCallback(()=>r([]),[]);return{entries:i,loading:o,clear:k,loadMore:R,hasMore:c,total:d,loadingMore:h}}function uM(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 Hm={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})},Kf=50,mM={triage:"Plan"};function qm(e){return e.scrollHeight-(e.scrollTop+e.clientHeight)<=Kf}function Hc(e){return[e.taskId,e.timestamp,e.agent??"",e.type,e.text,e.detail??""].join("|")}function hM(e){const n=new Map;return e.map(s=>{const i=Hc(s),r=n.get(i)??0;return n.set(i,r+1),`${i}|${r}`})}function pM(e){return e==="tool"||e==="tool_result"||e==="tool_error"}function fM(e,n){return e.agent?pM(e.type)?!0:!n||n.agent!==e.agent||n.type!==e.type:!1}function gM(e,n){const s=[];for(let i=0;i<e.length;i+=1){const r=e[i],o=n[i]??`${Hc(r)}|fallback`,l=i>0?e[i-1]:void 0,c=fM(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]??`${Hc(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 xM({entries:e,loading:n,executorModel:s,validatorModel:i,planningModel:r,hasMore:o=!1,onLoadMore:l,loadingMore:c=!1,totalCount:u=null}){const d=a.useRef(null),m=a.useRef(0),h=a.useRef(0),g=a.useRef(null),p=a.useRef(null),[f,x]=a.useState(!0),[v,b]=a.useState(!1),[y,S]=a.useState(!1),[j,R]=a.useState(!0),k=a.useMemo(()=>hM(e),[e]),M=a.useMemo(()=>gM(e,k),[e,k]);a.useLayoutEffect(()=>{const E=d.current;if(!E)return;const D=e.length,U=m.current,Y=h.current||E.scrollHeight,X=k[0]??null,_=k[k.length-1]??null,I=g.current!==X,T=p.current!==_;if(D>U)if(U===0)E.scrollTop=E.scrollHeight;else{const w=Y-(E.scrollTop+E.clientHeight)<=Kf,q=T&&!I,G=I&&!T;if(q&&w&&(E.scrollTop=E.scrollHeight),G){const me=E.scrollHeight-Y;me>0&&(E.scrollTop+=me)}}m.current=D,h.current=E.scrollHeight,g.current=X,p.current=_,R(qm(E))},[e,k]);const C=a.useCallback(()=>{const E=d.current;E&&R(qm(E))},[]),L=a.useCallback(()=>{const E=d.current;E&&(E.scrollTop=E.scrollHeight,R(!0))},[]),A=a.useCallback(E=>{E.key==="Escape"&&v&&b(!1)},[v]);a.useEffect(()=>{if(v)return document.addEventListener("keydown",A),()=>{document.removeEventListener("keydown",A)}},[v,A]);const P=s?.provider&&s?.modelId,O=i?.provider&&i?.modelId,V=r?.provider&&r?.modelId,$=a.useMemo(()=>{const E=[];return P&&E.push({role:"Executor",provider:s.provider,modelId:s.modelId}),O&&E.push({role:"Reviewer",provider:i.provider,modelId:i.modelId}),V&&E.push({role:"Planning",provider:r.provider,modelId:r.modelId}),E},[P,s,O,i,V,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(E=>t.jsx(Dn,{provider:E.provider,size:"sm"},`${E.role}-${E.provider}-${E.modelId??"default"}`)),t.jsx("button",{className:"agent-log-model-expand-btn",onClick:()=>S(E=>!E),"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(Vt,{size:14}):t.jsx(pn,{size:14})})]}),t.jsxs("div",{className:"agent-log-model-header-toggle",children:[t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>x(E=>!E),"aria-label":f?"Switch to plain text mode":"Switch to markdown mode","aria-pressed":f,"data-testid":"agent-log-mode-toggle",title:f?"Show raw text":"Show formatted markdown",children:f?"Markdown":"Plain"}),t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>b(E=>!E),"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(Cr,{size:14}):t.jsx(Lo,{size:14})})]}),y&&t.jsxs("div",{id:"agent-log-model-details",className:"agent-log-model-details",children:[t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Executor:"}),P?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Dn,{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:"}),O?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Dn,{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:"}),V?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Dn,{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:C,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(rt,{size:14,className:"animate-spin"}),"Loading…"]}):"Load More"})}),M.map(E=>{const D=E.kind==="single"?E.entry:E.entries[0],U=E.showBadge?t.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:uM(D.timestamp)}):null,Y=E.showBadge?t.jsxs("span",{className:"agent-log-badge-row",children:[t.jsxs("span",{className:"agent-log-agent-badge",children:["[",mM[D.agent]??D.agent,"]"]}),U]}):null;if(E.kind==="single"){const{entry:_}=E;if(_.type==="tool")return t.jsxs("div",{className:"agent-log-tool",children:[Y,"⚡ ",_.text,_.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",_.detail]})]},E.key);if(_.type==="tool_result")return t.jsxs("div",{className:"agent-log-tool-result",children:[Y,"✓ ",_.text,_.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",_.detail]})]},E.key);if(_.type==="tool_error")return t.jsxs("div",{className:"agent-log-tool-error",children:[Y,"✗ ",_.text,_.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",_.detail]})]},E.key)}const X=E.kind==="single"?D.text:E.entries.map(_=>_.text).join("");return E.kind==="thinking"?t.jsxs("div",{className:"agent-log-thinking",children:[Y,f?t.jsx("div",{className:"markdown-body",children:t.jsx(hi,{remarkPlugins:[pi],components:Hm,children:X})}):X]},E.key):t.jsxs("div",{className:"agent-log-text",children:[Y,f?t.jsx("div",{className:"markdown-body",children:t.jsx(hi,{remarkPlugins:[pi],components:Hm,children:X})}):X]},E.key)}),!j&&t.jsxs("button",{type:"button",className:"agent-log-return-to-live",onClick:L,"data-testid":"agent-log-return-to-live",children:[t.jsx(Vt,{size:12}),t.jsx("span",{children:"Live"})]})]})]})}function ka(e){return e??void 0}function eo(e){return{provider:ka(e.modelProvider),modelId:ka(e.modelId)}}function to(e){return{provider:ka(e.validatorModelProvider),modelId:ka(e.validatorModelId)}}function no(e){return{provider:ka(e.planningModelProvider),modelId:ka(e.planningModelId)}}function bM(e,n){return yp(e,n)}function vM(e,n){return jp(e,n)}function yM(e,n){return kp(e,n)}function Vl(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 Wl(e){return e.provider&&e.modelId?`${e.provider}/${e.modelId}`:""}function Kl(e,n){return e.provider===n.provider&&e.modelId===n.modelId}function jM(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 kM({task:e,addToast:n,onTaskUpdated:s,settings:i}){const[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState([]),[m,h]=a.useState(!1),[g,p]=a.useState(null),[f,x]=a.useState(()=>eo(e)),[v,b]=a.useState(()=>eo(e)),[y,S]=a.useState(()=>to(e)),[j,R]=a.useState(()=>to(e)),[k,M]=a.useState(()=>no(e)),[C,L]=a.useState(()=>no(e)),[A,P]=a.useState(()=>e.thinkingLevel??null),[O,V]=a.useState(()=>e.thinkingLevel??null),[$,E]=a.useState(null),D=a.useRef(e.id);a.useEffect(()=>{h(!0),p(null),ms().then(de=>{o(de.models),c(de.favoriteProviders),d(de.favoriteModels)}).catch(de=>{p(de.message||"Failed to load models")}).finally(()=>{h(!1)})},[]);const U=a.useCallback(async de=>{const xe=l,Ee=xe.includes(de)?xe.filter(De=>De!==de):[de,...xe];c(Ee);try{await ln({favoriteProviders:Ee,favoriteModels:u})}catch{c(xe),n("Failed to update favorites","error")}},[l,u,n]),Y=a.useCallback(async de=>{const xe=u,Ee=xe.includes(de)?xe.filter(De=>De!==de):[de,...xe];d(Ee);try{await ln({favoriteProviders:l,favoriteModels:Ee})}catch{d(xe),n("Failed to update model favorites","error")}},[u,l,n]);a.useEffect(()=>{D.current=e.id;const de=eo(e),xe=to(e),ie=no(e);x(de),b(de),S(xe),R(xe),M(ie),L(ie);const Ee=e.thinkingLevel??null;P(Ee),V(Ee),E(null)},[e.id,e.modelProvider,e.modelId,e.validatorModelProvider,e.validatorModelId,e.planningModelProvider,e.planningModelId,e.thinkingLevel]);const X=a.useMemo(()=>Wl(f),[f]),_=a.useMemo(()=>Wl(y),[y]),I=a.useMemo(()=>Wl(k),[k]),T=a.useMemo(()=>bM(e,i),[e,i]),w=a.useMemo(()=>vM(e,i),[e,i]),q=a.useMemo(()=>yM(e,i),[e,i]),G=$!==null,me=a.useCallback(async(de,xe)=>{const ie=e.id,Ee=v,De=j,qe=C;E(de);try{const Qe=s?de==="executor"?{modelProvider:xe.provider??null,modelId:xe.modelId??null}:de==="validator"?{validatorModelProvider:xe.provider??null,validatorModelId:xe.modelId??null}:{planningModelProvider:xe.provider??null,planningModelId:xe.modelId??null}:{modelProvider:(de==="executor"?xe:v).provider??null,modelId:(de==="executor"?xe:v).modelId??null,validatorModelProvider:(de==="validator"?xe:j).provider??null,validatorModelId:(de==="validator"?xe:j).modelId??null,planningModelProvider:(de==="planning"?xe:C).provider??null,planningModelId:(de==="planning"?xe:C).modelId??null},Je=await Qs(ie,Qe);if(D.current!==ie)return;const Ke=eo(Je),it=to(Je),Pe=no(Je);b(Ke),x(Ke),R(it),S(it),L(Pe),M(Pe),s?.(Je),n(jM(de,{executor:Ke,validator:it,planning:Pe}[de]),"success")}catch(Qe){if(D.current!==ie)return;de==="executor"?x(Ee):de==="validator"?S(De):M(qe),n(je(Qe)||"Failed to save model settings","error")}finally{D.current===ie&&E(null)}},[e.id,v,j,C,n,s]),ue=a.useCallback(de=>{const xe=Vl(de);x(xe),!Kl(xe,v)&&me("executor",xe)},[v,me]),le=a.useCallback(de=>{const xe=Vl(de);S(xe),!Kl(xe,j)&&me("validator",xe)},[j,me]),Se=a.useCallback(de=>{const xe=Vl(de);M(xe),!Kl(xe,C)&&me("planning",xe)},[C,me]),F=a.useCallback(async de=>{const xe=e.id,ie=O,Ee=de===""?null:de;P(Ee),E("thinking");try{const De=await Qs(xe,{thinkingLevel:Ee});if(D.current!==xe)return;const qe=De.thinkingLevel??null;V(qe),P(qe),s?.(De);const Qe=i?.defaultThinkingLevel??"off";n(qe===null?`Thinking level set to default (${Qe})`:`Thinking level set to ${qe}`,"success")}catch(De){if(D.current!==xe)return;P(ie),n(je(De)||"Failed to save thinking level","error")}finally{D.current===xe&&E(null)}},[e.id,O,i,n,s]),ge=!v.provider&&!v.modelId,se=!j.provider&&!j.modelId,fe=!C.provider&&!C.modelId;return t.jsxs("div",{className:"model-selector-tab",children:[t.jsx("h4",{children:"Model Configuration"}),t.jsx("p",{className:"model-selector-intro",children:"Override the AI models used for this task. When not specified, project or global defaults are used."}),m?t.jsx("div",{className:"model-selector-loading",children:"Loading available models…"}):g?t.jsxs("div",{className:"model-selector-error",children:["Error loading models: ",g,t.jsx("button",{className:"btn btn-sm",onClick:()=>{h(!0),p(null),ms().then(de=>{o(de.models),c(de.favoriteProviders),d(de.favoriteModels)}).catch(de=>p(de.message)).finally(()=>h(!1))},style:{marginLeft:"8px"},children:"Retry"})]}):r.length===0?t.jsx("div",{className:"model-selector-empty",children:"No models available. Configure authentication in Settings to enable model selection."}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"executorModel",children:"Executor Model"}),t.jsx("div",{className:"model-selector-current",children:ge?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",T.provider&&T.modelId?` (${T.provider}/${T.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[v.provider&&t.jsx(Dn,{provider:v.provider,size:"sm"}),v.provider,"/",v.modelId]})}),t.jsx(Hn,{id:"executorModel",label:"Executor Model",value:X,onChange:ue,models:r,disabled:G,placeholder:"Select executor model…",favoriteProviders:l,onToggleFavorite:U,favoriteModels:u,onToggleModelFavorite:Y}),t.jsx("small",{children:"The AI model used to implement this task."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"validatorModel",children:"Reviewer Model"}),t.jsx("div",{className:"model-selector-current",children:se?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",w.provider&&w.modelId?` (${w.provider}/${w.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[j.provider&&t.jsx(Dn,{provider:j.provider,size:"sm"}),j.provider,"/",j.modelId]})}),t.jsx(Hn,{id:"validatorModel",label:"Reviewer Model",value:_,onChange:le,models:r,disabled:G,placeholder:"Select reviewer model…",favoriteProviders:l,onToggleFavorite:U,favoriteModels:u,onToggleModelFavorite:Y}),t.jsx("small",{children:"The AI model used to review code and plans for this task."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"planningModel",children:"Planning Model"}),t.jsx("div",{className:"model-selector-current",children:fe?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",q.provider&&q.modelId?` (${q.provider}/${q.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[C.provider&&t.jsx(Dn,{provider:C.provider,size:"sm"}),C.provider,"/",C.modelId]})}),t.jsx(Hn,{id:"planningModel",label:"Planning Model",value:I,onChange:Se,models:r,disabled:G,placeholder:"Select planning model…",favoriteProviders:l,onToggleFavorite:U,favoriteModels:u,onToggleModelFavorite:Y}),t.jsx("small",{children:"The AI model used for task specification (triage phase)."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"thinkingLevel",children:"Thinking Level"}),t.jsx("div",{className:"model-selector-current",children:O===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:O})}),t.jsxs("select",{id:"thinkingLevel",value:A??"",onChange:de=>F(de.target.value),disabled:G,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:ge&&se&&fe&&O===null?"Using project or global default models.":"Model settings are up to date."})]})]})}const wM={open:t.jsx(Po,{size:16}),closed:t.jsx(Sr,{size:16}),merged:t.jsx(Kh,{size:16})};function NM({taskId:e,projectId:n,prInfo:s,automationStatus:i,autoMerge:r=!1,prAuthAvailable:o,onPrCreated:l,onPrUpdated:c,addToast:u}){const[d,m]=a.useState(!1),[h,g]=a.useState(""),[p,f]=a.useState(""),[x,v]=a.useState(!1),[b,y]=a.useState(!1),[S,j]=a.useState(null),R=a.useCallback(async()=>{if(h.trim()){v(!0);try{const L=await gy(e,{title:h.trim(),body:p.trim()||void 0},n);l(L),m(!1),g(""),f(""),u(`Created PR #${L.number}`,"success")}catch(L){u(je(L)||"Failed to create PR","error")}finally{v(!1)}}},[e,h,p,n,l,u]),k=a.useCallback(async()=>{if(s){y(!0);try{const L=await xy(e,n);j(L),c(L.prInfo),u("PR status refreshed","success")}catch(L){u(je(L)||"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(vs,{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(vs,{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(vs,{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:L=>g(L.target.value),disabled:x,className:"pr-input"}),t.jsx("textarea",{placeholder:"PR description (optional)",value:p,onChange:L=>f(L.target.value),disabled:x,className:"pr-textarea",rows:3}),t.jsxs("div",{className:"pr-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>m(!1),disabled:x,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:R,disabled:!h.trim()||x,children:x?"Creating…":"Create PR"})]})]})]}):t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(vs,{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(en,{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=wM[s.status]??t.jsx(Po,{size:16}),C=S?.blockingReasons??[];return t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(vs,{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:k,disabled:b,title:"Refresh PR status",children:t.jsx(En,{size:14,style:{verticalAlign:"middle",opacity:b?.5:1}})})]}),t.jsx("div",{className:"pr-title",children:s.title}),t.jsxs("div",{className:"pr-meta",children:[t.jsx("span",{children:s.headBranch}),t.jsx("span",{className:"pr-meta-arrow",children:"→"}),t.jsx("span",{children:s.baseBranch})]}),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:C.length>0?`Waiting for: ${C.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(ji,{size:14}),s.commentCount]}),t.jsxs("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"pr-link",children:[t.jsx(px,{size:14}),"View on GitHub"]})]})]})]})}const Vm=2e3;function SM(e){const n=e.updatedAt||e.createdAt,s=new Date(n).toLocaleString();return e.updatedAt?`${s} (edited)`:s}function CM(e){return e==="agent"||e==="system"}function EM({task:e,onTaskUpdated:n,addToast:s,currentAuthor:i="user",projectId:r}){const[o,l]=a.useState(""),[c,u]=a.useState(null),[d,m]=a.useState(""),[h,g]=a.useState(!1),[p,f]=a.useState(null),x=a.useMemo(()=>[...e.comments||[]].sort((M,C)=>new Date(C.createdAt).getTime()-new Date(M.createdAt).getTime()),[e.comments]),v=o.length>Vm;async function b(){const M=o.trim();if(M){g(!0);try{const C=await Jv(e.id,M,r);l(""),n?.(C),s("Comment added","success")}catch(C){s(je(C)||"Failed to add comment","error")}finally{g(!1)}}}async function y(M){const C=d.trim();if(C){g(!0);try{const L=await qv(e.id,M,C,r);u(null),m(""),n?.(L),s("Comment updated","success")}catch(L){s(je(L)||"Failed to update comment","error")}finally{g(!1)}}}async function S(M){f(M);try{const C=await Vv(e.id,M,r);n?.(C),s("Comment deleted","success")}catch(C){s(je(C)||"Failed to delete comment","error")}finally{f(null)}}function j(M){M.key==="Enter"&&(M.ctrlKey||M.metaKey)&&(M.preventDefault(),b())}return t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Comments"}),x.length===0?t.jsx("div",{className:"detail-log-empty",children:"No comments yet."}):t.jsx("div",{className:"detail-activity-list",children:x.map(M=>{const C=M.author===i,L=c===M.id,A=CM(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:[A?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:SM(M)})]}),C&&!L?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 S(M.id),disabled:p===M.id,children:p===M.id?"Deleting…":"Delete"})]}):null]}),L?t.jsxs("div",{className:"comments-edit-form",children:[t.jsx("textarea",{value:d,onChange:P=>m(P.target.value),rows:3,className:"comments-textarea"}),t.jsxs("div",{className:"comments-edit-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{u(null),m("")},disabled:h,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void y(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:j,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," / ",Vm]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void b(),disabled:h||!o.trim()||v,children:h?"Posting…":"Add Comment"})]})]})]})}function _M(e){return e?e.slice(0,7):"Unknown"}function MM({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:_M(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 Gf(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(mo.Fragment,{children:`${s}
|
|
649
|
+
`},i)})}function kr(e,n=60){if(!e||e.length<=n)return e;if(n<4)return e.slice(0,n);const s="...",i=e.lastIndexOf("/");if(i===-1){const m=Math.max(1,n-s.length);return e.slice(0,m)+s}const r=e.slice(i);if(s.length+r.length<=n)return s+r;const o=[];for(let m=1;m<e.length;m++)e[m]==="/"&&o.push(m);const l=n-s.length;let c=null,u=-1;for(let m=o.length-1;m>=0;m--){const h=o[m],g=e.slice(h);if(g.length>l)continue;const p=l-g.length;for(let f=0;f<o.length;f++){const x=o[f],v=e.slice(0,x);v.length<=p&&v.length+s.length+g.length<=n&&v.length+g.length>u&&(u=v.length+g.length,c=v+s+g)}}if(c)return c;const d=n-s.length;return s+e.slice(e.length-d)}function AM(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function RM({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),g=a.useRef(null);ni(g,e,"fusion:changes-diff-modal-size");const p=Si(l);a.useEffect(()=>{s.length>0&&u===null&&d(0)},[s,u]);const f=a.useCallback(()=>{d(y=>y!==null&&y>0?y-1:y)},[]),x=a.useCallback(()=>{d(y=>y!==null&&y<s.length-1?y+1:y)},[]);if(a.useEffect(()=>{if(!e)return;const y=S=>{if(S.key==="Escape"){l();return}S.key==="ArrowUp"&&(S.metaKey||S.ctrlKey)&&(S.preventDefault(),f()),S.key==="ArrowDown"&&(S.metaKey||S.ctrlKey)&&(S.preventDefault(),x())};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[e,l,f,x]),!e)return null;const v=u!==null?s[u]:null,b=o==="done";return t.jsx("div",{className:"modal-overlay open",...p,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal changes-diff-modal",ref:g,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:f,disabled:u===null||u<=0,title:"Previous file (Ctrl+↑)","aria-label":"Previous file",children:t.jsx(To,{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:x,disabled:u===null||u>=s.length-1,title:"Next file (Ctrl+↓)","aria-label":"Next file",children:t.jsx(pn,{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(fo,{size:14})}),c&&t.jsxs("button",{className:"btn btn-sm",onClick:c,children:[t.jsx(En,{size:14}),"Refresh"]}),t.jsx("button",{className:"modal-close",onClick:l,"aria-label":"Close",children:t.jsx(Ut,{size:20})})]})]}),t.jsxs("div",{className:"changes-diff-body",children:[t.jsxs("div",{className:"changes-diff-sidebar",children:[b&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(mr,{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,S)=>t.jsxs("button",{className:`changes-diff-file-item ${u===S?"selected":""}`,onClick:()=>d(S),title:y.path,children:[t.jsx("span",{className:`changes-file-status changes-file-status--${y.status}`,children:AM(y.status)}),t.jsx("span",{className:"changes-diff-file-path",children:kr(y.path,40)}),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:Gf(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 Wm(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function TM({taskId:e,worktree:n,projectId:s,column:i,mergeDetails:r,modifiedFiles:o}){const[l,c]=a.useState([]),[u,d]=a.useState({filesChanged:0,additions:0,deletions:0}),[m,h]=a.useState(!0),[g,p]=a.useState(null),[f,x]=a.useState(new Set),[v,b]=a.useState(null),[y,S]=a.useState(!0),[j,R]=a.useState(!1),k=i==="done",M=k&&!!r?.commitSha,C=i==="in-progress"||i==="in-review"||M,L=a.useCallback(async()=>{if(!C){h(!1);return}try{h(!0),p(null);const $=await mp(e,void 0,s),E=$.files.map(D=>({path:D.path,status:D.status,additions:D.additions,deletions:D.deletions,patch:D.patch}));c(E),d($.stats),E.length>0&&(x(new Set([E[0].path])),b(0))}catch($){p(je($)||"Failed to load diff")}finally{h(!1)}},[e,s,C]);a.useEffect(()=>{L()},[L]);const A=$=>{x(E=>{const D=new Set(E);if(D.has($))D.delete($);else{D.add($);const U=l.findIndex(Y=>Y.path===$);U!==-1&&b(U)}return D})},P=$=>{if($<0||$>=l.length)return;const E=l[$].path;x(new Set([E])),b($)},O=v!==null&&v>0,V=v!==null&&v<l.length-1;if(m)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--loading",children:[t.jsx("div",{className:"loading-spinner"}),t.jsx("span",{children:"Loading changes..."})]})});if(g)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--error",children:[t.jsx(as,{size:16}),t.jsxs("span",{children:["Error loading changes: ",g]})]})});if(!k&&!n)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:"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(k&&!M){const $=r?.filesChanged,E=r?.insertions,D=r?.deletions,U=$!=null||E!=null||D!=null;return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Bs,{size:24}),t.jsx("p",{children:"Detailed file changes unavailable."}),t.jsx("span",{className:"task-changes-state-hint",children:U?`Merge summary: ${$??0} file${($??0)===1?"":"s"} changed, +${E??0} additions, -${D??0} deletions.`:"No merge commit was recorded for this task."})]})})}return l.length===0?k&&o&&o.length>0?t.jsxs("div",{className:"detail-section task-changes-tab",children:[k&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(mr,{size:14}),t.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Bs,{size:24}),t.jsxs("p",{children:[o.length," file",o.length===1?"":"s"," modified during execution."]}),t.jsx("span",{className:"task-changes-state-hint",children:"The recorded merge commit has no diff (likely collapsed into a squash on main). Showing file paths only — patches unavailable."})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:o.map($=>t.jsx("div",{className:"changes-file-item",children:t.jsxs("div",{className:"changes-file-header changes-file-header--static",children:[t.jsx("span",{className:"changes-file-status changes-file-status--unknown",title:"status unknown",children:Wm("unknown")}),t.jsx("span",{className:"changes-file-path",title:$,children:kr($,40)})]})},$))})]}):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:k?"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:[k&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(mr,{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:()=>O&&P(v-1),disabled:!O,title:"Previous file","aria-label":"Previous file",children:t.jsx(To,{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:()=>V&&P(v+1),disabled:!V,title:"Next file","aria-label":"Next file",children:t.jsx(pn,{size:14})})]}),t.jsx("button",{className:`btn btn-sm ${y?"btn-primary":""}`,onClick:()=>S($=>!$),title:y?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(fo,{size:14})})]}),t.jsxs("div",{className:"changes-header-actions-secondary",children:[t.jsx("button",{className:"btn btn-sm",onClick:L,disabled:m,children:"Refresh"}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>R(!0),title:"Expand to full-screen diff view","aria-label":"Expand diff view",children:t.jsx(Lo,{size:14})})]})]})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:l.map($=>{const E=f.has($.path);return t.jsxs("div",{className:`changes-file-item ${E?"expanded":""}`,children:[t.jsxs("button",{className:"changes-file-header",onClick:()=>A($.path),children:[t.jsx("span",{className:"changes-file-toggle",children:E?t.jsx(Vt,{size:14}):t.jsx(pn,{size:14})}),t.jsx("span",{className:`changes-file-status changes-file-status--${$.status}`,title:$.status,children:Wm($.status)}),t.jsx("span",{className:"changes-file-path",title:$.path,children:kr($.path,40)}),t.jsxs("span",{className:"changes-file-stat",title:`+${$.additions} -${$.deletions}`,children:["+",$.additions," -",$.deletions]})]}),E&&$.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:Gf($.patch)})})})]},$.path)})}),t.jsx(RM,{isOpen:j,taskId:e,files:l,stats:u,mergeDetails:r,column:i,onClose:()=>R(!1),onRefresh:L})]})}function Km(e){return{executorValue:e?.executorProvider&&e?.executorModelId?`${e.executorProvider}/${e.executorModelId}`:"",validatorValue:e?.validatorProvider&&e?.validatorModelId?`${e.validatorProvider}/${e.validatorModelId}`:""}}function PM(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function PD(e,n){const s=PM(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 IM(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}const Gm=["image/png","image/jpeg","image/gif","image/webp"];function $M(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 Jf({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:g,onPriorityChange:p,executorModel:f,onExecutorModelChange:x,validatorModel:v,onValidatorModelChange:b,planningModel:y,onPlanningModelChange:S,thinkingLevel:j,onThinkingLevelChange:R,presetMode:k,onPresetModeChange:M,selectedPresetId:C,onSelectedPresetIdChange:L,selectedWorkflowSteps:A,onWorkflowStepsChange:P,onDefaultOnApplied:O,pendingImages:V,onImagesChange:$,tasks:E,projectId:D,disabled:U=!1,addToast:Y,isActive:X=!0,onAutoSaveDescription:_,onPlanningMode:I,onSubtaskBreakdown:T,onClose:w,renderBelowPrimary:q,renderBelowModelConfiguration:G,hideDependencies:me,autoExpandMoreOptionsOnSelection:ue=!0,reviewLevel:le,onReviewLevelChange:Se,executionMode:F,onExecutionModeChange:ge}){const se=(me?!1:o.length>0)||V.length>0||A.length>0||k!=="default"||(g??ys)!==ys||f!==""||v!==""||(y||"")!==""||(j||"")!==""||le!==void 0||F==="fast"||(c||"")!=="",[fe,de]=a.useState(!1),[xe,ie]=a.useState(ue?se:!1),[Ee,De]=a.useState(""),[qe,Qe]=a.useState([]),[Je,Ke]=a.useState([]),[it,Pe]=a.useState([]),[Ve,ae]=a.useState(!1),[ye,te]=a.useState(null),[Ae,Le]=a.useState([]),[pe,_e]=a.useState("idle"),[Fe,tt]=a.useState(!1),[Ne,oe]=a.useState(!1),[Te,he]=a.useState(!1),Me=a.useRef(null),We=a.useRef(null),Re=a.useRef(null),ot=a.useRef(null),J=a.useRef(null),ce=a.useRef(null),ve=a.useRef(null),Xe=a.useRef(!1),ee=a.useRef(se),Ge=a.useRef(n.trim()),ct=a.useRef(n.trim());a.useEffect(()=>{X&&(ae(!0),ms().then(N=>{Qe(N.models),Ke(N.favoriteProviders),Pe(N.favoriteModels)}).catch(()=>{}).finally(()=>ae(!1)),Fo(D).then(N=>te(N)).catch(()=>te(null)),Oo(D).then(N=>Le(N.filter(W=>W.enabled))).catch(()=>Le([])))},[X,D]);const vt=ye?.modelPresets||[],bt=vt.find(N=>N.id===C),ft=(me?!1:o.length>0)||V.length>0||A.length>0||k!=="default"||(g??ys)!==ys||f!==""||v!==""||(y||"")!==""||(j||"")!==""||le!==void 0||F==="fast"||(c||"")!=="";a.useEffect(()=>{if(e!=="create"||!X||!ye?.autoSelectModelPreset)return;const N=(ye.defaultPresetBySize,void 0);if(N){const W=Km(N);L(N.id),M("preset"),x(W.executorValue),b(W.validatorValue)}},[X,ye,vt,e]);const gt=a.useRef(!1);a.useEffect(()=>{if(e!=="create"||!X||gt.current||Ae.length===0)return;const N=Ae.filter(Ie=>Ie.defaultOn);if(N.length===0)return;gt.current=!0;const W=N.map(Ie=>Ie.id);P(W),O?.(W)},[e,X,Ae]),a.useEffect(()=>{X||(gt.current=!1)},[X]),a.useEffect(()=>{if(!ue){ee.current=ft;return}ft&&!ee.current&&ie(!0),ee.current=ft},[ft,ue]),a.useEffect(()=>{xe||(de(!1),De(""))},[xe]),a.useEffect(()=>{e!=="edit"||!X||ot.current&&(ot.current.focus(),ot.current.select())},[e,X]),a.useEffect(()=>{if(!fe)return;const N=W=>{We.current&&!We.current.contains(W.target)&&de(!1)};return document.addEventListener("mousedown",N),()=>document.removeEventListener("mousedown",N)},[fe]),a.useEffect(()=>{(e!=="edit"||U)&&he(!1)},[e,U]),a.useEffect(()=>{if(e!=="edit"){_e("idle");return}const N=n.trim();Ge.current=N,ct.current=N,_e("idle")},[e]),a.useEffect(()=>{if(e!=="edit"||!_||!X)return;const N=n.trim(),W=Ge.current;if(N===W||N===ct.current){ce.current&&(clearTimeout(ce.current),ce.current=null),Xe.current||_e("idle");return}return ce.current&&clearTimeout(ce.current),ce.current=setTimeout(async()=>{if(!Xe.current){Xe.current=!0,_e("saving");try{await _(N),ct.current=N,_e("saved"),ve.current&&clearTimeout(ve.current),ve.current=setTimeout(()=>{_e("idle"),ve.current=null},2e3)}catch{_e("idle")}finally{Xe.current=!1,ce.current=null}}},1500),()=>{ce.current&&(clearTimeout(ce.current),ce.current=null)}},[e,n,_,X]),a.useEffect(()=>()=>{ce.current&&clearTimeout(ce.current),ve.current&&clearTimeout(ve.current)},[]),a.useEffect(()=>{if(!Fe)return;const N=W=>{Me.current&&!Me.current.contains(W.target)&&tt(!1)};return document.addEventListener("mousedown",N),()=>document.removeEventListener("mousedown",N)},[Fe]);const _t=a.useCallback(N=>{const W=N.clipboardData?.items;if(W)for(let Ie=0;Ie<W.length;Ie++){const nt=W[Ie];if(nt.type.startsWith("image/")){const yt=nt.getAsFile();if(yt&&Gm.includes(yt.type)){N.preventDefault(),$([...V,{file:yt,previewUrl:URL.createObjectURL(yt)}]);return}}}},[V,$]),Rt=a.useCallback(N=>{N.preventDefault();const W=N.dataTransfer.files;for(let Ie=0;Ie<W.length;Ie++){const nt=W[Ie];if(Gm.includes(nt.type)){$([...V,{file:nt,previewUrl:URL.createObjectURL(nt)}]);return}}},[V,$]),Ft=a.useCallback(N=>{const W=V[N];W&&URL.revokeObjectURL(W.previewUrl),$(V.filter((Ie,nt)=>nt!==N))},[V,$]),wt=a.useCallback(N=>{l(o.includes(N)?o.filter(W=>W!==N):[...o,N])},[o,l]),At=(N,W)=>N.length>W?N.slice(0,W)+"…":N,qt=a.useCallback(N=>{s(N.target.value);const W=N.target;W.style.height="auto",W.style.height=W.scrollHeight+"px"},[s]),zt=a.useCallback(()=>{he(N=>!N)},[]),Wt=a.useCallback(N=>{!Te||N.key!=="Escape"||(N.preventDefault(),N.stopPropagation(),he(!1))},[Te]),Ot=a.useCallback(async N=>{const W=n.trim();if(!(!W||Ne)){oe(!0);try{const Ie=await op(W,N,D);s(Ie),tt(!1),Y("Description refined with AI","success"),Re.current&&(Re.current.style.height="auto",Re.current.style.height=Re.current.scrollHeight+"px")}catch(Ie){const nt=lp(Ie);Y(nt,"error")}finally{oe(!1)}}},[n,Ne,Y,s,D]),Nt=a.useCallback(async N=>{const W=Je,nt=W.includes(N)?W.filter(yt=>yt!==N):[N,...W];Ke(nt);try{await ln({favoriteProviders:nt,favoriteModels:it})}catch{Ke(W)}},[Je,it]),Mt=a.useCallback(async N=>{const W=it,nt=W.includes(N)?W.filter(yt=>yt!==N):[N,...W];Pe(nt);try{await ln({favoriteProviders:Je,favoriteModels:nt})}catch{Pe(W)}},[it,Je]),Ct=a.useCallback(N=>{if(N<=0)return;const W=[...A];[W[N-1],W[N]]=[W[N],W[N-1]],P(W)},[A,P]),Gt=a.useCallback(N=>{if(N>=A.length-1)return;const W=[...A];[W[N],W[N+1]]=[W[N+1],W[N]],P(W)},[A,P]),Et=a.useCallback(N=>{P(A.filter(W=>W!==N))},[A,P]),H=new Map;for(const N of Ae)H.set(N.id,{name:N.name,description:N.description});const be=E.filter(N=>!o.includes(N.id)).sort((N,W)=>{const Ie=W.createdAt.localeCompare(N.createdAt);if(Ie!==0)return Ie;const nt=parseInt(N.id.slice(N.id.lastIndexOf("-")+1),10)||0;return(parseInt(W.id.slice(W.id.lastIndexOf("-")+1),10)||0)-nt}),re=Ee?be.filter(N=>N.id.toLowerCase().includes(Ee.toLowerCase())||N.title&&N.title.toLowerCase().includes(Ee.toLowerCase())||N.description&&N.description.toLowerCase().includes(Ee.toLowerCase())):be;return t.jsxs("div",{className:"task-form",onDrop:Rt,onDragOver:N=>N.preventDefault(),onPaste:_t,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:ot,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:"Task title",value:i||"",onChange:N=>r(N.target.value),disabled:U})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:"task-form-description",className:"description-label-row",children:[t.jsx("span",{children:"Description"}),t.jsx("span",{className:`description-auto-save-status${pe==="idle"?"":" is-visible"}`,"aria-live":"polite",children:pe==="saving"?"Saving...":pe==="saved"?"Saved":""})]}),t.jsxs("div",{className:`description-with-refine${Te?" description--fullscreen":""}`,ref:Me,onKeyDown:Wt,children:[Te&&t.jsxs("div",{className:"description-fullscreen-header",children:[t.jsx("span",{children:"Editing Description"}),t.jsx("button",{type:"button",className:"btn btn-sm description-expand-btn",onClick:zt,"aria-label":"Collapse description",title:"Collapse description",children:t.jsx(Cr,{size:14})})]}),t.jsx("textarea",{ref:Re,autoFocus:e==="create",id:"task-form-description",value:n,onChange:qt,placeholder:"What needs to be done?",rows:e==="edit"?8:5,disabled:U||Ne}),(()=>{const N=!!n.trim()&&!U;return t.jsxs(t.Fragment,{children:[!Te&&t.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${N?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:zt,"aria-label":"Expand description",title:"Expand description",children:t.jsx(Lo,{size:14})}),N&&t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${Ne?"refine-button--loading":""}`,onClick:()=>tt(W=>!W),disabled:Ne,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(Xn,{size:12,style:{verticalAlign:"middle"}}),Ne?"Refining...":"Refine"]})]})})(),Fe&&t.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:N=>N.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"&&(I||T)&&t.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[I&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const N=n.trim();if(!N){Y("Enter a description first","error");return}w?.(),I(N)},disabled:U||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),T&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const N=n.trim();if(!N){Y("Enter a description first","error");return}w?.(),T(N)},disabled:U||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),q,t.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>ie(N=>!N),"aria-expanded":xe,"aria-controls":"task-form-more-options",disabled:U,"data-testid":"task-form-more-options-toggle",children:[t.jsx("span",{children:"More options"}),xe?t.jsx(ui,{size:14}):t.jsx(Vt,{size:14})]}),t.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${xe?"":" collapsed"}`,"aria-hidden":!xe,hidden:!xe,"data-testid":"task-form-more-options",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Attachments"}),V.length>0&&t.jsx("div",{className:"inline-create-previews",children:V.map((N,W)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:N.previewUrl,alt:N.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>Ft(W),disabled:U,title:"Remove image",children:"×"})]},N.previewUrl))}),t.jsx("input",{ref:J,type:"file",accept:"image/*",onChange:N=>{const W=N.target.files?.[0];W&&($([...V,{file:W,previewUrl:URL.createObjectURL(W)}]),N.target.value="")},style:{display:"none"}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>J.current?.click(),disabled:U,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:N=>u(N.target.value||void 0),disabled:U||m,children:[t.jsx("option",{value:"",children:"Use project default / local"}),(d??[]).map(N=>t.jsxs("option",{value:N.id,children:[N.name," (",IM(N.status),")"]},N.id))]}),(()=>{const N=(d??[]).find(W=>W.id===c);return N?t.jsx("div",{className:"task-form-node-status",children:t.jsx(Vi,{status:N.status,showLabel:!0})}):null})(),t.jsx("small",{children:h??"Task override takes priority over project default node routing."})]}),!me&&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:We,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>de(N=>!N),disabled:U,children:o.length>0?`${o.length} selected`:"Add dependencies"}),fe&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Ee,onChange:N=>De(N.target.value),onClick:N=>N.stopPropagation()}),re.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):re.map(N=>t.jsxs("div",{className:`dep-dropdown-item${o.includes(N.id)?" selected":""}`,onClick:()=>wt(N.id),onMouseDown:W=>W.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:N.id}),t.jsx("span",{className:"dep-dropdown-title",children:At(N.title||N.description||N.id,30)})]},N.id))]})]}),o.length>0&&t.jsx("div",{className:"selected-deps",children:o.map(N=>t.jsxs("span",{className:"dep-chip",children:[N,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>wt(N),disabled:U,children:"×"})]},N))})]})}),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:g??ys,onChange:N=>p(N.target.value),disabled:U,children:ad.map(N=>t.jsx("option",{value:N,children:N[0].toUpperCase()+N.slice(1)},N))})]}),ge&&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:N=>ge(N.target.value),disabled:U,children:[t.jsx("option",{value:"standard",children:"Standard"}),t.jsx("option",{value:"fast",children:"Fast"})]})]}),Ve?t.jsx("div",{className:"model-selector-loading",children:"Loading models…"}):qe.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:k==="preset"?C:k,onChange:N=>{const W=N.target.value;if(W==="default"){M("default"),L(""),x(""),b("");return}if(W==="custom"){M("custom"),L("");return}const Ie=vt.find(yt=>yt.id===W),nt=Km(Ie);M("preset"),L(W),x(nt.executorValue),b(nt.validatorValue)},disabled:U,children:[t.jsx("option",{value:"default",children:"Use default"}),vt.length>0?t.jsx("option",{disabled:!0,children:"──────────"}):null,vt.map(N=>t.jsx("option",{value:N.id,children:N.name},N.id)),t.jsx("option",{value:"custom",children:"Custom"})]})]}),k==="preset"&&bt?t.jsxs("small",{children:["Using preset: ",bt.name]}):null,k==="preset"?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>M("custom"),disabled:U,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(Hn,{id:"executor-model",label:"Executor Model",value:f,onChange:N=>{M("custom"),L(""),x(N)},models:qe,disabled:U||k==="preset",favoriteProviders:Je,onToggleFavorite:Nt,favoriteModels:it,onToggleModelFavorite:Mt})]}),t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"validator-model",className:"model-select-label",children:"Reviewer"}),t.jsx(Hn,{id:"validator-model",label:"Reviewer Model",value:v,onChange:N=>{M("custom"),L(""),b(N)},models:qe,disabled:U||k==="preset",favoriteProviders:Je,onToggleFavorite:Nt,favoriteModels:it,onToggleModelFavorite:Mt})]}),S&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"planning-model",className:"model-select-label",children:"Planning"}),t.jsx(Hn,{id:"planning-model",label:"Planning Model",value:y||"",onChange:N=>{M("custom"),L(""),S(N)},models:qe,disabled:U||k==="preset",favoriteProviders:Je,onToggleFavorite:Nt,favoriteModels:it,onToggleModelFavorite:Mt})]}),R&&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:j||"",onChange:N=>R(N.target.value),disabled:U||k==="preset",children:[t.jsxs("option",{value:"",children:["Default (",ye?.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"})]})]}),Se&&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:le??"",onChange:N=>Se(N.target.value===""?void 0:parseInt(N.target.value,10)),disabled:U,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"})]})]})]})]}),G,t.jsxs("div",{className:"form-group","data-testid":"workflow-steps-section",children:[t.jsx("label",{children:"Workflow Steps"}),t.jsxs("div",{className:"workflow-steps-section",children:[t.jsx("small",{className:"workflow-steps-description",children:"Select steps to run after task implementation completes"}),t.jsx("div",{className:"workflow-steps-list",children:Ae.length>0&&Ae.map(N=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${N.id}`,children:[t.jsx("input",{type:"checkbox",checked:A.includes(N.id),onChange:W=>{P(W.target.checked?[...A,N.id]:A.filter(Ie=>Ie!==N.id))},disabled:U}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[N.name,$M(N.phase||"pre-merge",N.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:N.description})]})]},N.id))})]}),A.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:"}),A.map((N,W)=>{const Ie=H.get(N);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${N}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:W+1}),t.jsx("span",{className:"workflow-step-order-name",children:Ie?.name||N}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Ct(W),disabled:U||W===0,"data-testid":`workflow-step-move-up-${N}`,title:"Move up",children:t.jsx(ui,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Gt(W),disabled:U||W===A.length-1,"data-testid":`workflow-step-move-down-${N}`,title:"Move down",children:t.jsx(Vt,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Et(N),disabled:U,"data-testid":`workflow-step-remove-${N}`,title:"Remove",children:t.jsx(Ut,{size:14})})]})]},N)})]})]})]})]})}const Jm={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 DM(e){switch(e){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return e}}function LM(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 zM(e){return e?new Date(e).toLocaleString():null}function FM(e){const n=e.split(`
|
|
650
|
+
`);return n.length<=1?e:`${n.length} lines`}function so(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 OM({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 BM({taskId:e,results:n,loading:s,enabledWorkflowSteps:i,canEdit:r,projectId:o,isTaskInProgress:l,onWorkflowStepsChange:c}){const[u,d]=a.useState({}),[m,h]=a.useState({}),[g,p]=a.useState(null),[f,x]=a.useState([]),[v,b]=a.useState(!1),y=n.some(w=>w.status==="pending"),{entries:S}=Wf(e,!!l&&y,o);a.useEffect(()=>{let w=!1;return Oo(o).then(q=>{w||x(q.filter(G=>G.enabled))}).catch(()=>{w||x([])}),()=>{w=!0}},[o]);const j=i??[],R=a.useMemo(()=>f.map(w=>({id:w.id,name:w.name,description:w.description,phase:w.phase||"pre-merge"})),[f]),k=a.useMemo(()=>new Map(R.map(w=>[w.id,w])),[R]),M=w=>{d(q=>({...q,[w]:!q[w]}))},C=w=>{h(q=>{const G=q[w]??"markdown";return{...q,[w]:G==="markdown"?"plain":"markdown"}})},L=w=>{p(w)},A=()=>{p(null)};a.useEffect(()=>{if(!g)return;const w=q=>{q.key==="Escape"&&A()};return document.addEventListener("keydown",w),()=>{document.removeEventListener("keydown",w)}},[g]);const P=a.useCallback((w,q)=>{if(c){if(q){if(j.includes(w)){c(j);return}c([...j,w]);return}c(j.filter(G=>G!==w))}},[c,j]),O=a.useCallback(w=>{if(!c||w<=0)return;const q=[...j];[q[w-1],q[w]]=[q[w],q[w-1]],c(q)},[c,j]),V=a.useCallback(w=>{if(!c||w>=j.length-1)return;const q=[...j];[q[w],q[w+1]]=[q[w+1],q[w]],c(q)},[c,j]),$=a.useCallback(w=>{c&&c(j.filter(q=>q!==w))},[c,j]),E=n.length>0,D=j.length>0;a.useEffect(()=>{r||b(!1)},[r]);const U=a.useMemo(()=>j.map(w=>{const q=k.get(w);return{id:w,name:q?.name||w,description:q?.description||"Step definition not found.",phase:q?.phase||"pre-merge"}}),[j,k]),Y=()=>!r||!v||s?null:t.jsxs("div",{className:"workflow-results-editor","data-testid":"workflow-steps-editor",children:[t.jsxs("div",{className:"workflow-steps-section",children:[t.jsx("small",{className:"workflow-steps-description",children:"Select steps to run after task implementation completes"}),t.jsx("div",{className:"workflow-steps-list",children:R.map(w=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${w.id}`,children:[t.jsx("input",{type:"checkbox",checked:j.includes(w.id),onChange:q=>P(w.id,q.target.checked)}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[w.name,so(w.phase,w.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:w.description})]})]},w.id))})]}),j.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:"}),j.map((w,q)=>{const G=k.get(w);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${w}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:q+1}),t.jsx("span",{className:"workflow-step-order-name",children:G?.name||w}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>O(q),disabled:q===0,"data-testid":`workflow-step-move-up-${w}`,title:"Move up",children:t.jsx(ui,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>V(q),disabled:q===j.length-1,"data-testid":`workflow-step-move-down-${w}`,title:"Move down",children:t.jsx(Vt,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>$(w),"data-testid":`workflow-step-remove-${w}`,title:"Remove",children:t.jsx(Ut,{size:14})})]})]},w)})]})]}),X=()=>{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(!E)return t.jsxs("div",{className:"workflow-results-empty","data-testid":"workflow-results-empty",children:[t.jsx("p",{children:"No workflow steps configured for this task."}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."})]});const w=n.filter(le=>le.status==="passed").length,q=n.filter(le=>le.status==="failed").length,G=n.filter(le=>le.status==="skipped").length,me=n.filter(le=>le.status==="pending").length,ue=[`${n.length} step${n.length!==1?"s":""}`];return w>0&&ue.push(`${w} passed`),q>0&&ue.push(`${q} failed`),G>0&&ue.push(`${G} skipped`),me>0&&ue.push(`${me} 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:ue.join(" · ")}),n.map((le,Se)=>{const F=le.phase||"pre-merge",ge=u[le.workflowStepId]??!1;return t.jsxs("div",{className:`workflow-result-item workflow-result-item--${le.status}`,"data-testid":`workflow-result-item-${le.workflowStepId}`,children:[t.jsxs("div",{className:"workflow-result-header",children:[t.jsxs("div",{className:"workflow-result-name",children:[le.workflowStepName,so(F,le.workflowStepId,"workflow-result-phase")]}),t.jsx("span",{className:`workflow-result-badge workflow-result-badge--${le.status}`,"data-testid":`workflow-result-badge-${le.workflowStepId}`,children:DM(le.status)})]}),t.jsxs("div",{className:"workflow-result-meta",children:[le.startedAt&&t.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",zM(le.startedAt)]}),le.completedAt&&t.jsx("span",{className:"workflow-result-duration",children:LM(le.startedAt,le.completedAt)})]}),le.status==="pending"&&le.startedAt?t.jsx(OM,{entries:S,startedAt:le.startedAt,stepId:le.workflowStepId}):le.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(le.workflowStepId),"data-testid":`workflow-result-toggle-${le.workflowStepId}`,children:ge?"Hide output":"Show output"}),!ge&&t.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${le.workflowStepId}`,children:FM(le.output)}),ge&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>C(le.workflowStepId),"data-testid":`workflow-result-mode-toggle-${le.workflowStepId}`,title:(m[le.workflowStepId]??"markdown")==="markdown"?"Switch to plain text":"Switch to markdown",children:(m[le.workflowStepId]??"markdown")==="markdown"?"Markdown":"Plain"}),t.jsx("button",{className:"workflow-result-expand-toggle",onClick:()=>L(le.workflowStepId),"data-testid":`workflow-result-expand-${le.workflowStepId}`,title:"Expand output",children:t.jsx(Lo,{size:12})})]})]}),ge&&t.jsx("div",{className:`workflow-result-output${(m[le.workflowStepId]??"markdown")==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":`workflow-result-output-${le.workflowStepId}`,children:(m[le.workflowStepId]??"markdown")==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(hi,{remarkPlugins:[pi],components:Jm,children:le.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:le.output})})]}):null]},`${le.workflowStepId}-${Se}`)})]})},_=r?t.jsx("button",{type:"button",className:"modal-edit-btn workflow-results-edit-toggle",onClick:()=>b(w=>!w),"data-testid":"workflow-steps-edit-toggle","aria-label":v?"Done editing workflow steps":"Edit workflow steps",title:v?"Done":"Edit",children:v?t.jsxs(t.Fragment,{children:[t.jsx($n,{size:14}),"Done"]}):t.jsxs(t.Fragment,{children:[t.jsx(ss,{size:14}),"Edit"]})}):null,I=!s&&!E&&D,T=r&&E;return t.jsxs("div",{className:"workflow-results-tab","data-task-id":e,children:[I?t.jsxs("div",{className:"workflow-configured-steps","data-testid":"workflow-configured-steps",children:[t.jsxs("div",{className:"workflow-configured-header","data-testid":"workflow-configured-header",children:[t.jsxs("div",{className:"workflow-configured-title-row",children:[t.jsx("h4",{children:"Configured Workflow Steps"}),t.jsxs("span",{className:"workflow-configured-count","data-testid":"workflow-configured-count",children:[U.length," step",U.length===1?"":"s"]})]}),_]}),t.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:U.map(w=>t.jsxs("div",{className:"workflow-configured-item","data-testid":`workflow-configured-step-${w.id}`,children:[t.jsxs("div",{className:"workflow-configured-name",children:[w.name,so(w.phase,w.id,"workflow-configured-phase")]}),t.jsx("p",{className:"workflow-configured-description",children:w.description})]},w.id))}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."}),Y()]}):t.jsxs(t.Fragment,{children:[T&&t.jsxs("div",{className:"workflow-results-edit-header","data-testid":"workflow-results-edit-header",children:[t.jsx("h4",{children:"Workflow Steps"}),_]}),X(),Y()]}),g&&(()=>{const w=n.find(me=>me.workflowStepId===g);if(!w)return null;const q=m[w.workflowStepId]??"markdown",G=w.phase||"pre-merge";return t.jsx("div",{className:"workflow-output-modal-overlay",onClick:me=>{me.target===me.currentTarget&&A()},"data-testid":"workflow-output-modal",children:t.jsxs("div",{className:"workflow-output-modal",role:"dialog","aria-modal":"true",children:[t.jsxs("div",{className:"workflow-output-modal-header",children:[t.jsxs("div",{className:"workflow-output-modal-title",children:[t.jsx("span",{className:"workflow-output-modal-name",children:w.workflowStepName}),so(G,w.workflowStepId,"workflow-output-modal-phase")]}),t.jsxs("div",{className:"workflow-output-modal-controls",children:[t.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>C(w.workflowStepId),"data-testid":"workflow-output-modal-mode-toggle",title:q==="markdown"?"Switch to plain text":"Switch to markdown",children:q==="markdown"?"Markdown":"Plain"}),t.jsx("button",{className:"workflow-output-modal-close",onClick:A,"data-testid":"workflow-output-modal-close","aria-label":"Close",children:t.jsx(Ut,{size:16})})]})]}),t.jsx("div",{className:"workflow-output-modal-body",children:t.jsx("div",{className:`workflow-result-output workflow-result-output--expanded${q==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":"workflow-output-modal-content",children:q==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(hi,{remarkPlugins:[pi],components:Jm,children:w.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:w.output})})})]})})})()]})}function UM(e){return e==="block"?"Block execution":e==="fallback-local"?"Fall back to local":"Not configured"}const HM=new Set(["planning","researching","executing","finalizing","merging"]);function qM(e){return e!==void 0&&e!=="online"}function VM({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??""),[g,p]=a.useState(!1),f=a.useRef(e.id);a.useEffect(()=>{f.current=e.id,h(e.nodeId??""),p(!1)},[e.id,e.nodeId]),a.useEffect(()=>{c(!0),d(null),vo().then(A=>{o(A)}).catch(A=>{d(je(A)||"Failed to load nodes")}).finally(()=>{c(!1)})},[]);const x=a.useMemo(()=>new Map(r.map(A=>[A.id,A])),[r]),v=a.useMemo(()=>[...r].sort((A,P)=>A.name.localeCompare(P.name)),[r]),b=n,y=e.nodeId??b?.defaultNodeId??null,S=e.nodeId?"Per-task override":b?.defaultNodeId?"Project default":"No routing",j=y?x.get(y):void 0,R=j?`${j.name} (${j.type})`:y?`${y} (node unavailable or unknown)`:"Local (no routing configured)",k=e.column==="in-progress"||HM.has(e.status),M=k||g||l,C=a.useCallback(async A=>{if(A===m)return;const P=e.id,O=m;h(A),p(!0);try{const V=await Qs(P,{nodeId:A||null});if(f.current!==P)return;h(V.nodeId??""),i?.(V),s(A?"Node override updated":"Node override cleared","success")}catch(V){if(f.current!==P)return;h(O),s(je(V)||"Failed to update node override","error")}finally{f.current===P&&p(!1)}},[s,i,m,e.id]),L=a.useCallback(()=>{C("")},[C]);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:[j?t.jsx(Vi,{status:j.status,compact:!0}):null,R,qM(j?.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:S})]}),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:UM(b?.unavailableNodePolicy)})]})]}),k&&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"}),k?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:A=>{C(A.target.value)},children:[t.jsx("option",{value:"",children:"Use project default"}),v.map(A=>t.jsxs("option",{value:A.id,title:`Status: ${A.status}`,children:[A.name," (",A.type,") — ",A.status]},A.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: ",x.get(e.nodeId)?.name??e.nodeId]}),t.jsx("button",{type:"button",className:"btn btn-sm",disabled:k||g,onClick:L,children:"Clear override"})]}):null]})]})}const WM=/^[a-zA-Z0-9_-]{1,64}$/,KM=200;function Ym(e){return e?new Date(e).toLocaleString():""}function GM(e,n=KM){return e.length<=n?e:e.substring(0,n)+"…"}function JM({taskId:e,addToast:n,onTaskUpdated:s,projectId:i,canEdit:r=!1}){const[o,l]=a.useState([]),[c,u]=a.useState(!0),[d,m]=a.useState(null),[h,g]=a.useState(""),[p,f]=a.useState(null),[x,v]=a.useState(""),[b,y]=a.useState(null),[S,j]=a.useState([]),[R,k]=a.useState(!1),[M,C]=a.useState(!1),[L,A]=a.useState(""),[P,O]=a.useState(""),[V,$]=a.useState(!1),[E,D]=a.useState(null),[U,Y]=a.useState(null),[X,_]=a.useState(!1),I=a.useCallback(async()=>{try{const F=await Wv(e,i);l(F)}catch(F){n(je(F)||"Failed to load documents","error")}finally{u(!1)}},[e,i,n]);a.useEffect(()=>{I()},[I]);async function T(F){d===F.key?(m(null),g(""),f(null),v(""),y(null),j([]),_(!1)):(m(F.key),g(F.content),f(null),v(""),y(null),j([]),_(!1))}async function w(F){if(b===F)y(null),j([]);else{y(F),k(!0);try{const ge=await Kv(e,F,i);j(ge)}catch(ge){n(je(ge)||"Failed to load revisions","error")}finally{k(!1)}}}function q(){d&&(f(d),v(h))}function G(){f(null),v("")}async function me(){if(!(!p||!x.trim())){$(!0);try{await Ud(e,p,x,{},i),f(null),v(""),await I();const F=o.find(ge=>ge.key===p);F&&g(F.content),n("Document saved","success")}catch(F){n(je(F)||"Failed to save document","error")}finally{$(!1)}}}async function ue(){const F=L.trim(),ge=P.trim();if(!F){n("Document key is required","error");return}if(!WM.test(F)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!ge){n("Content is required","error");return}$(!0);try{await Ud(e,F,ge,{},i),C(!1),A(""),O(""),await I(),n("Document created","success")}catch(se){n(je(se)||"Failed to create document","error")}finally{$(!1)}}async function le(F){D(F);try{await Gv(e,F,i),Y(null),D(null),d===F&&(m(null),g("")),b===F&&(y(null),j([])),await I(),n("Document deleted","success")}catch(ge){n(je(ge)||"Failed to delete document","error")}finally{D(null)}}function Se(F){g(F.content),f(null),v("")}return c?t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),t.jsx("div",{className:"detail-log-empty",children:"Loading documents…"})]}):t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),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:L,onChange:F=>A(F.target.value),placeholder:"e.g., plan, notes, research",disabled:V}),t.jsx("span",{className:"form-hint",children:"Alphanumeric, hyphens, underscores (1-64 chars)"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-content",children:"Content"}),t.jsx("textarea",{id:"doc-content",value:P,onChange:F=>O(F.target.value),rows:6,placeholder:"Enter document content…",disabled:V})]}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{C(!1),A(""),O("")},disabled:V,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void ue(),disabled:V||!L.trim()||!P.trim(),children:V?"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:Ym(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:()=>_(ge=>!ge),"aria-label":X?"Switch to plain text":"Switch to markdown","aria-pressed":X,title:X?"Switch to plain text":"Switch to markdown",children:X?"Markdown":"Plain"})}),t.jsx("div",{className:"task-document-content",children:X?t.jsx("div",{className:"task-document-content-markdown",children:t.jsx("div",{className:"markdown-body",children:t.jsx(hi,{remarkPlugins:[pi],children:h})})}):t.jsx("pre",{className:"task-document-content-text",children:h})}),b===F.key&&t.jsxs("div",{className:"task-document-revisions",children:[t.jsx("h5",{children:"Revision History"}),R?t.jsx("div",{className:"detail-log-empty",children:"Loading…"}):S.length<=1?t.jsx("div",{className:"detail-log-empty",children:"No previous revisions."}):t.jsx("div",{className:"task-document-revision-list",children:S.filter(ge=>ge.revision<F.revision).sort((ge,se)=>se.revision-ge.revision).map(ge=>t.jsxs("div",{className:"task-document-revision-item",onClick:()=>Se(ge),children:[t.jsxs("div",{className:"revision-header",children:[t.jsxs("span",{className:"revision-badge",children:["v",ge.revision]}),t.jsx("span",{className:"revision-author",children:ge.author}),t.jsx("span",{className:"revision-timestamp",children:Ym(ge.createdAt)})]}),t.jsx("div",{className:"revision-preview",children:GM(ge.content,100)})]},ge.id))})]})]}),p===F.key&&t.jsxs("div",{className:"task-document-edit-form",children:[t.jsx("textarea",{value:x,onChange:ge=>v(ge.target.value),rows:10,disabled:V}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:G,disabled:V,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void me(),disabled:V||!x.trim(),children:V?"Saving…":"Save"})]})]}),t.jsxs("div",{className:"task-document-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>void T(F),children:d===F.key?t.jsxs(t.Fragment,{children:[t.jsx(ui,{size:14})," Collapse"]}):t.jsxs(t.Fragment,{children:[t.jsx(Vt,{size:14})," Expand"]})}),d===F.key&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>void w(F.key),children:[t.jsx(hr,{size:14})," History"]}),r&&p!==F.key&&t.jsx("button",{className:"btn btn-sm",onClick:q,children:"Edit"}),r&&(U===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 le(F.key),disabled:E===F.key,children:E===F.key?"…":"Yes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Y(null),disabled:E===F.key,children:"No"})]}):t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>Y(F.key),children:t.jsx(Zt,{size:14})}))]})]})]},F.key))}),r&&!M&&t.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>C(!0),children:[t.jsx(en,{size:14})," New Document"]})]})}function io(e){return e.toLocaleString()}function Gl(e){const n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString()}function Ka(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 YM(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 QM({tokenUsage:e,loading:n,task:s}){const i=_p(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=YM(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:Ka(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:Ka(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:Ka(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} (${Ka(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} (${Ka(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 ${Gl(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:io(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:io(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:io(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:io(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:Gl(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:Gl(e.lastUsedAt)})})]})]})]}):t.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:"No token usage recorded for this task yet."})]})]})}const XM=new Set(["planning","researching","executing","finalizing","merging"]);function ZM(e,n){return yp(e,n)}function eA(e,n){return jp(e,n)}function tA(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 nA(e,n,s){if(e.planningModelProvider&&e.planningModelId)return{provider:e.planningModelProvider,modelId:e.planningModelId};const i=tA(n);return i||kp(e,s)}function sA(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 iA(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 aA(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function rA(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 Qm(e,n){return e.length>n?e.slice(0,n)+"…":e}function Xm(e=[],n=[]){return e.length===n.length&&e.every((s,i)=>s===n[i])}function Jl(e){const n=e.indexOf("/");return!e||n===-1?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function Yl(e){return e.trim()}function oA(e){const n=e.trim();return n.length>0?n:void 0}function Ga(e){return typeof e=="string"&&ad.includes(e)?e:ys}function Ja(e){return e==="fast"?"fast":"standard"}const Ql=200,lA=new Set(["triage","todo"]);function cA({task:e,projectId:n,tasks:s=[],onClose:i,onOpenDetail:r,onMoveTask:o,onDeleteTask:l,onMergeTask:c,onRetryTask:u,onDuplicateTask:d,onTaskUpdated:m,addToast:h,prAuthAvailable:g,initialTab:p="definition"}){const[f,x]=a.useState(p),[v,b]=a.useState(()=>"prompt"in e?e:null),[y,S]=a.useState(()=>!("prompt"in e));a.useEffect(()=>{if("prompt"in e){b(e),S(!1);return}let Z=!1;return S(!0),b(null),xo(e.id,n).then(Be=>{Z||(b(Be),S(!1))}).catch(()=>{Z||S(!1)}),()=>{Z=!0}},[e.id,n]);const j=v?{...v,...e,prompt:v.prompt,log:v.log}:{...e,prompt:""},R=e.status==="failed"||e.status==="stuck-killed"||e.status==="planning"||e.status==="needs-replan"||(e.stuckKillCount??0)>0||(e.recoveryRetryCount??0)>0||!!e.nextRecoveryAt;a.useEffect(()=>{x(p)},[p]),a.useEffect(()=>{L(!1)},[e.id]);const[k,M]=a.useState("activity"),[C,L]=a.useState(!1),[A,P]=a.useState(e.attachments||[]),[O,V]=a.useState(!1),[$,E]=a.useState(e.dependencies||[]),[D,U]=a.useState(!1),[Y,X]=a.useState(""),[_,I]=a.useState(null),[T,w]=a.useState([]),[q,G]=a.useState(!1),[me,ue]=a.useState(!1),[le,Se]=a.useState(!1),[F,ge]=a.useState(!1),[se,fe]=a.useState(!1),[de,xe]=a.useState(j.prompt||""),[ie,Ee]=a.useState(""),[De,qe]=a.useState(!1),[Qe,Je]=a.useState(""),[Ke,it]=a.useState(!1),[Pe,Ve]=a.useState(!1),[ae,ye]=a.useState(e.title||""),[te,Ae]=a.useState(e.description||""),[Le,pe]=a.useState(e.dependencies||[]),[_e,Fe]=a.useState(""),[tt,Ne]=a.useState(""),[oe,Te]=a.useState(""),[he,Me]=a.useState(""),[We,Re]=a.useState("default"),[ot,J]=a.useState(void 0),[ce,ve]=a.useState(ys),[Xe,ee]=a.useState(e.nodeId),[Ge,ct]=a.useState(Ja(e.executionMode)),[vt,bt]=a.useState(""),[ft,gt]=a.useState(e.enabledWorkflowSteps||[]),[_t,Rt]=a.useState(e.sourceIssue?.provider??""),[Ft,wt]=a.useState(e.sourceIssue?.repository??""),[At,qt]=a.useState(e.sourceIssue?.externalIssueId??""),[zt,Wt]=a.useState(e.sourceIssue?.url??""),[Ot,Nt]=a.useState([]),[Mt,Ct]=a.useState(!1),Gt=a.useRef(!1),[Et,H]=a.useState(!1),[be,re]=a.useState(!1),[N,W]=a.useState(!1),Ie=a.useRef(null),nt=a.useRef(null),yt=a.useRef(null),Pt=a.useRef(null);ni(Pt,!0,"fusion:task-detail-modal-size");const{getSlotsForId:Tt}=xp(n),tn=Tt("task-detail-tab");a.useEffect(()=>(Gt.current=!0,()=>{Gt.current=!1}),[]);const[nn,Ln]=a.useState(void 0),[Jt,Rn]=a.useState([]),[ke,at]=a.useState(!1),[gn,Tn]=a.useState(e.enabledWorkflowSteps||[]),Pn=e.column==="in-progress"||XM.has(e.status);a.useEffect(()=>{ye(e.title||""),Ae(e.description||""),Rt(e.sourceIssue?.provider??""),wt(e.sourceIssue?.repository??""),qt(e.sourceIssue?.externalIssueId??""),Wt(e.sourceIssue?.url??""),ct(Ja(e.executionMode)),W(!1),Ve(!1)},[e.id,e.title,e.description,e.sourceIssue,e.executionMode]),a.useEffect(()=>{Tn(e.enabledWorkflowSteps||[])},[e.id,e.enabledWorkflowSteps]),a.useEffect(()=>{let Z=!1;return Fo(n).then(Be=>{Z||Ln(Be)}).catch(()=>{}),()=>{Z=!0}},[n]),a.useEffect(()=>{if(f!=="workflow")return;let Z=!1;return at(!0),xj(e.id,n).then(Be=>{Z||Rn(Be)}).catch(Be=>{Z||h(`Failed to load workflow results: ${je(Be)}`,"error")}).finally(()=>{Z||at(!1)}),()=>{Z=!0}},[f,e.id,n,h]),a.useEffect(()=>{if(f!=="workflow")return;const Z=n?`?projectId=${encodeURIComponent(n)}`:"",Be=lt=>{try{const $t=JSON.parse(lt.data);$t.id===e.id&&Array.isArray($t.workflowStepResults)&&Rn($t.workflowStepResults)}catch{}};return qs(`/api/events${Z}`,{events:{"task:updated":Be}})},[f,e.id,n]),a.useEffect(()=>{D||X("")},[D]),a.useEffect(()=>{if(!e.assignedAgentId){I(null);return}const Z=T.find(lt=>lt.id===e.assignedAgentId);if(Z){I(Z);return}let Be=!1;return dp(e.assignedAgentId,n).then(lt=>{Be||I(lt)}).catch(()=>{Be||I(null)}),()=>{Be=!0}},[e.assignedAgentId,n,T]),a.useEffect(()=>{G(!1)},[e.id]),a.useEffect(()=>{if(!(Et||be))return;const Be=lt=>{const $t=lt.target,Vs=Ie.current?.contains($t),gs=yt.current?.contains($t);!Vs&&Et&&H(!1),!gs&&be&&re(!1)};return document.addEventListener("mousedown",Be),()=>document.removeEventListener("mousedown",Be)},[Et,be]),a.useEffect(()=>{if(!(Et||be))return;const Be=lt=>{lt.key==="Escape"&&(lt.stopPropagation(),Et&&H(!1),be&&re(!1))};return document.addEventListener("keydown",Be),()=>document.removeEventListener("keydown",Be)},[Et,be]),a.useEffect(()=>{fe(!1),xe(j.prompt||""),Ee("")},[e.id,j.prompt]);const Nn=lA.has(e.column)&&!Mt,es=a.useCallback(()=>{if(!Nn)return;Ve(!0),ye(e.title||""),Ae(e.description||""),pe(e.dependencies||[]);const Z=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"",Be=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"",lt=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";Fe(Z),Ne(Be),Te(lt),Me(e.thinkingLevel??""),ee(e.nodeId),Re(Z||Be||lt?"custom":"default"),bt(""),gt(e.enabledWorkflowSteps||[]),ct(Ja(e.executionMode)),Rt(e.sourceIssue?.provider??""),wt(e.sourceIssue?.repository??""),qt(e.sourceIssue?.externalIssueId??""),Wt(e.sourceIssue?.url??""),Nt([]),J(e.reviewLevel),ve(Ga(e.priority))},[Nn,e]),Sn=a.useCallback(()=>{Ve(!1),ye(e.title||""),Ae(e.description||""),pe(e.dependencies||[]),ee(e.nodeId),Rt(e.sourceIssue?.provider??""),wt(e.sourceIssue?.repository??""),qt(e.sourceIssue?.externalIssueId??""),Wt(e.sourceIssue?.url??""),ve(Ga(e.priority)),ct(Ja(e.executionMode)),Ot.forEach(Z=>URL.revokeObjectURL(Z.previewUrl)),Nt([])},[e.title,e.description,e.dependencies,e.nodeId,e.priority,e.executionMode,Ot]),Yt=a.useCallback(async()=>{Ct(!0);try{const Z={},Be=ae.trim(),lt=te.trim();Be&&Be!==(e.title??"")&&(Z.title=Be),lt&<!==(e.description??"")&&(Z.description=lt),Xm(Le,e.dependencies??[])||(Z.dependencies=Le),Xm(ft,e.enabledWorkflowSteps??[])||(Z.enabledWorkflowSteps=ft);const $t=Jl(_e),Vs=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"";_e!==Vs&&(Z.modelProvider=$t?.provider??null,Z.modelId=$t?.modelId??null);const gs=Jl(tt),xi=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"";tt!==xi&&(Z.validatorModelProvider=gs?.provider??null,Z.validatorModelId=gs?.modelId??null);const La=Jl(oe),Or=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";oe!==Or&&(Z.planningModelProvider=La?.provider??null,Z.planningModelId=La?.modelId??null);const Xi=e.thinkingLevel??"";he!==Xi&&(Z.thinkingLevel=he!==""?he:null),(e.nodeId??void 0)!==Xe&&(Z.nodeId=Xe??null);const el=e.reviewLevel;ot!==el&&(Z.reviewLevel=ot);const tl=Ga(e.priority);ce!==tl&&(Z.priority=ce);const nl=Ja(e.executionMode);Ge!==nl&&(Z.executionMode=Ge==="fast"?"fast":null);const Ai=Yl(_t),Zi=Yl(Ft),Ri=Yl(At),ea=oA(zt);if(Ai.length===0&&Zi.length===0&&Ri.length===0&&!ea)e.sourceIssue&&(Z.sourceIssue=null);else{if(!Ai||!Zi||!Ri){h("Source issue provider, repository, and issue identifier are required","error"),Ct(!1);return}const Cs=Number.parseInt(Ri,10),ri=e.sourceIssue?.issueNumber??Cs;if(!Number.isFinite(ri)||ri<=0){h("Source issue identifier must be numeric for new metadata","error"),Ct(!1);return}const B={provider:Ai,repository:Zi,externalIssueId:Ri,issueNumber:ri,...ea?{url:ea}:{}},we=e.sourceIssue;(!we||we.provider!==B.provider||we.repository!==B.repository||we.externalIssueId!==B.externalIssueId||we.issueNumber!==B.issueNumber||(we.url??void 0)!==B.url)&&(Z.sourceIssue=B)}if(Object.keys(Z).length>0){const Cs=await Qs(e.id,Z,n);m?.(Cs)}if(Ot.length>0){const Cs=[];for(const ri of Ot)try{const B=await gr(e.id,ri.file,n);P(we=>[...we,B])}catch{Cs.push(ri.file.name)}Cs.length>0&&h(`Failed to upload: ${Cs.join(", ")}`,"error")}Ot.forEach(Cs=>URL.revokeObjectURL(Cs.previewUrl)),Nt([]),h(`Updated ${e.id}`,"success"),Ve(!1)}catch(Z){h(`Failed to update ${e.id}: ${je(Z)}`,"error")}finally{Gt.current&&Ct(!1)}},[e,ae,te,Le,_e,tt,oe,he,Xe,ot,ce,Ge,ft,_t,Ft,At,zt,Ot,h,n,m]),Q=a.useCallback(async Z=>{try{await Qs(e.id,{description:Z},n),h("Description saved","success")}catch(Be){h(`Failed to save: ${je(Be)}`,"error")}},[e.id,h,n]),ze=a.useCallback(Z=>{Pe&&(Z.key==="Escape"?(Z.preventDefault(),Sn()):Z.key==="Enter"&&(Z.ctrlKey||Z.metaKey)&&(Z.preventDefault(),Yt()))},[Pe,Sn,Yt]);a.useEffect(()=>{if(Pe)return document.addEventListener("keydown",ze),()=>document.removeEventListener("keydown",ze)},[Pe,ze]);const Ye=a.useRef(null),{nodes:et}=qo(),{confirm:dt}=Hs(),{entries:St,loading:It,loadMore:kn,hasMore:sn,total:jt,loadingMore:os}=Wf(e.id,f==="logs"&&k==="agent-log",n);a.useEffect(()=>{const Z=Be=>{Be.key==="Escape"&&!Pe&&i()};return document.addEventListener("keydown",Z),()=>document.removeEventListener("keydown",Z)},[i,Pe]);const ws=Si(i),Ns=a.useCallback(async Z=>{try{await o(e.id,Z),i(),h(`Moved to ${An[Z]}`,"success")}catch(Be){h(je(Be),"error")}},[e.id,o,i,h]),$s=a.useCallback(async()=>{if(await dt({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0}))try{await l(e.id),i(),h(`Deleted ${e.id}`,"info")}catch(Be){const lt=rA(Be);if(!lt||lt.dependentIds.length===0){h(je(Be),"error");return}const $t=lt.dependentIds.join(", ");if(!await dt({title:"Force Delete Task",message:`${e.id} is a dependency of ${$t}.
|
|
651
|
+
|
|
652
|
+
Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await l(e.id,{removeDependencyReferences:!0}),i(),h(`Deleted ${e.id} after removing dependency references`,"info")}catch(gs){h(je(gs),"error")}}},[e.id,l,i,h,dt]),ii=a.useCallback(async()=>{await dt({title:"Merge Task",message:`Merge ${e.id} into the current branch?`})&&(i(),h(`Merging ${e.id}...`,"info"),c(e.id).then(Be=>{const lt=Be.merged?`Merged ${e.id} (branch: ${Be.branch})`:`Closed ${e.id} (${Be.error||"no branch to merge"})`;h(lt,"success")}).catch(Be=>{h(je(Be),"error")}))},[e.id,c,i,h,dt]),Ds=a.useCallback(()=>{u&&(i(),u(e.id).then(()=>{h(`Retried ${e.id}`,"success")}).catch(Z=>{h(je(Z),"error")}))},[e.id,u,i,h]),Ls=a.useCallback(async()=>{if(!(!d||!await dt({title:"Duplicate Task",message:`Duplicate ${e.id}? This will create a new task in Triage with the same description and prompt.`})))try{const Be=await d(e.id);i(),h(`Duplicated ${e.id} → ${Be.id}`,"success")}catch(Be){h(je(Be),"error")}},[e.id,d,i,h,dt]),Ei=a.useCallback(async()=>{try{e.paused?(await $v(e.id,n),h(`Unpaused ${e.id}`,"success")):(await sp(e.id,n),h(`Paused ${e.id}`,"success")),i()}catch(Z){h(je(Z),"error")}},[e.id,e.paused,i,h]),gi=a.useCallback(async()=>{try{await Fv(e.id,n),h(`Plan approved — ${e.id} moved to Todo`,"success"),i()}catch(Z){h(je(Z),"error")}},[e.id,i,h]),ut=a.useCallback(async()=>{if(await dt({title:"Reject Plan",message:"Reject this plan? The specification will be discarded and regenerated.",danger:!0}))try{await Ov(e.id,n),h(`Plan rejected — ${e.id} returned to Planning for replanning`,"info"),i()}catch(Be){h(je(Be),"error")}},[e.id,i,h,dt]),bn=a.useCallback(async()=>{if(await dt({title:"Rebuild Plan",message:"Rebuild the plan for this task? The task will move to planning for replanning."}))try{await Qv(e.id,n),i(),h(`Replanning ${e.id}...`,"info")}catch(Be){h(je(Be),"error")}},[e.id,n,i,h,dt]),ps=a.useCallback(()=>{qe(!0),Je("")},[]),ne=a.useCallback(()=>{H(!1),re(!1)},[]),Ce=a.useCallback(Z=>{ne(),Ns(Z)},[ne]),Ze=a.useCallback(Z=>{ne(),Z()},[ne]),xt=a.useCallback(()=>{ne(),ii()},[ne,ii]),ht=a.useCallback(()=>{qe(!1),Je(""),it(!1)},[]),xn=a.useCallback(async()=>{if(!Qe.trim()){h("Please enter feedback describing what needs refinement","error");return}if(Qe.length>2e3){h("Feedback must be 2000 characters or less","error");return}it(!0);try{const Z=await Xv(e.id,Qe.trim(),n);h(`Refinement task created: ${Z.id}`,"success"),i()}catch(Z){h(je(Z),"error")}finally{it(!1)}},[e.id,Qe,h,i]),Qt=a.useCallback(async Z=>{V(!0);try{const Be=await gr(e.id,Z,n);P(lt=>[...lt,Be]),h("Screenshot attached","success")}catch(Be){h(je(Be),"error")}finally{V(!1)}},[e.id,h]),an=a.useCallback(async Z=>{const Be=Z.target.files?.[0];Be&&(await Qt(Be),Ye.current&&(Ye.current.value=""))},[Qt]);a.useEffect(()=>{const Z=Be=>{const lt=Be.clipboardData?.items;if(lt)for(let $t=0;$t<lt.length;$t++){const Vs=lt[$t];if(Vs.type.startsWith("image/")){const gs=Vs.getAsFile();if(gs){Be.preventDefault(),Qt(gs);return}}}};return document.addEventListener("paste",Z),()=>document.removeEventListener("paste",Z)},[Qt]);const dn=a.useCallback(Z=>{Z.preventDefault()},[]),In=a.useCallback(Z=>{Z.preventDefault();const Be=Z.dataTransfer.files;for(let lt=0;lt<Be.length;lt++){const $t=Be[lt];if($t.type.startsWith("image/")){Qt($t);return}}},[Qt]),Vn=a.useCallback(async Z=>{try{await Hv(e.id,Z,n),P(Be=>Be.filter(lt=>lt.filename!==Z)),h("Attachment deleted","info")}catch(Be){h(je(Be),"error")}},[e.id,h]),Wn=a.useCallback(async Z=>{const Be=gn;Tn(Z);try{const lt=await Qs(e.id,{enabledWorkflowSteps:Z},n);h("Workflow steps updated","success"),m?.(lt)}catch(lt){Tn(Be),h(`Failed to update workflow steps: ${je(lt)}`,"error")}},[e.id,n,gn,m,h]),Cn=a.useCallback(async()=>{ue(!0);try{const Z=await Ma(void 0,n);w(Z),G(!0)}catch(Z){h(`Failed to load agents: ${je(Z)}`,"error"),G(!1)}finally{ue(!1)}},[n,h]),Kn=a.useCallback(async Z=>{try{const Be=await Zd(e.id,Z,n),lt=T.find($t=>$t.id===Z)??null;I(lt||($t=>$t?.id===Z?$t:null)),G(!1),m?.(Be),h("Assigned agent updated","success")}catch(Be){h(`Failed to assign agent: ${je(Be)}`,"error")}},[e.id,n,T,m,h]),zn=a.useCallback(async()=>{try{const Z=await Zd(e.id,null,n);I(null),G(!1),m?.(Z),h("Agent unassigned","success")}catch(Z){h(`Failed to unassign agent: ${je(Z)}`,"error")}},[e.id,n,m,h]),fs=a.useCallback(async Z=>{const Be=[...$,Z];E(Be);try{await Qs(e.id,{dependencies:Be},n)}catch(lt){E($),h(je(lt),"error")}},[e.id,$,h]),vn=a.useCallback(async(Z,Be)=>{Z.stopPropagation();const lt=$.filter($t=>$t!==Be);E(lt);try{await Qs(e.id,{dependencies:lt},n)}catch($t){E($),h(je($t),"error")}},[e.id,$,h]),Fn=a.useCallback(async Z=>{try{const Be=await xo(Z,n);r(Be)}catch{h(`Failed to load dependency ${Z}`,"error")}},[r,h]),ls=a.useCallback(async Z=>{Se(!0);try{await Qs(j.id,{prompt:Z},n),h("Spec updated","success"),v&&(v.prompt=Z)}catch(Be){throw h(je(Be),"error"),Be}finally{Se(!1)}},[j,v,h]),Ss=a.useCallback(async Z=>{ge(!0);try{await Yv(e.id,Z,n),h("AI revision requested. Task moved to planning.","success"),i()}catch(Be){const lt=je(Be);lt.includes("in-review")||lt.includes("done")?h("Cannot request revision: Task must be in 'todo' or 'in-progress' column.","error"):h(lt,"error")}finally{ge(!1)}},[e.id,h,i]),ts=a.useCallback(()=>{fe(!0),xe(j.prompt||""),Ee("")},[j.prompt]),rn=a.useCallback(()=>{fe(!1),xe(j.prompt||""),Ee("")},[j.prompt]),On=a.useCallback(async()=>{if(de===(j.prompt||"")){rn();return}fe(!1);try{await ls(de)}catch(Z){throw fe(!0),Z}},[de,j.prompt,ls,rn]),zs=a.useCallback(async()=>{ie.trim()&&await Ss(ie.trim())},[ie,Ss]),Xo=a.useCallback(Z=>{Z.key==="Escape"?(Z.preventDefault(),rn()):Z.key==="Enter"&&(Z.ctrlKey||Z.metaKey)&&(Z.preventDefault(),On())},[rn,On]),_i=s.filter(Z=>Z.id!==e.id&&!$.includes(Z.id)).sort((Z,Be)=>{const lt=Be.createdAt.localeCompare(Z.createdAt);if(lt!==0)return lt;const $t=parseInt(Z.id.slice(Z.id.lastIndexOf("-")+1),10)||0;return(parseInt(Be.id.slice(Be.id.lastIndexOf("-")+1),10)||0)-$t}),Dr=_?.name??e.assignedAgentId??null,Fs=a.useMemo(()=>{const Z=[];return j.modelProvider&&Z.push(j.modelProvider),j.validatorModelProvider&&!Z.includes(j.validatorModelProvider)&&Z.push(j.validatorModelProvider),j.planningModelProvider&&!Z.includes(j.planningModelProvider)&&Z.push(j.planningModelProvider),Z},[j.modelProvider,j.validatorModelProvider,j.planningModelProvider]),Lr=Cc[e.column]||[],zr=["todo","in-progress"],Fr=e.column==="in-review"?zr:Lr,Gn=Fr[0],Ia=Fr.slice(1),_n=Ia.length>0,ai=a.useCallback(()=>{H(!1),nt.current?.focus()},[]),Mi=a.useCallback(Z=>{if(!_n){Gn&&Ce(Gn);return}const Be=Z.currentTarget.querySelector(".detail-move-btn__arrow");if(!!(Z.target instanceof Element&&Z.target.closest(".detail-move-btn__arrow")||Be&&Z.clientX>0&&Z.clientX>=Be.getBoundingClientRect().left)){H($t=>!$t),re(!1);return}Gn&&Ce(Gn)},[_n,Gn,Ce]),$a=a.useCallback(Z=>{!_n||!(Z.key==="ArrowDown"||Z.altKey&&Z.key==="ArrowDown")||(Z.preventDefault(),H(!0),re(!1))},[_n]),Qi=a.useCallback(Z=>{Z.key==="Escape"&&(Z.preventDefault(),Z.stopPropagation(),ai())},[ai]);a.useEffect(()=>{if(!Et)return;Ie.current?.querySelector(".detail-move-menu-item")?.focus()},[Et]);const Zo={"creating-pr":"Creating PR…","awaiting-pr-checks":"Awaiting PR checks","merging-pr":"Merging PR…"},Da=e.status?Zo[e.status]:void 0;return t.jsx("div",{className:"modal-overlay open",...ws,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg task-detail-modal",ref:Pt,onDragOver:dn,onDrop:In,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx("span",{className:"detail-id",children:e.id}),t.jsx("span",{className:`detail-column-badge badge-${e.column}`,children:An[e.column]})]}),t.jsxs("div",{className:"modal-header-actions",children:[!Pe&&Nn&&t.jsx("button",{className:"modal-edit-btn",onClick:es,title:"Edit task","aria-label":"Edit task",children:t.jsx(ss,{size:14})}),t.jsx("button",{className:"modal-close",onClick:i,"aria-label":"Close",children:"×"})]})]}),t.jsxs("div",{className:`detail-body${f==="logs"&&k==="agent-log"&&!Pe?" detail-body--agent-log":""}`,children:[Pe?t.jsx("div",{className:"modal-edit-form",children:t.jsx(Jf,{mode:"edit",title:ae,onTitleChange:ye,description:te,onDescriptionChange:Ae,dependencies:Le,onDependenciesChange:pe,executorModel:_e,onExecutorModelChange:Fe,validatorModel:tt,onValidatorModelChange:Ne,planningModel:oe,onPlanningModelChange:Te,thinkingLevel:he,onThinkingLevelChange:Me,presetMode:We,onPresetModeChange:Re,selectedPresetId:vt,onSelectedPresetIdChange:bt,selectedWorkflowSteps:ft,onWorkflowStepsChange:gt,pendingImages:Ot,onImagesChange:Nt,tasks:s.filter(Z=>Z.id!==e.id),projectId:n,disabled:Mt,addToast:h,isActive:Pe,onAutoSaveDescription:Q,reviewLevel:ot,onReviewLevelChange:J,priority:ce,onPriorityChange:ve,nodeId:Xe,onNodeIdChange:ee,nodeOptions:et,nodeOverrideDisabled:Pn,nodeOverrideDisabledReason:Pn?"Execution node override is locked while a task is active/in progress.":void 0,executionMode:Ge,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:_t,onChange:Z=>Rt(Z.target.value),disabled:Mt,"data-testid":"task-source-provider-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Repository (e.g. owner/repo)",value:Ft,onChange:Z=>wt(Z.target.value),disabled:Mt,"data-testid":"task-source-repository-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Issue identifier",value:At,onChange:Z=>qt(Z.target.value),disabled:Mt,"data-testid":"task-source-external-id-input"}),t.jsx("input",{type:"url",className:"modal-edit-input",placeholder:"Issue URL",value:zt,onChange:Z=>Wt(Z.target.value),disabled:Mt,"data-testid":"task-source-url-input"})]}),t.jsx("small",{children:"Leave all fields empty to clear source issue metadata."})]})})}):t.jsxs(t.Fragment,{children:[(()=>{const Z=e.title||e.description||e.id,Be=!C&&Z.length>Ql;return t.jsxs(t.Fragment,{children:[t.jsx("h2",{className:"detail-title",children:Be?Z.slice(0,Ql)+"…":Z}),Z.length>Ql&&t.jsx("button",{className:"detail-description-toggle",onClick:()=>L(!C),children:C?"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--${Ga(e.priority)}`,children:["Priority: ",Ga(e.priority)]})]})]}),e.status==="failed"&&e.error&&t.jsxs("div",{className:"detail-error-alert",children:[t.jsx("span",{className:"detail-error-icon",children:"⚠"}),t.jsxs("div",{className:"detail-error-content",children:[t.jsx("div",{className:"detail-error-title",children:"Task Failed"}),t.jsx("div",{className:"detail-error-message",children:e.error})]})]}),!Pe&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"detail-tabs",children:[t.jsx("button",{className:`detail-tab${f==="definition"?" detail-tab-active":""}`,onClick:()=>x("definition"),children:"Definition"}),t.jsx("button",{className:`detail-tab${f==="logs"?" detail-tab-active":""}`,onClick:()=>x("logs"),children:"Logs"}),(e.column==="in-progress"||e.column==="in-review"||e.column==="done")&&t.jsx("button",{className:`detail-tab${f==="changes"?" detail-tab-active":""}`,onClick:()=>x("changes"),children:"Changes"}),t.jsx("button",{className:`detail-tab${f==="comments"?" detail-tab-active":""}`,onClick:()=>x("comments"),children:"Comments"}),t.jsx("button",{className:`detail-tab${f==="documents"?" detail-tab-active":""}`,onClick:()=>x("documents"),children:"Documents"}),t.jsx("button",{className:`detail-tab${f==="model"?" detail-tab-active":""}`,onClick:()=>x("model"),children:"Model"}),t.jsx("button",{className:`detail-tab${f==="workflow"?" detail-tab-active":""}`,onClick:()=>x("workflow"),children:"Workflow"}),t.jsx("button",{className:`detail-tab${f==="stats"?" detail-tab-active":""}`,onClick:()=>x("stats"),children:"Stats"}),t.jsx("button",{className:`detail-tab${f==="routing"?" detail-tab-active":""}`,onClick:()=>x("routing"),children:"Routing"}),tn.map((Z,Be)=>{const lt=`plugin-${Be}`;return t.jsx("button",{className:`detail-tab${f===lt?" detail-tab-active":""}`,onClick:()=>x(lt),children:Z.slot.label},`plugin-tab-${Z.pluginId}`)})]}),f==="workflow"?t.jsx("div",{className:"detail-section",children:t.jsx(BM,{taskId:e.id,results:Jt,loading:ke,enabledWorkflowSteps:gn,canEdit:Nn,projectId:n,isTaskInProgress:e.column==="in-progress"&&e.status!=="paused",onWorkflowStepsChange:Wn})}):f==="model"?t.jsx("div",{className:"detail-section",children:t.jsx(kM,{task:e,addToast:h,onTaskUpdated:m,settings:nn})}):f==="logs"?t.jsxs("div",{className:`detail-section${k==="agent-log"?" detail-section--agent-log":""}`,children:[t.jsxs("div",{className:"log-subview-toggle",children:[t.jsx("button",{className:`log-subview-btn${k==="activity"?" log-subview-btn-active":""}`,onClick:()=>M("activity"),children:"Activity"}),t.jsx("button",{className:`log-subview-btn${k==="agent-log"?" log-subview-btn-active":""}`,onClick:()=>M("agent-log"),children:"Agent Log"})]}),k==="agent-log"?t.jsx(xM,{entries:St,loading:It,executorModel:ZM(e,nn),validatorModel:eA(e,nn),planningModel:nA(e,St,nn),hasMore:sn,onLoadMore:kn,loadingMore:os,totalCount:jt}):t.jsxs("div",{className:"detail-activity",children:[t.jsx("h4",{children:"Activity"}),j.activityLogTruncatedCount?t.jsxs("div",{className:"detail-log-truncated",children:["Showing the most recent ",j.log.length," activity entries."]}):null,j.log&&j.log.length>0?t.jsx("div",{className:"detail-activity-list",children:[...j.log].reverse().map((Z,Be)=>t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-timestamp",children:iA(Z.timestamp)}),t.jsx("span",{className:"detail-log-action",children:Z.action})]}),Z.outcome&&t.jsx("div",{className:"detail-log-outcome",children:Z.outcome})]},Be))}):t.jsx("div",{className:"detail-log-empty",children:"(no activity)"})]})]}):f==="changes"?t.jsx(TM,{taskId:e.id,worktree:e.worktree,projectId:n,column:e.column,mergeDetails:e.mergeDetails,modifiedFiles:e.modifiedFiles}):f==="comments"?t.jsx(EM,{task:e,addToast:h,projectId:n,onTaskUpdated:m}):f==="documents"?t.jsx(JM,{taskId:e.id,addToast:h,projectId:n,onTaskUpdated:m,canEdit:Nn}):typeof f=="string"&&f.startsWith("plugin-")?t.jsx("div",{className:"detail-section",children:t.jsx(Uo,{slotId:"task-detail-tab",projectId:n})}):f==="stats"?t.jsx("div",{className:"detail-section",children:t.jsx(QM,{tokenUsage:j.tokenUsage,loading:y,task:j})}):f==="routing"?t.jsx("div",{className:"detail-section",children:t.jsx(VM,{task:e,settings:nn,addToast:h,onTaskUpdated:m})}):t.jsxs(t.Fragment,{children:[e.column==="done"&&e.summary&&t.jsxs("div",{className:"detail-section detail-summary",children:[t.jsx("h4",{children:"Summary"}),t.jsx("div",{className:"markdown-body",children:t.jsx(hi,{remarkPlugins:[pi],children:e.summary})})]}),t.jsx(MM,{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":N,"aria-label":N?"Collapse source issue details":"Expand source issue details",onClick:()=>W(Z=>!Z),children:t.jsx(pn,{size:16,className:N?"detail-source-chevron--expanded":void 0})})]}),N&&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:[Fs.length>0&&t.jsx("span",{className:"detail-provider-icons","data-testid":"detail-provider-icons",children:Fs.map(Z=>t.jsx(Dn,{provider:Z,size:"sm"},Z))}),t.jsxs("span",{className:"detail-meta-label",children:[t.jsx(yn,{size:14,style:{verticalAlign:"middle",marginRight:6}}),"Agent"]})]}),t.jsxs("div",{className:"detail-agent-actions",children:[Dr?t.jsxs("span",{className:"detail-agent-chip",children:[t.jsx(yn,{size:14}),Dr,t.jsx("button",{className:"detail-agent-clear",onClick:()=>void zn(),title:"Unassign agent",children:t.jsx(Ut,{size:12})})]}):t.jsx("button",{className:"btn btn-sm",onClick:()=>{q?G(!1):Cn()},children:"Assign Agent"}),q&&t.jsxs("div",{className:"agent-picker-dropdown",children:[me&&t.jsx("div",{className:"agent-picker-loading",children:"Loading agents..."}),!me&&T.filter(Z=>Z.state!=="terminated").map(Z=>t.jsxs("button",{className:`agent-picker-item${e.assignedAgentId===Z.id?" selected":""}`,onClick:()=>void Kn(Z.id),children:[t.jsx(yn,{size:14}),t.jsx("span",{className:"agent-picker-name",children:Z.name}),t.jsx("span",{className:"agent-picker-role",children:Z.role})]},Z.id)),!me&&T.filter(Z=>Z.state!=="terminated").length===0&&t.jsx("div",{className:"agent-picker-empty",children:"No agents available"})]})]})]})}),t.jsxs("div",{className:"detail-section detail-step-progress",children:[t.jsx("h4",{children:"Progress"}),j.steps&&j.steps.length>0?t.jsxs("div",{className:"step-progress-wrapper",children:[t.jsx("div",{className:"step-progress-bar",children:j.steps.map((Z,Be)=>t.jsx("div",{className:`step-progress-segment step-progress-segment--${Z.status}`,"data-tooltip":`${Z.name} (${Z.status})`,style:{backgroundColor:sA(Z.status)}},Be))}),t.jsxs("span",{className:"step-progress-label",children:[j.steps.filter(Z=>Z.status==="done").length,"/",j.steps.length," step",j.steps.length===1?"":"s"]})]}):t.jsx("div",{className:"step-progress-empty",children:"(no steps defined)"})]}),t.jsxs("div",{className:"detail-section",children:[!se&&t.jsx("div",{className:"detail-spec-edit-trigger",children:t.jsx("button",{className:"btn btn-sm",onClick:ts,children:"Edit"})}),se?t.jsxs("div",{className:"spec-editor-edit-mode",children:[t.jsx("textarea",{className:"spec-editor-textarea",value:de,onChange:Z=>xe(Z.target.value),onKeyDown:Xo,disabled:le,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:rn,disabled:le,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void On(),disabled:de===(j.prompt||"")||le,children:le?"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:ie,onChange:Z=>Ee(Z.target.value),placeholder:"e.g., 'Add more details about error handling', 'Split this into smaller steps', 'Include tests for the API endpoints'...",disabled:F,rows:4,maxLength:2e3}),t.jsxs("div",{className:"spec-editor-revision-actions",children:[t.jsxs("span",{className:"spec-editor-char-count",children:[ie.length,"/2000"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void zs(),disabled:!ie.trim()||F,children:F?"Requesting…":"Request AI Revision"})]})]})]}):y?t.jsx("div",{className:"spec-loading",children:"Loading specification…"}):j.prompt?t.jsx("div",{className:"markdown-body",children:t.jsx(hi,{remarkPlugins:[pi],children:j.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"}),A.length>0?t.jsx("div",{className:"detail-attachments-grid",children:A.map(Z=>{const Be=ti(`/api/tasks/${e.id}/attachments/${Z.filename}`);return t.jsxs("div",{className:"detail-attachment-card",children:[t.jsx("a",{className:"detail-attachment-link",href:Be,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{src:Be,alt:Z.originalName,className:"detail-attachment-image"})}),t.jsxs("div",{className:"detail-attachment-meta",children:[Z.originalName," (",aA(Z.size),")"]}),t.jsx("button",{className:"detail-attachment-delete",onClick:()=>Vn(Z.filename),title:"Delete attachment",children:"×"})]},Z.filename)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no attachments)"}),t.jsx("input",{className:"detail-hidden-file-input",ref:Ye,type:"file",accept:"image/*",onChange:an}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Ye.current?.click(),disabled:O,children:O?"Uploading…":"Attach Screenshot"})]}),t.jsxs("div",{className:"detail-deps",children:[t.jsx("h4",{children:"Dependencies"}),$.length>0?t.jsx("ul",{className:"detail-dep-list",children:$.map(Z=>{const Be=s.find($t=>$t.id===Z),lt=Be?.title||Be?.description||Z;return t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>Fn(Z),onKeyDown:$t=>{($t.key==="Enter"||$t.key===" ")&&($t.preventDefault(),Fn(Z))},role:"link",tabIndex:0,title:`Click to view ${Z}`,children:[t.jsx("span",{className:"detail-dep-id",children:Z}),t.jsx("span",{className:"detail-dep-label",children:Qm(lt,40)})]}),t.jsx("button",{className:"dep-remove-btn",onClick:$t=>vn($t,Z),title:`Remove dependency ${Z}`,children:"×"})]},Z)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no dependencies)"}),t.jsxs("div",{className:"dep-trigger-wrap",children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{D&&X(""),U(Z=>!Z)},children:"Add Dependency"}),D&&(()=>{const Z=Y.toLowerCase(),Be=Z?_i.filter(lt=>lt.id.toLowerCase().includes(Z)||lt.title&<.title.toLowerCase().includes(Z)||lt.description&<.description.toLowerCase().includes(Z)):_i;return t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Y,onChange:lt=>X(lt.target.value),onClick:lt=>lt.stopPropagation()}),Be.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Be.map(lt=>t.jsxs("div",{className:"dep-dropdown-item",onClick:()=>{fs(lt.id),U(!1)},children:[t.jsx("span",{className:"dep-dropdown-id",children:lt.id}),t.jsx("span",{className:"dep-dropdown-title",children:Qm(lt.title||lt.description||lt.id,30)})]},lt.id))]})})()]})]}),e.column==="in-review"&&t.jsx(NM,{taskId:e.id,projectId:n,prInfo:e.prInfo,automationStatus:e.status??null,autoMerge:nn?.autoMerge??!1,prAuthAvailable:g??!1,onPrCreated:Z=>{e.prInfo=Z,h(`PR #${Z.number} created`,"success")},onPrUpdated:Z=>{e.prInfo=Z},addToast:h})]})]})]}),t.jsx("div",{className:"modal-actions",children:Pe?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:Sn,disabled:Mt,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Yt,disabled:Mt,children:Mt?"Saving…":"Save"})]}):t.jsxs(t.Fragment,{children:[e.column==="triage"&&e.status==="awaiting-approval"&&j.prompt&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:gi,children:"Approve Plan"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:ut,children:"Reject Plan"})]}),e.column==="triage"&&e.status!=="awaiting-approval"&&!R&&t.jsx("button",{className:"btn btn-sm btn-danger",onClick:$s,"aria-label":"Delete task",title:"Delete task",children:"Delete"}),(e.column!=="triage"||e.status==="awaiting-approval"||R||e.paused)&&t.jsxs("div",{className:"detail-actions-dropdown",ref:yt,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>{re(Z=>!Z),H(!1)},"aria-haspopup":"menu","aria-expanded":be,children:["Actions",t.jsx(Vt,{size:12})]}),be&&t.jsxs("div",{className:"detail-actions-menu",role:"menu",children:[t.jsx("button",{className:"detail-actions-menu-item detail-actions-menu-item-danger",role:"menuitem",onClick:()=>Ze($s),children:"Delete"}),d&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>Ze(Ls),children:"Duplicate"}),(e.column==="done"||e.column==="in-review")&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>Ze(ps),children:"Refine"}),t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>Ze(bn),children:"Respecify"}),R&&u&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>Ze(Ds),children:"Retry"}),e.column!=="done"&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>Ze(Ei),children:e.paused?"Unpause":"Pause"})]})]}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("div",{className:"detail-move-dropdown",ref:Ie,children:e.column==="in-review"?t.jsxs("div",{className:"detail-move-actions-in-review",children:[t.jsxs("div",{children:[t.jsxs("button",{ref:nt,className:"btn btn-primary btn-sm detail-move-btn",onClick:Mi,onKeyDown:$a,disabled:!Gn,"aria-label":Gn?`Move to ${An[Gn]}`:void 0,"aria-haspopup":_n?"menu":void 0,"aria-expanded":_n?Et:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",Gn?An[Gn]:""]}),_n&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(Vt,{size:12})})]}),Et&&_n&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:Qi,children:Ia.map(Z=>t.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>Ce(Z),onKeyDown:Qi,children:Z==="in-progress"?"Back to In Progress":`Move to ${An[Z]}`},Z))})]}),Da?t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!0,children:Da}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:xt,children:"Merge & Close"})]}):t.jsxs("div",{children:[t.jsxs("button",{ref:nt,className:"btn btn-primary btn-sm detail-move-btn",onClick:Mi,onKeyDown:$a,disabled:!Gn,"aria-label":Gn?`Move to ${An[Gn]}`:void 0,"aria-haspopup":_n?"menu":void 0,"aria-expanded":_n?Et:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",Gn?An[Gn]:""]}),_n&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(Vt,{size:12})})]}),Et&&_n&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:Qi,children:Ia.map(Z=>t.jsxs("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>Ce(Z),onKeyDown:Qi,children:["Move to ",An[Z]]},Z))})]})})]})}),De&&t.jsx("div",{className:"modal-overlay open detail-refine-overlay",onClick:ht,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal detail-refine-modal",onClick:Z=>Z.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{className:"detail-refine-title",children:"Refine"}),t.jsx("button",{className:"modal-close",onClick:ht,"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:Qe,onChange:Z=>Je(Z.target.value),placeholder:"Enter your feedback here...",rows:6,maxLength:2e3,autoFocus:!0}),t.jsxs("div",{className:"detail-refine-input-group",children:[t.jsxs("div",{className:"detail-refine-char-count",children:[Qe.length,"/2000 characters"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:xn,disabled:!Qe.trim()||Ke,children:Ke?"Creating...":"Create Refinement Task"})]})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:ht,disabled:Ke,children:"Cancel"})})]})})]})})}const dA=640;function uA({isOpen:e,onClose:n,onImport:s,tasks:i,projectId:r}){const[o,l]=a.useState(""),[c,u]=a.useState(""),[d,m]=a.useState(""),[h,g]=a.useState(!1),[p,f]=a.useState("issues"),[x,v]=a.useState([]),[b,y]=a.useState(null),[S,j]=a.useState([]),[R,k]=a.useState(null),[M,C]=a.useState(null),[L,A]=a.useState(!1),[P,O]=a.useState([]),[V,$]=a.useState(!1),[E,D]=a.useState(""),U=a.useRef(!1),Y=a.useRef(null);ni(Y,e,"fusion:github-modal-size");const X=Si(n),[_,I]=a.useState(!1),[T,w]=a.useState("list"),q=a.useRef(null),G=new Set;for(const pe of i){const _e=pe.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);_e&&G.add(_e[1]);const Fe=pe.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);Fe&&G.add(Fe[1])}a.useEffect(()=>{if(e)return l(""),u(""),m(""),v([]),y(null),j([]),k(null),f("issues"),C(null),A(!1),O([]),$(!0),D(""),q.current=null,U.current=!0,dy().then(pe=>{if(U.current)if(O(pe),$(!1),pe.length===1){const _e=pe[0];l(_e.owner),u(_e.repo),D(_e.name)}else pe.length>1&&(l(""),u(""),D(""))}).catch(()=>{U.current&&$(!1)}),()=>{U.current=!1}},[e]);const me=a.useCallback(pe=>{if(D(pe),pe==="")l(""),u("");else{const _e=P.find(Fe=>Fe.name===pe);_e&&(l(_e.owner),u(_e.repo))}},[P]),ue=a.useCallback(async()=>{if(!o.trim()||!c.trim()){C("Repository must be selected");return}g(!0),C(null),v([]),y(null);try{const pe=d.split(",").map(Fe=>Fe.trim()).filter(Boolean),_e=await ry(o.trim(),c.trim(),30,pe.length>0?pe:void 0);v(_e),_e.length===0&&C("No open issues found")}catch(pe){C(je(pe)||"Failed to fetch issues")}finally{g(!1)}},[o,c,d]),le=a.useCallback(async()=>{if(!o.trim()||!c.trim()){C("Repository must be selected");return}g(!0),C(null),j([]),k(null);try{const pe=await ly(o.trim(),c.trim(),30);j(pe),pe.length===0&&C("No open pull requests found")}catch(pe){C(je(pe)||"Failed to fetch pull requests")}finally{g(!1)}},[o,c]);a.useEffect(()=>{if(!e||!o.trim()||!c.trim()||h||L)return;const pe={owner:o.trim(),repo:c.trim(),labels:d.trim(),tab:p};q.current?.owner===pe.owner&&q.current?.repo===pe.repo&&q.current?.labels===pe.labels&&q.current?.tab===pe.tab||(q.current=pe,p==="issues"?ue():le())},[o,c,d,p,e,h,L,ue,le]),a.useEffect(()=>{if(!e)return;const pe=_e=>{_e.key==="Escape"&&n()};return document.addEventListener("keydown",pe),()=>document.removeEventListener("keydown",pe)},[e,n]),a.useEffect(()=>{if(!e)return;const pe=()=>{I(window.innerWidth<=dA)};return pe(),window.addEventListener("resize",pe),()=>window.removeEventListener("resize",pe)},[e]);const Se=a.useCallback(pe=>{y(pe),_&&w("preview")},[_]),F=a.useCallback(pe=>{k(pe),_&&w("preview")},[_]),ge=a.useCallback(()=>{w("list")},[]),se=a.useCallback(async()=>{if(p==="issues"){if(b===null)return;A(!0),C(null);try{const pe=await oy(o.trim(),c.trim(),b,r);s(pe),y(null),_&&T==="preview"&&w("list")}catch(pe){const _e=je(pe);_e?.includes("already imported")?C(_e):C(_e||"Failed to import issue")}finally{A(!1)}}else{if(R===null)return;A(!0),C(null);try{const pe=await cy(o.trim(),c.trim(),R,r);s(pe),k(null),_&&T==="preview"&&w("list")}catch(pe){const _e=je(pe);_e?.includes("already imported")?C(_e):C(_e||"Failed to import pull request")}finally{A(!1)}}},[p,b,R,o,c,s,_,T]),fe=x.find(pe=>pe.number===b),de=S.find(pe=>pe.number===R);if(!e)return null;const xe=P.length>0,ie=P.length===1,Ee=x.filter(pe=>G.has(pe.html_url)).length,De=S.filter(pe=>G.has(pe.html_url)).length,qe=M==="No open issues found",Qe=M==="No open pull requests found",Je=p==="issues"?qe:Qe,Ke=!!M&&!qe&&x.length===0&&!h,it=!!M&&!Qe&&S.length===0&&!h,Pe=p==="issues"?Ke:it,Ve=h||x.length>0||qe||Ke,ae=h||S.length>0||Qe||it,ye=p==="issues"?Ve:ae,te=!!M&&x.length>0&&!qe,Ae=!!M&&S.length>0&&!Qe,Le=p==="issues"?te:Ae;return t.jsx("div",{className:"modal-overlay open",...X,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg github-import-modal",ref:Y,children:[t.jsxs("div",{className:"modal-header github-import-modal__header",children:[t.jsxs("div",{children:[t.jsx("h3",{children:"Import from GitHub"}),t.jsx("p",{className:"github-import-modal__subtitle",children:"Choose a detected remote, load open issues or pull requests, and import one into the board."})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close import modal",children:"×"})]}),t.jsxs("div",{className:"modal-body github-import-modal__body",children:[t.jsxs("div",{className:"github-import-tabs",role:"tablist","aria-label":"Import type",children:[t.jsxs("button",{role:"tab","aria-selected":p==="issues","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="issues"?"active":""}`,onClick:()=>{f("issues"),k(null)},disabled:h||L,children:[t.jsx(Po,{size:16}),t.jsx("span",{children:"Issues"})]}),t.jsxs("button",{role:"tab","aria-selected":p==="pulls","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="pulls"?"active":""}`,onClick:()=>{f("pulls"),y(null)},disabled:h||L,children:[t.jsx(vs,{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:V?t.jsxs("div",{className:"github-import-toolbar__loading",role:"status","aria-live":"polite",children:[t.jsx(rt,{size:16,className:"spin"}),t.jsx("span",{children:"Detecting…"})]}):xe?ie?t.jsxs("div",{className:"github-import-remote-pill","data-testid":"github-import-single-remote",children:[t.jsx("span",{className:"github-import-remote-pill__name",children:P[0].name}),t.jsxs("span",{className:"github-import-remote-pill__repo",children:[P[0].owner,"/",P[0].repo]})]}):t.jsxs("div",{className:"github-import-remote-select",children:[t.jsx("label",{htmlFor:"gh-remote",className:"visually-hidden",children:"Repository"}),t.jsxs("select",{id:"gh-remote",value:E,onChange:pe=>me(pe.target.value),disabled:h||L,"aria-label":"Select Git remote",children:[t.jsx("option",{value:"",children:"Select remote…"}),P.map(pe=>t.jsxs("option",{value:pe.name,children:[pe.name," (",pe.owner,"/",pe.repo,")"]},pe.name))]})]}):t.jsx("span",{className:"github-import-toolbar__no-remote",children:"No remotes"})}),t.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--filter",children:p==="issues"?t.jsxs(t.Fragment,{children:[t.jsx("label",{htmlFor:"gh-labels",className:"visually-hidden",children:"Filter by labels"}),t.jsx("input",{id:"gh-labels",type:"text",placeholder:"Filter: bug,enhancement…",value:d,onChange:pe=>m(pe.target.value),onKeyDown:pe=>pe.key==="Enter"&&ue(),disabled:h||L||!xe,"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"?ue:le,disabled:h||L||!o.trim()||!c.trim(),"aria-label":h?`Loading ${p}`:`Load ${p} from repository`,title:h?"Loading…":`Load ${p}`,children:[h?t.jsx(rt,{size:14,className:"spin"}):t.jsx(En,{size:14}),t.jsx("span",{children:h?"Loading…":"Load"})]})})]}),!V&&!xe&&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 ${_?"mobile":""} ${T==="list"?"active":""}`,"data-testid":"github-import-list-pane","aria-labelledby":"github-import-results-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[t.jsx("h4",{id:"github-import-results-heading",children:p==="issues"?"Issues":"Pull Requests"}),p==="issues"&&x.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[x.length," issue",x.length===1?"":"s"]}),t.jsxs("span",{children:[Ee," imported"]})]}),p==="pulls"&&S.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[S.length," pull request",S.length===1?"":"s"]}),t.jsxs("span",{children:[De," imported"]})]})]}),t.jsxs("div",{className:"github-import-pane-content",children:[!ye&&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(rt,{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."})]})]}),Pe&&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})]})}),Je&&t.jsx("div",{className:"github-import-state github-import-state--empty",role:"status",children:t.jsxs("div",{children:[t.jsxs("strong",{children:["No open ",p==="issues"?"issues":"pull requests"," found"]}),t.jsx("span",{children:p==="issues"?"Try a different label filter or choose another repository.":"Choose another repository."})]})}),p==="issues"&&x.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:x.map(pe=>{const _e=G.has(pe.html_url);return t.jsxs("div",{className:`issue-item ${b===pe.number?"selected":""} ${_e?"imported":""}`,onClick:()=>!_e&&Se(pe.number),children:[t.jsx("input",{type:"radio",name:"issue",checked:b===pe.number,onChange:()=>Se(pe.number),disabled:_e,"aria-label":`Select issue #${pe.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",pe.number]}),t.jsx("span",{className:"issue-title",children:pe.title})]}),pe.labels.length>0&&t.jsx("span",{className:"issue-labels",children:pe.labels.map(Fe=>t.jsx("span",{className:"label-chip",children:Fe.name},Fe.name))})]}),_e&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},pe.number)})}),p==="pulls"&&S.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:S.map(pe=>{const _e=G.has(pe.html_url);return t.jsxs("div",{className:`issue-item ${R===pe.number?"selected":""} ${_e?"imported":""}`,onClick:()=>!_e&&F(pe.number),children:[t.jsx("input",{type:"radio",name:"pull",checked:R===pe.number,onChange:()=>F(pe.number),disabled:_e,"aria-label":`Select pull request #${pe.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",pe.number]}),t.jsx("span",{className:"issue-title",children:pe.title})]}),t.jsxs("span",{className:"pull-branch-info",children:[pe.headBranch," → ",pe.baseBranch]})]}),_e&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},pe.number)})})]})]}),t.jsxs("section",{className:`github-import-preview-pane ${_?"mobile":""} ${T==="preview"?"active":""}`,"data-testid":"github-import-preview-pane","aria-labelledby":"github-import-preview-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[_&&t.jsxs("button",{className:"github-import-back-button",onClick:ge,"data-testid":"github-import-back-button","aria-label":`Back to ${p==="issues"?"issues":"pull requests"} list`,children:[t.jsx(_a,{size:16}),t.jsx("span",{children:"Back"})]}),t.jsx("h4",{id:"github-import-preview-heading",children:"Preview"})]}),t.jsxs("div",{className:"github-import-pane-content",children:[p==="issues"&&fe?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Issue #",fe.number]}),t.jsx("div",{className:"preview-title",children:fe.title}),t.jsx("div",{className:"preview-body",children:fe.body?fe.body.slice(0,200)+(fe.body.length>200?"…":""):"(no description)"})]}):p==="issues"?t.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-preview-empty",children:t.jsxs("div",{children:[t.jsx("strong",{children:"No issue selected"}),t.jsx("span",{children:"Choose an issue from the list to inspect its title and description."})]})}):null,p==="pulls"&&de?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Pull Request #",de.number]}),t.jsx("div",{className:"preview-title",children:de.title}),t.jsxs("div",{className:"preview-branch",children:[t.jsx("strong",{children:"Branch:"})," ",de.headBranch," → ",de.baseBranch]}),t.jsx("div",{className:"preview-body",children:de.body?de.body.slice(0,200)+(de.body.length>200?"…":""):"(no description)"})]}):p==="pulls"?t.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-preview-empty",children:t.jsxs("div",{children:[t.jsx("strong",{children:"No pull request selected"}),t.jsx("span",{children:"Choose a pull request from the list to inspect its details."})]})}):null]})]})]})]}),t.jsxs("div",{className:"modal-actions github-import-modal__actions",children:[t.jsx("button",{className:"btn",onClick:n,disabled:L,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:se,disabled:(p==="issues"?b===null:R===null)||L,children:L?t.jsx(rt,{size:14,className:"spin"}):"Import"})]})]})})}const mA=["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 hA(e,n){return e&&n?`${e}/${n}`:""}function pA(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 fA({isOpen:e,onClose:n,onTaskCreated:s,onTasksCreated:i,tasks:r,initialPlan:o,projectId:l,resumeSessionId:c}){const[u,d]=a.useState(""),[m,h]=a.useState({type:"initial"}),[g,p]=a.useState(null),[f,x]=a.useState([]),[v,b]=a.useState([]),[y,S]=a.useState(null),j=a.useRef(!1),R=a.useRef(!1),[k,M]=a.useState(""),[C,L]=a.useState(!0),[A,P]=a.useState(!1),[O,V]=a.useState(!1),[$,E]=a.useState(null),[D,U]=a.useState(0),Y=a.useRef(null),X=a.useRef(null),_=a.useRef(null),I=a.useRef(null),[T,w]=a.useState(c??null),q=a.useMemo(()=>Ji(),[]),{isLockedByOther:G,takeControl:me,isLoading:ue}=Wo(e?T:null),{activeTabMap:le,broadcastUpdate:Se,broadcastCompleted:F,broadcastLock:ge,broadcastUnlock:se,broadcastHeartbeat:fe}=Ra(),[de,xe]=a.useState(void 0),[ie,Ee]=a.useState(void 0),[De,qe]=a.useState([]),[Qe,Je]=a.useState(!1),[Ke,it]=a.useState(null),[Pe,Ve]=a.useState([]),[ae,ye]=a.useState([]),te=a.useRef(null),[Ae,Le]=a.useState([]),[pe,_e]=a.useState(!1),[Fe,tt]=a.useState(c??null),[Ne,oe]=a.useState(!!c),[Te,he]=a.useState(null),Me=a.useRef(!1),We=a.useRef(null);ni(X,e,"fusion:planning-modal-size"),a.useEffect(()=>{const H=We.current;if(!H)return;H.scrollHeight-H.scrollTop-H.clientHeight<32&&(H.scrollTop=H.scrollHeight)},[k]),a.useEffect(()=>{if(m.type!=="loading"){E(null),U(0);return}const H=Date.now();E(H),U(0);const be=setInterval(()=>{U(Math.max(0,Math.floor((Date.now()-H)/1e3)))},1e3);return()=>clearInterval(be)},[m.type]);const Re=a.useCallback(()=>{d(""),h({type:"initial"}),p(null),x([]),b([]),S(null),M(""),P(!1),V(!1),xe(void 0),Ee(void 0),I.current=null,w(null)},[]),ot=hA(de,ie),J=a.useCallback((H,be)=>{if(!H||!be)return"Using default";const re=De.find(N=>N.provider===H&&N.id===be);return re?`${re.provider}/${re.id}`:`${H}/${be}`},[De]),ce=a.useCallback(async()=>{Je(!0),it(null);try{const H=await ms();qe(H.models),Ve(H.favoriteProviders),ye(H.favoriteModels)}catch(H){it(je(H)||"Failed to load models")}finally{Je(!1)}},[]),ve=a.useCallback(H=>{Ve(be=>{const re=be,W=re.includes(H)?re.filter(Ie=>Ie!==H):[H,...re];return ln({favoriteProviders:W,favoriteModels:ae}).catch(()=>{Ve(re)}),W})},[ae]),Xe=a.useCallback(H=>{ye(be=>{const re=be,W=re.includes(H)?re.filter(Ie=>Ie!==H):[H,...re];return ln({favoriteProviders:Pe,favoriteModels:W}).catch(()=>{ye(re)}),W})},[Pe]),ee=a.useCallback(H=>{_.current?.close();const be=cj(H,l,{onThinking:re=>{M(N=>N+re),Se({sessionId:H,status:"generating",needsInput:!1,owningTabId:q,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onQuestion:re=>{P(!1),V(!1),ia(l),h({type:"question",session:{sessionId:H,currentQuestion:re,summary:null}}),M(""),Se({sessionId:H,status:"awaiting_input",needsInput:!0,owningTabId:q,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onSummary:re=>{P(!1),V(!1),ia(l),h({type:"summary",session:{sessionId:H,currentQuestion:null,summary:re},summary:re}),S(re),M(""),Se({sessionId:H,status:"complete",needsInput:!1,owningTabId:q,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onError:re=>{const N=re||"Session failed while contacting the AI.";P(!0),(async()=>{try{const W=await di(H);if(W&&(W.status==="generating"||W.status==="awaiting_input")){ee(H);return}}catch{}P(!1),V(!1),p(null),h(W=>W.type==="question"||W.type==="summary"||W.type==="error"?{type:"error",session:W.session,errorMessage:N}:{type:"error",session:{sessionId:H,currentQuestion:null,summary:null},errorMessage:N}),M(""),I.current=H,Se({sessionId:H,status:"error",needsInput:!1,owningTabId:q,type:"planning",title:u.trim()||"Planning session",projectId:l??null}),F({sessionId:H,status:"error"})})()},onComplete:()=>{P(!1),V(!1),I.current=null,F({sessionId:H,status:"complete"})},onConnectionStateChange:re=>{P(re==="reconnecting")}});_.current=be},[F,Se,u,l,q]),Ge=a.useCallback(async H=>{const be=H??u;if(be.trim()){p(null),M(""),b([]),x([]),P(!1),h({type:"loading"});try{const re=de&&ie?{planningModelProvider:de,planningModelId:ie}:void 0,{sessionId:N}=await Wy(be.trim(),l,re);I.current=N,w(N),tt(N),ee(N),x([])}catch(re){P(!1),p(je(re)||"Failed to start planning session"),h({type:"initial"}),I.current=null,w(null)}}},[ee,u,ie,de,l]);a.useEffect(()=>{e&&m.type==="initial"&&Y.current?.focus()},[e,m.type]),a.useEffect(()=>{e&&ce()},[e,ce]),a.useEffect(()=>{if(e&&o&&!j.current&&m.type==="initial"){d(o);const H=setTimeout(()=>{j.current=!0,Ge(o)},0);return()=>clearTimeout(H)}else if(e&&!o&&!j.current&&!R.current&&m.type==="initial"){R.current=!0;const H=r1(l);H&&d(H)}},[e,o,m.type,Ge,l]);const ct=a.useCallback(async H=>{_.current?.close(),_.current=null,p(null),M(""),x([]),b([]),S(null),V(!1),h({type:"loading"});try{const be=await di(H);if(!be){tt(null),oe(!1),h({type:"initial"});return}I.current=H,w(H);const re=ya(be.conversationHistory);if(b(re),x(re.map(N=>N.response).filter(N=>!!(N&&typeof N=="object"&&!Array.isArray(N)))),be.status==="awaiting_input"&&be.currentQuestion){ia(l);const N=JSON.parse(be.currentQuestion);h({type:"question",session:{sessionId:H,currentQuestion:N,summary:null}}),be.thinkingOutput&&M(be.thinkingOutput),ee(H)}else if(be.status==="complete"&&be.result){ia(l);const N=JSON.parse(be.result);h({type:"summary",session:{sessionId:H,currentQuestion:null,summary:N},summary:N}),S(N)}else be.status==="generating"?(h({type:"loading"}),be.thinkingOutput&&M(be.thinkingOutput),ee(H)):be.status==="error"&&h({type:"error",session:{sessionId:H,currentQuestion:null,summary:null},errorMessage:be.error||"Session failed"})}catch{p("Failed to load session"),h({type:"initial"})}},[ee,l]);a.useEffect(()=>{!e||!c||I.current!==c&&(tt(c),oe(!0),ct(c))},[e,c,ct]),a.useEffect(()=>{e&&Fe&&(c&&c===Fe||_.current?.isConnected()||ct(Fe))},[e]);const vt=a.useCallback(async()=>{_e(!0);try{const be=(await td(l)).filter(re=>re.type==="planning").sort((re,N)=>Date.parse(N.updatedAt)-Date.parse(re.updatedAt));Le(be)}catch{}finally{_e(!1)}},[l]);a.useEffect(()=>{e&&vt()},[e,vt]),a.useEffect(()=>{if(!e)return;const H=l?`?projectId=${encodeURIComponent(l)}`:"",be=N=>{try{const W=JSON.parse(N.data);if(W.type!=="planning")return;Le(Ie=>{const nt=Ie.findIndex(Pt=>Pt.id===W.id);return(nt>=0?[...Ie.slice(0,nt),W,...Ie.slice(nt+1)]:[W,...Ie]).sort((Pt,Tt)=>Date.parse(Tt.updatedAt)-Date.parse(Pt.updatedAt))})}catch{}},re=N=>{try{const W=JSON.parse(N.data);Le(Ie=>Ie.filter(nt=>nt.id!==W))}catch{}};return qs(`/api/events${H}`,{events:{"ai_session:updated":be,"ai_session:deleted":re},onReconnect:()=>{vt()}})},[e,l,vt]);const bt=a.useCallback(H=>{if(Fe===H){oe(!0);return}tt(H),oe(!0),ct(H)},[ct,Fe]),ft=a.useCallback(()=>{_.current?.close(),_.current=null,Re(),tt(null),oe(!0)},[Re]),gt=a.useCallback(()=>{oe(!1)},[]),_t=a.useCallback(async H=>{const be=N=>N==="generating"||N==="awaiting_input",re=Ae.find(N=>N.id===H);if(re&&be(re.status))try{await rp(H,l,q)}catch{}try{await fp(H)}catch{}F({sessionId:H,status:"complete",timestamp:Date.now()}),Le(N=>N.filter(W=>W.id!==H)),Fe===H&&(_.current?.close(),_.current=null,Re(),tt(null),oe(!1)),he(null)},[F,Ae,l,Re,Fe,q]);a.useEffect(()=>{e||(j.current=!1,R.current=!1,P(!1),V(!1),w(null))},[e]),a.useEffect(()=>{if(!e){te.current&&(se(te.current,q),te.current=null);return}if(T&&te.current!==T){te.current&&se(te.current,q),ge(T,q),te.current=T;return}!T&&te.current&&(se(te.current,q),te.current=null)},[ge,se,e,T,q]),a.useEffect(()=>{if(!e||!T||te.current!==T)return;fe(q);const H=setInterval(()=>{fe(q)},3e4);return()=>{clearInterval(H)}},[fe,e,T,q]),a.useEffect(()=>()=>{_.current?.close(),_.current=null,te.current&&(se(te.current,q),te.current=null)},[se,q]),a.useEffect(()=>{if(!e)return;const H=()=>{_.current?.close(),_.current=null};return window.addEventListener("beforeunload",H),()=>window.removeEventListener("beforeunload",H)},[e]);const Rt=a.useCallback(()=>{u&&m.type==="initial"&&a1(u,l),_.current?.close(),_.current=null,P(!1),V(!1),n()},[u,n,l,m.type]);a.useEffect(()=>{if(!e)return;const H=be=>{be.key==="Escape"&&Rt()};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[e,Rt]);const Ft=a.useCallback(async H=>{if(m.type!=="question")return;const{session:be}=m,re=be.sessionId,N=be.currentQuestion;if(!N){p("No active question in session");return}p(null),x(W=>[...W,H]),b(W=>[...W,{question:N,response:H}]),h({type:"loading"}),M("");try{await Ky(re,H,l,q)}catch(W){p(je(W)||"Failed to submit response"),h({type:"question",session:be})}},[l,q,m]),wt=a.useCallback(async()=>{const H=I.current;if(H){try{await Jy(H,l,q)}catch{}_.current?.close(),_.current=null,P(!1),V(!1),h({type:"error",session:{sessionId:H,currentQuestion:null,summary:null},errorMessage:"Generation stopped by user. You can retry or start a new session."}),M("")}},[l,q]),At=a.useCallback(async()=>{if(m.type!=="error")return;const H=m.session;p(null),V(!0),M(""),h({type:"loading"}),ee(H.sessionId);try{I.current=H.sessionId,w(H.sessionId),await Gy(H.sessionId,l,q)}catch(be){let re=be;if((je(be)||"").includes("not in an error state"))try{const W=await di(H.sessionId);if(!W)throw new Error("Failed to refresh planning session.");if(I.current=W.id,w(W.id),W.status==="generating")M(W.thinkingOutput??""),h({type:"loading"});else if(W.status==="awaiting_input"){if(!W.currentQuestion)throw new Error("Planning session is awaiting input but has no current question.");const Ie=JSON.parse(W.currentQuestion);ia(l),h({type:"question",session:{sessionId:W.id,currentQuestion:Ie,summary:null}}),_.current?.isConnected()||ee(W.id)}else if(W.status==="complete"){if(!W.result)throw new Error("Planning session is complete but has no result.");const Ie=JSON.parse(W.result);ia(l),h({type:"summary",session:{sessionId:W.id,currentQuestion:null,summary:Ie},summary:Ie}),S(Ie)}else W.status==="error"&&h({type:"error",session:{sessionId:W.id,currentQuestion:null,summary:null},errorMessage:W.error||"Retry failed. Please try again."});P(!1);return}catch(W){re=W}_.current?.close(),_.current=null,h({type:"error",session:H,errorMessage:je(re)||"Retry failed. Please try again."}),P(!1)}finally{V(!1)}},[ee,l,q,m]),qt=a.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const H=m.session.sessionId,be=await Yy(H,y??void 0,l);s(be),tt(null),Le(re=>re.filter(N=>N.id!==H)),F({sessionId:H,status:"complete",timestamp:Date.now()}),Rt()}catch(H){p(je(H)||"Failed to create task"),h({type:"summary",session:m.session,summary:m.summary})}}},[F,y,m,l,s,Rt]),zt=a.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const H=await Qy(m.session.sessionId,y??void 0,l);w(H.sessionId),h({type:"breakdown",sessionId:H.sessionId,subtasks:H.subtasks,dirty:!1})}catch(H){p(je(H)||"Failed to start breakdown"),h({type:"summary",session:m.session,summary:m.summary})}}},[y,m,l]),Wt=a.useCallback(async()=>{if(m.type==="breakdown"){p(null),h({type:"creating"});try{const H=m.sessionId,be=await Xy(H,m.subtasks,l);i(be.tasks),Le(re=>re.filter(N=>N.id!==H)),F({sessionId:H,status:"complete",timestamp:Date.now()}),d(""),h({type:"initial"}),p(null),x([]),b([]),S(null),M(""),xe(void 0),Ee(void 0),I.current=null,w(null),tt(null),n()}catch(H){p(je(H)||"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"&&f.length>0){const H=f.slice(0,-1);x(H),h({type:"question",session:m.session})}},[m,f]),Nt=()=>m.type==="question"?Math.min(f.length+1,3):3,Mt=T?le.get(T):null,Ct=Mt&&Mt.tabId!==q,Gt=!!(Ct&&!Mt.stale),Et=G&&(!Ct||Mt.stale);return e?t.jsx("div",{className:"modal-overlay open",onMouseDown:H=>{Me.current=H.target===H.currentTarget},onClick:H=>{H.target===H.currentTarget&&Me.current&&Rt(),Me.current=!1},role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",ref:X,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[Ne&&t.jsx("button",{className:"modal-back planning-mobile-back",onClick:gt,"aria-label":"Back to sessions",title:"Back to sessions",children:t.jsx(To,{size:18})}),t.jsx(ei,{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(Ut,{size:20})})})]}),t.jsxs("div",{className:`planning-modal-body planning-modal-body--split ${Ne?"planning-modal-body--show-detail":"planning-modal-body--show-list"}`,children:[t.jsx(yA,{sessions:Ae,loading:pe,selectedSessionId:Fe,pendingDeleteId:Te,onSelectSession:bt,onNewSession:ft,onRequestDelete:he,onConfirmDelete:H=>void _t(H),onCancelDelete:()=>he(null)}),t.jsxs("div",{className:"planning-detail",children:[g&&t.jsx("div",{className:"form-error planning-error",children:g}),A&&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(Xn,{size:32,className:"icon-triage-lg"}),t.jsx("h4",{children:"Transform your idea into a detailed task"}),t.jsx("p",{className:"text-muted",children:"Describe what you want to build in plain language. The AI will ask clarifying questions and help you structure a well-defined task."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"initial-plan",children:"What do you want to build?"}),t.jsx("textarea",{ref:Y,id:"initial-plan",rows:4,className:"planning-textarea",placeholder:"e.g., Build a user authentication system with login, signup, and password reset...",value:u,onChange:H=>d(H.target.value),onKeyDown:H=>{H.key==="Enter"&&!H.shiftKey&&u.trim()&&(H.preventDefault(),Ge())}})]}),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:mA.map((H,be)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>d(H),children:H.length>40?H.slice(0,40)+"...":H},be))})]}),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(Hn,{id:"planning-modal-model",label:"Planning Model",value:ot,onChange:H=>{const{provider:be,modelId:re}=pA(H);xe(be),Ee(re)},models:De,disabled:Qe,favoriteProviders:Pe,onToggleFavorite:ve,favoriteModels:ae,onToggleModelFavorite:Xe}),Ke&&t.jsxs("div",{className:"form-hint form-hint-error",children:[Ke," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{ce()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${de&&ie?"model-badge-custom":"model-badge-default"}`,children:J(de,ie)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>Ge(),disabled:!u.trim(),children:[t.jsx(ei,{size:16,className:"icon-mr-8"}),"Start Planning"]})})]}),m.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(rt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:k?"AI is thinking...":"Generating next question..."}),$&&t.jsxs("div",{className:"planning-elapsed",children:["Thinking… (",D,"s)"]}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>L(!C),type:"button",children:C?"Hide thinking":"Show thinking"}),t.jsx("div",{className:"planning-loading-actions",children:t.jsxs("button",{className:"btn planning-stop-btn",type:"button",onClick:()=>void wt(),children:[t.jsx(Qg,{size:14}),t.jsx("span",{className:"icon-ml-6",children:"Stop"})]})}),C&&k&&t.jsx("div",{className:"planning-thinking-output",ref:We,children:t.jsx("pre",{children:k})})]})]}),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(Is,{entries:v}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:m.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void At(),disabled:O,children:[O?t.jsx(rt,{size:14,className:"spin"}):t.jsx(En,{size:14}),t.jsx("span",{className:"icon-ml-6",children:O?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Rt,disabled:O,children:"Dismiss"})]})]})]})}),m.type==="creating"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(rt,{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(gA,{question:m.session.currentQuestion,progress:Nt(),historyEntries:v,onSubmit:Ft,onBack:f.length>0?Ot:void 0})}),m.type==="summary"&&y&&t.jsx(xA,{summary:y,historyEntries:v,onSummaryChange:S,tasks:r,onCreateTask:qt,onBreakIntoTasks:zt,onRefine:()=>{h({type:"question",session:m.session})},isLoading:!1}),m.type==="breakdown"&&t.jsx(vA,{subtasks:m.subtasks,dirty:m.dirty,isLoading:!1,onUpdateSubtasks:H=>h({...m,subtasks:H,dirty:!0}),onCreateTasks:Wt,onBack:()=>{const be={sessionId:m.sessionId,currentQuestion:null,summary:y??null};y&&h({type:"summary",session:be,summary:y})}})]}),G&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Do,{size:16}),t.jsx("span",{children:Et?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),Et&&t.jsx("button",{type:"button",onClick:()=>{me()},disabled:ue,className:"btn btn-primary session-lock-take-control",children:ue?"Taking control...":"Take Control"})]})})]})]})}):null}function gA({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(Is,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3].map(h=>t.jsx("div",{className:`planning-progress-step ${h<=n?"active":""}`},h))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~3"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:c,onChange:h=>u(h.target.value),onKeyDown:h=>{h.key==="Enter"&&!h.shiftKey&&c.trim()&&(h.preventDefault(),d())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(h=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:h.id,checked:o[e.id]===h.id,onChange:()=>l({[e.id]:h.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:h.label}),h.description&&t.jsx("span",{className:"planning-option-desc",children:h.description})]})]},h.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(h=>{const g=o[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:h.id,checked:g.includes(h.id),onChange:p=>{const f=p.target.checked?[...g,h.id]:g.filter(x=>x!==h.id);l({[e.id]:f})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:h.label}),h.description&&t.jsx("span",{className:"planning-option-desc",children:h.description})]})]},h.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!0?"selected":""}`,onClick:()=>l({[e.id]:!0}),children:[t.jsx(fn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!1?"selected":""}`,onClick:()=>l({[e.id]:!1}),children:[t.jsx(Ut,{size:18}),"No"]})]})]})]})]})]}),t.jsxs("div",{className:"planning-actions",children:[r&&t.jsxs("button",{className:"btn",onClick:r,children:[t.jsx(_a,{size:16,className:"icon-mr-4"}),"Back"]}),t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:d,disabled:!m(),children:["Continue",t.jsx(Nr,{size:16,className:"icon-ml-4"})]})]})]})}function xA({summary:e,historyEntries:n,onSummaryChange:s,tasks:i,onCreateTask:r,onBreakIntoTasks:o,onRefine:l,isLoading:c}){const[u,d]=a.useState(!1),[m,h]=a.useState(e.suggestedDependencies),g=p=>{const f=m.includes(p)?m.filter(x=>x!==p):[...m,p];h(f),s({...e,suggestedDependencies:f})};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Is,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(fn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Planning Complete!"}),t.jsx("p",{className:"text-muted",children:"Review and refine your task before creating it."})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{children:["Description",t.jsx("button",{type:"button",className:"planning-expand-btn",onClick:()=>d(!u),children:u?"Collapse":"Expand"})]}),t.jsx("textarea",{className:`planning-textarea ${u?"expanded":""}`,rows:u?10:4,value:e.description,onChange:p=>s({...e,description:p.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Suggested Size"}),t.jsxs("select",{className:"planning-size-select",value:e.suggestedSize,onChange:p=>s({...e,suggestedSize:p.target.value}),disabled:c,children:[t.jsx("option",{value:"S",children:"S (Small)"}),t.jsx("option",{value:"M",children:"M (Medium)"}),t.jsx("option",{value:"L",children:"L (Large)"})]})]}),i.length>0&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Suggested Dependencies"}),t.jsx("div",{className:"planning-deps-list",children:i.map(p=>t.jsxs("label",{className:`planning-dep-chip ${m.includes(p.id)?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:m.includes(p.id),onChange:()=>g(p.id)}),t.jsx("span",{className:"planning-dep-id",children:p.id}),t.jsx("span",{className:"planning-dep-title",children:p.title||p.description.slice(0,30)})]},p.id))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Key Deliverables"}),t.jsx("ul",{className:"planning-deliverables",children:e.keyDeliverables.map((p,f)=>t.jsx("li",{children:p},f))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:l,disabled:c,children:[t.jsx(_a,{size:16,className:"icon-mr-4"}),"Refine Further"]}),t.jsxs("div",{className:"planning-summary-actions-right",children:[t.jsx("button",{className:"btn",onClick:o,disabled:c,title:"Break the plan into multiple tasks with dependencies",children:c?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:16,className:"spin icon-mr-8"}),"Breaking down..."]}):t.jsxs(t.Fragment,{children:[t.jsx($o,{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(rt,{size:16,className:"spin icon-mr-8"}),"Creating..."]}):t.jsxs(t.Fragment,{children:[t.jsx(fn,{size:16,className:"icon-mr-8"}),"Create Task"]})})]})]})]})}function Zm(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 bA(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function vA({subtasks:e,dirty:n,isLoading:s,onUpdateSubtasks:i,onCreateTasks:r,onBack:o}){const[l,c]=a.useState(null),[u,d]=a.useState(null),[m,h]=a.useState(null),g=a.useRef([]),p=a.useMemo(()=>e.length===0||e.some(M=>!M.title.trim())?!0:Zm(e),[e]),f=a.useCallback((M,C)=>{i(e.map(L=>L.id===M?{...L,...C}:L))},[e,i]),x=a.useCallback(()=>{i([...e,bA(e.length+1)])},[e,i]),v=a.useCallback(M=>{i(e.filter(C=>C.id!==M).map(C=>({...C,dependsOn:C.dependsOn.filter(L=>L!==M)})))},[e,i]),b=a.useCallback((M,C)=>{if(C<0||C>=e.length)return;const L=[...e],[A]=L.splice(M,1);L.splice(C,0,A),i(L)},[e,i]),y=a.useCallback(M=>C=>{c(M),C.dataTransfer.setData("text/plain",M),C.dataTransfer.effectAllowed="move"},[]),S=a.useCallback(()=>{c(null),d(null),h(null)},[]),j=a.useCallback(M=>C=>{if(C.preventDefault(),M===l)return;const L=C.currentTarget.getBoundingClientRect(),A=L.top+L.height/2,P=C.clientY<A?"before":"after";d(M),h(P)},[l]),R=a.useCallback(M=>C=>{C.preventDefault();const L=C.dataTransfer.getData("text/plain");if(!L||L===M){S();return}const A=e.findIndex(E=>E.id===L),P=e.findIndex(E=>E.id===M);if(A===-1||P===-1){S();return}const O=[...e],[V]=O.splice(A,1);let $=P;m==="after"&&A<P&&$--,m==="after"&&$++,O.splice($,0,V),i(O),S()},[e,m,i,S]),k=a.useCallback(M=>{const C=M.currentTarget.getBoundingClientRect(),L=M.clientX,A=M.clientY;(L<C.left||L>C.right||A<C.top||A>C.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($o,{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,C)=>{const L=l===M.id,A=u===M.id,P=["task-detail-section","subtask-item",L?"subtask-item-dragging":"",A?"subtask-item-drop-target":"",A&&m==="before"?"subtask-item-drop-before":"",A&&m==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:P,"data-testid":`subtask-item-${C}`,draggable:!s,onDragStart:y(M.id),onDragEnd:S,onDragOver:j(M.id),onDrop:R(M.id),onDragLeave:k,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(Qc,{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:()=>b(C,C-1),disabled:s||C===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(Fi,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>b(C,C+1),disabled:s||C===e.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(wr,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>v(M.id),disabled:s,children:[t.jsx(Zt,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:O=>{g.current[C]=O},value:M.title,onChange:O=>f(M.id,{title:O.target.value}),onKeyDown:O=>{O.key==="Enter"&&(O.preventDefault(),C<e.length-1&&g.current[C+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:O=>f(M.id,{description:O.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:O=>f(M.id,{suggestedSize:O.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,C).filter(O=>O.id!==M.id).map(O=>{const V=M.dependsOn.includes(O.id);return t.jsxs("label",{className:`planning-dep-chip ${V?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:V,onChange:()=>{const $=V?M.dependsOn.filter(E=>E!==O.id):[...M.dependsOn,O.id];f(M.id,{dependsOn:$})},disabled:s}),t.jsx("span",{className:"planning-dep-id",children:O.id}),t.jsx("span",{className:"planning-dep-title",children:O.title||"Untitled"})]},O.id)}),C===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),C>0&&e.slice(0,C).filter(O=>O.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:x,disabled:s,children:[t.jsx(en,{size:16,className:"icon-mr-6"})," Add subtask"]}),Zm(e)&&t.jsx("div",{className:"form-error planning-error",children:"Dependencies contain a cycle. Remove circular references before creating tasks."})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:o,disabled:s,children:[t.jsx(_a,{size:16,className:"icon-mr-4"}),"Back to Summary"]}),t.jsx("button",{className:"btn btn-primary",onClick:r,disabled:s||p,children:s?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]})}function yA({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(db,{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(jA,{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(kA,{status:d.status}),t.jsx("span",{"aria-hidden":!0,children:" · "}),t.jsx("span",{children:wA(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:g=>{g.stopPropagation(),l(d.id)},"aria-label":"Delete session",title:"Delete session",children:t.jsx(Zt,{size:14})})]},d.id)})]})]})}function jA({status:e}){switch(e){case"generating":return t.jsx(rt,{size:14,className:"spin planning-sidebar-status-icon planning-sidebar-status-generating"});case"awaiting_input":return t.jsx(pc,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-awaiting"});case"complete":return t.jsx(fn,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-complete"});case"error":return t.jsx(as,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-error"});default:return t.jsx(wi,{size:14,className:"planning-sidebar-status-icon"})}}function kA({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 wA(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 NA(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function eh(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 SA({isOpen:e,onClose:n,initialDescription:s,onTasksCreated:i,parentTaskId:r,projectId:o,resumeSessionId:l}){const[c,u]=a.useState({type:"initial"}),[d,m]=a.useState([]),[h,g]=a.useState([]),[p,f]=a.useState(""),[x,v]=a.useState(!0),[b,y]=a.useState(!1),[S,j]=a.useState(!1),[R,k]=a.useState(s),[M,C]=a.useState(null),[L,A]=a.useState(!1),[P,O]=a.useState(null),[V,$]=a.useState(null),[E,D]=a.useState(null),U=a.useRef(null),Y=a.useRef([]),X=a.useRef(!1),_=a.useRef(null),I=c.type==="generating"||c.type==="editing"||c.type==="creating"||c.type==="error"?c.sessionId:null,T=a.useMemo(()=>Ji(),[]),{isLockedByOther:w,takeControl:q,isLoading:G}=Wo(e?I:null),{activeTabMap:me,broadcastUpdate:ue,broadcastCompleted:le,broadcastLock:Se,broadcastUnlock:F,broadcastHeartbeat:ge}=Ra(),se=a.useMemo(()=>d.length===0||d.some(oe=>!oe.title.trim())?!0:eh(d),[d]),fe=c.type==="generating"||c.type==="editing"||c.type==="error",de=I?me.get(I):null,{confirm:xe}=Hs(),ie=de&&de.tabId!==T,Ee=!!(ie&&!de.stale),De=w&&(!ie||de.stale),qe=a.useCallback(()=>{R&&o1(R,o),U.current?.close(),U.current=null,u({type:"initial"}),m([]),g([]),f(""),v(!0),y(!1),j(!1),C(null),A(!1),X.current=!1},[R,o]),Qe=a.useCallback(()=>{U.current?.close(),U.current=null,n()},[n]),Je=a.useCallback(async()=>{if(!((L||c.type==="editing"||c.type==="creating")&&!await xe({title:"Discard Changes",message:"Close subtask breakdown? Unsaved changes will be lost.",danger:!0}))){if(I)try{await cp(I,o,T)}catch{}qe(),n()}},[L,n,qe,I,T,c.type,o,xe]),Ke=a.useCallback(oe=>{U.current?.close(),U.current=Sj(oe,o,{onThinking:Te=>{f(he=>he+Te),ue({sessionId:oe,status:"generating",needsInput:!1,owningTabId:T,type:"subtask",title:R.trim()||"Subtask breakdown",projectId:o??null})},onSubtasks:Te=>{y(!1),j(!1),yl(o),m(Te),u({type:"editing",sessionId:oe}),A(!1),ue({sessionId:oe,status:"awaiting_input",needsInput:!0,owningTabId:T,type:"subtask",title:R.trim()||"Subtask breakdown",projectId:o??null})},onError:Te=>{const he=Te||"Session failed while contacting the AI.";y(!1),j(!1),C(null),u({type:"error",sessionId:oe,errorMessage:he}),ue({sessionId:oe,status:"error",needsInput:!1,owningTabId:T,type:"subtask",title:R.trim()||"Subtask breakdown",projectId:o??null}),le({sessionId:oe,status:"error"})},onComplete:()=>{le({sessionId:oe,status:"complete"})},onConnectionStateChange:Te=>{y(Te==="reconnecting")}})},[le,ue,R,o,T]),it=a.useCallback(async()=>{if(R.trim()){C(null),g([]),f(""),y(!1);try{const{sessionId:oe}=await kj(R.trim(),o);u({type:"generating",sessionId:oe}),Ke(oe)}catch(oe){C(je(oe)||"Failed to start subtask breakdown"),u({type:"initial"})}}},[Ke,R,o]);a.useEffect(()=>{if(!e){qe();return}if(e&&s&&!X.current)k(s),X.current=!0,it();else if(e&&!s&&!X.current){const oe=l1(o);oe&&k(oe)}},[e,s,it,qe]),a.useEffect(()=>{!e||!l||c.type!=="initial"||(async()=>{try{const oe=await di(l);if(!oe)return;const Te=ya(oe.conversationHistory);if(g(Te),oe.status==="generating"||oe.status==="awaiting_input")f(oe.thinkingOutput??""),u({type:"generating",sessionId:l}),Ke(l);else if(oe.status==="complete"&&oe.result){yl(o);const he=JSON.parse(oe.result);m(he),u({type:"editing",sessionId:l})}else oe.status==="error"&&(C(null),u({type:"error",sessionId:l,errorMessage:oe.error??"Session encountered an error"}))}catch(oe){C(je(oe)||"Failed to resume session")}})()},[Ke,e,l,c.type,o]),a.useEffect(()=>{if(!e){_.current&&(F(_.current,T),_.current=null);return}if(I&&_.current!==I){_.current&&F(_.current,T),Se(I,T),_.current=I;return}!I&&_.current&&(F(_.current,T),_.current=null)},[Se,F,e,I,T]),a.useEffect(()=>{if(!e||!I||_.current!==I)return;ge(T);const oe=setInterval(()=>{ge(T)},3e4);return()=>{clearInterval(oe)}},[ge,e,I,T]),a.useEffect(()=>()=>{U.current?.close(),_.current&&(F(_.current,T),_.current=null)},[F,T]),a.useEffect(()=>{if(!e)return;const oe=Te=>{Te.key==="Escape"&&(Te.preventDefault(),Je())};return document.addEventListener("keydown",oe),()=>document.removeEventListener("keydown",oe)},[e,Je]);const Pe=a.useCallback((oe,Te)=>{m(he=>he.map(Me=>Me.id===oe?{...Me,...Te}:Me)),A(!0)},[]),Ve=a.useCallback(()=>{m(oe=>[...oe,NA(oe.length+1)]),A(!0)},[]),ae=a.useCallback(oe=>{m(Te=>Te.filter(he=>he.id!==oe).map(he=>({...he,dependsOn:he.dependsOn.filter(Me=>Me!==oe)}))),A(!0)},[]),ye=a.useCallback(oe=>Te=>{O(oe),Te.dataTransfer.setData("text/plain",oe),Te.dataTransfer.effectAllowed="move"},[]),te=a.useCallback(()=>{O(null),$(null),D(null)},[]),Ae=a.useCallback(oe=>Te=>{if(Te.preventDefault(),oe===P)return;const he=Te.currentTarget.getBoundingClientRect(),Me=he.top+he.height/2,We=Te.clientY<Me?"before":"after";$(oe),D(We)},[P]),Le=a.useCallback(oe=>Te=>{Te.preventDefault();const he=Te.dataTransfer.getData("text/plain");if(!he||he===oe){O(null),$(null),D(null);return}m(Me=>{const We=Me.findIndex(ve=>ve.id===he),Re=Me.findIndex(ve=>ve.id===oe);if(We===-1||Re===-1)return Me;const ot=[...Me],[J]=ot.splice(We,1);let ce=Re;return E==="after"&&We<Re&&ce--,E==="after"&&ce++,ot.splice(ce,0,J),ot}),A(!0),O(null),$(null),D(null)},[E]),pe=a.useCallback(oe=>{const Te=oe.currentTarget.getBoundingClientRect(),he=oe.clientX,Me=oe.clientY;(he<Te.left||he>Te.right||Me<Te.top||Me>Te.bottom)&&($(null),D(null))},[]),_e=a.useCallback((oe,Te)=>{Te<0||Te>=d.length||(m(he=>{const Me=[...he],[We]=Me.splice(oe,1);return Me.splice(Te,0,We),Me}),A(!0))},[d.length]),Fe=a.useCallback(oe=>{Y.current[oe+1]?.focus()},[]),tt=a.useCallback(async()=>{if(!(!I||se)){C(null),u({type:"creating",sessionId:I});try{const oe=await Cj(I,d,r,o);i(oe.tasks),qe(),n()}catch(oe){C(je(oe)||"Failed to create tasks"),u({type:"editing",sessionId:I})}}},[se,n,i,r,o,qe,I,d]),Ne=a.useCallback(async()=>{if(c.type!=="error")return;const oe=c.sessionId;C(null),j(!0),f(""),u({type:"generating",sessionId:oe}),Ke(oe);try{await wj(oe,o,T)}catch(Te){let he=Te;if((je(Te)||"").includes("not in an error state"))try{const We=await di(oe);if(!We)throw new Error("Failed to refresh subtask session.");if(g(ya(We.conversationHistory)),We.status==="generating"||We.status==="awaiting_input")f(We.thinkingOutput??""),u({type:"generating",sessionId:We.id}),U.current?.isConnected()||Ke(We.id);else if(We.status==="complete"){if(!We.result)throw new Error("Subtask session is complete but has no result.");yl(o);const Re=JSON.parse(We.result);m(Re),u({type:"editing",sessionId:We.id}),A(!1)}else We.status==="error"&&u({type:"error",sessionId:We.id,errorMessage:We.error??"Retry failed. Please try again."});y(!1);return}catch(We){he=We}U.current?.close(),U.current=null,u({type:"error",sessionId:oe,errorMessage:je(he)||"Retry failed. Please try again."}),y(!1)}finally{j(!1)}},[Ke,o,T,c]);return e?t.jsx("div",{className:"modal-overlay open",onClick:oe=>oe.target===oe.currentTarget&&void Je(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx($o,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Subtask Breakdown"})]}),t.jsxs("div",{className:"modal-header-actions",children:[fe&&t.jsx("button",{className:"modal-send-to-background",onClick:Qe,title:"Send to background","aria-label":"Send to background",children:t.jsx(Cr,{size:16})}),t.jsx("button",{className:"modal-close",onClick:()=>void Je(),"aria-label":"Close",children:t.jsx(Ut,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[M&&t.jsx("div",{className:"form-error planning-error",children:M}),b&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Ee&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),c.type==="initial"&&t.jsx("div",{className:"planning-initial",children:t.jsxs("div",{className:"planning-view-scroll",children:[t.jsx("p",{className:"text-muted",children:"Preparing to break this task into subtasks."}),t.jsx("pre",{className:"planning-thinking-output",children:R})]})}),c.type==="generating"&&t.jsxs("div",{className:"planning-loading",children:[h.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Is,{entries:h,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsx(rt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:"AI is generating subtasks..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>v(!x),type:"button",children:x?"Hide thinking":"Show thinking"}),x&&p&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:p})})]})]}),c.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[h.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Is,{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 Ne(),disabled:S,children:[S?t.jsx(rt,{size:14,className:"spin"}):t.jsx(En,{size:14}),t.jsx("span",{className:"icon-ml-6",children:S?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:()=>void Je(),disabled:S,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(Is,{entries:h}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(fn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Review your subtasks"}),t.jsx("p",{className:"text-muted",children:"Edit titles, descriptions, sizes, and dependencies before creating all tasks at once."})]}),t.jsxs("div",{className:"planning-summary-form",children:[d.map((oe,Te)=>{const he=P===oe.id,Me=V===oe.id,We=["task-detail-section","subtask-item",he?"subtask-item-dragging":"",Me?"subtask-item-drop-target":"",Me&&E==="before"?"subtask-item-drop-before":"",Me&&E==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:We,"data-testid":`subtask-item-${Te}`,draggable:c.type!=="creating",onDragStart:ye(oe.id),onDragEnd:te,onDragOver:Ae(oe.id),onDrop:Le(oe.id),onDragLeave:pe,children:[t.jsxs("div",{className:"detail-title-row subtask-item-header subtask-item-header--between",children:[t.jsxs("div",{className:"subtask-drag-handle",title:"Drag to reorder",children:[t.jsx(Qc,{size:16}),t.jsx("strong",{children:oe.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>_e(Te,Te-1),disabled:c.type==="creating"||Te===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(Fi,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>_e(Te,Te+1),disabled:c.type==="creating"||Te===d.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(wr,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>ae(oe.id),disabled:c.type==="creating",children:[t.jsx(Zt,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:Re=>{Y.current[Te]=Re},value:oe.title,onChange:Re=>Pe(oe.id,{title:Re.target.value}),onKeyDown:Re=>{Re.key==="Enter"&&(Re.preventDefault(),Fe(Te))},disabled:c.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:8,value:oe.description,onChange:Re=>Pe(oe.id,{description:Re.target.value}),disabled:c.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Size"}),t.jsxs("select",{className:"planning-size-select",value:oe.suggestedSize,onChange:Re=>Pe(oe.id,{suggestedSize:Re.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,Te).filter(Re=>Re.id!==oe.id).map(Re=>{const ot=oe.dependsOn.includes(Re.id);return t.jsxs("label",{className:`planning-dep-chip ${ot?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:ot,onChange:()=>{const J=ot?oe.dependsOn.filter(ce=>ce!==Re.id):[...oe.dependsOn,Re.id];Pe(oe.id,{dependsOn:J})},disabled:c.type==="creating"}),t.jsx("span",{className:"planning-dep-id",children:Re.id}),t.jsx("span",{className:"planning-dep-title",children:Re.title||"Untitled"})]},Re.id)}),Te===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),Te>0&&d.slice(0,Te).filter(Re=>Re.id!==oe.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},oe.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:Ve,disabled:c.type==="creating",children:[t.jsx(en,{size:16,className:"icon-mr-6"})," Add subtask"]}),eh(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 Je(),disabled:c.type==="creating",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:()=>void tt(),disabled:c.type==="creating"||se,children:c.type==="creating"?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]}),w&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Do,{size:16}),t.jsx("span",{children:De?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),De&&t.jsx("button",{type:"button",onClick:()=>{q()},disabled:G,className:"btn btn-primary session-lock-take-control",children:G?"Taking control...":"Take Control"})]})})]})]})}):null}const CA=5,EA=1e3,_A=45e3;function ao(){return{scrollback:null,connected:null,data:[]}}function MA(e,n){const[s,i]=a.useState("disconnected"),r=a.useRef(0),o=a.useRef(e),l=a.useRef(n),c=o.current!==e||l.current!==n;c&&(o.current=e,l.current=n,r.current++);const u=a.useRef(null),d=a.useRef(0),m=a.useRef(null),h=a.useRef(null),g=a.useRef(!1),p=a.useRef(new Set),f=a.useRef(new Set),x=a.useRef(new Set),v=a.useRef(new Set),b=a.useRef(new Set),y=a.useRef(ao()),S=a.useCallback($=>{p.current.add($);const E=y.current;return E.data.length>0&&(E.data.forEach(D=>$(D)),E.data=[]),()=>p.current.delete($)},[]),j=a.useCallback($=>(f.current.add($),()=>f.current.delete($)),[]),R=a.useCallback($=>{x.current.add($);const E=y.current;return E.connected&&($(E.connected),E.connected=null),()=>x.current.delete($)},[]),k=a.useCallback($=>{v.current.add($);const E=y.current;return E.scrollback&&($(E.scrollback),E.scrollback=null),()=>v.current.delete($)},[]),M=a.useCallback($=>(b.current.add($),()=>b.current.delete($)),[]),C=a.useCallback($=>{const E=u.current;E?.readyState===WebSocket.OPEN&&E.send(JSON.stringify({type:"input",data:$}))},[]),L=a.useCallback(($,E)=>{const D=u.current;D?.readyState===WebSocket.OPEN&&D.send(JSON.stringify({type:"resize",cols:$,rows:E}))},[]),A=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=ao()},[]),P=a.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.current=null),u.current&&(g.current=!0,u.current.close(),u.current=null),y.current=ao()},[]),O=a.useCallback(()=>{if(!e){i("disconnected");return}if(u.current?.readyState===WebSocket.OPEN)return;u.current&&(g.current=!0,u.current.close()),g.current=!1,i("connecting");const $=r.current;let D=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/terminal/ws?sessionId=${encodeURIComponent(e)}`;n&&(D+=`&projectId=${encodeURIComponent(n)}`);const U=new WebSocket(ti(D));u.current=U,U.onopen=()=>{if(r.current!==$){U.close();return}y.current=ao(),i("connected"),d.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{r.current===$&&U.readyState===WebSocket.OPEN&&U.send(JSON.stringify({type:"ping"}))},_A)},U.onmessage=Y=>{if(r.current===$)try{const X=JSON.parse(Y.data),_=y.current;switch(X.type){case"data":X.data&&(p.current.size===0&&_.data.push(X.data),p.current.forEach(I=>I(X.data)));break;case"scrollback":X.data&&(_.scrollback=X.data,v.current.forEach(I=>I(X.data)));break;case"connected":X.shell&&X.cwd&&(_.connected={shell:X.shell,cwd:X.cwd},x.current.forEach(I=>I({shell:X.shell,cwd:X.cwd})));break;case"exit":X.exitCode!==void 0&&f.current.forEach(I=>I(X.exitCode));break;case"ping":U.readyState===WebSocket.OPEN&&U.send(JSON.stringify({type:"pong"}));break;case"pong":break}}catch{}},U.onclose=Y=>{if(r.current!==$)return;if(u.current=null,h.current&&(clearInterval(h.current),h.current=null),g.current){i("disconnected");return}if(Y.code===4e3||Y.code===4004){i("disconnected"),Y.code===4004&&b.current.forEach(I=>I());return}if(d.current++,d.current>CA){i("disconnected");return}const X=EA*Math.pow(2,d.current-1);i("reconnecting");const _=r.current;m.current=setTimeout(()=>{r.current===_&&(g.current||O())},Math.min(X,16e3))},U.onerror=()=>{}},[e,n]),V=a.useCallback(()=>{d.current=0,P(),O()},[P,O]);return a.useEffect(()=>(c&&(A(),d.current=0,i("disconnected")),e?O():i("disconnected"),P),[e,n,c,O,P,A]),{connectionStatus:s,sendInput:C,resize:L,onData:S,onExit:j,onConnect:R,onScrollback:k,reconnect:V,onSessionInvalid:M}}const Yf="kb-terminal-tabs",AA=15e3,RA=15e3;function th(){return`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function nh(e){if(typeof window>"u")return[];try{const n=qn(Yf,e);if(n)return JSON.parse(n)}catch{}return[]}function Xl(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return n.includes("Failed to parse URL")||n.includes("Invalid URL")}function sh(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 TA(e){const[n,s]=a.useState(()=>nh(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(nh(e)),r(!1),l(!0),u(null)},[e]),a.useEffect(()=>{try{ds(Yf,JSON.stringify(n),e)}catch{}},[e,n]),a.useEffect(()=>{let R=!1;const k=h.current;return(async()=>{if(!R)try{const C=await sh(vy(e),AA,"listTerminalSessions");if(R||k!==h.current)return;const L=new Set(C.map(A=>A.id));l(!0),s(A=>{if(R||k!==h.current)return A;const O=A.map(E=>({...E,_verified:L.has(E.sessionId)})).filter(E=>E._verified);if(O.length===0)return[];const V=O.map(({_verified:E,...D})=>D);return V.find(E=>E.isActive)?V:V.map((E,D)=>({...E,isActive:D===0}))}),r(!0)}catch(C){if(R||k!==h.current)return;const L=Xl(C);L||console.warn("Failed to validate terminal sessions with server:",C),l(!L),r(!0)}})(),()=>{R=!0}},[e]),a.useEffect(()=>{if(n.length===0&&i&&o){const R=h.current,k=setTimeout(()=>{sh(Ur(void 0,void 0,void 0,e),RA,"createTerminalSession").then(M=>{if(R!==h.current)return;const C={id:th(),sessionId:M.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};s(L=>L.length>0?L:[...L.map(P=>({...P,isActive:!1})),C]),u(null)}).catch(M=>{if(R!==h.current)return;Xl(M)||console.error(M);const C=M instanceof Error?M.message:typeof M=="string"?M:"Failed to create terminal session";u(C)})},0);return()=>clearTimeout(k)}},[i,o,n.length,d]);const g=a.useCallback(async()=>{const R=await Ur(void 0,void 0,void 0,e),k={id:th(),sessionId:R.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};return s(M=>[...M.map(L=>({...L,isActive:!1})),k]),k},[n.length]),p=a.useCallback(async()=>g(),[g]),f=a.useCallback(R=>{s(k=>{const M=k.find(P=>P.id===R);if(!M)return k;Hd(M.sessionId,e).catch(P=>{console.warn(`Failed to kill terminal session ${M.sessionId}:`,P)});const C=k.findIndex(P=>P.id===R),L=M.isActive,A=k.filter(P=>P.id!==R);if(A.length===0)return[];if(L){const P=Math.min(C,A.length-1);return A.map((O,V)=>({...O,isActive:V===P}))}return A})},[]),x=a.useCallback(R=>{s(k=>{let M=!1;const C=k.map(L=>L.id===R?(M=!0,{...L,isActive:!0}):{...L,isActive:!1});return M?C:k})},[]),v=a.useCallback((R,k)=>{s(M=>M.map(C=>C.id===R?{...C,title:k}:C))},[]),b=a.useCallback(async()=>{s(M=>{const C=M.find(L=>L.isActive);return C&&Hd(C.sessionId,e).catch(L=>{console.warn(`Failed to kill old session ${C.sessionId}:`,L)}),M});const R=n.find(M=>M.isActive);if(!R)return;const k=await Ur(void 0,void 0,void 0,e);s(M=>M.map(C=>C.id===R.id?{...C,sessionId:k.sessionId}:C))},[n]),y=a.useCallback(async()=>{const R=n.find(k=>k.isActive);if(R)try{const k=await Ur(void 0,void 0,void 0,e);s(M=>M.map(C=>C.id===R.id?{...C,sessionId:k.sessionId}:C)),u(null)}catch(k){Xl(k)||console.error(k);const M=k instanceof Error?k.message:typeof k=="string"?k:"Failed to create terminal session";u(M)}},[n]),S=n.find(R=>R.isActive)??null,j=a.useCallback(()=>{u(null),h.current+=1,m(R=>R+1)},[]);return{tabs:n,activeTab:S,isReady:i,bootstrapError:c,createTab:p,closeTab:f,setActiveTab:x,updateTabTitle:v,restartActiveTab:b,retryBootstrap:j,replaceActiveTabSession:y}}const PA=1e4,IA=[500,1500,3e3],Qf="kb-terminal-font-size",ar=14,$A=8,DA=32;function LA(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 zA(e){return`\x1B${e}`}const FA=[{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 rr(e){return Math.min(DA,Math.max($A,e))}function OA(){if(typeof window>"u")return ar;try{const e=window.localStorage.getItem(Qf);if(!e)return ar;const n=Number.parseInt(e,10);return Number.isFinite(n)?rr(n):ar}catch{return ar}}function BA(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 UA(e){return new Promise(n=>setTimeout(n,e))}async function HA(e,n=IA){let s;for(let i=0;i<=n.length;i+=1)try{return await e()}catch(r){if(!BA(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 UA(o)}throw s??new Error("Dynamic import failed")}function ih(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}function qA(){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=VA()-e.offsetTop-e.height;return i>=30&&i>80?i:0}let Zl=null;function VA(){return Zl===null&&(Zl=window.innerHeight),Zl}function WA({isOpen:e,onClose:n,initialCommand:s,projectId:i}){const[r,o]=a.useState(null),[l,c]=a.useState(null),[u,d]=a.useState(!1),[m,h]=a.useState(null),[g,p]=a.useState(0),[f,x]=a.useState(0),[v,b]=a.useState(null),[y,S]=a.useState(()=>OA()),[j,R]=a.useState(!1),[k,M]=a.useState(null),C=a.useRef(null),L=a.useRef(null),A=a.useRef(!1);ni(L,e,"fusion:terminal-modal-size");const P=a.useRef(null),O=a.useRef(null),V=a.useRef(!1),$=a.useRef(!1),E=a.useRef(null),D=a.useRef(()=>{}),U=a.useRef(null),Y=a.useRef(0),X=a.useRef(y),_=a.useRef(null),I=a.useRef(i);Y.current=f,X.current=y;const T=a.useCallback(he=>{if(he&&$.current!==he)return;const Me=O.current,We=P.current,Re=E.current;if(!(!Me||!We)&&!(he&&$.current!==he))try{Me.fit(),Re&&Re(We.cols,We.rows)}catch{}},[]);a.useEffect(()=>{e&&p(he=>he+1)},[e]),a.useEffect(()=>{if(!e||!ih())return;const he=window.visualViewport;if(!he)return;const Me=()=>{const We=qA();x(We),b(he.height),We>0&&L.current?.scrollIntoView&&L.current.scrollIntoView({block:"end",behavior:"smooth"}),_.current!==null&&(cancelAnimationFrame(_.current),_.current=null);const Re=typeof $.current=="string"?$.current:void 0;_.current=requestAnimationFrame(()=>{_.current=null,T(Re)})};return Me(),he.addEventListener("resize",Me),he.addEventListener("scroll",Me),()=>{he.removeEventListener("resize",Me),he.removeEventListener("scroll",Me),_.current!==null&&(cancelAnimationFrame(_.current),_.current=null),x(0),b(null)}},[T,e]),a.useEffect(()=>{if(!e)return;const he=L.current;if(!he||typeof ResizeObserver>"u")return;let Me=null;const We=new ResizeObserver(()=>{Me!==null&&cancelAnimationFrame(Me),Me=requestAnimationFrame(()=>{Me=null;const Re=typeof $.current=="string"?$.current:void 0;T(Re)})});return We.observe(he),()=>{We.disconnect(),Me!==null&&cancelAnimationFrame(Me)}},[T,e]);const{tabs:w,activeTab:q,isReady:G,bootstrapError:me,createTab:ue,closeTab:le,setActiveTab:Se,updateTabTitle:F,restartActiveTab:ge,retryBootstrap:se,replaceActiveTabSession:fe}=TA(i),{connectionStatus:de,sendInput:xe,resize:ie,onData:Ee,onConnect:De,onExit:qe,onScrollback:Qe,reconnect:Je,onSessionInvalid:Ke}=MA(q?.sessionId??null,i);E.current=ie,D.current=xe,a.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Qf,String(y))}catch{}},[y]);const it=a.useCallback(()=>{const he=P.current;if(he)try{O.current?.fit(),ie(he.cols,he.rows)}catch{}},[ie]);a.useEffect(()=>{if(!e||!G)return;const he=q?.sessionId;if(!he)return;const Me=I.current!==i;if(Me&&(I.current=i),$.current===he&&P.current&&!Me)return;P.current&&($.current!==he||Me)&&(P.current.dispose(),P.current=null,O.current=null,$.current=!1,U.current&&(window.removeEventListener("resize",U.current),U.current=null),d(!1),h(null));let We=!0,Re;return(async()=>{const J=HA(()=>Promise.all([on(()=>import("./vendor-xterm-DzcZoU0P.js").then(ee=>ee.x),__vite__mapDeps([0,1,2])),on(()=>import("./addon-fit-C7jRorKK.js").then(ee=>ee.a),__vite__mapDeps([3,1])),on(()=>import("./addon-web-links-CkJwd4cQ.js").then(ee=>ee.a),__vite__mapDeps([4,1]))])),ce=new Promise((ee,Ge)=>{Re=setTimeout(()=>{Ge(new Error("xterm initialization timed out"))},PA)});let ve,Xe;try{const[{Terminal:ee},{FitAddon:Ge},{WebLinksAddon:ct}]=await Promise.race([J,ce]);if(!We||!C.current||P.current)return;ve=new ee({cursorBlink:!0,cursorStyle:"block",fontSize:X.current,fontFamily:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace',theme:{background:"#1e1e1e",foreground:"#d4d4d4",cursor:"#d4d4d4",selectionBackground:"#264f78",black:"#1e1e1e",red:"#f48771",green:"#4ec9b0",yellow:"#dcdcaa",blue:"#569cd6",magenta:"#c586c0",cyan:"#9cdcfe",white:"#d4d4d4"},allowProposedApi:!0,scrollback:5e3}),Xe=new Ge,ve.loadAddon(Xe);const vt=new ct;if(ve.loadAddon(vt),!ih())try{const{WebglAddon:gt}=await on(async()=>{const{WebglAddon:Rt}=await import("./addon-webgl-BjvOw43o.js").then(Ft=>Ft.a);return{WebglAddon:Rt}},__vite__mapDeps([5,1])),_t=new gt;_t.onContextLoss(()=>{_t.dispose()}),ve.loadAddon(_t)}catch{}ve.open(C.current),Re&&clearTimeout(Re);const bt=C.current?.querySelector(".xterm-helper-textarea");if(bt&&bt.focus(),C.current)try{C.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}setTimeout(()=>{Xe.fit();const gt=C.current?.querySelector(".xterm-helper-textarea");gt&>.focus()},50),P.current=ve,O.current=Xe,$.current=he,Y.current>0&&(_.current!==null&&(cancelAnimationFrame(_.current),_.current=null),_.current=requestAnimationFrame(()=>{_.current=null,T(he)})),ve.onData(gt=>{$.current===he&&D.current(gt)});const ft=()=>{if($.current===he&&O.current&&P.current)try{O.current.fit();const{cols:gt,rows:_t}=P.current;E.current?.(gt,_t)}catch{}};window.addEventListener("resize",ft),U.current&&window.removeEventListener("resize",U.current),U.current=ft,d(!0),h(null)}catch(ee){if(Re&&clearTimeout(Re),!We)return;const Ge=ee instanceof Error?ee.message:"xterm initialization failed";h(Ge)}})(),()=>{We=!1,Re&&clearTimeout(Re)}},[T,e,G,q?.sessionId,i]),a.useEffect(()=>{e||(P.current&&(P.current.dispose(),P.current=null),O.current=null,$.current=!1,U.current&&(window.removeEventListener("resize",U.current),U.current=null),d(!1),h(null),V.current=!1,o(null),c(null),R(!1),M(null))},[e]),a.useEffect(()=>{if(!u||!P.current||!q)return;const he=q.sessionId,Me=ce=>{$.current===he&&P.current?.write(ce)},We=Ee(ce=>{Me(ce)}),Re=Qe(ce=>{Me(ce)}),ot=De(ce=>{F(q.id,id(ce.shell)||ce.shell)}),J=qe(ce=>{$.current===he&&(c(ce),P.current?.write(`\r
|
|
653
|
+
\x1B[33m[Process exited with code ${ce}]\x1B[0m\r
|
|
654
|
+
`))});return()=>{We(),Re(),ot(),J()}},[u,q?.sessionId,q?.id,q,de,Ee,Qe,De,qe,F]),a.useEffect(()=>{de==="connected"&&s&&V.current!==s&&q&&(V.current=s,setTimeout(()=>{xe(s+`
|
|
655
|
+
`)},500))},[de,s,xe,q,g]),a.useEffect(()=>{if(!u||!P.current)return;P.current.options.fontSize=y,_.current!==null&&(cancelAnimationFrame(_.current),_.current=null);const he=requestAnimationFrame(()=>{_.current=null,it()});return _.current=he,()=>{_.current===he&&(cancelAnimationFrame(he),_.current=null)}},[y,u,it]),a.useEffect(()=>{if(!e)return;const he=Me=>{if(!(!Me.ctrlKey&&!Me.metaKey)){if(Me.code==="Equal"||Me.code==="NumpadAdd"){Me.preventDefault(),S(We=>rr(We+1));return}if(Me.code==="Minus"||Me.code==="NumpadSubtract"){Me.preventDefault(),S(We=>rr(We-1));return}if(Me.code==="Digit0"||Me.code==="Numpad0"){Me.preventDefault(),S(ar);return}}};return window.addEventListener("keydown",he),()=>window.removeEventListener("keydown",he)},[e,it]),a.useEffect(()=>{if(!e)return;const he=Me=>{Me.key==="Escape"&&n()};return document.addEventListener("keydown",he),()=>document.removeEventListener("keydown",he)},[e,n]),a.useEffect(()=>{de==="connected"&&P.current&&setTimeout(()=>{if(!P.current||!C.current)return;const he=C.current.querySelector(".xterm-helper-textarea");he&&he.focus();try{C.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[de]);const Pe=a.useCallback(()=>{if(!C.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;P.current?.focus();const Me=C.current.querySelector(".xterm-helper-textarea");if(!Me)return;Me.autocapitalize="off",Me.autocomplete="off",Me.autocorrect="off",Me.spellcheck=!1,Me.setAttribute("inputmode","text");try{Me.focus({preventScroll:!0})}catch{Me.focus()}const We=Me.value.length;Me.setSelectionRange(We,We)},[]);a.useEffect(()=>Ke(()=>{P.current?.clear(),c(null),V.current=!1,P.current&&(P.current.dispose(),P.current=null),O.current=null,$.current=!1,U.current&&(window.removeEventListener("resize",U.current),U.current=null),d(!1),h(null),fe().catch(Me=>{console.error("Failed to replace invalid terminal session:",Me)})}),[Ke,fe]);const Ve=a.useCallback(he=>{he.target===he.currentTarget&&(A.current=!0)},[]),ae=a.useCallback(he=>{A.current&&he.target===he.currentTarget&&n(),A.current=!1},[n]),ye=a.useCallback(()=>{P.current?.clear()},[]),te=a.useCallback(async()=>{P.current?.clear(),c(null),V.current=!1;try{await ge()}catch(he){o(je(he)||"Failed to restart terminal session")}},[ge]),Ae=a.useCallback(()=>{P.current&&(P.current.dispose(),P.current=null),O.current=null,$.current=!1,U.current&&(window.removeEventListener("resize",U.current),U.current=null),h(null),d(!1)},[]),Le=a.useCallback(()=>{window.location.reload()},[]),pe=a.useCallback(()=>{S(he=>rr(he+1))},[]),_e=a.useCallback(()=>{S(he=>rr(he-1))},[]),Fe=a.useCallback(he=>{M(Me=>Me===he?null:he)},[]),tt=a.useCallback(he=>{if(k==="ctrl"){xe(LA(he)),M(null);return}if(k==="alt"){xe(zA(he)),M(null);return}xe(he)},[xe,k]),Ne=a.useCallback(he=>{xe(he),M(null)},[xe]);if(!e)return null;const oe=()=>{switch(de){case"connected":return t.jsx("span",{className:"terminal-status connected",title:"Connected"});case"connecting":case"reconnecting":return t.jsx("span",{className:"terminal-status connecting",title:"Connecting..."});case"disconnected":return t.jsx("span",{className:"terminal-status disconnected",title:"Disconnected"});default:return null}},Te=!G||!q&&!me;return t.jsx("div",{className:"modal-overlay open",onMouseDown:Ve,onMouseUp:ae,role:"dialog","aria-modal":"true","data-testid":"terminal-modal-overlay",style:f>0?{"--overlay-padding-top":"0px"}:void 0,children:t.jsxs("div",{ref:L,className:"modal terminal-modal","data-testid":"terminal-modal",style:f>0?{"--keyboard-overlap":`${f}px`,"--vv-height":v?`${v}px`:void 0}:void 0,children:[t.jsxs("div",{className:"terminal-header",children:[t.jsxs("div",{className:"terminal-tabs","data-testid":"terminal-tabs",children:[w.map(he=>t.jsxs("div",{className:`terminal-tab ${he.isActive?"terminal-tab--active":""}`,onClick:()=>Se(he.id),title:he.title,role:"tab","aria-selected":he.isActive,children:[t.jsx("span",{className:"terminal-tab-label",children:he.title}),w.length>1&&t.jsx("button",{className:"terminal-tab-close",onClick:Me=>{Me.stopPropagation(),le(he.id)},title:"Close tab",children:"×"})]},he.id)),t.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:ue,title:"New terminal",children:"+"})]}),t.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[t.jsx(ci,{size:16}),oe()]}),t.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[de==="disconnected"&&q&&t.jsxs("button",{className:"terminal-reconnect-btn",onClick:Je,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[t.jsx(En,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),l!==null&&t.jsxs("button",{className:"terminal-restart-btn",onClick:te,title:"New Session","data-testid":"terminal-restart-btn",children:[t.jsx(En,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:ye,"data-testid":"terminal-clear-btn",title:"Clear terminal",children:[t.jsx(Zt,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Clear"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:()=>R(he=>!he),"data-testid":"terminal-shortcut-toggle",title:"Shortcuts","aria-pressed":j,children:[t.jsx(Jx,{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(Ut,{size:20})})]})]}),r&&t.jsx("div",{className:"terminal-error","data-testid":"terminal-error",children:r}),t.jsxs("div",{className:"terminal-container","data-testid":"terminal-container",children:[Te&&!me&&t.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[t.jsx("div",{className:"terminal-spinner"}),t.jsx("span",{children:"Starting terminal..."})]}),me&&!q&&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: ",me]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:se,"data-testid":"terminal-retry-btn",children:[t.jsx(En,{size:14}),"Retry"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Le,"data-testid":"terminal-bootstrap-refresh-btn",children:[t.jsx(En,{size:14}),"Refresh page"]})]})]})}),m&&q&&t.jsx("div",{className:"terminal-loading","data-testid":"terminal-xterm-init-error",children:t.jsxs("div",{className:"terminal-error-content",children:[t.jsxs("span",{children:["Terminal UI failed to initialize: ",m]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:Ae,"data-testid":"terminal-reinit-btn",children:[t.jsx(En,{size:14}),"Reinitialize"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Le,"data-testid":"terminal-xterm-refresh-btn",children:[t.jsx(En,{size:14}),"Refresh page"]})]})]})}),t.jsx("div",{ref:C,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:Pe,onTouchStart:Pe},q?.sessionId)]}),j&&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 ${k==="ctrl"?"is-active":""}`,"data-testid":"terminal-modifier-ctrl",onClick:()=>Fe("ctrl"),"aria-pressed":k==="ctrl",children:"Ctrl"}),t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${k==="alt"?"is-active":""}`,"data-testid":"terminal-modifier-alt",onClick:()=>Fe("alt"),"aria-pressed":k==="alt",children:"Alt"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>Ne("\x1B"),children:"ESC"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>Ne(" "),children:"Tab"})]}),FA.map(he=>t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>tt(he.key),title:he.description,children:he.label},he.label))]}),t.jsxs("div",{className:"terminal-status-bar","data-testid":"terminal-status-bar",children:[t.jsxs("span",{className:`terminal-connection-status ${de}`,children:[de==="connected"&&"Connected",de==="connecting"&&"Connecting...",de==="reconnecting"&&"Reconnecting...",de==="disconnected"&&"Disconnected"]}),l!==null&&t.jsxs("span",{className:"terminal-exit-code","data-testid":"terminal-exit-code",children:["Exit: ",l]}),t.jsxs("span",{className:"terminal-font-size-controls",children:[t.jsx("button",{type:"button",className:"terminal-font-size-btn",onClick:_e,"data-testid":"terminal-font-size-decrease","aria-label":"Decrease terminal font size",children:t.jsx(pb,{size:14})}),t.jsxs("span",{className:"terminal-font-size-value","data-testid":"terminal-font-size-value",children:[y,"px"]}),t.jsx("button",{type:"button",className:"terminal-font-size-btn",onClick:pe,"data-testid":"terminal-font-size-increase","aria-label":"Increase terminal font size",children:t.jsx(en,{size:14})})]}),t.jsx("span",{className:"terminal-shortcuts",children:"Ctrl++/- zoom • ⌨ Shortcuts panel • Esc close"})]})]})})}const Ya={name:"",command:""};function ah(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function KA(e,n=60){return e.length<=n?e:e.slice(0,n-3)+"..."}function GA({isOpen:e,onClose:n,addToast:s,projectId:i,onRunScript:r}){const[o,l]=a.useState({}),[c,u]=a.useState(!0),[d,m]=a.useState(!1),[h,g]=a.useState(null),[p,f]=a.useState(Ya),[x,v]=a.useState(!1),[b,y]=a.useState(null),[S,j]=a.useState(null),R=Si(n),k=a.useCallback(async()=>{try{u(!0);const D=await br(i);l(D)}catch(D){s(je(D)||"Failed to load scripts","error")}finally{u(!1)}},[s,i]);a.useEffect(()=>{e&&k()},[e,k]);const M=a.useCallback(()=>{m(!0),g(null),f(Ya),j(null)},[]),C=a.useCallback((D,U)=>{g(D),m(!1),f({name:D,command:U}),j(null)},[]),L=a.useCallback(()=>{g(null),m(!1),f(Ya),j(null)},[]),A=a.useCallback(D=>{f(U=>({...U,name:D})),D&&!ah(D)?j("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):j(null)},[]),P=a.useCallback(async()=>{const D=p.name.trim(),U=p.command.trim();if(!D){s("Script name is required","error");return}if(!ah(D)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!U){s("Script command is required","error");return}v(!0);try{await yj(D,U,i),s(h?"Script updated":"Script created","success"),g(null),m(!1),f(Ya),j(null),await k()}catch(Y){const X=je(Y);X?.includes("already exists")?s("A script with this name already exists","error"):s(X||"Failed to save script","error")}finally{v(!1)}},[p,h,s,k,i]),O=a.useCallback(async D=>{try{await jj(D,i),s("Script deleted","success"),y(null),h===D&&(g(null),f(Ya)),await k()}catch(U){s(je(U)||"Failed to delete script","error")}},[h,s,k,i]),V=a.useCallback((D,U)=>{r&&r(D,U)},[r]);if(!e)return null;const $=d||h!==null,E=Object.entries(o).map(([D,U])=>({name:D,command:U}));return t.jsx("div",{className:"modal-overlay open",...R,"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(ci,{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(rt,{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:D=>A(D.target.value),placeholder:"e.g., build, test, lint",disabled:x||h!==null,"data-testid":"script-name-input",style:{width:"100%",borderColor:S?"var(--color-error)":void 0}}),S&&t.jsx("div",{style:{fontSize:"12px",color:"var(--color-error)",marginTop:"4px"},"data-testid":"script-name-error",children:S}),t.jsx("div",{style:{fontSize:"11px",color:"var(--text-muted)",marginTop:"4px"},children:"Letters, numbers, hyphens, and underscores only"})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"script-command",style:{display:"block",marginBottom:"4px",fontSize:"13px",fontWeight:500,color:"var(--text)"},children:"Command"}),t.jsx("textarea",{id:"script-command",className:"input",value:p.command,onChange:D=>f(U=>({...U,command:D.target.value})),placeholder:"e.g., npm run build",rows:3,disabled:x,"data-testid":"script-command-input",style:{width:"100%",resize:"vertical",fontFamily:"monospace"}})]}),t.jsxs("div",{className:"scripts-modal-form-actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end"},children:[t.jsx("button",{className:"btn btn-secondary",onClick:L,disabled:x,"data-testid":"script-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:P,disabled:x||!!S,"data-testid":"script-save-btn",children:x?t.jsxs(t.Fragment,{children:[t.jsx(rt,{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:E.length===0?"No scripts defined":`${E.length} script${E.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(en,{size:14}),"Add Script"]})]}),E.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(ci,{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:E.map(D=>t.jsx("div",{className:"script-card","data-testid":`script-${D.name}`,style:{padding:"12px 16px",border:"1px solid var(--border)",borderRadius:"8px",background:"var(--card)"},children:t.jsxs("div",{className:"script-card-header",style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"4px"},children:t.jsx("span",{style:{fontWeight:600,fontSize:"14px",fontFamily:"monospace"},children:D.name})}),t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:D.command,children:KA(D.command)})]}),t.jsxs("div",{className:"script-card-actions",style:{display:"flex",gap:"4px",marginLeft:"8px",flexShrink:0},children:[t.jsxs("button",{className:"btn btn-secondary",onClick:()=>V(D.name,D.command),title:"Run script","aria-label":`Run ${D.name}`,"data-testid":`run-script-${D.name}`,style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 10px",fontSize:"12px"},children:[t.jsx(jn,{size:12}),"Run"]}),t.jsx("button",{className:"btn-icon",onClick:()=>C(D.name,D.command),title:"Edit","aria-label":`Edit ${D.name}`,"data-testid":`edit-script-${D.name}`,children:t.jsx(en,{size:14,style:{transform:"rotate(45deg)"}})}),b===D.name?t.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[t.jsx("button",{className:"btn-icon",onClick:()=>O(D.name),title:"Confirm delete","aria-label":`Confirm delete ${D.name}`,"data-testid":`confirm-delete-script-${D.name}`,style:{color:"var(--color-error)"},children:t.jsx(Zt,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>y(null),title:"Cancel delete","aria-label":"Cancel delete","data-testid":`cancel-delete-script-${D.name}`,children:t.jsx(Ut,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>y(D.name),title:"Delete","aria-label":`Delete ${D.name}`,"data-testid":`delete-script-${D.name}`,children:t.jsx(Zt,{size:14})})]})]})},D.name))})]})})]})})}function JA(e,n,s){const[i,r]=a.useState([]),[o,l]=a.useState("."),[c,u]=a.useState(!1),[d,m]=a.useState(null),[h,g]=a.useState(0),p=a.useCallback(()=>{g(x=>x+1)},[]),f=a.useCallback(x=>{l(x),m(null)},[]);return a.useEffect(()=>{l("."),m(null),r([])},[e]),a.useEffect(()=>{if(!n||!e)return;let x=!1;async function v(){u(!0),m(null);try{const b=await Ly(e,o==="."?void 0:o,s);x||r(b.entries)}catch(b){x||(m(je(b)||"Failed to load files"),r([]))}finally{x||u(!1)}}return v(),()=>{x=!0}},[e,o,n,h,s]),{entries:i,currentPath:o,setPath:f,loading:c,error:d,refresh:p}}function YA(e,n,s,i){const[r,o]=a.useState(""),[l,c]=a.useState(""),[u,d]=a.useState(null),[m,h]=a.useState(!1),[g,p]=a.useState(!1),[f,x]=a.useState(null),v=a.useCallback(S=>{o(S),x(null)},[]);a.useEffect(()=>{if(!e||!n){o(""),c(""),d(null),x(null);return}let S=!1;async function j(){h(!0),x(null);try{const R=await zy(e,n,i);S||(o(R.content),c(R.content),d(R.mtime))}catch(R){S||(x(je(R)||"Failed to load file"),o(""),c(""),d(null))}finally{S||h(!1)}}return j(),()=>{S=!0}},[e,n,s,i]);const b=r!==l,y=a.useCallback(async()=>{if(!(!e||!n||!b)){p(!0),x(null);try{const S=await Fy(e,n,r,i);c(r),d(S.mtime)}catch(S){throw x(je(S)||"Failed to save file"),S}finally{p(!1)}}},[e,n,r,b,i]);return{content:r,setContent:v,originalContent:l,loading:m,saving:g,error:f,save:y,hasChanges:b,mtime:u}}const QA=1e4;function XA(e){const s=e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||e||"Project Root"}function ZA(e){return{id:e.id,label:e.id,title:e.title,worktree:e.worktree,kind:"task"}}function eR(e){const[n,s]=a.useState("Project Root"),[i,r]=a.useState([]),[o,l]=a.useState(!0),[c,u]=a.useState(null);return a.useEffect(()=>{let d=!1;async function m(){try{const g=await Dy(e);if(d)return;s(XA(g.project)),r(g.tasks.map(ZA)),u(null)}catch(g){d||u(je(g)||"Failed to load workspaces")}finally{d||l(!1)}}m();const h=window.setInterval(()=>{m()},QA);return()=>{d=!0,window.clearInterval(h)}},[e]),{projectName:n,workspaces:i,loading:o,error:c}}function tR(e){return e===void 0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function nR(e){return e?new Date(e).toLocaleDateString():""}function rh(e,n){return ow(e,n)}const Qa={visible:!1,x:0,y:0,entry:null,entryFullPath:""},ec={type:null,entry:null,entryFullPath:""},sR=200,iR=500,oh=10;function aR({x:e,y:n,entry:s,onAction:i,onClose:r}){const o=a.useRef(null),[l,c]=a.useState({x:e,y:n});a.useEffect(()=>{const m=o.current;if(!m)return;const h=m.getBoundingClientRect(),g=window.visualViewport,p=g?.width&&g.width>0?g.width:window.innerWidth,f=g?.height&&g.height>0?g.height:window.innerHeight,x=g?.offsetLeft??0,v=g?.offsetTop??0,b=8;let y=e-x,S=n-v;y+h.width>p-b&&(y=p-b-h.width),S+h.height>f-b&&(S=f-b-h.height),y<b&&(y=b),S<b&&(S=b),c({x:y+x,y:S+v})},[e,n]),a.useEffect(()=>{const m=h=>{h.key==="Escape"&&r()};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[r]);const u=s.type==="directory",d=[{id:"copy",label:"Copy",icon:Bi,disabled:!1},{id:"move",label:"Move",icon:xb,disabled:!1},{id:"rename",label:"Rename",icon:ss,disabled:!1},...u?[{id:"download-zip",label:"Download as ZIP",icon:Ro,disabled:!1}]:[{id:"download",label:"Download",icon:cx,disabled:!1}],{id:"divider",label:"",icon:Bi,disabled:!0},{id:"delete",label:"Delete",icon:Zt,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 rR({type:e,entry:n,entryFullPath:s,onConfirm:i,onCancel:r,loading:o,error:l}){const c=a.useRef(null),u=e==="rename"?n.name:"",[d,m]=a.useState(u);a.useEffect(()=>{setTimeout(()=>c.current?.focus(),50)},[]),a.useEffect(()=>{if(e==="rename"&&c.current){const f=n.name.lastIndexOf(".");f>0?c.current.setSelectionRange(0,f):c.current.select()}},[e,n.name]);const h=f=>{f.key==="Enter"&&d.trim()&&i(d.trim()),f.key==="Escape"&&r()};if(e==="delete")return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsxs("div",{className:"file-browser-dialog",onClick:f=>f.stopPropagation(),children:[t.jsxs("div",{className:"file-browser-dialog-title",children:["Delete ",n.type==="directory"?"Folder":"File"]}),t.jsxs("div",{className:"file-browser-dialog-message",children:["Are you sure you want to delete ",t.jsx("strong",{children:n.name}),"?",n.type==="directory"&&" This will delete all contents recursively."]}),l&&t.jsx("div",{className:"file-browser-dialog-error",children:l}),t.jsxs("div",{className:"file-browser-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:r,disabled:o,children:"Cancel"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>i(""),disabled:o,children:o?"Deleting...":"Delete"})]})]})});const p={copy:{title:"Copy",placeholder:"Destination path",confirm:"Copy"},move:{title:"Move",placeholder:"Destination path",confirm:"Move"},rename:{title:"Rename",placeholder:"New name",confirm:"Rename"}}[e];return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsxs("div",{className:"file-browser-dialog",onClick:f=>f.stopPropagation(),children:[t.jsx("div",{className:"file-browser-dialog-title",children:p.title}),t.jsx("div",{className:"file-browser-dialog-info",children:e==="rename"?n.name:s}),t.jsx("input",{ref:c,className:"file-browser-dialog-input",type:"text",value:d,onChange:f=>m(f.target.value),placeholder:p.placeholder,onKeyDown:h,disabled:o}),l&&t.jsx("div",{className:"file-browser-dialog-error",children:l}),t.jsxs("div",{className:"file-browser-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:r,disabled:o,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>i(d.trim()),disabled:o||!d.trim(),children:o?`${p.confirm}ing...`:p.confirm})]})]})})}function oR({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(Qa),[g,p]=a.useState(ec),[f,x]=a.useState(!1),[v,b]=a.useState(null),[y,S]=a.useState(!1),[j,R]=a.useState(null),k=a.useRef(null),M=a.useRef(null),C=a.useRef(null),L=a.useRef(!1),A=a.useCallback(()=>{k.current!==null&&(window.clearTimeout(k.current),k.current=null),M.current!==null&&(window.clearTimeout(M.current),M.current=null)},[]),P=a.useCallback(()=>{A(),C.current=null,S(!1),R(null)},[A]);a.useEffect(()=>()=>{A()},[A]);const O=a.useCallback((I,T,w,q)=>{h({visible:!0,x:I,y:T,entry:w,entryFullPath:q})},[]),V=a.useCallback((I,T,w)=>{if(I.touches.length!==1)return;const q=I.touches[0];q&&(P(),C.current={x:q.clientX,y:q.clientY},M.current=window.setTimeout(()=>{S(!0),R(w)},sR),k.current=window.setTimeout(()=>{const G=C.current;G&&(L.current=!0,S(!1),R(null),A(),O(G.x,G.y,T,w))},iR))},[P,A,O]),$=a.useCallback(I=>{const T=C.current,w=I.touches[0];!T||!w||(Math.abs(w.clientX-T.x)>oh||Math.abs(w.clientY-T.y)>oh)&&P()},[P]),E=a.useCallback(()=>{P()},[P]);a.useEffect(()=>{if(!m.visible)return;const I=document.querySelector(".file-browser-list"),T=()=>{L.current=!1,P(),h(Qa)};return I?.addEventListener("scroll",T),()=>I?.removeEventListener("scroll",T)},[P,m.visible]),a.useEffect(()=>{if(!m.visible)return;const I=T=>{T.key==="Escape"&&(L.current=!1,h(Qa))};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[m.visible]);const D=a.useCallback((I,T)=>{I.preventDefault(),I.stopPropagation(),P(),L.current=!1,O(I.clientX,I.clientY,T,rh(n,T.name))},[P,n,O]),U=a.useCallback(I=>{if(!m.entry)return;L.current=!1;const T=m.entry,w=m.entryFullPath;if(h(Qa),I==="download"){if(!c)return;const q=ap(c,w,d);window.open(ti(q),"_blank");return}if(I==="download-zip"){if(!c)return;const q=Vy(c,w,d);window.open(ti(q),"_blank");return}p({type:I,entry:T,entryFullPath:w}),b(null)},[m,c,d]),Y=a.useCallback(async I=>{if(!(!g.type||!g.entry||!c)){x(!0),b(null);try{switch(g.type){case"copy":await By(c,g.entryFullPath,I,d);break;case"move":await Uy(c,g.entryFullPath,I,d);break;case"rename":await qy(c,g.entryFullPath,I,d);break;case"delete":await Hy(c,g.entryFullPath,d);break}p(ec),u?.()}catch(T){b(je(T)||"Operation failed")}finally{x(!1)}}},[g,c,u,d]),X=a.useCallback(()=>{p(ec),b(null)},[]),_=a.useCallback((I,T)=>{if(L.current){L.current=!1;return}m.visible||(I.type==="directory"?i(T):s(T))},[m.visible,i,s]);return r?t.jsxs("div",{className:"file-browser-loading",children:[t.jsx(rt,{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(lw(n))},children:[t.jsx(pn,{size:16,style:{transform:"rotate(-90deg)"}}),"Up one level"]}),t.jsx("span",{className:"file-browser-path",children:n==="."?"Root":Aa(n)})]}),t.jsx("div",{className:"file-browser-list",children:e.length===0?t.jsx("div",{className:"file-browser-empty",children:"(empty directory)"}):e.map(I=>{const T=rh(n,I.name),w=y&&j===T;return t.jsxs("div",{className:`file-node file-node--${I.type} ${w?"file-node--long-pressing":""}`,onClick:()=>_(I,T),onContextMenu:q=>D(q,I),onTouchStart:q=>V(q,I,T),onTouchMove:$,onTouchEnd:E,onTouchCancel:E,children:[t.jsx("div",{className:"file-node-icon",children:I.type==="directory"?t.jsx(Un,{size:16}):t.jsx(Wh,{size:16})}),t.jsx("div",{className:"file-node-name",children:I.name}),I.type==="file"&&I.size!==void 0&&t.jsx("div",{className:"file-node-size",children:tR(I.size)}),I.mtime&&t.jsx("div",{className:"file-node-time",children:nR(I.mtime)})]},I.name)})}),m.visible&&m.entry&&t.jsx(aR,{x:m.x,y:m.y,entry:m.entry,onAction:U,onClose:()=>{L.current=!1,h(Qa)}}),g.type&&g.entry&&t.jsx(rR,{type:g.type,entry:g.entry,entryFullPath:g.entryFullPath,onConfirm:Y,onCancel:X,loading:f,error:v})]})}function lR(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=lR(i),d=u&&(s?!0:r),m=a.useCallback(()=>{o(!1)},[]),h=a.useCallback(()=>{o(!0)},[]),g=a.useCallback(()=>{c(p=>!p)},[]);return t.jsxs("div",{className:"file-editor-container",children:[u?t.jsxs("div",{className:"file-editor-toolbar",children:[t.jsxs("div",{className:"file-editor-mode-toggle",children:[!s&&t.jsxs("button",{className:`btn btn-sm ${d?"":"btn-primary"}`,onClick:m,disabled:!d,"aria-label":"Edit mode",children:[t.jsx(Vh,{size:14}),"Edit"]}),t.jsxs("button",{className:`btn btn-sm ${d?"btn-primary":""}`,onClick:h,disabled:d,"aria-label":"Preview mode",children:[t.jsx(fa,{size:14}),"Preview"]})]}),!s&&t.jsx("button",{className:`btn btn-sm ${l?"btn-primary":""}`,onClick:g,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(fo,{size:14})})]}):!s&&t.jsxs("div",{className:"file-editor-toolbar",children:[t.jsx("div",{className:"file-editor-mode-toggle"}),t.jsx("button",{className:`btn btn-sm ${l?"btn-primary":""}`,onClick:g,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(fo,{size:14})})]}),d?t.jsx("div",{className:"file-editor-preview markdown-body",children:t.jsx(hi,{remarkPlugins:[pi],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 dR(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function uR({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(Pd,{size:14}):t.jsx(xc,{size:14}),t.jsx("span",{className:"workspace-selector-trigger-label",children:l}),t.jsx(Vt,{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(Pd,{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(xc,{size:14}),t.jsx("span",{children:c.id})]}),c.title&&t.jsx("span",{className:"workspace-selector-option-meta",title:c.title,children:dR(c.title)})]},c.id))]})]})]})}const mR=768,Xf=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),hR=new Set([...Xf,".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 lh(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return hR.has(n)}function pR(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return Xf.has(n)}function fR({initialWorkspace:e="project",onClose:n,onWorkspaceChange:s,projectId:i}){const{projectName:r,workspaces:o}=eR(i),l=a.useRef(null);ni(l,!0,"fusion:files-modal-size");const c=Si(n),[u,d]=a.useState(e),[m,h]=a.useState(null),[g,p]=a.useState(!1),[f,x]=a.useState("list"),{entries:v,currentPath:b,setPath:y,loading:S,error:j,refresh:R}=JA(u,!0,i),{content:k,setContent:M,originalContent:C,loading:L,saving:A,error:P,save:O,hasChanges:V,mtime:$}=YA(u,m,!0,i);a.useEffect(()=>{d(e)},[e]),a.useEffect(()=>{const w=()=>{p(window.innerWidth<=mR)};return w(),window.addEventListener("resize",w),()=>window.removeEventListener("resize",w)},[]),a.useEffect(()=>{m||x("list")},[m]),a.useEffect(()=>{const w=q=>{q.key==="Escape"&&n(),(q.metaKey||q.ctrlKey)&&q.key==="s"&&(q.preventDefault(),V&&!A&&O())};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[n,V,A,O]);const E=a.useCallback(w=>{h(w),g&&x("editor")},[g]),D=a.useCallback(()=>{x("list")},[]),U=a.useCallback(()=>{M(C)},[C,M]),Y=a.useCallback(w=>{d(w),h(null),x("list"),s?.(w)},[s]),_=`Files — ${a.useMemo(()=>u==="project"?"Project":o.find(w=>w.id===u)?.id??u,[u,o])}`,I=a.useMemo(()=>!m||!pR(m)?null:ap(u,m,i),[m,u,i]),T=w=>{const q=new Blob([w]).size;return q<1024?`${q} B`:`${(q/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(Un,{size:18}),t.jsx("span",{children:_}),m&&t.jsx("span",{className:"file-browser-header-path",children:m})]}),t.jsxs("div",{className:"file-browser-header-actions",children:[t.jsx(uR,{currentWorkspace:u,projectName:r,workspaces:o,onSelect:Y}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Ut,{size:20})})]})]}),t.jsxs("div",{className:"file-browser-body",children:[t.jsx("div",{className:`file-browser-sidebar ${g?"mobile":""} ${f==="list"?"active":""}`,children:t.jsx(oR,{entries:v,currentPath:b,onSelectFile:E,onNavigate:y,loading:S,error:j,onRetry:R,workspace:u,onRefresh:R,projectId:i})}),t.jsx("div",{className:`file-browser-content ${g?"mobile":""} ${f==="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:[g&&f==="editor"&&t.jsxs("button",{className:"file-browser-back-button",onClick:D,"aria-label":"Back to file list",children:[t.jsx(_a,{size:16}),t.jsx("span",{children:"Back"})]}),m,lh(m)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(_x,{size:12}),"Binary file — read only"]}),$&&t.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date($).toLocaleString()]}),L&&t.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),t.jsx("div",{className:"file-browser-actions",children:!I&&V&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:U,disabled:A,children:[t.jsx(Mb,{size:14}),"Discard"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void O(),disabled:A,children:[t.jsx(Qh,{size:14}),A?"Saving...":"Save"]})]})})]}),P&&!I&&t.jsx("div",{className:"file-browser-error-banner",children:P}),I?t.jsx("div",{className:"file-browser-image-preview",children:t.jsx("img",{src:I,alt:m??"",className:"file-browser-image"})}):t.jsx("div",{className:"file-editor-wrapper",children:t.jsx(cR,{content:k,onChange:M,filePath:m,readOnly:lh(m)})}),!I&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:T(k)}),V&&t.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):t.jsxs("div",{className:"file-browser-placeholder",children:[t.jsx(Un,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to edit"})]})})]})]})})}function gR(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 Zv();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:je(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 xR(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 bR(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}const Zf="kb-usage-hidden-windows";function ch(e){const n=qn(Zf,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 vR(e,n){ds(Zf,JSON.stringify(e),n)}function eg(e,n,s){return s[e]?.includes(n)??!1}function yR({window:e,viewMode:n,isHidden:s,onToggleHidden:i}){const r=bR(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 b=Math.floor(v/36e5),y=Math.floor(b/24),S=b%24;y>0&&S>0?d=`resets in ${y}d ${S}h`:y>0?d=`resets in ${y}d`:b>0?d=`resets in ${b}h`:d=`resets in ${Math.floor(v/6e4)}m`}}const m=e.pace,h=m!==void 0;let g=0;h&&(g=o?100-m.percentElapsed:m.percentElapsed);const p=m?.status==="ahead",f=m?.status==="behind",x=m?.status==="on-track";return t.jsxs("div",{className:`usage-window ${s?"usage-window--hidden":""}`,children:[t.jsxs("div",{className:"usage-window-header",children:[t.jsx("span",{className:"usage-window-label",children:e.label}),t.jsxs("div",{className:"usage-window-header-controls",children:[!s&&t.jsx("span",{className:"usage-window-percentage",children:c}),!s&&t.jsx("button",{className:"btn-icon usage-window-hide-btn",onClick:i,"aria-label":`Hide ${e.label}`,"data-testid":"usage-window-hide-btn",children:t.jsx(fa,{size:14})})]})]}),t.jsxs("div",{className:"usage-progress-wrapper",children:[t.jsx("div",{className:"usage-progress-bar",children:t.jsx("div",{className:`usage-progress-fill ${r}`,style:{width:`${l}%`},role:"progressbar","aria-valuenow":l,"aria-valuemin":0,"aria-valuemax":100,"aria-label":`${e.label}: ${c}`})}),h&&t.jsx("div",{className:"usage-pace-marker",style:{left:`${g}%`},"aria-hidden":"true","data-testid":"pace-marker"})]}),t.jsxs("div",{className:"usage-window-footer",children:[t.jsx("span",{className:"usage-window-left",children:u}),t.jsxs("span",{className:"usage-window-reset-group",children:[d&&t.jsx("span",{className:"usage-window-reset",children:d}),e.resetAt&&t.jsx("span",{className:"usage-window-reset-at",children:xR(e.resetAt)})]})]}),h&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[p&&t.jsxs(t.Fragment,{children:[t.jsx(Xc,{size:14,className:"pace-icon pace-ahead"}),t.jsx("span",{className:"pace-text pace-ahead",children:m.message})]}),f&&t.jsxs(t.Fragment,{children:[t.jsx(Qb,{size:14,className:"pace-icon pace-behind"}),t.jsx("span",{className:"pace-text pace-behind",children:m.message})]}),x&&t.jsxs(t.Fragment,{children:[t.jsx(fn,{size:14,className:"pace-icon pace-ontrack"}),t.jsx("span",{className:"pace-text pace-ontrack",children:m.message})]})]})]})}function jR(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 kR({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(Dn,{provider:jR(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=eg(e.name,c.label,s);return t.jsx(yR,{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 wR(){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 NR({isOpen:e,onClose:n,projectId:s,anchorRect:i}){const{providers:r,loading:o,error:l,lastUpdated:c,refresh:u}=gR({autoRefresh:e}),[d,m]=a.useState(!1),[h,g]=a.useState(()=>typeof window<"u"?window.innerWidth>=769:!1),[p,f]=a.useState("used"),[x,v]=a.useState(()=>ch(s)),b=a.useRef(null),y=a.useRef(e),S=a.useRef(!1);a.useEffect(()=>{e||(S.current=!1)},[e]),a.useEffect(()=>{r.length>0&&(S.current=!0)},[r.length]),a.useEffect(()=>{if(typeof window>"u")return;const E=()=>{g(window.innerWidth>=769)};return window.addEventListener("resize",E),()=>window.removeEventListener("resize",E)},[]),a.useEffect(()=>{!y.current&&e&&(!c||Date.now()-c.getTime()>5e3)&&u(),y.current=e},[e,c,u]),a.useEffect(()=>{const E=qn("kb-usage-view-mode",s);if(E==="used"||E==="remaining"){f(E);return}f("used")},[s]);const j=a.useCallback(E=>{f(E),ds("kb-usage-view-mode",E,s)},[s]);a.useEffect(()=>{v(ch(s))},[s]),a.useEffect(()=>{vR(x,s)},[x,s]);const R=a.useCallback((E,D)=>{v(U=>{if(eg(E,D,U)){const Y=(U[E]??[]).filter(X=>X!==D);if(Y.length===0){const{[E]:X,..._}=U;return _}return{...U,[E]:Y}}return{...U,[E]:[...U[E]??[],D]}})},[]),k=a.useCallback(E=>{v(D=>{if(!D[E])return D;const{[E]:U,...Y}=D;return Y})},[]),M=a.useCallback(async()=>{m(!0),await u(),m(!1)},[u]);a.useEffect(()=>{if(!e)return;const E=D=>{D.key==="Escape"&&n()};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[e,n]);const C=a.useCallback(E=>{E.target===E.currentTarget&&n()},[n]);if(!e)return null;const L=!!(i&&h),O=L?Math.min((i?.bottom??0)+8,window.innerHeight-12):void 0,V=L?Math.max(window.innerWidth-(i?.right??0),0):void 0,$=t.jsxs("div",{className:`usage-modal${L?" usage-modal--popover":" modal"}`,"data-testid":"usage-modal",style:L?{position:"fixed",top:O,right:V}:void 0,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"usage-header",children:[t.jsx(Ps,{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:()=>j("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:()=>j("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(Ut,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:b,children:(o||!S.current&&!l)&&r.length===0?t.jsx(wR,{}):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(E=>t.jsx(kR,{provider:E,viewMode:p,hiddenWindows:x,onToggleWindow:R,onShowAllHidden:k},E.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(En,{size:14,className:d?"spin":"",style:{marginRight:6}}),"Refresh"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]});return L?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:C,"data-testid":"usage-modal-overlay",children:$})}function tg(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 _o(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 SR={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},ng={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},CR={cron:Uh,webhook:Zh,api:Hh,manual:Bn},ER={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},_R={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function MR({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(fn,{size:12}):t.jsx(Sr,{size:12}),t.jsx("span",{children:e.success?"Success":"Failed"}),n>0&&t.jsx("span",{className:"schedule-run-duration",children:tg(n)})]})}function AR({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"} ${_o(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx(fn,{size:12}):t.jsx(Sr,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:_o(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:ng[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:tg(r)}),s?t.jsx(ui,{size:12}):t.jsx(Vt,{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 RR({routine:e,onEdit:n,onDelete:s,onRun:i,onToggle:r,running:o,lastRunOutput:l}){const[c,u]=a.useState(!1),{confirm:d}=Hs(),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=SR[e.trigger.type],g=CR[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(g,{size:10}),ng[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(Io,{size:10}):t.jsx(Un,{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(rt,{size:14,className:"spinner"}):t.jsx(jn,{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(Xs,{size:14}):t.jsx(jn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:"Edit","aria-label":`Edit ${e.name}`,children:t.jsx(ss,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:m,title:"Delete","aria-label":`Delete ${e.name}`,children:t.jsx(Zt,{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(Hi,{size:12}),t.jsxs("span",{className:"routine-policy-badge",children:[e.steps.length," step",e.steps.length===1?"":"s"]})]}):e.command?t.jsx("div",{className:"routine-meta-item routine-meta-command-preview",title:e.command,children:t.jsx("code",{className:"routine-cron",children:e.command})}):null,e.trigger.type==="cron"&&p&&t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(wi,{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:ER[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:_R[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:_o(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:_o(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(MR,{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(f=>!f),"aria-expanded":c,children:[c?t.jsx(ui,{size:12}):t.jsx(Vt,{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((f,x)=>t.jsx(AR,{result:f,index:x},`${f.startedAt}-${x}`)),e.runHistory.length>10&&t.jsxs("div",{className:"schedule-history-more",children:["…and ",e.runHistory.length-10," more"]})]})]})]})}function TR({type:e,size:n=12}){return e==="command"?t.jsxs("span",{className:"step-type-badge step-type-command",title:"Command step",children:[t.jsx(ci,{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(tb,{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(Xn,{size:n}),t.jsx("span",{children:"AI Prompt"})]})}function tc(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function PR(e){return e==="command"?{id:tc(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:tc(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:tc(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function IR({step:e,onSave:n,onCancel:s}){const[i,r]=a.useState(e.name),[o,l]=a.useState(e.type),[c,u]=a.useState(e.command??""),[d,m]=a.useState(e.prompt??""),[h,g]=a.useState(e.modelProvider??""),[p,f]=a.useState(e.modelId??""),[x,v]=a.useState(e.taskTitle??""),[b,y]=a.useState(e.taskDescription??""),[S,j]=a.useState(e.taskColumn??"triage"),[R,k]=a.useState(e.timeoutMs),[M,C]=a.useState(e.continueOnFailure??!1),[L,A]=a.useState({}),[P,O]=a.useState([]),[V,$]=a.useState(!1),[E,D]=a.useState(null);a.useEffect(()=>{let I=!1;return $(!0),D(null),ms().then(T=>{I||O(T.models)}).catch(T=>{I||D(T instanceof Error?T.message:"Failed to load models")}).finally(()=>{I||$(!1)}),()=>{I=!0}},[]);const U=a.useCallback(()=>{const I={};return i.trim()||(I.name="Step name is required"),o==="command"&&!c.trim()&&(I.command="Command is required"),o==="ai-prompt"&&!d.trim()&&(I.prompt="Prompt is required"),o==="create-task"&&!b.trim()&&(I.taskDescription="Task description is required"),(o==="ai-prompt"||o==="create-task")&&(h||p)&&(!h||!p)&&(I.modelProvider="Both model provider and model ID must be set together"),R!==void 0&&R<1e3&&(I.timeoutMs="Timeout must be at least 1 second (1000ms)"),A(I),Object.keys(I).length===0},[i,o,c,d,b,h,p,R]),Y=h&&p?`${h}/${p}`:"",X=a.useCallback(I=>{if(!I)g(""),f("");else{const T=I.indexOf("/");T!==-1&&(g(I.slice(0,T)),f(I.slice(T+1)))}},[]),_=a.useCallback(()=>{if(!U())return;const I={...e,name:i.trim(),type:o,command:o==="command"?c.trim():void 0,prompt:o==="ai-prompt"?d.trim():void 0,taskTitle:o==="create-task"&&x.trim()?x.trim():void 0,taskDescription:o==="create-task"&&b.trim()?b.trim():void 0,taskColumn:o==="create-task"?S:void 0,modelProvider:(o==="ai-prompt"||o==="create-task")&&h.trim()?h.trim():void 0,modelId:(o==="ai-prompt"||o==="create-task")&&p.trim()?p.trim():void 0,timeoutMs:R||void 0,continueOnFailure:M};o!=="ai-prompt"&&delete I.prompt,o!=="create-task"&&(delete I.taskTitle,delete I.taskDescription,delete I.taskColumn),n(I)},[U,n,e,i,o,c,d,x,b,S,h,p,R,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:I=>r(I.target.value),"aria-invalid":!!L.name}),L.name&&t.jsx("small",{className:"field-error",children:L.name})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-type-${e.id}`,children:"Step Type"}),t.jsxs("select",{id:`step-type-${e.id}`,value:o,onChange:I=>l(I.target.value),children:[t.jsx("option",{value:"command",children:"Command"}),t.jsx("option",{value:"ai-prompt",children:"AI Prompt"}),t.jsx("option",{value:"create-task",children:"Create Task"})]})]}),o==="command"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-command-${e.id}`,children:"Command"}),t.jsx("textarea",{id:`step-command-${e.id}`,placeholder:"e.g. npm test",value:c,onChange:I=>u(I.target.value),rows:2,"aria-invalid":!!L.command}),L.command&&t.jsx("small",{className:"field-error",children:L.command})]}),o==="ai-prompt"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-prompt-${e.id}`,children:"Prompt"}),t.jsx("textarea",{id:`step-prompt-${e.id}`,placeholder:"e.g. Summarize the test results and highlight any failures",value:d,onChange:I=>m(I.target.value),rows:3,"aria-invalid":!!L.prompt}),L.prompt&&t.jsx("small",{className:"field-error",children:L.prompt})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-model-${e.id}`,children:"Model (optional)"}),t.jsx(Hn,{id:`step-model-${e.id}`,label:"Model",models:P,value:Y,onChange:X,placeholder:"Use default",disabled:V}),E&&t.jsx("small",{className:"field-error",children:E}),t.jsx("small",{children:"AI model for this step. Uses default if not selected."})]})]}),o==="create-task"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-title-${e.id}`,children:"Task Title (optional)"}),t.jsx("input",{id:`step-task-title-${e.id}`,type:"text",placeholder:"e.g. Review weekly dependencies",value:x,onChange:I=>v(I.target.value)}),t.jsx("small",{children:"Leave blank to auto-summarize from description"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-description-${e.id}`,children:"Task Description *"}),t.jsx("textarea",{id:`step-task-description-${e.id}`,placeholder:"e.g. Check all npm dependencies for security vulnerabilities and update outdated packages",value:b,onChange:I=>y(I.target.value),rows:4,"aria-invalid":!!L.taskDescription}),L.taskDescription&&t.jsx("small",{className:"field-error",children:L.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:S,onChange:I=>j(I.target.value),children:[t.jsx("option",{value:"triage",children:"Triage"}),t.jsx("option",{value:"todo",children:"To Do"})]}),t.jsx("small",{children:"Column where the new task will be created"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-model-${e.id}`,children:"Executor Model (optional)"}),t.jsx(Hn,{id:`step-task-model-${e.id}`,label:"Model",models:P,value:Y,onChange:X,placeholder:"Use default",disabled:V}),E&&t.jsx("small",{className:"field-error",children:E}),L.modelProvider&&t.jsx("small",{className:"field-error",children:L.modelProvider}),t.jsx("small",{children:"AI model for executing the created task. Uses default if not selected."})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-timeout-${e.id}`,children:"Timeout (ms, optional)"}),t.jsx("input",{id:`step-timeout-${e.id}`,type:"number",min:1e3,step:1e3,placeholder:"Override schedule timeout",value:R??"",onChange:I=>k(I.target.value?Number(I.target.value):void 0),"aria-invalid":!!L.timeoutMs}),L.timeoutMs&&t.jsx("small",{className:"field-error",children:L.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:I=>C(I.target.checked)}),"Continue on failure"]}),t.jsx("small",{children:"If checked, the next step will run even if this one fails"})]}),t.jsxs("div",{className:"step-editor-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:_,children:"Save Step"})]})]})}function $R({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=PR(d);n([...e,m]),r(m.id)},[e,n]),l=a.useCallback(d=>{n(e.filter(m=>m.id!==d)),i===d&&r(null)},[e,n,i]),c=a.useCallback((d,m)=>{const h=e.findIndex(f=>f.id===d);if(h<0)return;const g=m==="up"?h-1:h+1;if(g<0||g>=e.length)return;const p=[...e];[p[h],p[g]]=[p[g],p[h]],n(p)},[e,n]),u=a.useCallback(d=>{n(e.map(m=>m.id===d.id?d:m)),r(null)},[e,n]);return t.jsxs("div",{className:"steps-editor",children:[t.jsx("div",{className:"steps-editor-header",children:t.jsxs("span",{className:"steps-editor-title",children:["Steps (",e.length,")"]})}),e.length===0&&t.jsx("div",{className:"steps-empty-state",children:t.jsx("p",{children:"No steps added yet. Add a command or AI prompt step to get started."})}),t.jsx("div",{className:"steps-list",children:e.map((d,m)=>t.jsx("div",{className:"step-card",children:i===d.id?t.jsx(IR,{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(Qc,{size:14})}),t.jsx("span",{className:"step-card-index",children:m+1}),t.jsx(TR,{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(ui,{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(Vt,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(d.id),title:"Edit","aria-label":`Edit ${d.name}`,children:t.jsx(ss,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>l(d.id),title:"Delete","aria-label":`Delete ${d.name}`,children:t.jsx(Zt,{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(en,{size:14}),"Add Command Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ai-prompt"),children:[t.jsx(en,{size:14}),"Add AI Prompt Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("create-task"),children:[t.jsx(en,{size:14}),"Add Create Task Step"]})]})]})}const sg={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},DR={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function LR(e){const n=e.trim();for(const[s,i]of Object.entries(sg))if(i===n)return s;return"custom"}function zR(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function FR(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 OR(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 BR=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],UR=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function dh(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function uh({routine:e,onSubmit:n,onCancel:s,scope:i,projectId:r,onScopeChange:o}){const l=!!e,c=e?OR(e):{triggerType:"cron",cronExpression:"0 * * * *",webhookPath:"",webhookSecret:"",endpoint:""},[u,d]=a.useState(e?.name??""),[m,h]=a.useState(e?.description??""),[g,p]=a.useState(c.triggerType),[f,x]=a.useState(c.cronExpression),[v,b]=a.useState(()=>c.triggerType!=="cron"?"custom":LR(c.cronExpression)),[y,S]=a.useState(c.webhookPath),[j,R]=a.useState(c.webhookSecret),[k,M]=a.useState(c.endpoint),[C,L]=a.useState(e?.executionPolicy??"queue"),[A,P]=a.useState(e?.catchUpPolicy??"run_one"),[O,V]=a.useState(e?.enabled??!0),$=e?.steps&&e.steps.length===1&&e.steps[0].type==="ai-prompt"&&!e.command,E=e?.steps&&e.steps.length===1&&e.steps[0].type==="create-task"&&!e.command,[D,U]=a.useState(e?.steps&&e.steps.length>0&&!$&&!E?"advanced":"simple"),[Y,X]=a.useState(()=>$?"ai-prompt":E?"create-task":"command"),[_,I]=a.useState(e?.command??""),[T,w]=a.useState(e?.steps??[]),[q,G]=a.useState(!1),[me,ue]=a.useState(e?.timeoutMs??3e5),[le,Se]=a.useState($?e.steps?.[0]?.prompt??"":""),[F,ge]=a.useState(E?e.steps?.[0]?.taskTitle??"":""),[se,fe]=a.useState(E?e.steps?.[0]?.taskDescription??"":""),[de,xe]=a.useState(E?e.steps?.[0]?.taskColumn??"triage":"triage"),[ie,Ee]=a.useState($||E?e.steps?.[0]?.modelProvider??"":""),[De,qe]=a.useState($||E?e.steps?.[0]?.modelId??"":""),[Qe,Je]=a.useState([]),[Ke,it]=a.useState(!1),[Pe,Ve]=a.useState(null),[ae,ye]=a.useState(i??"global"),[te,Ae]=a.useState({}),[Le,pe]=a.useState(!1),_e=a.useRef(!0);a.useEffect(()=>()=>{_e.current=!1},[]),a.useEffect(()=>{i&&ye(i)},[i]),a.useEffect(()=>{let ee=!1;return it(!0),Ve(null),ms().then(Ge=>{ee||Je(Ge.models)}).catch(Ge=>{ee||Ve(Ge instanceof Error?Ge.message:"Failed to load models")}).finally(()=>{ee||it(!1)}),()=>{ee=!0}},[]);const Fe=ie&&De?`${ie}/${De}`:"",tt=a.useCallback(ee=>{if(!ee){Ee(""),qe("");return}const Ge=ee.indexOf("/");Ge!==-1&&(Ee(ee.slice(0,Ge)),qe(ee.slice(Ge+1)))},[]),Ne=a.useCallback(()=>{const ee={};if(u.trim()||(ee.name="Name is required"),ae==="project"&&!r&&(ee.scope="Project-specific entries require an active project."),g==="cron"&&v==="custom"&&(f.trim()?zR(f)||(ee.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):ee.cronExpression="Cron expression is required"),g==="webhook"&&!y.trim()&&(ee.webhookPath="Webhook path is required"),g==="api"&&!k.trim()&&(ee.endpoint="API endpoint is required"),D==="simple")Y==="command"&&!_.trim()&&(ee.command="Command is required"),Y==="ai-prompt"&&!le.trim()&&(ee.prompt="Prompt is required"),Y==="create-task"&&!se.trim()&&(ee.taskDescription="Task description is required"),(ie.trim()&&!De.trim()||!ie.trim()&&De.trim())&&(ee.model="Both model provider and model ID must be set, or both must be empty");else{T.length===0&&(ee.steps="At least one step is required"),q&&(ee.stepsEditing="Please save or cancel all step edits before saving the routine");const Ge=[];T.forEach((ct,vt)=>{ct.name?.trim()||Ge.push(`Step ${vt+1}: Name is required`),ct.type==="command"&&!ct.command?.trim()&&Ge.push(`Step ${vt+1}: Command is required`),ct.type==="ai-prompt"&&!ct.prompt?.trim()&&Ge.push(`Step ${vt+1}: Prompt is required`),ct.type==="create-task"&&!ct.taskDescription?.trim()&&Ge.push(`Step ${vt+1}: Task description is required`)}),Ge.length>0&&(ee.steps=Ge.join("; "))}return me<1e3&&(ee.timeoutMs="Timeout must be at least 1 second (1000ms)"),Ae(ee),Object.keys(ee).length===0},[u,g,f,v,y,k,ae,r,D,Y,_,le,se,ie,De,T,q,me]),oe=a.useCallback(async ee=>{if(ee.preventDefault(),!!Ne()){pe(!0);try{let Ge=e?.scope??ae??(r?"project":"global");Ge==="project"&&!r&&(Ge="global");const ct=FR(g,f,y,j,k);let vt,bt;D==="simple"?Y==="command"?vt=_.trim()||void 0:Y==="ai-prompt"?bt=[{id:dh(),type:"ai-prompt",name:u.trim(),prompt:le.trim(),modelProvider:ie.trim()||void 0,modelId:De.trim()||void 0}]:bt=[{id:dh(),type:"create-task",name:u.trim(),taskTitle:F.trim()||void 0,taskDescription:se.trim(),taskColumn:de,modelProvider:ie.trim()||void 0,modelId:De.trim()||void 0}]:bt=T;const ft={name:u.trim(),agentId:e?.agentId??"",description:m.trim()||void 0,trigger:ct,command:vt,steps:bt,timeoutMs:me,executionPolicy:C,catchUpPolicy:A,enabled:O,scope:Ge};await n(ft)}finally{_e.current&&pe(!1)}}},[Ne,n,u,m,g,f,y,j,k,D,Y,_,le,ie,De,F,se,de,T,me,C,A,O,ae,r,e?.scope,e?.agentId]),Te="routine-name-error",he="routine-cron-error",Me="routine-webhook-error",We="routine-endpoint-error",Re="routine-command-error",ot="routine-prompt-error",J="routine-task-description-error",ce="routine-model-error",ve="routine-timeout-error",Xe=a.useCallback(ee=>{b(ee),ee!=="custom"&&x(sg[ee])},[]);return t.jsxs("form",{className:"routine-form",onSubmit:oe,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:ee=>d(ee.target.value),"aria-invalid":!!te.name,"aria-describedby":te.name?Te:void 0}),te.name&&t.jsx("small",{id:Te,className:"field-error",children:te.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:ee=>h(ee.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${ae==="global"?" active":""}`,onClick:()=>{ye("global"),o?.("global")},role:"radio","aria-checked":ae==="global"?"true":"false",disabled:!!e?.scope,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:"Global scope",children:[t.jsx(Io,{size:12}),"Global"]}),t.jsxs("button",{type:"button",className:`routine-scope-btn${ae==="project"?" active":""}`,onClick:()=>{ye("project"),o?.("project")},role:"radio","aria-checked":ae==="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(Un,{size:12}),"Project"]})]}),t.jsx("small",{children:!r&&!e?.scope?"No active project. Routines will be created at global scope.":ae==="project"&&r?"This routine will be scoped to the current project.":"This routine will be created at global scope."}),te.scope&&t.jsx("small",{className:"field-error",children:te.scope})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Trigger Type"}),t.jsxs("div",{className:"routine-trigger-type-selector",role:"radiogroup","aria-label":"Trigger type",children:[t.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="cron"?" active":""}`,onClick:()=>p("cron"),role:"radio","aria-checked":g==="cron",children:[t.jsx(Uh,{size:14}),"Cron"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="webhook"?" active":""}`,onClick:()=>p("webhook"),role:"radio","aria-checked":g==="webhook",children:[t.jsx(Zh,{size:14}),"Webhook"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="api"?" active":""}`,onClick:()=>p("api"),role:"radio","aria-checked":g==="api",children:[t.jsx(Hh,{size:14}),"API"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="manual"?" active":""}`,onClick:()=>p("manual"),role:"radio","aria-checked":g==="manual",children:[t.jsx(Bn,{size:14}),"Manual"]})]})]}),g==="cron"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-frequency",children:"Frequency"}),t.jsx("select",{id:"routine-frequency",value:v,onChange:ee=>Xe(ee.target.value),children:Object.entries(DR).map(([ee,Ge])=>t.jsx("option",{value:ee,children:Ge},ee))}),t.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),t.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:f,onChange:ee=>x(ee.target.value),disabled:v!=="custom","aria-invalid":!!te.cronExpression,"aria-describedby":te.cronExpression?he:void 0}),te.cronExpression?t.jsx("small",{id:he,className:"field-error",children:te.cronExpression}):t.jsx("small",{children:v==="custom"?t.jsxs(t.Fragment,{children:["min hour day month weekday — ",t.jsx("a",{href:"https://crontab.guru",target:"_blank",rel:"noopener noreferrer",children:"crontab.guru"})]}):`Auto-filled from preset: ${f}`})]}),g==="webhook"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-path",children:"Webhook Path"}),t.jsx("input",{id:"routine-webhook-path",type:"text",placeholder:"/trigger/my-routine",value:y,onChange:ee=>S(ee.target.value),"aria-invalid":!!te.webhookPath,"aria-describedby":te.webhookPath?Me:void 0}),te.webhookPath?t.jsx("small",{id:Me,className:"field-error",children:te.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:j,onChange:ee=>R(ee.target.value)}),t.jsx("small",{children:"HMAC secret for signature verification. Leave empty for unauthenticated webhooks."})]})]}),g==="api"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-endpoint",children:"API Endpoint"}),t.jsx("input",{id:"routine-endpoint",type:"text",placeholder:"/api/routine/my-routine",value:k,onChange:ee=>M(ee.target.value),"aria-invalid":!!te.endpoint,"aria-describedby":te.endpoint?We:void 0}),te.endpoint?t.jsx("small",{id:We,className:"field-error",children:te.endpoint}):t.jsx("small",{children:"API endpoint path that triggers this routine"})]}),g==="manual"&&t.jsx("div",{className:"form-group",children:t.jsx("small",{className:"routine-trigger-info",children:"This routine will be triggered manually via the dashboard or API."})}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Action Mode"}),t.jsxs("div",{className:"schedule-mode-toggle",role:"radiogroup","aria-label":"Action mode",children:[t.jsx("button",{type:"button",className:`schedule-mode-btn${D==="simple"?" active":""}`,onClick:()=>U("simple"),role:"radio","aria-checked":D==="simple",children:"Simple"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${D==="advanced"?" active":""}`,onClick:()=>U("advanced"),role:"radio","aria-checked":D==="advanced",children:"Multi-Step"})]}),t.jsx("small",{children:D==="simple"?"Run one command, prompt, or task creation action":"Run multiple actions sequentially"})]}),D==="simple"?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Action Type"}),t.jsxs("div",{className:"schedule-mode-toggle",role:"radiogroup","aria-label":"Action type",children:[t.jsx("button",{type:"button",className:`schedule-mode-btn${Y==="command"?" active":""}`,onClick:()=>X("command"),role:"radio","aria-checked":Y==="command",children:"Command"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${Y==="ai-prompt"?" active":""}`,onClick:()=>X("ai-prompt"),role:"radio","aria-checked":Y==="ai-prompt",children:"AI Prompt"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${Y==="create-task"?" active":""}`,onClick:()=>X("create-task"),role:"radio","aria-checked":Y==="create-task",children:"Create Task"})]})]}),Y==="command"?t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-command",children:"Command"}),t.jsx("input",{id:"routine-command",type:"text",placeholder:"e.g. npx runfusion.ai backup --create",value:_,onChange:ee=>I(ee.target.value),"aria-invalid":!!te.command,"aria-describedby":te.command?Re:void 0}),te.command?t.jsx("small",{id:Re,className:"field-error",children:te.command}):t.jsx("small",{children:"Shell command to execute."})]}):Y==="ai-prompt"?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-prompt",children:"Prompt"}),t.jsx("textarea",{id:"routine-prompt",placeholder:"e.g. Summarize recent activity and create action items",value:le,onChange:ee=>Se(ee.target.value),rows:3,"aria-invalid":!!te.prompt,"aria-describedby":te.prompt?ot:void 0}),te.prompt?t.jsx("small",{id:ot,className:"field-error",children:te.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(Hn,{id:"routine-model",label:"Model",models:Qe,value:Fe,onChange:tt,placeholder:"Use default",disabled:Ke}),Pe&&t.jsx("small",{className:"field-error",children:Pe}),te.model&&t.jsx("small",{id:ce,className:"field-error",children:te.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:ee=>ge(ee.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:se,onChange:ee=>fe(ee.target.value),rows:4,"aria-invalid":!!te.taskDescription,"aria-describedby":te.taskDescription?J:void 0}),te.taskDescription?t.jsx("small",{id:J,className:"field-error",children:te.taskDescription}):t.jsx("small",{children:"Describes the task that will be created."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-column",children:"Target Column"}),t.jsxs("select",{id:"routine-task-column",value:de,onChange:ee=>xe(ee.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(Hn,{id:"routine-task-model",label:"Executor Model",models:Qe,value:Fe,onChange:tt,placeholder:"Use default",disabled:Ke}),Pe&&t.jsx("small",{className:"field-error",children:Pe}),te.model&&t.jsx("small",{id:ce,className:"field-error",children:te.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx($R,{steps:T,onChange:w,onEditingChange:G}),te.steps&&t.jsx("small",{className:"field-error",children:te.steps}),te.stepsEditing&&t.jsx("small",{className:"field-error",children:te.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:me,onChange:ee=>ue(Number(ee.target.value)),"aria-invalid":!!te.timeoutMs,"aria-describedby":te.timeoutMs?ve:void 0}),te.timeoutMs?t.jsx("small",{id:ve,className:"field-error",children:te.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:C,onChange:ee=>L(ee.target.value),children:BR.map(ee=>t.jsx("option",{value:ee.value,children:ee.label},ee.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:A,onChange:ee=>P(ee.target.value),children:UR.map(ee=>t.jsx("option",{value:ee.value,children:ee.label},ee.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:O,onChange:ee=>V(ee.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 HR=3e4;function qR({onClose:e,addToast:n,projectId:s}){const[i,r]=a.useState(()=>s?"project":"global"),[o,l]=a.useState([]),[c,u]=a.useState("list"),[d,m]=a.useState(),[h,g]=a.useState(null),[p,f]=a.useState({}),x=a.useRef(null);ni(x,!0,"fusion:automation-modal-size");const v=a.useMemo(()=>({scope:i,projectId:i==="project"?s:void 0}),[i,s]),b=a.useCallback(async()=>{try{const $=await dj(v);l($),f(E=>{const D={...E};for(const U of $){const Y=D[U.id];if(!Y||!U.lastRunResult)continue;const X=U.lastRunResult;X.success===Y.success&&(X.output||"")===Y.output&&(X.error||"")===(Y.error||"")&&delete D[U.id]}return D})}catch($){n(je($)||"Failed to load routines","error")}},[n,v]);a.useEffect(()=>{b()},[b]),a.useEffect(()=>{const $=setInterval(()=>{b()},HR);return()=>clearInterval($)},[b]),a.useEffect(()=>{const $=E=>{E.key==="Escape"&&(c!=="list"?(u("list"),m(void 0)):e())};return document.addEventListener("keydown",$),()=>document.removeEventListener("keydown",$)},[e,c]);const y=Si(e),S=a.useCallback(async $=>{try{await uj($,v),n("Routine created","success"),u("list"),await b()}catch(E){n(je(E)||"Failed to create routine","error")}},[n,b,v]),j=a.useCallback($=>{m($),u("edit")},[]),R=a.useCallback(async $=>{if(d)try{await Jd(d.id,$,v),n("Routine updated","success"),u("list"),m(void 0),await b()}catch(E){n(je(E)||"Failed to update routine","error")}},[d,n,b,v]),k=a.useCallback(async $=>{try{await mj($.id,v),n(`Deleted "${$.name}"`,"success"),await b()}catch(E){n(je(E)||"Failed to delete routine","error")}},[n,b,v]),M=a.useCallback(async $=>{g($.id);try{const{result:E}=await hj($.id,v);f(D=>({...D,[$.id]:{output:E.output||"",error:E.error,success:E.success}})),E.success?n(`"${$.name}" completed successfully`,"success"):n(`"${$.name}" failed: ${E.error||"Unknown error"}`,"error"),await b()}catch(E){n(je(E)||"Failed to run routine","error")}finally{g(null)}},[n,b,v]),C=a.useCallback(async $=>{try{await Jd($.id,{enabled:!$.enabled},v),n(`"${$.name}" ${$.enabled?"disabled":"enabled"}`,"success"),await b()}catch(E){n(je(E)||"Failed to toggle routine","error")}},[n,b,v]),L=a.useCallback(()=>{u("list"),m(void 0)},[]);a.useEffect(()=>{c!=="list"&&f({})},[c]);const A=a.useCallback($=>{r($),u("list"),m(void 0),f({})},[]),P=()=>c==="create"?t.jsx(uh,{onSubmit:S,onCancel:L,scope:i,projectId:s}):c==="edit"&&d?t.jsx(uh,{routine:d,onSubmit:R,onCancel:L,scope:i,projectId:s}):o.length===0?t.jsxs("div",{className:"routine-empty-state",children:[t.jsx(Bn,{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(en,{size:14}),"Create your first automation"]})]}):t.jsx("div",{className:"routine-list",children:o.map($=>t.jsx(RR,{routine:$,onEdit:j,onDelete:k,onRun:M,onToggle:C,running:h===$.id,lastRunOutput:p[$.id]??null},$.id))}),O=()=>P(),V=c==="list"&&o.length>0;return t.jsx("div",{className:"modal-overlay open",...y,children:t.jsxs("div",{ref:x,className:"modal modal-lg automation-modal",role:"dialog","aria-modal":"true","aria-labelledby":"schedules-modal-title",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(Bn,{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(Ut,{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:()=>A("global"),"aria-pressed":i==="global",title:"Global (user-level) automations",children:[t.jsx(Io,{size:14}),"Global"]}),t.jsxs("button",{type:"button",className:`scope-btn${i==="project"?" active":""}`,onClick:()=>A("project"),"aria-pressed":i==="project",title:"Project-scoped automations",children:[t.jsx(Un,{size:14}),"Project"]})]}),t.jsxs("span",{className:"scheduling-count",children:[t.jsx(Bn,{size:14}),o.length," automation",o.length===1?"":"s"]})]}),t.jsx("div",{className:"scheduling-toolbar-right",children:V&&t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>u("create"),"aria-label":"Create new automation",children:[t.jsx(en,{size:14}),"New Automation"]})})]}),t.jsx("div",{className:"schedule-modal-content",id:"scheduled-tasks-content",children:O()})]})})}const VR=3e4,qc=new Map,nc=new Map;function mh(e){return e??"default"}function hh(e){const n=qc.get(e);return n?Date.now()>=n.expiresAt?(qc.delete(e),null):n:null}function WR(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 KR(e){const n=nc.get(e);if(n)return n;const s=xr().then(({providers:i,ghCli:r})=>{const l={...WR(i,r),ghCli:r,expiresAt:Date.now()+VR};return qc.set(e,l),l}).finally(()=>{nc.delete(e)});return nc.set(e,s),s}function ig(e){const n=mh(e),s=hh(n),[i,r]=a.useState(s?.hasAiProvider??!1),[o,l]=a.useState(s?.hasGithub??!1),[,c]=a.useState(s?.ghCli),[u,d]=a.useState(s==null),m=a.useRef(!!s);return a.useEffect(()=>{let h=!1;const g=mh(e),p=hh(g);if(p)return r(p.hasAiProvider),l(p.hasGithub),c(p.ghCli),d(!1),m.current=!0,()=>{h=!0};m.current=!1;async function f(){!m.current&&d(!0);try{const v=await KR(g);if(h)return;r(v.hasAiProvider),l(v.hasGithub),c(v.ghCli)}catch{}finally{h||(m.current=!0,d(!1))}}return f(),()=>{h=!0}},[e]),a.useMemo(()=>({hasAiProvider:i,hasGithub:o,loading:u,hasWarnings:!i||!o}),[i,o,u])}function ag({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(Ut,{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 GR({isOpen:e,onClose:n,projectId:s,tasks:i,onCreateTask:r,addToast:o,onPlanningMode:l,onSubtaskBreakdown:c}){const{confirm:u}=Hs(),[d,m]=a.useState(""),[h,g]=a.useState([]),[p,f]=a.useState([]),[x,v]=a.useState(!1),[b,y]=a.useState(""),[S,j]=a.useState(""),[R,k]=a.useState(""),[M,C]=a.useState(""),[L,A]=a.useState(""),[P,O]=a.useState("default"),[V,$]=a.useState(!1),[E,D]=a.useState([]),[U,Y]=a.useState(!1),[X,_]=a.useState(void 0),[I,T]=a.useState(ys),[w,q]=a.useState(void 0),[G,me]=a.useState(null),[ue,le]=a.useState([]),[Se,F]=a.useState(!1),[ge,se]=a.useState(!1),fe=a.useRef(null),[de,xe]=a.useState(!1),[ie,Ee]=a.useState(""),De=a.useRef(null),{hasAiProvider:qe,hasGithub:Qe,loading:Je}=ig(s),{nodes:Ke}=qo(),it=a.useCallback(Ne=>{Y(!0),D(Ne)},[]),Pe=a.useCallback(()=>{Y(!1)},[]),Ve=a.useCallback(async()=>{if(ue.length>0){F(!0);return}se(!0);try{const Ne=await Ma(void 0,s);le(Ne),F(!0)}catch(Ne){const oe=je(Ne);o(oe?`Failed to load agents: ${oe}`:"Failed to load agents","error"),F(!1)}finally{se(!1)}},[ue.length,s,o]);a.useEffect(()=>{if(!Se)return;const Ne=oe=>{fe.current&&!fe.current.contains(oe.target)&&F(!1)};return document.addEventListener("mousedown",Ne),()=>document.removeEventListener("mousedown",Ne)},[Se]),a.useEffect(()=>{if(!de)return;const Ne=oe=>{De.current&&!De.current.contains(oe.target)&&(xe(!1),Ee(""))};return document.addEventListener("mousedown",Ne),()=>document.removeEventListener("mousedown",Ne)},[de]);const ae=i.filter(Ne=>!h.includes(Ne.id)).sort((Ne,oe)=>{const Te=oe.createdAt.localeCompare(Ne.createdAt);if(Te!==0)return Te;const he=parseInt(Ne.id.slice(Ne.id.lastIndexOf("-")+1),10)||0;return(parseInt(oe.id.slice(oe.id.lastIndexOf("-")+1),10)||0)-he}),ye=ie?ae.filter(Ne=>Ne.id.toLowerCase().includes(ie.toLowerCase())||Ne.title&&Ne.title.toLowerCase().includes(ie.toLowerCase())||Ne.description&&Ne.description.toLowerCase().includes(ie.toLowerCase())):ae,te=(Ne,oe)=>Ne.length>oe?Ne.slice(0,oe)+"…":Ne;a.useEffect(()=>{const Ne=d.trim()!==""||h.length>0||p.length>0||b!==""||S!==""||R!==""||M!==""||E.length>0||G!==null||X!==void 0||I!==ys||w!==void 0;$(Ne)},[d,h,p,b,S,R,M,E,G,X,I,w]);const Ae=a.useCallback(async()=>{V&&!await u({title:"Discard Changes",message:"You have unsaved changes. Discard them?",danger:!0})||(p.forEach(Ne=>URL.revokeObjectURL(Ne.previewUrl)),f([]),m(""),g([]),y(""),j(""),k(""),C(""),A(""),O("default"),D([]),Y(!1),me(null),F(!1),_(void 0),T(ys),q(void 0),$(!1),n())},[V,n,p,u]),Le=a.useCallback(async()=>{const Ne=d.trim();if(!(!Ne||x)){v(!0);try{const oe=b.indexOf("/"),Te=S.indexOf("/"),he=R.indexOf("/"),Me=await r({title:void 0,description:Ne,column:"triage",dependencies:h.length?h:void 0,enabledWorkflowSteps:U?E.length>0?E:[]:void 0,...G?{assignedAgentId:G}:{},modelPresetId:P==="preset"&&L||void 0,modelProvider:b&&oe!==-1?b.slice(0,oe):void 0,modelId:b&&oe!==-1?b.slice(oe+1):void 0,validatorModelProvider:S&&Te!==-1?S.slice(0,Te):void 0,validatorModelId:S&&Te!==-1?S.slice(Te+1):void 0,planningModelProvider:R&&he!==-1?R.slice(0,he):void 0,planningModelId:R&&he!==-1?R.slice(he+1):void 0,thinkingLevel:M!==""?M:void 0,reviewLevel:X,priority:I,nodeId:w});if(p.length>0){const We=[];for(const Re of p)try{await gr(Me.id,Re.file,s)}catch{We.push(Re.file.name)}We.length>0&&o(`Failed to upload: ${We.join(", ")}`,"error")}p.forEach(We=>URL.revokeObjectURL(We.previewUrl)),f([]),m(""),g([]),y(""),j(""),k(""),C(""),A(""),O("default"),D([]),Y(!1),me(null),F(!1),_(void 0),T(ys),q(void 0),o(`Created ${Me.id}`,"success"),n()}catch(oe){o(je(oe)||"Failed to create task","error")}finally{v(!1)}}},[d,h,p,b,S,R,M,x,r,o,n,s,P,L,E,U,G,X,I,w]),pe=a.useCallback(Ne=>{Ne.key==="Escape"&&(Ne.preventDefault(),Ae())},[Ae]),Fe=(G?ue.find(Ne=>Ne.id===G):void 0)?.name??G,tt=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:De,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>xe(Ne=>!Ne),disabled:x,"data-testid":"dep-trigger",children:h.length>0?`${h.length} selected`:"Add dependencies"}),de&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:ie,onChange:Ne=>Ee(Ne.target.value),onClick:Ne=>Ne.stopPropagation()}),ye.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):ye.map(Ne=>t.jsxs("div",{className:`dep-dropdown-item${h.includes(Ne.id)?" selected":""}`,onClick:()=>{g(h.includes(Ne.id)?h.filter(oe=>oe!==Ne.id):[...h,Ne.id]),xe(!1),Ee("")},onMouseDown:oe=>oe.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:Ne.id}),t.jsx("span",{className:"dep-dropdown-title",children:te(Ne.title||Ne.description||Ne.id,30)})]},Ne.id))]})]}),h.length>0&&t.jsx("div",{className:"selected-deps",children:h.map(Ne=>t.jsxs("span",{className:"dep-chip",children:[Ne,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>g(h.filter(oe=>oe!==Ne)),disabled:x,children:"×"})]},Ne))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Assign Agent"}),t.jsxs("div",{className:"agent-trigger-wrap",ref:fe,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{Se?F(!1):Ve()},disabled:x,"data-testid":"new-task-agent-button",children:[t.jsx(yn,{size:12,style:{verticalAlign:"middle"}}),Fe?` ${Fe}`:" Assign agent"]}),Se&&t.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:Ne=>Ne.preventDefault(),children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),ge&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!ge&&ue.filter(Ne=>Ne.state!=="terminated").map(Ne=>t.jsxs("div",{className:`dep-dropdown-item${G===Ne.id?" selected":""}`,onMouseDown:oe=>oe.preventDefault(),onClick:()=>{me(Ne.id===G?null:Ne.id),F(!1)},"data-testid":`agent-option-${Ne.id}`,children:[t.jsx(yn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:Ne.role}),t.jsx("span",{className:"dep-dropdown-title",children:Ne.name})]},Ne.id)),!ge&&ue.filter(Ne=>Ne.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),G&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:Ne=>Ne.preventDefault(),onClick:()=>{me(null),F(!1)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return e?t.jsx("div",{className:"modal-overlay open",onClick:Ae,onKeyDown:pe,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:Ne=>Ne.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:"New Task"}),t.jsx("button",{className:"modal-close",onClick:Ae,disabled:x,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!Je&&t.jsx(ag,{hasAiProvider:qe,hasGithub:Qe}),t.jsx(Jf,{mode:"create",description:d,onDescriptionChange:m,dependencies:h,onDependenciesChange:g,executorModel:b,onExecutorModelChange:y,validatorModel:S,onValidatorModelChange:j,presetMode:P,onPresetModeChange:O,selectedPresetId:L,onSelectedPresetIdChange:A,selectedWorkflowSteps:E,onWorkflowStepsChange:it,onDefaultOnApplied:Pe,pendingImages:p,onImagesChange:f,tasks:i,projectId:s,disabled:x,addToast:o,isActive:e,onPlanningMode:l,onSubtaskBreakdown:c,onClose:Ae,planningModel:R,onPlanningModelChange:k,thinkingLevel:M,onThinkingLevelChange:C,reviewLevel:X,onReviewLevelChange:_,priority:I,onPriorityChange:T,nodeId:w,onNodeIdChange:q,nodeOptions:Ke,renderBelowPrimary:tt,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:Ae,disabled:x,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Le,disabled:!d.trim()||x,children:x?"Creating...":"Create Task"})]})]})}):null}function li(e){if(!Number.isFinite(e)||e<0)return"—";const n=e/(1024*1024);return n<1024?`${n.toFixed(0)} MB`:`${(n/1024).toFixed(2)} GB`}function ph(e,n){return!Number.isFinite(e)||!Number.isFinite(n)||n<=0?"—":`${(e/n*100).toFixed(1)}%`}function JR(e,n){if(n<=0)return"normal";const s=e/n;return s>=.85?"critical":s>=.65?"warning":"normal"}function YR(e,n){if(n<=0)return"normal";const s=e/n;return s>=.5?"critical":s>=.25?"warning":"normal"}function QR(e,n){if(n<=0)return"normal";const s=e/n;return s>=.9?"critical":s>=.75?"warning":"normal"}function sc(e){return e==="critical"?"system-stats-modal__value--critical":e==="warning"?"system-stats-modal__value--warning":""}function XR(e){if(!e)return"Not yet";const n=new Date(e);return Number.isNaN(n.getTime())?"Not yet":n.toLocaleString()}function ZR({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,g]=a.useState(90),[p,f]=a.useState(!1),[x,v]=a.useState(!1),[b,y]=a.useState(null),[S,j]=a.useState(null),[R,k]=a.useState(null),M=a.useCallback(async I=>{l(!0);try{const T=await Fj(s);r(T),u(null),k(Date.now()),I?.preserveKillResult||y(null)}catch(T){u(T instanceof Error?T.message:"Failed to load system stats")}finally{l(!1)}},[s]);a.useEffect(()=>{if(!e)return;M();const I=window.setInterval(()=>{M()},5e3);return()=>{window.clearInterval(I)}},[e,M]),a.useEffect(()=>{if(!e)return;(async()=>{try{const T=await Gi();m(T.vitestAutoKillEnabled??!0),g(T.vitestKillThresholdPct??90),j(null)}catch(T){j(T instanceof Error?T.message:"Failed to load vitest settings")}})()},[e]),a.useEffect(()=>{if(!e)return;const I=T=>{T.key==="Escape"&&n()};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[e,n]);const C=a.useMemo(()=>{if(!i)return[];const I=i.systemStats,T=sc(JR(I.heapUsed,I.heapLimit)),w=sc(YR(I.rss,I.systemTotalMem));return[{label:"RSS",value:li(I.rss),detail:ph(I.rss,I.systemTotalMem),className:w},{label:"Heap Used",value:li(I.heapUsed),detail:`of ${li(I.heapTotal)}`,className:T},{label:"Heap Limit",value:li(I.heapLimit),detail:"V8 limit"},{label:"External",value:li(I.external)},{label:"Array Buffers",value:li(I.arrayBuffers)}]},[i]),L=a.useCallback(async I=>{m(I);try{await ln({vitestAutoKillEnabled:I}),j(null)}catch(T){j(T instanceof Error?T.message:"Failed to save vitest settings")}},[]),A=a.useCallback(async I=>{const T=Math.min(99,Math.max(50,Number.isFinite(I)?Math.round(I):90));g(T);try{await ln({vitestKillThresholdPct:T}),j(null)}catch(w){j(w instanceof Error?w.message:"Failed to save vitest settings")}},[]),P=a.useCallback(async()=>{if(!p){if(!x){v(!0);return}f(!0);try{const I=await Oj(s);y(I),v(!1),await M({preserveKillResult:!0})}catch(I){u(I instanceof Error?I.message:"Failed to kill vitest processes")}finally{f(!1)}}},[x,p,M,s]);if(!e)return null;const O=i?.systemStats,V=o&&!!i,$=R?`Updated ${new Date(R).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`:"Waiting for first update",E=i?.taskStats,D=O?O.systemTotalMem-O.systemFreeMem:0,U=O?sc(QR(D,O.systemTotalMem)):"",Y=i?.vitestProcessCount,X=b?b.killed>0?"system-stats-modal__kill-result system-stats-modal__kill-result--success":"system-stats-modal__kill-result system-stats-modal__kill-result--error":"",_=XR(i?.vitestLastAutoKillAt);return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"system-stats-modal-title",onClick:I=>{I.target===I.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(pr,{}),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(En,{size:16,className:V?"system-stats-modal__refresh--spinning":void 0})}),t.jsx("button",{type:"button",className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Ut,{})})]})]}),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:C.map(I=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:I.label}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${I.className}`.trim(),children:I.value}),I.detail?t.jsx("span",{className:"system-stats-modal__detail",children:I.detail}):null]})]},I.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:O?.loadAvg.map(I=>I.toFixed(2)).join(" ")??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Cores"}),t.jsx("dd",{children:O?.cpuCount??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Platform"}),t.jsx("dd",{children:O?.platform??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Node"}),t.jsx("dd",{children:O?.nodeVersion??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"PID"}),t.jsx("dd",{children:O?.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",children:[t.jsx("dt",{children:"Memory Used"}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${U}`.trim(),children:O?li(D):"—"}),t.jsx("span",{className:"system-stats-modal__detail",children:O?`${ph(D,O.systemTotalMem)} of ${li(O.systemTotalMem)}`:""})]})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Memory Free"}),t.jsx("dd",{children:O?li(O.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:E?.total??0})]}),Object.entries(E?.byColumn??{}).map(([I,T])=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:I}),t.jsx("dd",{children:T})]},I))]})]}),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:E?.agents.idle??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"active"}),t.jsx("dd",{children:E?.agents.active??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"running"}),t.jsx("dd",{children:E?.agents.running??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"error"}),t.jsx("dd",{children:E?.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(zb,{}),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:Y??"—"})]})}),t.jsxs("div",{className:"system-stats-modal__vitest-controls",children:[t.jsx("div",{className:"system-stats-modal__kill-row",children:t.jsxs("button",{type:"button",className:"btn btn-danger",onClick:()=>void P(),disabled:p||Y===0,children:[t.jsx(Ub,{}),t.jsx("span",{children:x?"Confirm Kill?":"Kill Vitest Processes"})]})}),t.jsxs("label",{className:"system-stats-modal__toggle-row",children:[t.jsx("input",{type:"checkbox",checked:d,onChange:I=>{L(I.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:I=>{const T=Number.parseInt(I.target.value,10);A(Number.isNaN(T)?90:T)}}),t.jsx("input",{id:"vitest-threshold-number",type:"number",className:"input",min:50,max:99,value:h,"aria-label":"Kill threshold (%)",onChange:I=>{const T=Number.parseInt(I.target.value,10);A(Number.isNaN(T)?90:T)},onBlur:()=>{A(h)}})]})]}),b&&t.jsxs("p",{className:X,children:["Killed ",b.killed," processes"]}),t.jsxs("p",{className:"system-stats-modal__last-kill",children:["Last auto-kill: ",_]}),S&&t.jsx("p",{className:"system-stats-modal__kill-result system-stats-modal__kill-result--error",children:S})]})]})]}),c&&i&&t.jsxs("div",{className:"system-stats-modal__footer-error",children:["Latest refresh failed: ",c]})]})})}const e4=5e3;function t4(e={}){const{projectId:n,type:s,limit:i=50,autoRefresh:r=!0,useCentralFeed:o=!1}=e,[l,c]=a.useState([]),[u,d]=a.useState(!1),[m,h]=a.useState(null),[g,p]=a.useState(!1),f=a.useRef(null),x=a.useRef(void 0),v=a.useCallback(async()=>{try{d(!0),h(null);let S;o?S=await nu({limit:i,projectId:n,type:s}):S=(await Yd({limit:i,type:s,projectId:n})).map(R=>({...R,projectId:n??"",projectName:""})),c(S),p(S.length===i),S.length>0&&(x.current=S[S.length-1].timestamp)}catch(S){h(S instanceof Error?S.message:"Failed to load activity log")}finally{d(!1)}},[i,n,s,o]),b=a.useCallback(async()=>{if(x.current)try{d(!0);let S;o?S=await nu({limit:i,projectId:n,type:s,since:x.current}):S=(await Yd({limit:i,type:s,since:x.current,projectId:n})).map(R=>({...R,projectId:n??"",projectName:""})),c(j=>[...j,...S]),p(S.length===i),S.length>0&&(x.current=S[S.length-1].timestamp)}catch(S){h(S instanceof Error?S.message:"Failed to load more entries")}finally{d(!1)}},[i,n,s,o]),y=a.useCallback(()=>{c([]),p(!1),x.current=void 0},[]);return a.useEffect(()=>{v()},[v]),a.useEffect(()=>{if(r)return f.current=setInterval(()=>{v()},e4),()=>{f.current&&(clearInterval(f.current),f.current=null)}},[r,v]),{entries:l,loading:u,error:m,refresh:v,clear:y,hasMore:g,loadMore:b}}const ic={"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"},n4={"task:created":t.jsx(en,{size:14,className:"activity-icon created"}),"task:moved":t.jsx(Nr,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx(En,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(Ut,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx(fn,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(Sr,{size:14,className:"activity-icon failed"}),"settings:updated":t.jsx(or,{size:14,className:"activity-icon settings"})};function s4(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 i4({isOpen:e,onClose:n,tasks:s,onOpenTaskDetail:i,projectId:r,projects:o=[],onProjectFilterChange:l,currentProject:c}){const[u,d]=a.useState("all"),[m,h]=a.useState(r||"all"),[g,p]=a.useState(!1);a.useEffect(()=>{h(r||"all")},[r]);const f=u==="all"?void 0:u,x=m==="all"?void 0:m,v=!c&&o.length>0,{entries:b,loading:y,error:S,refresh:j,hasMore:R}=t4({projectId:x,type:f,limit:100,autoRefresh:e,useCentralFeed:v}),k=b.map(P=>({id:P.id,timestamp:P.timestamp,type:P.type,taskId:P.taskId,taskTitle:P.taskTitle,details:P.details,metadata:P.metadata,projectId:P.projectId,projectName:P.projectName})),M=async()=>{try{await pj(),j(),p(!1)}catch{p(!1)}},C=P=>{i&&i(P)},L=P=>{h(P),l?.(P==="all"?void 0:P)};a.useEffect(()=>{if(!e)return;const P=O=>{O.key==="Escape"&&(g?p(!1):n())};return document.addEventListener("keydown",P),()=>document.removeEventListener("keydown",P)},[e,n,g]);const A=u!=="all"||m!=="all";return e?t.jsx("div",{className:"modal-overlay open",onClick:P=>{P.target===P.currentTarget&&n()},role:"dialog","aria-modal":"true","data-testid":"activity-log-modal-overlay",children:t.jsxs("div",{className:"modal modal-lg activity-log-modal","data-testid":"activity-log-modal",children:[t.jsxs("div",{className:"modal-header activity-log-header",children:[t.jsxs("div",{className:"activity-log-title",children:[t.jsx(hr,{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(Un,{size:14}),t.jsxs("select",{value:m,onChange:P=>L(P.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[t.jsx("option",{value:"all",children:"All Projects"}),o.map(P=>t.jsx("option",{value:P.id,children:P.name},P.id))]})]}),t.jsxs("div",{className:"activity-log-filter",children:[t.jsx(po,{size:14}),t.jsxs("select",{value:u,onChange:P=>d(P.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:"All Events"}),Object.entries(ic).map(([P,O])=>t.jsx("option",{value:P,children:O},P))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>j(),title:"Refresh","data-testid":"activity-refresh",children:y?t.jsx(rt,{size:14,className:"spin"}):t.jsx(En,{size:14})}),k.length>0&&t.jsx("button",{className:"activity-log-clear",onClick:()=>p(!0),title:"Clear Log","data-testid":"activity-clear",children:t.jsx(Zt,{size:14})})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",title:"Close","data-testid":"activity-close",children:"×"})]}),A&&t.jsxs("div",{className:"activity-log-active-filters",children:[t.jsx("span",{className:"activity-log-filter-label",children:"Active filters:"}),m!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Project: ",o.find(P=>P.id===m)?.name||m]}),u!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",ic[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:[S&&t.jsxs("div",{className:"activity-log-error","data-testid":"activity-error",children:[t.jsx(as,{size:16}),t.jsx("span",{children:S})]}),k.length===0&&!y&&!S&&t.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[t.jsx(hr,{size:48,className:"activity-log-empty-icon"}),t.jsx("p",{children:A?"No activity matches the current filters":"No activity recorded yet"}),A&&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:k.map(P=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:n4[P.type]}),t.jsxs("div",{className:"activity-log-entry-content",children:[t.jsxs("div",{className:"activity-log-entry-header",children:[t.jsx("span",{className:"activity-log-entry-type",children:ic[P.type]}),t.jsx("span",{className:"activity-log-entry-time",children:s4(P.timestamp)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[P.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>C(P.taskId),"data-testid":"activity-task-link",children:P.taskId}),P.taskTitle&&t.jsx("span",{className:"activity-log-task-title",children:P.taskTitle}),t.jsx("span",{className:"activity-log-entry-text",children:P.details})]}),P.metadata&&Object.keys(P.metadata).length>0&&t.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof P.metadata.from=="string"&&typeof P.metadata.to=="string"&&t.jsxs("span",{className:"activity-log-metadata-item",children:[P.metadata.from," → ",P.metadata.to]}),typeof P.metadata.merged=="boolean"&&t.jsx("span",{className:`activity-log-metadata-item ${P.metadata.merged?"success":"error"}`,children:P.metadata.merged?"Merged":"Not merged"})]})]})]},P.id))}),R&&!y&&t.jsx("button",{className:"activity-log-load-more",onClick:j,"data-testid":"activity-load-more",children:"Load More"}),y&&k.length>0&&t.jsx("div",{className:"activity-log-loading",children:t.jsx(rt,{size:20,className:"spin"})})]}),g&&t.jsx("div",{className:"activity-log-confirm-overlay",children:t.jsxs("div",{className:"activity-log-confirm-dialog",children:[t.jsx("h3",{children:"Clear Activity Log?"}),t.jsx("p",{children:"This will permanently delete all activity log entries. This action cannot be undone."}),t.jsxs("div",{className:"activity-log-confirm-actions",children:[t.jsx("button",{className:"activity-log-confirm-cancel",onClick:()=>p(!1),children:"Cancel"}),t.jsx("button",{className:"activity-log-confirm-clear",onClick:M,children:"Clear Log"})]})]})})]})}):null}const Xa=[{id:"status",label:"Status",icon:Yh},{id:"changes",label:"Changes",icon:qh},{id:"commits",label:"Commits",icon:mr},{id:"branches",label:"Branches",icon:Zs},{id:"worktrees",label:"Worktrees",icon:Ux},{id:"stashes",label:"Stashes",icon:Ro},{id:"remotes",label:"Remotes",icon:Kh}];function fh({status:e}){switch(e){case"added":case"untracked":return t.jsx(wx,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(Vh,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(yx,{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(Sx,{size:14,className:"gm-file-icon"})}}function gh({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 a4(e){return a.useCallback(async(n,s)=>{try{await navigator.clipboard.writeText(n),e(`Copied ${s||"to clipboard"}`,"success")}catch{e("Failed to copy","error")}},[e])}function wa(e){if(!e)return"—";const n=new Date(e);if(isNaN(n.getTime()))return"—";const i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4);if(r<1)return"just now";if(r<60)return`${r}m ago`;const o=Math.floor(r/60);if(o<24)return`${o}h ago`;const l=Math.floor(o/24);return l<30?`${l}d ago`:n.toLocaleDateString()}function r4({isOpen:e,onClose:n,tasks:s,addToast:i,projectId:r}){const o=Hs(),[l,c]=a.useState("status"),[u,d]=a.useState(!1),[m,h]=a.useState(null),g=a.useRef(null);ni(g,e,"fusion:git-modal-size");const p=Si(n),f=a4(i),[x,v]=a.useState(null),[b,y]=a.useState([]),[S,j]=a.useState(new Set),[R,k]=a.useState(""),[M,C]=a.useState(!1),[L,A]=a.useState(null),[P,O]=a.useState(!1),[V,$]=a.useState(null),[E,D]=a.useState(null),U=a.useRef(0),[Y,X]=a.useState([]),[_,I]=a.useState(null),[T,w]=a.useState(null),[q,G]=a.useState(!1),[me,ue]=a.useState(20),[le,Se]=a.useState(""),[F,ge]=a.useState([]),[se,fe]=a.useState(""),[de,xe]=a.useState(""),[ie,Ee]=a.useState(""),[De,qe]=a.useState(null),[Qe,Je]=a.useState([]),[Ke,it]=a.useState(!1),[Pe,Ve]=a.useState(null),[ae,ye]=a.useState(null),[te,Ae]=a.useState(!1),[Le,pe]=a.useState([]),[_e,Fe]=a.useState([]),[tt,Ne]=a.useState(""),[oe,Te]=a.useState(null),[he,Me]=a.useState(null),[We,Re]=a.useState(null),ot=a.useCallback(async()=>{if(e){d(!0),h(null);try{switch(l){case"status":{const H=await Os(r);v(H);break}case"changes":{const[H,be]=await Promise.all([Os(r),na(r)]);v(H),y(be),j(new Set),D(null),A(null),$(null);break}case"commits":{const H=await yy(me,r);X(H);break}case"branches":{const[H,be]=await Promise.all([za(r),Os(r)]);ge(H),v(be);break}case"worktrees":{const H=await Ny(r);pe(H);break}case"stashes":{const H=await Hr(r);Fe(H);break}case"remotes":{const H=await Os(r);v(H);break}}}catch(H){h(je(H)||"Failed to fetch git data"),i(je(H)||"Failed to fetch git data","error")}finally{d(!1)}}},[l,e,me,i,r]);a.useEffect(()=>{e&&ot()},[ot,e]),a.useEffect(()=>{if(!e)return;const H=be=>{if(be.key==="Escape"){n();return}if((be.key==="ArrowUp"||be.key==="ArrowDown")&&be.altKey){be.preventDefault();const re=Xa.findIndex(N=>N.id===l);be.key==="ArrowUp"&&re>0?c(Xa[re-1].id):be.key==="ArrowDown"&&re<Xa.length-1&&c(Xa[re+1].id)}};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[e,n,l]);const J=a.useCallback(async H=>{try{await Vd(H,r),i(`Staged ${H.length} file(s)`,"success");const be=await na(r);y(be),j(new Set),D(null),A(null),$(null)}catch(be){i(je(be)||"Failed to stage files","error")}},[i,r]),ce=a.useCallback(async H=>{try{await Iy(H,r),i(`Unstaged ${H.length} file(s)`,"success");const be=await na(r);y(be),j(new Set),D(null),A(null),$(null)}catch(be){i(je(be)||"Failed to unstage files","error")}},[i,r]),ve=a.useCallback(async H=>{if(await o.confirm({title:"Discard Changes",message:`Discard changes to ${H.length} file(s)? This cannot be undone.`,danger:!0}))try{await $y(H,r),i(`Discarded changes to ${H.length} file(s)`,"success");const[re,N]=await Promise.all([na(r),Os(r)]);y(re),v(N),j(new Set),D(null),A(null),$(null)}catch(re){i(je(re)||"Failed to discard changes","error")}},[i,r,confirm]),Xe=a.useCallback(async H=>{if(H.preventDefault(),!!R.trim()){C(!0);try{const be=await Wd(R.trim(),r);i(`Committed: ${be.hash}`,"success"),k("");const[re,N]=await Promise.all([na(r),Os(r)]);y(re),v(N),D(null),A(null),$(null)}catch(be){i(je(be)||"Failed to commit","error")}finally{C(!1)}}},[R,i,r]),ee=a.useCallback(async()=>{if(R.trim()){C(!0);try{const H=b.filter(W=>!W.staged).map(W=>W.file);H.length>0&&await Vd(H,r);const be=await Wd(R.trim(),r);i(`Committed: ${be.hash}`,"success"),k("");const[re,N]=await Promise.all([na(r),Os(r)]);y(re),v(N),D(null),A(null),$(null)}catch(H){i(je(H)||"Failed to commit","error")}finally{C(!1)}}},[R,b,i,r]),Ge=a.useCallback(async(H,be)=>{D({file:H,staged:be}),O(!0),$(null);const re=U.current+1;U.current=re;try{const N=await Py(H,be,r);if(U.current!==re)return;A(N)}catch(N){if(U.current!==re)return;const W=je(N)||"Failed to load file diff";A(null),$(W),i(W,"error")}finally{U.current===re&&O(!1)}},[i,r]),ct=a.useCallback(H=>{j(be=>{const re=new Set(be);return re.has(H)?re.delete(H):re.add(H),re})},[]),vt=a.useCallback(async H=>{if(_===H){I(null),w(null);return}I(H),G(!0);try{const be=await bo(H,r);w(be)}catch(be){i(je(be)||"Failed to load diff","error"),w(null)}finally{G(!1)}},[_,i,r]),bt=a.useCallback(()=>{ue(H=>Math.min(H+20,100))},[]),ft=a.useMemo(()=>{if(!le.trim())return Y;const H=le.toLowerCase();return Y.filter(be=>be.message.toLowerCase().includes(H)||be.author.toLowerCase().includes(H)||be.shortHash.toLowerCase().includes(H))},[Y,le]),gt=a.useCallback(async H=>{if(H.preventDefault(),!!se.trim()){d(!0);try{await Sy(se.trim(),de.trim()||void 0,r),i(`Created branch ${se}`,"success"),fe(""),xe("");const be=await za(r);ge(be)}catch(be){i(je(be)||"Failed to create branch","error")}finally{d(!1)}}},[se,de,i,r]),_t=a.useCallback(async H=>{d(!0);try{await Cy(H,r),i(`Switched to ${H}`,"success");const[be,re]=await Promise.all([Os(r),za(r)]);v(be),ge(re)}catch(be){i(je(be)||"Failed to checkout branch","error")}finally{d(!1)}},[i,r]),Rt=a.useCallback(async H=>{if(await o.confirm({title:"Delete Branch",message:`Delete branch "${H}"?`,danger:!0})){d(!0);try{await qd(H,void 0,r),i(`Deleted branch ${H}`,"success");const re=await za(r);ge(re)}catch(re){if(je(re).includes("not fully merged")){if(await o.confirm({title:"Force Delete Branch",message:"Branch has unmerged commits. Force delete?",danger:!0}))try{await qd(H,!0,r),i(`Force deleted branch ${H}`,"success");const W=await za(r);ge(W)}catch(W){i(je(W)||"Failed to delete branch","error")}}else i(je(re)||"Failed to delete branch","error")}finally{d(!1)}}},[i,r,confirm]),Ft=a.useMemo(()=>{if(!ie.trim())return F;const H=ie.toLowerCase();return F.filter(be=>be.name.toLowerCase().includes(H))},[F,ie]),wt=a.useCallback(async H=>{if(De===H){qe(null),Je([]),Ve(null),ye(null);return}qe(H),Je([]),Ve(null),ye(null),it(!0);try{const be=await wy(H,10,r);Je(be)}catch{Je([])}finally{it(!1)}},[De,r]),At=a.useCallback(async H=>{if(Pe===H){Ve(null),ye(null);return}Ve(H),ye(null),Ae(!0);try{const be=await bo(H,r);ye(be)}catch{ye(null)}finally{Ae(!1)}},[Pe,r]),qt=a.useCallback(()=>{qe(null),Je([]),Ve(null),ye(null)},[]),zt=a.useCallback(async H=>{H.preventDefault(),Te("create");try{await Ay(tt.trim()||void 0,r),i("Changes stashed","success"),Ne("");const be=await Hr(r);Fe(be)}catch(be){i(je(be)||"Failed to stash changes","error")}finally{Te(null)}},[tt,i,r]),Wt=a.useCallback(async(H,be=!1)=>{Te(`apply-${H}`);try{await Ry(H,be,r),i(be?"Stash popped":"Stash applied","success");const re=await Hr(r);Fe(re)}catch(re){i(je(re)||"Failed to apply stash","error")}finally{Te(null)}},[i,r]),Ot=a.useCallback(async H=>{if(await o.confirm({title:"Drop Stash",message:`Drop stash@{${H}}? This cannot be undone.`,danger:!0})){Te(`drop-${H}`);try{await Ty(H,r),i("Stash dropped","success");const re=await Hr(r);Fe(re)}catch(re){i(je(re)||"Failed to drop stash","error")}finally{Te(null)}}},[i,r,confirm]),Nt=a.useCallback(async()=>{Me("fetch");try{const H=await Ey(void 0,r);Re(H),i(H.message||"Fetch completed",H.fetched?"success":"info");const be=await Os(r);v(be)}catch(H){i(je(H)||"Fetch failed","error")}finally{Me(null)}},[i,r]),Mt=a.useCallback(async()=>{Me("pull");try{const H=await _y(r);Re(H),H.conflict?i("Merge conflict detected. Resolve manually.","error"):i(H.message||"Pull completed","success");const be=await Os(r);v(be)}catch(H){i(je(H)||"Pull failed","error")}finally{Me(null)}},[i,r]),Ct=a.useCallback(async()=>{Me("push");try{const H=await My(r);Re(H),i(H.message||"Push completed","success");const be=await Os(r);v(be)}catch(H){i(je(H)||"Push failed","error")}finally{Me(null)}},[i,r]),Gt=a.useMemo(()=>b.filter(H=>H.staged),[b]),Et=a.useMemo(()=>b.filter(H=>!H.staged),[b]);return e?t.jsx("div",{className:"modal-overlay open",...p,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal gm-modal",ref:g,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h3",{children:[t.jsx(xc,{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:ot,disabled:u,title:"Refresh",children:t.jsx(En,{size:14,className:u?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Ut,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:Xa.map(H=>{const be=H.icon;return t.jsxs("button",{role:"tab","aria-selected":l===H.id,className:`gm-nav-item${l===H.id?" active":""}`,onClick:()=>c(H.id),children:[t.jsx(be,{size:16}),t.jsx("span",{className:"gm-nav-label",children:H.label})]},H.id)})}),t.jsxs("div",{className:"gm-content",role:"tabpanel",children:[u&&t.jsxs("div",{className:"gm-loading",children:[t.jsx(rt,{size:24,className:"spin"}),t.jsx("span",{children:"Loading..."})]}),m&&!u&&t.jsxs("div",{className:"gm-error",children:[t.jsx(as,{size:18}),t.jsx("span",{children:m}),t.jsx("button",{className:"btn btn-sm",onClick:ot,children:"Retry"})]}),l==="status"&&!u&&x&&t.jsx(o4,{status:x,copyToClipboard:f}),l==="changes"&&!u&&t.jsx(l4,{status:x,stagedFiles:Gt,unstagedFiles:Et,selectedFiles:S,toggleFileSelection:ct,onStageFiles:J,onUnstageFiles:ce,onDiscardChanges:ve,onSelectDiffFile:Ge,selectedDiffTarget:E,changeDiff:L,loadingChangeDiff:P,changeDiffError:V,commitMessage:R,setCommitMessage:k,onCommit:Xe,onStageAllAndCommit:ee,committing:M}),l==="commits"&&!u&&t.jsx(c4,{commits:ft,commitSearch:le,setCommitSearch:Se,selectedCommit:_,commitDiff:T,loadingDiff:q,onCommitClick:vt,onLoadMore:bt,canLoadMore:Y.length>=me&&me<100,copyToClipboard:f}),l==="branches"&&!u&&t.jsx(d4,{branches:Ft,branchSearch:ie,setBranchSearch:Ee,newBranchName:se,setNewBranchName:fe,branchBase:de,setBranchBase:xe,onCreateBranch:gt,onCheckoutBranch:_t,onDeleteBranch:Rt,loading:u,allBranches:F,selectedBranch:De,branchCommits:Qe,loadingBranchCommits:Ke,expandedBranchCommit:Pe,branchCommitDiff:ae,loadingBranchCommitDiff:te,onSelectBranch:wt,onBranchCommitClick:At,onCloseBranchDetails:qt}),l==="worktrees"&&!u&&t.jsx(u4,{worktrees:Le}),l==="stashes"&&!u&&t.jsx(m4,{stashes:_e,stashMessage:tt,setStashMessage:Ne,onCreateStash:zt,onApplyStash:Wt,onDropStash:Ot,stashLoading:oe}),l==="remotes"&&!u&&t.jsx(h4,{status:x,remoteLoading:he,lastRemoteResult:We,onFetch:Nt,onPull:Mt,onPush:Ct,addToast:i,projectId:r,copyToClipboard:f})]})]})]})}):null}function o4({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(Zs,{size:14}),t.jsx("span",{children:e.branch})]})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Commit"}),t.jsxs("span",{className:"gm-status-value",children:[t.jsx("code",{className:"gm-hash",children:e.commit}),t.jsx("button",{className:"gm-icon-btn",onClick:()=>n(e.commit,"commit hash"),title:"Copy commit hash",children:t.jsx(Bi,{size:12})})]})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Working Tree"}),t.jsx("span",{className:`gm-status-badge ${e.isDirty?"dirty":"clean"}`,children:e.isDirty?t.jsxs(t.Fragment,{children:[t.jsx(as,{size:12}),"Modified"]}):t.jsxs(t.Fragment,{children:[t.jsx(fn,{size:12}),"Clean"]})})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Remote Sync"}),t.jsxs("span",{className:"gm-status-value",children:[e.ahead>0&&t.jsxs("span",{className:"gm-ahead",title:`${e.ahead} commit(s) ahead`,children:[t.jsx(Fi,{size:12}),e.ahead]}),e.behind>0&&t.jsxs("span",{className:"gm-behind",title:`${e.behind} commit(s) behind`,children:[t.jsx(wr,{size:12}),e.behind]}),e.ahead===0&&e.behind===0&&t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(fn,{size:12}),"Up to date"]})]})]})]})]})}function l4({status:e,stagedFiles:n,unstagedFiles:s,selectedFiles:i,toggleFileSelection:r,onStageFiles:o,onUnstageFiles:l,onDiscardChanges:c,onSelectDiffFile:u,selectedDiffTarget:d,changeDiff:m,loadingChangeDiff:h,changeDiffError:g,commitMessage:p,setCommitMessage:f,onCommit:x,onStageAllAndCommit:v,committing:b}){const y=s.filter(j=>i.has(`unstaged:${j.file}`)),S=n.filter(j=>i.has(`staged:${j.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(Zs,{size:14}),e.branch]}),e.isDirty&&t.jsx("span",{className:"gm-dirty-badge",children:"Modified"})]}),t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Unstaged Changes (",s.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[y.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>o(y.map(j=>j.file)),title:"Stage selected",children:[t.jsx(en,{size:12})," Stage (",y.length,")"]}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>c(y.map(j=>j.file)),title:"Discard selected",children:t.jsx(Sr,{size:12})})]}),s.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>o(s.map(j=>j.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(j=>{const R=d?.file===j.file&&d.staged===!1;return t.jsxs("div",{className:`gm-file-item${R?" active":""}`,onClick:()=>u(j.file,!1),role:"button",tabIndex:0,onKeyDown:k=>{(k.key==="Enter"||k.key===" ")&&(k.preventDefault(),u(j.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:k=>k.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`unstaged:${j.file}`),onChange:()=>r(`unstaged:${j.file}`)})}),t.jsx(fh,{status:j.status}),t.jsx("span",{className:"gm-file-name",title:j.file,children:kr(j.file,40)}),t.jsx(gh,{status:j.status}),t.jsx("button",{className:"gm-icon-btn",onClick:k=>{k.stopPropagation(),o([j.file])},title:"Stage file",children:t.jsx(en,{size:12})})]},`unstaged:${j.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:[S.length>0&&t.jsxs("button",{className:"btn btn-sm",onClick:()=>l(S.map(j=>j.file)),title:"Unstage selected",children:["Unstage (",S.length,")"]}),n.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(n.map(j=>j.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(j=>{const R=d?.file===j.file&&d.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${R?" active":""}`,onClick:()=>u(j.file,!0),role:"button",tabIndex:0,onKeyDown:k=>{(k.key==="Enter"||k.key===" ")&&(k.preventDefault(),u(j.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:k=>k.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`staged:${j.file}`),onChange:()=>r(`staged:${j.file}`)})}),t.jsx(fh,{status:j.status}),t.jsx("span",{className:"gm-file-name",title:j.file,children:kr(j.file,40)}),t.jsx(gh,{status:j.status}),t.jsx("button",{className:"gm-icon-btn",onClick:k=>{k.stopPropagation(),l([j.file])},title:"Unstage file",children:t.jsx(Ut,{size:12})})]},`staged:${j.file}`)})})]}),(d||h||m||g)&&t.jsxs("div",{className:"gm-diff-section",children:[d&&t.jsxs("div",{className:"gm-diff-target",children:[t.jsx(qh,{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(rt,{size:16,className:"spin"}),"Loading diff..."]}),g&&!h&&t.jsx("div",{className:"gm-diff-error",children:g}),m&&!h&&t.jsxs("div",{className:"gm-diff-viewer",children:[m.stat&&t.jsx("pre",{className:"gm-diff-stat",children:m.stat}),t.jsx("pre",{className:"gm-diff-patch",children:m.patch})]})]}),t.jsxs("form",{className:"gm-commit-form",onSubmit:x,children:[t.jsx("textarea",{className:"gm-commit-input",placeholder:"Commit message...",value:p,onChange:j=>f(j.target.value),rows:3,disabled:b}),t.jsxs("div",{className:"gm-commit-actions",children:[t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:b||!p.trim()||n.length===0,title:n.length===0?"No staged changes to commit":"Commit staged changes",children:[b?t.jsx(rt,{size:14,className:"spin"}):t.jsx(zi,{size:14}),"Commit"]}),s.length>0&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:v,disabled:b||!p.trim(),title:"Stage all and commit",children:"Stage All & Commit"})]})]})]})}function c4({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(ma,{size:14}),t.jsx("input",{type:"text",placeholder:"Search commits...",value:n,onChange:m=>s(m.target.value)})]})]}),t.jsx("div",{className:"gm-commits-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:n?"No matching commits":"No commits found"}):e.map((m,h)=>t.jsxs("div",{className:"gm-commit-item",children:[t.jsxs("div",{className:"gm-commit-graph",children:[t.jsx("div",{className:"gm-commit-dot"}),h<e.length-1&&t.jsx("div",{className:"gm-commit-line"})]}),t.jsxs("div",{className:"gm-commit-body",children:[t.jsxs("button",{className:"gm-commit-header",onClick:()=>l(m.hash),children:[t.jsxs("div",{className:"gm-commit-top-row",children:[t.jsx("code",{className:"gm-hash",children:m.shortHash}),t.jsx("span",{className:"gm-commit-message",title:m.message,children:m.message})]}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:m.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:wa(m.date)}),m.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),t.jsx("div",{className:"gm-commit-actions-row",children:t.jsx("button",{className:"gm-icon-btn",onClick:()=>d(m.hash,"commit hash"),title:"Copy full hash",children:t.jsx(Bi,{size:12})})}),i===m.hash&&t.jsx("div",{className:"gm-commit-diff",children:o?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(rt,{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 d4({branches:e,branchSearch:n,setBranchSearch:s,newBranchName:i,setNewBranchName:r,branchBase:o,setBranchBase:l,onCreateBranch:c,onCheckoutBranch:u,onDeleteBranch:d,loading:m,allBranches:h,selectedBranch:g,branchCommits:p,loadingBranchCommits:f,expandedBranchCommit:x,branchCommitDiff:v,loadingBranchCommitDiff:b,onSelectBranch:y,onBranchCommitClick:S,onCloseBranchDetails:j}){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(ma,{size:14}),t.jsx("input",{type:"text",placeholder:"Filter branches...",value:n,onChange:R=>s(R.target.value)})]})]}),t.jsxs("form",{className:"gm-create-form",onSubmit:c,children:[t.jsx("input",{type:"text",placeholder:"New branch name",value:i,onChange:R=>r(R.target.value),disabled:m}),t.jsxs("select",{value:o,onChange:R=>l(R.target.value),disabled:m,className:"gm-branch-select",children:[t.jsx("option",{value:"",children:"Base: HEAD"}),h.map(R=>t.jsx("option",{value:R.name,children:R.name},R.name))]}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:m||!i.trim(),children:[t.jsx(en,{size:14}),"Create"]})]}),t.jsx("div",{className:"gm-branches-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:n?"No matching branches":"No branches found"}):e.map(R=>t.jsxs("div",{children:[t.jsxs("div",{className:`gm-branch-item${R.isCurrent?" current":""}${g===R.name?" selected":""}`,onClick:()=>y(R.name),children:[t.jsxs("div",{className:"gm-branch-info",children:[t.jsxs("span",{className:"gm-branch-name",children:[R.isCurrent&&t.jsx($n,{size:14,className:"gm-current-icon"}),R.name]}),R.remote&&t.jsxs("span",{className:"gm-branch-remote",children:["→ ",R.remote]}),R.lastCommitDate&&t.jsx("span",{className:"gm-branch-date",children:wa(R.lastCommitDate)})]}),t.jsx("div",{className:"gm-branch-actions",children:!R.isCurrent&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:k=>{k.stopPropagation(),u(R.name)},disabled:m,title:"Checkout",children:t.jsx(Zs,{size:14})}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:k=>{k.stopPropagation(),d(R.name)},disabled:m,title:"Delete",children:t.jsx(Zt,{size:14})})]})})]}),g===R.name&&t.jsxs("div",{className:"gm-branch-details",children:[t.jsxs("div",{className:"gm-branch-details-header",children:[t.jsxs("span",{className:"gm-branch-details-title",children:[t.jsx(mr,{size:14}),"Commits on ",R.name]}),t.jsx("button",{className:"gm-icon-btn",onClick:j,title:"Close","data-testid":"close-branch-details",children:t.jsx(Ut,{size:14})})]}),f?t.jsxs("div",{className:"gm-branch-details-loading",children:[t.jsx(rt,{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(k=>t.jsxs("div",{className:"gm-branch-commit",children:[t.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>S(k.hash),"data-testid":`branch-commit-${k.shortHash}`,children:[t.jsx("span",{className:"gm-commit-hash",children:k.shortHash}),t.jsx("span",{className:"gm-commit-message",title:k.message,children:k.message}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:k.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:wa(k.date)}),k.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),x===k.hash&&t.jsx("div",{className:"gm-commit-diff",children:b?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(rt,{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"})})]},k.hash))})]})]},R.name))})]})}function u4({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:id(n.path)||n.path})]}),t.jsxs("div",{className:"gm-worktree-detail",children:[n.branch&&t.jsxs("span",{className:"gm-worktree-branch",children:[t.jsx(Zs,{size:12}),n.branch]}),n.taskId&&t.jsx("span",{className:"gm-worktree-task",children:n.taskId})]})]})},n.path))})]})}function m4({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(rt,{size:14,className:"spin"}):t.jsx(Ro,{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(Zs,{size:12}),c.branch]}),t.jsx("span",{children:wa(c.date)})]})]}),t.jsxs("div",{className:"gm-stash-actions",children:[t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>r(c.index,!1),disabled:l!==null,title:"Apply stash (keep)",children:l===`apply-${c.index}`?t.jsx(rt,{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(rt,{size:14,className:"spin"}):t.jsx(Zt,{size:14})})]})]},c.index))})]})}function h4({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:i,onPull:r,onPush:o,addToast:l,projectId:c,copyToClipboard:u}){const d=te=>{try{return new URL(te).hostname}catch{return te.replace(/^git@/,"").split(":")[0]||te}},[m,h]=a.useState([]),[g,p]=a.useState(!1),[f,x]=a.useState(null),[v,b]=a.useState(""),[y,S]=a.useState(""),[j,R]=a.useState(null),[k,M]=a.useState(""),[C,L]=a.useState(""),[A,P]=a.useState(!1),[O,V]=a.useState([]),[$,E]=a.useState(!1),[D,U]=a.useState(null),[Y,X]=a.useState([]),[_,I]=a.useState(!1),[T,w]=a.useState(null),q=m.find(te=>te.name===D),[G,me]=a.useState(null),[ue,le]=a.useState(null),[Se,F]=a.useState(!1),[ge,se]=a.useState(null),[fe,de]=a.useState(null),[xe,ie]=a.useState(!1);a.useEffect(()=>{Ee()},[]),a.useEffect(()=>{e&&e.ahead>0?De():e&&e.ahead===0&&V([])},[e?.ahead]),a.useEffect(()=>{m.length>0&&!D&&U(m[0].name)},[m]),a.useEffect(()=>{D?qe(D):(X([]),w(null))},[D]),a.useEffect(()=>{D&&!m.find(te=>te.name===D)&&U(m.length>0?m[0].name:null)},[m,D]);const Ee=async()=>{p(!0);try{const te=await uy(c);h(te)}catch(te){l(je(te)||"Failed to load remotes","error")}finally{p(!1)}},De=async()=>{E(!0);try{const te=await jy(c);V(te)}catch{V([])}finally{E(!1)}},qe=async te=>{I(!0),w(null);try{const Ae=await ky(te,void 0,10,c);X(Ae)}catch(Ae){w(je(Ae)||"Failed to load remote commits"),X([])}finally{I(!1)}},Qe=Hs(),Je=async te=>{if(te.preventDefault(),!(!v.trim()||!y.trim())){x("add");try{await my(v.trim(),y.trim(),c),l(`Remote '${v}' added successfully`,"success"),b(""),S(""),P(!1),await Ee()}catch(Ae){l(je(Ae)||"Failed to add remote","error")}finally{x(null)}}},Ke=async te=>{if(await Qe.confirm({title:"Remove Remote",message:`Are you sure you want to remove remote '${te}'?`,danger:!0})){x(`remove-${te}`);try{await hy(te,c),l(`Remote '${te}' removed`,"success"),await Ee()}catch(Le){l(je(Le)||"Failed to remove remote","error")}finally{x(null)}}},it=async te=>{if(C.trim()){x(`rename-${te}`);try{await py(te,C.trim(),c),l(`Remote renamed to '${C.trim()}'`,"success"),R(null),L(""),await Ee()}catch(Ae){l(je(Ae)||"Failed to rename remote","error")}finally{x(null)}}},Pe=async te=>{if(k.trim()){x(`url-${te}`);try{await fy(te,k.trim(),c),l("Remote URL updated","success"),R(null),M(""),await Ee()}catch(Ae){l(je(Ae)||"Failed to update remote URL","error")}finally{x(null)}}},Ve=a.useCallback(async(te,Ae)=>{if(Ae==="ahead"){if(G===te){me(null),le(null);return}me(te),le(null),F(!0);try{const Le=await bo(te);le(Le)}catch{le(null)}finally{F(!1)}}else{if(ge===te){se(null),de(null);return}se(te),de(null),ie(!0);try{const Le=await bo(te);de(Le)}catch{de(null)}finally{ie(!1)}}},[G,ge]),ae=te=>{R(`url-${te.name}`),M(te.pushUrl||te.fetchUrl)},ye=te=>{R(`name-${te.name}`),L(te.name)};return t.jsx("div",{className:"gm-panel gm-remotes-panel","data-testid":"remotes-panel",children:t.jsxs("div",{className:"gm-remotes-layout",children:[t.jsxs("div",{className:"gm-remote-selector","data-testid":"remote-selector",children:[t.jsxs("div",{className:"gm-remote-selector-header",children:[t.jsx("span",{className:"gm-remote-selector-title",children:"Remotes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>P(!A),disabled:f!==null,title:A?"Cancel":"Add Remote",children:A?t.jsx(Ut,{size:14}):t.jsx(en,{size:14})})]}),A&&t.jsxs("form",{className:"gm-remote-form",onSubmit:Je,children:[t.jsx("input",{type:"text",placeholder:"Remote name",value:v,onChange:te=>b(te.target.value),disabled:f==="add",className:"gm-input"}),t.jsx("input",{type:"text",placeholder:"Repository URL",value:y,onChange:te=>S(te.target.value),disabled:f==="add",className:"gm-input gm-input-url"}),t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:!v.trim()||!y.trim()||f==="add",children:[f==="add"?t.jsx(rt,{size:12,className:"spin"}):t.jsx(en,{size:12}),"Add"]})]}),g?t.jsxs("div",{className:"gm-loading",children:[t.jsx(rt,{size:16,className:"spin"}),"Loading..."]}):m.length===0?t.jsx("div",{className:"gm-empty",children:"No remotes"}):m.map(te=>t.jsxs("div",{className:`gm-remote-selector-item${D===te.name?" selected":""}`,onClick:()=>U(te.name),role:"button",tabIndex:0,children:[t.jsxs("div",{className:"gm-remote-selector-info",children:[t.jsxs("span",{className:"gm-remote-selector-name",children:[te.name,te.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),t.jsx("span",{className:"gm-remote-selector-host",children:d(te.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:Ae=>{Ae.stopPropagation(),Ke(te.name)},disabled:f!==null,title:"Remove remote",children:t.jsx(Zt,{size:14})})]},te.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[D&&q?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"gm-remote-sync-card","data-testid":"remote-sync-card",children:[t.jsxs("div",{className:"gm-remote-sync-card-header",children:[t.jsx("span",{className:"gm-remote-sync-card-title",children:D}),e&&(e.ahead>0||e.behind>0)&&t.jsxs("div",{className:"gm-remote-status",children:[e.ahead>0&&t.jsxs("div",{className:"gm-remote-indicator ahead",children:[t.jsx(Fi,{size:14}),e.ahead," to push"]}),e.behind>0&&t.jsxs("div",{className:"gm-remote-indicator behind",children:[t.jsx(wr,{size:14}),e.behind," to pull"]})]})]}),t.jsxs("div",{className:"gm-remote-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:i,disabled:n!==null||g,children:[n==="fetch"?t.jsx(rt,{size:14,className:"spin"}):t.jsx(En,{size:14}),"Fetch"]}),t.jsxs("button",{className:"btn btn-primary",onClick:r,disabled:n!==null||g,children:[n==="pull"?t.jsx(rt,{size:14,className:"spin"}):t.jsx(vs,{size:14}),"Pull"]}),t.jsxs("button",{className:"btn btn-primary",onClick:o,disabled:n!==null||g,children:[n==="push"?t.jsx(rt,{size:14,className:"spin"}):t.jsx(Fi,{size:14}),"Push"]})]})]}),t.jsxs("div",{className:"gm-remote-detail-card","data-testid":"remote-detail-card",children:[t.jsxs("div",{className:"gm-remote-detail-urls",children:[t.jsxs("div",{className:"gm-remote-detail-url-row",children:[t.jsx("span",{className:"gm-url-label",children:"Fetch:"}),j===`url-${D}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:k,onChange:te=>M(te.target.value),className:"gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Pe(D),disabled:f===`url-${D}`,children:f===`url-${D}`?t.jsx(rt,{size:12,className:"spin"}):t.jsx($n,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{R(null),M("")},title:"Cancel",children:t.jsx(Ut,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:q.fetchUrl,children:q.fetchUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>u(q.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:t.jsx(Bi,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>ae(q),disabled:f!==null,title:"Edit remote URL",children:t.jsx(ss,{size:14})})]})]}),q.pushUrl&&q.pushUrl!==q.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:q.pushUrl,children:q.pushUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>u(q.pushUrl,"push URL"),title:"Copy push URL",children:t.jsx(Bi,{size:14})})]})]}),t.jsx("div",{className:"gm-remote-detail-name-row",children:j===`name-${D}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:C,onChange:te=>L(te.target.value),className:"gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>it(D),disabled:f===`rename-${D}`,children:f===`rename-${D}`?t.jsx(rt,{size:12,className:"spin"}):t.jsx($n,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{R(null),L("")},title:"Cancel",children:t.jsx(Ut,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>ye(q),disabled:f!==null,title:"Edit remote name",children:t.jsx(ss,{size:14})})})]}),e&&e.ahead>0&&t.jsxs("div",{className:"gm-remote-section","data-testid":"commits-to-push",children:[t.jsx("div",{className:"gm-section-subheader",children:t.jsxs("h5",{children:[t.jsx(Fi,{size:14}),"Commits to Push (",e.ahead,")"]})}),$?t.jsxs("div",{className:"gm-loading",children:[t.jsx(rt,{size:14,className:"spin"}),"Loading..."]}):O.length>0?t.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:O.map(te=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>Ve(te.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:te.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:te.message,children:te.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:te.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:wa(te.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:G===te.hash?t.jsx(Vt,{size:14}):t.jsx(pn,{size:14})})]}),G===te.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:Se?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(rt,{size:16,className:"spin"}),"Loading diff..."]}):ue?t.jsxs(t.Fragment,{children:[te.message&&t.jsx("div",{className:"gm-commit-message-full",children:te.message}),ue.stat&&t.jsx("pre",{className:"gm-diff-stat",children:ue.stat}),t.jsx("pre",{className:"gm-diff-patch",children:ue.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},te.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(Yh,{size:14}),"Recent commits on ",D]})}),_?t.jsxs("div",{className:"gm-loading",children:[t.jsx(rt,{size:14,className:"spin"}),"Loading commits..."]}):T?t.jsxs("div",{className:"gm-error",children:[t.jsx(as,{size:14}),T]}):Y.length===0?t.jsxs("div",{className:"gm-empty",children:["No commits found on ",D,". Try fetching first."]}):t.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:Y.map(te=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>Ve(te.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:te.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:te.message,children:te.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:te.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:wa(te.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:ge===te.hash?t.jsx(Vt,{size:14}):t.jsx(pn,{size:14})})]}),ge===te.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:xe?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(rt,{size:16,className:"spin"}),"Loading diff..."]}):fe?t.jsxs(t.Fragment,{children:[te.message&&t.jsx("div",{className:"gm-commit-message-full",children:te.message}),fe.stat&&t.jsx("pre",{className:"gm-diff-stat",children:fe.stat}),t.jsx("pre",{className:"gm-diff-patch",children:fe.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},te.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 Za={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function p4(e,n){return e&&n?`${e}/${n}`:""}function f4(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 g4(e){switch(e){case"file-text":return Ui;case"check-circle":return fn;case"shield":return Ob;case"zap":return Bn;case"eye":return fa;case"globe":return Io;case"layout-grid":return qi;default:return fn}}function x4(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 b4({isOpen:e,onClose:n,addToast:s,projectId:i}){const[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState(!0),[m,h]=a.useState(!0),[g,p]=a.useState("my-steps"),[f,x]=a.useState(null),[v,b]=a.useState(!1),[y,S]=a.useState(Za),[j,R]=a.useState(!1),[k,M]=a.useState(!1),[C,L]=a.useState(null),[A,P]=a.useState(null),[O,V]=a.useState({}),[$,E]=a.useState([]),D=a.useRef(null);ni(D,e,"fusion:workflow-steps-modal-size");const U=a.useCallback(async()=>{try{d(!0);const F=await Oo(i);o(F)}catch(F){s(je(F)||"Failed to load workflow steps","error")}finally{d(!1)}},[s,i]),Y=a.useCallback(async()=>{try{const F=await br(i);V(F||{})}catch{}},[i]),X=a.useCallback(async()=>{try{const F=await ms();E(F.models||[])}catch{}},[]),_=a.useCallback(async()=>{try{h(!0);const F=await bj();c(F.templates)}catch(F){s(je(F)||"Failed to load templates","error")}finally{h(!1)}},[s]);a.useEffect(()=>{e&&(U(),_(),Y(),X())},[e,U,_,Y,X]);const I=a.useCallback(()=>{b(!0),x(null),S(Za)},[]),T=a.useCallback(F=>{x(F.id),b(!1),S({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||""})},[]),w=a.useCallback(()=>{x(null),b(!1),S(Za)},[]),q=a.useCallback(async()=>{if(!y.name.trim()||!y.description.trim()){s("Name and description are required","error");return}R(!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 ge={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 Qd(ge,i),s("Workflow step created","success")}else f&&(await fj(f,{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"));b(!1),x(null),S(Za),await U()}catch(F){s(je(F)||"Failed to save workflow step","error")}finally{R(!1)}},[y,v,f,s,U]),G=a.useCallback(async F=>{try{await gj(F,i),s("Workflow step deleted","success"),L(null),f===F&&(x(null),S(Za)),await U()}catch(ge){s(je(ge)||"Failed to delete workflow step","error")}},[f,s,U]),me=a.useCallback(async()=>{if(!(!f&&!v)&&y.mode==="prompt"){if(v){if(!y.name.trim()||!y.description.trim()){s("Name and description are required before refining","error");return}R(!0);try{const F=y.modelProvider&&y.modelId?{modelProvider:y.modelProvider,modelId:y.modelId}:{},ge={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},se=await Qd(ge,i);b(!1),x(se.id),M(!0);const fe=await Xd(se.id,i);S(de=>({...de,prompt:fe.prompt})),s("Prompt refined with AI","success"),await U()}catch(F){s(je(F)||"Failed to refine prompt","error")}finally{R(!1),M(!1)}return}if(f){M(!0);try{const F=await Xd(f,i);S(ge=>({...ge,prompt:F.prompt})),s("Prompt refined with AI","success"),await U()}catch(F){s(je(F)||"Failed to refine prompt","error")}finally{M(!1)}}}},[f,v,y,s,U]),ue=a.useCallback(async F=>{P(F.id);try{await vj(F.id,i),s(`Added ${F.name} workflow step`,"success"),await U(),p("my-steps")}catch(ge){const se=je(ge);se?.includes("already exists")?s(`A workflow step named '${F.name}' already exists`,"error"):s(se||"Failed to add workflow step from template","error")}finally{P(null)}},[s,U]),le=Si(n);if(!e)return null;const Se=v||f!==null;return t.jsx("div",{className:"modal-overlay open",...le,"data-testid":"workflow-step-manager",children:t.jsxs("div",{ref:D,className:"modal workflow-step-manager-modal",role:"dialog","aria-modal":"true","aria-label":"Workflow Steps",children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h2",{children:"Workflow Steps"}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]}),t.jsx("div",{className:"wfm-body",children:u?t.jsx("div",{className:"wfm-loading",children:"Loading..."}):t.jsxs(t.Fragment,{children:[!Se&&t.jsxs("div",{className:"wfm-tab-row",children:[t.jsxs("button",{className:`btn ${g==="my-steps"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>p("my-steps"),"data-testid":"tab-my-steps",children:[t.jsx(Ig,{size:14}),"My Workflow Steps (",r.length,")"]}),t.jsxs("button",{className:`btn ${g==="templates"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>p("templates"),"data-testid":"tab-templates",children:[t.jsx(qi,{size:14}),"Templates (",l.length,")"]})]}),g==="my-steps"&&!Se&&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:()=>T(F),title:"Edit","aria-label":`Edit ${F.name}`,children:t.jsx(ss,{size:14})}),C===F.id?t.jsxs("div",{className:"wfm-delete-confirm",children:[t.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>G(F.id),title:"Confirm delete","aria-label":`Confirm delete ${F.name}`,children:t.jsx($n,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>L(null),title:"Cancel delete","aria-label":"Cancel delete",children:t.jsx(Ut,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>L(F.id),title:"Delete","aria-label":`Delete ${F.name}`,children:t.jsx(Zt,{size:14})})]})]})},F.id))})]}),g==="templates"&&!Se&&t.jsx(t.Fragment,{children:m?t.jsxs("div",{className:"wfm-loading",children:[t.jsx(rt,{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 ge=g4(F.icon),se=x4(F.category),fe=A===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(ge,{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:se,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:()=>ue(F),disabled:fe,"data-testid":`add-template-${F.id}`,children:fe?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(en,{size:12}),"Add"]})})]})]})},F.id)})})}),Se&&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=>S(ge=>({...ge,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=>S(ge=>({...ge,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:()=>S(F=>({...F,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[t.jsx(ji,{size:14}),"AI Prompt"]}),t.jsxs("button",{className:`btn ${y.mode==="script"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>S(F=>({...F,mode:"script",prompt:"",modelProvider:"",modelId:""})),"data-testid":"mode-script",children:[t.jsx(ci,{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:()=>S(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:()=>S(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:me,disabled:!y.description.trim()||k,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[k?t.jsx(rt,{size:12,className:"spin"}):t.jsx(Xn,{size:12}),t.jsx("span",{children:"Refine with AI"})]})]}),t.jsx("textarea",{value:y.prompt,onChange:F=>S(ge=>({...ge,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:()=>S(F=>({...F,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[t.jsx(Ut,{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(Hn,{models:$,value:p4(y.modelProvider,y.modelId),onChange:F=>{const ge=f4(F);S(se=>({...se,modelProvider:ge.provider,modelId:ge.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(O).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=>S(ge=>({...ge,scriptName:F.target.value})),"data-testid":"workflow-step-script-select",children:[t.jsx("option",{value:"",children:"Select a script…"}),Object.entries(O).map(([F,ge])=>t.jsxs("option",{value:F,children:[F," (",ge,")"]},F))]})]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:y.enabled,onChange:F=>S(ge=>({...ge,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=>S(ge=>({...ge,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:w,disabled:j,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:q,disabled:j||!y.name.trim()||!y.description.trim()||y.mode==="script"&&!y.scriptName.trim(),"data-testid":"save-workflow-step",children:j?"Saving...":v?"Create":"Save"})]})]})]})]})}),!Se&&t.jsx("div",{className:"wfm-footer",children:t.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:I,"data-testid":"add-workflow-step",children:[t.jsx(en,{size:14}),"Add Workflow Step"]})})]})})}const v4=36e5,y4=3e5,ac=[{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 j4(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 k4(e){return typeof e!="number"||!Number.isFinite(e)?v4:Math.max(y4,Math.round(e))}function ID(e){if(ac.some(s=>s.value===e))return[...ac];const n={value:e,label:`${j4(e)} (custom)`};return[...ac,n].sort((s,i)=>s.value-i.value)}const w4=4,N4=5*6e4;function S4(e){const n=k4(e?.heartbeatIntervalMs);return Math.max(n*w4,N4)}function C4(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 E4(e){const{state:n,lastHeartbeatAt:s,lastError:i,pauseReason:r,runtimeConfig:o}=e,l=C4(e);if(n==="terminated")return{label:"Terminated",icon:t.jsx(bs,{size:14}),color:"var(--state-error-text)",stateDerived:!0};if(n==="error")return{label:i??"Error",icon:t.jsx(Ps,{size:14}),color:"var(--state-error-text)",stateDerived:!i};if(n==="paused")return{label:r?`Paused: ${r}`:"Paused",icon:t.jsx(Xs,{size:14}),color:"var(--state-paused-text)",stateDerived:!r};if(n==="running"||l&&n==="active")return{label:"Running",icon:t.jsx(Ps,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:t.jsx(yn,{size:14}),color:"var(--text-secondary)",stateDerived:!1};const c=new Date(s).getTime(),u=Date.now()-c,d=S4(o);return u>d?{label:"Unresponsive",icon:t.jsx(Ps,{size:14}),color:"var(--state-error-text)",stateDerived:!1}:{label:"Healthy",icon:t.jsx(qx,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}const er=[{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 _4({isOpen:e,onClose:n,addToast:s,projectId:i}){const[r,o]=a.useState([]),[l,c]=a.useState(!1),[u,d]=a.useState(!1),[m,h]=a.useState(""),[g,p]=a.useState("custom"),[f,x]=a.useState("all"),[v,b]=a.useState(()=>{if(typeof window>"u")return"list";const T=qn("fn-agent-view",i);return T==="board"||T==="list"?T:"list"});a.useEffect(()=>{const T=qn("fn-agent-view",i);if(T==="board"||T==="list"){b(T);return}b("list")},[i]),a.useEffect(()=>{ds("fn-agent-view",v,i)},[i,v]);const[y,S]=a.useState(null),j=a.useRef(null),[R,k]=a.useState(new Set),[M,C]=a.useState(new Map),{confirm:L}=Hs(),A=a.useMemo(()=>M.size===0?r:r.map(T=>{const w=M.get(T.id);return w?{...T,state:w}:T}),[r,M]),P=a.useMemo(()=>f==="all"?A.filter(T=>T.state!=="terminated"):A,[A,f]),O=a.useCallback(async()=>{c(!0);try{const w=await Ma(f!=="all"?{state:f}:void 0,i);o(w)}catch(T){s(`Failed to load agents: ${je(T)}`,"error")}finally{c(!1)}},[f,s,i]);a.useEffect(()=>{e&&O()},[e,O]),a.useEffect(()=>{if(!e)return;const T=setInterval(()=>{O()},3e4);return()=>{clearInterval(T)}},[e,O]);const V=async()=>{if(m.trim())try{await _j({name:m.trim(),role:g},i),s(`Agent "${m}" created`,"success"),h(""),d(!1),O()}catch(T){s(`Failed to create agent: ${je(T)}`,"error")}},$=async(T,w)=>{if(!R.has(T)){k(q=>new Set(q).add(T)),C(q=>{const G=new Map(q);return G.set(T,w),G});try{await Aj(T,w,i),s(`Agent state updated to ${w}`,"success"),await O(),C(q=>{const G=new Map(q);return G.delete(T),G})}catch(q){C(G=>{const me=new Map(G);return me.delete(T),me}),s(`Failed to update state: ${je(q)}`,"error")}finally{k(q=>{const G=new Set(q);return G.delete(T),G})}}},E=async(T,w)=>{if(await L({title:"Delete Agent",message:`Delete agent "${w}"? This cannot be undone.`,danger:!0}))try{await Rj(T,i),s(`Agent "${w}" deleted`,"success"),O()}catch(G){s(`Failed to delete agent: ${je(G)}`,"error")}},D=async(T,w)=>{const q=r.find(G=>G.id===T);if(q){if(q.role===w){S(null);return}try{await Mj(T,{role:w},i),s(`Agent role updated to ${er.find(G=>G.value===w)?.label??w}`,"success"),S(null),O()}catch(G){s(`Failed to update role: ${je(G)}`,"error")}}},U=(T,w)=>{T.key==="Escape"&&S(null)},Y=T=>er.find(w=>w.value===T)?.label??T,X=T=>er.find(w=>w.value===T)?.icon??"◆",_=T=>E4(T),I=T=>T.color==="var(--state-active-text)"?"active":T.color==="var(--state-paused-text)"?"paused":T.color==="var(--state-error-text)"?"error":"muted";return e?t.jsx("div",{className:"modal-overlay open",onClick:T=>T.target===T.currentTarget&&n(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal--wide agent-list-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{className:"modal-title",children:[t.jsx(yn,{size:20}),"Agents"]}),t.jsxs("div",{className:"modal-actions",children:[t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${v==="board"?" active":""}`,onClick:()=>b("board"),title:"Board view","aria-label":"Board view","aria-pressed":v==="board",children:t.jsx(qi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${v==="list"?" active":""}`,onClick:()=>b("list"),title:"List view","aria-label":"List view","aria-pressed":v==="list",children:t.jsx(bc,{size:16})})]}),t.jsx("button",{className:"btn-icon",onClick:()=>void O(),title:"Refresh",disabled:l,children:t.jsx(En,{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(po,{size:14}),t.jsxs("select",{className:"agent-state-filter-select",value:f,onChange:T=>x(T.target.value),"aria-label":"Filter agents by state",children:[t.jsx("option",{value:"all",children:"All States"}),t.jsx("option",{value:"idle",children:"Idle"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"running",children:"Running"}),t.jsx("option",{value:"paused",children:"Paused"}),t.jsx("option",{value:"error",children:"Error"}),t.jsx("option",{value:"terminated",children:"Terminated"})]})]}),t.jsxs("button",{className:"btn btn-task-create btn-sm",onClick:()=>d(!u),children:[t.jsx(en,{size:16}),u?"Cancel":"New Agent"]})]}),u&&t.jsxs("div",{className:"agent-create-form",children:[t.jsx("input",{type:"text",placeholder:"Agent name...",value:m,onChange:T=>h(T.target.value),onKeyDown:T=>T.key==="Enter"&&V(),className:"input",autoFocus:!0}),t.jsx("select",{className:"select",value:g,onChange:T=>p(T.target.value),children:er.map(T=>t.jsxs("option",{value:T.value,children:[T.icon," ",T.label]},T.value))}),t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:()=>void V(),children:"Create"})]}),t.jsx("div",{className:v==="board"?"agent-board":"agent-list",children:P.length===0?t.jsxs("div",{className:"agent-empty",children:[t.jsx(yn,{size:48,opacity:.3}),t.jsx("p",{children:"No agents found"}),t.jsx("p",{className:"text-secondary",children:"Create an agent to get started"})]}):v==="board"?P.map(T=>{const w=_(T),q=I(w);return t.jsxs("div",{className:"agent-board-card","data-state":T.state,children:[t.jsxs("div",{className:"agent-board-header",children:[t.jsx("span",{className:"agent-board-icon",children:X(T.role)}),t.jsx("span",{className:"agent-board-badge","data-state":T.state,children:T.state}),t.jsx("span",{className:"agent-board-health","data-health":q,title:w.label,children:w.icon})]}),t.jsx("div",{className:"agent-board-name",title:T.name,children:T.name}),t.jsx("div",{className:"agent-board-id",children:T.id}),t.jsxs("div",{className:"agent-board-actions",children:[T.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void $(T.id,"active"),disabled:R.has(T.id),title:"Activate",children:t.jsx(jn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void E(T.id,T.name),title:"Delete",children:t.jsx(Zt,{size:14})})]}),T.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void $(T.id,"paused"),disabled:R.has(T.id),title:"Pause",children:t.jsx(Xs,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:t.jsx(bs,{size:14})})]}),T.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void $(T.id,"active"),disabled:R.has(T.id),title:"Resume",children:t.jsx(jn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:t.jsx(bs,{size:14})})]}),T.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void $(T.id,"paused"),disabled:R.has(T.id),title:"Pause",children:t.jsx(Xs,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:t.jsx(bs,{size:14})})]}),T.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void $(T.id,"active"),disabled:R.has(T.id),title:"Retry",children:t.jsx(jn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:t.jsx(bs,{size:14})})]}),T.state==="terminated"&&t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void E(T.id,T.name),title:"Delete",children:t.jsx(Zt,{size:14})})]})]},T.id)}):P.map(T=>{const w=_(T),q=I(w);return t.jsxs("div",{className:"agent-card","data-state":T.state,children:[t.jsxs("div",{className:"agent-card-header",children:[t.jsxs("div",{className:"agent-info",children:[y===T.id?t.jsx("select",{ref:j,className:"select agent-role-select",value:T.role,onChange:G=>void D(T.id,G.target.value),onKeyDown:G=>U(G,T.id),onBlur:()=>S(null),autoFocus:!0,children:er.map(G=>t.jsxs("option",{value:G.value,children:[G.icon," ",G.label]},G.value))}):t.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>S(T.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:G=>{(G.key==="Enter"||G.key===" ")&&S(T.id)},children:X(T.role)}),t.jsxs("div",{className:"agent-meta",children:[t.jsx("span",{className:"agent-name",children:T.name}),t.jsx("span",{className:"agent-id text-secondary",children:T.id})]})]}),t.jsxs("div",{className:"agent-badges",children:[t.jsx("span",{className:"badge agent-list-state-badge","data-state":T.state,children:T.state}),t.jsxs("span",{className:"badge agent-list-health-badge","data-health":q,title:w.label,children:[w.icon,!w.stateDerived&&` ${w.label}`]}),t.jsx("span",{className:"badge text-secondary",children:Y(T.role)})]})]}),t.jsxs("div",{className:"agent-card-body",children:[T.taskId&&t.jsxs("div",{className:"agent-task",children:[t.jsx("span",{className:"text-secondary",children:"Working on:"}),t.jsx("span",{className:"badge",children:T.taskId})]}),T.lastHeartbeatAt&&t.jsxs("div",{className:"agent-heartbeat",children:[t.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),t.jsx("span",{children:new Date(T.lastHeartbeatAt).toLocaleString()})]})]}),t.jsxs("div",{className:"agent-card-actions",children:[T.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void $(T.id,"active"),disabled:R.has(T.id),title:"Activate",children:[t.jsx(jn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void E(T.id,T.name),title:"Delete",children:[t.jsx(Zt,{size:14})," Delete"]})]}),T.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void $(T.id,"paused"),disabled:R.has(T.id),title:"Pause",children:[t.jsx(Xs,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:[t.jsx(bs,{size:14})," Stop"]})]}),T.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void $(T.id,"active"),disabled:R.has(T.id),title:"Resume",children:[t.jsx(jn,{size:14})," Resume"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:[t.jsx(bs,{size:14})," Stop"]})]}),T.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void $(T.id,"paused"),disabled:R.has(T.id),title:"Pause",children:[t.jsx(Xs,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:[t.jsx(bs,{size:14})," Stop"]})]}),T.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void $(T.id,"active"),disabled:R.has(T.id),title:"Retry",children:[t.jsx(jn,{size:14})," Retry"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:[t.jsx(bs,{size:14})," Stop"]})]}),T.state==="terminated"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm btn-task-create",onClick:()=>void $(T.id,"active"),disabled:R.has(T.id),title:"Start",children:[t.jsx(jn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void E(T.id,T.name),title:"Delete",children:[t.jsx(Zt,{size:14})," Delete"]})]})]})]},T.id)})})]})]})}):null}function M4({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 b=await ey();return d.current&&r(b),b}catch(b){return d.current&&u({kind:"error",message:b instanceof Error?b.message:String(b)}),null}},[]);a.useEffect(()=>{m()},[m]);const h=a.useCallback(async()=>{l("testing"),u(null),await m(),d.current&&l(null)},[m]),g=a.useCallback(async b=>{l(b?"enabling":"disabling"),u(null);try{const y=await ty(b);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,f=i?.enabled??e,x=t.jsxs("span",{className:"onboarding-provider-card__description",children:["Route AI calls through your locally-installed ",t.jsx("code",{children:"claude"})," CLI. Uses your existing Claude subscription / quota instead of an API key."]}),v=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:12,className:"animate-spin"}),"Testing…"]}):"Test"}),f?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void g(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void g(!0),disabled:o!==null||!p,title:p?void 0:"`claude` binary not detected on PATH — install Claude CLI first.",children:o==="enabling"?"Enabling…":"Enable"})]});return s?t.jsxs("div",{className:`auth-provider-card auth-provider-card--cli${e?" auth-provider-card--authenticated":""}`,"data-testid":"claude-cli-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(Dn,{provider:"claude-cli",size:"sm"}),t.jsx("strong",{children:"Anthropic — via Claude CLI"}),t.jsx(A4,{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:[x,t.jsx(xh,{status:i,authenticated:e}),c&&t.jsx(bh,{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(Dn,{provider:"claude-cli",size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:"Anthropic — via Claude CLI"}),x,t.jsx(xh,{status:i,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(bh,{action:c})]})}function A4({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 xh({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(rt,{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 bh({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 R4(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 rc({instructions:e,"data-testid":n}){const[s,i]=a.useState(!1),r=R4(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($n,{size:12}):t.jsx(Bi,{size:12})})]})]},d))}):e})}const Ki="fusion_model_onboarding_state",Na=[],Sa=[],Mo=!1,Ao=!1,Ca={},T4=void 0,yi=["ai-setup","github","project-setup","first-task"],P4={"ai-setup":"AI Setup",github:"GitHub","project-setup":"Project","first-task":"First Task",complete:"Complete"};function ks(){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"?I4(n):null}catch{return null}}function I4(e){const n=e.postOnboardingDismissedAt??T4;return{...e,completedSteps:e.completedSteps??Na,skippedSteps:e.skippedSteps??Sa,dismissed:e.dismissed??Mo,completed:e.completed??Ao,stepData:e.stepData??Ca,...n?{postOnboardingDismissedAt:n}:{}}}function ro(e,n){if(!(typeof window>"u")){if(!n){const s={currentStep:e,updatedAt:new Date().toISOString(),completedSteps:Na,skippedSteps:Sa,dismissed:Mo,completed:Ao,stepData:Ca};try{localStorage.setItem(Ki,JSON.stringify(s))}catch{}return}try{const s=ks(),i=new Date().toISOString(),r=n.completed??Ao;let o=n.dismissed??Mo;r&&(o=!1);const l=n.completedSteps??s?.completedSteps??Na,c=n.skippedSteps??s?.skippedSteps??Sa,u={...s?.stepData??Ca};if(n.stepData)for(const[m,h]of Object.entries(n.stepData))h!==void 0&&(u[m]={...u[m]??{},...h});const d={currentStep:e,updatedAt:i,completedSteps:l,skippedSteps:c,dismissed:o,completed:r,stepData:u};localStorage.setItem(Ki,JSON.stringify(d))}catch{}}}function $4(e){if(!(typeof window>"u"))try{const n=ks(),s=new Date().toISOString();if(!n){const o={currentStep:e,updatedAt:s,completedSteps:Na,skippedSteps:[e],dismissed:Mo,completed:Ao,stepData:Ca};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 vh(){if(!(typeof window>"u"))try{const e=ks(),n=new Date().toISOString(),s=e?{...e,completedAt:n,completed:!0,dismissed:!1,updatedAt:n}:{currentStep:"complete",updatedAt:n,completedAt:n,completedSteps:Na,skippedSteps:Sa,dismissed:!1,completed:!0,stepData:Ca};localStorage.setItem(Ki,JSON.stringify(s))}catch{}}function Ea(){const e=ks();return e?e.completed===!0?!0:typeof e.completedAt=="string"&&e.completedAt.length>0:!1}function D4(){if(!(typeof window>"u"))try{const e=ks(),n=new Date().toISOString(),s=e?{...e,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:Na,skippedSteps:Sa,dismissed:!1,completed:!1,stepData:Ca,postOnboardingDismissedAt:n};localStorage.setItem(Ki,JSON.stringify(s))}catch{}}function rg(){const e=ks();return e?typeof e.postOnboardingDismissedAt=="string"&&e.postOnboardingDismissedAt.length>0:!1}function L4(){const e=ks();return!e||Ea()?!1:e.currentStep!=="complete"}function z4(){const e=ks();if(!e||Ea()||e.currentStep==="complete")return null;const n=e.currentStep,s=P4[n]??B4(e.currentStep);return{currentStep:e.currentStep,label:s,completedSteps:e.completedSteps}}function F4(){const e=ks();return e?e.skippedSteps:Sa}function O4(e){const n=ks();return!n||!n.stepData?null:n.stepData[e]??null}function B4(e){return e.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const og="fusion_onboarding_events",yh="fusion_onboarding_session_id",U4=200,H4=50;function As(e,n={}){if(!(typeof window>"u"))try{const s=V4(),i=G4(n.step),r={type:e,timestamp:new Date().toISOString(),...i?{step:i}:{},metadata:n,sessionId:q4()},o=K4([...s,r]);W4(o)}catch{}}function q4(){if(typeof window>"u")return"server-session";try{const e=sessionStorage.getItem(yh);if(e)return e;const n=jh();return sessionStorage.setItem(yh,n),n}catch{return jh()}}function jh(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function V4(){try{const e=localStorage.getItem(og);if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(J4):[]}catch{return[]}}function W4(e){try{localStorage.setItem(og,JSON.stringify(e))}catch{}}function K4(e){const n=[...e];for(;n.length>U4;)n.splice(0,H4);return n}function G4(e){if(e==="ai-setup"||e==="github"||e==="first-task"||e==="complete")return e}function J4(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 Y4={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"}}},lg={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:"..."}},Q4={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},kh={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 Vc(e){if(kh[e])return kh[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 oc=["anthropic","openai","google","gemini","ollama"],X4=["anthropic","claude-cli","openai-codex","gemini","minimax","kimi","zai"],Z4={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"},eT={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function Wc(e){return Z4[e]??e}function wh(e){const n=Wc(e),s=X4.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function Nh(e,n){if(e.authenticated!==n.authenticated)return e.authenticated?-1:1;const s=wh(e.id),i=wh(n.id);if(s!==i)return s-i;const r=Wc(e.id),o=Wc(n.id);if(r!==o)return r.localeCompare(o);const l=eT[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 tT(e,n){const s=n.trim();if(!s)return"API key is required";const i=lg[e]??Q4;return i.pattern.test(s)?null:`${Vc(e)} keys should follow this format: ${i.hint} (e.g. ${i.example})`}const cg={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"},nT={description:"AI provider — connect to start using AI models",apiKeyInfo:cg};function Kc(e){return Y4[e]??nT}function sT(e){return Kc(e.id).apiKeyInfo??cg}function Ys({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(pn,{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 iT({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 aT({provider:e,apiKeyInfo:n,inputValue:s,isSaving:i,error:r,success:o,isConnected:l,onInputChange:c,onSave:u,onClear:d}){const m=`onboarding-apikey-input-${e.id}`,h=i||!s.trim(),g=lg[e.id],p=`input onboarding-apikey-input${r?" onboarding-apikey-input--error":""}${o?" onboarding-apikey-input--success":""}`,f=t.jsxs(t.Fragment,{children:[g&&t.jsxs("small",{className:"onboarding-apikey-hint",children:["Format: ",g.hint]}),t.jsx("p",{className:"onboarding-apikey-instructions",children:n.setupInstructions}),n.dashboardUrl&&t.jsx("a",{href:n.dashboardUrl,target:"_blank",rel:"noreferrer",className:"onboarding-apikey-dashboard-link",children:"Get your API key →"}),t.jsx("p",{className:"onboarding-apikey-usage",children:n.usageDescription})]});return l?t.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${e.id}`,children:[t.jsxs("div",{className:"onboarding-apikey-connected-header",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:n.fieldLabel}),t.jsx("span",{className:"auth-status-badge connected",children:"✓ API key saved"})]}),t.jsx("button",{className:"btn btn-sm",onClick:()=>d(e.id),disabled:i,children:i?"Removing…":"Remove Key"}),t.jsx(Ys,{summary:"Advanced setup details",children:f}),r&&t.jsx("small",{className:"field-error",children:r})]}):t.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${e.id}`,children:[t.jsx("label",{htmlFor:m,className:"onboarding-apikey-field-label",children:n.fieldLabel}),t.jsxs("div",{className:"onboarding-apikey-input-row",children:[t.jsx("input",{id:m,type:"password",className:p,placeholder:n.inputPlaceholder??"Enter API key",value:s,onChange:x=>c(e.id,x.target.value),onKeyDown:x=>{x.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(Ys,{summary:"Advanced setup details",children:f})]})}const rT=150;function oT({onComplete:e,addToast:n,projectId:s,onOpenSetupWizard:i,onOpenNewTask:r,onOpenGitHubImport:o,firstCreatedTask:l,onViewTask:c}){const u=ks(),d=u?.currentStep,m=d==="complete"?"ai-setup":yi.includes(d)?d:"ai-setup",h=u?.completedSteps??[],g=u?.skippedSteps??F4(),[p,f]=a.useState(!0),[x,v]=a.useState(m),[b,y]=a.useState(h),[S,j]=a.useState(g),[R,k]=a.useState(!1),[M,C]=a.useState(""),[L,A]=a.useState(!1),[P,O]=a.useState(null),[V,$]=a.useState(null),[E,D]=a.useState([]),[U,Y]=a.useState(void 0),[X,_]=a.useState(!0),[I,T]=a.useState(null),[w,q]=a.useState({}),[G,me]=a.useState([]),[ue,le]=a.useState(""),[Se,F]=a.useState(!1),[ge,se]=a.useState({}),[fe,de]=a.useState({}),[xe,ie]=a.useState({}),Ee=a.useRef({}),De=a.useRef(null),qe=a.useRef(null),Qe=a.useRef(null),[Je,Ke]=a.useState({}),[it,Pe]=a.useState(()=>ks()?.stepData?.github?.skipped===!0),Ve=a.useRef(0),ae=a.useRef(l),ye=a.useRef(!1),te=u?.currentStep,Ae=!!u&&u.currentStep!=="complete";ni(qe,p,"fusion:model-onboarding-modal-size"),a.useEffect(()=>{const Q=De.current;Q&&(Q.scrollTop=0)},[x]);const[Le,pe]=a.useState(()=>ks()?.stepData?.["ai-setup"]?.skippedProviders??{}),_e=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"project-setup",label:"Project"},{key:"first-task",label:"First Task"}],Fe=_e.findIndex(Q=>Q.key===x),tt=x==="complete"?_e.length:Fe;a.useEffect(()=>{x!=="complete"&&ro(x,{completedSteps:b,skippedSteps:S})},[x,b,S]),a.useEffect(()=>{ye.current||(ye.current=!0,As("onboarding:wizard-opened",{source:Ae?"resume":"initial",resumedFromStep:te}))},[Ae,te]),a.useEffect(()=>{const Q=ae.current!=null,ze=l!=null;!Q&&ze&&k(!0),ze||k(!1),ae.current=l},[l]);const Ne=a.useRef(m);a.useEffect(()=>{if(Ne.current==="ai-setup"&&x!=="ai-setup"&&!E.some(ze=>ze.id!=="github"&&ze.authenticated)){const ze={};for(const Ye of E)Ye.id!=="github"&&!Ye.authenticated&&!Le[Ye.id]&&(ze[Ye.id]=!0);if(Object.keys(ze).length>0){const Ye={...Le,...ze};pe(Ye),ro(x,{stepData:{"ai-setup":{skippedProviders:Ye}}})}}Ne.current=x},[x,E,Le]);const oe=a.useCallback(async()=>{try{const{providers:Q,ghCli:ze}=await xr();D(Q),Y(ze),q(Ye=>{const et={};for(const[dt,St]of Object.entries(Ye)){const It=Q.find(kn=>kn.id===dt);It&&!It.authenticated&&(et[dt]=St)}return Object.keys(et).length===Object.keys(Ye).length?Ye:et}),pe(Ye=>{const et={...Ye};for(const dt of Q)dt.authenticated&&et[dt.id]&&delete et[dt.id];return Object.keys(et).length===Object.keys(Ye).length?Ye:et})}catch{}},[]),Te=a.useRef(!1);a.useEffect(()=>{Te.current&&oe(),Te.current=x!=="ai-setup"},[x,oe]);const he=E.find(Q=>Q.id==="github"),Me=!!he,We=he?.authenticated??!1,Re=U?.authenticated??!1,ot=We||Re,J=!We&&Re,ce=a.useCallback(Q=>{if(Q.authenticated)return"connected";const ze=Je?.[Q.id];return ze==="timeout"||ze==="failed"?"retry":Le[Q.id]?"skipped":"not-connected"},[Je,Le]);function ve({status:Q}){const ze={connected:{text:"✓ Connected",className:"auth-status-badge connected"},"not-connected":{text:"Not connected",className:"auth-status-badge not-connected"},skipped:{text:"Skipped",className:"auth-status-badge skipped"},retry:{text:"Retry",className:"auth-status-badge retry"}},{text:Ye,className:et}=ze[Q];return t.jsx("span",{"data-testid":"provider-status-badge",className:et,"data-status":Q,children:Ye})}const Xe=a.useCallback(()=>{if(ot)return"connected";const Q=Je.github;return Q==="pending"?"pending":Q==="failed"||Q==="timeout"?"failed":it?"skipped":"not-connected"},[ot,Je,it]);function ee({status:Q}){const ze={connected:{text:"✓ Connected",className:"auth-status-badge connected"},pending:{text:"⏳ Connecting…",className:"auth-status-badge pending"},failed:{text:"✗ Connection failed",className:"auth-status-badge retry"},skipped:{text:"Skipped",className:"auth-status-badge skipped"},"not-connected":{text:"Not connected",className:"auth-status-badge not-connected"}},{text:Ye,className:et}=ze[Q];return t.jsx("span",{"data-testid":"github-status-badge",className:et,"data-status":Q,children:Ye})}const Ge=a.useCallback(async()=>{try{const Q=await ms();me(Q.models)}catch{}},[]),ct=a.useCallback(async()=>{try{const Q=await Gi();if(Q.defaultProvider&&Q.defaultModelId){const ze=`${Q.defaultProvider}/${Q.defaultModelId}`;le(ze)}}catch{}},[]);a.useEffect(()=>{Promise.all([oe(),Ge(),ct()]).finally(()=>_(!1))},[oe,Ge,ct]),a.useEffect(()=>{const Q=O4("ai-setup");if(Q?.loginOutcomes){const ze=Q.loginOutcomes,Ye={};for(const[et,dt]of Object.entries(ze))dt!=="pending"&&(Ye[et]=dt);Object.keys(Ye).length>0&&Ke(Ye)}},[]);const vt=a.useCallback((Q,ze)=>{ro(x,{completedSteps:b,stepData:{"ai-setup":{loginOutcomes:{[Q]:ze}}}})},[x,b]);a.useEffect(()=>{const Q=Object.entries(Je).filter(([ze,Ye])=>Ye!=="pending");for(const[ze,Ye]of Q)vt(ze,Ye)},[Je,vt]),a.useEffect(()=>()=>{Qe.current&&clearInterval(Qe.current),Object.values(Ee.current).forEach(clearTimeout),Ee.current={}},[]);const bt=a.useCallback(Q=>{Pe(Q),ro(x,{completedSteps:b,stepData:{github:{skipped:Q}}})},[x,b]),ft=a.useCallback(Q=>Q==="complete"?-1:yi.indexOf(Q),[]),gt=a.useCallback(()=>{y(ze=>[...new Set([...ze,x])]),j(ze=>ze.filter(Ye=>Ye!==x)),As("onboarding:step-completed",{step:x}),x==="github"&&!We&&bt(!1);const Q=ft(x);Q>=0&&Q<yi.length-1&&v(yi[Q+1])},[x,We,bt,ft]),_t=a.useCallback(()=>{j(ze=>[...new Set([...ze,x])]),$4(x),As("onboarding:step-skipped",{step:x}),x==="github"&&!We&&bt(!0);const Q=ft(x);Q>=0&&Q<yi.length-1&&v(yi[Q+1])},[x,We,bt,ft]),Rt=a.useCallback(()=>{const Q=x;y(Ye=>Ye.filter(et=>et!==Q)),j(Ye=>Ye.filter(et=>et!==Q)),Q==="github"&&!We&&bt(!1);const ze=ft(x);ze>0&&v(yi[ze-1])},[x,We,bt,ft]),Ft=a.useCallback(()=>{_t()},[_t]),wt=a.useCallback(async Q=>{Ke(ze=>{const Ye=ze[Q];if(Ye&&Ye!=="pending"){const{[Q]:et,...dt}=ze;return dt}return ze}),q(ze=>{if(!(Q in ze))return ze;const Ye={...ze};return delete Ye[Q],Ye}),Ke(ze=>({...ze,[Q]:"pending"})),T(Q),Ve.current=0;try{const{url:ze,instructions:Ye}=await ny(Q);Ye?.trim()&&q(et=>({...et,[Q]:Ye})),window.open(ti(ze),"_blank"),Qe.current=setInterval(async()=>{if(Ve.current++,Ve.current>=rT){Qe.current&&(clearInterval(Qe.current),Qe.current=null),T(null),Ke(et=>({...et,[Q]:"timeout"})),q(et=>{if(!(Q in et))return et;const dt={...et};return delete dt[Q],dt}),n("Login timed out. Please try again.","warning");return}try{const{providers:et,ghCli:dt}=await xr();D(et),Y(dt),et.find(It=>It.id===Q)?.authenticated&&(Qe.current&&(clearInterval(Qe.current),Qe.current=null),T(null),Ke(It=>({...It,[Q]:"success"})),q(It=>{if(!(Q in It))return It;const kn={...It};return delete kn[Q],kn}),Q==="github"&&bt(!1),n("Login successful","success"))}catch{}},2e3)}catch(ze){ze instanceof Error&&ze.message.includes("already in progress")||ze&&typeof ze=="object"&&"status"in ze&&ze.status===409?(n("Login already in progress. Please wait or cancel the current attempt.","warning"),Ke(et=>({...et,[Q]:"failed"}))):(n(ze instanceof Error?ze.message:"Login failed","error"),Ke(et=>({...et,[Q]:"failed"}))),T(null),q(et=>{if(!(Q in et))return et;const dt={...et};return delete dt[Q],dt})}},[n,bt]),At=a.useCallback(Q=>{Qe.current&&(clearInterval(Qe.current),Qe.current=null),T(null),Ve.current=0,Ke(ze=>({...ze,[Q]:"cancelled"})),q(ze=>{if(!(Q in ze))return ze;const Ye={...ze};return delete Ye[Q],Ye})},[]),qt=a.useCallback((Q,ze)=>{se(et=>({...et,[Q]:ze}));const Ye=Ee.current[Q];Ye&&(clearTimeout(Ye),delete Ee.current[Q]),de(et=>{if(!et[Q])return et;const dt={...et};return delete dt[Q],dt}),ie(et=>{if(!et[Q])return et;const dt={...et};return delete dt[Q],dt})},[]),zt=a.useCallback(()=>{const Q=De.current;if(!Q)return;const ze=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof Q.scrollTo=="function"){Q.scrollTo({top:0,behavior:ze?"auto":"smooth"});return}}catch{}Q.scrollTop=0},[]),Wt=a.useCallback(async(Q,ze)=>{const Ye=(ze??ge[Q]??"").trim(),et=tT(Q,Ye);if(et){de(St=>({...St,[Q]:et}));return}const dt=Ee.current[Q];dt&&(clearTimeout(dt),delete Ee.current[Q]),T(Q),de(St=>{const It={...St};return delete It[Q],It}),ie(St=>{if(!St[Q])return St;const It={...St};return delete It[Q],It});try{await iy(Q,Ye),await oe(),zt(),se(St=>{const It={...St};return delete It[Q],It}),de(St=>{if(!St[Q])return St;const It={...St};return delete It[Q],It}),ie(St=>({...St,[Q]:"✓ Key saved"})),Ee.current[Q]=setTimeout(()=>{ie(St=>{if(!St[Q])return St;const It={...St};return delete It[Q],It}),delete Ee.current[Q]},3e3),n("API key saved","success")}catch(St){const It=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";de(kn=>({...kn,[Q]:It})),ie(kn=>{if(!kn[Q])return kn;const sn={...kn};return delete sn[Q],sn}),n(It,"error")}finally{T(null)}},[ge,n,oe,zt]),Ot=a.useCallback(async Q=>{T(Q);try{await ay(Q),await oe(),n("API key removed","success")}catch(ze){n(ze instanceof Error?ze.message:"Failed to clear API key","error")}finally{T(null)}},[n,oe]),Nt=a.useCallback(async Q=>{T(Q);try{await sy(Q),await oe(),n("Logged out","success")}catch(ze){n(ze instanceof Error?ze.message:"Logout failed","error")}finally{T(null)}},[n,oe]),Mt=a.useCallback(Q=>{le(Q)},[]),Ct=a.useCallback(async()=>{try{const Q={modelOnboardingComplete:!0};if(ue){const ze=ue.indexOf("/"),Ye=ze!==-1?ue.slice(0,ze):void 0,et=ze!==-1?ue.slice(ze+1):ue,dt=G.find(St=>St.id===et);dt?(Q.defaultProvider=dt.provider,Q.defaultModelId=dt.id):Ye&&et&&(Q.defaultProvider=Ye,Q.defaultModelId=et)}await ln(Q),vh()}catch{}},[ue,G,ln,vh]),Gt=a.useCallback(async()=>{const Q=[...new Set([...b,"first-task"])];F(!0);try{await Ct(),As("onboarding:completed",{completedSteps:Q,skippedSteps:S}),y(Q),j(ze=>ze.filter(Ye=>Ye!=="first-task")),v("complete")}finally{F(!1)}},[Ct,b,S]),Et=a.useCallback(async()=>{if(!s)return;const Q=M.trim();if(!Q){O("Please enter a task description.");return}O(null),A(!0);let ze=!1;try{const Ye=await np({description:Q},s);$(Ye),k(!0),As("onboarding:first-task-created",{taskId:Ye?.id}),n("Task created","success"),ze=!0}catch(Ye){const et=Ye instanceof Error?Ye.message:"Something went wrong creating your task. Please try again.";O(et),n(et,"error")}finally{A(!1)}ze&&Ct()},[s,M,n,Ct]),H=a.useCallback(async()=>{F(!0);try{await Ct()}finally{F(!1)}As("onboarding:open-new-task",{}),r?.()},[Ct,r]),be=a.useCallback(async()=>{if(ot){F(!0);try{await Ct()}finally{F(!1)}f(!1),e(),As("onboarding:open-github-import",{}),o?.()}},[Ct,ot,e,o]),re=a.useCallback(async()=>{As("onboarding:dismissed",{currentStep:x,completedSteps:b,skippedSteps:S}),F(!0);try{await ln({modelOnboardingComplete:!0})}catch{}f(!1),e()},[x,b,S,e]),N=a.useCallback(()=>{As("onboarding:finished",{}),f(!1),e()},[e]),W=a.useCallback(()=>{const Q=l??V;Q&&(Ct(),c?.(Q),e())},[l,V,Ct,c,e]),Ie=a.useCallback(()=>{Ct(),e()},[Ct,e]);if(!p)return null;const nt=Xe(),yt=E.filter(Q=>Q.id!=="github"),Pt=[...yt].sort(Nh),Tt=Pt.some(Q=>!Q.type||Q.type==="oauth"),tn=Pt.some(Q=>Q.type==="api_key"),nn=yt.filter(Q=>Q.authenticated),Ln=nn.length>0,Jt=!!s,Rn=x==="github"&&!Ln,ke=(()=>{if(!ue)return"";const Q=ue.indexOf("/"),ze=Q===-1?void 0:ue.slice(0,Q),Ye=Q===-1?ue:ue.slice(Q+1),et=G.find(dt=>dt.id===Ye&&(!ze||dt.provider===ze));return et?.name?et.name:ze?`${Vc(ze)} ${Ye}`:ue})(),at=[];if(Jt?at.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):at.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),Ln){const Q=Vc(nn[0]?.id??"");at.push({label:"AI Provider",status:"connected",detail:`${Q} connected — AI agents can work on tasks`})}else yt.length>0&&yt.some(Q=>Le[Q.id])?at.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):at.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});ot?at.push({label:"GitHub",status:"connected",detail:J?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!Me||it?at.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):at.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),ke&&at.push({label:"Default Model",status:"connected",detail:ke});const gn=l??V,Tn=gn?.description?.split(`
|
|
656
|
+
`)[0]?.trim()||gn?.title||"",Pn=new Set(oc),Nn=Pt.filter(Q=>Pn.has(Q.id)).sort((Q,ze)=>{const Ye=oc.indexOf(Q.id),et=oc.indexOf(ze.id);return Ye!==et?Ye-et:Nh(Q,ze)}),es=Pt.filter(Q=>Q.authenticated&&!Pn.has(Q.id)),Sn=Pt.filter(Q=>!Q.authenticated&&!Pn.has(Q.id)),Yt=Q=>{if(Q.id==="claude-cli"&&Q.type==="cli")return t.jsx(M4,{authenticated:Q.authenticated,onToggled:()=>{oe()}},Q.id);if(Q.type==="api_key"){const ze=Kc(Q.id),Ye=sT(Q);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${Q.id}`,className:`onboarding-provider-card${Q.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${Q.id}`,"aria-hidden":"true",children:t.jsx(Dn,{provider:Q.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(Jh,{size:14,className:"onboarding-provider-key-icon"}),Q.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:ze.description}),t.jsx(ve,{status:ce(Q)}),Q.authenticated&&Q.keyHint&&t.jsxs("span",{className:"auth-key-hint",children:["Key: ",Q.keyHint]})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx(aT,{provider:Q,apiKeyInfo:Ye,inputValue:ge[Q.id]??"",isSaving:I===Q.id,error:fe[Q.id],success:xe[Q.id],isConnected:Q.authenticated,onInputChange:qt,onSave:Wt,onClear:Ot})})]},Q.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${Q.id}`,className:`onboarding-provider-card${Q.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${Q.id}`,"aria-hidden":"true",children:t.jsx(Dn,{provider:Q.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:Q.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:Kc(Q.id).description}),t.jsx(ve,{status:ce(Q)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:I===Q.id?t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:Q.authenticated?"Logging out…":"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>At(Q.id),children:"Cancel"})]}):Q.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>Nt(Q.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>wt(Q.id),children:"Login"})}),I===Q.id&&w[Q.id]&&t.jsx(rc,{instructions:w[Q.id],"data-testid":`onboarding-login-instructions-${Q.id}`}),Je[Q.id]==="timeout"&&I!==Q.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),Je[Q.id]==="failed"&&I!==Q.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},Q.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:qe,children:[t.jsxs("div",{className:"model-onboarding-header",children:[t.jsxs("h2",{id:"onboarding-title",className:"model-onboarding-title",children:[x==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(Bn,{size:24})," Set Up AI ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(vs,{size:24})," Connect GitHub ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(Id,{size:24})," Set Up Your Project"]}),x==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(Id,{size:24})," Create Your First Task"]}),x==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx(fn,{size:24})," All Set!"]})]}),x!=="complete"&&t.jsx("button",{className:"modal-close",onClick:re,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(Ut,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:_e.map((Q,ze)=>{const Ye=tt>ze,et=b.includes(Q.key)&&Ye,dt=S.includes(Q.key)&&!b.includes(Q.key)&&Ye,St=et||dt;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[ze>0&&t.jsx("div",{className:`model-onboarding-step-connector ${ze<=tt?"done":""}`}),St?t.jsxs("button",{className:`model-onboarding-step-indicator ${x===Q.key?"active":""} ${et?"done":""} ${dt?"skipped":""}`,onClick:()=>v(Q.key),"aria-label":`Go back to ${Q.label}`,title:`Review ${Q.label}`,children:[t.jsx("span",{className:"step-number",children:et?t.jsx(fn,{size:14}):dt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):ze+1}),t.jsx("span",{className:"step-label",children:Q.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${x===Q.key?"active":""} ${et?"done":""} ${dt?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:et?t.jsx(fn,{size:14}):dt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):ze+1}),t.jsx("span",{className:"step-label",children:Q.label})]})]},Q.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:De,children:[x==="ai-setup"&&t.jsxs("div",{className:"model-onboarding-ai-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Fusion uses AI models to plan, write, and review code for you. Connect an AI provider below to get started — you can use a hosted service or enter an API key."}),t.jsx("p",{className:"onboarding-helper-text model-onboarding-primary-helper",children:"You only need one provider to get started."}),!X&&E.length>0&&(()=>{const Q=E.filter(St=>St.id!=="github"&&St.authenticated).length,ze=E.filter(St=>St.id!=="github").length,Ye=Object.keys(Le).filter(St=>!E.find(It=>It.id===St)?.authenticated).length;if(ze===0)return null;let et="onboarding-provider-summary",dt="";return Q>0?(et+=" onboarding-provider-summary--connected",dt=`✓ ${Q} of ${ze} provider${ze!==1?"s":""} connected`):Ye>0?(et+=" onboarding-provider-summary--skipped",dt=`${Ye} provider${Ye!==1?"s":""} skipped`):(et+=" onboarding-provider-summary--none",dt="No providers connected yet"),t.jsx("div",{className:et,"data-testid":"provider-summary",children:dt})})(),t.jsx(Ys,{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."})}),E.length>0&&!E.some(Q=>Q.authenticated)&&t.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),X?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(rt,{size:24,className:"animate-spin"}),t.jsx("span",{children:"Loading providers…"})]}):E.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"}),Nn.length>0?t.jsx("div",{className:"model-onboarding-providers",children:Nn.map(Q=>Yt(Q))}):t.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),es.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:es.map(Q=>Yt(Q))})]}),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(Ys,{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."})}),G.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(Hn,{models:G,value:ue,onChange:Mt,placeholder:"Select a default model…",label:"Default model"})}),ue&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",G.find(Q=>Q.id===ue)?.name??ue]})})]}),t.jsx(Ys,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:t.jsx("div",{"data-testid":"onboarding-advanced-provider-settings",children:Sn.length>0?t.jsx("div",{className:"model-onboarding-providers",children:Sn.map(Q=>Yt(Q))}):t.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."})})}),Tt&&t.jsx(Ys,{summary:"How does login work?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Clicking Login opens the provider's website in a new tab where you sign in. Once you authorize Fusion, this page will automatically detect the connection. Your credentials are never stored in Fusion."})}),tn&&t.jsx(Ys,{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."})})]})]}),x==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[ot?t.jsx("p",{className:"model-onboarding-description",children:J?"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."}),!ot&&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"})]})}),Rn&&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(Ys,{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."})}),Me?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(vs,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(ee,{status:nt})})]}),We&&(I==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>Nt("github"),children:"Disconnect"}))]}),(nt==="not-connected"||nt==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[I==="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:()=>At("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>wt("github"),children:[t.jsx(vs,{size:16}),"Connect"]}),I==="github"&&w.github&&t.jsx(rc,{instructions:w.github,"data-testid":"onboarding-login-instructions-github"})]}),nt==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:J?"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."}),nt==="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:()=>wt("github"),children:"Retry"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Ft,children:"Skip for now"})]})]}),nt==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),nt==="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:()=>wt("github"),children:"Connect anyway"})})]}),nt==="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(Dn,{provider:"github",size:"lg"})}),J?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:J?"Continue with gh CLI auth →":"Continue without GitHub →"}),J&&(I==="github"?t.jsxs("button",{className:"btn btn-sm",disabled:!0,children:[t.jsx(rt,{size:14,className:"onboarding-spinner"}),"Waiting for OAuth login…"]}):t.jsxs("button",{className:"btn btn-sm",onClick:()=>wt("github"),children:[t.jsx(Dn,{provider:"github",size:"sm"}),"Connect OAuth (optional)"]}))]}),J&&I==="github"&&w.github&&t.jsx(rc,{instructions:w.github,"data-testid":"onboarding-login-instructions-github"})]})]}),x==="project-setup"&&t.jsxs("div",{className:"model-onboarding-project-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Choose your first project before creating or importing tasks. You can register an existing local directory or clone a GitHub repository URL through the setup wizard."}),Jt?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(Ys,{summary:"What does project setup do?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Project setup registers a workspace so Fusion knows where to read files, run commands, and track task changes."})})]}),x==="first-task"&&t.jsxs("div",{className:"model-onboarding-first-task",children:[t.jsx("p",{className:"model-onboarding-description",children:"Create your first task to start the board and launch AI execution."}),R&&gn?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx(fn,{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:gn.id}),Tn&&t.jsx("p",{className:"onboarding-task-created__description",children:Tn}),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:W,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:Ie,children:"Go to Dashboard"})]})]}):t.jsxs(t.Fragment,{children:[Jt?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:Q=>{C(Q.target.value),O(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:Et,disabled:L,"data-testid":"onboarding-first-task-submit",children:L?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),P&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:P}),t.jsx("p",{className:"onboarding-helper-text",children:"Your text has been preserved — fix the issue and try again."})]})]}):t.jsxs("div",{className:"onboarding-project-prerequisite","data-testid":"onboarding-project-prerequisite",children:[t.jsx("p",{className:"onboarding-helper-text",children:"A project must be selected before you can create tasks or import from GitHub."}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:i,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"})]}),t.jsx(iT,{items:at}),Jt&&t.jsxs(t.Fragment,{children:[t.jsx(Ys,{summary:"What happens when I create a task?",children:t.jsx("p",{className:"onboarding-helper-text",children:"A task describes something you want done. Fusion's AI agents will read your description and work on implementing it. You can track progress on the board and review the results."})}),t.jsxs("div",{className:"onboarding-cta-options",children:[t.jsxs("button",{className:"onboarding-cta-card primary",onClick:H,disabled:Se,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(en,{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${ot?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:be,disabled:Se||!ot,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(vs,{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"}),!ot&&t.jsx("small",{className:"onboarding-cta-note",children:"Requires GitHub connection"})]})]})]}),t.jsxs("p",{className:"onboarding-skip-note",children:["You can create tasks anytime from the board, or use"," ",t.jsx("code",{children:"fn task create"})," in the terminal."]})]})]})]}),x==="complete"&&t.jsxs("div",{className:"model-onboarding-complete",children:[t.jsx(fn,{size:48,className:"success-icon"}),t.jsx("p",{children:"Setup complete! Head to the board to create your first task, or explore the dashboard to see what's available."})]})]}),t.jsxs("div",{className:"model-onboarding-footer",children:[x==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:re,disabled:Se,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:_t,children:"Skip setup →"}),t.jsx("button",{className:"btn btn-primary",onClick:gt,children:"Next →"})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Rt,children:"← Back"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:_t,children:"Skip GitHub →"}),t.jsx("button",{className:"btn btn-primary",onClick:gt,children:"Next →"})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Rt,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:gt,disabled:!Jt,children:"Next →"})]}),x==="first-task"&&!R&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Rt,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:Gt,disabled:Se,children:Se?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),x==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:N,children:[t.jsx(fn,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function dg({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 lT=a.lazy(()=>on(()=>import("./SetupWizardModal-BQoo_AvX.js"),__vite__mapDeps([6,1,7,8,9,0,2,10])).then(e=>({default:e.SetupWizardModal}))),cT=a.lazy(()=>on(()=>import("./SettingsModal-BluRnKGd.js"),__vite__mapDeps([11,1,12,13,14,15,0,2,16])).then(e=>({default:e.SettingsModal})));function dT(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{on(()=>import("./SettingsModal-BluRnKGd.js"),__vite__mapDeps([11,1,12,13,14,15,0,2,16]))},{timeout:1500})}function uT({projectId:e,tasks:n,projects:s,currentProject:i,addToast:r,toasts:o,removeToast:l,modalManager:c,projectActions:u,taskHandlers:d,taskOperations:m,deepLink:h,settings:g,onSettingsClose:p,onReopenOnboarding:f}){const[x,v]=a.useState(null),b=c.detailTask?(()=>{const M=n.find(C=>C.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,S=a.useCallback(()=>{c.openNewTask()},[c]),j=a.useCallback(()=>{c.openGitHubImport()},[c]),R=a.useCallback(M=>{v(null),c.closeModelOnboarding(),c.openDetailTask(M)},[c]),k=a.useCallback(async M=>{const C=await d.handleModalCreate(M);return c.modelOnboardingOpen&&v(C),C},[d.handleModalCreate,c.modelOnboardingOpen]);return a.useEffect(()=>{!c.modelOnboardingOpen&&x&&v(null)},[c.modelOnboardingOpen,x]),a.useEffect(()=>{dT()},[]),t.jsxs(t.Fragment,{children:[b&&t.jsx(Ii,{children:t.jsx(cA,{task:b,projectId:e,tasks:n,onClose:h.handleDetailClose,onOpenDetail:c.openDetailTask,onMoveTask:m.moveTask,onDeleteTask:m.deleteTask,onMergeTask:m.mergeTask,onRetryTask:m.retryTask,onDuplicateTask:m.duplicateTask,onTaskUpdated:c.updateDetailTask,addToast:r,prAuthAvailable:g.prAuthAvailable,initialTab:c.detailTaskInitialTab})}),c.settingsOpen&&t.jsx(Ii,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(cT,{onClose:y,addToast:r,initialSection:c.settingsInitialSection,projectId:e,themeMode:g.themeMode,colorTheme:g.colorTheme,onThemeModeChange:g.setThemeMode,onColorThemeChange:g.setColorTheme,onReopenOnboarding:f})})}),t.jsx(uA,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:d.handleGitHubImport,tasks:n,projectId:e}),t.jsx(Ii,{children:t.jsx(fA,{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(Ii,{children:t.jsx(SA,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:d.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx(WA,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx(GA,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx(fR,{initialWorkspace:c.fileBrowserWorkspace,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),t.jsx(NR,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e,anchorRect:c.usageAnchorRect}),t.jsx(ZR,{isOpen:c.systemStatsOpen,onClose:c.closeSystemStats,projectId:e}),c.schedulesOpen&&t.jsx(qR,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx(Ii,{children:t.jsx(GR,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:k,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan,onSubtaskBreakdown:c.openSubtaskBreakdown})}),t.jsx(i4,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:i,onOpenTaskDetail:M=>{const C=n.find(L=>L.id===M);C&&c.openDetailTask(C)}}),t.jsx(Ii,{children:t.jsx(r4,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx(Ii,{children:t.jsx(b4,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(_4,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(a.Suspense,{fallback:null,children:t.jsx(lT,{onProjectRegistered:u.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(oT,{onComplete:u.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:u.handleAddProject,onOpenNewTask:S,onOpenGitHubImport:j,firstCreatedTask:x,onViewTask:R}),t.jsx(dg,{toasts:o,onRemove:l})]})}function mT({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 Gc=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function hT(e,n){if(n==="ready")return"done";const s=Gc.findIndex(r=>r.id===n),i=Gc.findIndex(r=>r.id===e);return i<s?"done":i===s?"active":"pending"}function pT({stage:e}){const[n]=a.useState(()=>rv());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:Gc.map(s=>{const i=hT(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(rt,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:s.label})]},s.id)})})]})})}const fT=5e3;function gT(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function xT(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++,jo(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 bT(e,n,s,i){const[r,o]=a.useState({globalPause:!1,enginePaused:!1,maxConcurrent:2}),[l,c]=a.useState(!0),[u,d]=a.useState(null),m=a.useRef(null),h=a.useRef(null),g=a.useCallback(async()=>{h.current&&h.current.abort(),h.current=new AbortController;try{c(!0),d(null);const v=await 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(()=>(g(),()=>{h.current&&h.current.abort()}),[g]),a.useEffect(()=>(m.current&&clearInterval(m.current),m.current=setInterval(()=>{g()},fT),()=>{m.current&&(clearInterval(m.current),m.current=null)}),[g]);const p=xT(e,s,i),f=gT(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:f,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:u,refresh:g}}const vT={planning:ei,subtask:Hi,mission_interview:us,milestone_interview:us,slice_interview:us},yT={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function jT({sessions:e,generating:n,needsInput:s,onOpenSession:i,onDismissSession:r}){const{confirm:o}=Hs(),[l,c]=a.useState(!1),[u,d]=a.useState(new Set),m=a.useRef(null),h=a.useRef(new Map),g=a.useRef(null),{activeTabMap:p}=Ra(),f=a.useMemo(()=>Ji(),[]);if(a.useEffect(()=>{if(!l)return;const b=y=>{m.current&&!m.current.contains(y.target)&&c(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[l]),a.useEffect(()=>{const b=new Set,y=new Map;for(const S of e){const j=p.get(S.id),R=[S.status,S.updatedAt,j?.tabId??S.lockedByTab??"",j?.stale?"stale":"fresh"].join("|"),k=h.current.get(S.id);k&&k!==R&&b.add(S.id),y.set(S.id,R)}if(h.current=y,b.size!==0)return d(b),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{d(new Set),g.current=null},500),()=>{g.current&&(clearTimeout(g.current),g.current=null)}},[p,e]),e.length===0)return null;const x=e.length,v=s>0;return t.jsxs("div",{ref:m,className:"background-tasks-indicator",children:[t.jsxs("button",{className:`background-tasks-indicator__pill${v?" background-tasks-indicator__pill--attention":""}`,onClick:()=>c(b=>!b),title:`${x} background AI task${x!==1?"s":""}${s>0?` (${s} need${s!==1?"":"s"} input)`:""}`,children:[n>0&&t.jsx(rt,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&t.jsx(pc,{size:12}),t.jsxs("span",{children:["AI ",x]})]}),l&&t.jsxs("div",{className:"background-tasks-indicator__popover",children:[t.jsx("div",{className:"background-tasks-indicator__popover-header",children:"Background Tasks"}),t.jsx("div",{className:"background-tasks-indicator__popover-list",children:e.map(b=>{const y=vT[b.type],S=b.status==="generating",j=b.status==="awaiting_input",R=b.status==="error",k=p.get(b.id),M=k?.tabId??b.lockedByTab??null,C=!!(M&&M!==f&&!k?.stale),L=u.has(b.id);return t.jsxs("div",{className:`background-tasks-indicator__item${L?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:L?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:L?"translateY(-1px)":void 0},onClick:async()=>{C&&!await o({title:"Open Active Session",message:"This session is active in another tab. Open anyway?"})||(i(b),c(!1))},children:[R?t.jsx(as,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--color-error)"}}):t.jsx(y,{size:14,className:"background-tasks-indicator__session-icon"}),t.jsxs("div",{className:"background-tasks-indicator__session-content",children:[t.jsx("div",{className:"background-tasks-indicator__session-title",children:b.title}),t.jsxs("div",{className:"background-tasks-indicator__session-meta",children:[R?"Failed":yT[b.type],S&&" — generating...",j&&!C&&" — needs input",j&&C&&" — active in another tab"]})]}),S&&t.jsx(rt,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),j&&!C&&t.jsx(pc,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),j&&C&&t.jsx(Do,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),t.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:A=>{A.stopPropagation(),r(b.id)},title:"Dismiss",children:t.jsx(Ut,{size:12})})]},b.id)})})]})]})}function kT(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 wT(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:jn};case"paused":return{label:"Paused",color:"var(--triage)",icon:Xs};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:Bn}}}function NT({tasks:e,projectId:n,taskStuckTimeoutMs:s,backgroundSessions:i,backgroundGenerating:r,backgroundNeedsInput:o,onOpenBackgroundSession:l,onDismissBackgroundSession:c,lastFetchTimeMs:u,currentProjectPath:d,onOpenProjectDirectory:m}){const{stats:h,loading:g,error:p}=bT(e,n,s,u),[f,x]=a.useState(!1),v=a.useMemo(()=>wT(h.executorState),[h.executorState]),b=a.useMemo(()=>kT(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(Xc,{size:14}),p]})}):g&&h.runningTaskCount===0?t.jsx("div",{className:"executor-status-bar executor-status-bar--loading",role:"status","aria-label":"Executor status",children:t.jsx("span",{className:"executor-status-bar__loading-text",children:"Loading..."})}):t.jsxs("div",{className:`executor-status-bar ${h.executorState==="running"?"executor-status-bar--running":""}`,role:"status","aria-label":"Executor status",children:[i&&i.length>0&&l&&c&&t.jsxs(t.Fragment,{children:[t.jsx(jT,{sessions:i,generating:r??0,needsInput:o??0,onOpenSession:l,onDismissSession:c}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--queued","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Queued"}),t.jsx("span",{className:"executor-status-bar__count",children:h.queuedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--running ${h.runningTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Running"}),t.jsx("span",{className:"executor-status-bar__count",children:h.runningTaskCount}),t.jsx("span",{className:"executor-status-bar__separator","aria-hidden":"true",children:"/"}),t.jsx("span",{className:"executor-status-bar__max",children:h.maxConcurrent})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),h.stuckTaskCount>0&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--stuck",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--stuck executor-status-bar__indicator--active","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Stuck"}),t.jsx("span",{className:"executor-status-bar__count executor-status-bar__count--error",children:h.stuckTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--blocked ${h.blockedTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Blocked"}),t.jsx("span",{className:`executor-status-bar__count ${h.blockedTaskCount>0?"executor-status-bar__count--warning":""}`,children:h.blockedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--review","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"In Review"}),t.jsx("span",{className:"executor-status-bar__count",children:h.inReviewCount})]}),d&&m&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--project-directory",children:[t.jsx("button",{className:`executor-status-bar__folder-toggle${f?" executor-status-bar__folder-toggle--active":""}`,onClick:()=>x(S=>!S),"aria-label":f?"Hide project directory":"Show project directory","aria-expanded":f,"data-testid":"executor-project-path-toggle",title:f?"Hide project directory":"Show project directory",children:t.jsx(Un,{size:12,"aria-hidden":"true"})}),f&&t.jsx("button",{className:"executor-status-bar__project-path",onClick:m,title:d,"data-testid":"executor-project-path-link",children:d})]})]}),t.jsx("div",{className:"executor-status-bar__spacer"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--time",children:[t.jsx(wi,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__time",children:b})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx(y,{size:12,style:{color:v.color},"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__state",style:{color:v.color},children:v.label})]})]})}const ST={planning:ei,subtask:Hi,mission_interview:us,milestone_interview:us,slice_interview:us},CT={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},Li=new Set;function ET({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:i}){const[r,o]=a.useState(0),l=()=>o(f=>f+1);a.useEffect(()=>{if(Li.size===0)return;const f=new Map(e.map(v=>[v.id,v]));let x=!1;for(const v of Li){const b=f.get(v);b&&b.status!=="awaiting_input"&&b.status!=="error"&&(Li.delete(v),x=!0)}x&&l()},[e]);const c=a.useMemo(()=>e.filter(f=>(f.status==="awaiting_input"||f.status==="error")&&!Li.has(f.id)),[e,r]);if(c.length===0)return null;const u=c.filter(f=>f.status==="awaiting_input").length,d=c.filter(f=>f.status==="error").length;let m="";u>0&&d>0?m=`${u} AI session${u===1?"":"s"} need${u===1?"s":""} your input, ${d} failed`:u>0?m=`${u} AI session${u===1?"":"s"} need${u===1?"s":""} your input`:d>0&&(m=`${d} AI session${d===1?"":"s"} failed`);const h=f=>{Li.add(f),l()},g=f=>{Li.delete(f.id),l(),n(f)},p=()=>{for(const f of c)Li.add(f.id);l(),i()};return t.jsxs("section",{className:"session-notification-banner",role:"region","aria-live":"polite","aria-label":"AI sessions needing input or failed",children:[t.jsxs("div",{className:"session-notification-banner__header",children:[t.jsxs("div",{className:"session-notification-banner__headline",children:[t.jsx(as,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:m})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[t.jsx(Ut,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Dismiss all"})]})]}),t.jsx("div",{className:"session-notification-banner__list",children:c.map(f=>{const x=ST[f.type],v=f.status==="error";return t.jsxs("article",{className:`session-notification-banner__item${v?" session-notification-banner__item--error":""}`,"data-session-type":f.type,"data-session-status":f.status,children:[t.jsxs("div",{className:"session-notification-banner__item-main",children:[v?t.jsx(as,{size:16,className:"session-notification-banner__type-icon session-notification-banner__type-icon--error","aria-hidden":"true"}):t.jsx(x,{size:16,className:"session-notification-banner__type-icon","aria-hidden":"true"}),t.jsxs("div",{className:"session-notification-banner__text",children:[t.jsx("p",{className:"session-notification-banner__title",title:f.title,children:f.title}),t.jsx("p",{className:"session-notification-banner__meta",children:v?"Failed":CT[f.type]})]})]}),t.jsxs("div",{className:"session-notification-banner__actions",children:[t.jsx("button",{className:"session-notification-banner__resume",onClick:()=>g(f),children:v?"Retry":"Resume"}),t.jsx("button",{className:"session-notification-banner__dismiss",onClick:()=>{h(f.id),s(f.id)},"aria-label":`Dismiss ${f.title}`,children:t.jsx(Ut,{size:14,"aria-hidden":"true"})})]})]},f.id)})})]})}function _T({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/releases",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(Ut,{size:16,"aria-hidden":"true"})})]})}function MT({onResume:e}){const n=z4();if(!n)return null;const s=n.completedSteps.length,i=yi.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(Xn,{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:()=>{As("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),e()},children:[t.jsx(jn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function AT({onOpenSettings:e,onOpenModelOnboarding:n}){const s=Ea(),i=rg(),[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 b=!1;return(async()=>{try{o(!0),c(!1);const[S,j]=await Promise.all([xr(),Gi()]);if(b)return;const R=S.providers??[],k=R.find(P=>P.id==="github"),C=!R.some(P=>P.id!=="github"&&P.authenticated),L=!j.defaultProvider&&!j.defaultModelId,A=k?!k.authenticated:!1;h({needsAiProvider:C,needsDefaultModel:L,needsGitHub:A})}catch{b||c(!0)}finally{b||o(!1)}})(),()=>{b=!0}},[s,i]);const g=a.useCallback(()=>{D4(),d(!0)},[]),p=a.useCallback(()=>{n()},[n]),f=a.useCallback(()=>{e("global-models")},[e]),x=a.useCallback(()=>{e("authentication")},[e]),v=a.useMemo(()=>{const b=[];return m.needsAiProvider&&b.push({id:"ai-provider",title:"Connect AI Provider",description:"Connect an AI provider to enable AI agents for task planning and code generation",actionLabel:"Set Up AI",onAction:p,icon:Bn}),m.needsDefaultModel&&b.push({id:"default-model",title:"Select Default Model",description:"Choose a default AI model for task execution",actionLabel:"Choose Model",onAction:f,icon:Jh}),m.needsGitHub&&b.push({id:"github",title:"Connect GitHub",description:"Connect GitHub to import issues and track pull requests",actionLabel:"Connect GitHub",onAction:x,icon:vs}),b},[m.needsAiProvider,m.needsDefaultModel,m.needsGitHub,x,f,p]);return!s||i||u||r||l||v.length===0?null:t.jsxs("section",{className:"post-onboarding-recommendations",role:"region","aria-label":"Setup recommendations",children:[t.jsxs("div",{className:"post-onboarding-recommendations__main",children:[t.jsx("div",{className:"post-onboarding-recommendations__icon","aria-hidden":"true",children:t.jsx(ei,{size:18,"aria-hidden":!0})}),t.jsxs("div",{className:"post-onboarding-recommendations__content",children:[t.jsx("h2",{className:"post-onboarding-recommendations__title",children:"Recommended Next Steps"}),t.jsx("p",{className:"post-onboarding-recommendations__description",children:"Complete these setup items to get the most out of Fusion."}),t.jsx("ul",{className:"post-onboarding-recommendations__list",children:v.map(b=>{const y=b.icon;return t.jsxs("li",{className:"post-onboarding-recommendations__item",children:[t.jsxs("span",{className:"post-onboarding-recommendations__item-icon","aria-hidden":"true",children:[t.jsx(as,{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:b.title}),t.jsx("span",{children:b.description})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-primary",onClick:b.onAction,children:b.actionLabel})]},b.id)})})]})]}),t.jsx("button",{type:"button",className:"post-onboarding-recommendations__dismiss",onClick:g,"aria-label":"Dismiss recommendations",children:t.jsx(Ut,{size:16,"aria-hidden":!0})})]})}function RT({size:e=20}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:t.jsx("path",{d:"M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.203 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.942.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z"})})}function lc(e){return e>99?"99+":String(e)}function TT({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:g,onOpenScripts:p,onToggleTerminal:f,onOpenFiles:x,onOpenGitHubImport:v,onOpenPlanning:b,onResumePlanning:y,activePlanningSessionCount:S=0,onOpenUsage:j,onRunScript:R,projectId:k,onViewAllProjects:M,showSkillsTab:C,experimentalFeatures:L}){const A=Tr(),[P,O]=a.useState(!1),[V,$]=a.useState(!1),[E,D]=a.useState({}),[U,Y]=a.useState(!1),X=a.useMemo(()=>Object.entries(E).sort(([F],[ge])=>F.localeCompare(ge)),[E]);a.useEffect(()=>{if(!V)return;let F=!1;return Y(!0),br(k).then(ge=>{F||D(ge)}).catch(()=>{F||D({})}).finally(()=>{F||Y(!1)}),()=>{F=!0}},[V,k]);const _=a.useCallback(()=>O(!1),[]),I=a.useCallback(F=>{_(),F?.()},[_]);if(a.useEffect(()=>{if(!P)return;const F=ge=>{ge.key==="Escape"&&O(!1)};return document.addEventListener("keydown",F),()=>document.removeEventListener("keydown",F)},[P]),A!=="mobile"||i||r)return null;const T=S>0&&y?y:b,w=!!L?.roadmap,q=!!C,G=!!L?.todoView,me=w&&(!q||e==="roadmaps"),ue=q&&(!w||e!=="roadmaps"),le=q&&!ue,Se=e==="documents"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||e==="todos"&&G||e==="roadmaps"&&!me||e==="skills"&&!ue;return t.jsxs(t.Fragment,{children:[t.jsxs("nav",{className:`mobile-nav-bar${s?" mobile-nav-bar--with-footer":""}`,role:"tablist","aria-label":"Primary navigation",children:[t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="board"||e==="list"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-tasks",role:"tab","aria-selected":e==="board"||e==="list",onClick:()=>{n(e==="board"||e==="list"?e:"board")},children:[t.jsx(qi,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Tasks"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="agents"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-agents",role:"tab","aria-selected":e==="agents",onClick:()=>n("agents"),children:[t.jsx(yn,{}),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(us,{}),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(ji,{}),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(xa,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),d>0&&t.jsx("span",{className:"mobile-nav-tab-badge",children:lc(d)})]}),ue&&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(Bn,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),me&&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(vc,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Roadmaps"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${Se?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>O(F=>!F),children:[t.jsx(fc,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),P&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mobile-more-sheet-backdrop",onClick:_}),t.jsxs("div",{className:"mobile-more-sheet",children:[t.jsx("div",{className:"mobile-more-sheet-handle"}),t.jsx("div",{className:"mobile-more-sheet-title",children:"Navigate"}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-mailbox",onClick:()=>I(u),children:[t.jsx(xa,{}),t.jsx("span",{children:"Mailbox"}),d>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:lc(d)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>I(l),children:[t.jsx(Ps,{}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-system-stats",onClick:()=>I(c),children:[t.jsx(pr,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>I(m),children:[t.jsx(Zs,{}),t.jsx("span",{children:"Git Manager"})]}),t.jsxs("div",{className:"mobile-more-split-row",children:[t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-split-primary","data-testid":"mobile-more-item-terminal",onClick:()=>I(f),children:[t.jsx(ci,{}),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":V,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(pn,{size:14,className:`mobile-more-chevron${V?" mobile-more-chevron--open":""}`})})]}),V&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:U?t.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[t.jsx(rt,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):X.length>0?t.jsxs(t.Fragment,{children:[X.map(([F,ge])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${F}`,onClick:()=>{R&&R(F,ge),_(),$(!1)},children:[t.jsx(jn,{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:()=>{_(),$(!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:()=>{_(),$(!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:()=>I(x),children:[t.jsx(Un,{}),t.jsx("span",{children:"Files"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>I(T),children:[t.jsx(ei,{}),t.jsx("span",{children:"Planning"}),S>0&&t.jsx("span",{className:"mobile-more-item-badge",children:lc(S)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>I(h),children:[t.jsx(jc,{}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>I(g),children:[t.jsx(wi,{}),t.jsx("span",{children:"Automation"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>I(v),children:[t.jsx(RT,{}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>I(j),children:[t.jsx(Ps,{}),t.jsx("span",{children:"Usage"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>I(M),children:[t.jsx(Gh,{}),t.jsx("span",{children:"Projects"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>I(()=>n("documents")),children:[t.jsx(Ui,{}),t.jsx("span",{children:"Documents"})]}),le&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>I(()=>n("skills")),children:[t.jsx(Bn,{}),t.jsx("span",{children:"Skills"})]}),w&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-roadmaps",onClick:()=>I(()=>n("roadmaps")),children:[t.jsx(vc,{}),t.jsx("span",{children:"Roadmaps"})]}),L?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>I(()=>n("insights")),children:[t.jsx(Xn,{}),t.jsx("span",{children:"Insights"})]}),L?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>I(()=>n("memory")),children:[t.jsx(ho,{}),t.jsx("span",{children:"Memory"})]}),L?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{I(()=>n("dev-server"))},children:[t.jsx(pr,{size:14}),t.jsx("span",{children:"Dev Server"})]}),G&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-todos",onClick:()=>I(()=>n("todos")),children:[t.jsx(Xh,{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:()=>I(o),children:[t.jsx(or,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function PT({agents:e,filter:n,highlightedIndex:s,visible:i,onSelect:r,position:o="below"}){const l=a.useMemo(()=>{const c=n.trim().toLowerCase();return c?e.filter(u=>u.name.toLowerCase().includes(c)):e},[e,n]);return i?t.jsx("div",{className:`agent-mention-popup agent-mention-popup--${o}`,"data-testid":"agent-mention-popup",role:"listbox","aria-label":"Agent mention suggestions",children:l.length===0?t.jsx("div",{className:"agent-mention-empty",children:"No agents found"}):l.map((c,u)=>t.jsxs("button",{type:"button",className:`agent-mention-item${u===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${c.id}`,onMouseDown:d=>d.preventDefault(),onClick:()=>r(c),role:"option","aria-selected":u===s,children:[t.jsx(yn,{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 Ad="__fn_agent__";function ug(e,n){const s=typeof e=="string"?e.trim():"",i=typeof n=="string"?n.trim():"";return!s||!i?{}:{modelProvider:s,modelId:i}}function Sh(e,n,s){const i=typeof e=="string"?e.trim():"",r=ug(n,s),o=i||(r.modelProvider&&r.modelId?Ad:"");return o?{agentId:o,...r}:null}function cc(e,n,s){const i=ug(n,s),r=i.modelProvider??"",o=i.modelId??"";return`${e}::${r}/${o}`}function IT(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 Ch(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:IT(e.metadata),createdAt:e.createdAt}}function $T(e,n){const[s,i]=a.useState(null),[r,o]=a.useState(!1),[l,c]=a.useState([]),[u,d]=a.useState(!1),[m,h]=a.useState(!1),[g,p]=a.useState(""),[f,x]=a.useState(""),[v,b]=a.useState([]),[y,S]=a.useState(""),j=a.useRef(null),R=a.useRef(!1),k=a.useRef(""),M=a.useRef(""),C=a.useRef(null);a.useEffect(()=>{k.current=y},[y]);const L=a.useCallback(async X=>{const _={agentId:X.agentId};return X.modelProvider&&X.modelId&&(_.modelProvider=X.modelProvider,_.modelId=X.modelId),(await Xk(_,e)).session},[e]),A=a.useCallback(async(X,_,I)=>{const T=Sh(X,_,I);if(!T)return;const w=cc(T.agentId,T.modelProvider,T.modelId);o(!0);try{const{session:q}=await Qk({agentId:T.agentId,modelProvider:T.modelProvider,modelId:T.modelId},e);if(q)i(q),M.current=w;else{const G=await L(T);i(G),M.current=w}}catch(q){console.error("[useQuickChat] Failed to initialize session:",q),n?.("Failed to initialize chat","error")}finally{o(!1)}},[e,n,L]),P=a.useCallback(async()=>{if(s){d(!0);try{const X=await au(s.id,{limit:50},e);c(X.messages.map(Ch))}catch(X){console.error("[useQuickChat] Failed to load messages:",X)}finally{d(!1)}}},[s,e]);a.useEffect(()=>{s?P():c([])},[s,P]);const O=a.useCallback(async()=>{if(s){d(!0);try{const X=await au(s.id,{limit:50},e);c(X.messages.map(Ch))}catch(X){console.error("[useQuickChat] Failed to reload messages:",X)}finally{d(!1)}}},[s,e]),V=a.useCallback(async(X,_,I)=>{const T=Sh(X,_,I);if(!T)return;const w=cc(T.agentId,T.modelProvider,T.modelId);C.current=T;const q=w===M.current&&s;if(q||(j.current&&(j.current.close(),j.current=null),p(""),x(""),b([]),h(!1)),q){await O();return}i(null),c([]),M.current=w,await A(T.agentId,T.modelProvider,T.modelId)},[A,O,s]),$=a.useCallback(async(X,_)=>{await V(Ad,X,_)},[V]),E=a.useCallback(async()=>{const X=C.current;if(!X)return;const _=cc(X.agentId,X.modelProvider,X.modelId);j.current&&(j.current.close(),j.current=null),p(""),x(""),b([]),h(!1),c([]),i(null),o(!0);try{const I=await L(X);i(I),M.current=_}catch(I){console.error("[useQuickChat] Failed to start a fresh session:",I),n?.("Failed to start a new chat","error")}finally{o(!1)}},[n,L]),D=a.useCallback(()=>{s&&(R.current=!0,j.current?.close(),j.current=null,Zk(s.id,e).catch(()=>{}),h(!1),p(""),x(""),b([]))},[s,e]),U=a.useCallback(()=>{k.current="",S("")},[]),Y=a.useCallback(X=>{if(!s||!X.trim())return;if(m){k.current=X,S(X);return}R.current=!1,j.current&&(j.current.close(),j.current=null);const I={id:`temp-${Date.now()}`,sessionId:s.id,role:"user",content:X,createdAt:new Date().toISOString()};c(me=>[...me,I]),p(""),x(""),b([]),h(!0);let T="",w="",q=[];const G={onThinking:me=>{w+=me,x(w)},onText:me=>{T+=me,p(T)},onToolStart:me=>{q=[...q,{toolName:me.toolName,args:me.args,isError:!1,status:"running"}],b(q)},onToolEnd:me=>{const ue=[...q];for(let le=ue.length-1;le>=0;le--){const Se=ue[le];if(Se?.toolName===me.toolName&&Se.status==="running"){ue[le]={...Se,status:"completed",isError:me.isError,result:me.result},q=ue,b(ue);return}}q=[...ue,{toolName:me.toolName,isError:me.isError,result:me.result,status:"completed"}],b(q)},onDone:me=>{const ue={id:me.messageId||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:T,thinkingOutput:w||void 0,toolCalls:q.length>0?q:void 0,createdAt:new Date().toISOString()};c(Se=>[...Se,ue]),p(""),x(""),b([]),h(!1),j.current=null;const le=k.current.trim();le&&(k.current="",S(""),Y(le))},onError:me=>{if(p(""),x(""),b([]),h(!1),j.current=null,console.error("[useQuickChat] Stream error:",me),n?.("Failed to get response","error"),!R.current){const ue=k.current.trim();ue&&(k.current="",S(""),Y(ue))}O()}};j.current=ew(s.id,X,G,void 0,e)},[s,m,e,n,O]);return a.useEffect(()=>()=>{j.current&&(j.current.close(),j.current=null)},[]),a.useMemo(()=>({activeSession:s,sessionsLoading:r,messages:l,messagesLoading:u,isStreaming:m,streamingText:g,streamingThinking:f,streamingToolCalls:v,pendingMessage:y,sendMessage:Y,stopStreaming:D,clearPendingMessage:U,switchSession:V,startModelChat:$,startFreshSession:E,loadMessages:P,reloadMessages:O}),[s,r,l,u,m,g,f,v,y,Y,D,U,V,$,E,P,O])}function DT(e,n){const[s,i]=a.useState([]),[r,o]=a.useState(null),[l,c]=a.useState(!1),u=a.useCallback(async g=>{c(!0);try{const p=n?.filterState,f=p&&p!=="all"?{state:p}:void 0,x=n?.showSystemAgents??!1,v=await Ma({...f,...g,includeEphemeral:g?.includeEphemeral??x},e),b=Array.from(new Map(v.map(y=>[y.id,y])).values());i(b)}catch(p){console.error("Failed to load agents:",p)}finally{c(!1)}},[e,n?.filterState,n?.showSystemAgents]),d=a.useCallback(async()=>{try{const g=await Tj(e);o(g)}catch(g){console.error("Failed to load agent stats:",g)}},[e]);a.useEffect(()=>{u(),d()},[u,d]),a.useEffect(()=>{const g=e?`?projectId=${encodeURIComponent(e)}`:"",p=()=>{u(),d()};return qs(`/api/events${g}`,{events:{"agent:created":p,"agent:updated":p,"agent:deleted":p,"agent:stateChanged":p}})},[e,u,d]);const m=n?.showSystemAgents??!1,h=s.filter(g=>g.state!=="active"&&g.state!=="running"?!1:m||!jw(g));return{agents:s,activeAgents:h,stats:r,isLoading:l,loadAgents:u,loadStats:d}}function LT({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=rw(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(Wh,{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 zT=200;function FT(e={}){const{projectId:n,workspace:s="project"}=e,[i,r]=a.useState(!1),[o,l]=a.useState(""),[c,u]=a.useState(-1),[d,m]=a.useState([]),[h,g]=a.useState(!1),[p,f]=a.useState(0),x=a.useRef(null),v=a.useRef(null);a.useEffect(()=>()=>{x.current&&clearTimeout(x.current),v.current?.abort()},[]);const b=a.useCallback((k,M)=>{if(M<0||M>k.length){r(!1);return}const C=L=>/[a-zA-Z0-9/_.-]/.test(L);for(let L=M-1;L>=0;L--){if(k[L]==="#")if(L===0){const A=k.slice(L+1,M);u(L),l(A),f(0),r(!0);return}else{const A=k[L-1];if(/[\s,.;:!?'"()[\]{}]/.test(A)){const P=k.slice(L+1,M);u(L),l(P),f(0),r(!0);return}r(!1);return}if(!C(k[L])){r(!1);return}}r(!1)},[]),y=a.useCallback(()=>{r(!1),l(""),u(-1),m([]),f(0),g(!1)},[]),S=a.useCallback(async k=>{if(!k.trim()){m([]),g(!1);return}v.current?.abort(),v.current=new AbortController;try{g(!0);const M=await Oy(k,s,n);m(M.files),f(0)}catch(M){M.name!=="AbortError"&&m([])}finally{g(!1)}},[s,n]);a.useEffect(()=>{if(i)return x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{S(o)},zT),()=>{x.current&&clearTimeout(x.current)}},[o,i,S]);const j=a.useCallback((k,M)=>{if(!i||c<0)return M;const C=M.slice(0,c),L=M.slice(c+1),A=L.match(/[\s]|$/),P=A?A.index:L.length,O=L.slice(P);return`${C}#${k.path}${O}`},[i,c]),R=a.useCallback((k,M)=>{if(!i||d.length===0)return!1;switch(k.key){case"ArrowDown":return k.preventDefault(),f(C=>Math.min(C+1,d.length-1)),!0;case"ArrowUp":return k.preventDefault(),f(C=>Math.max(C-1,0)),!0;case"Enter":case"Tab":return d[p]?(k.preventDefault(),!0):!1;case"Escape":return k.preventDefault(),y(),!0;default:return!1}},[i,d,p,y]);return{mentionActive:i,files:d,loading:h,mentionQuery:o,selectedIndex:p,setSelectedIndex:f,detectMention:b,selectFile:j,dismissMention:y,handleKeyDown:R}}function OT(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let dc=null;function BT(){return dc===null&&(dc=window.innerHeight),dc}function UT(){if(typeof window>"u"||!window.visualViewport)return 0;const e=window.visualViewport,n=Math.max(0,window.innerHeight-e.offsetTop-e.height);if(n>0)return n;const i=BT()-e.offsetTop-e.height;return i>=30&&i>80?i:0}function mg({enabled:e=!0}={}){const[n,s]=a.useState(0),[i,r]=a.useState(null);return a.useEffect(()=>{if(!e||!OT()){s(0),r(null);return}const o=window.visualViewport;if(!o){s(0),r(null);return}const l=()=>{const c=UT();s(c),r(c>0?o.height:null)};return l(),o.addEventListener("resize",l),o.addEventListener("scroll",l),()=>{o.removeEventListener("resize",l),o.removeEventListener("scroll",l),s(0),r(null)}},[e]),{keyboardOverlap:n,viewportHeight:i}}function uo(e,n){return e.length<=n?e:`${e.slice(0,n)}…`}function HT(e){if(!e)return null;const n=Object.entries(e);return n.length===0?null:n.map(([s,i])=>{let r="";if(typeof i=="string")r=i;else try{r=JSON.stringify(i)}catch{r=String(i)}return`${s}=${uo(r,50)}`}).join(", ")}function qT(e){if(e===void 0)return null;if(typeof e=="string")return uo(e,200);try{return uo(JSON.stringify(e),200)}catch{return uo(String(e),200)}}function Eh(e,n){const s=e.status==="running",i=e.status==="completed"&&e.isError,r=HT(e.args),o=qT(e.result),l=s?r:o?`result: ${o}`:r?`args: ${r}`:null,c=s?"running":i?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${s?" chat-tool-call--running":""}${i?" chat-tool-call--error":""}`,open:s,children:[t.jsxs("summary",{children:[t.jsx("span",{className:"chat-tool-call-status-dot","aria-hidden":"true"}),t.jsx("span",{className:"chat-tool-call-name",children:e.toolName}),l&&t.jsx("span",{className:"chat-tool-call-preview",title:l,children:l}),t.jsx("span",{className:"chat-tool-call-status-text",children:c})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[r&&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:r})]}),o&&t.jsxs("div",{className:`chat-tool-call-row${i?" 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:o})]})]})]},`${e.toolName}-${n}`)}function VT({toolCalls:e,compact:n=!1}){if(!e||e.length===0)return null;const s=`chat-tool-calls${n?" chat-tool-calls--compact":""}`;if(e.length===1)return t.jsxs("div",{className:s,"data-testid":"chat-tool-calls",children:[t.jsxs("div",{className:"chat-tool-calls-header",children:[t.jsx(Dd,{size:12,"aria-hidden":"true"}),t.jsx("span",{children:"Tool calls"})]}),Eh(e[0],0)]});const i=e.filter(c=>c.status==="completed"&&!c.isError).length,r=e.filter(c=>c.status==="running").length,o=e.filter(c=>c.status==="completed"&&c.isError).length,l=r>0;return t.jsx("div",{className:s,"data-testid":"chat-tool-calls",children:t.jsxs("details",{className:"chat-tool-calls-group",open:l,children:[t.jsxs("summary",{className:"chat-tool-calls-group-summary",children:[t.jsxs("div",{className:"chat-tool-calls-header",children:[t.jsx(Dd,{size:12,"aria-hidden":"true"}),t.jsxs("span",{children:[e.length," tool calls"]})]}),t.jsxs("span",{className:"chat-tool-calls-group-status",children:[i>0&&t.jsxs("span",{className:"chat-tool-calls-group-count",children:[i," completed"]}),r>0&&t.jsxs("span",{className:"chat-tool-calls-group-count chat-tool-calls-group-count--running",children:[r," running"]}),o>0&&t.jsxs("span",{className:"chat-tool-calls-group-count chat-tool-calls-group-count--error",children:[o," error"]})]})]}),t.jsx("div",{className:"chat-tool-calls-group-items",children:e.map((c,u)=>Eh(c,u))})]})})}function WT(e){return`${e.name?.trim()||e.id} (${e.role})`}function KT(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 GT(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 _h(e,n=!1){return t.jsx(VT,{toolCalls:e,compact:n})}const JT={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 YT(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 oo={width:320,height:400},la={width:280,height:260},Jc=768,ca=8;function QT(e,n){const s=a.useCallback(()=>{if(typeof window>"u")return 0;const x=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return x&&parseFloat(x)||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 x=`fusion-quick-chat-position-${e||"default"}`;try{const v=localStorage.getItem(x);if(v){const b=JSON.parse(v);if(typeof b.x=="number"&&typeof b.y=="number"&&!isNaN(b.x)&&!isNaN(b.y))return b}}catch{}return i()}),[l,c]=a.useState(!1),u=a.useRef(null),d=n??a.useRef(!1),m=a.useCallback(x=>{if(typeof window>"u")return x;const v=48,b=window.innerWidth<=768?4:8,y=window.innerWidth<=768?44:0,S=window.innerWidth>768?s():0,j=window.innerWidth-v-b,R=window.innerHeight-v-b-y-S;return{x:Math.max(b,Math.min(j,x.x)),y:Math.max(b,Math.min(R,x.y))}},[s]),h=a.useCallback(x=>{if(typeof window>"u")return;const v=`fusion-quick-chat-position-${e||"default"}`;try{localStorage.setItem(v,JSON.stringify(x))}catch{}},[e]),g=a.useCallback(x=>{if(x.button!==0&&x.pointerType==="mouse")return;const b=x.target.closest(".quick-chat-fab");b&&(x.preventDefault(),typeof b.setPointerCapture=="function"&&b.setPointerCapture(x.pointerId),u.current={x:r.x,y:r.y,pointerX:x.clientX,pointerY:x.clientY},d.current=!1,c(!0),document.body.style.userSelect="none")},[r]),p=a.useCallback(x=>{if(!u.current||!l)return;const v=x.clientX-u.current.pointerX,b=x.clientY-u.current.pointerY;if((Math.abs(v)>=5||Math.abs(b)>=5)&&(d.current=!0),d.current){const y=u.current.x-v,S=u.current.y-b,j=m({x:y,y:S});o(j)}},[l,m]),f=a.useCallback(x=>{if(!u.current)return;const v=x.target.closest(".quick-chat-fab");if(v&&typeof v.releasePointerCapture=="function"&&v.releasePointerCapture(x.pointerId),c(!1),document.body.style.userSelect="",!d.current){u.current=null;return}h(r),u.current=null,d.current=!1},[r,h]);return{position:r,isDragging:l,handlePointerDown:g,handlePointerMove:p,handlePointerUp:f}}function XT(e,n,s){const i=`fusion:quick-chat-size-${e||"default"}`,r=a.useCallback(()=>typeof window<"u"&&window.innerWidth>Jc,[]),o=a.useCallback((g,p,f)=>{if(typeof window>"u")return g;const x=Math.max(la.width,window.innerWidth-p-ca),v=Math.max(la.height,window.innerHeight-f-ca);return{width:Math.max(la.width,Math.min(x,g.width)),height:Math.max(la.height,Math.min(v,g.height))}},[]),l=a.useCallback(()=>{if(typeof window>"u"||window.innerWidth<=Jc)return oo;try{const g=localStorage.getItem(i);if(!g)return oo;const p=JSON.parse(g);return typeof p.width!="number"||typeof p.height!="number"?oo:{width:p.width,height:p.height}}catch{return oo}},[i]),[c,u]=a.useState(l),[d,m]=a.useState({right:0,bottom:0});a.useEffect(()=>{if(!r())return;const g={right:n+d.right,bottom:s+d.bottom};u(p=>o(p,g.right,g.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(g=>{if(!r())return;const p=g.currentTarget.dataset.resizeDirection;if(!p)return;g.preventDefault(),g.stopPropagation();const f=g.currentTarget;typeof f.setPointerCapture=="function"&&f.setPointerCapture(g.pointerId);const x={pointerX:g.clientX,pointerY:g.clientY,width:c.width,height:c.height,anchorRight:d.right,anchorBottom:d.bottom};document.body.style.userSelect="none";const v=y=>{const S=y.clientX-x.pointerX,j=y.clientY-x.pointerY;let R=x.width,k=x.height,M=x.anchorRight,C=x.anchorBottom;if(p.includes("w")&&(R=x.width-S),p.includes("e")){const $=S;R=x.width+$,M=x.anchorRight-$}if(p.includes("n")&&(k=x.height-j),p.includes("s")){const $=j;k=x.height+$,C=x.anchorBottom-$}const L=n+M,A=s+C,P=o({width:R,height:k},L,A),O=Math.max(ca-n,Math.min(window.innerWidth-n-la.width-ca,M)),V=Math.max(ca-s,Math.min(window.innerHeight-s-la.height-ca,C));u(P),m({right:O,bottom:V})},b=y=>{typeof f.releasePointerCapture=="function"&&f.releasePointerCapture(y.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",b);try{localStorage.setItem(i,JSON.stringify({width:c.width,height:c.height}))}catch{}};document.addEventListener("pointermove",v),document.addEventListener("pointerup",b)},[d.bottom,d.right,o,s,n,r,c.height,c.width,i]);return{panelSize:c,anchorOffset:d,handleResizeStart:h}}function ZT({projectId:e,addToast:n,showFAB:s=!0,open:i,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:c,onToggleModelFavorite:u}){const{agents:d}=DT(e),[m,h]=a.useState(!1),g=i!==void 0,p=g?i:m,f=g?re=>{r?.(typeof re=="function"?re(p):re)}:h,{keyboardOverlap:x,viewportHeight:v}=mg({enabled:p}),b=x>0?{"--keyboard-overlap":`${x}px`,...v!==null?{"--vv-height":`${v}px`}:{}}:{},[y,S]=a.useState("agent"),[j,R]=a.useState(""),[k,M]=a.useState([]),[C,L]=a.useState(!1),[A,P]=a.useState(""),[O,V]=a.useState(""),[$,E]=a.useState(""),[D,U]=a.useState(!1),[Y,X]=a.useState(0),[_,I]=a.useState(-1),[T,w]=a.useState(()=>new Set),[,q]=a.useState(!1),[G,me]=a.useState({top:0,left:0}),ue=FT({projectId:e}),le=a.useCallback(re=>{if(!re||!ue.mentionActive)return;const N=re.getBoundingClientRect();me({top:N.top-260,left:N.left+8})},[ue.mentionActive]),Se=a.useRef(!1),F=a.useRef(!1),ge=a.useRef(""),se=a.useRef(0),fe=a.useRef(null),{position:de,isDragging:xe,handlePointerDown:ie,handlePointerMove:Ee,handlePointerUp:De}=QT(e,Se),qe=de.y+60,{panelSize:Qe,anchorOffset:Je,handleResizeStart:Ke}=XT(e,de.x,qe),it=typeof window<"u"&&window.innerWidth>Jc,{activeSession:Pe,messages:Ve,isStreaming:ae,streamingText:ye,streamingThinking:te,streamingToolCalls:Ae,sessionsLoading:Le,messagesLoading:pe,sendMessage:_e,stopStreaming:Fe,pendingMessage:tt,clearPendingMessage:Ne,switchSession:oe,startModelChat:Te,startFreshSession:he}=$T(e,n),Me=a.useRef(null),We=a.useRef(null),Re=a.useRef(null),ot=a.useRef(null),J=a.useMemo(()=>KT(A),[A]),ce=a.useMemo(()=>k.find(re=>`${re.provider}/${re.id}`===A)??null,[k,A]),ve=a.useMemo(()=>GT(ce,J),[ce,J]),Xe=a.useMemo(()=>y==="model"?J?`${Ad}::${J.modelProvider}/${J.modelId}`:"":j?`${j}::`:"",[y,J,j]),ee=y==="agent"?!!j:!!J;a.useEffect(()=>{if(d.length===0){R(""),S("model");return}d.some(N=>N.id===j)||R(d[0]?.id??"")},[d,j]),a.useEffect(()=>{!p||F.current||(F.current=!0,L(!0),ms().then(re=>{const N=re.models??[];if(M(N),A||N.length===0)return;const W=re.defaultProvider,Ie=re.defaultModelId;if(W&&Ie){const nt=`${W}/${Ie}`;if(N.some(Pt=>`${Pt.provider}/${Pt.id}`===nt)){P(nt),S("model");return}}if(d.length===0){const nt=N[0];nt&&P(`${nt.provider}/${nt.id}`)}}).catch(re=>{console.error("[QuickChatFAB] Failed to load models:",re),M([])}).finally(()=>{L(!1)}))},[p,d.length,A]),a.useEffect(()=>{if(!p){ge.current="";return}if(!Xe){ge.current="";return}const re=Xe===ge.current&&!Pe&&!Le;if(!(Xe===ge.current&&!re)){if(ge.current=Xe,y==="model"&&J){Te(J.modelProvider,J.modelId);return}y==="agent"&&j&&oe(j)}},[p,y,J,j,Xe,Pe,Le,Te,oe]),a.useEffect(()=>{p||(U(!1),E(""),I(-1))},[p]);const Ge=a.useCallback(re=>{R(re)},[]),ct=a.useCallback(re=>{P(re)},[]),vt=a.useCallback(()=>{!ee||Le||he()},[ee,Le,he]),bt=a.useMemo(()=>d.find(re=>re.id===j)??null,[d,j]),ft=a.useMemo(()=>{const re=$.trim().toLowerCase();return re?d.filter(N=>N.name.toLowerCase().includes(re)):d},[d,$]),gt=a.useMemo(()=>{const re=new Map;for(const N of d)re.set(N.name.toLowerCase(),N);return re},[d]);a.useEffect(()=>{X(0)},[$,D]),a.useEffect(()=>()=>{fe.current!==null&&(window.clearTimeout(fe.current),fe.current=null)},[]),a.useEffect(()=>{if(!p)return;const re=W=>{const Ie=W.target;Me.current?.contains(Ie)||We.current?.contains(Ie)||Ie.closest(".model-combobox-dropdown--portal")||f(!1)},N=W=>{W.key==="Escape"&&f(!1)};return document.addEventListener("mousedown",re),document.addEventListener("keydown",N),()=>{document.removeEventListener("mousedown",re),document.removeEventListener("keydown",N)}},[p,f]),a.useEffect(()=>{if(!p)return;const re=Re.current;re&&(re.scrollTop=re.scrollHeight)},[Ve,ye,te,p]);const _t=a.useMemo(()=>y==="agent"?bt?`Message ${bt.name||bt.id}`:"Select an agent to start chatting":ve?`Message ${ve}`:"Select a model to start chatting",[y,bt,ve]),Rt=!ee||!Pe,Ft=tt.length>50?`${tt.slice(0,50)}…`:tt,wt=a.useCallback(()=>{const re=O.trim();!re||Rt||(V(""),U(!1),E(""),I(-1),_e(re))},[_e,Rt,O]),At=a.useCallback((re,N)=>{const W=YT(re,N);if(W){U(!0),E(W.filter),I(W.start);return}U(!1),E(""),I(-1)},[]),qt=a.useCallback(re=>{const N=ot.current;if(!N||_<0)return;const W=N.selectionStart??se.current,Ie=N.selectionEnd??W,nt=Math.max(W,Ie),yt=Math.min(_,nt),Tt=`${`@${re.name.replace(/\s+/g,"_")}`} `,tn=O.slice(0,yt)+Tt+O.slice(nt),nn=yt+Tt.length;V(tn),U(!1),E(""),X(0),I(-1),window.requestAnimationFrame(()=>{ot.current&&(ot.current.focus(),ot.current.setSelectionRange(nn,nn))})},[_,O]),zt=a.useCallback(re=>{const N=re.target.value,W=re.target.selectionStart??N.length;se.current=W,V(N),At(N,W),ue.detectMention(N,W),q(ue.mentionActive),ue.mentionActive&&le(re.target)},[At,ue,le]),Wt=a.useCallback(()=>{fe.current!==null&&window.clearTimeout(fe.current),fe.current=window.setTimeout(()=>{U(!1),E(""),I(-1),q(!1),ue.dismissMention(),fe.current=null},120)},[ue]),Ot=a.useCallback(()=>{fe.current!==null&&(window.clearTimeout(fe.current),fe.current=null)},[]),Nt=a.useCallback(re=>{const N=re.currentTarget,W=N.selectionStart??N.value.length;se.current=W,At(N.value,W),ue.detectMention(N.value,W),q(ue.mentionActive),ue.mentionActive&&le(N)},[At,ue,le]),Mt=a.useCallback(re=>{re.key!=="Escape"&&Nt(re)},[Nt]),Ct=a.useCallback(re=>{const N=/@([\w-]+)/g,W=[];let Ie=0,nt=N.exec(re);for(;nt;){const[yt,Pt=""]=nt,Tt=nt.index;Tt>Ie&&W.push(re.slice(Ie,Tt));const tn=Pt.replace(/_/g," ").toLowerCase(),nn=gt.get(tn);nn?W.push(t.jsxs("span",{className:"chat-mention-chip",children:["@",nn.name.replace(/\s+/g,"_")]},`${nn.id}-${Tt}`)):W.push(yt),Ie=Tt+yt.length,nt=N.exec(re)}return Ie<re.length&&W.push(re.slice(Ie)),W.length===0?re:W},[gt]),Gt=a.useCallback(re=>{w(N=>{const W=new Set(N);return W.has(re)?W.delete(re):W.add(re),W})},[]),Et=a.useCallback((re,N=!1)=>N?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:re}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(hi,{remarkPlugins:[pi],components:JT,children:re})}),[]),H=a.useCallback(re=>{if(se.current=re.currentTarget.selectionStart??se.current,ue.mentionActive&&ue.files.length>0){if(ue.handleKeyDown(re,O),re.key==="Enter"||re.key==="Tab"){const N=ue.files[ue.selectedIndex];if(N){const W=ue.selectFile(N,O);V(W),ue.dismissMention(),q(!1)}}return}if(D&&re.key==="ArrowDown"){re.preventDefault(),ft.length>0&&X(N=>(N+1)%ft.length);return}if(D&&re.key==="ArrowUp"){re.preventDefault(),ft.length>0&&X(N=>N===0?ft.length-1:N-1);return}if(D&&re.key==="Enter"){re.preventDefault();const N=ft[Y]??ft[0];N&&qt(N);return}if(D&&re.key==="Escape"){re.preventDefault(),re.stopPropagation(),U(!1),E(""),I(-1);return}re.key!=="Enter"||re.shiftKey||(re.preventDefault(),wt())},[D,ft,Y,qt,wt,ue,O]),be=a.useCallback(()=>{if(Se.current){Se.current=!1;return}f(re=>!re)},[f]);return t.jsxs(t.Fragment,{children:[s&&t.jsx("button",{ref:We,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":xe?"true":"false",style:{right:de.x,bottom:de.y},onPointerDown:ie,onPointerMove:Ee,onPointerUp:De,onClick:be,children:t.jsx(ji,{size:24})}),p&&t.jsxs("div",{className:"quick-chat-panel",ref:Me,"data-testid":"quick-chat-panel",style:{right:de.x+Je.right,bottom:qe+Je.bottom,...it?{width:Qe.width,height:Qe.height}:{},...b},children:[it&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"n","data-testid":"quick-chat-resize-n",onPointerDown:Ke,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:Ke,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:Ke,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:Ke,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:Ke,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:Ke,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:Ke,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:Ke,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"}),ve&&t.jsx("span",{className:"quick-chat-model-tag","data-testid":"quick-chat-model-tag",title:ve,children:ve})]}),t.jsxs("div",{className:"quick-chat-panel-header-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm","data-testid":"quick-chat-new-thread",onClick:vt,disabled:!ee||Le,children:"New chat"}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":"Close quick chat","data-testid":"quick-chat-close",onClick:()=>f(!1),children:t.jsx(Ut,{size:16})})]})]}),d.length>0&&t.jsxs("div",{className:"quick-chat-mode-toggle","data-testid":"quick-chat-mode-toggle",children:[t.jsx("button",{type:"button",className:`quick-chat-mode-btn${y==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-mode-agent",onClick:()=>{S("agent"),P("")},children:"Agent"}),t.jsx("button",{type:"button",className:`quick-chat-mode-btn${y==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-mode-model",onClick:()=>{S("model"),R("")},children:"Model"})]}),y==="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:j,onChange:re=>Ge(re.target.value),"data-testid":"quick-chat-agent-select",children:d.map(re=>t.jsx("option",{value:re.id,children:WT(re)},re.id))})]}),y==="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(Hn,{id:"quick-chat-model-override",models:k,value:A,onChange:ct,label:"Select model override",placeholder:C?"Loading models…":"Select a model",disabled:C||k.length===0,favoriteProviders:o,favoriteModels:l,onToggleFavorite:c,onToggleModelFavorite:u})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:Re,"data-testid":"quick-chat-messages",children:Le||pe?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):Ve.length===0&&!ye&&!te&&!ae?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[Ve.map(re=>{const N=re.role==="user",W=!N&&T.has(re.id);return t.jsxs("div",{className:`quick-chat-panel-message ${N?"quick-chat-panel-message--sent":"quick-chat-panel-message--received"}`,"data-testid":`quick-chat-message-${re.id}`,children:[N?t.jsx("p",{children:Ct(re.content)}):t.jsxs(t.Fragment,{children:[Et(re.content,W),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${W?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":W?"Show rendered markdown":"Show plain text",onClick:()=>Gt(re.id),children:W?t.jsx(gc,{size:14}):t.jsx(fa,{size:14})})]}),_h(re.toolCalls,!0)]},re.id)}),ae&&t.jsxs("div",{className:"quick-chat-panel-message quick-chat-panel-message--received quick-chat-panel-message--streaming","data-testid":"quick-chat-streaming-message",children:[ye?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:Et(ye,T.has("__streaming__"))}),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${T.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":T.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>Gt("__streaming__"),children:T.has("__streaming__")?t.jsx(gc,{size:14}):t.jsx(fa,{size:14})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:"Thinking…"}),_h(Ae,!0),te&&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:te})]})]})]})}),t.jsxs("div",{className:"quick-chat-panel-input",children:[t.jsxs("div",{className:"quick-chat-input-wrapper",children:[t.jsx("input",{ref:ot,type:"text",value:O,onChange:zt,onKeyDown:H,onKeyUp:Mt,onClick:Nt,onBlur:Wt,onFocus:Ot,placeholder:_t,disabled:Rt,"data-testid":"quick-chat-input"}),t.jsx(PT,{agents:d,filter:$,highlightedIndex:Y,visible:D,onSelect:qt,position:"above"}),t.jsx(LT,{visible:ue.mentionActive&&!D,position:G,files:ue.files,selectedIndex:ue.selectedIndex,onSelect:re=>{const N=ue.selectFile(re,O);V(N),ue.dismissMention(),q(!1),ot.current?.focus()},loading:ue.loading}),tt&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${Ft}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:Ne,children:"×"})]})]}),ae?t.jsx("button",{type:"button",className:"chat-input-stop",onClick:Fe,"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:t.jsx(bs,{size:14})}):t.jsx("button",{type:"button",onClick:()=>void wt(),disabled:Rt||O.trim().length===0,"data-testid":"quick-chat-send",children:t.jsx(zi,{size:16})})]})]})]})}function tr(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function Mh(e){return e.status==="generating"||e.status==="awaiting_input"}function nr(e){return e==="complete"||e==="error"}function eP(e){const[n,s]=a.useState([]),i=a.useRef(new Map),r=a.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:c,requestSync:u}=Ra(),d=a.useCallback(()=>{td(e).then(p=>{const f=p.filter(v=>{const b=tr(v.updatedAt),y=r.current.get(v.id);return y===void 0?!0:b<=y?!1:(r.current.delete(v.id),!0)}),x=new Map;for(const v of f)x.set(v.id,tr(v.updatedAt));i.current=x,s(f)}).catch(p=>{console.warn("[useBackgroundSessions] Failed to fetch AI sessions:",p)})},[e]);a.useEffect(()=>{u(),d()},[d,u]),a.useEffect(()=>{s(p=>{if(o.size===0)return p;let f=!1;const x=new Map(p.map(v=>[v.id,v]));for(const v of o.values()){if(e&&v.projectId&&v.projectId!==e)continue;const b=v.lastEventTimestamp,y=i.current.get(v.sessionId)??0;if(b<y)continue;const S=r.current.get(v.sessionId);if(S!==void 0&&b<=S)continue;if(S!==void 0&&b>S&&!nr(v.status)&&r.current.delete(v.sessionId),nr(v.status)){x.delete(v.sessionId)&&(f=!0),i.current.set(v.sessionId,b);continue}const j=x.get(v.sessionId),R=v.type??j?.type,k=v.title??j?.title;if(!j&&(!R||!k))continue;const M={id:v.sessionId,type:R??"planning",status:v.status,title:k??"AI Session",projectId:v.projectId??j?.projectId??e??null,lockedByTab:v.owningTabId??j?.lockedByTab??null,updatedAt:v.updatedAt??j?.updatedAt??new Date(b).toISOString()},C=x.get(v.sessionId);(!C||C.status!==M.status||C.title!==M.title||C.type!==M.type||C.projectId!==M.projectId||C.lockedByTab!==M.lockedByTab||C.updatedAt!==M.updatedAt)&&(x.set(v.sessionId,M),i.current.set(v.sessionId,b),f=!0)}return f?[...x.values()].sort((v,b)=>tr(b.updatedAt)-tr(v.updatedAt)):p})},[e,o]),a.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",f=v=>{try{const b=JSON.parse(v.data),y=tr(b.updatedAt)||Date.now();s(S=>{const j=i.current.get(b.id)??0;if(y<j)return S;const R=r.current.get(b.id);if(R!==void 0&&y<=R)return S;if(R!==void 0&&y>R&&!nr(b.status)&&r.current.delete(b.id),i.current.set(b.id,y),nr(b.status))return S.filter(M=>M.id!==b.id);const k=S.findIndex(M=>M.id===b.id);if(k>=0){const M=[...S];return M[k]=b,M}return Mh(b)?[b,...S]:S}),l({sessionId:b.id,status:b.status,needsInput:b.status==="awaiting_input",type:b.type,title:b.title,projectId:b.projectId,owningTabId:b.lockedByTab,updatedAt:b.updatedAt,timestamp:y}),nr(b.status)&&c({sessionId:b.id,status:b.status,timestamp:y})}catch{}},x=v=>{try{const b=JSON.parse(v.data),y=Date.now();r.current.set(b,y),i.current.set(b,Math.max(i.current.get(b)??0,y)),c({sessionId:b,status:"complete",timestamp:y}),s(S=>S.filter(j=>j.id!==b))}catch{}};return qs(`/api/events${p}`,{events:{"ai_session:updated":f,"ai_session:deleted":x},onReconnect:()=>{d()}})},[c,l,e,d]);const m=a.useCallback(async p=>{const x=n.find(S=>S.id===p)?.type,v=Ji();let b=!1;if(x==="planning")try{await rp(p,e,v)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of planning session ${p} despite lock by another tab`)}else if(x==="subtask")try{await cp(p,e,v)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of subtask session ${p} despite lock by another tab`)}else if(x==="mission_interview")try{await pp(p,e,v)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of mission interview session ${p} despite lock by another tab`)}b&&console.warn(`[useBackgroundSessions] Cancellation failed for session ${p}, attempting delete anyway`);const y=Date.now();r.current.set(p,y),i.current.set(p,Math.max(i.current.get(p)??0,y)),c({sessionId:p,status:"complete",timestamp:y});try{await fp(p)}catch{}s(S=>S.filter(j=>j.id!==p))},[c,e,n]),h=a.useMemo(()=>n.filter(p=>Mh(p)),[n]),g=a.useMemo(()=>h.filter(p=>p.type==="planning"),[h]);return{sessions:h,generating:h.filter(p=>p.status==="generating").length,needsInput:h.filter(p=>p.status==="awaiting_input").length,planningSessions:g,dismissSession:m,refresh:d}}function Yn(e){return{...e,dependencies:Array.isArray(e.dependencies)?e.dependencies:[],steps:Array.isArray(e.steps)?e.steps:[],log:Array.isArray(e.log)?e.log:[]}}function Ah(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function tP(e){const n=e?.projectId,s=e?.searchQuery,i=e?.sseEnabled??!0,[r,o]=a.useState([]),[l,c]=a.useState(!1),u=a.useRef(l);u.current=l;const d=a.useRef(r),m=a.useRef(0),h=a.useRef(0),g=a.useRef(s),p=a.useRef(null),f=a.useRef(void 0),x=a.useRef(0),v=a.useRef(n);d.current=r,g.current=s,v.current!==n&&(v.current=n,x.current++);const b=1e3,y=a.useCallback(async E=>{const D=++m.current,U=n,Y=E?.searchQueryOverride??s,X=E?.includeArchivedOverride??u.current;try{const _=await _v(void 0,void 0,U,Y,X);if(m.current!==D||n!==U)return;o(_.map(Yn)),f.current=Date.now()}catch{if(m.current!==D||n!==U)return;if(E?.clearOnError){o([]);return}o(_=>_)}},[n,s]);p.current=y;const S=a.useCallback(async()=>{u.current||(c(!0),u.current=!0,await p.current({includeArchivedOverride:!0}))},[]);a.useEffect(()=>{if(s===void 0)return;const E=setTimeout(()=>{y({searchQueryOverride:s})},300);return()=>clearTimeout(E)},[s]),a.useEffect(()=>{y({clearOnError:!0});const E=()=>{if(document.visibilityState!=="visible")return;const D=Date.now();D-h.current<b||(h.current=D,y())};return document.addEventListener("visibilitychange",E),()=>{document.removeEventListener("visibilitychange",E)}},[y]),a.useEffect(()=>{if(i===!1)return;const E=x.current,D=n?`?projectId=${encodeURIComponent(n)}`:"",U=()=>x.current!==E;let Y=!0;const X=G=>{if(U())return;const me=Yn(JSON.parse(G.data));if(g.current){p.current({searchQueryOverride:g.current});return}o(ue=>ue.some(le=>le.id===me.id)?ue:[...ue,me])},_=G=>{if(U())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:me,to:ue}=JSON.parse(G.data),le=Yn(me);o(Se=>Se.map(F=>F.id===le.id?{...le,column:ue}:F)),f.current=Date.now()},I=G=>{if(U())return;if(g.current){p.current({searchQueryOverride:g.current});return}const me=Yn(JSON.parse(G.data));o(ue=>ue.map(le=>{if(le.id!==me.id||Ah(me.updatedAt,le.updatedAt)<0)return le;if(le.column===me.column)return me;const F=Ah(le.columnMovedAt,me.columnMovedAt);return le.columnMovedAt&&!me.columnMovedAt?{...me,column:le.column,columnMovedAt:le.columnMovedAt}:F>0?{...me,column:le.column,columnMovedAt:le.columnMovedAt}:me})),f.current=Date.now()},T=G=>{if(U())return;if(g.current){p.current({searchQueryOverride:g.current});return}const me=Yn(JSON.parse(G.data));o(ue=>ue.filter(le=>le.id!==me.id))},w=G=>{if(U())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:me}=JSON.parse(G.data),ue=Yn(me);o(le=>le.map(Se=>Se.id===ue.id?{...ue,column:"done"}:Se))},q=qs(`/api/events${D}`,{events:{"task:created":X,"task:moved":_,"task:updated":I,"task:deleted":T,"task:merged":w},onReconnect:()=>{Y&&(U()||p.current())}});return()=>{Y=!1,q()}},[n,i]);const j=a.useCallback(async E=>{const D=Yn(await np(E,n));return o(U=>U.some(Y=>Y.id===D.id)?U:[...U,D]),D},[n]),R=a.useCallback(async(E,D)=>Yn(await Av(E,D,n)),[n]),k=a.useCallback(async E=>Yn(await sp(E,n)),[n]),M=a.useCallback(async E=>Yn(await Rv(E,n)),[n]),C=a.useCallback(async E=>Tv(E,n),[n]),L=a.useCallback(async E=>Yn(await Pv(E,n)),[n]),A=a.useCallback(async E=>{const D=Yn(await Iv(E,n));return o(U=>U.some(Y=>Y.id===D.id)?U:[...U,D]),D},[n]),P=a.useCallback(async(E,D)=>{const U=d.current.find(X=>X.id===E),Y=U?{...U,...D,updatedAt:new Date().toISOString()}:void 0;Y&&o(X=>X.map(_=>_.id===E?Y:_));try{const X=Yn(await Qs(E,D,n));return o(_=>_.map(I=>I.id===E?X:I)),X}catch(X){throw U&&o(_=>_.map(I=>I.id===E?U:I)),X}},[n]),O=a.useCallback(async E=>{const D=Yn(await Dv(E,n));return o(U=>U.map(Y=>Y.id===E?D:Y)),D},[n]),V=a.useCallback(async E=>{const D=Yn(await Lv(E,n));return o(U=>U.map(Y=>Y.id===E?D:Y)),D},[n]),$=a.useCallback(async()=>{const D=(await zv(n)).map(Yn);return o(U=>U.map(Y=>D.find(_=>_.id===Y.id)||Y)),D},[n]);return{tasks:r,createTask:j,moveTask:R,pauseTask:k,deleteTask:M,mergeTask:C,retryTask:L,duplicateTask:A,updateTask:P,archiveTask:O,unarchiveTask:V,archiveAllDone:$,loadArchivedTasks:S,includeArchived:l,lastFetchTimeMs:f.current}}const nP=5e3,sP=1e3;function iP(){const[e,n]=a.useState([]),[s,i]=a.useState(!0),[r,o]=a.useState(null),l=a.useRef(null),c=a.useRef(0),u=a.useCallback(async()=>{try{o(null);const g=await eu();n(g)}catch(g){o(g instanceof Error?g.message:"Failed to fetch projects")}},[]);a.useEffect(()=>{let g=!1;async function p(){i(!0);const x=performance.now();try{const v=await eu(),y=`initial fetchProjectsAcrossNodes took ${Math.round(performance.now()-x)}ms (${v.length} projects)`;console.log(`[useProjects] ${y}`),lr("[useProjects]",y),g||(n(v),o(null))}catch(v){const y=`initial fetch failed after ${Math.round(performance.now()-x)}ms: ${v instanceof Error?v.message:String(v)}`;console.warn(`[useProjects] ${y}`),lr("[useProjects]",y),g||o(v instanceof Error?v.message:"Failed to fetch projects")}finally{g||i(!1)}}p();const f=()=>{if(document.visibilityState!=="visible")return;const x=Date.now();x-c.current<sP||(c.current=x,u())};return document.addEventListener("visibilitychange",f),()=>{g=!0,document.removeEventListener("visibilitychange",f)}},[u]),a.useEffect(()=>{if(!s)return l.current=setInterval(()=>{u()},nP),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async g=>{const p=await Lj(g);return n(f=>[...f,p]),p},[]),m=a.useCallback(async(g,p)=>{const f=await Hj(g,p);return n(x=>x.map(v=>v.id===g?f:v)),f},[]),h=a.useCallback(async g=>{await up(g),n(p=>p.filter(f=>f.id!==g))},[]);return{projects:e,loading:s,error:r,refresh:u,register:d,update:m,unregister:h}}const aP="kb-dashboard-current-project";function rP(e){return e??"local"}function oP(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=rP(s);a.useEffect(()=>{let p=!1;async function f(){try{const x=await Gi();if(p)return;d.current=x.dashboardCurrentProjectIdByNode??{};const v=d.current[m];if(v){const b=e.find(y=>y.id===v);b&&(r(b),c.current=!0)}if(!v)try{const b=localStorage.getItem(aP);if(b){const y=JSON.parse(b);y?.id&&e.some(j=>j.id===y.id)&&(r(y),c.current=!0,d.current={...d.current,[m]:y.id},await ln({dashboardCurrentProjectIdByNode:d.current}).catch(()=>{}))}}catch{}}catch{}finally{p||l(!1)}}return f(),()=>{p=!0}},[m,e]),a.useEffect(()=>{if(!o){if(i){if(!e.some(x=>x.id===i.id)&&e.length>0){const x=e.find(v=>v.status==="active");r(x||e[0]||null);return}const f={...d.current,[m]:i.id};d.current=f,ln({dashboardCurrentProjectIdByNode:f}).catch(()=>{})}else if(e.length>0&&!u.current){const p=e.find(f=>f.status==="active");p&&r(p)}}},[i,e,o,m]);const h=a.useCallback(p=>{if(u.current=!1,r(p),p){const f={...d.current,[m]:p.id};d.current=f,ln({dashboardCurrentProjectIdByNode:f}).catch(()=>{})}},[m]),g=a.useCallback(()=>{u.current=!0,r(null);const p={...d.current};delete p[m],d.current=p,ln({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[m]);return{currentProject:i,setCurrentProject:h,clearCurrentProject:g,loading:o}}const hg=a.createContext(null);function lP({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()},[]),mo.createElement(hg.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function cP(){const e=a.useContext(hg);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const pg="kb-dashboard-theme-mode",fg="kb-dashboard-color-theme",gg=[...vw],Yc="theme-data",uc="theme-data.css";function dP(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.endsWith("/")?e.slice(0,-1)+`/${uc}`:e.replace(/\/[^/]+$/,`/${uc}`):`/${uc}`}const Ts=typeof window<"u",uP=Ts?a.useLayoutEffect:a.useEffect;function xg(e){return e==="dark"||e==="light"||e==="system"}function Rh(){if(!Ts)return"dark";try{const e=localStorage.getItem(pg);if(xg(e))return e}catch{}return"dark"}function Th(){if(!Ts)return"default";try{const e=localStorage.getItem(fg);if(e&&gg.includes(e))return e}catch{}return"default"}function Ph(e){if(Ts)try{localStorage.setItem(pg,e)}catch{}}function Ih(e){if(Ts)try{localStorage.setItem(fg,e)}catch{}}function mP(e,n){return e==="system"?n?"dark":"light":e}function hP(e,n,s){if(!Ts)return;const i=mP(e,s);document.documentElement.setAttribute("data-theme",i),document.documentElement.setAttribute("data-color-theme",n)}function $h(){if(!Ts)return;const e=dP(),n=document.getElementById(Yc);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=Yc,document.head.appendChild(s)}function Dh(){if(!Ts)return;const e=document.getElementById(Yc);e&&e.remove()}function pP(){const[e,n]=a.useState(()=>Rh()),[s,i]=a.useState(()=>Th()),[r,o]=a.useState(!0),[l,c]=a.useState(()=>Ts?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(!Ts||!r)return;let f=!1;return Gi().then(x=>{f||(xg(x.themeMode)&&!m.current&&(u.current!==x.themeMode&&(u.current=x.themeMode,n(x.themeMode)),Rh()!==x.themeMode&&Ph(x.themeMode)),x.colorTheme&&gg.includes(x.colorTheme)&&!h.current&&(d.current!==x.colorTheme&&(d.current=x.colorTheme,i(x.colorTheme)),Th()!==x.colorTheme&&Ih(x.colorTheme)))}).catch(x=>{console.warn("[useTheme] Failed to hydrate theme from global settings",x)}).finally(()=>{f||o(!1)}),()=>{f=!0}},[r]),a.useEffect(()=>{if(!Ts)return;const f=window.matchMedia("(prefers-color-scheme: dark)"),x=v=>{c(v.matches)};return f.addEventListener("change",x),()=>f.removeEventListener("change",x)},[]),uP(()=>{hP(e,s,l)},[e,s,l]),a.useEffect(()=>{!Ts||r||(s!=="default"?$h():Dh())},[s,r]);const g=a.useCallback(f=>{m.current=!0,u.current=f,n(f),Ph(f),ln({themeMode:f}).catch(x=>{console.warn("[useTheme] Failed to persist themeMode to global settings",x)})},[]),p=a.useCallback(f=>{h.current=!0,d.current=f,i(f),Ih(f),f!=="default"?$h():Dh(),ln({colorTheme:f}).catch(x=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",x)})},[]);return{themeMode:e,colorTheme:s,setThemeMode:g,setColorTheme:p,isSystemDark:l}}function fP(e){const{planningSessions:n}=e,[s,i]=a.useState(!1),[r,o]=a.useState(!1),[l,c]=a.useState(null),[u,d]=a.useState(void 0),[m,h]=a.useState(!1),[g,p]=a.useState(null),[f,x]=a.useState(void 0),[v,b]=a.useState(null),[y,S]=a.useState("definition"),[j,R]=a.useState(!1),[k,M]=a.useState(void 0),[C,L]=a.useState(!1),[A,P]=a.useState(!1),[O,V]=a.useState(!1),[$,E]=a.useState(null),[D,U]=a.useState(!1),[Y,X]=a.useState(!1),[_,I]=a.useState(void 0),[T,w]=a.useState(!1),[q,G]=a.useState("project"),[me,ue]=a.useState(!1),[le,Se]=a.useState(!1),[F,ge]=a.useState(!1),[se,fe]=a.useState(!1),[de,xe]=a.useState(!1),[ie,Ee]=a.useState(!1),[De,qe]=a.useState(!1),Qe=!!(v||j||s||r||m||Y||T||me||le||F||de||se||O||D||C||A||ie||De),Je=a.useCallback(()=>i(!0),[]),Ke=a.useCallback(()=>i(!1),[]),it=a.useCallback(()=>o(!0),[]),Pe=a.useCallback(H=>{c(H),o(!0)},[]),Ve=a.useCallback(()=>{const H=n[0];H&&(d(H.id),o(!0))},[n]),ae=a.useCallback(H=>{d(H),o(!0)},[]),ye=a.useCallback(()=>{o(!1),c(null),d(void 0)},[]),te=a.useCallback(H=>{p(H),h(!0)},[]),Ae=a.useCallback(H=>{x(H),h(!0)},[]),Le=a.useCallback(()=>{h(!1),p(null),x(void 0)},[]),pe=a.useCallback((H,be="definition")=>{b(H),S(be)},[]),_e=a.useCallback(H=>{b(H),S("changes")},[]),Fe=a.useCallback(H=>{b(be=>be&&{...be,...H})},[]),tt=a.useCallback(()=>{b(null)},[]),Ne=a.useCallback(H=>{M(H),R(!0)},[]),oe=a.useCallback(()=>{R(!1),M(void 0)},[]),Te=a.useCallback(()=>L(!0),[]),he=a.useCallback(()=>L(!1),[]),Me=a.useCallback(()=>P(!0),[]),We=a.useCallback(()=>P(!1),[]),Re=a.useCallback(H=>{E(H??null),V(!0)},[]),ot=a.useCallback(()=>{V(!1),E(null)},[]),J=a.useCallback(()=>U(!0),[]),ce=a.useCallback(()=>U(!1),[]),ve=a.useCallback(()=>{X(H=>!H)},[]),Xe=a.useCallback(()=>{X(!1),I(void 0)},[]),ee=a.useCallback(()=>w(!0),[]),Ge=a.useCallback(()=>w(!1),[]),ct=a.useCallback(H=>{G(H)},[]),vt=a.useCallback(()=>ue(!0),[]),bt=a.useCallback(()=>ue(!1),[]),ft=a.useCallback(()=>Se(!0),[]),gt=a.useCallback(()=>Se(!1),[]),_t=a.useCallback(()=>ge(!0),[]),Rt=a.useCallback(()=>ge(!1),[]),Ft=a.useCallback(()=>fe(!0),[]),wt=a.useCallback(()=>fe(!1),[]),At=a.useCallback(()=>xe(!0),[]),qt=a.useCallback(()=>xe(!1),[]),zt=a.useCallback(async(H,be)=>{xe(!1),I(be),X(!0)},[]),Wt=a.useCallback(()=>Ee(!0),[]),Ot=a.useCallback(()=>Ee(!1),[]),Nt=a.useCallback(()=>qe(!0),[]),Mt=a.useCallback(()=>qe(!1),[]),Ct=a.useCallback((H,be)=>{be(`Created ${H.id} from planning mode`,"success"),o(!1),c(null)},[]),Gt=a.useCallback((H,be)=>{const re=H.map(N=>N.id).join(", ");be(`Created ${re} from planning mode`,"success"),o(!1),c(null)},[]),Et=a.useCallback((H,be)=>{const re=H.map(N=>N.id).join(", ");be(`Created ${re} from subtask breakdown`,"success"),h(!1),p(null)},[]);return{newTaskModalOpen:s,isPlanningOpen:r,planningInitialPlan:l,planningResumeSessionId:u,isSubtaskOpen:m,subtaskInitialDescription:g,subtaskResumeSessionId:f,detailTask:v,detailTaskInitialTab:y,settingsOpen:j,settingsInitialSection:k,schedulesOpen:C,githubImportOpen:A,usageOpen:O,usageAnchorRect:$,systemStatsOpen:D,terminalOpen:Y,terminalInitialCommand:_,filesOpen:T,fileBrowserWorkspace:q,activityLogOpen:me,gitManagerOpen:le,workflowStepsOpen:F,agentsOpen:se,scriptsOpen:de,setupWizardOpen:ie,modelOnboardingOpen:De,anyModalOpen:Qe,openNewTask:Je,closeNewTask:Ke,openPlanning:it,openPlanningWithInitialPlan:Pe,resumePlanning:Ve,openPlanningWithSession:ae,closePlanning:ye,openSubtaskBreakdown:te,openSubtaskWithSession:Ae,closeSubtask:Le,openDetailTask:pe,openDetailWithChangesTab:_e,updateDetailTask:Fe,closeDetailTask:tt,openSettings:Ne,closeSettings:oe,openSchedules:Te,closeSchedules:he,openGitHubImport:Me,closeGitHubImport:We,openUsage:Re,closeUsage:ot,openSystemStats:J,closeSystemStats:ce,toggleTerminal:ve,closeTerminal:Xe,openFiles:ee,closeFiles:Ge,setFileWorkspace:ct,openActivityLog:vt,closeActivityLog:bt,openGitManager:ft,closeGitManager:gt,openWorkflowSteps:_t,closeWorkflowSteps:Rt,openAgents:Ft,closeAgents:wt,openScripts:At,closeScripts:qt,runScript:zt,openSetupWizard:Wt,closeSetupWizard:Ot,openModelOnboarding:Nt,closeModelOnboarding:Mt,onPlanningTaskCreated:Ct,onPlanningTasksCreated:Gt,onSubtaskTasksCreated:Et}}function gP(e){const[n,s]=a.useState(2),[i,r]=a.useState("."),[o,l]=a.useState(!0),[c,u]=a.useState(!1),[d,m]=a.useState(!1),[h,g]=a.useState(void 0),[p,f]=a.useState(!1),[x,v]=a.useState(!1),[b,y]=a.useState({}),[S,j]=a.useState(!1),[R,k]=a.useState(!1),[M,C]=a.useState(!1),[L,A]=a.useState(!1),[P,O]=a.useState(!1),V=a.useCallback(async()=>{const[Y,X]=await Promise.allSettled([Bv(e),Fo(e)]);if(Y.status==="fulfilled"&&(s(Y.value.maxConcurrent),r(Y.value.rootDir)),X.status==="fulfilled"){const _=X.value;l(!!_.autoMerge),u(!!_.globalPause),m(!!_.enginePaused),v(!!_.prAuthAvailable),g(_.taskStuckTimeoutMs),f(_.showQuickChatFAB===!0),y(_.experimentalFeatures??{});const I=_.experimentalFeatures??{};j(I.insights===!0),k(I.roadmap===!0),C(I.memoryView===!0),A(I.devServerView===!0||I.devServer===!0),O(I.todoView===!0)}},[e]);a.useEffect(()=>{V()},[V]);const $=a.useCallback(async()=>{const Y=!o;l(Y);try{await Br({autoMerge:Y},e)}catch{l(!Y)}},[o,e]),E=a.useCallback(async()=>{const Y=!c;u(Y);try{await Br({globalPause:Y,globalPauseReason:Y?"manual":void 0},e)}catch{u(!Y)}},[c,e]),D=a.useCallback(async()=>{const Y=!d;m(Y);try{await Br({enginePaused:Y},e)}catch{m(!Y)}},[d,e]),U=a.useCallback(async()=>{const Y=!p;f(Y);try{await Br({showQuickChatFAB:Y},e)}catch{f(!Y)}},[p,e]);return{maxConcurrent:n,rootDir:i,autoMerge:o,globalPaused:c,enginePaused:d,taskStuckTimeoutMs:h,showQuickChatFAB:p,prAuthAvailable:x,experimentalFeatures:b,insightsEnabled:S,roadmapEnabled:R,memoryEnabled:M,devServerEnabled:L,todosEnabled:P,toggleAutoMerge:$,toggleGlobalPause:E,toggleEnginePause:D,toggleShowQuickChatFAB:U,refresh:V}}function xP(e){const{projectId:n,projects:s,projectsLoading:i,currentProject:r,setCurrentProject:o,addToast:l,openTaskDetail:c,closeTaskDetail:u}=e,d=a.useRef(!1),m=a.useRef(null);return a.useEffect(()=>{const g=new URLSearchParams(window.location.search),p=g.get("project"),f=g.get("task");if(!f||i)return;if(p){const v=s.find(b=>b.id===p);if(!v){l(`Project '${p}' not found`,"error");return}r?.id!==v.id&&o(v)}if(d.current)return;d.current=!0,xo(f,p??n).then(v=>{c(v),m.current=f}).catch(()=>{l(`Task ${f} not found`,"error")})},[n,s,i,r,o,l,c]),{handleDetailClose:a.useCallback(()=>{if(m.current){const g=new URLSearchParams(window.location.search);g.delete("task");const p=g.toString();window.history.replaceState(null,"",p?`${window.location.pathname}?${p}`:window.location.pathname),m.current=null}u()},[u])}}function bP(){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(f=>f!==m):[m,...h];l.current=p,i(()=>p);try{await ln({favoriteProviders:p,favoriteModels:c.current})}catch(f){throw l.current=h,i(()=>h),f}},[]),d=a.useCallback(async m=>{const h=c.current,p=h.includes(m)?h.filter(f=>f!==m):[m,...h];c.current=p,o(()=>p);try{await ln({favoriteProviders:l.current,favoriteModels:p})}catch(f){throw c.current=h,o(()=>h),f}},[]);return{availableModels:e,favoriteProviders:s,favoriteModels:r,toggleFavoriteProvider:u,toggleFavoriteModel:d}}function vP({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;xr().then(({providers:u})=>{const d=u.some(h=>h.authenticated);if(u.length>0&&!d||u.length>0&&d)return Gi().then(h=>{const g=!!(h.defaultProvider&&h.defaultModelId);(h.modelOnboardingComplete===!1||h.modelOnboardingComplete===void 0)&&(!d||!g)&&!Ea()?l=!0:!d&&!Ea()&&(c=!0)})}).then(()=>{if(o.current){r.current=!1;return}l?(As("onboarding:auto-triggered",{trigger:"first-run"}),s()):c&&(As("onboarding:auto-triggered",{trigger:"missing-provider"}),i("authentication"))}).catch(()=>{})},[e,n,s,i])}const Lh="kb-update-banner-dismissed";function yP(){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(Lh)==="true";d(h);let g=!1;return Uv().then(p=>{g||p.disabled||(i(p.updateAvailable===!0),o(typeof p.latestVersion=="string"?p.latestVersion:null),c(typeof p.currentVersion=="string"?p.currentVersion:null))}).catch(()=>{}).finally(()=>{g||n(!1)}),()=>{g=!0}},[]);const m=a.useCallback(()=>{d(!0),sessionStorage.setItem(Lh,"true")},[]);return{updateAvailable:s,latestVersion:r,currentVersion:l,loading:e,dismissed:u,dismiss:m}}const jP=["board","list","agents","missions","chat","documents","roadmaps","skills","mailbox","insights","memory","devserver","dev-server","todos"];function zh(e){return e!==null&&jP.includes(e)}function kP(e){return e==="devserver"?"dev-server":e}function wP(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 b=window.localStorage.getItem("kb-dashboard-view-mode");if(b==="overview"||b==="project")return b}return"overview"}),[g,p]=a.useState(()=>{const b=qn("kb-dashboard-task-view");return zh(b)?b:"board"}),f=a.useRef(!1);a.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",m)},[m]),a.useEffect(()=>{const b=qn("kb-dashboard-task-view",r?.id);if(zh(b)){const y=!f.current&&b==="devserver";p(y?"devserver":kP(b))}else p("board");r?.id&&(f.current=!0)},[r?.id]),a.useEffect(()=>{ds("kb-dashboard-task-view",g,r?.id)},[r?.id,g]),a.useEffect(()=>{n||i||r&&m==="overview"&&h("project")},[n,i,r,m]),a.useEffect(()=>{if(n||i||l||s||o>0||r)return;const b=window.setTimeout(()=>{c()},500);return()=>window.clearTimeout(b)},[n,s,o,i,r,l,c]);const x=a.useCallback(b=>{p(b)},[]),v=a.useCallback(()=>{const b=["dark","light","system"],y=b.indexOf(u),S=b[(y+1)%b.length];d(S)},[u,d]);return{viewMode:m,setViewMode:h,taskView:g,setTaskView:p,handleChangeTaskView:x,handleToggleTheme:v}}function NP(e){const{setCurrentProject:n,clearCurrentProject:s,setViewMode:i,currentProject:r,refreshProjects:o,toggleFavoriteProvider:l,toggleFavoriteModel:c,addToast:u,openSettings:d,openSetupWizard:m,closeSetupWizard:h,closeModelOnboarding:g}=e,p=a.useCallback(C=>{n(C),i("project")},[n,i]),f=a.useCallback(()=>{s(),i("overview")},[s,i]),x=a.useCallback(()=>{d()},[d]),v=a.useCallback(()=>{m()},[m]),b=a.useCallback(C=>{h(),n(C),i("project"),u(`Project ${C.name} registered successfully`,"success"),o()},[h,n,i,u,o]),y=a.useCallback(()=>{g()},[g]),S=a.useCallback(async C=>{try{await Bj(C.id),u(`Project ${C.name} paused`,"success"),await o()}catch{u(`Failed to pause project ${C.name}`,"error")}},[u,o]),j=a.useCallback(async C=>{try{await Uj(C.id),u(`Project ${C.name} resumed`,"success"),await o()}catch{u(`Failed to resume project ${C.name}`,"error")}},[u,o]),R=a.useCallback(async C=>{try{await up(C.id),u(`Project ${C.name} removed`,"success"),r?.id===C.id&&(s(),i("overview")),await o()}catch{u(`Failed to remove project ${C.name}`,"error")}},[r,s,i,u,o]),k=a.useCallback(async C=>{try{await l(C)}catch{u("Failed to update favorites","error")}},[l,u]),M=a.useCallback(async C=>{try{await c(C)}catch{u("Failed to update model favorites","error")}},[c,u]);return{handleSelectProject:p,handleViewAllProjects:f,handleOpenSettings:x,handleAddProject:v,handleSetupComplete:b,handleModelOnboardingComplete:y,handlePauseProject:S,handleResumeProject:j,handleRemoveProject:R,handleToggleFavorite:k,handleToggleModelFavorite:M}}function SP(e){const{createTask:n,onPlanningTaskCreated:s,onPlanningTasksCreated:i,onSubtaskTasksCreated:r,addToast:o}=e,l=a.useCallback(async g=>n({...g,column:"triage"}),[n]),c=a.useCallback(async g=>await n({...g,column:"triage"}),[n]),u=a.useCallback(g=>{s(g,o)},[s,o]),d=a.useCallback(g=>{i(g,o)},[i,o]),m=a.useCallback(g=>{r(g,o)},[r,o]),h=a.useCallback(g=>{o(`Imported ${g.id} from GitHub`,"success")},[o]);return{handleBoardQuickCreate:l,handleModalCreate:c,handlePlanningTaskCreated:u,handlePlanningTasksCreated:d,handleSubtaskTasksCreated:m,handleGitHubImport:h}}async function CP(e){return Bo("/health",{nodeId:e})}async function EP(e){return Bo("/projects",{nodeId:e})}async function _P(e,n,s){const i=new URLSearchParams({projectId:n});return s&&s.trim()&&i.set("q",s.trim()),Bo(`/tasks?${i.toString()}`,{nodeId:e})}async function MP(e,n){return Bo(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:e})}async function $D(e){return z(`/nodes/${encodeURIComponent(e)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function DD(e){return z(`/nodes/${encodeURIComponent(e)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function LD(e){return z(`/nodes/${encodeURIComponent(e)}/settings/sync-status`)}async function zD(e){return z(`/nodes/${encodeURIComponent(e)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}function AP(e,n){const{projectId:s,searchQuery:i}=n??{},[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState(null),[m,h]=a.useState(!1),[g,p]=a.useState(null),f=a.useRef(null),x=a.useCallback(async()=>{if(!e){o([]),c([]),d(null),h(!1),p(null);return}f.current?.abort();const b=new AbortController;f.current=b,h(!0),p(null);try{const y=[CP(e),EP(e)];s&&(y.push(_P(e,s,i)),y.push(MP(e,s)));const S=await Promise.allSettled(y);if(b.signal.aborted)return;const j=S[0],R=S[1];if(j.status==="rejected"){p(`Failed to fetch node health: ${j.reason}`),h(!1);return}if(d(j.value),R.status==="rejected"){p(`Failed to fetch projects: ${R.reason}`),h(!1);return}if(o(R.value),s&&S[2]){const k=S[2];if(k.status==="rejected"){p(`Failed to fetch tasks: ${k.reason}`),h(!1);return}k.status==="fulfilled"&&c(k.value)}h(!1)}catch(y){b.signal.aborted||(p(y instanceof Error?y.message:"Unknown error"),h(!1))}},[e,s,i]);a.useEffect(()=>(x(),()=>{f.current?.abort()}),[x]);const v=a.useCallback(()=>{x()},[x]);return{projects:r,tasks:l,health:u,loading:m,error:g,refresh:v}}function RP(e){const[n,s]=a.useState(!1),[i,r]=a.useState(null);return a.useEffect(()=>{if(!e){s(!1),r(null);return}const o=`/api/proxy/${encodeURIComponent(e)}/events`;return qs(o,{events:{"task:created":l=>{r({type:"task:created",data:l.data})},"task:moved":l=>{r({type:"task:moved",data:l.data})},"task:updated":l=>{r({type:"task:updated",data:l.data})},"task:deleted":l=>{r({type:"task:deleted",data:l.data})},"task:merged":l=>{r({type:"task:merged",data:l.data})}},onOpen:()=>s(!0),onError:()=>s(!1)})},[e]),{isConnected:n,lastEvent:i}}const TP="fusion-dashboard-current-node",bg=a.createContext(null);function PP({children:e}){const[n,s]=a.useState(null),[i,r]=a.useState(!0),o=a.useRef(!1),l=a.useRef(void 0);a.useEffect(()=>{let m=!1;async function h(){try{const g=await Gi();if(m)return;l.current=g.dashboardCurrentNodeId;const p=g.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const f=localStorage.getItem(TP);if(f){const x=JSON.parse(f);x?.id&&x?.type==="remote"&&(l.current=x.id,await ln({dashboardCurrentNodeId:x.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,ln({dashboardCurrentNodeId:m}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,ln({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,i]);const c=a.useCallback(m=>{s(m)},[]),u=a.useCallback(()=>{s(null),l.current=void 0,ln({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),d={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:u};return t.jsx(bg.Provider,{value:d,children:e})}function IP(){const e=a.useContext(bg);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}function $P({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&&(xv(l),window.location.reload())},[n]),o=a.useCallback(()=>{bv(),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 DP=200,LP=a.lazy(()=>on(()=>import("./AgentsView-CsEX_Fsi.js").then(e=>e.A),__vite__mapDeps([17,1,18,8,19])).then(e=>({default:e.AgentsView}))),zP=a.lazy(()=>on(()=>import("./DocumentsView-zpHkjZdf.js"),__vite__mapDeps([20,1,0,2,21])).then(e=>({default:e.DocumentsView}))),FP=a.lazy(()=>on(()=>import("./InsightsView-CgguV1au.js"),__vite__mapDeps([22,1,14,0,2,23])).then(e=>({default:e.InsightsView}))),OP=a.lazy(()=>on(()=>import("./NodesView-DP_O4ae0.js"),__vite__mapDeps([24,1,18,0,2,25])).then(e=>({default:e.NodesView}))),BP=a.lazy(()=>on(()=>import("./ChatView-DhudD-jT.js"),__vite__mapDeps([26,1,0,2])).then(e=>({default:e.ChatView}))),UP=a.lazy(()=>on(()=>import("./RoadmapsView-DNaToPqN.js"),__vite__mapDeps([27,1,0,2,28])).then(e=>({default:e.RoadmapsView}))),HP=a.lazy(()=>on(()=>import("./SkillsView-AS8Cr_Md.js"),__vite__mapDeps([29,1,0,2,30])).then(e=>({default:e.SkillsView}))),qP=a.lazy(()=>on(()=>import("./MemoryView-BWXP8uGT.js"),__vite__mapDeps([31,1,12,13,0,2,32])).then(e=>({default:e.MemoryView}))),VP=a.lazy(()=>on(()=>import("./DevServerView-CNItMoga.js"),__vite__mapDeps([33,1,0,2,34])).then(e=>({default:e.DevServerView}))),WP=a.lazy(()=>on(()=>import("./TodoView-nWOpOg3R.js"),__vite__mapDeps([35,1,36,0,2,37])).then(e=>({default:e.TodoView})));function KP(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{on(()=>import("./AgentsView-CsEX_Fsi.js").then(n=>n.A),__vite__mapDeps([17,1,18,8,19])),on(()=>import("./DocumentsView-zpHkjZdf.js"),__vite__mapDeps([20,1,0,2,21])),on(()=>import("./InsightsView-CgguV1au.js"),__vite__mapDeps([22,1,14,0,2,23])),on(()=>import("./NodesView-DP_O4ae0.js"),__vite__mapDeps([24,1,18,0,2,25])),on(()=>import("./ChatView-DhudD-jT.js"),__vite__mapDeps([26,1,0,2])),on(()=>import("./RoadmapsView-DNaToPqN.js"),__vite__mapDeps([27,1,0,2,28])),on(()=>import("./SkillsView-AS8Cr_Md.js"),__vite__mapDeps([29,1,0,2,30])),on(()=>import("./MemoryView-BWXP8uGT.js"),__vite__mapDeps([31,1,12,13,0,2,32])),on(()=>import("./DevServerView-CNItMoga.js"),__vite__mapDeps([33,1,0,2,34])),on(()=>import("./TodoView-nWOpOg3R.js"),__vite__mapDeps([35,1,36,0,2,37]))})}const mc="kb-setup-warning-dismissed";function GP(){const{toasts:e,addToast:n,removeToast:s}=cP(),i=typeof window<"u"&&!!window.electronAPI;a.useEffect(()=>{KP()},[]);const{projects:r,loading:o,error:l,refresh:c}=iP(),{nodes:u}=qo(),{currentNode:d,currentNodeId:m,isRemote:h,setCurrentNode:g,clearCurrentNode:p}=IP(),{currentProject:f,setCurrentProject:x,clearCurrentProject:v,loading:b}=oP(r,{nodeId:m}),{hasAiProvider:y,hasGithub:S,loading:j,hasWarnings:R}=ig(f?.id),{updateAvailable:k,latestVersion:M,currentVersion:C,dismissed:L,dismiss:A}=yP();a.useEffect(()=>{if(m&&!d&&u.length>0){const ut=u.find(bn=>bn.id===m);if(ut){g(ut);return}}m&&u.length>0&&(u.some(bn=>bn.id===m)||p())},[m,d,u,g,p]);const[P,O]=a.useState(""),V=AP(m,{projectId:f?.id,searchQuery:P||void 0});RP(m);const $=h&&V.projects.length>0?V.projects:r,{themeMode:E,colorTheme:D,setThemeMode:U,setColorTheme:Y}=pP(),{sessions:X,generating:_,needsInput:I,planningSessions:T,dismissSession:w}=eP(f?.id),q=X.filter(ut=>ut.status==="awaiting_input"||ut.status==="error"),G=fP({projectId:f?.id,planningSessions:T}),{viewMode:me,setViewMode:ue,taskView:le,handleChangeTaskView:Se}=wP({projectsLoading:o,projectsError:l,currentProjectLoading:b,currentProject:f,projectsLength:r.length,setupWizardOpen:G.setupWizardOpen,openSetupWizard:G.openSetupWizard,themeMode:E,setThemeMode:U}),F=a.useCallback(ut=>{ut==="missions"&&(ce(void 0),Xe(void 0),Ge(void 0)),Se(ut)},[Se]),ge=le==="board"||le==="list",{tasks:se,createTask:fe,moveTask:de,pauseTask:xe,deleteTask:ie,mergeTask:Ee,retryTask:De,updateTask:qe,duplicateTask:Qe,archiveTask:Je,unarchiveTask:Ke,archiveAllDone:it,loadArchivedTasks:Pe,lastFetchTimeMs:Ve}=tP({...f?{projectId:f.id}:{},searchQuery:P||void 0,sseEnabled:ge}),[ae,ye]=a.useState(!1),te=a.useRef(performance.now()),Ae=a.useRef(!1),Le=a.useRef(!1),pe=a.useMemo(()=>o?"projects":b?"project":"tasks",[o,b]);a.useEffect(()=>{if(!o&&!Ae.current){Ae.current=!0;const ut=`projects loaded at ${Math.round(performance.now()-te.current)}ms from mount`;console.log(`[App] ${ut}`),lr("[App]",ut)}if(!b&&!Le.current){Le.current=!0;const ut=`current-project resolved at ${Math.round(performance.now()-te.current)}ms from mount`;console.log(`[App] ${ut}`),lr("[App]",ut)}},[o,b]),a.useEffect(()=>{if(ae||o||b)return;const ut=performance.now(),bn=window.setTimeout(()=>{const ps=`dashboard ready at ${Math.round(performance.now()-te.current)}ms from mount (settle delay=${Math.round(performance.now()-ut)}ms)`;console.log(`[App] ${ps}`),lr("[App]",ps),ye(!0)},DP);return()=>{window.clearTimeout(bn)}},[ae,o,b]);const Fe=Tr()==="mobile",{keyboardOverlap:tt}=mg({enabled:Fe}),Ne=Fe&&tt>0,[oe,Te]=a.useState(0),he=a.useCallback(()=>{gp(f?.id).then(ut=>{Te(ut.unreadCount)}).catch(ut=>{console.warn("[App] Failed to fetch mailbox unread count:",ut)})},[f?.id]);a.useEffect(()=>{he();const ut=new URLSearchParams;f?.id&&ut.set("projectId",f.id);const bn=ut.size>0?`?${ut.toString()}`:"";return qs(`/api/events${bn}`,{events:{"message:sent":he,"message:received":he,"message:read":he,"message:deleted":he}})},[f?.id,he]);const[Me,We]=a.useState(!1),[Re,ot]=a.useState(!1),[J,ce]=a.useState(void 0),[ve,Xe]=a.useState(void 0),[ee,Ge]=a.useState(void 0),[ct,vt]=a.useState(!1),[bt,ft]=a.useState(!1),[gt,_t]=a.useState(()=>qn(mc,f?.id)==="true");a.useEffect(()=>{_t(qn(mc,f?.id)==="true")},[f?.id]),a.useEffect(()=>{const ut=()=>{ft(!0)};return window.addEventListener(Nc,ut),()=>{window.removeEventListener(Nc,ut)}},[]);const Rt=a.useCallback(()=>{ds(mc,"true",f?.id),_t(!0)},[f?.id]),{maxConcurrent:Ft,autoMerge:wt,globalPaused:At,enginePaused:qt,taskStuckTimeoutMs:zt,showQuickChatFAB:Wt,prAuthAvailable:Ot,experimentalFeatures:Nt,insightsEnabled:Mt,roadmapEnabled:Ct,memoryEnabled:Gt,devServerEnabled:Et,todosEnabled:H,toggleAutoMerge:be,toggleGlobalPause:re,toggleEnginePause:N,refresh:W}=gP(f?.id),Ie=Nt.skillsView===!0,nt=Nt.nodesView===!0,yt=!0;a.useEffect(()=>{Object.keys(Nt).length!==0&&(le==="insights"&&!Mt&&Se("board"),le==="roadmaps"&&!Ct&&Se("board"),le==="memory"&&!Gt&&Se("board"),(le==="devserver"||le==="dev-server")&&!Et&&Se("board"),le==="todos"&&!H&&Se("board"))},[le,Mt,Ct,Nt,Se,yt,Gt,Et,H]),a.useEffect(()=>{Me&&!nt&&We(!1)},[Me,nt]);const{availableModels:Pt,favoriteProviders:Tt,favoriteModels:tn,toggleFavoriteProvider:nn,toggleFavoriteModel:Ln}=bP();vP({projectId:f?.id,setupWizardOpen:G.setupWizardOpen,openModelOnboarding:G.openModelOnboarding,openSettings:G.openSettings});const{handleSelectProject:Jt,handleViewAllProjects:Rn,handleOpenSettings:ke,handleAddProject:at,handleSetupComplete:gn,handleModelOnboardingComplete:Tn,handlePauseProject:Pn,handleResumeProject:Nn,handleRemoveProject:es,handleToggleFavorite:Sn,handleToggleModelFavorite:Yt}=NP({setCurrentProject:x,clearCurrentProject:v,setViewMode:ue,currentProject:f,refreshProjects:c,toggleFavoriteProvider:nn,toggleFavoriteModel:Ln,addToast:n,openSettings:G.openSettings,openSetupWizard:G.openSetupWizard,closeSetupWizard:G.closeSetupWizard,closeModelOnboarding:G.closeModelOnboarding}),{handleDetailClose:Q}=xP({projectId:f?.id,projects:r,projectsLoading:o,currentProject:f,setCurrentProject:x,addToast:n,openTaskDetail:G.openDetailTask,closeTaskDetail:G.closeDetailTask}),{handleBoardQuickCreate:ze,handleModalCreate:Ye,handlePlanningTaskCreated:et,handlePlanningTasksCreated:dt,handleSubtaskTasksCreated:St,handleGitHubImport:It}=SP({createTask:fe,onPlanningTaskCreated:G.onPlanningTaskCreated,onPlanningTasksCreated:G.onPlanningTasksCreated,onSubtaskTasksCreated:G.onSubtaskTasksCreated,addToast:n}),kn=a.useCallback((ut,bn)=>{if(bn==="changes"){G.openDetailWithChangesTab(ut);return}G.openDetailTask(ut,bn)},[G]),sn=a.useCallback(()=>{nt&&We(ut=>!ut)},[nt]),jt=a.useCallback(()=>{G.setFileWorkspace("project"),G.openFiles()},[G]),os=a.useCallback(async()=>{ot(!0);try{await c()}finally{ot(!1)}},[c]),ws=a.useCallback(ut=>{Xe(ut),ce(void 0),Se("missions")},[Se]),Ns=a.useCallback(ut=>{ut.type==="planning"?G.openPlanningWithSession(ut.id):ut.type==="subtask"?G.openSubtaskWithSession(ut.id):ut.type==="mission_interview"?(Xe(void 0),ce(ut.id),Ge(void 0),Se("missions")):(ut.type==="milestone_interview"||ut.type==="slice_interview")&&(ce(void 0),Xe(void 0),Ge(ut.id),Se("missions"))},[Se,G]),$s=a.useCallback(()=>{},[]),ii=a.useCallback(()=>{},[]),Ds=!o&&!b&&r.length===0&&!f&&!!l,Ls=()=>Ds?t.jsx(mT,{errorMessage:l??"Failed to fetch projects",isRetrying:Re,onRetry:os}):Me?t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(ns,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(OP,{addToast:n,onClose:()=>We(!1)})})})}):me==="overview"?t.jsx(ns,{children:t.jsx(YN,{projects:r,loading:o,onSelectProject:Jt,onAddProject:at,onPauseProject:Pn,onResumeProject:Nn,onRemoveProject:es,nodes:u})}):le==="skills"?Ie?t.jsx(ns,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(HP,{addToast:n,projectId:f?.id,onClose:()=>Se("board")})})}):(Se("board"),null):le==="chat"?t.jsx(ns,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(BP,{addToast:n,projectId:f?.id})})}):le==="mailbox"?t.jsx(ns,{children:t.jsx(U1,{projectId:f?.id,addToast:n,onUnreadCountChange:Te})}):le==="roadmaps"?t.jsx(ns,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(UP,{addToast:n,projectId:f?.id})})}):le==="missions"?t.jsx(ns,{children:t.jsx(z1,{isInline:!0,isOpen:!0,onClose:()=>{Xe(void 0),ce(void 0),Ge(void 0),Se("board")},addToast:n,projectId:f?.id,onSelectTask:ut=>{const bn=se.find(ps=>ps.id===ut);bn&&G.openDetailTask(bn)},availableTasks:se.map(ut=>({id:ut.id,title:ut.title})),resumeSessionId:J,targetMissionId:ve,milestoneSliceResumeSessionId:ee,onMilestoneSliceResumeFetchError:()=>Ge(void 0)})}):le==="agents"&&yt?t.jsx(ns,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(LP,{addToast:n,projectId:f?.id})})}):le==="documents"?t.jsx(ns,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(zP,{projectId:f?.id,addToast:n,onOpenDetail:G.openDetailTask})})}):le==="insights"?t.jsx(ns,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(FP,{projectId:f?.id,addToast:n,onClose:()=>Se("board")})})}):le==="memory"?t.jsx(ns,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(qP,{addToast:n,projectId:f?.id})})}):le==="todos"?t.jsx(ns,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(WP,{addToast:n,projectId:f?.id})})}):le==="devserver"||le==="dev-server"?t.jsx(ns,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(VP,{addToast:n,projectId:f?.id})})}):le==="board"?t.jsx(ns,{children:t.jsx(DN,{tasks:h&&V.tasks.length>0?V.tasks:se,projectId:f?.id,maxConcurrent:Ft,onMoveTask:de,onPauseTask:xe,onOpenDetail:G.openDetailTask,addToast:n,onQuickCreate:ze,onNewTask:G.openNewTask,onPlanningMode:G.openPlanningWithInitialPlan,onSubtaskBreakdown:G.openSubtaskBreakdown,autoMerge:wt,onToggleAutoMerge:be,globalPaused:At,onUpdateTask:qe,onRetryTask:De,onArchiveTask:Je,onUnarchiveTask:Ke,onDeleteTask:ie,onArchiveAllDone:it,onLoadArchivedTasks:Pe,searchQuery:P,availableModels:Pt,onOpenDetailWithTab:kn,favoriteProviders:Tt,favoriteModels:tn,onToggleFavorite:Sn,onToggleModelFavorite:Yt,taskStuckTimeoutMs:zt,onOpenMission:ws,lastFetchTimeMs:Ve})}):t.jsx(ns,{children:t.jsx(ON,{tasks:h&&V.tasks.length>0?V.tasks:se,projectId:f?.id,onMoveTask:de,onRetryTask:De,onOpenDetail:G.openDetailTask,addToast:n,globalPaused:At,onNewTask:G.openNewTask,onQuickCreate:ze,onPlanningMode:G.openPlanningWithInitialPlan,onSubtaskBreakdown:G.openSubtaskBreakdown,availableModels:Pt,favoriteProviders:Tt,favoriteModels:tn,onToggleFavorite:Sn,onToggleModelFavorite:Yt,taskStuckTimeoutMs:zt,searchQuery:P,lastFetchTimeMs:Ve})});if(!ae)return t.jsxs(t.Fragment,{children:[t.jsx(pT,{stage:pe}),t.jsx(dg,{toasts:e,onRemove:s})]});const Ei=!G.modelOnboardingOpen&&L4(),gi=!G.modelOnboardingOpen&&!Ei&&Ea()&&!rg();return t.jsxs(t.Fragment,{children:[t.jsx(dw,{isElectron:i,onOpenSettings:ke,onOpenGitHubImport:G.openGitHubImport,onOpenPlanning:G.openPlanning,onResumePlanning:G.resumePlanning,activePlanningSessionCount:T.length,onOpenUsage:G.openUsage,onOpenActivityLog:G.openActivityLog,onOpenSystemStats:G.openSystemStats,onOpenMailbox:()=>F("mailbox"),mailboxUnreadCount:oe,onOpenSchedules:G.openSchedules,onOpenGitManager:G.openGitManager,onOpenNodes:sn,showNodesButton:nt,onOpenWorkflowSteps:G.openWorkflowSteps,onOpenScripts:G.openScripts,onRunScript:G.runScript,onToggleTerminal:G.toggleTerminal,onOpenFiles:G.openFiles,filesOpen:G.filesOpen,globalPaused:At,enginePaused:qt,onToggleGlobalPause:re,onToggleEnginePause:N,view:le,onChangeView:me==="project"&&f?F:void 0,showSkillsTab:Ie,showAgentsTab:yt,searchQuery:P,onSearchChange:O,projects:$,currentProject:f,onSelectProject:Jt,onViewAllProjects:Rn,projectId:f?.id,mobileNavEnabled:Fe,availableNodes:u,currentNode:d,onSelectNode:ut=>{ut===null?p():g(ut)},isRemote:h,experimentalFeatures:{insights:Mt,roadmap:Ct,memoryView:Gt,devServer:Et,devServerView:Et,todoView:H}}),me==="project"&&f&&!Me&&le!=="missions"&&!G.isPlanningOpen&&t.jsx(ET,{sessions:q,onResumeSession:Ns,onDismissSession:$s,onDismissAll:ii}),me==="project"&&f&&Ei&&t.jsx(MT,{onResume:G.openModelOnboarding}),me==="project"&&f&&gi&&t.jsx(AT,{onOpenModelOnboarding:G.openModelOnboarding,onOpenSettings:ut=>G.openSettings(ut)}),me==="project"&&f&&k&&M&&C&&!L&&t.jsx(_T,{latestVersion:M,currentVersion:C,onDismiss:A}),me==="project"&&f&&!j&&R&&!gt&&t.jsx(ag,{hasAiProvider:y,hasGithub:S,onDismiss:Rt}),t.jsx("div",{className:`project-content${me==="project"&&f?" project-content--with-footer":""}${Fe&&!Ne?" project-content--with-mobile-nav":""}`,children:Ls()}),me==="project"&&f&&!Me&&t.jsx(NT,{tasks:h&&V.tasks.length>0?V.tasks:se,projectId:f.id,taskStuckTimeoutMs:zt,backgroundSessions:X,backgroundGenerating:_,backgroundNeedsInput:I,onOpenBackgroundSession:Ns,onDismissBackgroundSession:w,lastFetchTimeMs:Ve,currentProjectPath:f.path,onOpenProjectDirectory:jt}),t.jsx(TT,{view:le,onChangeView:me==="project"&&f?F:()=>{},footerVisible:me==="project"&&!!f,modalOpen:G.anyModalOpen,keyboardOpen:Ne,onOpenSettings:ke,onOpenActivityLog:G.openActivityLog,onOpenSystemStats:G.openSystemStats,onOpenMailbox:()=>F("mailbox"),mailboxUnreadCount:oe,onOpenGitManager:G.openGitManager,onOpenWorkflowSteps:G.openWorkflowSteps,onOpenSchedules:G.openSchedules,onOpenScripts:G.openScripts,onToggleTerminal:G.toggleTerminal,onOpenFiles:G.openFiles,onOpenGitHubImport:G.openGitHubImport,onOpenPlanning:G.openPlanning,onResumePlanning:G.resumePlanning,activePlanningSessionCount:T.length,onOpenUsage:()=>G.openUsage(null),onViewAllProjects:Rn,onRunScript:G.runScript,projectId:f?.id,showSkillsTab:Ie,experimentalFeatures:{insights:Mt,roadmap:Ct,memoryView:Gt,devServer:Et,devServerView:Et,todoView:H}}),me==="project"&&f&&le!=="chat"&&le!=="mailbox"&&le!=="insights"&&le!=="devserver"&&le!=="dev-server"&&t.jsx(ZT,{projectId:f.id,addToast:n,showFAB:Wt,open:ct,onOpenChange:vt,favoriteProviders:Tt,favoriteModels:tn,onToggleFavorite:Sn,onToggleModelFavorite:Yt}),t.jsx(uT,{projectId:f?.id,tasks:se,projects:r,currentProject:f,addToast:n,toasts:e,removeToast:s,modalManager:G,projectActions:{handleAddProject:at,handleSetupComplete:gn,handleModelOnboardingComplete:Tn},taskHandlers:{handleModalCreate:Ye,handlePlanningTaskCreated:et,handlePlanningTasksCreated:dt,handleSubtaskTasksCreated:St,handleGitHubImport:It},taskOperations:{moveTask:de,deleteTask:ie,mergeTask:Ee,retryTask:De,duplicateTask:Qe},deepLink:{handleDetailClose:Q},settings:{prAuthAvailable:Ot,themeMode:E,colorTheme:D,setThemeMode:U,setColorTheme:Y},onSettingsClose:()=>{G.closeSettings(),W()},onReopenOnboarding:()=>{G.closeSettings(),G.openModelOnboarding()}}),t.jsx($P,{open:bt})]})}function JP(){return t.jsx(lP,{children:t.jsx(PP,{children:t.jsx(Nw,{children:t.jsx(GP,{})})})})}Sv();dv();vg.createRoot(document.getElementById("root")).render(t.jsx(a.StrictMode,{children:t.jsx(uv,{children:t.jsx(JP,{})})}));"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{on as $,Ps as A,yn as B,fn as C,k4 as D,ID as E,Ui as F,Io as G,pn as H,ac as I,jn as J,Xs as K,rt as L,Zt as M,Vt as N,E4 as O,Dn as P,Mj as Q,En as R,ma as S,Xc as T,y4 as U,j4 as V,Aj as W,Ut as X,d$ as Y,Bn as Z,Rj as _,ds as a,D$ as a$,TI as a0,PI as a1,xo as a2,zy as a3,gc as a4,fa as a5,_a as a6,hi as a7,pi as a8,ui as a9,vr as aA,Xk as aB,jD as aC,kD as aD,Zk as aE,ew as aF,FT as aG,Tr as aH,mg as aI,Wh as aJ,To as aK,yb as aL,PT as aM,LT as aN,bs as aO,zi as aP,ji as aQ,VT as aR,E$ as aS,M$ as aT,_$ as aU,A$ as aV,R$ as aW,T$ as aX,P$ as aY,I$ as aZ,$$ as a_,wD as aa,CD as ab,SD as ac,ND as ad,ED as ae,Xn as af,as as ag,Qb as ah,ei as ai,px as aj,Ro as ak,wi as al,LD as am,$D as an,DD as ao,zD as ap,fr as aq,Ob as ar,or as as,cx as at,ss as au,Qh as av,qo as aw,iP as ax,yD as ay,au as az,v$ as b,mD as b$,L$ as b0,z$ as b1,F$ as b2,O$ as b3,U$ as b4,H$ as b5,B$ as b6,$n as b7,Qc as b8,Bi as b9,XI as bA,oj as bB,ZI as bC,ed as bD,ij as bE,aj as bF,rj as bG,sj as bH,VI as bI,Cr as bJ,Lo as bK,zb as bL,pr as bM,Rb as bN,V$ as bO,W$ as bP,K$ as bQ,G$ as bR,J$ as bS,Y$ as bT,Q$ as bU,q$ as bV,np as bW,ba as bX,Lj as bY,xv as bZ,bv as b_,bD as ba,xD as bb,vD as bc,Dd as bd,mI as be,uI as bf,dI as bg,hI as bh,kI as bi,wI as bj,vI as bk,gI as bl,xI as bm,bI as bn,fI as bo,pI as bp,cI as bq,yI as br,cR as bs,GI as bt,KI as bu,e$ as bv,WI as bw,JI as bx,YI as by,QI as bz,Oe as c,nD as c$,$I as c0,II as c1,hD as c2,DI as c3,qI as c4,BI as c5,LI as c6,UI as c7,zI as c8,HI as c9,C$ as cA,pc as cB,Un as cC,oR as cD,M4 as cE,rc as cF,Uo as cG,iI as cH,tI as cI,sI as cJ,aI as cK,rI as cL,oI as cM,lI as cN,Vi as cO,xw as cP,Ho as cQ,RD as cR,Km as cS,TD as cT,PD as cU,jI as cV,X$ as cW,eD as cX,sD as cY,tD as cZ,Z$ as c_,FI as ca,OI as cb,Ig as cc,ni as cd,JA as ce,NI as cf,S$ as cg,XP as ch,ZP as ci,xr as cj,y$ as ck,eI as cl,nI as cm,uy as cn,ny as co,ti as cp,sy as cq,iy as cr,ay as cs,EI as ct,j$ as cu,k$ as cv,w$ as cw,Si as cx,MD as cy,AD as cz,x$ as d,iD as d0,dp as d1,Bd as d2,qx as d3,aD as d4,m$ as d5,o$ as d6,c$ as d7,l$ as d8,f$ as d9,SI as dA,CI as dB,AI as dC,RI as dD,MI as dE,p$ as da,Vh as db,a$ as dc,i$ as dd,v4 as de,u$ as df,Sr as dg,xM as dh,n$ as di,t$ as dj,Fy as dk,s$ as dl,r$ as dm,rD as dn,oD as dp,Mb as dq,yc as dr,pD as ds,dD as dt,cD as du,uD as dv,lD as dw,N$ as dx,_D as dy,_I as dz,b$ as e,gD as f,qn as g,ms as h,Ma as i,fD as j,Hn as k,_j as l,g$ as m,DT as n,Hs as o,Fo as p,Br as q,je as r,qs as s,jw as t,ln as u,h$ as v,bc as w,Zs as x,en as y,po as z};
|