@runfusion/fusion 0.11.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +1644 -509
- package/dist/client/assets/{AgentDetailView-DQBjJSPJ.js → AgentDetailView-B7j297GT.js} +4 -4
- package/dist/client/assets/AgentsView-Dvf_xUkx.js +522 -0
- package/dist/client/assets/{AgentsView-xm_3NO4M.css → AgentsView-V5GhlBYu.css} +1 -1
- package/dist/client/assets/ChatView-BgUt38ty.js +1 -0
- package/dist/client/assets/{DevServerView-BVixhlF0.js → DevServerView-C2qTJch7.js} +1 -1
- package/dist/client/assets/{DirectoryPicker-tvBgHxa7.js → DirectoryPicker-DRfhg9zz.js} +1 -1
- package/dist/client/assets/{DocumentsView-DVw_wT6V.js → DocumentsView-j8ic1xUw.js} +1 -1
- package/dist/client/assets/{InsightsView-G3MZhwSx.js → InsightsView-CpAz3o0i.js} +3 -3
- package/dist/client/assets/{MemoryView-Bl9gx2Dw.js → MemoryView-BcQsi_JK.js} +2 -2
- package/dist/client/assets/{NodesView-dwVhD4V2.js → NodesView-Bo_Yhr4N.js} +4 -4
- package/dist/client/assets/{PiExtensionsManager-CEHp6_Mj.js → PiExtensionsManager-DHt2zFg8.js} +3 -3
- package/dist/client/assets/{PluginManager-Dx0mcwat.js → PluginManager-BQhBHWrB.js} +1 -1
- package/dist/client/assets/ResearchView-BzRdUzNq.css +1 -0
- package/dist/client/assets/{ResearchView-BvlLYC_1.js → ResearchView-CLyyqAWE.js} +1 -1
- package/dist/client/assets/{RoadmapsView-DdYXssP2.js → RoadmapsView-tG7IdOoc.js} +2 -2
- package/dist/client/assets/{SettingsModal-CGWipm3s.js → SettingsModal-CXUGeZ0_.js} +1 -1
- package/dist/client/assets/{SettingsModal-CriZP5Lp.css → SettingsModal-DcGFm6NR.css} +1 -1
- package/dist/client/assets/SettingsModal-UziTDnLh.js +31 -0
- package/dist/client/assets/{SetupWizardModal-CKsJduYM.js → SetupWizardModal-BMJL6eNR.js} +1 -1
- package/dist/client/assets/SkillMultiselect-DDHJnrkn.css +1 -0
- package/dist/client/assets/SkillMultiselect-ILMft-Kz.js +1 -0
- package/dist/client/assets/SkillsView-x4_YwBz6.js +1 -0
- package/dist/client/assets/{TodoView-ByXJ90yL.js → TodoView-BBYcMbXE.js} +2 -2
- package/dist/client/assets/{folder-open-CxOUgHDf.js → folder-open-DDdJt8aE.js} +1 -1
- package/dist/client/assets/index-B15xwijw.css +1 -0
- package/dist/client/assets/index-DmSs2FGE.js +661 -0
- package/dist/client/assets/{list-checks--sf9u9ox.js → list-checks-DFxQ9biT.js} +1 -1
- package/dist/client/assets/{star-CF1f2iPu.js → star-BKs1bgJN.js} +1 -1
- package/dist/client/assets/{upload-rOBd4OhB.js → upload-Bb5Pidne.js} +1 -1
- package/dist/client/assets/{users-De-vFat1.js → users-BImNn91Q.js} +1 -1
- package/dist/client/index.html +2 -2
- package/dist/client/theme-data.css +1 -1
- package/dist/client/version.json +1 -1
- package/dist/extension.js +548 -96
- package/dist/pi-claude-cli/package.json +1 -1
- package/dist/pi-claude-cli/src/__tests__/prompt-builder.test.ts +36 -0
- package/dist/pi-claude-cli/src/prompt-builder.ts +19 -28
- package/package.json +1 -1
- package/skill/fusion/references/cli-commands.md +14 -0
- package/skill/fusion/references/engine-tools.md +1 -0
- package/dist/client/assets/AgentsView-DlA0yHBg.js +0 -522
- package/dist/client/assets/ChatView-DK5CmiAk.js +0 -1
- package/dist/client/assets/ResearchView-BVJFgfat.css +0 -1
- package/dist/client/assets/SettingsModal-Bgjg_4CD.js +0 -31
- package/dist/client/assets/SkillsView-C4Tz7CxC.js +0 -1
- package/dist/client/assets/index-BCz4ye4p.css +0 -1
- package/dist/client/assets/index-D7gT6mCr.js +0 -656
|
@@ -0,0 +1,661 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AgentDetailView-B7j297GT.js","assets/vendor-react-K0fH_qHe.js","assets/star-BKs1bgJN.js","assets/SkillMultiselect-ILMft-Kz.js","assets/SkillMultiselect-DDHJnrkn.css","assets/list-checks-DFxQ9biT.js","assets/vendor-xterm-DzcZoU0P.js","assets/vendor-xterm-LZoznX6r.css","assets/AgentDetailView-B5tq9ius.css","assets/addon-fit-C7jRorKK.js","assets/addon-web-links-CkJwd4cQ.js","assets/addon-webgl-BjvOw43o.js","assets/SetupWizardModal-BMJL6eNR.js","assets/DirectoryPicker-DRfhg9zz.js","assets/folder-open-DDdJt8aE.js","assets/DirectoryPicker-DzKVmxOf.css","assets/SetupWizardModal-DRF5fOoR.css","assets/SettingsModal-UziTDnLh.js","assets/SettingsModal-CXUGeZ0_.js","assets/SettingsModal-DcGFm6NR.css","assets/users-BImNn91Q.js","assets/SettingsModal-9HS8MnmW.css","assets/AgentsView-Dvf_xUkx.js","assets/upload-Bb5Pidne.js","assets/AgentsView-V5GhlBYu.css","assets/DocumentsView-j8ic1xUw.js","assets/DocumentsView-BrhyOdeE.css","assets/InsightsView-CpAz3o0i.js","assets/InsightsView-4KiUKzbz.css","assets/ResearchView-CLyyqAWE.js","assets/ResearchView-BzRdUzNq.css","assets/NodesView-Bo_Yhr4N.js","assets/NodesView-DCoS6iYh.css","assets/ChatView-BgUt38ty.js","assets/RoadmapsView-tG7IdOoc.js","assets/RoadmapsView-BOYnyMCh.css","assets/SkillsView-x4_YwBz6.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-BcQsi_JK.js","assets/MemoryView-DiajLXby.css","assets/DevServerView-C2qTJch7.js","assets/DevServerView-DlZpuAnj.css","assets/TodoView-BBYcMbXE.js","assets/TodoView-C1g65hJo.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as a,j as t,R as So,a as ma,g as ep,c as Fg}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 tp=(...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 Og=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 Ug=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 Ud=e=>{const n=Ug(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 pl={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 Bg=e=>{for(const n in e)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},Hg=a.createContext({}),qg=()=>a.useContext(Hg),Vg=a.forwardRef(({color:e,size:n,strokeWidth:s,absoluteStrokeWidth:i,className:r="",children:o,iconNode:l,...c},u)=>{const{size:d=24,strokeWidth:m=2,absoluteStrokeWidth:h=!1,color:f="currentColor",className:p=""}=qg()??{},g=i??h?Number(s??m)*24/Number(n??d):s??m;return a.createElement("svg",{ref:u,...pl,width:n??d??pl.width,height:n??d??pl.height,stroke:e??f,strokeWidth:g,className:tp("lucide",p,r),...!o&&!Bg(c)&&{"aria-hidden":"true"},...c},[...l.map(([b,v])=>a.createElement(b,v)),...Array.isArray(o)?o:[o]])});/**
|
|
33
|
+
* @license lucide-react v1.7.0 - ISC
|
|
34
|
+
*
|
|
35
|
+
* This source code is licensed under the ISC license.
|
|
36
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
37
|
+
*/const Ve=(e,n)=>{const s=a.forwardRef(({className:i,...r},o)=>a.createElement(Vg,{ref:o,iconNode:n,className:tp(`lucide-${Og(Ud(e))}`,`lucide-${e}`,i),...r}));return s.displayName=Ud(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 Wg=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],Ds=Ve("activity",Wg);/**
|
|
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 Kg=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h2",key:"tvwodi"}],["path",{d:"M20 8v11a2 2 0 0 1-2 2h-2",key:"1gkqxj"}],["path",{d:"m9 15 3-3 3 3",key:"1pd0qc"}],["path",{d:"M12 12v9",key:"192myk"}]],Gg=Ve("archive-restore",Kg);/**
|
|
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 Jg=[["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"}]],Mr=Ve("archive",Jg);/**
|
|
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 Yg=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],Ar=Ve("arrow-down",Yg);/**
|
|
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 Qg=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],_a=Ve("arrow-left",Qg);/**
|
|
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 Xg=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],Rr=Ve("arrow-right",Xg);/**
|
|
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 Zg=[["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"}]],np=Ve("arrow-up-down",Zg);/**
|
|
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 eb=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Fi=Ve("arrow-up",eb);/**
|
|
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 tb=[["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"}]],nb=Ve("book-open",tb);/**
|
|
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 sb=[["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"}]],Cn=Ve("bot",sb);/**
|
|
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 ib=[["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"}]],kc=Ve("box",ib);/**
|
|
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 ab=[["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"}]],Co=Ve("brain",ab);/**
|
|
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 rb=[["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"}]],sp=Ve("calendar",rb);/**
|
|
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 ob=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],lb=Ve("check-check",ob);/**
|
|
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 cb=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],qn=Ve("check",cb);/**
|
|
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 db=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],sn=Ve("chevron-down",db);/**
|
|
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 ub=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],Ho=Ve("chevron-left",ub);/**
|
|
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 mb=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],kn=Ve("chevron-right",mb);/**
|
|
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 hb=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],gi=Ve("chevron-up",hb);/**
|
|
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 pb=[["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"}]],ps=Ve("circle-alert",pb);/**
|
|
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 fb=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],wn=Ve("circle-check-big",fb);/**
|
|
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 gb=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],qo=Ve("circle-dot",gb);/**
|
|
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 bb=[["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"}]],wc=Ve("circle-question-mark",bb);/**
|
|
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 xb=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],vb=Ve("circle-stop",xb);/**
|
|
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 yb=[["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"}]],Tr=Ve("circle-x",yb);/**
|
|
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 jb=[["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"}]],kb=Ve("clipboard-list",jb);/**
|
|
168
|
+
* @license lucide-react v1.7.0 - ISC
|
|
169
|
+
*
|
|
170
|
+
* This source code is licensed under the ISC license.
|
|
171
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
172
|
+
*/const wb=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],Ci=Ve("clock",wb);/**
|
|
173
|
+
* @license lucide-react v1.7.0 - ISC
|
|
174
|
+
*
|
|
175
|
+
* This source code is licensed under the ISC license.
|
|
176
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
177
|
+
*/const Nb=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],ip=Ve("code",Nb);/**
|
|
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 Sb=[["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"}]],Cb=Ve("columns-3",Sb);/**
|
|
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 Eb=[["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"}]],Ui=Ve("copy",Eb);/**
|
|
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 _b=[["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"}]],Mb=Ve("cpu",_b);/**
|
|
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 Ab=[["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"}]],Rb=Ve("download",Ab);/**
|
|
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 Tb=[["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"}]],Pb=Ve("ellipsis-vertical",Tb);/**
|
|
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 Ib=[["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"}]],Nc=Ve("ellipsis",Ib);/**
|
|
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 $b=[["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"}]],Db=Ve("external-link",$b);/**
|
|
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 Lb=[["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"}]],rd=Ve("eye-off",Lb);/**
|
|
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 zb=[["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"}]],Ma=Ve("eye",zb);/**
|
|
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 Fb=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}]],Hs=Ve("file-code",Fb);/**
|
|
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 Ob=[["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"}]],Sc=Ve("file-diff",Ob);/**
|
|
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 Ub=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}]],Bb=Ve("file-minus",Ub);/**
|
|
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 Hb=[["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"}]],ap=Ve("file-pen",Hb);/**
|
|
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 qb=[["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"}]],Vb=Ve("file-plus",qb);/**
|
|
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 Wb=[["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"}]],Kb=Ve("file-question-mark",Wb);/**
|
|
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 Gb=[["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"}]],Bi=Ve("file-text",Gb);/**
|
|
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 Jb=[["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"}]],Yb=Ve("file-type",Jb);/**
|
|
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 Qb=[["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"}]],rp=Ve("file",Qb);/**
|
|
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 Xb=[["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"}]],Cc=Ve("folder-git-2",Xb);/**
|
|
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 Zb=[["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"}]],Bd=Ve("folder-root",Zb);/**
|
|
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 ex=[["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"}]],Qn=Ve("folder",ex);/**
|
|
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 tx=[["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"}]],Eo=Ve("funnel",tx);/**
|
|
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 nx=[["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"}]],Ws=Ve("git-branch",nx);/**
|
|
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 sx=[["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"}]],Pr=Ve("git-commit-horizontal",sx);/**
|
|
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 ix=[["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"}]],op=Ve("git-merge",ix);/**
|
|
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 ax=[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v7",key:"1yeb86"}],["line",{x1:"6",x2:"6",y1:"9",y2:"21",key:"rroup"}]],Es=Ve("git-pull-request",ax);/**
|
|
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 rx=[["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"}]],Vo=Ve("globe",rx);/**
|
|
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=[["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"}]],lp=Ve("grid-3x3",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 lx=[["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"}]],od=Ve("grip-vertical",lx);/**
|
|
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 cx=[["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"}]],dx=Ve("hard-drive",cx);/**
|
|
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 ux=[["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"}]],mx=Ve("heart",ux);/**
|
|
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 hx=[["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"}]],xr=Ve("history",hx);/**
|
|
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 px=[["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"}]],or=Ve("inbox",px);/**
|
|
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 fx=[["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"}]],cp=Ve("key",fx);/**
|
|
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 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"}]],bx=Ve("keyboard",gx);/**
|
|
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 xx=[["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=Ve("layers",xx);/**
|
|
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 vx=[["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=Ve("layout-grid",vx);/**
|
|
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 yx=[["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"}]],ai=Ve("lightbulb",yx);/**
|
|
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 jx=[["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=Ve("link",jx);/**
|
|
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 kx=[["path",{d:"M16 5H3",key:"m91uny"}],["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 19H3",key:"zzsher"}],["path",{d:"M18 9v6",key:"1twb98"}],["path",{d:"M21 12h-6",key:"bt1uis"}]],wx=Ve("list-plus",kx);/**
|
|
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 Nx=[["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"}]],Wo=Ve("list-tree",Nx);/**
|
|
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 Sx=[["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"}]],Ec=Ve("list",Sx);/**
|
|
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 Cx=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],lt=Ve("loader-circle",Cx);/**
|
|
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 Ex=[["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"}]],Ko=Ve("lock",Ex);/**
|
|
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 _x=[["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"}]],ba=Ve("mail",_x);/**
|
|
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 Mx=[["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"}]],_c=Ve("map",Mx);/**
|
|
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 Ax=[["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"}]],Go=Ve("maximize-2",Ax);/**
|
|
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 Rx=[["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"}]],Tx=Ve("message-square-plus",Rx);/**
|
|
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 Px=[["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"}]],Ni=Ve("message-square",Px);/**
|
|
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 Ix=[["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"}]],Ir=Ve("minimize-2",Ix);/**
|
|
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 $x=[["path",{d:"M5 12h14",key:"1ays0h"}]],Dx=Ve("minus",$x);/**
|
|
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 Lx=[["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"}]],vr=Ve("monitor",Lx);/**
|
|
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 zx=[["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"}]],Fx=Ve("move",zx);/**
|
|
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 Ox=[["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"}]],Mc=Ve("package",Ox);/**
|
|
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 Ux=[["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"}]],dp=Ve("paperclip",Ux);/**
|
|
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 Bx=[["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"}]],qs=Ve("pause",Bx);/**
|
|
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 Hx=[["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"}]],ms=Ve("pencil",Hx);/**
|
|
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 qx=[["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"}]],En=Ve("play",qx);/**
|
|
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 Vx=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],ln=Ve("plus",Vx);/**
|
|
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 Wx=[["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"}]],up=Ve("radio",Wx);/**
|
|
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 Kx=[["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"}]],Ln=Ve("refresh-cw",Kx);/**
|
|
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 Gx=[["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"}]],Hd=Ve("rocket",Gx);/**
|
|
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 Jx=[["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"}]],Yx=Ve("rotate-ccw",Jx);/**
|
|
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 Qx=[["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"}]],Xx=Ve("rotate-cw",Qx);/**
|
|
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 Zx=[["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"}]],mp=Ve("save",Zx);/**
|
|
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 ev=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],wi=Ve("search",ev);/**
|
|
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 tv=[["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=Ve("send",tv);/**
|
|
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 nv=[["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"}]],yr=Ve("server",nv);/**
|
|
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 sv=[["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"}]],hr=Ve("settings",sv);/**
|
|
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 iv=[["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"}]],av=Ve("shield-alert",iv);/**
|
|
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 rv=[["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"}]],ov=Ve("shield",rv);/**
|
|
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 lv=[["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"}]],cv=Ve("skull",lv);/**
|
|
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 dv=[["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"}]],os=Ve("sparkles",dv);/**
|
|
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 uv=[["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"}]],hp=Ve("square-check-big",uv);/**
|
|
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 mv=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],Cs=Ve("square",mv);/**
|
|
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 hv=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]],ks=Ve("target",hv);/**
|
|
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 pv=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],pi=Ve("terminal",pv);/**
|
|
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 fv=[["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"}]],_o=Ve("text-wrap",fv);/**
|
|
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 gv=[["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"}]],on=Ve("trash-2",gv);/**
|
|
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 bv=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],xv=Ve("trending-up",bv);/**
|
|
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 vv=[["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"}]],ld=Ve("triangle-alert",vv);/**
|
|
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 yv=[["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"}]],qd=Ve("unlink",yv);/**
|
|
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 jv=[["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"}]],sa=Ve("user",jv);/**
|
|
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 kv=[["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"}]],pp=Ve("webhook",kv);/**
|
|
598
|
+
* @license lucide-react v1.7.0 - ISC
|
|
599
|
+
*
|
|
600
|
+
* This source code is licensed under the ISC license.
|
|
601
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
602
|
+
*/const wv=[["rect",{width:"8",height:"8",x:"3",y:"3",rx:"2",key:"by2w9f"}],["path",{d:"M7 11v4a2 2 0 0 0 2 2h4",key:"xkn7yn"}],["rect",{width:"8",height:"8",x:"13",y:"13",rx:"2",key:"1cgmvn"}]],Ac=Ve("workflow",wv);/**
|
|
603
|
+
* @license lucide-react v1.7.0 - ISC
|
|
604
|
+
*
|
|
605
|
+
* This source code is licensed under the ISC license.
|
|
606
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
607
|
+
*/const Nv=[["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"}]],Vd=Ve("wrench",Nv);/**
|
|
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 Sv=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Kt=Ve("x",Sv);/**
|
|
613
|
+
* @license lucide-react v1.7.0 - ISC
|
|
614
|
+
*
|
|
615
|
+
* This source code is licensed under the ISC license.
|
|
616
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
617
|
+
*/const Cv=[["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"}]],Yn=Ve("zap",Cv),Rc="fusion:version-reload",Tc="fusion:version-update";function Ev(){try{if(sessionStorage.getItem(Tc))return sessionStorage.removeItem(Tc),!0}catch{}return!1}function fp(e){if(sessionStorage.getItem(Rc)){console.warn("[versionCheck] reload already attempted, suppressing",e);return}sessionStorage.setItem(Rc,"1"),console.info("[versionCheck] reloading:",e),window.location.reload()}function _v(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 Mv(e){return _v(e)?(fp(`chunk load error: ${e?.message??e}`),!0):!1}async function Av(){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 fl=!1;async function gl(){if(!(fl||document.visibilityState!=="visible")){fl=!0;try{const e=await Av();if(e&&e!=="mon8x2sx-75359cb6"){try{sessionStorage.setItem(Tc,"1")}catch{}fp(`build version changed: mon8x2sx-75359cb6 -> ${e}`)}}finally{fl=!1}}}function Rv(){window.setTimeout(()=>sessionStorage.removeItem(Rc),5e3),document.addEventListener("visibilitychange",()=>{gl()}),window.addEventListener("focus",()=>{gl()}),window.setTimeout(()=>void gl(),2e3)}class Jo 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),!Mv(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(ld,{size:40})}),t.jsx("div",{className:"error-boundary__title",children:i}),this.state.error&&t.jsx("pre",{className:"error-boundary__message",children:this.state.error.message}),t.jsxs("div",{className:"error-boundary__actions",children:[t.jsx("button",{className:"btn btn-primary",onClick:this.resetErrorBoundary,children:"Retry"}),t.jsx("button",{className:"btn",onClick:()=>window.location.reload(),children:"Reload page"})]})]})}}function is({children:e,onError:n}){return t.jsx(Jo,{level:"page",onError:n,children:e})}function Ii({children:e,onError:n}){return t.jsx(Jo,{level:"modal",onError:n,children:e})}function Tv({children:e,onError:n}){return t.jsx(Jo,{level:"root",onError:n,children:e})}const Pv="modulepreload",Iv=function(e){return"/"+e},Wd={},hn=function(n,s,i){let r=Promise.resolve();if(s&&s.length>0){let l=function(d){return Promise.all(d.map(m=>Promise.resolve(m).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),u=c?.nonce||c?.getAttribute("nonce");r=l(s.map(d=>{if(d=Iv(d),d in Wd)return;Wd[d]=!0;const m=d.endsWith(".css"),h=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${h}`))return;const f=document.createElement("link");if(f.rel=m?"stylesheet":Pv,m||(f.as="script"),f.crossOrigin="",f.href=d,u&&f.setAttribute("nonce",u),document.head.appendChild(f),m)return new Promise((p,g)=>{f.addEventListener("load",p),f.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return r.then(l=>{for(const c of l||[])c.status==="rejected"&&o(c.reason);return n().catch(o)})},cd="fn.authToken",Kd="token",$v="fn_token";let pa,Gd=!1,Mo=!1;const Pc="fn:auth-token-recovery-required";function Dv(){try{const e=window.localStorage.getItem(cd);return e&&e.length>0?e:void 0}catch{return}}function gp(e){try{window.localStorage.setItem(cd,e)}catch{}}function Lv(){if(!(Gd||typeof window>"u")){Gd=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(Kd);if(!n)return;gp(n),e.searchParams.delete(Kd);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function xa(){if(pa!==void 0)return pa;const e=Lv();if(e)return pa=e,e;const n=Dv();if(n)return pa=n,n}function zv(e){pa=e,Mo=!1,gp(e)}function Fv(){pa=void 0,Mo=!1;try{window.localStorage.removeItem(cd)}catch{}}function Jd(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function Ov(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function Uv(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!Ov(e.protocol))return!1;const s=e.hostname===n.hostname,i=e.port===n.port,r=Jd(e.protocol)===Jd(n.protocol);return s&&i&&r}function Bv(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 ri(e){const n=xa();if(!n||typeof window>"u")return e;const s=Bv(e);return!s||!Uv(s.parsed)?e:(s.parsed.searchParams.set($v,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function bi(e){const n=xa();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function Hv(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function qv(){typeof window>"u"||Mo||(Mo=!0,window.dispatchEvent(new CustomEvent(Pc)))}async function Vv(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();Hv(i)&&qv()}catch{}}function Wv(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,xa();const e=window.fetch.bind(window);window.fetch=function(s,i){const r=xa(),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=>(Vv(u),u))}}class Kv extends Error{status;details;constructor(n,s,i){super(n),this.name="ApiRequestError",this.status=s,this.details=i}}function Gv(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function ls(e){return`/api${e}`}async function I(e,n={}){const s=ls(e),i=xa(),r=(()=>{if(i){const f=new Headers(n.headers??{});return f.has("Content-Type")||f.set("Content-Type","application/json"),bi(f)}if(!n.headers)return{"Content-Type":"application/json"};const h=new Headers(n.headers);return h.has("Content-Type")||h.set("Content-Type","application/json"),Object.fromEntries(h.entries())})(),o=await fetch(s,{...n,headers:r});if(o.status===204){if(!o.ok)throw new Error(`Request failed for ${s}: ${o.status} ${o.statusText}`);return}const l=o.headers.get("content-type")??"",c=await o.text(),u=l.includes("application/json");if(l.includes("text/html")||Gv(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 Kv(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return m}function X4(){return I("/health")}function Z4(){return I("/updates/check")}function Jv(e,n,s,i,r){const o=new URLSearchParams;s&&o.set("projectId",s),i&&o.set("q",i),r&&o.set("includeArchived","1");const l=o.size>0?`?${o.toString()}`:"";return I(`/tasks${l}`)}async function jr(e,n){const i=ls(H(`/tasks/${e}`,n));for(let r=1;r<=2;r++){const o=await fetch(i,{headers:bi({"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 bp(e,n){const{title:s,description:i,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:u,modelPresetId:d,modelProvider:m,modelId:h,validatorModelProvider:f,validatorModelId:p,planningModelProvider:g,planningModelId:b,thinkingLevel:v,summarize:x,reviewLevel:y,executionMode:k,priority:S,source:_}=e;return I(H("/tasks",n),{method:"POST",body:JSON.stringify({title:s,description:i,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:u,modelPresetId:d,modelProvider:m,modelId:h,validatorModelProvider:f,validatorModelId:p,planningModelProvider:g,planningModelId:b,thinkingLevel:v,summarize:x,reviewLevel:y,executionMode:k,priority:S,source:_})})}function ii(e,n,s){return I(H(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Yv(e,n,s,i,r,o,l,c,u){return I(H("/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 Qv(e,n,s){return I(H(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n})})}function Xv(e,n,s){const i=new URLSearchParams,r=i.size>0?`?${i.toString()}`:"";return I(H(`/tasks/${e}${r}`,n),{method:"DELETE"})}function Zv(e,n){return I(H(`/tasks/${e}/merge`,n),{method:"POST"})}function ey(e,n){return I(H(`/tasks/${e}/retry`,n),{method:"POST"})}function ty(e,n){return I(H(`/tasks/${e}/reset`,n),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({confirm:!0})})}function ny(e,n){return I(H(`/tasks/${e}/duplicate`,n),{method:"POST"})}function xp(e,n){return I(H(`/tasks/${e}/pause`,n),{method:"POST"})}function sy(e,n){return I(H(`/tasks/${e}/unpause`,n),{method:"POST"})}function iy(e,n){return I(H(`/tasks/${e}/archive`,n),{method:"POST"})}function ay(e,n){return I(H(`/tasks/${e}/unarchive`,n),{method:"POST"})}function ry(e){return I(H("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function oy(e,n){return I(H(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function ly(e,n){return I(H(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function cy(e){return I(H("/config",e))}function Yo(e){return I(H("/settings",e))}function Qr(e,n){return I(H("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function dy(e){return I(H("/update-check",e))}function e$(e){return I(H("/remote/settings",e))}function t$(e,n){return I(H("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function n$(e){return I(H("/remote/status",e))}function s$(e){return I(H("/remote/install-cloudflared",e),{method:"POST"})}function i$(e){return I(H("/remote/tunnel/start",e),{method:"POST"})}function a$(e){return I(H("/remote/tunnel/stop",e),{method:"POST"})}function r$(e){return I(H("/remote/tunnel/kill-external",e),{method:"POST"})}function o$(e){return I(H("/remote/token/persistent/regenerate",e),{method:"POST"})}function l$(e,n){return I(H("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function vp(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 c$(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:i}=e,r=vp(null,s,i);return I(H(`/remote/url${r}`,n))}function d$(e="text",n={}){const{projectId:s,tokenType:i="persistent",ttlMs:r}=n,o=vp(e,i,r);return I(H(`/remote/qr${o}`,s))}function u$(e){return I(H("/memory",e))}function m$(e,n){return I(H("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function h$(e){return I(H("/memory/files",e))}function p$(e,n){const s=`path=${encodeURIComponent(e)}`;return I(H(`/memory/file?${s}`,n))}function f$(e,n,s){return I(H("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function g$(e,n){let s,i=n;if(n!==void 0)s=e;else if(typeof e=="string"&&e.trim().length>0){const r=e.trim();r.includes("/")||r.endsWith(".md")||r.startsWith(".")?s=r:i=r}return I(H("/memory/compact",i),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function b$(e){return I(H("/memory/dream",e),{method:"POST"})}function x$(e){return I(H("/memory/insights",e))}function v$(e,n){return I(H("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function y$(e){return I(H("/memory/extract",e),{method:"POST"})}function j$(e){return I(H("/memory/audit",e))}function k$(e){return I(H("/memory/stats",e))}function w$(e){return I(H("/memory/backend",e))}function N$(e){return I(H("/memory/install-qmd",e),{method:"POST"})}function S$(e,n){return I(H("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function Ji(){return I("/settings/global")}function gn(e){return I("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function C$(e){return I(H("/settings/scopes",e))}function E$(e){return I(H("/settings/pi-extensions",e))}function _$(e,n){return I(H("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function M$(e,n,s){return I(H("/settings/test-notification",s),{method:"POST",body:JSON.stringify({providerId:e,...n??{}})})}function A$(){return I("/pi-settings")}async function R$(e){return I("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function T$(e){return I("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function P$(e){return I(H("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function kr(e,n,s){const i=new FormData;i.append("file",n);const r=await fetch(ls(H(`/tasks/${e}/attachments`,s)),{method:"POST",headers:bi(),body:i}),o=await r.json();if(!r.ok)throw new Error(o.error||"Upload failed");return o}async function uy(e,n,s){return I(H(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function Yd(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=H(`/tasks/${e}/logs${r}`,n),l=await fetch(ls(o),{headers:bi()});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 my(e,n,s,i){return I(H(`/tasks/${e}/comments/${n}`,i),{method:"PATCH",body:JSON.stringify({text:s})})}function hy(e,n,s){return I(H(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function py(e,n){return I(H(`/tasks/${e}/documents`,n))}function fy(e,n,s){return I(H(`/tasks/${e}/documents/${n}/revisions`,s))}async function I$(e,n){const s=new URLSearchParams;e?.q&&s.set("q",e.q),e?.limit!==void 0&&s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset));const i=s.toString(),r=`/documents${i?`?${i}`:""}`;return I(H(r,n))}function $$(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const i=s.toString(),r=`/files/markdown-list${i?`?${i}`:""}`;return I(H(r,e))}function Qd(e,n,s,i,r){return I(H(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:i?.author,metadata:i?.metadata})})}function gy(e,n,s){return I(H(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function by(e,n,s){return I(H(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function xy(e,n,s){return I(H(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function vy(e,n){return I(H(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function yy(e,n,s){return I(H(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function fs(){return I("/models")}function jy(){return I("/usage")}function ky(){return I("/providers/claude-cli/status")}function wy(){return I("/providers/droid-cli/status")}async function D$(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return I(`/providers/hermes/status${n}`)}async function L$(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return(await I(`/providers/hermes/profiles${n}`)).profiles??[]}async function z$(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return I(`/providers/openclaw/status${n}`)}async function F$(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),I(`/providers/paperclip/status?${n.toString()}`)}async function O$(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),(await I(`/providers/paperclip/companies?${n.toString()}`)).companies??[]}async function U$(e){const n=new URLSearchParams({apiUrl:e.apiUrl,companyId:e.companyId});return e.apiKey&&n.set("apiKey",e.apiKey),(await I(`/providers/paperclip/agents?${n.toString()}`)).agents??[]}async function B$(e){return I("/providers/paperclip/cli-mint-key",{method:"POST",body:JSON.stringify(e)})}async function H$(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return I(`/providers/paperclip/cli-status${s?`?${s}`:""}`)}async function q$(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return(await I(`/providers/paperclip/cli-companies${s?`?${s}`:""}`)).companies??[]}async function V$(e){const n=new URLSearchParams({companyId:e.companyId});return e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath),(await I(`/providers/paperclip/cli-agents?${n.toString()}`)).agents??[]}async function W$(e={}){const n=new URLSearchParams;e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return I(`/providers/paperclip/cli-discovery${s?`?${s}`:""}`)}function Ny(e){return I("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function Sy(e){return I("/auth/droid-cli",{method:"POST",body:JSON.stringify({enabled:e})})}async function Cy(){const n=(await I("/custom-providers")).map(s=>({id:s.id,name:s.name,baseUrl:s.baseUrl,api:s.apiType==="anthropic-compatible"?"anthropic-messages":"openai-completions",apiKey:s.apiKey,models:(s.models??[]).map(i=>({id:i.id,name:i.name}))}));return Object.assign(n,{providers:n})}function Ey(e){return I("/custom-providers",{method:"POST",body:JSON.stringify(e)})}function K$(e,n){const s=n,i={...typeof s.name=="string"?{name:s.name}:{},...typeof s.baseUrl=="string"?{baseUrl:s.baseUrl}:{},...typeof s.apiKey=="string"?{apiKey:s.apiKey}:{},...Array.isArray(s.models)?{models:s.models.map(r=>({id:r.id,name:r.name??r.id}))}:{},...s.api?{apiType:s.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible"}:{},..."apiType"in n?{apiType:n.apiType}:{}};return I(`/custom-providers/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(i)})}function G$(e){return I(`/custom-providers/${encodeURIComponent(e)}`,{method:"DELETE"})}function _y(e){const n=e.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible";return Ey({name:e.name?.trim()||e.id,apiType:n,baseUrl:e.baseUrl,apiKey:e.apiKey,models:e.models?.map(s=>({id:s.id,name:s.name??s.id}))})}function wr(){return I("/auth/status")}function My(e){return I("/auth/login",{method:"POST",body:JSON.stringify({provider:e,origin:window.location.origin})})}function Ay(e){return I("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function Ry(e){return I("/auth/cancel",{method:"POST",body:JSON.stringify({provider:e})})}function Ty(e,n){return I("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function Py(e){return I("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function Iy(e,n,s,i){return I("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:i})})}function $y(e,n,s,i){return I(H("/github/issues/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function Dy(e,n,s){return I("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function Ly(e,n,s,i){return I(H("/github/pulls/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function zy(e){return I(H("/git/remotes",e))}function Fy(e){return I(H("/git/remotes/detailed",e))}function Oy(e,n,s){return I(H("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function Uy(e,n){return I(H(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function By(e,n,s){return I(H(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function Hy(e,n,s){return I(H(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function qy(e,n,s){return I(H(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function Vy(e,n){return I(H(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}async function Wy(e,n){return(await I(H("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:e})})).results}function Xr(e,n,s,i){return I(H("/terminal/sessions",i),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function Xd(e,n){return I(H(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Ky(e){return I(H("/terminal/sessions",e))}function Us(e){return I(H("/git/status",e))}function Gy(e,n){const s=e?`?limit=${e}`:"";return I(H(`/git/commits${s}`,n))}function Ao(e,n){return I(H(`/git/commits/${e}/diff`,n))}function Jy(e){return I(H("/git/commits/ahead",e))}function Yy(e,n,s,i){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return I(H(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,i))}function Ba(e){return I(H("/git/branches",e))}function Qy(e,n,s){const i=`?limit=${n}`;return I(H(`/git/branches/${encodeURIComponent(e)}/commits${i}`,s))}function Xy(e){return I(H("/git/worktrees",e))}function Zy(e,n,s){return I(H("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function ej(e,n){return I(H(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function Zd(e,n,s){const i=n?"?force=true":"";return I(H(`/git/branches/${encodeURIComponent(e)}${i}`,s),{method:"DELETE"})}function tj(e,n){return I(H("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function nj(e){return I(H("/git/pull",e),{method:"POST"})}function sj(e){return I(H("/git/push",e),{method:"POST"})}function Zr(e){return I(H("/git/stashes",e))}function ij(e,n){return I(H("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function aj(e,n,s){return I(H(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function rj(e,n){return I(H(`/git/stashes/${e}`,n),{method:"DELETE"})}function oj(e,n,s){const i=new URLSearchParams;return i.set("path",e),i.set("staged",String(n)),I(H(`/git/diff/file?${i.toString()}`,s))}function ia(e){return I(H("/git/changes",e))}function eu(e,n){return I(H("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function lj(e,n){return I(H("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function tu(e,n){return I(H("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function cj(e,n){return I(H("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function dj(e){return I(H("/workspaces",e))}function uj(e,n,s){const i=new URLSearchParams({workspace:e});return n&&i.set("path",n),s&&i.set("projectId",s),I(`/files?${i.toString()}`)}function mj(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),I(`/files/${encodeURIComponent(n)}?${i.toString()}`)}function hj(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),I(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function pj(e,n,s){const i=new URLSearchParams({q:e});return n&&i.set("workspace",n),s&&i.set("projectId",s),I(`/files/search?${i.toString()}`)}function fj(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),I(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function gj(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),I(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function bj(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),I(`/files/${encodeURIComponent(n)}/delete?${i.toString()}`,{method:"POST"})}function xj(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),I(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function yp(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${i.toString()}`}function vj(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${i.toString()}`}function yj(e,n,s){return I(H("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function jj(e,n,s,i){return I(H("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function kj(e,n,s){return I(H(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function wj(e,n,s){return I(H(`/planning/${encodeURIComponent(e)}/stop`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function jp(e,n,s){return I(H("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function J$(e,n,s,i){return I(H("/agents/onboarding/start-streaming",s),{method:"POST",body:JSON.stringify({intent:e,context:n,planningModelProvider:i?.planningModelProvider,planningModelId:i?.planningModelId})})}function Y$(e,n,s){return I(H("/agents/onboarding/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n})})}function Q$(e,n){return I(H("/agents/onboarding/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function Nj(e,n,s){return I(H("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Sj(e,n,s){return I(H("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Cj(e,n,s){return I(H("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const Ic=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(Ic))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function Ej(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function Aa(e,n,s={}){const i=s.maxReconnectAttempts??10;let r=null,o=!1,l=0,c=null,u=null,d=!1;const m=p=>{const g=p.lastEventId;if(!g)return!0;const b=Number.parseInt(g,10);return Number.isFinite(b)?u!==null&&b<=u?!1:(u=b,!0):!0},h=()=>{if(o)return;const p=Ej(e,u),g=new EventSource(ri(p));r=g,g.onopen=()=>{l=0,d=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},g.onmessage=b=>{const v=b;m(v)&&n.onMessage?.(v)};for(const[b,v]of Object.entries(n.events??{}))g.addEventListener(b,x=>{const y=x;m(y)&&v(y)});g.onerror=()=>{if(o||r!==g)return;if(g.readyState===EventSource.CONNECTING){d||(d=!0,s.onConnectionStateChange?.("reconnecting"));return}if(g.close(),l>=i){s.onFatalError?.("Connection lost");return}d=!0,s.onConnectionStateChange?.("reconnecting"),l+=1;const v=Math.min(1e3*2**(l-1),3e4);c=setTimeout(()=>{c=null,h()},v)}};h();const f={close:()=>{o=!0,c&&(clearTimeout(c),c=null),r?.close(),Ic.delete(f)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return Ic.add(f),f}function nu(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 _j(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 Mj(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((i,r)=>_j(i,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function Aj(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 su(e){return Array.isArray(e)?e.map(nu):(e.candidates??[]).map(nu)}async function Rj(e){try{const n=await I(H("/dev-server/candidates",e));return su(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await I(H("/dev-server/detect",e));return su(s)}throw n}}function dd(e){return I(H("/dev-server/status",e)).then(va)}async function X$(e={},n){const s=new URLSearchParams;typeof e.maxLines=="number"&&Number.isFinite(e.maxLines)&&s.set("maxLines",String(Math.max(1,Math.floor(e.maxLines)))),typeof e.offset=="number"&&Number.isFinite(e.offset)&&s.set("offset",String(Math.max(0,Math.floor(e.offset)))),typeof e.lastEventId=="number"&&Number.isFinite(e.lastEventId)&&s.set("lastEventId",String(Math.max(0,Math.floor(e.lastEventId))));const i=s.size>0?`?${s.toString()}`:"";try{const r=await I(H(`/dev-server/logs/history${i}`,n));return Mj(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await dd(n);return Aj(o.logs,e)}throw r}}function Tj(e,n){const s=e.cwd??e.packagePath??".",i=e.scriptName;return I(H("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:i,scriptId:i,cwd:s,packagePath:e.packagePath})}).then(va)}function Pj(e){return I(H("/dev-server/stop",e),{method:"POST"}).then(va)}function Ij(e){return I(H("/dev-server/restart",e),{method:"POST"}).then(va)}async function $j(e,n){const s=typeof e=="string"?{url:e}:e;try{const i=await I(H("/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 I(H("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return va(r)}throw i}}function Z$(e){return ls(H("/dev-server/logs/stream",e))}async function eD(e){try{return(await I(H("/devserver",e))).sessions??[]}catch{try{const n=await dd(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 tD(e,n){try{return await I(H(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await dd(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 nD(e,n){try{return await I(H(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await Tj({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 sD(e,n){try{return await I(H(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await Pj(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 iD(e,n){try{return await I(H(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await Ij(n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}}}async function aD(e,n,s){try{const i=await I(H(`/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 $j({url:n},s);return{url:i.previewUrl??i.manualUrl??null,source:"manual"}}}async function rD(e){try{return(await I(H("/devserver/detect",e))).candidates??[]}catch{try{return(await Rj(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function oD(e,n){return ls(H(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function $r(e,n,s=25e3){const i=setInterval(()=>{xw(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(i)}}}function Dj(e,n){return ls(H(`/planning/${encodeURIComponent(e)}/stream`,n))}function Lj(e,n){return ls(H(`/agents/onboarding/${encodeURIComponent(e)}/stream`,n))}function lD(e,n,s,i){const r=Lj(e,n),o=Aa(r,{events:{thinking:l=>{try{s.onThinking?.(JSON.parse(l.data))}catch{s.onThinking?.(l.data)}},question:l=>{try{s.onQuestion?.(JSON.parse(l.data))}catch{}},summary:l=>{try{s.onSummary?.(JSON.parse(l.data))}catch{}},error:l=>{try{const c=JSON.parse(l.data);s.onError?.(c.message||c)}catch{s.onError?.(l.data||"Stream error")}},complete:()=>{s.onComplete?.()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:l=>s.onError?.(l)});return{close:o.close,isConnected:o.isConnected}}function zj(e,n,s,i){const r=Dj(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Aa(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 Dr(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 Fj(e){return I(Dr("/routines",e))}function Oj(e,n){return I(Dr("/routines",n),{method:"POST",body:JSON.stringify(e)})}function iu(e,n,s){return I(Dr(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function Uj(e,n){await I(Dr(`/routines/${e}`,n),{method:"DELETE"})}function Bj(e,n){return I(Dr(`/routines/${e}/trigger`,n),{method:"POST"})}function au(e){const n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e.limit)),e?.since!==void 0&&n.set("since",e.since),e?.type!==void 0&&n.set("type",e.type),e?.projectId&&n.set("projectId",e.projectId);const s=n.size>0?`?${n.toString()}`:"";return I(`/activity${s}`)}function Hj(e){const n=H("/activity",e);return I(n,{method:"DELETE"})}function Qo(e){return I(H("/workflow-steps",e))}function ru(e,n){return I(H("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function qj(e,n,s){return I(H(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Vj(e,n){return I(H(`/workflow-steps/${e}`,n),{method:"DELETE"})}function ou(e,n){return I(H(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function Wj(e,n){return I(H(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function Kj(){return I("/workflow-step-templates")}function Gj(e,n){return I(H(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function Nr(e){return I(H("/scripts",e))}function Jj(e,n,s){return I(H("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function Yj(e,n){return I(H(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function kp(e,n,s){return(await I(H("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const eo={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 wp(e){if(!(e instanceof Error))return eo.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?eo.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?eo.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:eo.NETWORK}function Qj(e,n){return I(H("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function Xj(e,n,s){return I(H(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Zj(e,n){return ls(H(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function ek(e,n,s,i){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=Aa(Zj(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 tk(e,n,s,i){return I(H("/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 Np(e,n,s){return I(H("/subtasks/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function H(e,n){if(!n)return e;const s=e.includes("?")?"&":"?";return`${e}${s}projectId=${encodeURIComponent(n)}`}function nk(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 Xo(e,n){const{nodeId:s,localNodeId:i,...r}=n??{},o=nk(e,s,i);return I(o,r)}function Ra(e,n){const s=new URLSearchParams;e?.state&&s.set("state",e.state),e?.role&&s.set("role",e.role),e?.includeEphemeral===!0&&s.set("includeEphemeral","true"),n&&s.set("projectId",n);const i=s.size>0?`?${s.toString()}`:"";return I(`/agents${i}`)}function $c(e,n){return I(H(`/agents/${encodeURIComponent(e)}`,n))}function sk(e,n){return I(H("/agents",n),{method:"POST",body:JSON.stringify(e)})}function ik(e,n,s){return I(H(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function cD(e,n){return I(H(`/agents/${encodeURIComponent(e)}/upgrade-heartbeat-procedure`,n),{method:"POST"})}function dD(e,n,s){return I(H(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function uD(e,n,s){return I(H(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function mD(e,n,s){return I(H(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function hD(e,n){return I(H(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function pD(e,n,s){const i=`path=${encodeURIComponent(n)}`;return I(H(`/agents/${encodeURIComponent(e)}/memory/file?${i}`,s))}function fD(e,n,s,i){return I(H(`/agents/${encodeURIComponent(e)}/memory/file`,i),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function ak(e,n,s){return I(H(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function rk(e,n){return I(H(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function gD(e,n,s){const i=new URLSearchParams;i.set("limit",String(n)),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return I(`/agents/${encodeURIComponent(e)}/runs${r}`)}function bD(e,n,s){return I(H(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function xD(e,n,s){return I(H(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function vD(e,n,s){const i=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return I(H(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:i,triggerDetail:r})})}function yD(e,n){return I(H(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function ok(e){return I(H("/agents/stats",e))}function jD(e,n){return I(H(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function kD(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeEphemeral&&s.set("includeEphemeral","true");const i=s.toString();return I(`/agents/org-tree${i?`?${i}`:""}`)}function wD(e,n){return I(H(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function lu(e,n,s){return I(H(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function ND(e,n){return I(H(`/agents/${encodeURIComponent(e)}/tasks`,n))}function SD(){return I("/agents/companies")}function CD(e,n){return I(H("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function ED(e,n){return I(H("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function _D(e,n){return I(H(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function MD(e){return I(H("/backups",e))}function AD(e){return I(H("/backups",e),{method:"POST"})}function RD(e,n){const s=H("/settings/export",n),i=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return I(i)}function TD(e,n,s){return I(H("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}function cu(){return I("/projects/across-nodes")}function pr(e,n){I("/_perf/dashboard-load",{method:"POST",body:JSON.stringify({source:e,message:n})}).catch(()=>{})}function Ro(){return I("/nodes")}function lk(e){return I("/nodes",{method:"POST",body:JSON.stringify(e)})}function ck(e,n){return I(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function dk(e){return I(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function uk(e){const n=await I(`/nodes/${encodeURIComponent(e)}/health-check`,{method:"POST"});return{nodeId:n.nodeId??e,status:n.status,responseTimeMs:n.responseTimeMs,error:n.error,checkedAt:n.checkedAt??new Date().toISOString()}}function PD(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=xa();l&&o.set("fn_token",l);const c=o.toString(),u=`/browse-directory${c?`?${c}`:""}`;return I(u)}function mk(e){return I("/projects",{method:"POST",body:JSON.stringify(e)})}function Sp(e){return I(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function du(e){return I(`/projects/${encodeURIComponent(e)}/health`)}function hk(e){return I(H("/executor/stats",e))}function pk(e){return I(H("/system-stats",e))}function fk(e){return I(H("/kill-vitest",e),{method:"POST"})}function uu(e){const n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e.limit)),e?.since&&n.set("since",e.since),e?.projectId&&n.set("projectId",e.projectId),e?.type&&n.set("type",e.type);const s=n.size>0?`?${n.toString()}`:"";return I(`/activity-feed${s}`)}function gk(e){return I(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function bk(e){return I(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function ID(){return I("/global-concurrency")}function $D(e){return I("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function xk(e,n){return I(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function Cp(e,n,s){const i=new URLSearchParams;n&&i.set("worktree",n),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return I(`/tasks/${encodeURIComponent(e)}/diff${r}`)}function vk(e){return I(H("/missions",e))}function yk(e,n){return I(H("/missions",n),{method:"POST",body:JSON.stringify(e)})}function Ep(e,n){return I(H(`/missions/${encodeURIComponent(e)}`,n))}function jk(e,n,s){return I(H(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function kk(e,n){return I(H(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function wk(e,n,s){const i=new URLSearchParams;i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset));const r=i.size>0?`?${i.toString()}`:"";return I(H(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function Nk(e){return I(H("/missions/health",e))}function Sk(e,n,s){return I(H(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function Ck(e,n,s){return I(H(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Ek(e,n){return I(H(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function _k(e,n,s){return I(H(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function Mk(e,n,s){return I(H(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Ak(e,n){return I(H(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Rk(e,n){return I(H(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function Tk(e,n,s){return I(H(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function Pk(e,n,s){return I(H(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Ik(e,n){return I(H(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function $k(e,n,s){return I(H(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function Dk(e,n){return I(H(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function Lk(e,n,s,i){return I(H(`/missions/features/${encodeURIComponent(e)}/triage`,i),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s})})}function zk(e,n){return I(H(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST"})}function bl(e,n){return I(H(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function Fk(e,n,s){return I(H(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function Ok(e,n,s){return I(H(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Uk(e,n,s){return I(H(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function Bk(e,n,s){return I(H(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function Hk(e,n){return I(H(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function xl(e,n){return I(H(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function mu(e,n){return I(H(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function qk(e,n){return I(H(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function hu(e,n){return I(H(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function Vk(e,n,s){const i=new URLSearchParams;i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset));const r=i.size>0?`?${i.toString()}`:"";return I(H(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function Wk(e,n){return I(H(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function Kk(e,n){return I(H(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function Gk(e,n){return I(H(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function Jk(e,n){return I(H(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function Yk(e,n,s){return I(H(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function Qk(e,n,s){return I(H("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function Xk(e,n,s,i){return I(H("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Zk(e,n,s){return I(H(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function _p(e,n,s){return I(H("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function ew(e,n,s){return I(H("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function tw(e,n,s,i){const r=ls(H(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Aa(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 Lr(e,n,s){return H(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function zr(e,n,s){return H(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function nw(e,n){return I(Lr(e,"/start",n),{method:"POST"})}function sw(e,n,s,i){return I(Lr(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function iw(e,n,s,i){const r=ls(Lr(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Aa(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 aw(e,n,s){return I(Lr(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function rw(e,n){return I(Lr(e,"/skip",n),{method:"POST"})}function ow(e,n){return I(zr(e,"/start",n),{method:"POST"})}function lw(e,n,s,i){return I(zr(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function cw(e,n,s,i){const r=ls(zr(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Aa(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 dw(e,n,s){return I(zr(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function uw(e,n){return I(zr(e,"/skip",n),{method:"POST"})}async function mw(e,n){try{return await I(H(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function DD(e){return I(H("/roadmaps",e))}function LD(e,n){return I(H("/roadmaps",n),{method:"POST",body:JSON.stringify(e)})}function zD(e,n){return I(H(`/roadmaps/${encodeURIComponent(e)}`,n))}function FD(e,n,s){return I(H(`/roadmaps/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function OD(e,n){return I(H(`/roadmaps/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function UD(e,n,s){return I(H(`/roadmaps/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function BD(e,n,s){return I(H(`/roadmaps/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function HD(e,n){return I(H(`/roadmaps/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function qD(e,n,s){return I(H(`/roadmaps/milestones/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function VD(e,n,s){return I(H(`/roadmaps/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function WD(e,n){return I(H(`/roadmaps/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function KD(e,n,s){return I(H(`/roadmaps/${encodeURIComponent(e)}/milestones/reorder`,s),{method:"POST",body:JSON.stringify({orderedMilestoneIds:n})})}function GD(e,n,s){return I(H(`/roadmaps/milestones/${encodeURIComponent(e)}/features/reorder`,s),{method:"POST",body:JSON.stringify({orderedFeatureIds:n})})}function JD(e,n,s,i){return I(H(`/roadmaps/features/${encodeURIComponent(e)}/move`,i),{method:"POST",body:JSON.stringify({targetMilestoneId:n,targetIndex:s})})}function YD(e,n){return I(H(`/roadmaps/${encodeURIComponent(e)}/handoff`,n))}function QD(e,n,s,i){return I(H(`/roadmaps/${encodeURIComponent(e)}/suggestions/milestones`,i),{method:"POST",body:JSON.stringify({goalPrompt:n.trim(),...s!==void 0?{count:s}:{}})})}function XD(e,n,s){return I(H(`/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 ZD(e){return I(H("/todos",e))}function eL(e,n){const s={title:e};return I(H("/todos",n),{method:"POST",body:JSON.stringify(s)})}function tL(e,n,s){const i={title:n};return I(H(`/todos/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(i)})}function nL(e,n){return I(H(`/todos/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function sL(e,n,s){const i={text:n};return I(H(`/todos/${encodeURIComponent(e)}/items`,s),{method:"POST",body:JSON.stringify(i)})}function iL(e,n,s){const i=n;return I(H(`/todos/items/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(i)})}function aL(e,n){return I(H(`/todos/items/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function rL(e,n,s){return I(H(`/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 ud(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeCompleted&&s.set("includeCompleted","1"),n?.includeArchived&&s.set("includeArchived","1");const i=s.toString(),r=await fetch(ls(`/ai-sessions${i?`?${i}`:""}`),{headers:bi()});return r.ok?(await r.json()).sessions??[]:[]}async function hw(e){return I(`/ai-sessions/${encodeURIComponent(e)}/archive`,{method:"POST"})}async function pw(e){return I(`/ai-sessions/${encodeURIComponent(e)}/unarchive`,{method:"POST"})}async function fi(e){const n=await fetch(ls(`/ai-sessions/${encodeURIComponent(e)}`),{headers:bi()});return n.ok?n.json():null}async function fw(e,n){const s=await I(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function gw(e,n){return I(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function bw(e,n){return I(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function Mp(e){await fetch(ls(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:bi()})}function xw(e,n){return I(H(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function vw(e,n){const s=new URLSearchParams;s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),e?.unreadOnly&&s.set("unreadOnly","true"),e?.type&&s.set("type",e.type),n&&s.set("projectId",n);const i=s.size>0?`?${s.toString()}`:"";return I(`/messages/inbox${i}`)}function yw(e,n){const s=new URLSearchParams;s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),e?.type&&s.set("type",e.type),n&&s.set("projectId",n);const i=s.size>0?`?${s.toString()}`:"";return I(`/messages/outbox${i}`)}function Ap(e){return I(H("/messages/unread-count",e))}function jw(e,n){return I(H("/messages",n),{method:"POST",body:JSON.stringify(e)})}function kw(e,n){return I(H(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function ww(e){return I(H("/messages/read-all",e),{method:"POST"})}function Nw(e,n){return I(H(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Sw(e,n,s){const i=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return I(H(i,s))}function Cw(e,n){return I(H(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function oL(e,n,s){const i=new URLSearchParams;i.set("limit",String(n)),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return I(`/agents/${encodeURIComponent(e)}/reflections${r}`)}function lL(e,n){return I(H(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function cL(e,n,s){const i=new URLSearchParams;s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return I(`/agents/${encodeURIComponent(e)}/performance${r}`)}function dL(e,n,s){const i=new URLSearchParams;i.set("limit",String(n.limit)),n?.category&&i.set("category",n.category),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return I(`/agents/${encodeURIComponent(e)}/ratings${r}`)}function uL(e,n,s){return I(H(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function mL(e,n){return I(H(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function hL(e,n,s){return I(H(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function pL(e,n){return I(H(`/agents/${encodeURIComponent(e)}/budget`,n))}function fL(e,n){return I(H(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function gL(e){return I(H("/plugins",e))}async function bL(e,n){return I(H("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function xL(e,n){return I(H(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function vL(e,n){return I(H(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function yL(e,n){return I(H(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function jL(e,n){return I(H(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function kL(e,n,s){return I(H(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function wL(e,n){return I(H(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function Ew(e){return I(H("/plugins/ui-slots",e))}async function NL(e){return I(H("/plugins/runtimes",e))}async function SL(e){return(await I(H("/skills/discovered",e))).skills}async function CL(e,n,s){return I(H("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function EL(e,n,s){const i=new URLSearchParams;e&&i.set("q",e),i.set("limit",String(n));const r=i.size>0?`?${i.toString()}`:"";return I(H(`/skills/catalog${r}`,s))}async function _L(e,n){return(await I(H(`/skills/${encodeURIComponent(e)}/content`,n))).content}function ML(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const i=s.toString();return I(`/chat/sessions${i?`?${i}`:""}`)}async function _w(e,n){const s=e.agentId.trim();if(!s)throw new Error("agentId is required");const i=e.modelProvider?.trim(),r=e.modelId?.trim();if(i&&!r||!i&&r)throw new Error("Both modelProvider and modelId must be provided together, or neither should be provided");const o=new URLSearchParams;return o.set("lookup","resume"),o.set("agentId",s),n&&o.set("projectId",n),i&&r&&(o.set("modelProvider",i),o.set("modelId",r)),{session:(await I(`/chat/sessions?${o.toString()}`)).sessions[0]??null}}function Mw(e,n){return I(H("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function AL(e,n,s){return I(H(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function RL(e,n){return I(H(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function pu(e,n,s){const i=new URLSearchParams;n?.limit!==void 0&&i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset)),n?.before&&i.set("before",n.before);const r=i.toString();return I(H(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function Aw(e,n){return I(H(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function Rw(e,n,s,i,r,o){const l=ls(H(`/chat/sessions/${encodeURIComponent(e)}/messages`,r)),c=new AbortController;let u=!1;const d=(m,h)=>{if(!(!m||!h))switch(m){case"thinking":try{s.onThinking?.(JSON.parse(h))}catch{s.onThinking?.(h)}break;case"text":try{s.onText?.(JSON.parse(h))}catch{s.onText?.(h)}break;case"tool_start":try{s.onToolStart?.(JSON.parse(h))}catch{}break;case"tool_end":try{s.onToolEnd?.(JSON.parse(h))}catch{}break;case"done":try{s.onDone?.(JSON.parse(h))}catch{s.onDone?.({messageId:""})}break;case"error":try{const f=JSON.parse(h);s.onError?.(f.message||f)}catch{s.onError?.(h||"Stream error")}break}};return(async()=>{try{const m=Array.isArray(i)&&i.length>0,h=m?(()=>{const k=new FormData;return k.append("content",n),i.forEach(S=>k.append("attachments",S)),k})():JSON.stringify({content:n}),f=await fetch(l,{method:"POST",headers:m?bi():bi({"Content-Type":"application/json"}),body:h,signal:c.signal});if(!f.ok){const k=await f.text();let S=`Request failed: ${f.status}`;try{S=JSON.parse(k).error||S}catch{}s.onError?.(S);return}if(!f.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected");const p=f.body.getReader(),g=new TextDecoder;let b="",v="",x=[];const y=(k,S=!1)=>{b+=k;const _=b.split(`
|
|
618
|
+
`);b=_.pop()||"",S&&b.length>0&&(_.push(b),b="");for(const N of _){const A=N.endsWith("\r")?N.slice(0,-1):N;if(A.startsWith("event:"))v=A.slice(6).trim();else if(A.startsWith("data:")){const C=A.slice(5);x.push(C.startsWith(" ")?C.slice(1):C)}else if(A===""){const C=x.join(`
|
|
619
|
+
`);d(v,C),v="",x=[]}}if(S&&v&&x.length>0){const N=x.join(`
|
|
620
|
+
`);d(v,N),v="",x=[]}};for(;;){const{done:k,value:S}=await p.read();if(k){y(g.decode(),!0);break}y(g.decode(S,{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 TL(e={},n){const s=new URLSearchParams;e.category&&s.set("category",e.category),e.status&&s.set("status",e.status),e.runId&&s.set("runId",e.runId),e.limit!==void 0&&s.set("limit",String(e.limit)),e.offset!==void 0&&s.set("offset",String(e.offset));const i=s.size>0?`?${s.toString()}`:"";return I(H(`/insights${i}`,n))}function PL(e,n){return I(H(`/insights/${encodeURIComponent(e)}/dismiss`,n),{method:"POST"})}function IL(e="manual",n,s){return I(H("/insights/run",s),{method:"POST",body:JSON.stringify({trigger:e,inputMetadata:n})})}function $L(e){return I(H("/insights/runs",e))}function DL(e,n){return I(H(`/insights/${encodeURIComponent(e)}/create-task`,n),{method:"POST"})}function LL(e={},n){const s=new URLSearchParams;e.q&&s.set("q",e.q),e.status&&s.set("status",e.status),e.limit!==void 0&&s.set("limit",String(e.limit));const i=s.size>0?`?${s.toString()}`:"";return I(H(`/research/runs${i}`,n))}function zL(e,n){return I(H("/research/runs",n),{method:"POST",body:JSON.stringify(e)})}function FL(e,n){return I(H(`/research/runs/${encodeURIComponent(e)}`,n))}function OL(e,n){return I(H(`/research/runs/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function UL(e,n){return I(H(`/research/runs/${encodeURIComponent(e)}/retry`,n),{method:"POST"})}function BL(e,n,s){return I(H(`/research/runs/${encodeURIComponent(e)}/export?format=${encodeURIComponent(n)}`,s))}function HL(e,n,s){return I(H(`/research/runs/${encodeURIComponent(e)}/create-task`,s),{method:"POST",body:JSON.stringify(n)})}function qL(e,n,s){return I(H(`/research/runs/${encodeURIComponent(e)}/attach-task`,s),{method:"POST",body:JSON.stringify(n)})}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 Pw({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 Iw(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Vi({status:e,showLabel:n=!1,className:s,compact:i=!1}){const r=Iw(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 fu=new Map,$w=6e4;function Rp(e){const[n,s]=a.useState([]),[i,r]=a.useState(!0),[o,l]=a.useState(null),c=a.useRef(!1),u=a.useRef(!1),d=a.useCallback(m=>n.filter(h=>h.slot.slotId===m),[n]);return a.useEffect(()=>{const m=e??"default";let h=!1;async function f(){const p=fu.get(m);if(p&&Date.now()<p.expiresAt){if(h||u.current)return;s(p.slots),r(!1);return}!c.current&&r(!0),l(null);try{const b=await Ew(e);if(h||u.current)return;fu.set(m,{slots:b,expiresAt:Date.now()+$w}),s(b),c.current=!0}catch(b){if(h||u.current)return;l(b instanceof Error?b.message:"Failed to fetch UI slots"),c.current=!0}finally{!h&&!u.current&&r(!1)}}return f(),()=>{h=!0}},[e]),a.useEffect(()=>{c.current=!1,u.current=!1},[e]),a.useEffect(()=>()=>{u.current=!0},[]),a.useMemo(()=>({slots:n,getSlotsForId:d,loading:i,error:o}),[n,d,i,o])}function Zo({slotId:e,projectId:n}){const{getSlotsForId:s,loading:i,error:r}=Rp(n);if(i||r||!e)return null;const o=s(e);return o.length===0?null:t.jsx(Jo,{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 Dw(){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 Ta(){const[e,n]=a.useState(Dw);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 Pa(e){return e.replace(/\\/g,"/")}function md(e){return e.replace(/[\\/]+$/g,"")}function hd(e){const n=Pa(md(e));return n?n.split("/").filter(Boolean):[]}function pd(e){const n=Pa(md(e));if(!n)return e;const s=n.split("/").filter(Boolean);return s[s.length-1]||n}function Tp(e,n){const s=hd(e);return s.length===0?Pa(e):s.slice(-2).join("/")}function Lw(e){const n=Pa(md(e)),s=n.lastIndexOf("/");return s<0?"":n.slice(0,s+1)}function zw(e,n){return!e||e==="."?n:[...hd(e),n].join("/")}function Fw(e){const n=hd(e);return n.length===0?".":(n.pop(),n.length===0?".":n.join("/"))}function VL(e){const n=Pa(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 Pp={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function Ow({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(sn,{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=Pp[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:Tp(u.path)})]}),d&&t.jsx(qn,{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 gu({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 Uw({onOpenSettings:e,onOpenGitHubImport:n,onOpenPlanning:s,onResumePlanning:i,activePlanningSessionCount:r=0,onOpenUsage:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:u,mailboxUnreadCount:d=0,onOpenSchedules:m,onOpenGitManager:h,onOpenNodes:f,showNodesButton:p,onOpenWorkflowSteps:g,onOpenScripts:b,onRunScript:v,onToggleTerminal:x,onOpenFiles:y,filesOpen:k,globalPaused:S,enginePaused:_,onToggleGlobalPause:N,onToggleEnginePause:A,view:C="board",onChangeView:z,showSkillsTab:M,showAgentsTab:T,searchQuery:U="",onSearchChange:q,projects:D=[],currentProject:R,onSelectProject:F,onViewAllProjects:V,projectId:K,isElectron:ee=!1,mobileNavEnabled:E,availableNodes:$=[],currentNode:P,onSelectNode:w,isRemote:O=!1,experimentalFeatures:Z}){const Ne=Ta(),se=Ne==="mobile",we=se||Ne==="tablet",L=se&&E,[ne,Q]=a.useState(!1),[be,de]=a.useState(!1),[me,ie]=a.useState(!1),[xe,Re]=a.useState(!1),[Oe,nt]=a.useState(!1),[et,Ze]=a.useState(!1),[rt,He]=a.useState(!1),[Ge,oe]=a.useState(!1),[je,X]=a.useState(!1),[Ae,Te]=a.useState(!1),[pe,_e]=a.useState(!1),[Fe,it]=a.useState({}),[ve,ce]=a.useState(!1),[Ie,he]=a.useState(-1),[Me,Je]=a.useState(null),[$e,ft]=a.useState({}),[J,re]=a.useState(!1),ye=a.useRef(null),at=a.useRef(null),te=a.useRef(null),Ye=a.useRef(null),mt=a.useRef(null),ht=a.useRef(null),xt=a.useRef(!1),St=a.useRef(null),bt=a.useRef(null),Nt=a.useRef(null),Qt=a.useRef(null),Pt=a.useRef(null),Dt=a.useRef(null),Et=a.useRef(null),Xt=a.useRef(null),Lt=a.useRef(!1),Ft=a.useMemo(()=>$.filter(Se=>Se.type==="remote"),[$]),zt=Ft.length>0,Tt=a.useMemo(()=>Object.entries(Fe).sort(([Se],[ut])=>Se.localeCompare(ut)),[Fe]),Gt=Tt.length>0,Ot=Tt.length+(Gt?1:0),qt=a.useMemo(()=>Object.entries($e).sort(([Se],[ut])=>Se.localeCompare(ut)),[$e]),nn=a.useMemo(()=>!!(Z?.researchView||Z?.todoView||Z?.insights||Z?.roadmap||M||Z?.memoryView||Z?.devServerView||!L),[Z,M,L]),ge=a.useCallback(()=>{const Se=window.visualViewport;return Se&&Se.width>0&&Se.height>0?{width:Se.width,height:Se.height,offsetTop:Se.offsetTop,offsetLeft:Se.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),ze=a.useCallback(()=>{const Se=Et.current;if(!Se)return;const ut=Se.getBoundingClientRect(),Zt=Xt.current,{width:_n,height:Nn,offsetTop:zn,offsetLeft:ss}=ge(),Rn=16,ue=16,Ke=6,pt=Zt?.offsetWidth||Math.max(ut.width,260),$t=Math.min(pt,Math.max(_n-Rn*2,160)),Vt=Zt?.offsetHeight||280,dn=Math.min(Vt,Math.max(Nn-ue*2,160)),Vn=ut.top-zn,$n=ut.bottom-zn,Dn=ut.right-ss,en=Nn-$n,Ct=Vn,pn=en<dn&&Ct>en,W=Math.min(Math.max(Dn-$t,Rn),_n-Rn-$t)+ss,Le=pn?Math.max(ue+zn,Vn-dn-Ke+zn):Math.min($n+Ke+zn,Nn+zn-ue-dn);Je({top:Le,left:W,width:$t})},[ge]),dt=a.useCallback((Se,ut)=>{v?.(Se,ut),_e(!1),he(-1)},[v]),j=a.useCallback(()=>{b?.(),_e(!1),he(-1)},[b]),Y=a.useCallback(Se=>{switch(Se.key){case"ArrowDown":Se.preventDefault(),Ot>0&&he(ut=>ut<Ot-1?ut+1:0);break;case"ArrowUp":Se.preventDefault(),Ot>0&&he(ut=>ut>0?ut-1:Ot-1);break;case"Enter":if(Se.preventDefault(),Ie>=0)if(Ie<Tt.length){const[ut,Zt]=Tt[Ie];dt(ut,Zt)}else Gt&&Ie===Tt.length&&j();break;case"Home":Se.preventDefault(),Ot>0&&he(0);break;case"End":Se.preventDefault(),Ot>0&&he(Ot-1);break}},[j,dt,Ie,Tt,Gt,Ot]);a.useEffect(()=>{xt.current=Oe},[Oe]),a.useEffect(()=>{Lt.current=pe},[pe]),a.useEffect(()=>{if(!Oe||!we)return;let Se=!1;return re(!0),Nr(K).then(ut=>{Se||ft(ut)}).catch(()=>{Se||ft({})}).finally(()=>{Se||re(!1)}),()=>{Se=!0}},[Oe,we,K]),a.useEffect(()=>{if(!pe||we)return;let Se=!1;return ce(!0),Nr(K).then(ut=>{Se||it(ut)}).catch(()=>{Se||it({})}).finally(()=>{Se||ce(!1)}),()=>{Se=!0}},[pe,we,K]),a.useEffect(()=>{if(!pe)return;const Se=ut=>{Dt.current&&!Dt.current.contains(ut.target)&&_e(!1)};return document.addEventListener("mousedown",Se),()=>document.removeEventListener("mousedown",Se)},[pe]),a.useEffect(()=>{if(!pe)return;const Se=ut=>{ut.key==="Escape"&&(_e(!1),Et.current?.focus())};return document.addEventListener("keydown",Se),()=>document.removeEventListener("keydown",Se)},[pe]),a.useEffect(()=>{if(pe){he(-1);const Se=window.setTimeout(()=>Xt.current?.focus(),0);return()=>window.clearTimeout(Se)}Je(null)},[pe]),a.useEffect(()=>{if(!pe)return;const Se=requestAnimationFrame(()=>{ze()});return()=>cancelAnimationFrame(Se)},[pe,ve,Tt.length,Gt,ze]),a.useEffect(()=>{if(!pe)return;const Se=()=>ze();window.addEventListener("resize",Se),window.addEventListener("scroll",Se,!0);const ut=window.visualViewport;return ut&&(ut.addEventListener("resize",Se),ut.addEventListener("scroll",Se)),()=>{window.removeEventListener("resize",Se),window.removeEventListener("scroll",Se,!0),ut&&(ut.removeEventListener("resize",Se),ut.removeEventListener("scroll",Se))}},[pe,ze]),a.useEffect(()=>{we&&(_e(!1),he(-1))},[we]);const fe=ne||U.length>0,Pe=(be||U.length>0)&&!me,We=(C==="board"||C==="list")&&!se&&q&&!me&&U.length===0,gt=(C==="board"||C==="list")&&!se&&q;a.useEffect(()=>{U===""&&ie(!1)},[U]),a.useEffect(()=>{if(!xe)return;const Se=ut=>{at.current&&!at.current.contains(ut.target)&&ye.current&&!ye.current.contains(ut.target)&&Re(!1)};return document.addEventListener("mousedown",Se),()=>document.removeEventListener("mousedown",Se)},[xe]),a.useEffect(()=>{if(!je)return;const Se=ut=>{Ye.current&&!Ye.current.contains(ut.target)&&te.current&&!te.current.contains(ut.target)&&X(!1)};return document.addEventListener("mousedown",Se),()=>document.removeEventListener("mousedown",Se)},[je]),a.useEffect(()=>{if(!et)return;const Se=ut=>{St.current&&!St.current.contains(ut.target)&&Ze(!1)};return document.addEventListener("mousedown",Se),()=>document.removeEventListener("mousedown",Se)},[et]),a.useEffect(()=>{const Se=ut=>{if(ut.key==="Escape"){if(oe(!1),X(!1),xt.current){nt(!1);return}if(Lt.current){_e(!1),Et.current?.focus();return}Re(!1),Q(!1),Ze(!1),He(!1)}};return document.addEventListener("keydown",Se),()=>document.removeEventListener("keydown",Se)},[]),a.useEffect(()=>{if(!rt)return;const Se=ut=>{bt.current&&!bt.current.contains(ut.target)&&He(!1)};return document.addEventListener("mousedown",Se),()=>document.removeEventListener("mousedown",Se)},[rt]),a.useEffect(()=>{if(!Ae)return;const Se=ut=>{Pt.current&&!Pt.current.contains(ut.target)&&Te(!1)};return document.addEventListener("mousedown",Se),()=>document.removeEventListener("mousedown",Se)},[Ae]),a.useEffect(()=>{if(!Ae)return;const Se=ut=>{ut.key==="Escape"&&Te(!1)};return document.addEventListener("keydown",Se),()=>document.removeEventListener("keydown",Se)},[Ae]),a.useEffect(()=>{if(!Ge)return;const Se=ut=>{Nt.current&&!Nt.current.contains(ut.target)&&Qt.current&&!Qt.current.contains(ut.target)&&oe(!1)};return document.addEventListener("mousedown",Se),()=>document.removeEventListener("mousedown",Se)},[Ge]);const Mt=a.useCallback(()=>{Q(Se=>!Se)},[]),cn=a.useCallback(()=>{de(!0),ie(!1)},[]),bn=a.useCallback(()=>{de(!1),ie(!0),q&&q("")},[q]),rn=a.useCallback(()=>{Re(Se=>!Se)},[]),Jt=a.useCallback(Se=>{Se&&Se(),Re(!1),nt(!1)},[]),Sn=a.useCallback(()=>{Q(!1),q&&q("")},[q]);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"})]}),se&&D.length>=1&&F&&t.jsxs("div",{className:"mobile-project-switch",ref:bt,children:[t.jsx("button",{className:`mobile-project-switch-trigger${rt?" mobile-project-switch-trigger--open":""}`,onClick:()=>He(Se=>!Se),title:"Switch project","aria-label":"Switch project","aria-expanded":rt,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:t.jsx(sn,{size:14,className:`mobile-project-switch-chevron${rt?" mobile-project-switch-chevron--open":""}`})}),rt&&t.jsx("div",{className:"mobile-project-switch-dropdown",role:"listbox","aria-label":"Select project","data-testid":"mobile-project-switch-dropdown",children:D.map(Se=>{const ut=R?.id===Se.id,Zt=Pp[Se.status]?.color;return t.jsxs("button",{className:`mobile-project-switch-item${ut?" mobile-project-switch-item--current":""}`,onClick:()=>{F(Se),He(!1)},role:"option","aria-selected":ut,"data-testid":`mobile-project-switch-item-${Se.id}`,children:[t.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:Zt||"var(--text-muted)"}}),t.jsxs("div",{className:"mobile-project-switch-info",children:[t.jsx("span",{className:"mobile-project-switch-name",children:Se.name}),t.jsx("span",{className:"mobile-project-switch-path",children:Tp(Se.path)})]}),ut&&t.jsx(qn,{size:14,className:"mobile-project-switch-check"})]},Se.id)})})]}),!we&&D.length>=1&&V&&t.jsx(Ow,{projects:D,currentProject:R??null,onViewAll:V,onSelectProject:F}),zt&&t.jsxs("div",{className:`header-node-selector${se?" header-node-selector--mobile":""}`,ref:se?void 0:St,children:[t.jsx(Pw,{node:P??null,showDetails:!se}),!se&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:`btn-icon node-selector-trigger${et?" node-selector-trigger--open":""}`,onClick:()=>Ze(Se=>!Se),title:"Switch node","aria-label":"Switch node","aria-expanded":et,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:t.jsx(kn,{size:12,className:`node-selector-chevron${et?" node-selector-chevron--open":""}`})}),et&&t.jsxs("div",{className:"node-selector-dropdown",role:"listbox","aria-label":"Select node",children:[t.jsxs("button",{className:`node-selector-option${O?"":" node-selector-option--active"}`,onClick:()=>{w?.(null),Ze(!1)},role:"option","aria-selected":!O,"data-testid":"node-option-local",children:[t.jsx(Vi,{status:"online",compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:"Local"})]}),Ft.map(Se=>t.jsxs("button",{className:`node-selector-option${P?.id===Se.id?" node-selector-option--active":""}`,onClick:()=>{w?.(Se),Ze(!1)},role:"option","aria-selected":P?.id===Se.id,"data-testid":`node-option-${Se.id}`,children:[t.jsx(Vi,{status:Se.status,compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:Se.name}),t.jsx("span",{className:"node-selector-option-status",children:Se.status})]},Se.id))]})]})]})]}),t.jsxs("div",{className:"header-actions",children:[L&&z&&(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:()=>z("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:()=>z("list"),title:"List view","aria-label":"List view","aria-pressed":C==="list","data-testid":"mobile-view-toggle-list",children:t.jsx(Ec,{size:16})})]}),q&&se&&(L||C==="board"||C==="list")&&!fe&&t.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:Mt,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:t.jsx(wi,{size:16})}),We&&t.jsx("button",{className:"btn-icon",onClick:cn,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:t.jsx(wi,{size:16})}),se&&L&&o&&t.jsx("button",{className:"btn-icon",onClick:Se=>o(Se.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"mobile-header-usage-btn",children:t.jsx(Ds,{size:16})}),!L&&z&&t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${C==="board"?" active":""}`,onClick:()=>z("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:()=>z("list"),title:"List view","aria-label":"List view","aria-pressed":C==="list",children:t.jsx(Ec,{size:16})}),T&&t.jsx("button",{className:`view-toggle-btn${C==="agents"?" active":""}`,onClick:()=>z("agents"),title:"Agents view","aria-label":"Agents view","aria-pressed":C==="agents",children:t.jsx(Cn,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="missions"?" active":""}`,onClick:()=>z("missions"),title:"Missions view","aria-label":"Missions view","aria-pressed":C==="missions",children:t.jsx(ks,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="chat"?" active":""}`,onClick:()=>z("chat"),title:"Chat view","aria-label":"Chat view","aria-pressed":C==="chat",children:t.jsx(Ni,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="documents"?" active":""}`,onClick:()=>z("documents"),title:"Documents view","aria-label":"Documents view","aria-pressed":C==="documents",children:t.jsx(Bi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="mailbox"?" active":""}`,onClick:()=>z("mailbox"),title:"Mailbox view","aria-label":"Mailbox view","aria-pressed":C==="mailbox",children:t.jsx(ba,{size:16})}),nn&&t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:Qt,className:`view-toggle-btn${["research","skills","roadmaps","insights","memory","dev-server","devserver"].includes(C)||Z?.todoView&&C==="todos"?" active":""}`,onClick:()=>oe(Se=>!Se),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":Ge,"data-testid":"view-toggle-overflow-trigger",children:t.jsx(sn,{size:12})}),Ge&&t.jsxs("div",{ref:Nt,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[Z?.researchView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="research"?" active":""}`,onClick:()=>{z("research"),oe(!1)},role:"menuitem","data-testid":"view-overflow-research",children:[t.jsx(wi,{size:14}),t.jsx("span",{children:"Research"})]}),Z?.insights&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="insights"?" active":""}`,onClick:()=>{z("insights"),oe(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[t.jsx(os,{size:14}),t.jsx("span",{children:"Insights"})]}),Z?.roadmap&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="roadmaps"?" active":""}`,onClick:()=>{z("roadmaps"),oe(!1)},role:"menuitem","data-testid":"view-overflow-roadmaps",children:[t.jsx(_c,{size:14}),t.jsx("span",{children:"Roadmaps"})]}),M&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="skills"?" active":""}`,onClick:()=>{z("skills"),oe(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[t.jsx(Yn,{size:14}),t.jsx("span",{children:"Skills"})]}),Z?.memoryView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="memory"?" active":""}`,onClick:()=>{z("memory"),oe(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[t.jsx(Co,{size:14}),t.jsx("span",{children:"Memory"})]}),Z?.devServerView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="dev-server"||C==="devserver"?" active":""}`,onClick:()=>{z("devserver"),oe(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[t.jsx(vr,{size:14}),t.jsx("span",{children:"Dev Server"}),t.jsx("span",{className:"visually-hidden","data-testid":"view-toggle-dev-server"})]}),Z?.todoView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="todos"?" active":""}`,onClick:()=>{z("todos"),oe(!1)},role:"menuitem","data-testid":"view-overflow-todos",children:[t.jsx(hp,{size:14}),t.jsx("span",{children:"Todos"})]})]})]})]}),!we&&o&&t.jsx("button",{className:"btn-icon",onClick:Se=>o(Se.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"desktop-header-usage-btn",children:t.jsx(Ds,{size:16})}),!we&&c&&t.jsx("button",{className:"btn-icon",onClick:c,title:"System Stats","data-testid":"desktop-header-system-stats-btn",children:t.jsx(vr,{size:16})}),!we&&l&&t.jsx("button",{className:"btn-icon",onClick:l,title:"View Activity Log",children:t.jsx(xr,{size:16})}),!we&&!ee&&t.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:t.jsx(gu,{size:16})}),!we&&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(ai,{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})]}),!we&&t.jsxs("div",{className:"terminal-split-btn",ref:Dt,children:[t.jsx("button",{className:"btn-icon btn-icon--terminal terminal-split-btn__main",onClick:x,title:"Open Terminal","data-testid":"terminal-toggle-btn",children:t.jsx(pi,{size:16})}),b&&v&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"terminal-split-btn__divider"}),t.jsx("button",{ref:Et,className:`btn-icon terminal-split-btn__chevron${pe?" btn-icon--active":""}`,onClick:()=>_e(Se=>!Se),title:"Scripts","aria-haspopup":"listbox","aria-expanded":pe,"aria-label":"Quick scripts","data-testid":"scripts-btn",children:t.jsx(sn,{size:12,className:`quick-scripts-dropdown__trigger-chevron${pe?" rotate":""}`})}),pe&&t.jsx("div",{ref:Xt,tabIndex:-1,className:"quick-scripts-dropdown__menu",role:"listbox","aria-label":"Scripts",onKeyDown:Y,"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:ve?t.jsxs("div",{className:"quick-scripts-dropdown__loading","data-testid":"quick-scripts-loading",children:[t.jsx(lt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts..."})]}):Tt.length===0?t.jsxs("div",{className:"quick-scripts-dropdown__empty","data-testid":"quick-scripts-empty",children:[t.jsx("div",{className:"quick-scripts-dropdown__empty-icon",children:t.jsx(pi,{size:16})}),t.jsx("p",{children:"No scripts configured"}),t.jsx("button",{className:"quick-scripts-dropdown__empty-action btn",onClick:j,children:"Add your first script"})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-scripts-dropdown__list",children:Tt.map(([Se,ut],Zt)=>t.jsxs("button",{className:`quick-scripts-dropdown__item ${Ie===Zt?"highlighted":""}`,onClick:()=>dt(Se,ut),role:"option","aria-selected":Ie===Zt,"data-testid":`quick-script-item-${Se}`,children:[t.jsx(En,{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:Se}),t.jsx("span",{className:"quick-scripts-dropdown__item-command",title:ut,children:ut.length>50?`${ut.slice(0,50)}...`:ut})]})]},Se))}),t.jsx("div",{className:"quick-scripts-dropdown__footer",children:t.jsxs("button",{className:`quick-scripts-dropdown__manage ${Gt&&Ie===Tt.length?"highlighted":""}`,onClick:j,"data-testid":"quick-scripts-manage",children:[t.jsx(hr,{size:14}),t.jsx("span",{children:"Manage Scripts..."})]})})]})})]})]}),!we&&y&&t.jsx("button",{className:`btn-icon${k?" btn-icon--active":""}`,onClick:y,title:"Browse files","data-testid":"files-toggle-btn",children:t.jsx(Qn,{size:16})}),!we&&h&&t.jsx("button",{className:"btn-icon",onClick:h,title:"Git Manager","data-testid":"git-manager-btn",children:t.jsx(Ws,{size:16})}),!we&&g&&t.jsx("button",{className:"btn-icon",onClick:g,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:t.jsx(Ac,{size:16})}),!we&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{ref:te,className:"btn-icon",onClick:()=>X(Se=>!Se),title:"More actions","aria-label":"More actions","aria-expanded":je,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:t.jsx(Nc,{size:16})}),je&&t.jsxs("div",{ref:Ye,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[f&&p!==!1&&t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{f(),X(!1)},role:"menuitem","data-testid":"desktop-overflow-nodes-btn",children:[t.jsx(yr,{size:14}),t.jsx("span",{children:"Nodes"})]}),t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{Jt(m),X(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[t.jsx(Ci,{size:14}),t.jsx("span",{children:"Automation"})]})]})]}),t.jsxs("div",{className:"engine-control-split-btn",ref:Pt,children:[t.jsx("button",{className:`btn-icon engine-control-split-btn__main${S?" btn-icon--stopped":""}`,onClick:N,title:S?"Start AI engine":"Stop AI engine","data-testid":"engine-control-main-btn",children:S?t.jsx(En,{size:16}):t.jsx(Cs,{size:16})}),t.jsx("span",{className:"engine-control-split-btn__divider"}),t.jsx("button",{className:`btn-icon engine-control-split-btn__chevron${Ae?" btn-icon--active":""}`,onClick:()=>Te(Se=>!Se),title:"Engine options","aria-haspopup":"menu","aria-expanded":Ae,"data-testid":"engine-control-chevron-btn",children:t.jsx(sn,{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${_?" engine-control-split-btn__menu-item--active":""}`,onClick:()=>{A?.(),Te(!1)},role:"menuitem",title:_?"Resume scheduling":"Pause triage",disabled:!!S,"data-testid":"engine-control-pause-triage-btn",children:[_?t.jsx(En,{size:14}):t.jsx(qs,{size:14}),t.jsx("span",{children:_?"Resume scheduling":"Pause triage"})]})})]}),!we&&t.jsx("button",{className:"btn-icon",onClick:e,title:"Settings",children:t.jsx(hr,{size:16})}),t.jsx(Zo,{slotId:"header-action",projectId:K}),we&&!L&&t.jsx("button",{ref:ye,className:"btn-icon compact-overflow-trigger",onClick:rn,title:"More header actions","aria-label":"More header actions","aria-expanded":xe,"aria-haspopup":"menu",children:t.jsx(Nc,{size:16})}),we&&!L&&xe&&t.jsxs("div",{ref:at,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[D.length>=1&&V&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Jt(V),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[t.jsx(lp,{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(Qn,{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(ai,{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(Ws,{size:16}),t.jsx("span",{children:"Git Manager"})]}),f&&p!==!1&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Jt(f),role:"menuitem","data-testid":"overflow-nodes-btn",children:[t.jsx(yr,{size:16}),t.jsx("span",{children:"Nodes"})]}),!ee&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Jt(n),role:"menuitem",children:[t.jsx(gu,{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(x),role:"menuitem","data-testid":"overflow-terminal-primary-btn",children:[t.jsx(pi,{size:16}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{className:"mobile-overflow-split-toggle",onClick:()=>nt(Se=>!Se),role:"menuitem","aria-expanded":Oe,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:t.jsx(kn,{size:14,className:`mobile-overflow-chevron${Oe?" mobile-overflow-chevron--open":""}`})})]}),Oe&&t.jsx("div",{className:"mobile-overflow-submenu",role:"menu","aria-label":"Scripts submenu",children:J?t.jsxs("div",{className:"mobile-overflow-submenu-loading","data-testid":"overflow-scripts-loading",children:[t.jsx(lt,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):qt.length>0?t.jsxs(t.Fragment,{children:[qt.map(([Se,ut])=>t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{v&&v(Se,ut),Re(!1),nt(!1)},role:"menuitem","data-testid":`overflow-script-item-${Se}`,children:[t.jsx(En,{size:14}),t.jsx("span",{children:Se})]},Se)),b&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>Jt(b),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(Hs,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):b&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>Jt(b),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(Hs,{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(Ci,{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(xr,{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(ba,{size:16}),t.jsxs("span",{children:["Mailbox",d>0?` (${d})`:""]})]}),o&&t.jsxs("button",{className:"mobile-overflow-item",onClick:Se=>Jt(()=>o(Se.currentTarget.getBoundingClientRect())),role:"menuitem","data-testid":"overflow-usage-btn",children:[t.jsx(Ds,{size:16}),t.jsx("span",{children:"View Usage"})]}),g&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Jt(g),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[t.jsx(Ac,{size:16}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Jt(e),role:"menuitem",children:[t.jsx(hr,{size:16}),t.jsx("span",{children:"Settings"})]})]})]})]}),gt&&Pe&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{className:"header-search",children:[t.jsx(wi,{size:14,className:"header-search-icon"}),t.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:U,onChange:Se=>q(Se.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:bn,"aria-label":"Close search",children:t.jsx(Kt,{size:14})})]})}),q&&se&&fe&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{ref:mt,className:"header-search mobile-search-expanded",children:[t.jsx(wi,{size:14,className:"header-search-icon"}),t.jsx("input",{ref:ht,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:U,onChange:Se=>q(Se.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:Sn,"aria-label":"Close search",children:t.jsx(Kt,{size:14})})]})})]})}const Bw={themeMode:"dark",colorTheme:"default",dashboardFontScalePct:100,defaultProvider:void 0,defaultModelId:void 0,fallbackProvider:void 0,fallbackModelId:void 0,defaultThinkingLevel:void 0,ntfyEnabled:!1,ntfyTopic:void 0,ntfyBaseUrl:void 0,ntfyEvents:["in-review","merged","failed","awaiting-approval","awaiting-user-review","planning-awaiting-input","gridlock"],ntfyDashboardHost:void 0,webhookEnabled:!1,webhookUrl:void 0,webhookFormat:"generic",webhookEvents:[],notificationProviders:[],customProviders:[],defaultProjectId:void 0,setupComplete:void 0,favoriteProviders:void 0,favoriteModels:void 0,openrouterModelSync:!0,updateCheckEnabled:!0,updateCheckFrequency:"daily",showGitHubStarButton:!0,modelOnboardingComplete:void 0,useClaudeCli:void 0,useDroidCli:void 0,executionGlobalProvider:void 0,executionGlobalModelId:void 0,planningGlobalProvider:void 0,planningGlobalModelId:void 0,validatorGlobalProvider:void 0,validatorGlobalModelId:void 0,titleSummarizerGlobalProvider:void 0,titleSummarizerGlobalModelId:void 0,daemonToken:void 0,daemonPort:4040,daemonHost:"127.0.0.1",settingsSyncEnabled:!1,settingsSyncAuth:!1,settingsSyncInterval:9e5,settingsSyncConflictResolution:"last-write-wins",dashboardCurrentNodeId:void 0,dashboardCurrentProjectIdByNode:void 0,vitestAutoKillEnabled:!0,vitestKillThresholdPct:90,researchGlobalDefaults:{searchProvider:void 0,synthesisProvider:void 0,synthesisModelId:void 0,enabledSources:{webSearch:!0,pageFetch:!0,github:!1,localDocs:!0,llmSynthesis:!0},maxSourcesPerRun:20,defaultExportFormat:"markdown"},researchGlobalEnabled:!0,researchGlobalMaxConcurrentRuns:3,researchGlobalDefaultTimeout:3e5,researchGlobalMaxSourcesPerRun:20,researchGlobalMaxSynthesisRounds:2,researchWebSearchProvider:"none",researchSearxngUrl:void 0,researchBraveApiKey:void 0,researchGoogleSearchApiKey:void 0,researchGoogleSearchCx:void 0,researchTavilyApiKey:void 0,researchGitHubEnabled:!1,researchLocalDocsEnabled:!0,researchMaxSearchResults:10,researchFetchTimeoutMs:3e4,researchUserAgent:"FusionResearchBot/1.0",remoteAccess:{activeProvider:null,providers:{tailscale:{enabled:!1,hostname:"",targetPort:0,acceptRoutes:!1},cloudflare:{enabled:!1,quickTunnel:!0,tunnelName:"",tunnelToken:null,ingressUrl:""}},tokenStrategy:{persistent:{enabled:!0,token:null},shortLived:{enabled:!1,ttlMs:9e5,maxTtlMs:864e5}},lifecycle:{rememberLastRunning:!1,wasRunningOnShutdown:!1,lastRunningProvider:null}},experimentalFeatures:{}},Hw={globalPause:!1,globalPauseReason:void 0,enginePaused:!1,maxConcurrent:2,maxTriageConcurrent:2,globalMaxConcurrent:4,maxWorktrees:4,pollIntervalMs:15e3,heartbeatMultiplier:1,groupOverlappingFiles:!0,overlapIgnorePaths:[],autoMerge:!0,mergeStrategy:"direct",requirePrApproval:!1,pushAfterMerge:!1,pushRemote:"origin",unavailableNodePolicy:"block",defaultNodeId:void 0,worktreeInitCommand:void 0,testCommand:void 0,buildCommand:void 0,recycleWorktrees:!1,worktreeNaming:"random",taskPrefix:"FN",includeTaskIdInCommit:!0,commitAuthorEnabled:!0,commitAuthorName:"Fusion",commitAuthorEmail:"noreply@runfusion.ai",planningProvider:void 0,planningModelId:void 0,planningFallbackProvider:void 0,planningFallbackModelId:void 0,defaultProviderOverride:void 0,defaultModelIdOverride:void 0,executionProvider:void 0,executionModelId:void 0,validatorProvider:void 0,validatorModelId:void 0,validatorFallbackProvider:void 0,validatorFallbackModelId:void 0,modelPresets:[],autoSelectModelPreset:!1,defaultPresetBySize:{},autoResolveConflicts:!0,smartConflictResolution:!0,worktreeRebaseBeforeMerge:!0,worktreeRebaseRemote:"",worktreeRebaseLocalBase:!0,mergeConflictStrategy:"smart-prefer-main",workflowStepTimeoutMs:36e4,strictScopeEnforcement:!1,buildRetryCount:0,verificationFixRetries:3,buildTimeoutMs:3e5,requirePlanApproval:!1,specStalenessEnabled:!1,specStalenessMaxAgeMs:360*60*1e3,taskStuckTimeoutMs:void 0,aiSessionTtlMs:10080*60*1e3,aiSessionCleanupIntervalMs:3600*1e3,autoUnpauseEnabled:!0,autoUnpauseBaseDelayMs:3e5,autoUnpauseMaxDelayMs:36e5,maxStuckKills:6,maxPostReviewFixes:1,maxSpawnedAgentsPerParent:5,maxSpawnedAgentsGlobal:20,maintenanceIntervalMs:9e5,autoArchiveDoneTasksEnabled:!0,autoArchiveDoneAfterMs:2880*60*1e3,archiveAgentLogMode:"compact",autoUpdatePrStatus:!1,githubCommentOnDone:!1,githubCommentTemplate:void 0,autoBackupEnabled:!1,autoBackupSchedule:"0 2 * * *",autoBackupRetention:7,autoBackupDir:".fusion/backups",autoSummarizeTitles:!1,useAiMergeCommitSummary:!0,titleSummarizerProvider:void 0,titleSummarizerModelId:void 0,titleSummarizerFallbackProvider:void 0,titleSummarizerFallbackModelId:void 0,scripts:void 0,setupScript:void 0,insightExtractionEnabled:!1,insightExtractionSchedule:"0 2 * * *",insightExtractionMinIntervalMs:864e5,memoryEnabled:!0,memoryBackendType:"qmd",memoryAutoSummarizeEnabled:!1,memoryAutoSummarizeThresholdChars:5e4,memoryAutoSummarizeSchedule:"0 3 * * *",memoryDreamsEnabled:!1,memoryDreamsSchedule:"0 4 * * *",tokenCap:void 0,runStepsInNewSessions:!1,maxParallelSteps:2,missionStaleThresholdMs:6e5,missionMaxTaskRetries:3,missionHealthCheckIntervalMs:3e5,agentPrompts:void 0,promptOverrides:void 0,reflectionEnabled:!1,reflectionIntervalMs:36e5,reflectionAfterTask:!0,reviewHandoffPolicy:"disabled",showQuickChatFAB:!1,researchSettings:{enabled:!0,searchProvider:void 0,synthesisProvider:void 0,synthesisModelId:void 0,enabledSources:{webSearch:!0,pageFetch:!0,github:!1,localDocs:!0,llmSynthesis:!0},limits:{maxConcurrentRuns:3,maxSourcesPerRun:20,maxDurationMs:3e5,requestTimeoutMs:3e4}},researchEnabled:!0,researchMaxConcurrentRuns:3,researchDefaultTimeout:3e5,researchMaxSourcesPerRun:20,researchMaxSynthesisRounds:2},qw=Object.freeze(Object.keys(Bw)),Vw=Object.freeze(Object.keys(Hw));function WL(e){return qw.includes(e)}function KL(e){return Vw.includes(e)}function ke(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Ww(e){return!!(e?.provider&&e?.modelId)}function Ei(...e){for(const n of e)if(Ww(n))return{provider:n.provider,modelId:n.modelId};return{}}function el(e){return Ei({provider:e?.defaultProviderOverride,modelId:e?.defaultModelIdOverride},{provider:e?.defaultProvider,modelId:e?.defaultModelId})}function Kw(e){return Ei({provider:e?.executionProvider,modelId:e?.executionModelId},{provider:e?.executionGlobalProvider,modelId:e?.executionGlobalModelId},el(e))}function Gw(e){return Ei({provider:e?.planningProvider,modelId:e?.planningModelId},{provider:e?.planningGlobalProvider,modelId:e?.planningGlobalModelId},el(e))}function Jw(e){return Ei({provider:e?.validatorProvider,modelId:e?.validatorModelId},{provider:e?.validatorGlobalProvider,modelId:e?.validatorGlobalModelId},el(e))}function GL(e){return Ei({provider:e?.titleSummarizerProvider,modelId:e?.titleSummarizerModelId},{provider:e?.titleSummarizerGlobalProvider,modelId:e?.titleSummarizerGlobalModelId},{provider:e?.planningProvider,modelId:e?.planningModelId},el(e))}function Ip(e,n){return Ei({provider:e.modelProvider,modelId:e.modelId},Kw(n))}function $p(e,n){return Ei({provider:e.validatorModelProvider,modelId:e.validatorModelId},Jw(n))}function Dp(e,n){return Ei({provider:e.planningModelProvider,modelId:e.planningModelId},Gw(n))}const JL=["off","minimal","low","medium","high"],Oi=["triage","todo","in-progress","in-review","done","archived"],fd=["low","normal","high","urgent"],_s="normal",Yw=["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"],Bn={triage:"Planning",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},Qw={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"},Dc={triage:["todo"],todo:["in-progress","triage"],"in-progress":["in-review","todo","triage","done"],"in-review":["done","in-progress","todo","triage"],done:["todo","triage","archived"],archived:["done"]};function Xw(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 Zw(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 eN({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 Lp=a.createContext(null);function tN({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 So.createElement(Lp.Provider,{value:u},e,So.createElement(eN,{isOpen:c!==null,options:c?.options??null,onConfirm:()=>l(!0),onCancel:()=>l(!1)}))}function Ks(){const e=a.useContext(Lp);return e||{confirm:async n=>!1}}function nN(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 zp({prInfo:e,issueInfo:n,onIssueRefresh:s}){const i=()=>{e?.url&&window.open(e.url,"_blank","noopener,noreferrer")},r=()=>{n?.url&&window.open(n.url,"_blank","noopener,noreferrer")};return t.jsxs(t.Fragment,{children:[e&&t.jsxs("span",{className:`card-github-badge card-github-badge--${e.status}`,title:`PR #${e.number}: ${e.title}`,onClick:i,children:[t.jsx(Es,{size:12}),t.jsxs("span",{children:["#",e.number]})]}),n&&t.jsxs("span",{className:`card-github-badge ${nN(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,onClick:r,children:[t.jsx(qo,{size:12}),t.jsxs("span",{children:["#",n.number]})]})]})}function to(e,n){return`${e??"default"}:${n}`}class sN{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=to(this.projectId,o);this.subscriptionsByTask.set(l,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const i=to(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=to(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(ri(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=to(this.projectId,l.taskId),u=this.badgeUpdates.get(c);this.badgeUpdates.set(c,{prInfo:bu(l,"prInfo")?l.prInfo??null:u?.prInfo,issueInfo:bu(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 sN;let iN=0;function bu(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function Fp(e){const n=a.useRef(null);n.current===null&&(n.current=`badge-hook-${iN++}`);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 To(e,n,s,i){return e===void 0||!n?s:!i||n>=i?e??void 0:s}function aN({taskId:e,prInfo:n,issueInfo:s,updatedAt:i,isInViewport:r,projectId:o}){const{badgeUpdates:l,subscribeToBadge:c,unsubscribeFromBadge:u}=Fp(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=To(m?.prInfo,m?.timestamp,n,n?.lastCheckedAt??i),f=To(m?.issueInfo,m?.timestamp,s,s?.lastCheckedAt??i);return!h&&!f?null:t.jsx(zp,{prInfo:h,issueInfo:f})}const rN=a.memo(aN);rN.displayName="TaskCardBadge";const oN={sm:16,md:20,lg:24};function lN({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 xu({size:e,color:n,label:s="OpenAI"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"openai-icon","aria-label":s,children:t.jsx("path",{d:"M22.282 9.821a6 6 0 0 0-.516-4.91a6.05 6.05 0 0 0-6.51-2.9A6.065 6.065 0 0 0 4.981 4.18a6 6 0 0 0-3.998 2.9a6.05 6.05 0 0 0 .743 7.097a5.98 5.98 0 0 0 .51 4.911a6.05 6.05 0 0 0 6.515 2.9A6 6 0 0 0 13.26 24a6.06 6.06 0 0 0 5.772-4.206a6 6 0 0 0 3.997-2.9a6.06 6.06 0 0 0-.747-7.073M13.26 22.43a4.48 4.48 0 0 1-2.876-1.04l.141-.081l4.779-2.758a.8.8 0 0 0 .392-.681v-6.737l2.02 1.168a.07.07 0 0 1 .038.052v5.583a4.504 4.504 0 0 1-4.494 4.494M3.6 18.304a4.47 4.47 0 0 1-.535-3.014l.142.085l4.783 2.759a.77.77 0 0 0 .78 0l5.843-3.369v2.332a.08.08 0 0 1-.033.062L9.74 19.95a4.5 4.5 0 0 1-6.14-1.646M2.34 7.896a4.5 4.5 0 0 1 2.366-1.973V11.6a.77.77 0 0 0 .388.677l5.815 3.354l-2.02 1.168a.08.08 0 0 1-.071 0l-4.83-2.786A4.504 4.504 0 0 1 2.34 7.872zm16.597 3.855l-5.833-3.387L15.119 7.2a.08.08 0 0 1 .071 0l4.83 2.791a4.494 4.494 0 0 1-.676 8.105v-5.678a.79.79 0 0 0-.407-.667m2.01-3.023l-.141-.085l-4.774-2.782a.78.78 0 0 0-.785 0L9.409 9.23V6.897a.07.07 0 0 1 .028-.061l4.83-2.787a4.5 4.5 0 0 1 6.68 4.66zm-12.64 4.135l-2.02-1.164a.08.08 0 0 1-.038-.057V6.075a4.5 4.5 0 0 1 7.375-3.453l-.142.08L8.704 5.46a.8.8 0 0 0-.393.681zm1.097-2.365l2.602-1.5l2.607 1.5v2.999l-2.597 1.5l-2.607-1.5Z",fill:n})})}function Zs({size:e,color:n,label:s="Google Gemini"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"gemini-icon","aria-label":s,children:t.jsx("path",{d:"M11.04 19.32Q12 21.51 12 24q0-2.49.93-4.68.96-2.19 2.58-3.81t3.81-2.55Q21.51 12 24 12q-2.49 0-4.68-.93a12.3 12.3 0 0 1-3.81-2.58 12.3 12.3 0 0 1-2.58-3.81Q12 2.49 12 0q0 2.49-.96 4.68-.93 2.19-2.55 3.81a12.3 12.3 0 0 1-3.81 2.58Q2.49 12 0 12q2.49 0 4.68.96 2.19.93 3.81 2.55t2.55 3.81",fill:n})})}function cN({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 vu({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 dN({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 vl({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 yu({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 ju({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 ku({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 Ha({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 wu({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 yl({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 Nu({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 jl({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 uN({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 mN({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 Su({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 kl({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 hN({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 Cu({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 wl({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 Eu({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 Nl({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 _u({size:e,color:n,label:s="Anthropic — via Claude CLI"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"claude-cli-icon","aria-label":s,children:[t.jsx("g",{transform:"translate(-1 -1.5) scale(0.82)",children:t.jsx("path",{d:"M17.3041 3.541h-3.6718l6.696 16.918H24Zm-10.6082 0L0 20.459h3.7442l1.3693-3.5527h7.0052l1.3693 3.5528h3.7442L10.5363 3.5409Zm-.3712 10.2232 2.2914-5.9456 2.2914 5.9456Z",fill:n})}),t.jsx("rect",{x:"13",y:"13",width:"10",height:"9",rx:"1.5",fill:n}),t.jsx("path",{d:"M15.2 16.2l1.6 1.4-1.6 1.4M18.6 19.6h2.4",stroke:"var(--provider-icon-contrast)",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})]})}function pN({size:e,color:n,label:s="Factory AI — via Droid CLI"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"droid-cli-icon","aria-label":s,children:[t.jsx("rect",{x:"2",y:"3",width:"14",height:"14",rx:"3",fill:n}),t.jsx("path",{d:"M6.5 7.5h2.6a2.9 2.9 0 1 1 0 5.8H6.5zM9 7.5v5.8",stroke:"var(--provider-icon-contrast)",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round"}),t.jsx("rect",{x:"13",y:"13",width:"10",height:"9",rx:"1.5",fill:n}),t.jsx("path",{d:"M15.2 16.2l1.6 1.4-1.6 1.4M18.6 19.6h2.4",stroke:"var(--provider-icon-contrast)",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})]})}const fN={anthropic:{component:lN,color:"var(--provider-anthropic)"},"claude-cli":{component:_u,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"pi-claude-cli":{component:_u,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"droid-cli":{component:pN,color:"var(--provider-openai)",label:"Factory AI — via Droid CLI"},openai:{component:xu,color:"var(--provider-openai)"},"openai-codex":{component:xu,color:"var(--provider-openai)",label:"OpenAI Codex"},google:{component:Zs,color:"var(--provider-gemini)"},gemini:{component:Zs,color:"var(--provider-gemini)"},"google-antigravity":{component:Zs,color:"var(--provider-gemini)",label:"Google Gemini"},antigravity:{component:Zs,color:"var(--provider-gemini)",label:"Google Gemini"},"google-vertex":{component:Zs,color:"var(--provider-gemini)",label:"Google Vertex AI"},vertex:{component:Zs,color:"var(--provider-gemini)",label:"Google Vertex AI"},"google-cloud-code":{component:Zs,color:"var(--provider-gemini)",label:"Google Cloud Code"},"cloud-code":{component:Zs,color:"var(--provider-gemini)",label:"Google Cloud Code"},"google-gemini-cli":{component:Zs,color:"var(--provider-gemini)",label:"Google Gemini CLI"},"google-generative-ai":{component:Zs,color:"var(--provider-gemini)",label:"Google Generative AI"},ollama:{component:cN,color:"var(--text)"},github:{component:Cu,color:"var(--text)"},"github-copilot":{component:Cu,color:"var(--text)",label:"GitHub Copilot"},openrouter:{component:hN,color:"var(--provider-openrouter)"},minimax:{component:vu,color:"var(--provider-minimax)"},"minimax-cn":{component:vu,color:"var(--provider-minimax)",label:"MiniMax (CN)"},zai:{component:dN,color:"var(--provider-zai)"},kimi:{component:vl,color:"var(--provider-kimi)"},moonshot:{component:vl,color:"var(--provider-kimi)"},"kimi-coding":{component:vl,color:"var(--provider-kimi)",label:"Kimi"},bedrock:{component:yu,color:"var(--provider-bedrock)"},"amazon-bedrock":{component:yu,color:"var(--provider-bedrock)",label:"Amazon Bedrock"},xai:{component:ju,color:"var(--text)"},grok:{component:ju,color:"var(--text)",label:"xAI"},opencode:{component:ku,color:"var(--provider-opencode)"},"opencode-go":{component:ku,color:"var(--provider-opencode)",label:"Opencode (Go)"},qwen:{component:Ha,color:"var(--provider-qwen)"},"qwen-ai":{component:Ha,color:"var(--provider-qwen)",label:"Qwen"},"qwen-coder":{component:Ha,color:"var(--provider-qwen)",label:"Qwen Coder"},alibaba:{component:Ha,color:"var(--provider-qwen)",label:"Qwen"},tongyi:{component:Ha,color:"var(--provider-qwen)",label:"Qwen"},lmstudio:{component:wu,color:"var(--provider-lmstudio)",label:"LM Studio"},"lm-studio":{component:wu,color:"var(--provider-lmstudio)",label:"LM Studio"},huggingface:{component:yl,color:"var(--provider-huggingface)",label:"Hugging Face"},"hugging-face":{component:yl,color:"var(--provider-huggingface)",label:"Hugging Face"},hf:{component:yl,color:"var(--provider-huggingface)",label:"Hugging Face"},mistral:{component:Nu,color:"var(--provider-mistral)",label:"Mistral AI"},"mistral-ai":{component:Nu,color:"var(--provider-mistral)",label:"Mistral AI"},azure:{component:jl,color:"var(--provider-azure)"},"azure-openai":{component:jl,color:"var(--provider-azure)",label:"Azure OpenAI"},"azure-openai-responses":{component:jl,color:"var(--provider-azure)",label:"Azure OpenAI"},fireworks:{component:kl,color:"var(--provider-fireworks)",label:"Fireworks AI"},"fireworks-ai":{component:kl,color:"var(--provider-fireworks)",label:"Fireworks AI"},fireworksai:{component:kl,color:"var(--provider-fireworks)",label:"Fireworks AI"},cerebras:{component:uN,color:"var(--provider-cerebras)"},groq:{component:mN,color:"var(--provider-groq)"},vercel:{component:Su,color:"var(--provider-vercel)"},"vercel-ai-gateway":{component:Su,color:"var(--provider-vercel)",label:"Vercel AI Gateway"},hermes:{component:wl,color:"var(--provider-hermes)",label:"Hermes"},"hermes-agent":{component:wl,color:"var(--provider-hermes)",label:"Hermes"},hermesagent:{component:wl,color:"var(--provider-hermes)",label:"Hermes"},openclaw:{component:Eu,color:"var(--provider-openclaw)",label:"OpenClaw"},"open-claw":{component:Eu,color:"var(--provider-openclaw)",label:"OpenClaw"},paperclip:{component:Nl,color:"var(--provider-paperclip)",label:"Paperclip"},paperclipai:{component:Nl,color:"var(--provider-paperclip)",label:"Paperclip"},"paperclip-ai":{component:Nl,color:"var(--provider-paperclip)",label:"Paperclip"}};function An({provider:e,size:n="sm"}){const s=e.toLowerCase(),i=fN[s],r=i?.component,o=i?.color??"var(--text-muted)",l=i?.label,c=oN[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(Mb,{size:c})})}const Ps={data:new Map,pendingPromise:null,lastFetchTime:null},gN=5e3;function jo(e,n){return n?`${n}::${e}`:e}function bN(e,n){const s=Ps.data.get(jo(e,n));if(!(!s||Date.now()-s.timestamp>gN))return s}function xN(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 Wy(c,e)}catch(h){d=h instanceof Error?h:new Error(String(h));const f=ke(h);if(f?.includes("429")||f?.toLowerCase().includes("rate limit")){const p=Math.min(1e3*Math.pow(2,m),3e4);await new Promise(g=>setTimeout(g,p));continue}break}if(d)throw d;return{}},[e]),o=a.useCallback(async c=>{if(c.length===0)return;const d=Date.now()-5e3;if(c.every(f=>{const p=Ps.data.get(jo(f,e));return p&&p.timestamp>d})&&Ps.lastFetchTime&&Ps.lastFetchTime>d)return;if(i.current&&(clearTimeout(i.current),i.current=null),Ps.pendingPromise){s(!0);try{await Ps.pendingPromise}finally{s(!1)}return}s(!0);const h=r(c);Ps.pendingPromise=h;try{const f=await h,p=Date.now();for(const[g,b]of Object.entries(f))Ps.data.set(jo(g,e),{result:b,timestamp:p});Ps.lastFetchTime=p}catch{}finally{Ps.pendingPromise=null,s(!1)}},[r,e]),l=a.useCallback(c=>Ps.data.get(jo(c,e)),[e]);return{fetchBatch:o,isLoading:n,lastFetchTime:Ps.lastFetchTime,getBatchData:l}}const Lc=new Map,vN=3e4;function Op(e,n,s,i){return`${e}:${n??""}:${s??""}:${i??""}`}function yN(e,n,s,i){const r=Op(e,n,s,i),o=Lc.get(r);return o?Date.now()>o.expiresAt?(Lc.delete(r),null):o.stats:null}function jN(e,n,s,i,r){const o=Op(e,n,s,i);Lc.set(o,{stats:r,expiresAt:Date.now()+vN})}function kN(e,n,s,i,r={}){const o=r.enabled??!0,l=r.worktree,c=r.stepVersion,u=r.pollIntervalMs,[d,m]=a.useState(null),[h,f]=a.useState(!1);return a.useEffect(()=>{if(!o){m(null),f(!1);return}const p=n==="done"&&!!s,g=(n==="in-progress"||n==="in-review")&&!!l;if(!e||!p&&!g){m(null),f(!1);return}const b=g?l:void 0,v=c!==void 0?String(c):void 0;let x=!1;async function y(S=!1){if(!S){const _=yN(e,i,b,v);if(_){x||(m(_),f(!1));return}}f(!0);try{const _=await Cp(e,b,i);x||(m(_.stats),jN(e,i,b,v,_.stats))}catch{x||m(null)}finally{x||f(!1)}}y();let k;return u&&g&&(k=setInterval(()=>{y(!0)},u)),()=>{x=!0,k&&clearInterval(k)}},[e,n,s,i,o,l,c,u]),{stats:d,loading:h}}const wN=new Set(["failed","stuck-killed"]);function Po(e,n,s){if(e.column!=="in-progress"||e.status&&wN.has(e.status)||!n||n<=0)return!1;const i=new Date(e.updatedAt).getTime();return(s??Date.now())-i>n}function NN(e){switch(e){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function SN(e){return e==="done"||e==="skipped"}function CN(e,n,s){const i=s?.get(e)?.trim();if(i)return i;const r=n?.workflowStepName?.trim();return r||e}function Up(e,n){const s=(e.steps??[]).map((u,d)=>({id:`step-${d}`,name:u.name,status:u.status,source:"step",phase:"pre-merge"})),i=new Map((e.workflowStepResults??[]).map(u=>[u.workflowStepId,u])),r=(e.enabledWorkflowSteps??[]).map(u=>{const d=i.get(u);return{id:`workflow-${u}`,name:CN(u,d,n),status:d?NN(d.status):"pending",source:"workflow",phase:d?.phase??"pre-merge"}}),o=[...s,...r],l=o.length,c=o.filter(u=>SN(u.status)).length;return{total:l,completed:c,items:o}}function EN(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 Bp(e){return e.filter(n=>{const s=typeof n.action=="string"?n.action:"",i=typeof n.outcome=="string"?n.outcome:"";return s.includes("[timing]")||i.includes("[timing]")}).map(n=>{const i=`${n.action??""}
|
|
621
|
+
${n.outcome??""}`.match(/(\d+(?:\.\d+)?)ms\b/i),r=i?Number(i[1]):void 0;return{timestamp:n.timestamp,durationMs:Number.isFinite(r)?r:void 0,summary:EN(n)}})}function _N(e){if(!e||e.length===0)return null;let n=0,s=0;for(const i of Bp(e))typeof i.durationMs=="number"&&(n+=i.durationMs,s+=1);return s>0?n:null}const zc=new Map;async function MN(e,n){const s=zc.get(e);if(s)return s;try{const i=await Ep(e,n);return zc.set(e,i.title),i.title}catch{return e}}const Mu=12;function AN(e){return e.length<=Mu?e:e.slice(0,Mu-3)+"..."}const Fc=new Map;async function RN(e,n){const s=Fc.get(e);if(s)return s;try{const i=await $c(e,n);return Fc.set(e,i.name),i.name}catch{return e}}function TN(e){return typeof e=="string"&&fd.includes(e)?e:_s}function PN(e,n){return e.length<=n?e:e.slice(0,n-3)+"..."}const IN=new Set(["triage","todo"]),Au=new Set(["planning","researching","executing","finalizing","merging"]),Ru=new Set(["merging","merging-pr"]),$N={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"},DN=new Set(["in-progress","in-review","done"]),LN=3e4;function Wi(e){if(!e)return null;const n=Date.parse(e);return Number.isFinite(n)?n:null}function zN(e){const n=Wi(e.columnMovedAt??e.updatedAt);if(n==null)return null;const s=Date.now();return n>s?null:n}function Tu(e,n){const s=Wi(e.columnMovedAt??e.updatedAt);return s==null?null:Math.max(0,n-s)}function lr(e,n){const s=Wi(e.executionStartedAt);if(s==null)return null;const i=Wi(e.executionCompletedAt),r=i!=null&&i>=s?i:n;return Math.max(0,r-s)}function FN(e){return e.column==="done"?zN(e):null}function Hp(e,n){const s=Wi(e.updatedAt);return s==null?null:Math.max(0,n-s)}function ON(e,n){const s=lr(e,n);if(s!=null)return s;const i=Hp(e,n),r=cr(e,n);return r!=null?r+(i??0):i}function UN(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=Wi(o.startedAt);if(l==null)continue;let c;if(o.completedAt){const u=Wi(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 cr(e,n){const s=typeof e.timedExecutionMs=="number"?e.timedExecutionMs:_N(e.log),i=UN(e,n);return s==null&&i==null?null:(s??0)+(i??0)}function Pu(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 Iu(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 $u(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 BN(e,n){return e.length!==n.length?!1:e.every((s,i)=>s.name===n[i]?.name&&s.status===n[i]?.status)}function HN(e,n){return e.length!==n.length?!1:e.every((s,i)=>s===n[i])}function qN(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>s===n[i])}function VN(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 WN(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 KN(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 JN(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&&KN(s.attachments,i.attachments)&&GN(s.comments,i.comments)&&HN(s.dependencies,i.dependencies)&&BN(s.steps,i.steps)&&qN(s.enabledWorkflowSteps,i.enabledWorkflowSteps)&&WN(s.workflowStepResults,i.workflowStepResults)&&$u(s.prInfo,i.prInfo)&&$u(s.issueInfo,i.issueInfo)}function YN({task:e,projectId:n,queued:s,onOpenDetail:i,addToast:r,globalPaused:o,onUpdateTask:l,onArchiveTask:c,onUnarchiveTask:u,onDeleteTask:d,onRetryTask:m,onOpenDetailWithTab:h,taskStuckTimeoutMs:f,onOpenMission:p,onMoveTask:g,lastFetchTimeMs:b,workflowStepNameLookup:v}){const[x,y]=a.useState(!1),[k,S]=a.useState(!1),[_,N]=a.useState(!1),[A,C]=a.useState(e.description||""),[z,M]=a.useState(!1),[T,U]=a.useState(e.column==="in-progress"||e.column==="triage"&&e.steps.some(j=>j.status==="done"||j.status==="skipped")),[q,D]=a.useState(null),[R,F]=a.useState(null),[V,K]=a.useState(!1),[ee,E]=a.useState(!1),[$,P]=a.useState(()=>Date.now()),w=a.useRef(null),O=a.useRef(!1),Z=a.useRef(null),Ne=a.useRef(null),[se,le]=a.useState(!1),{badgeUpdates:we,subscribeToBadge:L,unsubscribeFromBadge:ne}=Fp(n),{confirm:Q}=Ks(),be=a.useRef(null),de=a.useRef(!1),me=a.useCallback(j=>j instanceof Element?!!j.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);a.useEffect(()=>{C(e.description||"")},[e.id,e.description]),a.useEffect(()=>{if(!V)return;const j=Y=>{Ne.current&&!Ne.current.contains(Y.target)&&K(!1)};return document.addEventListener("click",j),()=>document.removeEventListener("click",j)},[V]),a.useEffect(()=>{if(!e.missionId){D(null);return}const j=zc.get(e.missionId);if(j){D(j);return}let Y=!1;return MN(e.missionId,n).then(fe=>{Y||D(fe)}),()=>{Y=!0}},[e.missionId,n]),a.useEffect(()=>{if(!e.assignedAgentId){F(null);return}const j=Fc.get(e.assignedAgentId);if(j){F(j);return}F(null);let Y=!1;return RN(e.assignedAgentId,n).then(fe=>{Y||F(fe)}),()=>{Y=!0}},[e.assignedAgentId,n]),a.useEffect(()=>{if(_&&w.current){const j=w.current;j.focus(),j.style.height="auto",j.style.height=j.scrollHeight+"px"}},[_]),a.useEffect(()=>{if(typeof IntersectionObserver>"u"){le(!0);return}const j=Z.current;if(!j)return;const Y=new IntersectionObserver(([fe])=>{le(fe?.isIntersecting??!0)},{rootMargin:"200px"});return Y.observe(j),()=>Y.disconnect()},[_,e.id]);const ie=a.useCallback(j=>{j.dataTransfer.setData("text/plain",e.id),j.dataTransfer.effectAllowed="move",y(!0)},[e.id]),xe=a.useCallback(()=>{y(!1)},[]),Re=a.useCallback(j=>j.dataTransfer.types.includes("Files"),[]),Oe=a.useCallback(j=>{Re(j)&&(j.preventDefault(),j.stopPropagation(),j.dataTransfer.dropEffect="copy",S(!0))},[Re]),nt=a.useCallback(j=>{Re(j)&&(j.preventDefault(),j.stopPropagation(),S(!1))},[Re]),et=a.useCallback(async j=>{if(!Re(j))return;j.preventDefault(),j.stopPropagation(),S(!1);const Y=Array.from(j.dataTransfer.files);for(const fe of Y)try{await kr(e.id,fe,n),r(`Attached ${fe.name} to ${e.id}`,"success")}catch(Pe){r(`Failed to attach ${fe.name}: ${ke(Pe)}`,"error")}},[e.id,Re,r]),Ze=a.useCallback(()=>{_||i(e)},[e,i,_]),rt=a.useCallback(j=>{if(O.current){O.current=!1;return}me(j.target)||Ze()},[Ze,me]),He=a.useCallback(j=>{const Y=j.touches[0];Y&&(be.current={x:Y.clientX,y:Y.clientY,time:Date.now()},de.current=!1)},[]),Ge=a.useCallback(j=>{if(!be.current)return;const Y=j.touches[0];if(!Y)return;const fe=Math.abs(Y.clientX-be.current.x),Pe=Math.abs(Y.clientY-be.current.y);(fe>Du||Pe>Du)&&(de.current=!0)},[]),oe=a.useCallback(j=>{if(me(j.target)||!be.current)return;const fe=Date.now()-be.current.time<QN,Pe=!de.current;fe&&Pe&&(O.current=!0,Ze()),be.current=null,de.current=!1},[Ze,me]),je=a.useCallback(async(j,Y)=>{j.stopPropagation();try{const fe=await jr(Y,n);i(fe)}catch{r(`Failed to load dependency ${Y}`,"error")}},[i,r]),X=e.status==="failed",Ae=e.paused===!0,Te=TN(e.priority),pe=Te!==_s,_e=Po(e,f,b),Fe=e.column==="triage"&&e.status==="awaiting-approval",it=e.column==="archived",ve=!o&&!s&&!X&&!Ae&&!_e&&!Fe&&(e.column==="in-progress"||Au.has(e.status)),ce=!s&&!Ae&&!_&&!it,Ie=IN.has(e.column)&&!ve&&!Ae&&!s&&l,he=!!(e.prInfo||e.issueInfo),Me=!!(e.assignedAgentId&&R===null),Je=a.useMemo(()=>{const j=[];return e.modelProvider&&j.push(e.modelProvider),e.validatorModelProvider&&!j.includes(e.validatorModelProvider)&&j.push(e.validatorModelProvider),e.planningModelProvider&&!j.includes(e.planningModelProvider)&&j.push(e.planningModelProvider),j},[e.modelProvider,e.validatorModelProvider,e.planningModelProvider]),$e=a.useMemo(()=>Up(e,v),[e.steps,e.enabledWorkflowSteps,e.workflowStepResults,v]),ft=$e.total>0&&(e.status==="executing"||e.column==="in-progress");a.useEffect(()=>{if(e.column!=="in-progress"&&e.column!=="in-review")return;const j=e.status!=null&&Ru.has(e.status);if(e.column==="in-progress"){const fe=lr(e,Date.now()),Pe=Tu(e,Date.now()),We=cr(e,Date.now());if(fe==null&&Pe==null&&We==null)return}if(!j&&e.column==="in-review"){const fe=lr(e,Date.now()),Pe=cr(e,Date.now());if(fe==null&&Pe==null)return}P(Date.now());const Y=window.setInterval(()=>{P(Date.now())},LN);return()=>window.clearInterval(Y)},[e.column,e.status,e.columnMovedAt,e.updatedAt,e.workflowStepResults,e.timedExecutionMs,e.executionStartedAt,e.executionCompletedAt]);const J=a.useMemo(()=>{if(!DN.has(e.column))return null;if(e.status!=null&&Ru.has(e.status)){const gt=ON(e,$);if(gt!=null){const Mt=Iu(gt);if(Mt){const cn=Hp(e,$),bn=cn==null?null:Pu(cn),rn=bn?`Execution time ${Mt}. Merge phase ${bn}`:`Execution time ${Mt}. Merging`;return{label:Mt,title:rn,ariaLabel:rn}}}}if(e.column==="in-progress"){const gt=lr(e,$)??Tu(e,$)??cr(e,$);if(gt==null)return null;const Mt=Pu(gt);return Mt?{label:Mt,title:`In progress ${Mt}`,ariaLabel:`In progress ${Mt}`}:null}const Y=lr(e,$)??cr(e,$);if(Y==null)return null;const fe=Iu(Y);if(!fe)return null;const Pe=FN(e);if(Pe==null)return{label:fe,title:`Execution time ${fe}`,ariaLabel:`Execution time ${fe}`};const We=new Date(Pe).toLocaleString();return{label:fe,title:`Execution time ${fe}. Completed ${We}`,ariaLabel:`Execution time ${fe}. Completed ${We}`}},[e.column,e.status,e.columnMovedAt,e.timedExecutionMs,e.updatedAt,e.workflowStepResults,e.log,e.executionStartedAt,e.executionCompletedAt,$]);a.useEffect(()=>{if(!he||!se){ne(e.id);return}return L(e.id),()=>{ne(e.id)}},[he,se,L,e.id,ne]);const re=we.get(`${n??"default"}:${e.id}`),ye=e.column==="in-progress"||e.column==="in-review",at=a.useMemo(()=>e.steps.map(j=>`${j.name}:${j.status}`).join("|"),[e.steps]),{stats:te}=kN(e.id,e.column,e.mergeDetails?.commitSha,n,{enabled:se,worktree:e.worktree,stepVersion:ye?at:void 0,pollIntervalMs:ye?3e4:void 0}),Ye=a.useMemo(()=>bN(e.id,n),[e.id,n]),mt=a.useMemo(()=>{const j=re?.prInfo,Y=re?.timestamp,fe=Ye?.result?.prInfo,Pe=Ye?.timestamp?new Date(Ye.timestamp).toISOString():void 0,We=e.prInfo,gt=e.prInfo?.lastCheckedAt??e.updatedAt;let Mt=To(j,Y,We,gt);const cn=Y&&Y>=gt?Y:gt;return fe&&Pe&&(!cn||Pe>cn)&&(Mt=fe),Mt},[re,Ye,e.prInfo,e.updatedAt]),ht=a.useMemo(()=>{const j=re?.issueInfo,Y=re?.timestamp,fe=Ye?.result?.issueInfo,Pe=Ye?.timestamp?new Date(Ye.timestamp).toISOString():void 0,We=e.issueInfo,gt=e.issueInfo?.lastCheckedAt??e.updatedAt;let Mt=To(j,Y,We,gt);const cn=Y&&Y>=gt?Y:gt;return fe&&Pe&&(!cn||Pe>cn)&&(Mt=fe),Mt},[re,Ye,e.issueInfo,e.updatedAt]),xt=a.useCallback(j=>{j?.stopPropagation(),!(!Ie||z)&&(N(!0),C(e.description||""))},[Ie,z,e.description]),St=a.useCallback(()=>{N(!1),C(e.description||"")},[e.description]),bt=a.useCallback(()=>A!==(e.description||""),[A,e.description]),Nt=a.useCallback(async()=>{if(!(!l||z)){if(!bt()){St();return}M(!0);try{await l(e.id,{description:A.trim()||void 0}),r(`Updated ${e.id}`,"success"),N(!1)}catch(j){r(`Failed to update ${e.id}: ${ke(j)}`,"error")}finally{M(!1)}}},[l,e.id,A,z,bt,St,r]),Qt=a.useCallback(j=>{j.key==="Enter"&&!j.shiftKey?(j.preventDefault(),Nt()):j.key==="Escape"&&(j.preventDefault(),St())},[Nt,St]),Pt=a.useCallback(()=>{setTimeout(()=>{const j=document.activeElement;j===w.current||j?.closest(".card-editing-content")||(bt()?Nt():St())},0)},[bt,Nt,St]),Dt=a.useCallback(j=>{Ie&&(j.stopPropagation(),xt(j))},[Ie,xt]),Et=a.useCallback(j=>{j.stopPropagation(),xt(j)},[xt]),Xt=a.useCallback(j=>{C(j.target.value);const Y=j.target;Y.style.height="auto",Y.style.height=Y.scrollHeight+"px"},[]),Lt=a.useCallback(j=>{j.stopPropagation(),c&&c(e.id).then(()=>{r(`Archived ${e.id}`,"success")}).catch(Y=>{r(`Failed to archive ${e.id}: ${ke(Y)}`,"error")})},[r,c,e.id]),Ft=a.useCallback(j=>{j.stopPropagation(),u&&u(e.id).then(()=>{r(`Unarchived ${e.id}`,"success")}).catch(Y=>{r(`Failed to unarchive ${e.id}: ${ke(Y)}`,"error")})},[r,u,e.id]),zt=a.useCallback(async j=>{if(j.stopPropagation(),!(!d||!await Q({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0})))try{await d(e.id),r(`Deleted ${e.id}`,"success")}catch(fe){const Pe=VN(fe);if(!Pe||Pe.dependentIds.length===0){r(`Failed to delete ${e.id}: ${ke(fe)}`,"error");return}const We=Pe.dependentIds.join(", ");if(!await Q({title:"Force Delete Task",message:`${e.id} is a dependency of ${We}.
|
|
622
|
+
|
|
623
|
+
Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await d(e.id,{removeDependencyReferences:!0}),r(`Deleted ${e.id} after removing dependency references`,"success")}catch(Mt){r(`Failed to delete ${e.id}: ${ke(Mt)}`,"error")}}},[r,Q,d,e.id]),Tt=a.useCallback(j=>{j.stopPropagation(),h?.(e,"changes")},[e,h]),Gt=a.useCallback(j=>{j.stopPropagation(),U(Y=>!Y)},[]),Ot=a.useCallback(j=>{j.stopPropagation(),e.missionId&&p&&p(e.missionId)},[e.missionId,p]),qt=a.useCallback(j=>{j.stopPropagation(),K(Y=>!Y)},[]),nn=a.useCallback((j,Y)=>{j.stopPropagation(),K(!1),g&&g(e.id,Y).then(()=>{r(`Moved ${e.id} to ${Bn[Y]}`,"success")}).catch(fe=>{r(`Failed to move ${e.id}: ${ke(fe)}`,"error")})},[r,g,e.id]),ge=a.useCallback(async j=>{if(j.stopPropagation(),!(!m||ee)){E(!0);try{await m(e.id)}catch(Y){r(`Failed to retry ${e.id}: ${ke(Y)}`,"error")}finally{E(!1)}}},[r,ee,m,e.id]),ze=`card${x?" dragging":""}${s?" queued":""}${ve?" agent-active":""}${X?" failed":""}${Ae?" paused":""}${_e?" stuck":""}${Fe?" awaiting-approval":""}${k?" file-drop-target":""}${_?" card-editing":""}${z?" card-saving":""}`,dt=(()=>{if(e.column==="in-progress"){const j=te?.filesChanged,Y=j==null||j===0?e.modifiedFiles?.length:void 0,fe=j!=null&&j>0?j:Y;return fe==null||fe===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:Tt,disabled:!h,children:[t.jsx(Qn,{size:12}),t.jsxs("span",{children:[fe," ",fe===1?"file":"files"," changed"]})]})}if(e.column==="in-review"){const j=te?.filesChanged,Y=j==null||j===0?e.modifiedFiles?.length:void 0,fe=j!=null&&j>0?j:Y;return fe==null||fe===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:Tt,disabled:!h,children:[t.jsx(Qn,{size:12}),t.jsxs("span",{children:[fe," ",fe===1?"file":"files"," changed"]})]})}if(e.column==="done"){const j=te?.filesChanged,Y=e.mergeDetails?.filesChanged,fe=j??Y;if(fe!=null&&fe>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:Tt,disabled:!h,children:[t.jsx(Qn,{size:12}),t.jsxs("span",{children:[fe," ",fe===1?"file":"files"," changed"]})]});const Pe=e.modifiedFiles?.length;if(Pe!=null&&Pe>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:Tt,disabled:!h,children:[t.jsx(Qn,{size:12}),t.jsxs("span",{children:[Pe," ",Pe===1?"file":"files"," changed"]})]})}return null})();return _?t.jsx("div",{ref:Z,className:ze,"data-id":e.id,onDoubleClick:Dt,children:t.jsxs("div",{className:"card-editing-content",children:[t.jsx("textarea",{ref:w,className:"card-edit-desc-textarea",placeholder:"Task description",value:A,onChange:Xt,onKeyDown:Qt,onBlur:Pt,disabled:z,rows:4}),z&&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:Z,className:ze,"data-id":e.id,draggable:ce,onDragStart:ce?ie:void 0,onDragEnd:ce?xe:void 0,onDragOver:Oe,onDragLeave:nt,onDrop:et,onClick:rt,onTouchStart:He,onTouchMove:Ge,onTouchEnd:oe,onDoubleClick:Dt,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":""}${Au.has(e.status)?" pulsing":""}${X?" 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(zp,{prInfo:mt,issueInfo:ht}),pe&&t.jsx("span",{className:`card-priority-badge card-priority-badge--${Te}`,children:Te}),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:Ot,title:`Mission: ${q??e.missionId}`,role:p?"button":void 0,tabIndex:p?0:void 0,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[t.jsx(ks,{size:11}),AN(q??e.missionId)]}),t.jsxs("div",{className:"card-header-actions",children:[Ie&&t.jsx("button",{className:"card-edit-btn",onClick:Et,title:"Edit task","aria-label":"Edit task",children:t.jsx(ms,{size:12})}),e.column==="triage"&&d&&t.jsx("button",{className:"card-delete-btn",onClick:zt,title:"Delete task","aria-label":"Delete task",children:t.jsx(on,{size:12})}),e.column==="done"&&c&&t.jsx("button",{className:"card-archive-btn",onClick:Lt,title:"Archive task","aria-label":"Archive task",children:"Archive"}),e.column==="archived"&&u&&t.jsx("button",{className:"card-unarchive-btn",onClick:Ft,title:"Unarchive task","aria-label":"Unarchive task",children:"Unarchive"}),e.column==="in-progress"&&g&&t.jsxs("div",{className:"card-send-back",ref:Ne,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:qt,title:"Send back","aria-label":"Send back","aria-haspopup":"menu","aria-expanded":V,children:["Send back",t.jsx(sn,{size:10})]}),V&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:Dc["in-progress"].filter(j=>j!=="in-review").map(j=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:Y=>nn(Y,j),children:Bn[j]},j))})]}),e.column==="in-review"&&g&&t.jsxs("div",{className:"card-send-back",ref:Ne,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:qt,title:"Move task","aria-label":"Move task","aria-haspopup":"menu","aria-expanded":V,children:["Move",t.jsx(sn,{size:10})]}),V&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:Dc["in-review"].map(j=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:Y=>nn(Y,j),children:j==="done"?"Done (no merge)":Bn[j]},j))})]}),e.size&&t.jsx("span",{className:`card-size-badge size-${e.size.toLowerCase()}`,children:e.size})]})]}),X&&e.error&&t.jsxs("div",{className:"card-error",title:e.error,children:[t.jsx("span",{className:"card-error-icon",children:"⚠"}),t.jsx("span",{className:"card-error-text",children:e.error.length>60?e.error.slice(0,60)+"…":e.error}),m&&t.jsxs("button",{type:"button",className:"btn btn-sm card-error-retry-btn",onClick:ge,disabled:ee,children:[t.jsx(Xx,{size:12}),ee?"Retrying…":"Retry"]})]}),t.jsx("div",{className:"card-title",title:e.title||e.description||void 0,children:zu(e.title,Lu)||zu(e.description,Lu)||e.id}),ft&&(()=>{const j=$e.completed/$e.total*100;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"card-progress",children:[t.jsx("div",{className:"card-progress-bar",children:t.jsx("div",{className:"card-progress-fill",style:{width:`${j}%`,backgroundColor:$N[e.column]}})}),t.jsxs("span",{className:"card-progress-label",children:[$e.completed,"/",$e.total]})]}),t.jsxs("button",{type:"button",className:"card-steps-toggle",onClick:Gt,"aria-expanded":T,"aria-label":T?"Hide steps":"Show steps",children:[t.jsxs("span",{children:[$e.total," step",$e.total===1?"":"s"]}),t.jsx(sn,{size:14,className:`card-steps-toggle-icon${T?" expanded":""}`})]}),T&&t.jsx("div",{className:"card-steps-list",children:$e.items.map(Y=>{const fe=Y.source==="workflow"&&Y.status==="failed";return t.jsxs("div",{className:"card-step-item",children:[t.jsx("span",{className:`card-step-dot card-step-dot--${Y.status}${fe?" card-step-dot--workflow-failed":""}`,"aria-hidden":"true"}),t.jsx("span",{className:`card-step-name${Y.status==="done"?" completed":""}`,children:Y.name}),Y.source==="workflow"&&t.jsx("span",{className:`card-step-workflow-badge card-step-workflow-badge--${Y.phase}`,title:"Workflow check",children:"workflow"})]},Y.id)})})]})})(),(dt||J)&&t.jsxs("div",{className:"card-footer-row",children:[dt,J&&t.jsxs("span",{className:"card-time-indicator",title:J.title,"aria-label":J.ariaLabel,children:[t.jsx(Ci,{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(j=>t.jsxs("span",{className:"card-dep-badge clickable",onClick:Y=>void je(Y,j),title:`Click to view ${j}`,children:[t.jsx(ga,{size:12,style:{verticalAlign:"middle"}})," ",j]},j))}),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(Ci,{size:12,style:{verticalAlign:"middle"}})," Queued"]})]}),(e.assignedAgentId||Je.length>0)&&t.jsxs("div",{className:"card-agent-row",children:[Je.length>0&&t.jsx("span",{className:"card-provider-icons","data-testid":"card-provider-icons",children:Je.map(j=>t.jsx(An,{provider:j,size:"sm"},j))}),e.assignedAgentId&&t.jsxs("span",{className:`card-agent-badge${Me?" card-agent-badge--loading":""}`,title:`Assigned to ${R??e.assignedAgentId}`,children:[t.jsx(Cn,{size:11}),t.jsx("span",{className:"card-agent-badge-text",children:PN(R??e.assignedAgentId,15)})]})]}),t.jsx(Zo,{slotId:"task-card-badge",projectId:n})]})}const Du=10,QN=300,Lu=140;function zu(e,n){return e?e.length>n?e.slice(0,n)+"…":e:""}const Io=a.memo(YN,JN);Io.displayName="TaskCard";function XN({label:e,activeTasks:n,queuedTasks:s,projectId:i,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:u,onOpenDetailWithTab:d,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p}){return t.jsxs("div",{className:"worktree-group",children:[t.jsxs("div",{className:"worktree-group-header",children:[t.jsx("span",{className:"worktree-icon",children:e==="Up Next"||e==="Unassigned"?t.jsx(kb,{size:14}):t.jsx(Ws,{size:14})}),t.jsx("span",{className:"worktree-label",children:e})]}),n.map(g=>t.jsx(Io,{task:g,projectId:i,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:u,onOpenDetailWithTab:d,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p},g.id)),s.map(g=>t.jsx(Io,{task:g,projectId:i,queued:!0,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:u,onOpenDetailWithTab:d,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p},g.id))]})}const qp=a.memo(XN);qp.displayName="WorktreeGroup";function Fu(e){return e.toLowerCase().replace(/[-_./]/g,"")}function ZN(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 e1(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 t1(e,n){const s=Fu(e),i=Fu(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&&ZN(s,o)||s.length>=4&&e1(s,o,1))return!0;return!1}function n1(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=>t1(o,r))})}function Xn({models:e,value:n,onChange:s,placeholder:i="Select a model…",disabled:r=!1,id:o,label:l,favoriteProviders:c=[],onToggleFavorite:u,favoriteModels:d=[],onToggleModelFavorite:m,noChangeValue:h,noChangeLabel:f="No change"}){const[p,g]=a.useState(!1),[b,v]=a.useState(""),[x,y]=a.useState(0),[k,S]=a.useState(null),[_,N]=a.useState(null),A=a.useRef(null),C=a.useRef(null),z=a.useRef(null),M=a.useRef(null),T=a.useRef(null),U=a.useMemo(()=>n1(e,b),[e,b]),q=a.useMemo(()=>U.reduce((Q,be)=>((Q[be.provider]??=[]).push(be),Q),{}),[U]),D=a.useMemo(()=>{const Q=[];for(const be of d){const de=be.indexOf("/");if(de===-1)continue;const me=be.slice(0,de),ie=be.slice(de+1),xe=U.find(Re=>Re.provider===me&&Re.id===ie);xe&&Q.push({model:xe,fullId:be})}return Q},[d,U]),R=a.useMemo(()=>{const Q=Object.entries(q),be=new Set(c);return Q.sort(([de],[me])=>{const ie=be.has(de),xe=be.has(me);if(ie&&!xe)return-1;if(!ie&&xe)return 1;if(ie&&xe){const Re=c.indexOf(de),Oe=c.indexOf(me);if(Re!==Oe)return Re-Oe}return de.localeCompare(me)})},[q,c]),F=typeof h=="string"&&h.length>0,V=a.useMemo(()=>{if(!n||F&&n===h)return null;const Q=n.indexOf("/");return Q===-1?null:n.slice(0,Q)},[F,h,n]),K=a.useMemo(()=>{const Q=[];return F&&Q.push({type:"no-change",value:h,label:f}),Q.push({type:"default",value:"",label:"Use default"}),Q},[F,f,h]),ee=a.useMemo(()=>{const Q=[...K];for(const{model:be,fullId:de}of D)Q.push({type:"favorite",value:de,label:be.name,provider:be.provider});return R.forEach(([be,de])=>{Q.push({type:"provider",value:`__group_${be}`,label:be,provider:be}),de.forEach(me=>{Q.push({type:"model",value:`${me.provider}/${me.id}`,label:me.name,provider:me.provider})})}),Q},[D,R,K]),E=a.useMemo(()=>{if(F&&n===h)return f;if(!n)return"Use default";const Q=n.indexOf("/");if(Q===-1)return n;const be=n.slice(0,Q),de=n.slice(Q+1);return e.find(ie=>ie.provider===be&&ie.id===de)?.name||n},[F,f,h,n,e]),$=a.useMemo(()=>ee.findIndex(Q=>Q.value===n),[ee,n]),P=a.useCallback(()=>{const Q=window.visualViewport;return Q&&Q.height>0&&Q.width>0?{width:Q.width,height:Q.height,offsetTop:Q.offsetTop,offsetLeft:Q.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),w=a.useCallback(()=>{const{height:Q}=P(),be=typeof window.matchMedia=="function",de=be?window.matchMedia("(max-width: 640px)").matches:!1,me=be?window.matchMedia("(max-width: 768px)").matches:!1;return Q<=0?320:de?Math.min(Q*.6,360):me?Math.min(Q*.7,420):320},[P]),O=a.useCallback(()=>{const Q=C.current;if(!Q)return;const be=Q.getBoundingClientRect(),{width:de,height:me,offsetTop:ie,offsetLeft:xe}=P(),Re=16,Oe=16,nt=4,et=w(),Ze=be.bottom-ie,rt=be.top-ie,He=be.left-xe,Ge=me-Ze,oe=rt,je=Math.max(Ge-Oe-nt,160),X=Math.max(oe-Oe-nt,160),Ae=Ge<et&&oe>Ge,Te=Math.max(Math.min(Ae?X:je,et),160),pe=Math.min(be.width,de-Re*2),_e=Math.min(Math.max(He,Re),de-Re-pe)+xe,Fe=Ae?Math.max(Oe+ie,rt-Te-nt+ie):Math.min(Ze+nt+ie,me+ie-Oe-Te);S({top:Fe,left:_e,width:pe,maxHeight:Te})},[P,w]);a.useEffect(()=>{N(document.body)},[]);const Z=a.useRef(!1);a.useEffect(()=>{if(!p){Z.current=!1;return}if(Z.current||ee.length===0)return;const Q=ee.findIndex((be,de)=>de>=($>=0?$:0)&&be.type!=="provider");y(Q>=0?Q:0),Z.current=!0},[p,ee,$]),a.useEffect(()=>{p&&Z.current&&(y(0),T.current&&(T.current.scrollTop=0))},[b,p]),a.useEffect(()=>{if(!p)return;O();const Q=requestAnimationFrame(()=>M.current?.focus());return()=>cancelAnimationFrame(Q)},[p,O]),a.useEffect(()=>{if(!p)return;const Q=()=>O();window.addEventListener("resize",Q),window.addEventListener("scroll",Q,!0);const be=window.visualViewport;return be&&(be.addEventListener("resize",Q),be.addEventListener("scroll",Q)),()=>{window.removeEventListener("resize",Q),window.removeEventListener("scroll",Q,!0),be&&(be.removeEventListener("resize",Q),be.removeEventListener("scroll",Q))}},[p,O]),a.useEffect(()=>{if(!p)return;const Q=be=>{const de=be.target,me=A.current?.contains(de),ie=z.current?.contains(de);!me&&!ie&&(g(!1),v(""))};return document.addEventListener("mousedown",Q),()=>document.removeEventListener("mousedown",Q)},[p]);const Ne=a.useCallback(Q=>{switch(Q.key){case"ArrowDown":if(Q.preventDefault(),!p)g(!0);else{let be=x;for(let de=1;de<=ee.length;de++){const me=(x+de)%ee.length;if(ee[me]?.type!=="provider"){be=me;break}}y(be)}break;case"ArrowUp":if(Q.preventDefault(),p){let be=x;for(let de=1;de<=ee.length;de++){const me=(x-de+ee.length)%ee.length;if(ee[me]?.type!=="provider"){be=me;break}}y(be)}break;case"Enter":if(Q.preventDefault(),p){const be=ee[x];be&&be.type!=="provider"&&be.type!=="favorite"&&(s(be.value),g(!1),v(""))}else g(!0);break;case"Escape":Q.preventDefault(),g(!1),v("");break;case"Tab":p&&(g(!1),v(""));break}},[p,x,ee,s]),se=a.useCallback(Q=>{s(Q),g(!1),v("")},[s]),le=a.useCallback(()=>{v(""),M.current?.focus()},[]),we=a.useCallback(()=>{r||g(Q=>!Q)},[r]);a.useEffect(()=>{if(p&&T.current){const Q=T.current.querySelector(`[data-index="${x}"]`);Q&&typeof Q.scrollIntoView=="function"&&Q.scrollIntoView({block:"nearest"})}},[x,p]);const L=b.length>0,ne=p&&k?t.jsxs("div",{ref:z,className:"model-combobox-dropdown model-combobox-dropdown--portal",role:"listbox","data-testid":"model-combobox-portal",onKeyDown:Ne,style:{top:`${k.top}px`,left:`${k.left}px`,width:`${k.width}px`,maxHeight:`${k.maxHeight}px`},children:[t.jsxs("div",{className:"model-combobox-search-wrapper",children:[t.jsx("input",{ref:M,type:"text",className:"model-combobox-search",placeholder:"Filter models…",value:b,onChange:Q=>v(Q.target.value),onClick:Q=>Q.stopPropagation()}),L&&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:[U.length," model",U.length!==1?"s":""]}),t.jsxs("div",{ref:T,className:"model-combobox-list",children:[K.map((Q,be)=>t.jsx("div",{"data-index":be,className:`model-combobox-option ${x===be?"model-combobox-option--highlighted":""} ${n===Q.value?"model-combobox-option--selected":""}`,onClick:()=>se(Q.value),onMouseEnter:()=>y(be),role:"option","aria-selected":n===Q.value,children:t.jsx("span",{className:"model-combobox-option-text model-combobox-option-text--default",children:Q.label})},`${Q.type}-${Q.value}`)),D.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"model-combobox-divider"}),D.map(({model:Q,fullId:be},de)=>{const me=de+K.length,ie=x===me,xe=n===be;return t.jsxs("div",{"data-index":me,className:`model-combobox-option model-combobox-option--favorite ${ie?"model-combobox-option--highlighted":""} ${xe?"model-combobox-option--selected":""}`,onClick:()=>se(be),onMouseEnter:()=>y(me),role:"option","aria-selected":xe,children:[t.jsxs("span",{className:"model-combobox-option-main",children:[t.jsx("span",{className:"model-combobox-option-icon",children:t.jsx(An,{provider:Q.provider,size:"sm"})}),t.jsx("span",{className:"model-combobox-option-text",children:Q.name})]}),t.jsx("span",{className:"model-combobox-option-id",children:Q.id}),m&&t.jsx("button",{type:"button",className:"model-combobox-option-favorite model-combobox-option-favorite--active",onClick:Re=>{Re.stopPropagation(),m(be)},title:"Remove from favorites","aria-label":`Remove ${Q.name} from favorites`,children:"★"})]},be)}),t.jsx("div",{className:"model-combobox-divider"})]}),R.map(([Q,be])=>{const de=ee.findIndex(xe=>xe.value===`__group_${Q}`),me=c.includes(Q),ie=be.filter(xe=>{const Re=`${xe.provider}/${xe.id}`;return!d.includes(Re)});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(An,{provider:Q,size:"sm"}),t.jsx("span",{className:"model-combobox-optgroup-text",children:Q}),u&&t.jsx("button",{type:"button",className:`model-combobox-optgroup-favorite ${me?"model-combobox-optgroup-favorite--active":""}`,onClick:xe=>{xe.stopPropagation(),u(Q)},title:me?"Remove from favorites":"Add to favorites","aria-label":me?`Remove ${Q} from favorites`:`Add ${Q} to favorites`,children:"★"})]}),ie.map(xe=>{const Re=`${xe.provider}/${xe.id}`,Oe=ee.findIndex(rt=>rt.value===Re),nt=x===Oe,et=n===Re,Ze=d.includes(Re);return t.jsxs("div",{"data-index":Oe,className:`model-combobox-option ${nt?"model-combobox-option--highlighted":""} ${et?"model-combobox-option--selected":""}`,onClick:()=>se(Re),onMouseEnter:()=>y(Oe),role:"option","aria-selected":et,children:[t.jsx("span",{className:"model-combobox-option-text",children:xe.name}),t.jsx("span",{className:"model-combobox-option-id",children:xe.id}),m&&t.jsx("button",{type:"button",className:`model-combobox-option-favorite ${Ze?"model-combobox-option-favorite--active":""}`,onClick:rt=>{rt.stopPropagation(),m(Re)},title:Ze?"Remove from favorites":"Add to favorites","aria-label":Ze?`Remove ${xe.name} from favorites`:`Add ${xe.name} to favorites`,children:Ze?"★":"☆"})]},Re)})]},Q)}),U.length===0&&L&&t.jsxs("div",{className:"model-combobox-no-results",children:["No models match '",b,"'"]})]})]}):null;return t.jsxs(t.Fragment,{children:[t.jsx("div",{ref:A,className:"model-combobox",onKeyDown:Ne,children:t.jsxs("button",{ref:C,type:"button",id:o,className:"model-combobox-trigger",onClick:we,disabled:r,"aria-haspopup":"listbox","aria-expanded":p,"aria-label":l,children:[V&&t.jsx("span",{className:"model-combobox-trigger-icon",children:t.jsx(An,{provider:V,size:"sm"})}),t.jsx("span",{className:"model-combobox-trigger-text",children:E||i}),t.jsx("span",{className:"model-combobox-trigger-arrow",children:"▼"})]})}),_&&ne?ma.createPortal(ne,_):null]})}function gd(e,n){return typeof n!="string"||n.length===0?e:`kb:${n}:${e}`}function Zn(e,n){return typeof window>"u"?null:window.localStorage.getItem(gd(e,n))}function ys(e,n,s){typeof window>"u"||window.localStorage.setItem(gd(e,s),n)}function Sr(e,n){typeof window>"u"||window.localStorage.removeItem(gd(e,n))}const s1=1e4,i1=1e3;function tl(){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 Ro();n(p)}catch(p){o(p instanceof Error?p.message:"Failed to fetch nodes")}},[]);a.useEffect(()=>{let p=!1;async function g(){i(!0);try{const v=await Ro();p||(n(v),o(null))}catch(v){p||o(v instanceof Error?v.message:"Failed to fetch nodes")}finally{p||i(!1)}}g();const b=()=>{if(document.visibilityState!=="visible")return;const v=Date.now();v-c.current<i1||(c.current=v,u())};return document.addEventListener("visibilitychange",b),()=>{p=!0,document.removeEventListener("visibilitychange",b)}},[u]),a.useEffect(()=>{if(!s)return l.current=setInterval(()=>{u()},s1),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async p=>{const g=await lk(p);return n(b=>[...b,g]),g},[]),m=a.useCallback(async(p,g)=>{const b=await ck(p,g);return n(v=>v.map(x=>x.id===p?b:x)),b},[]),h=a.useCallback(async p=>{await dk(p),n(g=>g.filter(b=>b.id!==p))},[]),f=a.useCallback(async p=>{const g=await uk(p);n(b=>b.map(v=>v.id===p?{...v,status:g.status,updatedAt:g.checkedAt}:v))},[]);return{nodes:e,loading:s,error:r,refresh:u,register:d,update:m,unregister:h,healthCheck:f}}const qa="kb-quick-entry-text",a1=["image/png","image/jpeg","image/gif","image/webp"];function r1(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function Sl(e,n){return e&&n?`${e}/${n}`:""}function Cl(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 Vp({onCreate:e,addToast:n,tasks:s=[],availableModels:i,onPlanningMode:r,onSubtaskBreakdown:o,projectId:l,autoExpand:c=!0,favoriteProviders:u,favoriteModels:d,onToggleFavorite:m,onToggleModelFavorite:h}){const[f,p]=a.useState(()=>typeof window<"u"&&Zn(qa,l)||""),[g,b]=a.useState(!1),[v,x]=a.useState(!1),[y,k]=a.useState(!1),S=a.useRef(null),_=a.useRef(null),N=a.useRef(!1),A=a.useRef(l),[C,z]=a.useState([]),M=a.useRef([]),[T,U]=a.useState([]),[q,D]=a.useState(!1),[R,F]=a.useState(""),[V,K]=a.useState(null),[ee,E]=a.useState([]),[$,P]=a.useState(void 0),[w,O]=a.useState(!1),[Z,Ne]=a.useState(!1),[se,le]=a.useState(!1),[we,L]=a.useState(!1),[ne,Q]=a.useState(null),[be,de]=a.useState(void 0),[me,ie]=a.useState(void 0),[xe,Re]=a.useState(void 0),[Oe,nt]=a.useState(void 0),[et,Ze]=a.useState(void 0),[rt,He]=a.useState(void 0),Ge=a.useRef(null),oe=a.useRef(null),je=a.useRef(null),X=a.useRef(null),Ae=a.useRef(null),Te=a.useRef(null),[pe,_e]=a.useState(null),[Fe,it]=a.useState(null),[ve,ce]=a.useState(null),Ie=a.useRef(null),he=a.useRef(null),[Me,Je]=a.useState(null),[$e]=a.useState(()=>typeof document<"u"?document.body:null),[ft,J]=a.useState(!1),[re,ye]=a.useState(null),[at,te]=a.useState(i??[]),[Ye,mt]=a.useState([]),[ht,xt]=a.useState([]),[St,bt]=a.useState(null),[Nt,Qt]=a.useState(void 0),[Pt,Dt]=a.useState(!1),[Et,Xt]=a.useState(void 0),{nodes:Lt}=tl(),[Ft,zt]=a.useState(!1),[Tt,Gt]=a.useState(!1),Ot=a.useRef(null),qt=a.useRef(null),[nn,ge]=a.useState(null),ze=u??Ye,dt=d??ht,j=!e;a.useEffect(()=>{if(i)te(i),J(!1),ye(null);else{let ae=!1;return J(!0),ye(null),fs().then(Ee=>{ae||(te(Ee.models),u||mt(Ee.favoriteProviders),d||xt(Ee.favoriteModels))}).catch(Ee=>{ae||ye(ke(Ee)||"Failed to load models")}).finally(()=>{ae||J(!1)}),Yo(l).then(Ee=>{ae||bt(Ee)}).catch(()=>{}),()=>{ae=!0}}},[i,u,d,l]);const Y=Sl(be,me),fe=Sl(xe,Oe),Pe=Sl(et,rt),We=!!(be&&me),gt=!!(xe&&Oe),Mt=!!(et&&rt),cn=Number(We)+Number(gt)+Number(Mt),bn=Nt?St?.modelPresets?.find(ae=>ae.id===Nt)?.name??"Models":cn>0?`${cn} model${cn===1?"":"s"}`:"Models",rn=a.useCallback((ae,Ee)=>{if(!ae||!Ee)return"Using default";const tt=at.find(kt=>kt.provider===ae&&kt.id===Ee);return tt?`${tt.provider}/${tt.id}`:`${ae}/${Ee}`},[at]);a.useEffect(()=>{p(Zn(qa,l)||"")},[l]),a.useEffect(()=>{typeof window<"u"&&ys(qa,f,l)},[f,l]),a.useEffect(()=>{A.current!==l&&(A.current=l,E([]),P(void 0),K(null),O(!1),_e(null))},[l]),a.useEffect(()=>{typeof window<"u"&&localStorage.removeItem("kb-quick-entry-expanded")},[]),a.useEffect(()=>{M.current=C},[C]),a.useEffect(()=>()=>{M.current.forEach(ae=>URL.revokeObjectURL(ae.previewUrl))},[]);const Jt=a.useCallback(()=>{const ae=S.current;if(!ae)return;ae.style.height="auto";const Ee=Math.min(ae.scrollHeight,200);ae.style.height=`${Ee}px`},[]);a.useEffect(()=>{v&&Jt()},[f,v,Jt]),a.useEffect(()=>{if(!g&&f===""&&S.current){const ae=setTimeout(()=>{S.current?.focus()},0);return()=>clearTimeout(ae)}},[g,f]),a.useEffect(()=>{q||F("")},[q]),a.useEffect(()=>{if(!Ft)return;const ae=Ee=>{const tt=Ee.target,kt=Ot.current?.contains(tt),wt=qt.current?.contains(tt);!kt&&!wt&&zt(!1)};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[Ft]),a.useEffect(()=>{if(!we)return;const ae=Ee=>{const tt=Ee.target,kt=Ge.current?.contains(tt),wt=oe.current?.contains(tt),fn=tt instanceof Element&&tt.closest?.(".model-combobox-dropdown--portal")!=null;!kt&&!wt&&!fn&&(L(!1),Q(null))};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[we]),a.useEffect(()=>{if(!Z)return;const ae=Ee=>{const tt=Ee.target;Ae.current?.contains(tt)||Te.current?.contains(tt)||(Ne(!1),it(null))};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[Z]),a.useEffect(()=>{if(!w)return;const ae=Ee=>{const tt=Ee.target;je.current?.contains(tt)||X.current?.contains(tt)||(O(!1),_e(null))};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[w]);const Sn=a.useCallback(()=>{C.forEach(ae=>URL.revokeObjectURL(ae.previewUrl)),z([]),_.current&&(_.current.value=""),p(""),U([]),K(null),O(!1),_e(null),Ne(!1),it(null),de(void 0),ie(void 0),Re(void 0),nt(void 0),Ze(void 0),He(void 0),Qt(void 0),Dt(!1),Xt(void 0),D(!1),L(!1),ce(null),Q(null),zt(!1),Gt(!1),x(!1),k(!1),N.current=!0,S.current&&(S.current.style.height="auto"),typeof window<"u"&&Sr(qa,l)},[C,l]),Se=a.useCallback(ae=>{if(!ae||ae.length===0)return;const Ee=[];for(let tt=0;tt<ae.length;tt++){const kt=ae[tt];a1.includes(kt.type)&&Ee.push({file:kt,previewUrl:URL.createObjectURL(kt)})}Ee.length>0&&z(tt=>[...tt,...Ee])},[]),ut=a.useCallback(ae=>{g||Se(ae.clipboardData?.files)},[Se,g]),Zt=a.useCallback(ae=>{z(Ee=>{const tt=Ee[ae];return tt&&URL.revokeObjectURL(tt.previewUrl),Ee.filter((kt,wt)=>wt!==ae)})},[]),_n=a.useCallback(async()=>{const ae=f.trim();if(!ae||g||!e)return;const Ee=f;b(!0),p("");try{const tt=await e({description:ae,column:"triage",dependencies:T.length?T:void 0,...V?{assignedAgentId:V}:{},modelPresetId:Nt,modelProvider:We?be:void 0,modelId:We?me:void 0,validatorModelProvider:gt?xe:void 0,validatorModelId:gt?Oe:void 0,planningModelProvider:Mt?et:void 0,planningModelId:Mt?rt:void 0,...Pt?{executionMode:"fast"}:{},nodeId:Et});if(tt&&C.length>0){const kt=[];for(const wt of C)try{await kr(tt.id,wt.file,l)}catch{kt.push(wt.file.name)}kt.length>0&&n(`Failed to upload: ${kt.join(", ")}`,"error")}Sn()}catch(tt){p(Ee),n(ke(tt)||"Failed to create task","error")}finally{b(!1)}},[f,g,e,T,V,We,be,me,gt,xe,Oe,Mt,et,rt,C,l,n,Sn,Pt,Et]),Nn=a.useCallback(ae=>{if(ae.key==="Enter"){if(ae.shiftKey&&v)return;ae.preventDefault(),_n()}else if(ae.key==="Escape"){if(ae.preventDefault(),ne){Q(null);return}if(we){L(!1),ce(null);return}if(q){D(!1);return}if(Ft){zt(!1);return}if(Z){Ne(!1),it(null);return}if(w){O(!1),_e(null);return}f.trim()&&(p(""),S.current&&(S.current.style.height="auto"),typeof window<"u"&&Sr(qa,l)),x(!1),k(!1),S.current?.blur()}},[_n,f,v,q,w,Z,we,ne,Ft,l,k]),zn=a.useCallback(()=>{N.current&&(N.current=!1)},[]),ss=a.useCallback(()=>{c&&x(!0)},[c]),Rn=a.useCallback(ae=>{U(Ee=>Ee.includes(ae)?Ee.filter(tt=>tt!==ae):[...Ee,ae])},[]),ue=a.useCallback(()=>{const ae=window.visualViewport;return ae&&ae.width>0&&ae.height>0?{width:ae.width,height:ae.height,offsetTop:ae.offsetTop,offsetLeft:ae.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),Ke=a.useCallback(()=>{const ae=Ge.current;if(!ae)return;const Ee=ae.getBoundingClientRect(),{width:tt,height:kt,offsetTop:wt,offsetLeft:fn}=ue(),un=16,Xe=16,It=4,mn=tt<=768,es=Math.min(mn?kt*.6:kt*.5,360),Hn=Math.max(Ee.width*1.35,320),On=mn?Math.min(tt-un*2,360):Hn,Tn=Math.min(On,Math.max(tt-un*2,240)),Wn=Ee.top-wt,gs=Ee.bottom-wt,Pn=Ee.left-fn,Kn=kt-gs,bs=Wn,zs=Math.max(Kn-Xe-It,160),xs=Math.max(bs-Xe-It,160),In=Kn<es&&bs>Kn,Gn=Math.max(Math.min(In?xs:zs,es),160),Fs=Math.min(Math.max(Pn,un),tt-un-Tn)+fn,Ai=In?Math.max(Xe+wt,Wn-Gn-It+wt):Math.min(gs+It+wt,kt+wt-Xe-Gn);ce({top:Ai,left:Fs,width:Tn,maxHeight:Gn})},[ue]),pt=a.useCallback(()=>{const ae=Ot.current?.querySelector(".refine-button");if(!ae)return;const Ee=ae.getBoundingClientRect(),{width:tt,height:kt,offsetTop:wt,offsetLeft:fn}=ue(),un=8,Xe=12,It=4,mn=Math.min(200,Math.max(kt-Xe*2,160)),es=Math.min(200,tt-un*2),Hn=Ee.top-wt,On=Ee.bottom-wt,Tn=Ee.left-fn,Wn=kt-On,gs=Hn,Pn=Wn<mn&&gs>Wn,Kn=Math.min(Math.max(Tn,un),tt-un-es)+fn,bs=Pn?Math.max(Xe+wt,Hn-mn-It+wt):Math.min(On+It+wt,kt+wt-Xe-mn);ge({top:bs,left:Kn})},[ue]),$t=a.useCallback(()=>{const ae=Ie.current;if(!ae)return;const Ee=ae.getBoundingClientRect(),{width:tt,height:kt,offsetTop:wt,offsetLeft:fn}=ue(),un=16,Xe=16,It=4,mn=tt<=768,es=Math.min(mn?kt*.6:kt*.5,320),Hn=mn?Math.min(tt-un*2,360):Math.max(Ee.width,280),On=Math.min(Hn,Math.max(tt-un*2,240)),Tn=Ee.top-wt,Wn=Ee.bottom-wt,gs=Ee.left-fn,Pn=kt-Wn,Kn=Tn,bs=Math.max(Pn-Xe-It,200),zs=Math.max(Kn-Xe-It,200),xs=Pn<es&&Kn>Pn,In=Math.max(Math.min(xs?zs:bs,es),200),Gn=Math.min(Math.max(gs,un),tt-un-On)+fn,Fs=xs?Math.max(Xe+wt,Tn-In-It+wt):Math.min(Wn+It+wt,kt+wt-Xe-In);Je({top:Fs,left:Gn,width:On,maxHeight:In})},[ue]),Vt=a.useCallback(()=>{const ae=je.current?.querySelector("button");if(!ae)return;const Ee=ae.getBoundingClientRect(),{width:tt,height:kt,offsetTop:wt,offsetLeft:fn}=ue(),un=16,Xe=16,It=4,mn=tt<=768,es=Math.min(mn?kt*.6:kt*.5,320),Hn=mn?Math.min(tt-un*2,280):Math.max(Ee.width,240),On=Math.min(Hn,Math.max(tt-un*2,200)),Tn=Ee.top-wt,Wn=Ee.bottom-wt,gs=Ee.left-fn,Pn=kt-Wn,Kn=Tn,bs=Math.max(Pn-Xe-It,160),zs=Math.max(Kn-Xe-It,160),xs=Pn<es&&Kn>Pn,In=Math.max(Math.min(xs?zs:bs,es),160),Gn=Math.min(Math.max(gs,un),tt-un-On)+fn,Fs=xs?Math.max(Xe+wt,Tn-In-It+wt):Math.min(Wn+It+wt,kt+wt-Xe-In);_e({top:Fs,left:Gn,width:On,maxHeight:In})},[ue]),dn=a.useCallback(()=>{const ae=Ae.current?.querySelector("button");if(!ae)return;const Ee=ae.getBoundingClientRect(),{width:tt,height:kt,offsetTop:wt,offsetLeft:fn}=ue(),un=16,Xe=16,It=4,mn=tt<=768,es=Math.min(mn?kt*.6:kt*.5,320),Hn=mn?Math.min(tt-un*2,280):Math.max(Ee.width,240),On=Math.min(Hn,Math.max(tt-un*2,200)),Tn=Ee.top-wt,Wn=Ee.bottom-wt,gs=Ee.left-fn,Pn=kt-Wn,Kn=Tn,bs=Math.max(Pn-Xe-It,160),zs=Math.max(Kn-Xe-It,160),xs=Pn<es&&Kn>Pn,In=Math.max(Math.min(xs?zs:bs,es),160),Gn=Math.min(Math.max(gs,un),tt-un-On)+fn,Fs=xs?Math.max(Xe+wt,Tn-In-It+wt):Math.min(Wn+It+wt,kt+wt-Xe-In);it({top:Fs,left:Gn,width:On,maxHeight:In})},[ue]);a.useEffect(()=>{if(!we)return;const ae=()=>Ke();window.addEventListener("resize",ae),window.addEventListener("scroll",ae,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",ae),Ee.addEventListener("scroll",ae)),()=>{window.removeEventListener("resize",ae),window.removeEventListener("scroll",ae,!0),Ee&&(Ee.removeEventListener("resize",ae),Ee.removeEventListener("scroll",ae))}},[we,Ke]),a.useEffect(()=>{if(!Ft)return;const ae=()=>pt();window.addEventListener("resize",ae),window.addEventListener("scroll",ae,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",ae),Ee.addEventListener("scroll",ae)),()=>{window.removeEventListener("resize",ae),window.removeEventListener("scroll",ae,!0),Ee&&(Ee.removeEventListener("resize",ae),Ee.removeEventListener("scroll",ae))}},[Ft,pt]),a.useEffect(()=>{if(!q)return;const ae=()=>$t();window.addEventListener("resize",ae),window.addEventListener("scroll",ae,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",ae),Ee.addEventListener("scroll",ae)),()=>{window.removeEventListener("resize",ae),window.removeEventListener("scroll",ae,!0),Ee&&(Ee.removeEventListener("resize",ae),Ee.removeEventListener("scroll",ae))}},[q,$t]),a.useEffect(()=>{if(!w)return;const ae=()=>Vt();window.addEventListener("resize",ae),window.addEventListener("scroll",ae,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",ae),Ee.addEventListener("scroll",ae)),()=>{window.removeEventListener("resize",ae),window.removeEventListener("scroll",ae,!0),Ee&&(Ee.removeEventListener("resize",ae),Ee.removeEventListener("scroll",ae))}},[w,Vt]),a.useEffect(()=>{if(!Z)return;const ae=()=>dn();window.addEventListener("resize",ae),window.addEventListener("scroll",ae,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",ae),Ee.addEventListener("scroll",ae)),()=>{window.removeEventListener("resize",ae),window.removeEventListener("scroll",ae,!0),Ee&&(Ee.removeEventListener("resize",ae),Ee.removeEventListener("scroll",ae))}},[Z,dn]);const Vn=a.useCallback(ae=>{const Ee=Cl(ae);Ze(Ee.provider),He(Ee.modelId)},[]),$n=a.useCallback(ae=>{const Ee=Cl(ae);de(Ee.provider),ie(Ee.modelId)},[]),Dn=a.useCallback(ae=>{const Ee=Cl(ae);Re(Ee.provider),nt(Ee.modelId)},[]),en=a.useCallback(async ae=>{if(m){m(ae);return}const Ee=Ye,kt=Ee.includes(ae)?Ee.filter(wt=>wt!==ae):[ae,...Ee];mt(kt);try{await gn({favoriteProviders:kt,favoriteModels:ht})}catch{mt(Ee)}},[Ye,ht,m]),Ct=a.useCallback(async ae=>{if(h){h(ae);return}const Ee=ht,kt=Ee.includes(ae)?Ee.filter(wt=>wt!==ae):[ae,...Ee];xt(kt);try{await gn({favoriteProviders:Ye,favoriteModels:kt})}catch{xt(Ee)}},[ht,Ye,h]),pn=a.useCallback(()=>{const ae=f.trim();if(!ae){n("Enter a description first","error");return}r?.(ae),Sn()},[f,r,n,Sn]),W=a.useCallback(()=>{const ae=f.trim();if(!ae){n("Enter a description first","error");return}o?.(ae),Sn()},[f,o,n,Sn]),Le=a.useCallback(()=>{_n()},[_n]),Qe=a.useCallback(async ae=>{const Ee=f.trim();if(!(!Ee||Tt)){zt(!1),Gt(!0);try{const tt=await kp(Ee,ae,l);p(tt),n("Description refined with AI","success"),S.current&&(S.current.style.height="auto",S.current.style.height=`${Math.min(S.current.scrollHeight,200)}px`)}catch(tt){const kt=wp(tt);n(kt,"error")}finally{Gt(!1)}}},[f,Tt,n,l]),ot=(ae,Ee)=>ae.length>Ee?ae.slice(0,Ee)+"…":ae,vt=a.useCallback(async()=>{if(i){te(i),ye(null),J(!1);return}J(!0),ye(null);try{const ae=await fs();te(ae.models),u||mt(ae.favoriteProviders),d||xt(ae.favoriteModels)}catch(ae){ye(ke(ae)||"Failed to load models")}finally{J(!1)}},[i,u,d]),_t=a.useCallback(async()=>{if(ee.length>0&&$===l){O(!0),Vt();return}le(!0);try{const ae=await Ra(void 0,l);E(ae),P(l),O(!0),Vt()}catch(ae){const Ee=ke(ae);n(Ee?`Failed to load agents: ${Ee}`:"Failed to load agents","error"),O(!1)}finally{le(!1)}},[ee.length,$,l,n,Vt]),Fn=(V?ee.find(ae=>ae.id===V):void 0)?.name??V,ds=Et?Lt.find(ae=>ae.id===Et):void 0,Ns=y,Js=a.useCallback(()=>{k(ae=>{const Ee=!ae;return x(Ee),Ee})},[]);return t.jsxs("div",{className:`quick-entry-box ${y?"quick-entry-box--expanded":"quick-entry-box--collapsed"}`,"data-testid":"quick-entry-box",children:[t.jsx("div",{className:"description-with-refine",children:t.jsxs("div",{className:"quick-entry-main-row",children:[t.jsx("div",{className:"quick-entry-textarea-wrap",children:t.jsx("textarea",{ref:S,className:`quick-entry-input ${v?"quick-entry-input--expanded":""}`,placeholder:g?"Creating...":"Add a task...",value:f,onChange:ae=>p(ae.target.value),onKeyDown:Nn,onPaste:ut,onFocus:ss,onBlur:zn,disabled:g||j,"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:Js,"aria-expanded":y,"aria-controls":"quick-entry-controls","data-testid":"quick-entry-toggle",title:y?"Collapse":"Expand",children:y?t.jsx(gi,{size:14}):t.jsx(sn,{size:14})})]})}),t.jsxs("div",{id:"quick-entry-controls",className:"quick-entry-controls",hidden:!Ns,"aria-hidden":!Ns,children:[Ns&&!g&&t.jsxs("div",{className:"quick-entry-actions","data-testid":"quick-entry-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:pn,onMouseDown:ae=>ae.preventDefault(),disabled:!f.trim(),"data-testid":"plan-button",title:"Open planning mode with current description",children:[t.jsx(ai,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Plan"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:W,onMouseDown:ae=>ae.preventDefault(),disabled:!f.trim(),"data-testid":"subtask-button",title:"Break down into AI-generated subtasks",children:[t.jsx(Wo,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Subtask"]}),t.jsxs("div",{className:"refine-trigger-wrap",ref:Ot,children:[t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${Tt?"refine-button--loading":""}`,onClick:()=>{zt(ae=>{const Ee=!ae;return Ee?pt():ge(null),Ee})},disabled:!f.trim()||Tt,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(os,{size:12,style:{verticalAlign:"middle"}}),Tt?"Refining...":"Refine"]}),Ft&&$e&&nn&&ma.createPortal(t.jsxs("div",{ref:qt,className:"refine-menu refine-menu--portal",onMouseDown:ae=>ae.preventDefault(),style:{position:"fixed",top:`${nn.top}px`,left:`${nn.left}px`},children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>Qe("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:()=>Qe("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:()=>Qe("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:()=>Qe("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)]}),t.jsx("div",{className:"dep-trigger-wrap",children:t.jsxs("button",{ref:Ie,type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-deps",onClick:()=>{D(ae=>{const Ee=!ae;return Ee?(L(!1),ce(null),Q(null),O(!1),_e(null),Ne(!1),it(null),$t()):Je(null),Ee})},children:[t.jsx(ga,{size:12,style:{verticalAlign:"middle"}}),T.length>0?`${T.length} deps`:"Deps"]})}),q&&$e&&Me&&(()=>{const ae=R.toLowerCase(),Ee=(ae?s.filter(tt=>tt.id.toLowerCase().includes(ae)||tt.title&&tt.title.toLowerCase().includes(ae)||tt.description&&tt.description.toLowerCase().includes(ae)):[...s]).sort((tt,kt)=>{const wt=kt.createdAt.localeCompare(tt.createdAt);if(wt!==0)return wt;const fn=parseInt(tt.id.slice(tt.id.lastIndexOf("-")+1),10)||0;return(parseInt(kt.id.slice(kt.id.lastIndexOf("-")+1),10)||0)-fn});return ma.createPortal(t.jsxs("div",{ref:he,className:"dep-dropdown dep-dropdown--portal",onMouseDown:tt=>tt.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:R,onChange:tt=>F(tt.target.value),onClick:tt=>tt.stopPropagation()}),Ee.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No existing tasks"}):Ee.map(tt=>t.jsxs("div",{className:`dep-dropdown-item${T.includes(tt.id)?" selected":""}`,onMouseDown:kt=>kt.preventDefault(),onClick:()=>Rn(tt.id),children:[t.jsx("span",{className:"dep-dropdown-id",children:tt.id}),t.jsx("span",{className:"dep-dropdown-title",children:ot(tt.title||tt.description||tt.id,60)})]},tt.id))]}),$e)})(),t.jsxs("button",{type:"button",className:"btn btn-sm","data-testid":"quick-entry-attach",onClick:()=>_.current?.click(),children:[t.jsx(dp,{size:12,style:{verticalAlign:"middle"}}),C.length>0?`Attach (${C.length})`:"Attach"]}),t.jsxs("button",{ref:Ge,type:"button",className:"btn btn-sm","data-testid":"quick-entry-models",onClick:()=>{D(!1),O(!1),_e(null),Ne(!1),it(null),Q(null),L(!0),Ke()},children:[t.jsx(Co,{size:12,style:{verticalAlign:"middle"}}),bn]}),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:()=>{D(!1),O(!1),_e(null),L(!1),ce(null),Q(null),Ne(ae=>{const Ee=!ae;return Ee?dn():it(null),Ee})},children:[t.jsx(yr,{size:12,style:{verticalAlign:"middle"}}),` ${ds?.name??"Node"}`,ds&&t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(Vi,{status:ds.status,showLabel:!0})})]})}),Z&&$e&&Fe&&ma.createPortal(t.jsxs("div",{ref:Te,className:"dep-dropdown node-picker-dropdown node-picker-dropdown--portal",onMouseDown:ae=>ae.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${Et==null?" selected":""}`,onMouseDown:ae=>ae.preventDefault(),onClick:()=>{Xt(void 0),Ne(!1),it(null)},children:t.jsx("span",{className:"node-picker-item-name",children:"Project default / local"})}),Lt.map(ae=>t.jsxs("div",{className:`dep-dropdown-item node-picker-item${Et===ae.id?" selected":""}`,onMouseDown:Ee=>Ee.preventDefault(),onClick:()=>{Xt(ae.id),Ne(!1),it(null)},children:[t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(Vi,{status:ae.status})}),t.jsx("span",{className:"node-picker-item-name",children:ae.name}),t.jsx("span",{className:"node-picker-item-status",children:r1(ae.status)})]},ae.id))]}),$e),t.jsx("div",{className:"agent-trigger-wrap",ref:je,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{w?(O(!1),_e(null)):(Ne(!1),it(null),_t())},"data-testid":"quick-entry-agent-button",children:[t.jsx(Cn,{size:12,style:{verticalAlign:"middle"}}),Fn?` ${Fn}`:" Agent"]})}),w&&$e&&pe&&ma.createPortal(t.jsxs("div",{ref:X,className:"dep-dropdown agent-picker-dropdown agent-picker-dropdown--portal",onMouseDown:ae=>ae.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"}),se&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!se&&ee.filter(ae=>ae.state!=="terminated").map(ae=>t.jsxs("div",{className:`dep-dropdown-item${V===ae.id?" selected":""}`,onMouseDown:Ee=>Ee.preventDefault(),onClick:()=>{K(ae.id===V?null:ae.id),O(!1),_e(null)},children:[t.jsx(Cn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:ae.role}),t.jsx("span",{className:"dep-dropdown-title",children:ae.name})]},ae.id)),!se&&ee.filter(ae=>ae.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),V&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:ae=>ae.preventDefault(),onClick:()=>{K(null),O(!1),_e(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]}),$e),t.jsx("button",{type:"button",className:`btn btn-sm ${Pt?"btn-primary":""}`,onClick:()=>Dt(ae=>!ae),onMouseDown:ae=>ae.preventDefault(),"aria-pressed":Pt,"data-testid":"quick-entry-fast-toggle",title:"Toggle fast execution mode",children:"Fast"}),t.jsxs("button",{type:"button",className:"btn btn-task-create btn-sm",onClick:Le,onMouseDown:ae=>ae.preventDefault(),disabled:!f.trim()||g,"data-testid":"quick-entry-save",title:"Create task",children:[t.jsx(mp,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Save"]})]}),C.length>0&&t.jsx("div",{className:"inline-create-previews",children:C.map((ae,Ee)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:ae.previewUrl,alt:ae.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>Zt(Ee),disabled:g,title:"Remove image","data-testid":`quick-entry-preview-remove-${Ee}`,children:"×"})]},ae.previewUrl))}),we&&$e&&ve&&ma.createPortal(t.jsx("div",{ref:oe,className:"model-nested-menu model-nested-menu--portal",onMouseDown:ae=>ae.preventDefault(),"data-testid":"model-nested-menu",style:{position:"fixed",top:`${ve.top}px`,left:`${ve.left}px`,width:`${ve.width}px`,maxHeight:ve.maxHeight?`${ve.maxHeight}px`:void 0,overflowY:ve.maxHeight?"auto":void 0},children:ne===null?t.jsxs("div",{className:"model-menu-items",children:[t.jsxs("button",{type:"button",className:`model-menu-item ${Mt?"model-menu-item--active":""}`,onClick:()=>Q("plan"),"data-testid":"model-menu-plan",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(ai,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Plan"]}),t.jsx("span",{className:"model-menu-item-value",children:Mt?rn(et,rt):"Using default"}),t.jsx(kn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${We?"model-menu-item--active":""}`,onClick:()=>Q("executor"),"data-testid":"model-menu-executor",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(os,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Executor"]}),t.jsx("span",{className:"model-menu-item-value",children:We?rn(be,me):"Using default"}),t.jsx(kn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${gt?"model-menu-item--active":""}`,onClick:()=>Q("validator"),"data-testid":"model-menu-validator",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(Co,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Reviewer"]}),t.jsx("span",{className:"model-menu-item-value",children:gt?rn(xe,Oe):"Using default"}),t.jsx(kn,{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:()=>Q(null),"data-testid":"model-submenu-back",children:[t.jsx(sn,{size:12,style:{transform:"rotate(90deg)",marginRight:4}}),"Back"]}),t.jsxs("div",{className:"model-submenu-header",children:[ne==="plan"&&"Plan Model",ne==="executor"&&"Executor Model",ne==="validator"&&"Reviewer Model"]}),t.jsx(Xn,{models:at,value:ne==="plan"?Pe:ne==="executor"?Y:fe,onChange:ne==="plan"?Vn:ne==="executor"?$n:Dn,placeholder:"Using default",disabled:ft,id:`model-${ne}-select`,label:`${ne} model`,favoriteProviders:ze,onToggleFavorite:en,favoriteModels:dt,onToggleModelFavorite:Ct}),re&&t.jsxs("div",{className:"model-submenu-error",children:[t.jsx("span",{children:re}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:vt,children:"Retry"})]})]})}),$e)]}),t.jsx("input",{ref:_,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:ae=>{Se(ae.target.files),ae.currentTarget.value=""},"data-testid":"quick-entry-file-input"}),t.jsx("div",{className:"quick-entry-hint",children:"Enter to create · Esc to cancel"})]})}function o1(e){return pd(e)||e}function l1(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 c1(e,n,s){const i=e.filter(g=>g.worktree),r=e.filter(g=>!g.worktree),o=new Map;for(const g of i){const b=g.worktree,v=o.get(b)||[];v.push(g),o.set(b,v)}const l=new Map(n.map(g=>[g.id,g])),u=n.filter(g=>g.column==="todo").filter(g=>!g.paused&&(g.dependencies||[]).every(b=>{const v=l.get(b);return v&&(v.column==="done"||v.column==="in-review"||v.column==="archived")})),m=l1(u).map(g=>l.get(g)).filter(g=>g!==void 0&&u.includes(g)),h=[],f=Array.from(o.keys());for(const g of f)h.push({label:o1(g),activeTasks:o.get(g),queuedTasks:[]});r.length>0&&h.push({label:"Unassigned",activeTasks:r,queuedTasks:[]});const p=m.slice(0,s);return p.length>0&&h.push({label:"Up Next",activeTasks:[],queuedTasks:p}),h}const Ou=100,El=50,Uu=25;function d1({column:e,tasks:n,projectId:s,maxConcurrent:i,onMoveTask:r,onPauseTask:o,onOpenDetail:l,addToast:c,onQuickCreate:u,onNewTask:d,autoMerge:m,onToggleAutoMerge:h,globalPaused:f,onUpdateTask:p,onRetryTask:g,onArchiveTask:b,onUnarchiveTask:v,onDeleteTask:x,onArchiveAllDone:y,collapsed:k,onToggleCollapse:S,allTasks:_,availableModels:N,onPlanningMode:A,onSubtaskBreakdown:C,onOpenDetailWithTab:z,favoriteProviders:M,favoriteModels:T,onToggleFavorite:U,onToggleModelFavorite:q,isSearchActive:D,taskStuckTimeoutMs:R,onOpenMission:F,lastFetchTimeMs:V,workflowStepNameLookup:K}){const[ee,E]=a.useState(!1),[$,P]=a.useState(El),[w,O]=a.useState(!1),[Z,Ne]=a.useState(!1),[se,le]=a.useState(!1),[we,L]=a.useState(!1),ne=a.useRef(null),Q=Zw(n.length),{confirm:be}=Ks();a.useEffect(()=>{if(!w)return;function _e(it){ne.current?.contains(it.target)||O(!1)}function Fe(it){it.key==="Escape"&&O(!1)}return document.addEventListener("mousedown",_e),document.addEventListener("keydown",Fe),()=>{document.removeEventListener("mousedown",_e),document.removeEventListener("keydown",Fe)}},[w]);const de=e==="archived",me=de&&k,ie=!de&&!D&&e!=="in-progress"&&n.length>Ou;a.useEffect(()=>{P(_e=>e==="in-progress"||de||n.length<=Ou?El:Math.min(Math.max(_e,El),n.length))},[e,de,n.length]);const xe=a.useCallback(_e=>{de||(_e.preventDefault(),_e.dataTransfer.dropEffect="move",E(!0))},[de]),Re=a.useCallback(_e=>{_e.currentTarget.contains(_e.relatedTarget)||E(!1)},[]),Oe=a.useCallback(async _e=>{_e.preventDefault(),E(!1);const Fe=_e.dataTransfer.getData("text/plain");if(!Fe)return;const it=n.find(ve=>ve.id===Fe);if(!(it&&it.column===e))try{await r(Fe,e)}catch(ve){c(ke(ve),"error")}},[e,r,c,n]),nt=a.useMemo(()=>e!=="in-progress"?[]:c1(n,n,i),[e,n,i]),et=a.useMemo(()=>ie?n.slice(0,$):n,[ie,n,$]),Ze=Math.max(0,n.length-et.length),rt=a.useCallback(()=>{P(_e=>Math.min(_e+Uu,n.length))},[n.length]),He=a.useCallback(async()=>{if(O(!1),!(n.length===0||!await be({title:"Replan All Tasks",message:`Move all ${n.length} todo task${n.length===1?"":"s"} back to planning to be replanned?`}))){Ne(!0);try{const Fe=await Promise.allSettled(n.map(ce=>r(ce.id,"triage"))),it=Fe.filter(ce=>ce.status==="rejected").length,ve=Fe.length-it;it===0?c(`Moved ${ve} task${ve===1?"":"s"} to planning for replanning`,"success"):c(`Moved ${ve} of ${Fe.length} tasks; ${it} failed`,"error")}finally{Ne(!1)}}},[n,r,c,be]),Ge=a.useMemo(()=>n.filter(_e=>!_e.paused),[n]),oe=Ge.length,je=e==="todo"||e==="in-progress"||e==="in-review",X=Z||se||we,Ae=a.useCallback(async()=>{if(!(!o||(O(!1),oe===0)||!await be({title:"Stop All Tasks",message:`Stop all ${oe} ${Bn[e].toLowerCase()} task${oe===1?"":"s"}?`,danger:!0}))){le(!0);try{const Fe=await Promise.allSettled(Ge.map(ce=>o(ce.id))),it=Fe.filter(ce=>ce.status==="rejected").length,ve=Fe.length-it;it===0?c(`Stopped ${ve} task${ve===1?"":"s"}`,"success"):c(`Stopped ${ve} of ${Fe.length} tasks; ${it} failed`,"error")}finally{le(!1)}}},[o,oe,e,Ge,c,be]),Te=a.useCallback(async()=>{if(O(!1),!(n.length===0||!await be({title:"Move All to Todo",message:`Move all ${n.length} ${Bn[e].toLowerCase()} task${n.length===1?"":"s"} to Todo?`}))){L(!0);try{const Fe=await Promise.allSettled(n.map(ce=>r(ce.id,"todo"))),it=Fe.filter(ce=>ce.status==="rejected").length,ve=Fe.length-it;it===0?c(`Moved ${ve} task${ve===1?"":"s"} to Todo`,"success"):c(`Moved ${ve} of ${Fe.length} tasks to Todo; ${it} failed`,"error")}finally{L(!1)}}},[n,e,r,c,be]),pe=a.useCallback(async()=>{if(!(!y||n.length===0||!await be({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(ke(Fe)||"Failed to archive tasks","error")}},[y,n.length,c,be]);return t.jsxs("div",{className:`column${ee?" drag-over":""}${de?" column-archived":""}${me?" column-collapsed":""}`,"data-column":e,onDragOver:xe,onDragLeave:Re,onDrop:Oe,children:[t.jsxs("div",{className:"column-header",children:[t.jsx("div",{className:`column-dot dot-${e}`}),t.jsx("h2",{children:Bn[e]}),t.jsx("span",{className:`column-count${Q?" count-flash":""}`,children:n.length}),e==="in-review"&&h&&t.jsxs("label",{className:"auto-merge-toggle",title:m?"Auto-merge enabled":"Auto-merge disabled",children:[t.jsx("input",{type:"checkbox",checked:!!m,onChange:h}),t.jsx("span",{className:"toggle-slider"}),t.jsx("span",{className:"toggle-label",children:"Auto-merge"})]}),d&&t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:d,children:"+ New Task"}),e==="done"&&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(Mr,{size:16})}),de&&S&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:S,title:k?"Expand archived tasks":"Collapse archived tasks","aria-label":k?"Expand archived tasks":"Collapse archived tasks",children:k?t.jsx(sn,{size:16}):t.jsx(gi,{size:16})}),je&&t.jsxs("div",{className:"column-menu",ref:ne,children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>O(_e=>!_e),"aria-haspopup":"menu","aria-expanded":w,"aria-label":`${Bn[e]} column actions`,title:"Column actions",disabled:X,children:t.jsx(Pb,{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 He(),disabled:n.length===0||Z,children:["Replan All",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Planning"]})]}),(e==="in-progress"||e==="in-review")&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Ae(),disabled:oe===0||se||!o,children:["Stop All",t.jsx("span",{className:"column-menu-item-hint",children:n.length===0?"No tasks in this column":oe===0?"All tasks are already paused":`Pause ${oe} active task${oe===1?"":"s"}`})]}),t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Te(),disabled:n.length===0||we,children:["Move All to Todo",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Todo"]})]})]})]})]})]}),!me&&t.jsx("p",{className:"column-desc",children:Qw[e]}),!me&&t.jsxs("div",{className:"column-body",children:[e==="triage"&&u&&t.jsx(Vp,{onCreate:u,addToast:c,tasks:_??[],availableModels:N,onPlanningMode:A,onSubtaskBreakdown:C,projectId:s,autoExpand:!1,favoriteProviders:M,favoriteModels:T,onToggleFavorite:U,onToggleModelFavorite:q}),e==="in-progress"?nt.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):nt.map(_e=>t.jsx(qp,{label:_e.label,activeTasks:_e.activeTasks,queuedTasks:_e.queuedTasks,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onOpenDetailWithTab:z,taskStuckTimeoutMs:R,onOpenMission:F,lastFetchTimeMs:V,workflowStepNameLookup:K},_e.label)):n.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):t.jsxs(t.Fragment,{children:[et.map(_e=>t.jsx(Io,{task:_e,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onArchiveTask:b,onUnarchiveTask:v,onDeleteTask:x,onOpenDetailWithTab:z,taskStuckTimeoutMs:R,onOpenMission:F,onMoveTask:r,lastFetchTimeMs:V,workflowStepNameLookup:K},_e.id)),ie&&Ze>0&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:rt,children:["Load ",Math.min(Uu,Ze)," more (",Ze," remaining)"]})]}),t.jsx(Zo,{slotId:"board-column-footer",projectId:s})]})]})}const Wp=a.memo(d1);Wp.displayName="Column";function u1(e,n){return[...e].sort((s,i)=>{if(n==="in-review"){const r=s.status==="merging"||s.status==="merging-pr",o=i.status==="merging"||i.status==="merging-pr";if(r!==o)return r?-1:1}return s.columnMovedAt&&i.columnMovedAt?i.columnMovedAt.localeCompare(s.columnMovedAt):s.columnMovedAt&&!i.columnMovedAt?-1:!s.columnMovedAt&&i.columnMovedAt?1:s.createdAt.localeCompare(i.createdAt)})}function m1(e,n){return e.length!==n.length?!1:e.every((s,i)=>s===n[i])}const Bu=new Map;function h1(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 p1({tasks:e,projectId:n,maxConcurrent:s,onMoveTask:i,onPauseTask:r,onOpenDetail:o,addToast:l,onQuickCreate:c,onNewTask:u,autoMerge:d,onToggleAutoMerge:m,globalPaused:h,onUpdateTask:f,onRetryTask:p,onArchiveTask:g,onUnarchiveTask:b,onDeleteTask:v,onArchiveAllDone:x,onLoadArchivedTasks:y,searchQuery:k="",availableModels:S,onPlanningMode:_,onSubtaskBreakdown:N,onOpenDetailWithTab:A,favoriteProviders:C,favoriteModels:z,onToggleFavorite:M,onToggleModelFavorite:T,taskStuckTimeoutMs:U,onOpenMission:q,lastFetchTimeMs:D}){const[R,F]=a.useState(!0),V=a.useRef(!1),{fetchBatch:K}=xN(n),ee=a.useRef(null),[E,$]=a.useState(Bu),P=k.trim()!=="",w=a.useRef({triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]}),O=a.useCallback(()=>{F(se=>{const le=!se;return!le&&!V.current&&y&&(V.current=!0,y()),le})},[y]),Z=a.useMemo(()=>{const se=Object.fromEntries(Oi.map(L=>[L,[]]));for(const L of e)se[L.column].push(L);const le=w.current,we={};for(const L of Oi){const ne=u1(se[L],L);we[L]=m1(le[L],ne)?le[L]:ne}return w.current=we,we},[e]);a.useEffect(()=>{let se=!1;return Qo(n).then(le=>{if(se)return;const we=new Map(le.map(L=>[L.id,L.name]));$(L=>h1(L,we)?L:we)}).catch(()=>{se||$(le=>le.size===0?le:Bu)}),()=>{se=!0}},[n]);const Ne=a.useMemo(()=>e.filter(se=>se.prInfo||se.issueInfo).map(se=>se.id),[e]);return a.useEffect(()=>{if(Ne.length!==0)return ee.current&&clearTimeout(ee.current),ee.current=setTimeout(()=>{const se=[];for(let le=0;le<Ne.length;le+=50)se.push(Ne.slice(le,le+50));se.forEach(le=>{K(le)})},500),()=>{ee.current&&clearTimeout(ee.current)}},[Ne,K]),t.jsx(t.Fragment,{children:t.jsx("main",{className:"board",id:"board",children:Oi.map(se=>t.jsx(Wp,{column:se,tasks:Z[se],projectId:n,maxConcurrent:s,onMoveTask:i,onPauseTask:r,onOpenDetail:o,addToast:l,globalPaused:h,onUpdateTask:f,onRetryTask:p,onArchiveTask:g,onUnarchiveTask:b,onDeleteTask:v,allTasks:e,availableModels:S,onOpenDetailWithTab:A,favoriteProviders:C,favoriteModels:z,onToggleFavorite:M,onToggleModelFavorite:T,isSearchActive:P,taskStuckTimeoutMs:U,onOpenMission:q,lastFetchTimeMs:D,workflowStepNameLookup:E,...se==="triage"?{onQuickCreate:c,onNewTask:u,onPlanningMode:_,onSubtaskBreakdown:N}:{},...se==="in-review"?{autoMerge:d,onToggleAutoMerge:m}:{},...se==="done"?{onArchiveAllDone:x}:{},...se==="archived"?{collapsed:R,onToggleCollapse:O}:{}},se))})})}const Va={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-secondary)"},Hu=new Set(["planning","researching","executing","finalizing","merging"]),Oc=["id","title","status","column","dependencies","progress"];function f1(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function g1(e){return e==="online"?"●":e==="connecting"?"◐":e==="error"?"✕":"○"}function qu(e){try{const n=Zn("kb-dashboard-list-columns",e);if(n){const i=JSON.parse(n).filter(r=>Oc.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set(Oc)}function Vu(e){try{const n=Zn("kb-dashboard-hide-done",e);if(n!==null)return n==="true"}catch{}return!1}function Wu(e){try{const n=Zn("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 Ku(e){try{const n=Zn("kb-dashboard-selected-tasks",e);if(n){const s=JSON.parse(n);return new Set(s)}}catch{}return new Set}function b1(e){return e.status==="executing"||e.column==="in-progress"}function Gu(e){const n=Up(e);return n.total===0||!b1(e)?{label:"-",percent:0,hasProgress:!1}:{label:`${n.completed}/${n.total}`,percent:n.completed/n.total*100,hasProgress:!0}}function x1({tasks:e,onMoveTask:n,onOpenDetail:s,addToast:i,globalPaused:r,onNewTask:o,onQuickCreate:l,availableModels:c,favoriteProviders:u=[],favoriteModels:d=[],onToggleFavorite:m,onToggleModelFavorite:h,onPlanningMode:f,onSubtaskBreakdown:p,onTasksUpdated:g,projectId:b,projectName:v,taskStuckTimeoutMs:x,searchQuery:y="",lastFetchTimeMs:k}){const[S,_]=a.useState("id"),[N,A]=a.useState("desc"),[C,z]=a.useState(null),[M,T]=a.useState(null),[U,q]=a.useState(null),R=Ta()==="mobile",[F,V]=a.useState(()=>qu(b)),[K,ee]=a.useState(()=>Vu(b)),[E,$]=a.useState(()=>Wu(b));a.useEffect(()=>{typeof window<"u"&&ys("kb-dashboard-list-columns",JSON.stringify([...F]),b)},[b,F]),a.useEffect(()=>{typeof window<"u"&&ys("kb-dashboard-hide-done",K.toString(),b)},[K,b]),a.useEffect(()=>{typeof window<"u"&&ys("kb-dashboard-list-collapsed",JSON.stringify([...E]),b)},[E,b]);const[P,w]=a.useState(!1),O=a.useRef(null),[Z,Ne]=a.useState(()=>Ku(b));a.useEffect(()=>{V(qu(b)),ee(Vu(b)),$(Wu(b)),Ne(Ku(b))},[b]),a.useEffect(()=>{typeof window<"u"&&ys("kb-dashboard-selected-tasks",JSON.stringify([...Z]),b)},[b,Z]);const se=a.useCallback(J=>{Ne(re=>{const ye=new Set(re);return ye.has(J)?ye.delete(J):ye.add(J),ye})},[]),le=a.useCallback(()=>{Ne(new Set)},[]),we=a.useCallback(J=>{V(re=>{const ye=new Set(re);return ye.has(J)?ye.size>1&&ye.delete(J):ye.add(J),ye})},[]);a.useEffect(()=>{if(!P)return;const J=ye=>{O.current&&!O.current.contains(ye.target)&&w(!1)},re=ye=>{ye.key==="Escape"&&w(!1)};return document.addEventListener("mousedown",J),document.addEventListener("keydown",re),()=>{document.removeEventListener("mousedown",J),document.removeEventListener("keydown",re)}},[P]);const L={id:"ID",title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},ne=a.useCallback(J=>{S===J?A(re=>re==="asc"?"desc":"asc"):(_(J),A("asc"))},[S]),Q=a.useCallback(J=>{q(re=>re===J?null:J)},[]),be=a.useCallback(J=>{$(re=>{const ye=new Set(re);return ye.has(J)?ye.delete(J):ye.add(J),ye})},[]),de=a.useCallback(()=>{q(null)},[]),me=a.useMemo(()=>{let J=y?e.filter(te=>te.id.toLowerCase().includes(y.toLowerCase())||te.title&&te.title.toLowerCase().includes(y.toLowerCase())||te.description.toLowerCase().includes(y.toLowerCase())):[...e];K&&!U&&(J=J.filter(te=>te.column!=="done"&&te.column!=="archived"));const ye=[...U?J.filter(te=>te.column===U):J].sort((te,Ye)=>{let mt=0;switch(S){case"id":mt=te.id.localeCompare(Ye.id);break;case"title":mt=(te.title||te.description).localeCompare(Ye.title||Ye.description);break;case"status":mt=(te.status||"").localeCompare(Ye.status||"");break;case"column":mt=te.column.localeCompare(Ye.column);break}return N==="asc"?mt:-mt}),at={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};return ye.forEach(te=>at[te.column].push(te)),at},[e,y,S,N,K,U]),ie=a.useMemo(()=>Object.values(me).reduce((J,re)=>J+re.length,0),[me]),xe=a.useMemo(()=>e.filter(J=>J.column==="done"||J.column==="archived").length,[e]),Re=a.useMemo(()=>K?xe:0,[K,xe]),Oe=a.useCallback(()=>{const J=Object.values(me).flat().filter(re=>re.column!=="archived").map(re=>re.id);Ne(re=>{if(J.every(at=>re.has(at))){const at=new Set(re);return J.forEach(te=>at.delete(te)),at}else return new Set([...re,...J])})},[me]),nt=a.useMemo(()=>{const J=Object.values(me).flat().filter(re=>re.column!=="archived");return J.length===0?!1:J.every(re=>Z.has(re.id))},[me,Z]),et=a.useMemo(()=>{const J=Object.values(me).flat().filter(ye=>ye.column!=="archived");if(J.length===0)return!1;const re=J.filter(ye=>Z.has(ye.id)).length;return re>0&&re<J.length},[me,Z]),[Ze,rt]=a.useState("__no_change__"),[He,Ge]=a.useState("__no_change__"),[oe,je]=a.useState("__no_change__"),[X,Ae]=a.useState([]),[Te,pe]=a.useState(!1),_e=a.useMemo(()=>oe&&oe!=="__no_change__"?X.find(J=>J.id===oe):void 0,[X,oe]),[Fe,it]=a.useState(!1);a.useEffect(()=>{if(Z.size===0)return;let J=!1;return(async()=>{pe(!0);try{const ye=await Ro();J||Ae(ye)}catch(ye){console.error("Failed to fetch nodes for bulk edit",ye),J||Ae([])}finally{J||pe(!1)}})(),()=>{J=!0}},[Z.size]);const ve=a.useCallback(async()=>{if(Z.size===0)return;const J=Array.from(Z).filter(ye=>{const at=e.find(te=>te.id===ye);return at&&at.column!=="archived"});if(J.length===0){i("No valid tasks to update (archived tasks cannot be modified)","error");return}const re={taskIds:J};if(Ze!=="__no_change__")if(Ze==="")re.modelProvider=null,re.modelId=null;else{const ye=Ze.indexOf("/");ye!==-1&&(re.modelProvider=Ze.slice(0,ye),re.modelId=Ze.slice(ye+1))}if(He!=="__no_change__")if(He==="")re.validatorModelProvider=null,re.validatorModelId=null;else{const ye=He.indexOf("/");ye!==-1&&(re.validatorModelProvider=He.slice(0,ye),re.validatorModelId=He.slice(ye+1))}if(oe!=="__no_change__"&&(oe===""?re.nodeId=null:re.nodeId=oe),Object.keys(re).length===1){i("No changes to apply","info");return}it(!0);try{const ye=await Yv(re.taskIds,re.modelProvider,re.modelId,re.validatorModelProvider,re.validatorModelId,void 0,void 0,re.nodeId,b);g&&g(ye.updated),i(`Updated ${J.length} task${J.length===1?"":"s"}`,"success"),le(),rt("__no_change__"),Ge("__no_change__"),je("__no_change__")}catch(ye){i(ke(ye)||"Failed to update models","error")}finally{it(!1)}},[Z,e,Ze,He,oe,b,i,le,g]),ce=a.useCallback(J=>{s(J)},[s]),Ie=a.useCallback((J,re)=>{if(re.paused){J.preventDefault();return}J.dataTransfer.setData("text/plain",re.id),J.dataTransfer.effectAllowed="move",z(re.id)},[]),he=a.useCallback(()=>{z(null),T(null)},[]),Me=a.useCallback((J,re)=>{J.preventDefault(),J.dataTransfer.dropEffect="move",T(re)},[]),Je=a.useCallback(()=>{T(null)},[]),$e=a.useCallback(async(J,re)=>{J.preventDefault(),T(null);const ye=J.dataTransfer.getData("text/plain");if(ye){if(re==="archived"){i("Tasks can only be archived via the archive button","error");return}try{await n(ye,re)}catch(at){i(ke(at),"error")}}},[n,i]),ft=J=>S!==J?t.jsx(np,{size:14,className:"sort-icon"}):N==="asc"?t.jsx(Fi,{size:14,className:"sort-icon active"}):t.jsx(Ar,{size:14,className:"sort-icon active"});return t.jsxs("div",{className:"list-view",children:[t.jsxs("div",{className:"list-toolbar",children:[t.jsxs("div",{className:"list-column-toggle",ref:O,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>w(J=>!J),"aria-expanded":P,"aria-haspopup":"menu",children:[t.jsx(Cb,{size:14}),"Columns"]}),P&&t.jsx("div",{className:"list-column-dropdown",role:"menu",children:Oc.map(J=>{const re=F.has(J),ye=re&&F.size===1;return t.jsxs("label",{className:`list-column-dropdown-item${ye?" disabled":""}`,role:"menuitem",title:ye?"At least one column must be visible":"",children:[t.jsx("input",{type:"checkbox",checked:re,onChange:()=>we(J),disabled:ye}),t.jsx("span",{children:L[J]})]},J)})})]}),t.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>ee(J=>!J),"aria-pressed":K,title:K?"Show done tasks":"Hide done tasks",children:[K?t.jsx(Ma,{size:14}):t.jsx(rd,{size:14}),K?"Show Done":"Hide Done"]}),t.jsxs("div",{className:"list-stats",children:[U?`${ie} of ${e.length} tasks in ${Bn[U]}`:`${ie} of ${e.length} tasks`,Re>0&&!U&&t.jsxs("span",{className:"list-stats-hidden",children:[" (",Re," hidden)"]}),U&&t.jsx("button",{className:"btn btn-sm",onClick:de,"aria-label":"Clear column filter",style:{marginLeft:"8px"},children:"Clear"})]}),Z.size>0&&t.jsxs("div",{className:"list-selection-stats",children:[t.jsxs("span",{className:"selection-count",children:[Z.size," selected"]}),t.jsx("button",{className:"btn btn-sm btn-link",onClick:le,children:"Clear"})]}),Z.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(Xn,{models:c,value:Ze,onChange:rt,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(Xn,{models:c,value:He,onChange:Ge,label:"Reviewer Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:u,onToggleFavorite:m,favoriteModels:d,onToggleModelFavorite:h})}),t.jsxs("div",{className:"bulk-edit-dropdown bulk-edit-node-wrap",children:[t.jsxs("select",{className:"select bulk-node-select",value:oe,onChange:J=>je(J.target.value),"aria-label":"Node Override",disabled:Te,children:[t.jsx("option",{value:"__no_change__",children:"No change"}),t.jsx("option",{value:"",children:"Use project default"}),X.map(J=>t.jsx("option",{value:J.id,children:`${g1(J.status)} ${J.name||J.id} (${f1(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:ve,disabled:Fe||Ze==="__no_change__"&&He==="__no_change__"&&oe==="__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 re=e.filter(Ye=>Ye.column===J).length,ye=J==="done"||J==="archived",at=K&&ye?0:re,te=K&&ye&&re>0;return t.jsxs("div",{className:`list-drop-zone${M===J?" drag-over":""}${U===J?" active":""}`,onClick:()=>Q(J),onDragOver:Ye=>Me(Ye,J),onDragLeave:Je,onDrop:Ye=>$e(Ye,J),"data-column":J,children:[t.jsx("span",{className:"drop-zone-dot",style:{background:Va[J]}}),t.jsx("span",{className:"drop-zone-label",children:Bn[J]}),t.jsx("span",{className:"drop-zone-count",children:te?`${at} of ${re}`:re})]},J)})}),t.jsxs("div",{className:"list-table-container",children:[t.jsx("div",{className:"list-quick-entry-above-table",children:t.jsx(Vp,{onCreate:l??(async()=>i("Task creation not available","error")),addToast:i,tasks:e,availableModels:c,onPlanningMode:f,onSubtaskBreakdown:p,projectId:b,autoExpand:!1,favoriteProviders:u,favoriteModels:d,onToggleFavorite:m,onToggleModelFavorite:h})}),ie===0?t.jsx("div",{className:"list-empty",children:y?"No tasks match your filter":"No tasks yet"}):R?t.jsx("div",{className:"list-cards",children:Oi.map(J=>{if(U&&J!==U||K&&(J==="done"||J==="archived")&&!U)return null;const re=me[J],ye=re.length===0;if(y&&ye)return null;const at=E.has(J);return t.jsxs(a.Fragment,{children:[t.jsxs("div",{className:`list-card-section-header${at?" list-section-header--collapsed":""}`,onClick:()=>be(J),"aria-expanded":!at,role:"button",tabIndex:0,onKeyDown:te=>{(te.key==="Enter"||te.key===" ")&&(te.preventDefault(),be(J))},children:[t.jsx(kn,{size:14,className:`list-section-chevron${at?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${J}`}),t.jsx("span",{className:"list-section-title",children:Bn[J]}),t.jsx("span",{className:"list-section-count",children:re.length})]}),!at&&t.jsx(t.Fragment,{children:ye?t.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):re.map(te=>{const Ye=te.status==="failed",mt=te.paused===!0,ht=Po(te,x,k),xt=!r&&!Ye&&!mt&&!ht&&(te.column==="in-progress"||Hu.has(te.status)),St=typeof te.status=="string"&&te.status.trim().length>0,bt=!!(te.dependencies&&te.dependencies.length>0),Nt=Gu(te),Qt=Nt.hasProgress,Pt=Z.size>0;return t.jsxs("div",{className:`list-card${xt?" agent-active":""}${Pt?" list-card--selectable":""}`,onClick:()=>ce(te),"data-id":te.id,children:[Pt&&t.jsx("label",{className:"list-card-checkbox",onClick:Dt=>Dt.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:Z.has(te.id),onChange:Dt=>{Dt.stopPropagation(),se(te.id)},onClick:Dt=>Dt.stopPropagation(),disabled:te.column==="archived","aria-label":`Select ${te.id}`})}),t.jsxs("div",{className:"list-card-row",children:[t.jsx("span",{className:"list-card-id",children:te.id}),te.executionMode==="fast"&&t.jsx("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",children:"Fast"}),t.jsx("span",{className:"list-card-spacer"}),ht?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):St?t.jsx("span",{className:`list-status-badge list-status-badge--${te.column}${Ye?" failed":""}${xt?" pulsing":""}`,children:te.status}):null]}),t.jsx("div",{className:"list-card-row",children:t.jsx("div",{className:"list-card-title",children:te.title||te.description})}),(bt||Qt)&&t.jsxs("div",{className:"list-card-row list-card-meta",children:[bt&&t.jsxs("span",{className:"list-dep-badge",title:te.dependencies.join(", "),children:[t.jsx(ga,{size:12})," ",te.dependencies.length]}),Qt&&t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${Nt.percent}%`,backgroundColor:Va[te.column]}})}),t.jsx("span",{className:"list-progress-label",children:Nt.label})]})]})]},te.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:nt,ref:J=>{J&&(J.indeterminate=et)},onChange:Oe,"aria-label":"Select all visible tasks"})}),F.has("id")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>ne("id"),children:["ID ",ft("id")]}),F.has("title")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>ne("title"),children:["Title ",ft("title")]}),F.has("status")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>ne("status"),children:["Status ",ft("status")]}),F.has("column")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>ne("column"),children:["Column ",ft("column")]}),F.has("dependencies")&&t.jsx("th",{className:"list-header-cell",children:"Dependencies"}),F.has("progress")&&t.jsx("th",{className:"list-header-cell",children:"Progress"})]})}),t.jsx("tbody",{children:Oi.map(J=>{if(U&&J!==U||K&&(J==="done"||J==="archived")&&!U)return null;const re=me[J],ye=re.length===0;if(y&&ye)return null;const at=E.has(J);return t.jsxs(a.Fragment,{children:[t.jsx("tr",{className:`list-section-header${at?" list-section-header--collapsed":""}`,onClick:()=>be(J),"aria-expanded":!at,children:t.jsxs("th",{colSpan:F.size+1,className:"list-section-cell",children:[t.jsx(kn,{size:14,className:`list-section-chevron${at?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${J}`}),t.jsx("span",{className:"list-section-title",children:Bn[J]}),t.jsx("span",{className:"list-section-count",children:re.length})]})}),!at&&t.jsx(t.Fragment,{children:ye?t.jsx("tr",{className:"list-section-empty",children:t.jsx("td",{colSpan:F.size+1,className:"list-empty-cell",children:"No tasks"})}):re.map(te=>{const Ye=te.status==="failed",mt=te.paused===!0,ht=Po(te,x,k),xt=!r&&!Ye&&!mt&&!ht&&(te.column==="in-progress"||Hu.has(te.status)),St=C===te.id;return t.jsxs("tr",{className:`list-row${Ye?" failed":""}${mt?" paused":""}${ht?" stuck":""}${xt?" agent-active":""}${St?" dragging":""}`,onClick:()=>ce(te),draggable:!mt,onDragStart:bt=>Ie(bt,te),onDragEnd:he,"data-id":te.id,children:[t.jsx("td",{className:"list-cell list-cell-checkbox",children:t.jsx("input",{type:"checkbox",checked:Z.has(te.id),onChange:bt=>{bt.stopPropagation(),se(te.id)},onClick:bt=>bt.stopPropagation(),disabled:te.column==="archived","aria-label":`Select ${te.id}`})}),F.has("id")&&t.jsx("td",{className:"list-cell list-cell-id",children:te.id}),F.has("title")&&t.jsx("td",{className:"list-cell list-cell-title",children:t.jsxs("div",{className:"list-title-content",children:[te.executionMode==="fast"&&t.jsx("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",children:"Fast"}),t.jsx("span",{className:"list-title-text",children:te.title||te.description})]})}),F.has("status")&&t.jsx("td",{className:"list-cell",children:ht?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):te.status?t.jsx("span",{className:`list-status-badge list-status-badge--${te.column}${Ye?" failed":""}${xt?" pulsing":""}`,children:te.status}):t.jsx("span",{className:"list-status-badge",children:"-"})}),F.has("column")&&t.jsx("td",{className:"list-cell",children:t.jsx("span",{className:"list-column-badge",style:{background:`${Va[te.column]}20`,color:Va[te.column]},children:Bn[te.column]})}),F.has("dependencies")&&t.jsx("td",{className:"list-cell list-cell-deps",children:te.dependencies&&te.dependencies.length>0?t.jsxs("span",{className:"list-dep-badge",title:te.dependencies.join(", "),children:[t.jsx(ga,{size:12})," ",te.dependencies.length]}):"-"}),F.has("progress")&&t.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const bt=Gu(te);return bt.hasProgress?t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${bt.percent}%`,backgroundColor:Va[te.column]}})}),t.jsx("span",{className:"list-progress-label",children:bt.label})]}):"-"})()})]},te.id)})})]},J)})})]})]})]})}const v1={active:{label:"Active",color:"var(--success)",icon:En},paused:{label:"Paused",color:"var(--warning)",icon:qs},errored:{label:"Error",color:"var(--color-error)",icon:ps},initializing:{label:"Initializing",color:"var(--info)",icon:lt}};function y1(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 j1(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 k1(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 w1({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=v1[e.status],f=h.icon,p=a.useCallback(()=>{s(e)},[s,e]),g=a.useCallback(S=>{S.stopPropagation(),i(e)},[i,e]),b=a.useCallback(S=>{S.stopPropagation(),r(e)},[r,e]),v=a.useCallback(S=>{if(S.stopPropagation(),!d){m(!0);return}o(e),m(!1)},[d,o,e]),x=e.status==="paused",y=e.status==="errored",k=e.status==="initializing";return t.jsxs("div",{className:`project-card ${u?"project-card-loading":""} ${y?"project-card-errored":""}`,onClick:p,"data-project-id":e.id,role:"button",tabIndex:0,onKeyDown:S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),p())},children:[t.jsxs("div",{className:"project-card-header",children:[t.jsx("div",{className:"project-card-icon",children:t.jsx(Qn,{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:j1(e.path)})]}),t.jsxs("div",{className:"project-card-status-badge",style:{color:h.color,borderColor:h.color},children:[t.jsx(f,{size:12,className:k?"animate-spin":""}),t.jsx("span",{children:h.label})]})]}),t.jsxs("div",{className:"project-card-health",children:[n&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.activeTaskCount}),t.jsx("span",{className:"project-card-metric-label",children:"Active Tasks"})]}),t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.inFlightAgentCount}),t.jsx("span",{className:"project-card-metric-label",children:"Agents"})]}),t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.totalTasksCompleted}),t.jsx("span",{className:"project-card-metric-label",children:"Completed"})]})]}),!n&&t.jsx("div",{className:"project-card-metric project-card-metric-empty",children:t.jsx("span",{className:"project-card-metric-label",children:"No health data available"})})]}),t.jsxs("div",{className:"project-card-footer",children:[t.jsxs("div",{className:"project-card-activity",children:[t.jsx("span",{className:"project-card-activity-label",children:"Last activity:"}),t.jsx("span",{className:"project-card-activity-time",children:y1(e.lastActivityAt||n?.lastActivityAt)})]}),t.jsxs("div",{className:"project-card-actions",children:[x?t.jsxs("button",{className:"project-card-action project-card-action-resume",onClick:b,disabled:u,title:"Resume project","aria-label":"Resume project",children:[t.jsx(En,{size:14}),t.jsx("span",{children:"Resume"})]}):t.jsxs("button",{className:"project-card-action project-card-action-pause",onClick:g,disabled:u||k,title:k?"Cannot pause while initializing":"Pause project","aria-label":"Pause project",children:[t.jsx(qs,{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(Rr,{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(on,{size:14}),t.jsx("span",{children:d?"Confirm":""})]})]})]})]})}const N1=a.memo(w1,k1);function S1(){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(Qn,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(Ds,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(wn,{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__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 C1=1e4,Ju=5;function E1(e){const[n,s]=a.useState({}),[i,r]=a.useState(!0),[o,l]=a.useState(null),c=a.useRef(null),u=a.useRef(null),d=a.useRef(!1),m=a.useCallback(async()=>{if(e.length===0){s({}),d.current||(d.current=!0),r(!1);return}u.current&&u.current.abort(),u.current=new AbortController,!d.current&&r(!0),l(null);try{const p={};for(let g=0;g<e.length;g+=Ju){const b=e.slice(g,g+Ju),v=await Promise.allSettled(b.map(async x=>{try{return await du(x)}catch{return null}}));if(b.forEach((x,y)=>{const k=v[y];p[x]=k.status==="fulfilled"?k.value:null}),u.current?.signal.aborted)return}s(p),d.current=!0}catch(p){if(p instanceof Error&&p.name==="AbortError")return;l(p instanceof Error?p.message:"Failed to fetch health data"),d.current=!0}finally{r(!1)}},[e]),h=a.useCallback(async f=>{try{const p=await du(f);s(g=>({...g,[f]:p}))}catch(p){console.error(`Failed to fetch health for project ${f}:`,p)}},[]);return a.useEffect(()=>(d.current=!1,m(),()=>{u.current&&u.current.abort()}),[m]),a.useEffect(()=>{if(e.length!==0)return c.current&&clearInterval(c.current),c.current=setInterval(()=>{m()},C1),()=>{c.current&&(clearInterval(c.current),c.current=null)}},[m,e.length]),{healthMap:n,loading:i,error:o,refresh:m,refreshProject:h}}function _1({projects:e,loading:n=!1,onSelectProject:s,onAddProject:i,onPauseProject:r,onResumeProject:o,onRemoveProject:l,nodes:c=[]}){const[u,d]=a.useState("all"),[m,h]=a.useState(null),[f,p]=a.useState("activity"),[g,b]=a.useState("desc");a.useEffect(()=>{if(typeof window>"u")return;const q=localStorage.getItem("kb-dashboard-recent-projects");if(q)try{const D=JSON.parse(q);x(D)}catch{}},[]);const[v,x]=a.useState([]),y=a.useMemo(()=>e.map(q=>q.id),[e]),{healthMap:k,loading:S}=E1(y),_=a.useMemo(()=>e.map(q=>({project:q,health:k[q.id]||null})),[e,k]),N=a.useMemo(()=>{let q=[..._];return u!=="all"&&(q=q.filter(({project:D})=>D.status===u)),m!==null&&(q=q.filter(({project:D})=>D.nodeId===m)),q},[_,u,m]),A=a.useMemo(()=>{const q=[...N];return q.sort((D,R)=>{let F=0;switch(f){case"name":F=D.project.name.localeCompare(R.project.name);break;case"activity":{const V=D.project.lastActivityAt||D.health?.lastActivityAt||D.project.updatedAt,K=R.project.lastActivityAt||R.health?.lastActivityAt||R.project.updatedAt;F=new Date(K).getTime()-new Date(V).getTime();break}case"status":{const V={errored:0,initializing:1,paused:2,active:3};F=V[D.project.status]-V[R.project.status];break}}return g==="asc"?F:-F}),q},[N,f,g]),C=a.useMemo(()=>{const q=e.length,D=e.filter($=>$.status==="active").length,R=e.filter($=>$.status==="errored").length,F=new Set;e.forEach($=>{$.nodeId&&F.add($.nodeId)});const V=F.size||(q>0?1:0);let K=0,ee=0,E=0;return Object.values(k).forEach($=>{$&&(K+=$.activeTaskCount,ee+=$.totalTasksCompleted,E+=$.inFlightAgentCount)}),{totalProjects:q,activeProjects:D,erroredProjects:R,totalNodes:V,totalActiveTasks:K,totalCompletedTasks:ee,totalInFlightAgents:E}},[e,k]),z=a.useMemo(()=>({all:e.length,active:e.filter(q=>q.status==="active").length,paused:e.filter(q=>q.status==="paused").length,errored:e.filter(q=>q.status==="errored").length}),[e]),M=a.useMemo(()=>{const q=new Map;return e.forEach(D=>{const R=D.nodeId,F=q.get(R);if(F)F.count++;else{const K=c.find(ee=>ee.id===R)?.name??D._sourceNodeName??"Local";q.set(R,{name:K,count:1})}}),Array.from(q.entries()).map(([D,{name:R,count:F}])=>({nodeId:D??null,name:R,count:F}))},[e,c]),T=a.useCallback(q=>{const D=[q.id,...v.filter(R=>R!==q.id)].slice(0,3);x(D),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify(D)),s(q)},[s,v]);return n||S&&e.length>0&&Object.keys(k).length===0?t.jsx(S1,{}):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(or,{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(ln,{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(Qn,{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(Ds,{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(wn,{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(ps,{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(yr,{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(ln,{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:z.all})]}),t.jsxs("button",{className:`project-filter-tab ${u==="active"?"active":""}`,onClick:()=>d("active"),children:["Active",t.jsx("span",{className:"project-filter-count",children:z.active})]}),t.jsxs("button",{className:`project-filter-tab ${u==="paused"?"active":""}`,onClick:()=>d("paused"),children:["Paused",t.jsx("span",{className:"project-filter-count",children:z.paused})]}),t.jsxs("button",{className:`project-filter-tab ${u==="errored"?"active":""} ${z.errored>0?"has-errors":""}`,onClick:()=>d("errored"),children:["Errored",t.jsx("span",{className:"project-filter-count",children:z.errored})]})]}),M.length>1&&t.jsxs("div",{className:"project-node-filter",children:[t.jsx(yr,{size:14}),t.jsxs("select",{value:m??"",onChange:q=>{h(q.target.value||null)},className:"project-node-filter-select","aria-label":"Filter by node",children:[t.jsx("option",{value:"",children:"All Nodes"}),M.map(({nodeId:q,name:D,count:R})=>t.jsxs("option",{value:q??"",children:[D," (",R,")"]},q??"local"))]})]}),t.jsxs("div",{className:"project-sort",children:[t.jsx(Eo,{size:14}),t.jsxs("select",{value:`${f}-${g}`,onChange:q=>{const[D,R]=q.target.value.split("-");p(D),b(R)},className:"project-sort-select","aria-label":"Sort projects",children:[t.jsx("option",{value:"activity-desc",children:"Last Activity (Newest)"}),t.jsx("option",{value:"activity-asc",children:"Last Activity (Oldest)"}),t.jsx("option",{value:"name-asc",children:"Name (A-Z)"}),t.jsx("option",{value:"name-desc",children:"Name (Z-A)"}),t.jsx("option",{value:"status-asc",children:"Status (Error → Active)"}),t.jsx("option",{value:"status-desc",children:"Status (Active → Error)"})]}),t.jsx(np,{size:14})]})]}),t.jsx("div",{className:"project-grid",children:A.map(({project:q,health:D})=>{const R=c.find(V=>V.id===q.nodeId),F=R?void 0:q._sourceNodeName;return t.jsx(N1,{project:q,health:D,node:R,nodeNameFallback:F,onSelect:T,onPause:r,onResume:o,onRemove:l},q.id)})}),A.length===0&&t.jsxs("div",{className:"project-overview__no-results",children:[t.jsx(Eo,{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 M1=45e3,A1=3e3,R1=2e3,T1=1500,Yu="fusion:sse-client-id";let aa=null;const Si=new Map;function Qu(){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 Kp(){if(!(typeof window>"u")){if(aa)return aa;try{const e=window.sessionStorage.getItem(Yu);if(e)return aa=e,e;const n=Qu();return window.sessionStorage.setItem(Yu,n),aa=n,n}catch{return aa=Qu(),aa}}}function Gp(e){if(!(typeof window>"u"))try{return{parsed:new URL(e,window.location.origin),preserveRelativePath:e.startsWith("/")}}catch{return}}function Jp(e){return e.origin===window.location.origin&&e.pathname==="/api/events"}function P1(e){const n=Kp();if(!n)return e;const s=Gp(e);return!s||!Jp(s.parsed)?e:(s.parsed.searchParams.set("clientId",n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function bd(e,n){const s=Kp();if(!s)return;const i=Gp(e);if(!i||!Jp(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),ri(`${r.pathname}${r.search}${r.hash}`)}function I1(e){if(typeof window>"u")return;const n=bd(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 nl(e){e.keepaliveTimer&&(clearInterval(e.keepaliveTimer),e.keepaliveTimer=null)}function Xu(e){if(typeof window>"u"||typeof window.fetch!="function")return;const n=bd(e.url,"keepalive");if(!n)return;const s=typeof AbortController<"u"?new AbortController:null,i=s?window.setTimeout(()=>s.abort(),T1):null;window.fetch(n,{method:"POST",cache:"no-store",signal:s?.signal}).catch(()=>{}).finally(()=>{i!==null&&window.clearTimeout(i)})}function $1(e){nl(e),bd(e.url,"keepalive")&&(Xu(e),e.keepaliveTimer=window.setInterval(()=>{Xu(e)},R1))}if(typeof window<"u"){const e=()=>{for(const s of Array.from(Si.values()))if(!s.closed){if(nl(s),I1(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(Si.values()))i.subscribers.size!==0&&(i.closed=!1,xd(i))};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e),window.addEventListener("pageshow",n)}function dr(e){e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),e.heartbeatTimer=setTimeout(()=>{Yp(e)},M1)}function Yp(e){if(e.heartbeatTimer&&(clearTimeout(e.heartbeatTimer),e.heartbeatTimer=null),e.es&&(e.es.close(),e.es=null),nl(e),e.nativeListeners.clear(),e.closed||e.subscribers.size===0||e.reconnectTimer)return;const n=Si.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=Si.get(e.url);s&&s===e&&e.subscribers.size>0&&xd(e)},A1)}}function xd(e){if(e.es||e.closed)return;e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=null);const n=new EventSource(ri(P1(e.url)));e.es=n,$1(e),n.addEventListener("open",()=>{dr(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);Yp(e)}),n.addEventListener("message",()=>dr(e)),n.addEventListener("heartbeat",()=>dr(e)),Qp(e),dr(e)}function Qp(e){if(!e.es)return;const n=new Set;for(const s of e.subscribers)for(const i of s.events.keys())n.add(i);for(const s of n){if(e.nativeListeners.has(s))continue;const i=r=>{dr(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 D1(e){e.closed=!0,e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),nl(e),e.reconnectTimer&&clearTimeout(e.reconnectTimer),e.es&&e.es.close(),e.es=null,e.nativeListeners.clear(),Si.delete(e.url)}function Gs(e,n={}){let s=Si.get(e);s||(s={url:e,es:null,subscribers:new Set,nativeListeners:new Map,heartbeatTimer:null,keepaliveTimer:null,reconnectTimer:null,hasOpenedOnce:!1,closed:!1},Si.set(e,s));const i={events:new Map,onOpen:n.onOpen,onReconnect:n.onReconnect,onError:n.onError};if(n.events)for(const[l,c]of Object.entries(n.events)){let u=i.events.get(l);u||(u=new Set,i.events.set(l,u)),u.add(c)}s.subscribers.add(i);const r=!!s.es&&s.hasOpenedOnce;xd(s),Qp(s),r&&queueMicrotask(()=>{s.subscribers.has(i)&&i.onOpen?.()});let o=!0;return()=>{if(!o)return;o=!1;const l=Si.get(e);l&&(l.subscribers.delete(i),l.subscribers.size===0&&D1(l))}}const vd="kb-planning-last-description",yd="kb-subtask-last-description",jd="kb-mission-last-goal";function L1(e,n){ys(vd,e,n)}function z1(e){return Zn(vd,e)||""}function ra(e){Sr(vd,e)}function F1(e,n){ys(yd,e,n)}function O1(e){return Zn(yd,e)||""}function _l(e){Sr(yd,e)}function U1(e,n){ys(jd,e,n)}function B1(e){return Zn(jd,e)||""}function yi(e){Sr(jd,e)}function H1(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 q1(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 V1(e){let n=0;const s=[];for(const i of e){if(i.question){n+=1,s.push({...i,questionNumber:n});continue}i.thinkingOutput&&s.push({...i,questionNumber:null})}return s}function Ls({entries:e,defaultShowThinking:n=!1}){const[s,i]=a.useState({}),r=V1(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?H1(o):void 0,h=o.question&&m!==void 0?q1(o.question,m):"";return t.jsxs("div",{className:"conversation-entry",children:[c?t.jsxs("div",{className:"conversation-entry-question",children:[t.jsxs("span",{className:"conversation-entry-question-label",children:["Q",o.questionNumber]}),t.jsx("p",{children:o.question?.question})]}):t.jsx("div",{className:"conversation-entry-question",children:t.jsx("span",{className:"conversation-entry-question-label",children:"AI Reasoning"})}),c&&t.jsxs("div",{className:"conversation-entry-response",children:[t.jsx("strong",{children:"Your response"}),t.jsx("p",{children:h||"—"})]}),u&&t.jsxs("div",{className:"conversation-entry-thinking",children:[t.jsxs("button",{type:"button",className:"conversation-thinking-toggle",onClick:()=>{i(f=>({...f,[l]:!d}))},"aria-expanded":d,children:[t.jsx("span",{"aria-hidden":"true",children:d?"▾":"▸"}),d?`Hide ${c?"AI thinking":"AI reasoning"}`:`Show ${c?"AI thinking":"AI reasoning"}`]}),d&&t.jsx("pre",{children:o.thinkingOutput})]})]},`${o.question?.id??"thinking"}-${l}`)})})}const Zu="fusion-tab-id";function W1(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Yi(){if(typeof window>"u")return"server-tab";const e=window.sessionStorage.getItem(Zu);if(e)return e;const n=W1();return window.sessionStorage.setItem(Zu,n),n}function sl(e){const n=a.useMemo(()=>Yi(),[]),[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(fw(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=gw(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=ri(`/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:Gs("/api/events",{events:{"ai_session:updated":m=>{try{const h=JSON.parse(m.data);if(h.id!==e)return;const f=h.lockedByTab??null;o(f),i(!!(f&&f!==n))}catch{}}}}),[e,n]);const u=a.useCallback(async()=>{if(e){c(!0);try{await Promise.resolve(bw(e,n)),i(!1),o(null)}finally{c(!1)}}},[e,n]);return{isLockedByOther:s,currentHolder:r,takeControl:u,isLoading:l}}const K1="fusion:ai-session-sync",em="fusion:ai-session-sync",G1=3e4,J1=6e4;function ei(){return Date.now()}function Y1(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function tm(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 Q1{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=Y1(),this.snapshot={tabId:this.tabId,sessions:new Map,activeTabMap:new Map},this.isBrowser()&&(this.initializeTransport(),this.startHeartbeat(),this.startStaleSweep(),this.setupBeforeUnloadCleanup())}subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}getSnapshot(){return this.snapshot}requestSync(){this.publish({type:"sync:request",tabId:this.tabId,timestamp:ei()})}broadcastUpdate(n){const s=n.timestamp??ei();this.applySessionUpdate({sessionId:n.sessionId,status:n.status,needsInput:n.needsInput??n.status==="awaiting_input",owningTabId:n.owningTabId,type:n.type,title:n.title,projectId:n.projectId,updatedAt:n.updatedAt},s),this.publish({type:"session:updated",sessionId:n.sessionId,status:n.status,needsInput:n.needsInput,owningTabId:n.owningTabId,sessionType:n.type,title:n.title,projectId:n.projectId,updatedAt:n.updatedAt,timestamp:s})}broadcastCompleted(n){const s=n.status??"complete",i=n.timestamp??ei();this.applySessionUpdate({sessionId:n.sessionId,status:s,needsInput:!1,owningTabId:null},i),this.ownershipBySession.delete(n.sessionId),this.ownedSessions.delete(n.sessionId),this.emit(),this.publish({type:"session:completed",sessionId:n.sessionId,status:s,timestamp:i})}broadcastLock(n,s){const i=ei();this.applyTabOwnership(n,s,i),this.ownedSessions.set(n,s),this.publish({type:"tab:active",tabId:s,sessionId:n,timestamp:i})}broadcastUnlock(n,s){const i=ei();this.releaseTabOwnership(n,s,i),this.ownedSessions.delete(n),this.publish({type:"tab:inactive",tabId:s,sessionId:n,timestamp:i})}broadcastHeartbeat(n){const s=ei();this.updateHeartbeat(n,s),this.publish({type:"tab:heartbeat",tabId:n,timestamp:s})}destroy(){this.cleanupStorageListener?.(),this.cleanupStorageListener=null,this.cleanupBeforeUnload?.(),this.cleanupBeforeUnload=null,this.channel&&(this.channel.close(),this.channel=null),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null),this.staleSweepInterval&&(clearInterval(this.staleSweepInterval),this.staleSweepInterval=null)}reset(){this.sessionStates.clear(),this.ownershipBySession.clear(),this.heartbeatByTab.clear(),this.ownedSessions.clear(),this.snapshot={tabId:this.tabId,sessions:new Map,activeTabMap:new Map},this.emit()}isBrowser(){return typeof window<"u"}initializeTransport(){if(typeof BroadcastChannel<"u")try{this.channel=new BroadcastChannel(K1),this.channel.onmessage=s=>{const i=tm(s.data);i&&this.handleIncomingMessage(i)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==em||!s.newValue))try{const i=JSON.parse(s.newValue),r=tm(i.message);r&&this.handleIncomingMessage(r)}catch{}};window.addEventListener("storage",n),this.cleanupStorageListener=()=>{window.removeEventListener("storage",n)}}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{const n=ei();this.updateHeartbeat(this.tabId,n),this.publish({type:"tab:heartbeat",tabId:this.tabId,timestamp:n})},G1)}startStaleSweep(){this.staleSweepInterval=setInterval(()=>{this.emit()},1e4)}setupBeforeUnloadCleanup(){const n=()=>{for(const[s,i]of this.ownedSessions.entries()){const r=ei();this.publish({type:"tab:inactive",tabId:i,sessionId:s,timestamp:r})}};window.addEventListener("beforeunload",n),this.cleanupBeforeUnload=()=>{window.removeEventListener("beforeunload",n)}}publish(n){const s={...n,senderTabId:this.tabId};if(this.channel){this.channel.postMessage(s);return}if(this.usingStorageFallback)try{const i={id:`${s.type}-${s.timestamp}-${Math.random().toString(36).slice(2,8)}`,message:s};window.localStorage.setItem(em,JSON.stringify(i))}catch{}}handleIncomingMessage(n){switch(n.type){case"session:updated":{this.applySessionUpdate({sessionId:n.sessionId,status:n.status,needsInput:n.needsInput,owningTabId:n.owningTabId,type:n.sessionType,title:n.title,projectId:n.projectId,updatedAt:n.updatedAt},n.timestamp);return}case"session:completed":{this.applySessionUpdate({sessionId:n.sessionId,status:n.status??"complete",needsInput:!1,owningTabId:null},n.timestamp),this.ownershipBySession.delete(n.sessionId),this.emit();return}case"tab:active":{this.applyTabOwnership(n.sessionId,n.tabId,n.timestamp);return}case"tab:inactive":{this.releaseTabOwnership(n.sessionId,n.tabId,n.timestamp);return}case"tab:heartbeat":{this.updateHeartbeat(n.tabId,n.timestamp);return}case"sync:request":{if(n.tabId===this.tabId)return;const s=[...this.sessionStates.values()].map(o=>{const l=this.ownershipBySession.get(o.sessionId);return{...o,owningTabId:l?.tabId??o.owningTabId??null}}),i=[...this.ownershipBySession.entries()].map(([o,l])=>({sessionId:o,tabId:l.tabId,timestamp:l.timestamp})),r=[...this.heartbeatByTab.entries()].map(([o,l])=>({tabId:o,timestamp:l}));this.publish({type:"sync:response",tabId:n.tabId,sessions:s,locks:i,heartbeats:r,timestamp:ei()});return}case"sync:response":{if(n.tabId!==this.tabId)return;for(const s of n.sessions)this.applySessionUpdate({sessionId:s.sessionId,status:s.status,needsInput:s.needsInput,owningTabId:s.owningTabId,type:s.type,title:s.title,projectId:s.projectId,updatedAt:s.updatedAt},s.lastEventTimestamp,!1);for(const s of n.locks??[])this.applyTabOwnership(s.sessionId,s.tabId,s.timestamp,!1);for(const s of n.heartbeats??[])this.updateHeartbeat(s.tabId,s.timestamp,!1);this.emit();return}default:return}}applySessionUpdate(n,s,i=!0){const r=this.sessionStates.get(n.sessionId);if(r&&s<r.lastEventTimestamp)return;const o=this.ownershipBySession.get(n.sessionId),l={sessionId:n.sessionId,status:n.status,needsInput:n.needsInput??n.status==="awaiting_input",lastEventTimestamp:s,owningTabId:n.owningTabId??o?.tabId??r?.owningTabId??null,type:n.type??r?.type,title:n.title??r?.title,projectId:n.projectId??r?.projectId,updatedAt:n.updatedAt??new Date(s).toISOString()};this.sessionStates.set(n.sessionId,l),n.owningTabId!==void 0&&(n.owningTabId?this.applyTabOwnership(n.sessionId,n.owningTabId,s,!1):this.ownershipBySession.delete(n.sessionId)),i&&this.emit()}applyTabOwnership(n,s,i,r=!0){const o=this.ownershipBySession.get(n);if(o&&i<o.timestamp)return;this.ownershipBySession.set(n,{tabId:s,timestamp:i}),this.updateHeartbeat(s,i,!1);const l=this.sessionStates.get(n);l&&i>=l.lastEventTimestamp&&this.sessionStates.set(n,{...l,owningTabId:s,lastEventTimestamp:i}),r&&this.emit()}releaseTabOwnership(n,s,i,r=!0){const o=this.ownershipBySession.get(n);if(!o||o.tabId!==s||i<o.timestamp)return;this.ownershipBySession.delete(n);const l=this.sessionStates.get(n);l&&i>=l.lastEventTimestamp&&this.sessionStates.set(n,{...l,owningTabId:null,lastEventTimestamp:i}),r&&this.emit()}updateHeartbeat(n,s,i=!0){const r=this.heartbeatByTab.get(n);r!==void 0&&s<r||(this.heartbeatByTab.set(n,s),i&&this.emit())}emit(){const n=ei(),s=new Map;for(const[r,o]of this.sessionStates.entries()){const l=this.ownershipBySession.get(r);s.set(r,{...o,owningTabId:l?.tabId??o.owningTabId??null})}const i=new Map;for(const[r,o]of this.ownershipBySession.entries()){const l=this.heartbeatByTab.get(o.tabId)??o.timestamp,c=n-l>J1;i.set(r,{sessionId:r,tabId:o.tabId,lastHeartbeatTimestamp:l,lastLockTimestamp:o.timestamp,stale:c})}this.snapshot={tabId:this.tabId,sessions:s,activeTabMap:i};for(const r of this.listeners)r()}}const ti=new Q1;function Ia(){const e=a.useSyncExternalStore(c=>ti.subscribe(c),()=>ti.getSnapshot(),()=>ti.getSnapshot());a.useEffect(()=>{ti.requestSync()},[]);const n=a.useCallback(c=>{ti.broadcastUpdate(c)},[]),s=a.useCallback(c=>{ti.broadcastCompleted(c)},[]),i=a.useCallback((c,u)=>{ti.broadcastLock(c,u)},[]),r=a.useCallback((c,u)=>{ti.broadcastUnlock(c,u)},[]),o=a.useCallback(c=>{ti.broadcastHeartbeat(c)},[]),l=a.useCallback(()=>{ti.requestSync()},[]);return{tabId:e.tabId,sessions:e.sessions,activeTabMap:e.activeTabMap,broadcastUpdate:n,broadcastCompleted:s,broadcastLock:i,broadcastUnlock:r,broadcastHeartbeat:o,requestSync:l}}function X1(e,n){return e&&n?`${e}/${n}`:""}function Z1(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 e0=["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 t0({isOpen:e,onClose:n,onMissionCreated:s,projectId:i,initialGoal:r,resumeSessionId:o}){const[l,c]=a.useState(""),[u,d]=a.useState({type:"initial"}),[m,h]=a.useState(null),[f,p]=a.useState([]),[g,b]=a.useState([]),[v,x]=a.useState(null),[y,k]=a.useState(!1),S=a.useRef(!1),[_,N]=a.useState(""),[A,C]=a.useState(!0),[z,M]=a.useState(!1),[T,U]=a.useState(!1),[q,D]=a.useState(!1),R=a.useRef(null),F=a.useRef(null),V=a.useRef(null),K=a.useRef(null),[ee,E]=a.useState(o??null),$=a.useMemo(()=>Yi(),[]),{isLockedByOther:P,takeControl:w,isLoading:O}=sl(e?ee:null),{activeTabMap:Z,broadcastUpdate:Ne,broadcastCompleted:se,broadcastLock:le,broadcastUnlock:we,broadcastHeartbeat:L}=Ia(),{confirm:ne}=Ks(),[Q,be]=a.useState(void 0),[de,me]=a.useState(void 0),[ie,xe]=a.useState([]),[Re,Oe]=a.useState(!0),[nt,et]=a.useState(null),[Ze,rt]=a.useState([]),[He,Ge]=a.useState([]),oe=X1(Q,de);a.useEffect(()=>{(async()=>{try{Oe(!0);const re=await fs();xe(re.models),rt(re.favoriteProviders),Ge(re.favoriteModels)}catch(re){et(ke(re)||"Failed to load models")}finally{Oe(!1)}})()},[]);const je=a.useCallback(J=>{rt(re=>{const ye=re,te=ye.includes(J)?ye.filter(Ye=>Ye!==J):[J,...ye];return gn({favoriteProviders:te,favoriteModels:He}).catch(()=>{rt(ye)}),te})},[He]),X=a.useCallback(J=>{Ge(re=>{const ye=re,te=ye.includes(J)?ye.filter(Ye=>Ye!==J):[J,...ye];return gn({favoriteProviders:Ze,favoriteModels:te}).catch(()=>{Ge(ye)}),te})},[Ze]),Ae=a.useCallback((J,re)=>{if(!J||!re)return"Using default";const ye=ie.find(at=>at.provider===J&&at.id===re);return ye?`${ye.provider}/${ye.id}`:`${J}/${re}`},[ie]),Te=a.useCallback(J=>{F.current?.close();const re=tw(J,i,{onThinking:ye=>{N(at=>at+ye),Ne({sessionId:J,status:"generating",needsInput:!1,owningTabId:$,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onQuestion:ye=>{M(!1),U(!1),yi(i),d({type:"question",sessionId:J,question:ye}),N(""),k(!0),Ne({sessionId:J,status:"awaiting_input",needsInput:!0,owningTabId:$,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onSummary:ye=>{M(!1),U(!1),yi(i),d({type:"summary",sessionId:J,summary:ye}),x(ye),N(""),k(!0),Ne({sessionId:J,status:"complete",needsInput:!1,owningTabId:$,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onError:ye=>{const at=ye||"Session failed while contacting the AI.";M(!1),U(!1),h(null),d({type:"error",sessionId:J,errorMessage:at}),N(""),k(!0),V.current=J,Ne({sessionId:J,status:"error",needsInput:!1,owningTabId:$,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null}),se({sessionId:J,status:"error"})},onComplete:()=>{M(!1),U(!1),V.current=null,se({sessionId:J,status:"complete"})},onConnectionStateChange:ye=>{M(ye==="reconnecting")}});F.current=re},[se,Ne,l,i,$]),pe=a.useCallback(async J=>{const re=J??l;if(re.trim()){h(null),N(""),p([]),b([]),M(!1),d({type:"loading"});try{const{sessionId:ye}=await Qk(re.trim(),i,Q&&de?{modelProvider:Q,modelId:de}:void 0);V.current=ye,E(ye),yi(i),Te(ye),p([])}catch(ye){M(!1),h(ke(ye)||"Failed to start interview session"),d({type:"initial"}),V.current=null,E(null)}}},[Te,l,Q,de,i]);a.useEffect(()=>{e&&u.type==="initial"&&R.current?.focus()},[e,u.type]),a.useEffect(()=>{if(e&&r&&!S.current&&u.type==="initial"){c(r);const J=setTimeout(()=>{S.current=!0,pe(r)},0);return()=>clearTimeout(J)}else if(e&&!r&&!S.current&&u.type==="initial"){const J=B1(i);J&&c(J)}},[e,r,u.type,pe]),a.useEffect(()=>{e||(S.current=!1,M(!1),U(!1),E(null))},[e]),a.useEffect(()=>{if(!e||!o||u.type!=="initial")return;let J=!1;return fi(o).then(re=>{if(J||!re)return;const ye=ya(re.conversationHistory);if(b(ye),E(re.id),p(ye.map(at=>at.response).filter(at=>!!(at&&typeof at=="object"&&!Array.isArray(at)))),re.status==="awaiting_input"&&re.currentQuestion)try{yi(i);const at=JSON.parse(re.currentQuestion);V.current=re.id,k(!0),d({type:"question",sessionId:re.id,question:at})}catch{h("Failed to restore session question.")}else if(re.status==="complete"&&re.result)try{yi(i);const at=JSON.parse(re.result);V.current=re.id,k(!0),x(at),d({type:"summary",sessionId:re.id,summary:at})}catch{h("Failed to restore session result.")}else re.status==="generating"?(V.current=re.id,k(!0),re.thinkingOutput&&N(re.thinkingOutput),d({type:"loading"}),Te(re.id)):re.status==="error"&&(V.current=re.id,k(!0),h(null),d({type:"error",sessionId:re.id,errorMessage:re.error??"The session encountered an error."}))}).catch(()=>{J||h("Failed to resume session.")}),()=>{J=!0}},[Te,e,o,u.type,i]),a.useEffect(()=>{if(!e){K.current&&(we(K.current,$),K.current=null);return}if(ee&&K.current!==ee){K.current&&we(K.current,$),le(ee,$),K.current=ee;return}!ee&&K.current&&(we(K.current,$),K.current=null)},[le,we,e,ee,$]),a.useEffect(()=>{if(!e||!ee||K.current!==ee)return;L($);const J=setInterval(()=>{L($)},3e4);return()=>{clearInterval(J)}},[L,e,ee,$]),a.useEffect(()=>()=>{F.current?.close(),F.current=null,K.current&&(we(K.current,$),K.current=null)},[we,$]),a.useEffect(()=>{if(!e)return;const J=re=>{(u.type==="question"||u.type==="summary")&&(re.preventDefault(),re.returnValue=""),F.current?.close()};return window.addEventListener("beforeunload",J),()=>window.removeEventListener("beforeunload",J)},[e,u]);const _e=a.useCallback(()=>{F.current?.close(),F.current=null,n()},[n]),Fe=a.useCallback(async()=>{if(l&&U1(l,i),!(y&&!await ne({title:"Close Interview",message:"Are you sure you want to close? Your interview progress will be lost.",danger:!0}))){if(F.current?.close(),F.current=null,u.type==="question"||u.type==="summary"||u.type==="error")try{await _p(u.sessionId,i,$)}catch{}c(""),d({type:"initial"}),h(null),p([]),b([]),x(null),N(""),M(!1),U(!1),k(!1),D(!1),be(void 0),me(void 0),V.current=null,E(null),n()}},[l,y,u,n,i,$,ne]);a.useEffect(()=>{if(!e)return;const J=re=>{re.key==="Escape"&&Fe()};return document.addEventListener("keydown",J),()=>document.removeEventListener("keydown",J)},[e,Fe]);const it=a.useCallback(async J=>{if(u.type!=="question")return;const{sessionId:re}=u;h(null),p(ye=>[...ye,J]),b(ye=>[...ye,{question:u.question,response:J}]),d({type:"loading"}),N("");try{Te(re),await Xk(re,J,i,$),k(!0)}catch(ye){F.current?.close(),F.current=null,h(ke(ye)||"Failed to submit response"),d({type:"question",sessionId:re,question:u.question})}},[u,i,$,Te]),ve=a.useCallback(async()=>{if(u.type!=="error")return;const J=u.sessionId;h(null),U(!0),N(""),d({type:"loading"}),Te(J);try{V.current=J,E(J),await Zk(J,i,$)}catch(re){let ye=re;if((ke(re)||"").includes("not in an error state"))try{const te=await fi(J);if(!te)throw new Error("Failed to refresh interview session.");const Ye=ya(te.conversationHistory);if(b(Ye),p(Ye.map(mt=>mt.response).filter(mt=>!!(mt&&typeof mt=="object"&&!Array.isArray(mt)))),V.current=te.id,E(te.id),k(!0),te.status==="generating")N(te.thinkingOutput??""),d({type:"loading"}),F.current?.isConnected()||Te(te.id);else if(te.status==="awaiting_input"){if(!te.currentQuestion)throw new Error("Interview session is awaiting input but has no current question.");yi(i);const mt=JSON.parse(te.currentQuestion);d({type:"question",sessionId:te.id,question:mt}),F.current?.isConnected()||Te(te.id)}else if(te.status==="complete"){if(!te.result)throw new Error("Interview session is complete but has no result.");yi(i);const mt=JSON.parse(te.result);x(mt),d({type:"summary",sessionId:te.id,summary:mt})}else te.status==="error"&&d({type:"error",sessionId:te.id,errorMessage:te.error??"Retry failed. Please try again."});M(!1);return}catch(te){ye=te}F.current?.close(),F.current=null,d({type:"error",sessionId:J,errorMessage:ke(ye)||"Retry failed. Please try again."}),M(!1)}finally{U(!1)}},[Te,i,$,u]),ce=a.useCallback(async()=>{if(u.type==="summary"){h(null),D(!0);try{const J=await ew(u.sessionId,v||void 0,i);s(J),yi(i),F.current?.close(),F.current=null,c(""),d({type:"initial"}),h(null),p([]),b([]),x(null),N(""),M(!1),U(!1),k(!1),D(!1),V.current=null,E(null),n()}catch(J){h(ke(J)||"Failed to create mission"),D(!1)}}},[u,v,s,n,i]),Ie=()=>u.type==="question"?Math.min(f.length+1,6):6,he=u.type==="loading"||u.type==="question"||u.type==="summary"||u.type==="error",Me=ee?Z.get(ee):null,Je=Me&&Me.tabId!==$,$e=!!(Je&&!Me.stale),ft=P&&(!Je||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(ks,{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(Ir,{size:16})}),t.jsx("button",{className:"modal-close",onClick:Fe,"aria-label":"Close",children:t.jsx(Kt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[m&&t.jsx("div",{className:"form-error planning-error",children:m}),z&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),$e&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),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(os,{size:32,className:"icon-triage-lg"}),t.jsx("h4",{children:"Transform your vision into a structured mission"}),t.jsx("p",{className:"text-muted",children:"Describe what you want to build. The AI will interview you to understand scope, constraints, and requirements, then produce a structured plan with milestones, slices, and features."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"mission-goal",children:"What do you want to build?"}),t.jsx("textarea",{ref:R,id:"mission-goal",rows:4,className:"planning-textarea",placeholder:"e.g., Build a real-time collaborative document editor with presence, comments, and version history...",value:l,onChange: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:e0.map((J,re)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>c(J),children:J.length>45?J.slice(0,45)+"...":J},re))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"mission-interview-modal-model",className:"form-label",children:["Planning Model",Re&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(Xn,{id:"mission-interview-modal-model",label:"Planning Model",value:oe,onChange:J=>{const{provider:re,modelId:ye}=Z1(J);be(re),me(ye)},models:ie,disabled:Re,favoriteProviders:Ze,onToggleFavorite:je,favoriteModels:He,onToggleModelFavorite:X}),nt&&t.jsxs("div",{className:"form-hint form-hint-error",children:[nt," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{Oe(!0);const J=await fs();xe(J.models),rt(J.favoriteProviders),Ge(J.favoriteModels),et(null)}catch(J){et(ke(J)||"Failed to load models")}finally{Oe(!1)}})()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${Q&&de?"model-badge-custom":"model-badge-default"}`,children:Ae(Q,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(ks,{size:16,className:"icon-mr-8"}),"Start Interview"]})})]}),u.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(lt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:_?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>C(!A),type:"button",children:A?"Hide thinking":"Show thinking"}),A&&_&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:_})})]})]}),u.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[g.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ls,{entries:g}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:u.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void ve(),disabled:T,children:[T?t.jsx(lt,{size:14,className:"spin"}):t.jsx(Ln,{size:14}),t.jsx("span",{className:"icon-ml-6",children:T?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Fe,disabled:T,children:"Cancel"})]})]})]})}),u.type==="question"&&t.jsx(n0,{question:u.question,progress:Ie(),historyEntries:g,onSubmit:it}),u.type==="summary"&&v&&t.jsx(s0,{summary:v,historyEntries:g,onSummaryChange:x,onApprove:ce,onStartOver:()=>{d({type:"initial"}),k(!1),x(null),p([]),b([]),E(null),F.current?.close(),F.current=null},isCreating:q}),P&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Ko,{size:16}),t.jsx("span",{children:ft?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),ft&&t.jsx("button",{type:"button",onClick:()=>{w()},disabled:O,className:"btn btn-primary session-lock-take-control",children:O?"Taking control...":"Take Control"})]})})]})]})}):null}function n0({question:e,progress:n,historyEntries:s,onSubmit:i}){const[r,o]=a.useState({}),[l,c]=a.useState(""),u=a.useCallback(()=>{e.type==="text"?i({[e.id]:l}):e.type==="confirm"?i({[e.id]:r[e.id]===!0}):i(r)},[e,r,l,i]);a.useEffect(()=>{o({}),c("")},[e.id]);const d=()=>{switch(e.type){case"text":return l.trim().length>0;case"single_select":return r[e.id]!==void 0;case"multi_select":return Array.isArray(r[e.id])&&r[e.id].length>0;case"confirm":return r[e.id]!==void 0;default:return!0}};return t.jsxs("div",{className:"planning-question-form",children:[t.jsxs("div",{className:"planning-view-scroll planning-question-scroll",children:[s.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ls,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3,4,5,6].map(m=>t.jsx("div",{className:`planning-progress-step ${m<=n?"active":""}`},m))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~6"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:l,onChange:m=>c(m.target.value),onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&l.trim()&&(m.preventDefault(),u())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(m=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:m.id,checked:r[e.id]===m.id,onChange:()=>o({[e.id]:m.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(m=>{const h=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:m.id,checked:h.includes(m.id),onChange:f=>{const p=f.target.checked?[...h,m.id]:h.filter(g=>g!==m.id);o({[e.id]:p})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!0?"selected":""}`,onClick:()=>o({[e.id]:!0}),children:[t.jsx(wn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(Kt,{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(Rr,{size:16,className:"icon-ml-4"})]})})]})}function s0({summary:e,historyEntries:n,onSummaryChange:s,onApprove:i,onStartOver:r,isCreating:o}){const[l,c]=a.useState(()=>new Set(e.milestones.map((S,_)=>_))),[u,d]=a.useState(()=>{const S=new Set;return e.milestones.forEach((_,N)=>{_.slices.forEach((A,C)=>S.add(`${N}-${C}`))}),S}),m=S=>{c(_=>{const N=new Set(_);return N.has(S)?N.delete(S):N.add(S),N})},h=S=>{d(_=>{const N=new Set(_);return N.has(S)?N.delete(S):N.add(S),N})},f=(S,_)=>{const N=[...e.milestones];N[S]={...N[S],..._},s({...e,milestones:N})},p=(S,_,N)=>{const A=[...e.milestones],C=[...A[S].slices];C[_]={...C[_],...N},A[S]={...A[S],slices:C},s({...e,milestones:A})},g=(S,_,N,A)=>{const C=[...e.milestones],z=[...C[S].slices],M=[...z[_].features];M[N]={...M[N],...A},z[_]={...z[_],features:M},C[S]={...C[S],slices:z},s({...e,milestones:C})},b=S=>{const _=e.milestones.filter((N,A)=>A!==S);s({...e,milestones:_})},v=(S,_)=>{const N=[...e.milestones];N[S]={...N[S],slices:N[S].slices.filter((A,C)=>C!==_)},s({...e,milestones:N})},x=(S,_,N)=>{const A=[...e.milestones],C=[...A[S].slices];C[_]={...C[_],features:C[_].features.filter((z,M)=>M!==N)},A[S]={...A[S],slices:C},s({...e,milestones:A})},y=(S,_)=>{const N=[...e.milestones],A=[...N[S].slices];A[_]={...A[_],features:[...A[_].features,{title:"New feature",description:""}]},N[S]={...N[S],slices:A},s({...e,milestones:N})},k=e.milestones.reduce((S,_)=>S+_.slices.reduce((N,A)=>N+A.features.length,0),0);return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ls,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(wn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Mission Plan Ready"}),t.jsxs("p",{className:"text-muted",children:[e.milestones.length," milestones, ",k," features. Review and edit before approving."]})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Mission Title"}),t.jsx("input",{type:"text",className:"form-input",value:e.missionTitle||"",onChange:S=>s({...e,missionTitle:S.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Mission Description"}),t.jsx("textarea",{className:"planning-textarea",rows:3,value:e.missionDescription||"",onChange:S=>s({...e,missionDescription:S.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Roadmap"}),t.jsx("div",{className:"roadmap-list",children:e.milestones.map((S,_)=>t.jsxs("div",{className:"roadmap-card",children:[t.jsxs("div",{className:"roadmap-card-header",onClick:()=>m(_),children:[l.has(_)?t.jsx(sn,{size:16,className:"icon-text-secondary"}):t.jsx(kn,{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:S.title,onChange:N=>f(_,{title:N.target.value}),onClick:N=>N.stopPropagation()}),e.milestones.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:N=>{N.stopPropagation(),b(_)},title:"Remove milestone",children:t.jsx(on,{size:14,className:"icon-text-secondary"})})]}),l.has(_)&&t.jsxs("div",{className:"roadmap-card-body",children:[t.jsx("textarea",{className:"planning-textarea roadmap-textarea-md",rows:2,placeholder:"Milestone description...",value:S.description||"",onChange:N=>f(_,{description:N.target.value})}),t.jsxs("div",{className:"roadmap-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Verification Criteria"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-sm",rows:2,placeholder:"How to confirm this milestone is complete...",value:S.verification||"",onChange:N=>f(_,{verification:N.target.value})})]}),S.slices.map((N,A)=>{const C=`${_}-${A}`;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(sn,{size:14,className:"icon-text-secondary"}):t.jsx(kn,{size:14,className:"icon-text-secondary"}),t.jsx(Mc,{size:14,className:"icon-slice"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:N.title,onChange:z=>p(_,A,{title:z.target.value}),onClick:z=>z.stopPropagation()}),S.slices.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:z=>{z.stopPropagation(),v(_,A)},title:"Remove slice",children:t.jsx(on,{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:N.verification||"",onChange:z=>p(_,A,{verification:z.target.value})})]}),N.features.map((z,M)=>t.jsxs("div",{className:"roadmap-feature-row",children:[t.jsx(kc,{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:z.title,onChange:T=>g(_,A,M,{title:T.target.value})}),z.description&&t.jsx("p",{className:"roadmap-feature-text",children:z.description}),z.acceptanceCriteria&&t.jsxs("p",{className:"roadmap-feature-text--italic",children:["AC: ",z.acceptanceCriteria]})]}),t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:()=>x(_,A,M),title:"Remove feature",children:t.jsx(on,{size:12,className:"icon-text-secondary"})})]},M)),t.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>y(_,A),children:[t.jsx(ln,{size:12}),"Add Feature"]})]})]},A)})]})]},_))})]})]})]}),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(lt,{size:16,className:"spin icon-mr-8"}),"Creating Mission..."]}):t.jsxs(t.Fragment,{children:[t.jsx(wn,{size:16,className:"icon-mr-8"}),"Approve Plan"]})})]})]})}function i0({isOpen:e,onClose:n,onApplied:s,targetType:i,targetId:r,targetTitle:o,missionContext:l,projectId:c,resumeSessionId:u}){const[d,m]=a.useState({type:"initial"}),[h,f]=a.useState(null),[p,g]=a.useState([]),[b,v]=a.useState([]),[x,y]=a.useState(null),[k,S]=a.useState(""),[_,N]=a.useState(!0),[A,C]=a.useState(!1),[z,M]=a.useState(!1),T=a.useRef(null),U=a.useRef(null),q=a.useRef(null),D=a.useRef(null),[R,F]=a.useState(null),V=a.useMemo(()=>Yi(),[]);sl(e?R:null);const{activeTabMap:K,broadcastUpdate:ee,broadcastCompleted:E,broadcastLock:$,broadcastUnlock:P,broadcastHeartbeat:w}=Ia(),O=i==="milestone"?nw:ow,Z=i==="milestone"?sw:lw,Ne=i==="milestone"?iw:cw,se=i==="milestone"?aw:dw,le=i==="milestone"?rw:uw,we=i==="milestone"?"Milestone":"Slice",L=i==="milestone"?"milestone_interview":"slice_interview",ne=a.useCallback(He=>{U.current?.close();const Ge=Ne(He,c,{onThinking:oe=>{S(je=>je+oe),ee({sessionId:He,status:"generating",needsInput:!1,owningTabId:V,type:L,title:o,projectId:c??null})},onQuestion:oe=>{C(!1),Q(),m({type:"question",sessionId:He,question:oe}),S(""),ee({sessionId:He,status:"awaiting_input",needsInput:!0,owningTabId:V,type:L,title:o,projectId:c??null})},onSummary:oe=>{C(!1),Q(),m({type:"summary",sessionId:He,summary:oe}),y(oe),S(""),ee({sessionId:He,status:"complete",needsInput:!1,owningTabId:V,type:L,title:o,projectId:c??null})},onError:oe=>{const je=oe||"Session failed while contacting the AI.";C(!1),f(null),m({type:"error",sessionId:He,errorMessage:je}),S(""),q.current=He,ee({sessionId:He,status:"error",needsInput:!1,owningTabId:V,type:L,title:o,projectId:c??null}),E({sessionId:He,status:"error"})},onComplete:()=>{C(!1),q.current=null,E({sessionId:He,status:"complete"})},onConnectionStateChange:oe=>{C(oe==="reconnecting")}});U.current=Ge},[E,ee,Ne,L,c,V,o]),Q=()=>{y(null),g([]),v([]),S("")},be=a.useCallback(async()=>{f(null),Q(),C(!1),m({type:"loading"});try{const{sessionId:He}=await O(r,c);q.current=He,F(He),ne(He)}catch(He){C(!1),f(ke(He)||`Failed to start ${we.toLowerCase()} interview`),m({type:"initial"}),q.current=null,F(null)}},[ne,c,O,r,we]),de=a.useCallback(async()=>{f(null),M(!0);try{await le(r,c),s(),m({type:"applied"})}catch(He){f(ke(He)||`Failed to skip ${we.toLowerCase()} interview`),M(!1)}},[s,c,le,r,we]);a.useEffect(()=>{e&&d.type==="initial"&&T.current?.focus()},[e,d.type]),a.useEffect(()=>{if(!e||!u||d.type!=="initial")return;let He=!1;return fi(u).then(Ge=>{if(He||!Ge)return;const oe=ya(Ge.conversationHistory);if(v(oe),F(Ge.id),g(oe.map(je=>je.response).filter(je=>!!(je&&typeof je=="object"&&!Array.isArray(je)))),Ge.status==="awaiting_input"&&Ge.currentQuestion)try{const je=JSON.parse(Ge.currentQuestion);q.current=Ge.id,m({type:"question",sessionId:Ge.id,question:je})}catch{f("Failed to restore session question.")}else if(Ge.status==="complete"&&Ge.result)try{const je=JSON.parse(Ge.result);q.current=Ge.id,y(je),m({type:"summary",sessionId:Ge.id,summary:je})}catch{f("Failed to restore session result.")}else Ge.status==="generating"?(q.current=Ge.id,Ge.thinkingOutput&&S(Ge.thinkingOutput),m({type:"loading"}),ne(Ge.id)):Ge.status==="error"&&(q.current=Ge.id,f(null),m({type:"error",sessionId:Ge.id,errorMessage:Ge.error??"The session encountered an error."}))}).catch(()=>{He||f("Failed to resume session.")}),()=>{He=!0}},[ne,e,u,d.type]),a.useEffect(()=>{e||(C(!1),F(null))},[e]),a.useEffect(()=>{if(!(!e||!R)){if(D.current!==R){D.current&&P(D.current,V),$(R,V),D.current=R;return}!R&&D.current&&(P(D.current,V),D.current=null)}},[$,P,e,R,V]),a.useEffect(()=>{if(!e||!R||D.current!==R)return;w(V);const He=setInterval(()=>{w(V)},3e4);return()=>{clearInterval(He)}},[w,e,R,V]),a.useEffect(()=>()=>{U.current?.close(),U.current=null,D.current&&(P(D.current,V),D.current=null)},[P,V]);const me=a.useCallback(()=>{U.current?.close(),U.current=null,n()},[n]),ie=a.useCallback(async()=>{U.current?.close(),U.current=null,Q(),m({type:"initial"}),f(null),q.current=null,F(null),n()},[n]),xe=a.useCallback(async He=>{if(d.type!=="question")return;const{sessionId:Ge}=d;f(null),g(oe=>[...oe,He]),v(oe=>[...oe,{question:d.question,response:He}]),m({type:"loading"}),S("");try{ne(Ge),await Z(Ge,He,c,V)}catch(oe){U.current?.close(),U.current=null,f(ke(oe)||"Failed to submit response"),m({type:"question",sessionId:Ge,question:d.question})}},[ne,c,Z,V,d]),Re=a.useCallback(async()=>{if(d.type==="summary"){f(null),M(!0);try{await se(d.sessionId,x||void 0,c),s(),m({type:"applied"})}catch(He){f(ke(He)||"Failed to apply interview results"),M(!1)}}},[se,x,s,c,d]),Oe=()=>d.type==="question"?Math.min(p.length+1,6):6,nt=d.type==="loading"||d.type==="question"||d.type==="summary"||d.type==="error",et=R?K.get(R):null,rt=!!(et&&et.tabId!==V&&!et.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:He=>He.target===He.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(os,{size:20,className:"icon-triage"}),t.jsxs("h3",{children:["Plan ",we,": ",o]})]}),t.jsxs("div",{className:"modal-header-actions",children:[nt&&t.jsx("button",{className:"modal-send-to-background",onClick:me,title:"Send to background","aria-label":"Send to background",children:t.jsx(Ir,{size:16})}),t.jsx("button",{className:"modal-close",onClick:ie,"aria-label":"Close",children:t.jsx(Kt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[h&&t.jsx("div",{className:"form-error planning-error",children:h}),A&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),rt&&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(os,{size:32,className:"icon-triage-lg"}),t.jsxs("h4",{children:["Refine ",we," 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 be(),children:[t.jsx(os,{size:16,className:"icon-mr-8"}),"Start Interview"]}),t.jsxs("button",{className:"btn planning-use-context-btn",onClick:()=>void de(),disabled:z,children:[z?t.jsx(lt,{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(lt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:k?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>N(!_),type:"button",children:_?"Hide thinking":"Show thinking"}),_&&k&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:k})})]})]}),d.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[b.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ls,{entries:b}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:d.errorMessage}),t.jsx("div",{className:"ai-error-actions",children:t.jsx("button",{className:"btn",onClick:ie,children:"Cancel"})})]})]})}),d.type==="question"&&t.jsx(a0,{question:d.question,progress:Oe(),historyEntries:b,onSubmit:xe}),d.type==="summary"&&x&&t.jsx(r0,{summary:x,historyEntries:b,onSummaryChange:y,onApply:Re,onCancel:ie,isApplying:z}),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(wn,{size:48,className:"icon-success"}),t.jsxs("h4",{children:[we," 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 a0({question:e,progress:n,historyEntries:s,onSubmit:i}){const[r,o]=a.useState({}),[l,c]=a.useState(""),u=a.useCallback(()=>{e.type==="text"?i({[e.id]:l}):e.type==="confirm"?i({[e.id]:r[e.id]===!0}):i(r)},[e,r,l,i]);a.useEffect(()=>{o({}),c("")},[e.id]);const d=()=>{switch(e.type){case"text":return l.trim().length>0;case"single_select":return r[e.id]!==void 0;case"multi_select":return Array.isArray(r[e.id])&&r[e.id].length>0;case"confirm":return r[e.id]!==void 0;default:return!0}};return t.jsxs("div",{className:"planning-question-form",children:[t.jsxs("div",{className:"planning-view-scroll planning-question-scroll",children:[s.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ls,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3,4,5,6].map(m=>t.jsx("div",{className:`planning-progress-step ${m<=n?"active":""}`},m))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~6"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:l,onChange:m=>c(m.target.value),onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&l.trim()&&(m.preventDefault(),u())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(m=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:m.id,checked:r[e.id]===m.id,onChange:()=>o({[e.id]:m.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(m=>{const h=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:m.id,checked:h.includes(m.id),onChange:f=>{const p=f.target.checked?[...h,m.id]:h.filter(g=>g!==m.id);o({[e.id]:p})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!0?"selected":""}`,onClick:()=>o({[e.id]:!0}),children:[t.jsx(wn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(Kt,{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(Rr,{size:16,className:"icon-ml-4"})]})})]})}function r0({summary:e,historyEntries:n,onSummaryChange:s,onApply:i,onCancel:r,isApplying:o}){const[l,c]=a.useState(e),[u,d]=a.useState(!0),m=(h,f)=>{const p={...l,[h]:f};c(p),s(p)};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ls,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-panel",children:[t.jsx("div",{className:"planning-summary-header",children:t.jsxs("button",{className:"planning-summary-toggle",onClick:()=>d(!u),"aria-expanded":u,children:[u?t.jsx(sn,{size:16}):t.jsx(kn,{size:16}),t.jsx("span",{children:"Refined Scope"})]})}),u&&t.jsxs("div",{className:"planning-summary-content",children:[l.description&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:l.description,onChange:h=>m("description",h.target.value)})]}),l.planningNotes&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Planning Notes"}),t.jsx("textarea",{rows:3,value:l.planningNotes,onChange:h=>m("planningNotes",h.target.value)})]}),l.verification&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Verification Criteria"}),t.jsx("textarea",{rows:2,value:l.verification,onChange:h=>m("verification",h.target.value)})]}),!l.description&&!l.planningNotes&&!l.verification&&t.jsx("p",{className:"text-muted planning-summary-empty",children:"No additional details were generated for this item."})]})]})]}),t.jsxs("div",{className:"planning-view-footer",children:[t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:i,disabled:o,children:[o?t.jsx(lt,{size:16,className:"spin"}):null,"Apply"]}),t.jsx("button",{className:"btn",onClick:r,disabled:o,children:"Cancel"})]})]})}const Wa={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)"}},nm={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)"}},sm={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)"}},no={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)"}},so={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)"}},io={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)"}},im={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)"}},o0=3;function l0(e){return e==="completed"?"planned":e==="needs_update"?"needs_update":"not_started"}function am({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 rm(e){return e?e.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const Ml={title:"",description:"",status:"planning",autopilotEnabled:!1},Al={title:"",description:"",status:"planning",dependencies:[]},Rl={title:"",description:"",status:"pending"},Tl={title:"",description:"",acceptanceCriteria:"",status:"defined"},c0=3600*1e3;function $o(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 d0(e){if(!e)return"healthy";const n=typeof e.lastErrorAt=="string"&&Date.now()-new Date(e.lastErrorAt).getTime()<=c0,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 u0(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 m0(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 Pl(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 Xp=["feature_triaged","feature_completed"],Zp=["slice_activated","slice_completed","milestone_completed"],ef=["mission_started","mission_paused","mission_resumed","mission_completed"],tf=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function om(e,n){switch(n){case"errors":return e==="error"||e==="warning";case"state_changes":return ef.includes(e);case"tasks":return Xp.includes(e);case"slices":return Zp.includes(e);case"autopilot":return tf.includes(e);default:return!0}}function h0(e){return e==="error"||e==="warning"?"mission-event__type--error":ef.includes(e)?"mission-event__type--state":Xp.includes(e)?"mission-event__type--task":Zp.includes(e)?"mission-event__type--slice":tf.includes(e)?"mission-event__type--autopilot":"mission-event__type--default"}function p0(e){return e.replace(/_/g," ")}function f0(e,n){return n?e==="watching"?`Watching since ${$o(n)}`:`Last activation ${$o(n)}`:null}function g0({isOpen:e,isInline:n=!1,onClose:s,addToast:i,projectId:r,onSelectTask:o,availableTasks:l=[],resumeSessionId:c,targetMissionId:u,milestoneSliceResumeSessionId:d,onMilestoneSliceResumeFetchError:m}){const h=n||e,[f,p]=a.useState([]),[g,b]=a.useState(null),[v,x]=a.useState(!0),[y,k]=a.useState(!1),[S,_]=a.useState(!1),[N,A]=a.useState(null),[C,z]=a.useState(Ml),[M,T]=a.useState(!1),[U,q]=a.useState(new Set),[D,R]=a.useState(new Set),[F,V]=a.useState(null),[K,ee]=a.useState(Al),[E,$]=a.useState(!1),[P,w]=a.useState(null),[O,Z]=a.useState(Rl),[Ne,se]=a.useState(!1),[le,we]=a.useState(null),[L,ne]=a.useState(null),[Q,be]=a.useState(Tl),[de,me]=a.useState(!1),[ie,xe]=a.useState(null),[Re,Oe]=a.useState(null),[nt,et]=a.useState(""),[Ze,rt]=a.useState(!1),[He,Ge]=a.useState([]),[oe,je]=a.useState(void 0),X=oe??c,[Ae,Te]=a.useState(null),[pe,_e]=a.useState(null),[Fe,it]=a.useState(null);a.useEffect(()=>{h&&X&&rt(!0)},[h,X]),a.useEffect(()=>{if(!h||X)return;let B=!1;return ud(r).then(Ce=>{if(B)return;const De=Ce.filter(yt=>yt.type==="mission_interview"&&(yt.status==="awaiting_input"||yt.status==="error"));Ge(De)}).catch(Ce=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",Ce)}),()=>{B=!0}},[h,r,X]),a.useEffect(()=>{if(!h||!d)return;let B=!1;return fi(d).then(Ce=>{if(!(B||!Ce))try{const De=JSON.parse(Ce.inputPayload||"{}");De.targetId&&De.targetType&&Te({type:De.targetType,id:De.targetId,title:De.targetTitle||Ce.title,resumeSessionId:d})}catch{Te({type:"milestone",id:"",title:Ce.title,resumeSessionId:d})}}).catch(Ce=>{B||(console.warn("[MissionManager] Failed to fetch session for milestone/slice resume:",Ce),m?.())}),()=>{B=!0}},[h,d,m]);const[ve,ce]=a.useState(null),[Ie,he]=a.useState(new Map),[Me,Je]=a.useState(null),[$e,ft]=a.useState({title:"",assertion:"",status:"pending"}),[J,re]=a.useState(!1),[ye,at]=a.useState(null),[te,Ye]=a.useState(new Map),[mt,ht]=a.useState(new Set),[xt,St]=a.useState(new Set),[bt,Nt]=a.useState(null),[Qt,Pt]=a.useState(new Map),[Dt,Et]=a.useState(null),[Xt,Lt]=a.useState(null),[Ft,zt]=a.useState(!0),[Tt,Gt]=a.useState(new Set),[Ot,qt]=a.useState(new Map),[nn,ge]=a.useState(null),[ze,dt]=a.useState(new Map),[j,Y]=a.useState(null),[fe,Pe]=a.useState(new Map),[We,gt]=a.useState(new Map),[Mt,cn]=a.useState("structure"),[bn,rn]=a.useState([]),Jt=a.useRef([]),Sn=a.useRef([]),Se=a.useRef(null),ut=a.useRef(null),Zt=a.useRef("structure"),_n=a.useRef("all"),[Nn,zn]=a.useState(!1),[ss,Rn]=a.useState(0),[ue,Ke]=a.useState("all"),[pt,$t]=a.useState(new Set),Vt=a.useRef(null),dn=a.useRef(null);Sn.current=f,Se.current=g,ut.current=Dt,Zt.current=Mt,_n.current=ue;const Vn=a.useCallback((B="auto")=>{const Ce=dn.current;if(Ce&&typeof Ce.scrollIntoView=="function"){Ce.scrollIntoView({block:"end",behavior:B});return}const De=Vt.current;De&&(De.scrollTop=De.scrollHeight)},[]),$n=a.useCallback(()=>{const B=Vt.current;return B?B.scrollHeight-B.scrollTop-B.clientHeight<=100:!0},[]),Dn=a.useCallback(async B=>{if(B.length===0){gt(new Map);return}const Ce=await Nk(r);gt(De=>{const yt=new Map(De);for(const[xn,Rt]of Object.entries(Ce))u0(Rt)&&yt.set(xn,Rt);return yt})},[r]),en=a.useCallback(async()=>{try{x(!0);const B=await vk(r);p(B),Dn(B)}catch(B){i(ke(B)||"Failed to load missions","error")}finally{x(!1)}},[i,r,Dn]),Ct=a.useCallback(async B=>{try{k(!0);const Ce=await Ep(B,r);if(b(Ce),Ce.milestones.length>0){const De=Ce.milestones[0].id;Et(De),zt(!0),q(new Set([De])),bl(De,r).then(yt=>{he(xn=>{const Rt=new Map(xn);return Rt.set(De,yt),Rt})}).catch(()=>{}),xl(De,r).then(yt=>{Pt(xn=>{const Rt=new Map(xn);return Rt.set(De,yt),Rt})}).catch(()=>{}),Ce.milestones[0].slices.length>0&&R(new Set([Ce.milestones[0].slices[0].id]))}else Et(null),Lt(null)}catch(Ce){i(ke(Ce)||"Failed to load mission details","error")}finally{k(!1)}},[i,r]);a.useEffect(()=>{if(!h||!Dt){Lt(null);return}let B=!1;return Lt(null),mu(Dt,r).then(Ce=>{if(!B){if(!Pl(Ce)){Lt(null);return}Lt(Ce),Pt(De=>{const yt=new Map(De);return yt.set(Dt,Ce.rollup),yt})}}).catch(()=>{B||Lt(null)}),()=>{B=!0}},[h,Dt,r]),a.useEffect(()=>{zt(!0)},[Dt]);const pn=a.useCallback(B=>{!B||B!==ut.current||mu(B,r).then(Ce=>{ut.current!==B||!Pl(Ce)||(Lt(Ce),Pt(De=>{const yt=new Map(De);return yt.set(B,Ce.rollup),yt}))}).catch(()=>{})},[r]),W=a.useCallback(async(B,Ce)=>{const De=Ce?.append??!1,yt=De?Jt.current.length:0;De||(zn(!0),$t(new Set));try{const xn=await wk(B,{limit:50,offset:yt,eventType:void 0},r),Rt=xn.events.filter(Yt=>om(Yt.eventType,ue));rn(Yt=>{if(!De)return Rt;const Ue=new Set(Yt.map(jt=>jt.id)),Be=[...Yt];for(const jt of Rt)Ue.has(jt.id)||Be.push(jt);return Be}),Rn(xn.total),De||requestAnimationFrame(()=>{Vn("auto")})}catch(xn){i(ke(xn)||"Failed to load mission activity","error")}finally{De||zn(!1)}},[i,ue,r,Vn]);a.useEffect(()=>{Jt.current=bn},[bn]),a.useEffect(()=>{h&&(en(),b(null),Et(null),Lt(null),rn([]),Rn(0),cn("structure"),Ke("all"),$t(new Set))},[h,en]);const Le=a.useRef(null);a.useEffect(()=>{h&&u&&Le.current!==u&&f.length>0&&(Le.current=u,Ct(u))},[h,u,f,Ct]),a.useEffect(()=>{h||(Le.current=null)},[h]),a.useEffect(()=>{!h||!g||Mt!=="activity"||W(g.id)},[Mt,h,W,g,ue]),a.useEffect(()=>{if(!h||typeof EventSource>"u")return;const B=new URLSearchParams;r&&B.set("projectId",r);const Ce=`/api/events${B.size>0?`?${B.toString()}`:""}`,De=()=>{Dn(Sn.current)},yt=ns=>{De();const Mn=ns;if(Mn.data)try{const Wt=JSON.parse(Mn.data);Wt?.id&&p(Pi=>Pi.map(Ts=>Ts.id===Wt.id?{...Ts,...Wt}:Ts))}catch{}Se.current&&Ct(Se.current.id)},xn=ns=>{De(),Se.current&&Ct(Se.current.id)},Rt=()=>{De(),Se.current&&Ct(Se.current.id)},Yt=ns=>{De(),Se.current&&Ct(Se.current.id)},Ue=ns=>{const Mn=ns;if(Mn.data)try{const Wt=JSON.parse(Mn.data);Wt&&Wt.featureId&&(Qs(Wt.featureId),ui(Wt.featureId),Wt.milestoneId&&pn(Wt.milestoneId))}catch{}},Be=ns=>{const Mn=ns;if(Mn.data)try{const Wt=JSON.parse(Mn.data);Wt&&Wt.featureId&&(Qs(Wt.featureId),ui(Wt.featureId),Wt.milestoneId&&pn(Wt.milestoneId),Se.current&&Ct(Se.current.id))}catch{}},jt=ns=>{const Mn=ns;if(Mn.data)try{const Wt=JSON.parse(Mn.data);Wt&&Wt.milestoneId&&(Gn(Wt.milestoneId),pn(Wt.milestoneId))}catch{}},yn=ns=>{const Mn=ns;if(Mn.data)try{const Wt=JSON.parse(Mn.data);Wt&&Wt.milestoneId&&(In(Wt.milestoneId),Gn(Wt.milestoneId),pn(Wt.milestoneId))}catch{}};return Gs(Ce,{events:{"mission:updated":yt,"slice:updated":xn,"feature:updated":Rt,"milestone:updated":Yt,"mission:event":ns=>{De();const Mn=Se.current;if(!Mn||Zt.current!=="activity")return;const Wt=$n(),Pi=ns;if(Pi.data)try{const Ts=JSON.parse(Pi.data);if(!m0(Ts)||Ts.missionId!==Mn.id||!om(Ts.eventType,_n.current))return;rn(hi=>{const ml=hi.filter(hl=>hl.id!==Ts.id);return[Ts,...ml].slice(0,100)}),Rn(hi=>hi+1),Wt&&requestAnimationFrame(()=>{const hi=Vt.current;hi&&(hi.scrollTop=0)})}catch{}},"validator-run:started":Ue,"validator-run:completed":Be,"milestone:validation:updated":jt,"assertion:created":yn,"assertion:updated":yn,"assertion:deleted":yn,"assertion:linked":yn,"assertion:unlinked":yn,"fix-feature:created":ns=>{const Mn=ns;if(Mn.data)try{const Wt=JSON.parse(Mn.data);if(Wt&&Wt.sourceFeatureId){Qs(Wt.sourceFeatureId);const Pi=Wt?.feature?.sliceId,Ts=Se.current;if(Pi&&Ts){const hi=Ts.milestones.find(ml=>ml.slices.some(hl=>hl.id===Pi));hi&&pn(hi.id)}Se.current&&Ct(Se.current.id)}}catch{}}}})},[h,$n,Ct,Dn,r,pn]);const Qe=a.useCallback(()=>{_(!0),A(null),z(Ml)},[]),ot=a.useCallback(B=>{A(B.id),_(!1),z({title:B.title,description:B.description||"",status:B.status,autopilotEnabled:B.autopilotEnabled??!1})},[]),vt=a.useCallback(()=>{A(null),_(!1),z(Ml)},[]),_t=a.useCallback(async()=>{if(!C.title.trim()){i("Mission title is required","error");return}try{if(T(!0),S)await yk({title:C.title.trim(),description:C.description.trim()||void 0,autopilotEnabled:C.autopilotEnabled},r),i("Mission created","success");else if(N){const B={title:C.title.trim(),description:C.description.trim()||void 0,status:C.status,autopilotEnabled:C.autopilotEnabled};C.autopilotEnabled&&(B.autoAdvance=!0),await jk(N,B,r),i("Mission updated","success"),g?.id===N&&await Ct(N)}await en(),vt()}catch(B){i(ke(B)||"Failed to save mission","error")}finally{T(!1)}},[C,S,N,i,en,Ct,g,vt,r]),Ht=a.useCallback(async B=>{try{await kk(B,r),i("Mission deleted","success"),g?.id===B&&b(null),await en(),ce(null)}catch(Ce){i(ke(Ce)||"Failed to delete mission","error")}},[i,en,g,r]),Fn=a.useCallback(()=>{$(!0),V(null),ee(Al)},[]),ds=a.useCallback(B=>{V(B.id),$(!1),ee({title:B.title,description:B.description||"",status:B.status,dependencies:B.dependencies})},[]),Ns=a.useCallback(()=>{V(null),$(!1),ee(Al)},[]),Js=a.useCallback(async()=>{if(!K.title.trim()){i("Milestone title is required","error");return}try{T(!0),E&&g?(await Sk(g.id,{title:K.title.trim(),description:K.description.trim()||void 0,dependencies:K.dependencies},r),i("Milestone created","success")):F&&(await Ck(F,{title:K.title.trim(),description:K.description.trim()||void 0,status:K.status,dependencies:K.dependencies},r),i("Milestone updated","success")),await Ct(g.id),Ns()}catch(B){i(ke(B)||"Failed to save milestone","error")}finally{T(!1)}},[K,E,F,g,i,Ct,Ns,C.title,r]),ae=a.useCallback(async B=>{try{await Ek(B,r),i("Milestone deleted","success"),await Ct(g.id),ce(null)}catch(Ce){i(ke(Ce)||"Failed to delete milestone","error")}},[i,Ct,g,r]),Ee=a.useCallback(B=>{Et(B),zt(!0),q(Ce=>{const De=new Set(Ce);return!De.has(B)?(De.add(B),bl(B,r).then(xn=>{he(Rt=>{const Yt=new Map(Rt);return Yt.set(B,xn),Yt})}).catch(()=>{}),xl(B,r).then(xn=>{Pt(Rt=>{const Yt=new Map(Rt);return Yt.set(B,xn),Yt})}).catch(()=>{})):De.delete(B),De})},[r]),tt=a.useCallback(B=>{we(B),se(!0),w(null),Z(Rl)},[]),kt=a.useCallback(B=>{w(B.id),se(!1),Z({title:B.title,description:B.description||"",status:B.status})},[]),wt=a.useCallback(()=>{w(null),se(!1),we(null),Z(Rl)},[]),fn=a.useCallback(async()=>{if(!O.title.trim()){i("Slice title is required","error");return}try{T(!0),Ne&&le?(await _k(le,{title:O.title.trim(),description:O.description.trim()||void 0},r),i("Slice created","success")):P&&(await Mk(P,{title:O.title.trim(),description:O.description.trim()||void 0,status:O.status},r),i("Slice updated","success")),await Ct(g.id),wt()}catch(B){i(ke(B)||"Failed to save slice","error")}finally{T(!1)}},[O,Ne,P,le,g,i,Ct,wt,r]),un=a.useCallback(async B=>{try{await Ak(B,r),i("Slice deleted","success"),await Ct(g.id),ce(null)}catch(Ce){i(ke(Ce)||"Failed to delete slice","error")}},[i,Ct,g,r]),Xe=a.useCallback(async B=>{try{await Rk(B,r),i("Slice activated","success"),await Ct(g.id)}catch(Ce){i(ke(Ce)||"Failed to activate slice","error")}},[i,Ct,g,r]),It=a.useCallback(B=>{R(Ce=>{const De=new Set(Ce);return De.has(B)?De.delete(B):De.add(B),De})},[]),mn=a.useCallback(B=>{xe(B),me(!0),ne(null),be(Tl)},[]),es=a.useCallback(B=>{ne(B.id),me(!1),be({title:B.title,description:B.description||"",acceptanceCriteria:B.acceptanceCriteria||"",status:B.status})},[]),Hn=a.useCallback(()=>{ne(null),me(!1),xe(null),be(Tl)},[]),On=a.useCallback(async()=>{if(!Q.title.trim()){i("Feature title is required","error");return}try{T(!0),de&&ie?(await Tk(ie,{title:Q.title.trim(),description:Q.description.trim()||void 0,acceptanceCriteria:Q.acceptanceCriteria.trim()||void 0},r),i("Feature created","success")):L&&(await Pk(L,{title:Q.title.trim(),description:Q.description.trim()||void 0,acceptanceCriteria:Q.acceptanceCriteria.trim()||void 0,status:Q.status},r),i("Feature updated","success")),await Ct(g.id),Hn()}catch(B){i(ke(B)||"Failed to save feature","error")}finally{T(!1)}},[Q,de,L,ie,g,i,Ct,Hn,r]),Tn=a.useCallback(async B=>{try{await Ik(B,r),i("Feature deleted","success"),await Ct(g.id),ce(null)}catch(Ce){i(ke(Ce)||"Failed to delete feature","error")}},[i,Ct,g,r]),Wn=a.useCallback(async()=>{if(!Re||!nt.trim()){i("Task ID is required","error");return}try{await $k(Re,nt.trim(),r),i("Feature linked to task","success"),await Ct(g.id),Oe(null),et("")}catch(B){i(ke(B)||"Failed to link feature to task","error")}},[Re,nt,i,Ct,g,r]),gs=a.useCallback(async B=>{try{await Dk(B,r),i("Feature unlinked from task","success"),await Ct(g.id)}catch(Ce){i(ke(Ce)||"Failed to unlink feature","error")}},[i,Ct,g,r]),Pn=a.useCallback(async B=>{try{T(!0),await Lk(B,void 0,void 0,r),i("Feature triaged — task created","success"),await Ct(g.id)}catch(Ce){i(ke(Ce)||"Failed to triage feature","error")}finally{T(!1)}},[i,Ct,g,r]),Kn=a.useCallback(async B=>{it(B);try{const Ce=await mw(B,r);_e({featureId:B,enrichedDescription:Ce.description})}catch{await Pn(B)}finally{it(null)}},[Pn,r]),bs=a.useCallback(async()=>{pe&&(_e(null),await Pn(pe.featureId))},[Pn,pe]),zs=a.useCallback(()=>{_e(null)},[]),xs=a.useCallback(async B=>{try{T(!0);const Ce=await zk(B,r);i(`Triaged ${Ce.count} feature${Ce.count!==1?"s":""}`,"success"),await Ct(g.id)}catch(Ce){i(ke(Ce)||"Failed to triage slice features","error")}finally{T(!1)}},[i,Ct,g,r]),In=a.useCallback(async B=>{try{const Ce=await bl(B,r);he(De=>{const yt=new Map(De);return yt.set(B,Ce),yt})}catch{}},[r]),Gn=a.useCallback(async B=>{try{const Ce=await xl(B,r);Pt(De=>{const yt=new Map(De);return yt.set(B,Ce),yt})}catch{}},[r]),Fs=a.useCallback(async B=>{if(!$e.title.trim()||!$e.assertion.trim()){i("Title and assertion text are required","error");return}try{T(!0),await Fk(B,{title:$e.title.trim(),assertion:$e.assertion.trim(),status:$e.status},r),i("Assertion created","success"),await In(B),await Gn(B),re(!1),ft({title:"",assertion:"",status:"pending"})}catch(Ce){i(ke(Ce)||"Failed to create assertion","error")}finally{T(!1)}},[$e,i,In,Gn,r]),Ai=a.useCallback(B=>{Je(B.id),ft({title:B.title,assertion:B.assertion,status:B.status})},[]),Ri=a.useCallback(()=>{Je(null),re(!1),ft({title:"",assertion:"",status:"pending"})},[]),Br=a.useCallback(async(B,Ce)=>{if(!$e.title.trim()||!$e.assertion.trim()){i("Title and assertion text are required","error");return}try{T(!0),await Ok(B,{title:$e.title.trim(),assertion:$e.assertion.trim(),status:$e.status},r),i("Assertion updated","success"),await In(Ce),await Gn(Ce),Ri()}catch(De){i(ke(De)||"Failed to update assertion","error")}finally{T(!1)}},[$e,i,In,Gn,Ri,r]),Ys=a.useCallback(async B=>{try{const Ce=await Hk(B,r);Ye(De=>{const yt=new Map(De);return yt.set(B,Ce),yt})}catch{}},[r]),vi=a.useCallback(async B=>{const Ce=ye!==B;at(De=>De===B?null:B),Ce&&await Ys(B)},[ye,Ys]),Xi=a.useCallback(B=>{at(B),Ys(B),requestAnimationFrame(()=>{const Ce=document.querySelector(`[data-mission-assertion-id="${B}"]`);Ce instanceof HTMLElement&&typeof Ce.scrollIntoView=="function"&&Ce.scrollIntoView({behavior:"smooth",block:"center"})})},[Ys]),cl=a.useCallback(async(B,Ce)=>{try{ht(De=>new Set(De).add(Ce)),await Uk(B,Ce,r),i("Feature linked to assertion","success"),await Ys(Ce),Nt(null)}catch(De){i(ke(De)||"Failed to link feature","error")}finally{ht(De=>{const yt=new Set(De);return yt.delete(Ce),yt})}},[i,Ys,r]),dl=a.useCallback(async(B,Ce)=>{const De=`${B}-${Ce}`;try{St(yt=>new Set(yt).add(De)),await Bk(B,Ce,r),i("Feature unlinked from assertion","success"),await Ys(Ce)}catch(yt){i(ke(yt)||"Failed to unlink feature","error")}finally{St(yt=>{const xn=new Set(yt);return xn.delete(De),xn})}},[i,Ys,r]),Hr=a.useCallback(async B=>{try{Gt(De=>new Set(De).add(B)),await qk(B,r),i("Validation triggered","success");const Ce=await hu(B,r);qt(De=>{const yt=new Map(De);return yt.set(B,Ce),yt})}catch(Ce){i(ke(Ce)||"Failed to trigger validation","error")}finally{Gt(Ce=>{const De=new Set(Ce);return De.delete(B),De})}},[i,r]),Qs=a.useCallback(async B=>{try{const Ce=await hu(B,r);qt(De=>{const yt=new Map(De);return yt.set(B,Ce),yt})}catch{}},[r]),ui=a.useCallback(async B=>{try{const Ce=await Vk(B,{limit:10},r);dt(De=>{const yt=new Map(De);return yt.set(B,Ce),yt})}catch{}},[r]),Zi=a.useCallback(B=>{const Ce=Se.current;if(Ce){for(const De of Ce.milestones)for(const yt of De.slices)if(yt.features.find(Rt=>Rt.id===B)){q(Rt=>{const Yt=new Set(Rt);return Yt.add(De.id),Yt}),R(Rt=>{const Yt=new Set(Rt);return Yt.add(yt.id),Yt}),ge(B),Et(De.id),Qs(B),ui(B),requestAnimationFrame(()=>{const Rt=document.querySelector(`[data-mission-feature-id="${B}"]`);Rt instanceof HTMLElement&&typeof Rt.scrollIntoView=="function"&&Rt.scrollIntoView({behavior:"smooth",block:"center"})});return}}},[Qs,ui]),qr=a.useCallback(async B=>{try{const Ce=await Wk(B,r);Pe(De=>{const yt=new Map(De);return yt.set(B,Ce),yt})}catch{}},[r]),Vr=a.useCallback(async B=>{nn===B?ge(null):(ge(B),await Qs(B),await ui(B))},[nn,Qs,ui]),ts=a.useCallback(async B=>{j===B?Y(null):(Y(B),await qr(B))},[j,qr]),ea=a.useCallback(async B=>{try{await Kk(B,r),i("Mission resumed","success"),await Ct(B),en()}catch(Ce){i(ke(Ce)||"Failed to resume mission","error")}},[i,Ct,en,r]),us=a.useCallback(async B=>{try{const De=(await Gk(B,r)).pausedTaskIds?.length??0;i(`Mission stopped (${De} task${De!==1?"s":""} paused)`,"success"),await Ct(B),en()}catch(Ce){i(ke(Ce)||"Failed to stop mission","error")}},[i,Ct,en,r]),La=a.useCallback(async B=>{try{await Jk(B,r),i("Mission started — first slice activated","success"),await Ct(B),en()}catch(Ce){i(ke(Ce)||"Failed to start mission","error")}},[i,Ct,en,r]),Wr=a.useCallback(async(B,Ce)=>{try{await Yk(B,{enabled:Ce},r),i(Ce?"Autopilot enabled":"Autopilot disabled","success"),await Ct(B),en()}catch(De){i(ke(De)||"Failed to update autopilot","error")}},[i,Ct,en,r]),za=a.useCallback(B=>{cn("structure"),Et(null),Lt(null),rn([]),Rn(0),Ke("all"),$t(new Set),Ct(B.id)},[Ct]),ta=a.useCallback(()=>{b(null),Et(null),Lt(null),cn("structure"),rn([]),Rn(0),Ke("all"),$t(new Set),en()},[en]),Fa=bn.length<ss,mi=g?.autopilotState??"inactive",G=mi==="watching"||mi==="activating",qe=f0(mi,g?.lastAutopilotActivityAt),ct=a.useMemo(()=>!Xt||!Dt||!Pl(Xt)?null:Xt.rollup.milestoneId===Dt?Xt:null,[Dt,Xt]),Ut=a.useMemo(()=>{const B=new Map;for(const Ce of ct?.validationTelemetry.validationRounds??[]){const De=B.get(Ce.featureId);(!De||Ce.startedAt>De.startedAt)&&B.set(Ce.featureId,Ce)}return B},[ct]),Xs=a.useCallback(()=>{!g||Nn||!Fa||W(g.id,{append:!0})},[Nn,Fa,W,g]),Os=a.useCallback(B=>{$t(Ce=>{const De=new Set(Ce);return De.has(B)?De.delete(B):De.add(B),De})},[]),Oa=a.useCallback(B=>{B.key==="Enter"&&!B.shiftKey&&(B.preventDefault(),_t())},[_t]),Ua=a.useCallback(B=>{B.key==="Enter"&&!B.shiftKey&&(B.preventDefault(),Js())},[Js]),Kr=a.useCallback(B=>{B.key==="Enter"&&!B.shiftKey&&(B.preventDefault(),fn())},[fn]),Gr=a.useCallback(B=>{B.key==="Enter"&&!B.shiftKey&&(B.preventDefault(),On())},[On]),ul=a.useRef(null);if(a.useEffect(()=>{if(!h)return;const B=Ce=>{Ce.key==="Escape"&&s()};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[h,s]),!h)return null;const Jr=t.jsxs("div",{ref:ul,className:`mission-manager${n?" mission-manager--inline":""}`,role:n?void 0:"dialog","aria-modal":n?void 0:!0,"aria-label":n?void 0:"Mission Manager","data-testid":"mission-manager-dialog",children:[t.jsxs("div",{className:`mission-manager__header${n?" mission-manager__header--inline":""}`,children:[t.jsxs("div",{className:"mission-manager__header-title",children:[g?t.jsx("button",{className:"mission-manager__back-btn",onClick:ta,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:t.jsx(Ho,{size:18})}):null,t.jsx(ks,{size:18,className:"mission-manager__header-icon"}),t.jsx("h2",{className:"mission-manager__title",children:g?g.title:"Missions"})]}),!n&&t.jsx("button",{className:"modal-close",onClick:s,title:"Close","aria-label":"Close Mission Manager","data-testid":"mission-close-btn",children:t.jsx(Kt,{size:18})})]}),t.jsx("div",{className:"mission-manager__body",children:v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(lt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(lt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):g?t.jsxs("div",{className:"mission-detail",children:[t.jsxs("div",{className:"mission-detail__header",children:[t.jsxs("div",{className:"mission-detail__title-row",children:[t.jsxs("div",{className:"mission-detail__title-text",children:[G&&t.jsx("span",{className:"mission-detail__autopilot-dot",title:"Autopilot watching"}),t.jsx("h3",{className:"mission-detail__title",children:g.title})]}),t.jsx("span",{className:"mission-status-badge",style:{backgroundColor:(Wa[g.status]||Wa.planning).bg,color:(Wa[g.status]||Wa.planning).text},children:g.status})]}),g.description&&t.jsx("p",{className:"mission-detail__description",children:g.description}),t.jsx("div",{className:"mission-detail__meta",children:t.jsxs("span",{className:"mission-detail__meta-info",children:[g.milestones.length," milestones"]})}),t.jsxs("div",{className:"mission-detail__autopilot",children:[t.jsxs("div",{className:"mission-detail__autopilot-toggle",children:[t.jsxs("label",{className:"mission-toggle","data-testid":"mission-autopilot-toggle",children:[t.jsx("input",{type:"checkbox",checked:g.autopilotEnabled??!1,onChange:B=>Wr(g.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(Yn,{size:14,className:"mission-detail__autopilot-icon"}),"Autopilot"]})]}),t.jsxs("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(so[mi]||so.inactive).bg,color:(so[mi]||so.inactive).text},"data-testid":"autopilot-state-badge",children:[G&&t.jsx("span",{className:"mission-detail__autopilot-pulse"}),mi]})]}),qe&&t.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:qe})]}),t.jsxs("div",{className:"mission-detail__actions",children:[g.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>us(g.id),title:"Stop mission","aria-label":"Stop mission",children:t.jsx(Cs,{size:14})}),g.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>ea(g.id),title:"Resume mission","aria-label":"Resume mission",children:t.jsx(En,{size:14})}),g.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>La(g.id),title:"Start mission","aria-label":"Start mission",children:t.jsx(En,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>ot(g),title:"Edit mission","aria-label":"Edit mission",children:t.jsx(ms,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ce({type:"mission",id:g.id}),title:"Delete mission","aria-label":"Delete mission",children:t.jsx(on,{size:14})})]})]}),N===g.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:C.title,onChange:B=>z({...C,title:B.target.value}),onKeyDown:Oa,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:C.description,onChange:B=>z({...C,description:B.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:C.status,onChange:B=>z({...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=>z({...C,autopilotEnabled:B.target.checked})}),t.jsx(Yn,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:_t,disabled:M,children:[M?t.jsx(lt,{size:14,className:"spinner"}):t.jsx(qn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:vt,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-detail__tabs",role:"tablist","aria-label":"Mission detail tabs",children:[t.jsx("button",{className:`mission-btn ${Mt==="structure"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>cn("structure"),role:"tab","aria-selected":Mt==="structure","data-testid":"mission-tab-structure",children:"Structure"}),t.jsxs("button",{className:`mission-btn ${Mt==="activity"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>cn("activity"),role:"tab","aria-selected":Mt==="activity","data-testid":"mission-tab-activity",children:["Activity (",ss,")"]})]}),Mt==="structure"?t.jsxs("div",{className:"mission-detail__milestones",children:[g.milestones.map(B=>{const Ce=ct?.rollup.milestoneId===B.id?ct:null,De=Ce?.rollup??Qt.get(B.id),yt=Ce?.validationTelemetry.validationRounds??[],xn=Ce?.fixFeatures??[],Rt=im[De?.state??"not_started"]??im.not_started,Yt=De&&(De.state==="blocked"||De.state==="failed")?Ce?.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:()=>Ee(B.id),children:[t.jsx("button",{className:"mission-milestone__expand",children:U.has(B.id)?t.jsx(sn,{size:16}):t.jsx(kn,{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:nm[B.status].bg,color:nm[B.status].text},children:B.status}),t.jsxs("span",{className:"mission-milestone__count",children:[B.slices.length," slices"]}),t.jsx(am,{state:l0(B.interviewState)}),De&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Rt.bg,color:Rt.text},title:"Validation state",children:rm(De.state)}),De.totalAssertions>0&&t.jsx("div",{className:"mission-milestone__coverage-bar",title:`${De.passedAssertions??0} of ${De.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-milestone__coverage-bar-fill",style:{width:`${(De.passedAssertions??0)/De.totalAssertions*100}%`,backgroundColor:(De.passedAssertions??0)===De.totalAssertions?"var(--color-success)":"var(--color-warning)"}})})]}),B.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Te({type:"milestone",id:B.id,title:B.title}),title:"Plan milestone","aria-label":"Plan milestone",children:t.jsx(Bi,{size:14})}),t.jsxs("div",{className:"mission-milestone__actions",onClick:Ue=>Ue.stopPropagation(),children:[t.jsx("button",{className:"mission-icon-btn",onClick:()=>tt(B.id),title:"Add slice",children:t.jsx(ln,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>ds(B),title:"Edit milestone",children:t.jsx(ms,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ce({type:"milestone",id:B.id}),title:"Delete milestone",children:t.jsx(on,{size:14})})]})]}),U.has(B.id)&&t.jsxs("div",{className:"mission-milestone__body",children:[(E||F===B.id)&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:K.title,onChange:Ue=>ee({...K,title:Ue.target.value}),onKeyDown:Ua,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:K.description,onChange:Ue=>ee({...K,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:Js,disabled:M,children:[M?t.jsx(lt,{size:14,className:"spinner"}):t.jsx(qn,{size:14}),F?"Update":"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Ns,children:"Cancel"})]})]}),Ce&&t.jsxs("div",{className:"mission-validation-telemetry",children:[t.jsxs("div",{className:"mission-validation-telemetry__header",children:[t.jsx("span",{className:"mission-validation-telemetry__title",children:"Validation Telemetry"}),t.jsxs("span",{className:"mission-validation-telemetry__meta",children:[Ce.validationTelemetry.totalRuns," rounds",Ce.validationTelemetry.lastValidatorStatus?` · Last ${Ce.validationTelemetry.lastValidatorStatus}`:""]})]}),Yt&&t.jsxs("div",{className:"mission-blocked-reason",children:[t.jsx("strong",{children:"Blocked reason:"})," ",Yt]}),yt.length>0&&t.jsxs("div",{className:"mission-validation-rounds",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm mission-validation-rounds__toggle",onClick:()=>zt(Ue=>!Ue),title:Ft?"Hide validation rounds":"Show validation rounds",children:[Ft?t.jsx(sn,{size:12}):t.jsx(kn,{size:12}),"Validation rounds (",yt.length,")"]}),Ft&&t.jsx("div",{className:"mission-validation-rounds__list",children:yt.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(Be=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Xi(Be),title:`Jump to assertion ${Be}`,children:Be},`${Ue.roundId}-${Be}`))}):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(Be=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Zi(Be),title:`Jump to fix feature ${Be}`,children:Be},`${Ue.roundId}-${Be}`))}):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))})]}),xn.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:xn.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:()=>Zi(Ue.id),title:`Jump to feature ${Ue.id}`,children:Ue.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:no[Ue.status].bg,color:no[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:()=>Zi(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(Be=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Xi(Be),title:`Jump to assertion ${Be}`,children:Be},`${Ue.id}-${Be}`))})]})]},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:()=>It(Ue.id),children:[t.jsx("button",{className:"mission-slice__expand",children:D.has(Ue.id)?t.jsx(sn,{size:16}):t.jsx(kn,{size:16})}),t.jsx(Mc,{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:sm[Ue.status].bg,color:sm[Ue.status].text},children:Ue.status}),t.jsxs("span",{className:"mission-slice__count",children:[Ue.features?.length||0," features"]}),t.jsx(am,{state:Ue.planState??"not_started"}),Ue.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Te({type:"slice",id:Ue.id,title:Ue.title}),title:"Plan slice","aria-label":"Plan slice",children:t.jsx(Bi,{size:14})}),t.jsxs("div",{className:"mission-slice__actions",onClick:Be=>Be.stopPropagation(),children:[Ue.status==="pending"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Xe(Ue.id),title:"Activate slice",children:t.jsx(En,{size:14})}),Ue.status==="active"&&Ue.features?.some(Be=>Be.status==="defined")&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>xs(Ue.id),title:"Triage all features",disabled:M,children:M?t.jsx(lt,{size:14,className:"spinner"}):t.jsx(Yn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>mn(Ue.id),title:"Add feature",children:t.jsx(ln,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>kt(Ue),title:"Edit slice",children:t.jsx(ms,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ce({type:"slice",id:Ue.id}),title:"Delete slice",children:t.jsx(on,{size:14})})]})]}),D.has(Ue.id)&&t.jsxs("div",{className:"mission-slice__body",children:[Ne&&le===B.id&&!P&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:O.title,onChange:Be=>Z({...O,title:Be.target.value}),onKeyDown:Kr,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:O.description,onChange:Be=>Z({...O,description:Be.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:fn,disabled:M,children:[M?t.jsx(lt,{size:14,className:"spinner"}):t.jsx(qn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:wt,children:"Cancel"})]})]}),P===Ue.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:O.title,onChange:Be=>Z({...O,title:Be.target.value}),onKeyDown:Kr,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:O.description,onChange:Be=>Z({...O,description:Be.target.value}),rows:2}),t.jsxs("select",{value:O.status,onChange:Be=>Z({...O,status:Be.target.value}),children:[t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"complete",children:"Complete"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:fn,disabled:M,children:[M?t.jsx(lt,{size:14,className:"spinner"}):t.jsx(qn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:wt,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-features",children:[Ue.features?.map(Be=>t.jsxs("div",{className:"mission-feature","data-mission-feature-id":Be.id,children:[t.jsxs("div",{className:"mission-feature__header",children:[t.jsx("button",{className:"mission-feature__expand",onClick:()=>Vr(Be.id),title:nn===Be.id?"Collapse details":"Expand to show run history",children:nn===Be.id?t.jsx(sn,{size:14}):t.jsx(kn,{size:14})}),t.jsx(kc,{size:14,className:"mission-feature__icon"}),t.jsx("span",{className:"mission-feature__title",children:Be.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:no[Be.status].bg,color:no[Be.status].text},children:Be.status}),Be.loopState&&Be.loopState!=="idle"&&t.jsxs("span",{className:`mission-loop-state mission-loop-state--${Be.loopState}`,title:`Loop state: ${Be.loopState}`,children:[Be.loopState==="implementing"&&"⏳",Be.loopState==="validating"&&"🔄",Be.loopState==="needs_fix"&&"🔧",Be.loopState==="passed"&&"✅",Be.loopState==="blocked"&&"🚫"]}),Be.generatedFromFeatureId&&t.jsx("button",{className:"mission-feature__lineage",onClick:()=>Zi(Be.generatedFromFeatureId),title:`Generated from feature: ${Be.generatedFromFeatureId}`,children:"🔗 Fix"}),(Be.loopState==="validating"||Be.loopState==="needs_fix")&&(()=>{const jt=Ot.get(Be.id),yn=Ut.get(Be.id),Rs=jt?.implementationAttemptCount??yn?.implementationAttempt??Be.implementationAttemptCount??0,Ti=jt?.retryBudgetRemaining??Math.max(0,o0-Rs);return t.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",Rs," · ",Ti," ",Ti===1?"retry":"retries"," left"]})})(),Be.loopState==="implementing"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>Hr(Be.id),title:"Validate feature",disabled:Tt.has(Be.id),children:Tt.has(Be.id)?t.jsx(lt,{size:14,className:"spinner"}):t.jsx(os,{size:14})}),Be.taskId&&t.jsx("span",{className:"mission-feature__task-link",onClick:()=>o?.(Be.taskId),title:"Click to view task",children:Be.taskId}),t.jsxs("div",{className:"mission-feature__actions",children:[Be.status==="defined"&&!Be.taskId&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Kn(Be.id),title:"Triage — create task",disabled:M||Fe===Be.id,children:Fe===Be.id?t.jsx(lt,{size:14,className:"spinner"}):t.jsx(Yn,{size:14})}),Be.taskId?t.jsx("button",{className:"mission-icon-btn",onClick:()=>gs(Be.id),title:"Unlink task",children:t.jsx(qd,{size:14})}):Be.status!=="defined"?t.jsx("button",{className:"mission-icon-btn",onClick:()=>Oe(Be.id),title:"Link to task",children:t.jsx(ga,{size:14})}):null,t.jsx("button",{className:"mission-icon-btn",onClick:()=>es(Be),title:"Edit feature",children:t.jsx(ms,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ce({type:"feature",id:Be.id}),title:"Delete feature",children:t.jsx(on,{size:14})})]})]}),Be.description&&t.jsx("p",{className:"mission-feature__description",children:Be.description}),Be.acceptanceCriteria&&t.jsxs("p",{className:"mission-feature__criteria",children:[t.jsx("strong",{children:"Acceptance:"})," ",Be.acceptanceCriteria]}),pe?.featureId===Be.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:bs,disabled:M,children:[M?t.jsx(lt,{size:14,className:"spinner"}):null,"Create Task"]}),t.jsx("button",{className:"btn",onClick:zs,disabled:M,children:"Cancel"})]})]}),L===Be.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:Q.title,onChange:jt=>be({...Q,title:jt.target.value}),onKeyDown:Gr,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:Q.description,onChange:jt=>be({...Q,description:jt.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:Q.acceptanceCriteria,onChange:jt=>be({...Q,acceptanceCriteria:jt.target.value}),rows:2}),t.jsxs("select",{value:Q.status,onChange:jt=>be({...Q,status:jt.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:On,disabled:M,children:[M?t.jsx(lt,{size:14,className:"spinner"}):t.jsx(qn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Hn,children:"Cancel"})]})]}),nn===Be.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"})}),(ze.get(Be.id)??[]).map(jt=>t.jsxs("div",{className:"mission-run",children:[t.jsxs("div",{className:"mission-run__header",onClick:()=>ts(jt.id),children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-run__status mission-run__status--${jt.status}`,title:jt.status,children:jt.status}),t.jsx("span",{className:"mission-run__time",children:new Date(jt.startedAt).toLocaleString()}),jt.completedAt&&t.jsxs("span",{className:"mission-run__duration",children:[Math.round((new Date(jt.completedAt).getTime()-new Date(jt.startedAt).getTime())/1e3),"s"]}),jt.triggerType&&t.jsx("span",{className:"mission-run__trigger",children:jt.triggerType}),t.jsx("button",{className:"mission-icon-btn",title:j===jt.id?"Hide details":"Show details",children:j===jt.id?t.jsx(sn,{size:12}):t.jsx(kn,{size:12})})]}),j===jt.id&&fe.get(jt.id)&&t.jsxs("div",{className:"mission-run__details",children:[jt.summary&&t.jsx("p",{className:"mission-run__summary",children:jt.summary}),jt.blockedReason&&t.jsxs("p",{className:"mission-run__blocked-reason",children:[t.jsx("strong",{children:"Blocked:"})," ",jt.blockedReason]}),fe.get(jt.id)?.failures&&fe.get(jt.id).failures.length>0&&t.jsxs("div",{className:"mission-run__failures",children:[t.jsx("span",{className:"mission-run__failures-title",children:"Failed Assertions:"}),fe.get(jt.id).failures.map(yn=>t.jsxs("div",{className:"mission-run__failure",children:[t.jsx("span",{className:"mission-run__failure-message",children:yn.message}),yn.expected&&t.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",yn.expected]}),yn.actual&&t.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",yn.actual]})]},yn.id))]}),(!fe.get(jt.id)?.failures||fe.get(jt.id).failures.length===0)&&t.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},jt.id)),(!ze.get(Be.id)||ze.get(Be.id).length===0)&&t.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},Be.id)),de&&ie===Ue.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:Q.title,onChange:Be=>be({...Q,title:Be.target.value}),onKeyDown:Gr,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:Q.description,onChange:Be=>be({...Q,description:Be.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:Q.acceptanceCriteria,onChange:Be=>be({...Q,acceptanceCriteria:Be.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:On,disabled:M,children:[M?t.jsx(lt,{size:14,className:"spinner"}):t.jsx(qn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Hn,children:"Cancel"})]})]}),!de&&(!Ue.features||Ue.features.length===0)&&t.jsxs("div",{className:"mission-manager__empty mission-features__empty",children:[t.jsx(kc,{size:16}),t.jsx("span",{children:"No fix features generated."})]})]})]})]},Ue.id)),B.slices.length===0&&!Ne&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Mc,{size:16}),t.jsx("span",{children:"No slices yet"})]}),t.jsxs("div",{className:"mission-assertions",children:[t.jsxs("div",{className:"mission-assertions__header",children:[t.jsx("span",{className:"mission-assertions__title",children:"Assertions"}),De&&t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Rt.bg,color:Rt.text},children:rm(De.state)}),De&&De.totalAssertions>0&&t.jsx("div",{className:"mission-assertions__coverage-bar",title:`${De.passedAssertions??0} of ${De.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-assertions__coverage-bar-fill",style:{width:`${(De.passedAssertions??0)/De.totalAssertions*100}%`,backgroundColor:(De.passedAssertions??0)===De.totalAssertions?"var(--color-success)":"var(--color-warning)"}})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>{re(!0),Je(null),ft({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:t.jsx(ln,{size:14})})]}),J&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:$e.title,onChange:Ue=>ft({...$e,title:Ue.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:$e.assertion,onChange:Ue=>ft({...$e,assertion:Ue.target.value}),rows:2}),t.jsxs("select",{value:$e.status,onChange:Ue=>ft({...$e,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:()=>Fs(B.id),disabled:M,children:[M?t.jsx(lt,{size:14,className:"spinner"}):t.jsx(qn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Ri,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-assertions__list",children:[(Array.isArray(Ie.get(B.id))?Ie.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:$e.title,onChange:Be=>ft({...$e,title:Be.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text",value:$e.assertion,onChange:Be=>ft({...$e,assertion:Be.target.value}),rows:2}),t.jsxs("select",{value:$e.status,onChange:Be=>ft({...$e,status:Be.target.value}),children:[t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"passed",children:"Passed"}),t.jsx("option",{value:"failed",children:"Failed"}),t.jsx("option",{value:"blocked",children:"Blocked"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:()=>Br(Ue.id,B.id),disabled:M,children:[M?t.jsx(lt,{size:14,className:"spinner"}):t.jsx(qn,{size:14}),"Save"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Ri,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(io[Ue.status]??io.pending).bg,color:(io[Ue.status]??io.pending).text},children:Ue.status}),t.jsx("span",{className:"mission-assertion__title",children:Ue.title}),(()=>{const jt=te.get(Ue.id)?.length??0;return jt>0?t.jsxs("span",{className:"mission-assertion__linked-count",title:`${jt} linked feature${jt!==1?"s":""}`,children:["(",jt," linked)"]}):null})(),t.jsx("button",{className:"mission-icon-btn",onClick:()=>vi(Ue.id),title:"Toggle details",children:ye===Ue.id?t.jsx(sn,{size:14}):t.jsx(kn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ai(Ue),title:"Edit assertion",children:t.jsx(ms,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ce({type:"assertion",id:Ue.id}),title:"Delete assertion",children:t.jsx(on,{size:14})})]})}),ye===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()=>{ye!==Ue.id&&await vi(Ue.id),Nt(bt===Ue.id?null:Ue.id)},title:"Link a feature",children:[t.jsx(ga,{size:12}),"Link Feature"]})]}),bt===Ue.id&&t.jsx("div",{className:"mission-assertion__feature-picker",children:t.jsx("div",{className:"mission-assertion__feature-picker-dropdown",children:(()=>{const Be=new Set((te.get(Ue.id)??[]).map(yn=>yn.id)),jt=[];return g?.milestones.forEach(yn=>yn.slices.forEach(Rs=>jt.push(...Rs.features.filter(Ti=>!Be.has(Ti.id))))),jt.length===0?t.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):jt.map(yn=>t.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>cl(yn.id,Ue.id),disabled:mt.has(Ue.id),children:[t.jsx("span",{className:"mission-assertion__feature-picker-title",children:yn.title}),mt.has(Ue.id)&&t.jsx(lt,{size:12,className:"spinner"})]},yn.id))})()})}),(()=>{const Be=te.get(Ue.id)??[];return Be.length===0?t.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):Be.map(jt=>{const yn=`${jt.id}-${Ue.id}`,Rs=xt.has(yn);return t.jsxs("div",{className:"mission-assertion__linked-feature",children:[t.jsx("span",{className:"mission-assertion__linked-feature-title",children:jt.title}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>dl(jt.id,Ue.id),disabled:Rs,title:"Unlink feature",children:Rs?t.jsx(lt,{size:12,className:"spinner"}):t.jsx(qd,{size:12})})]},jt.id)})})()]})]})]},Ue.id)),(!Ie.get(B.id)||Ie.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)}),g&&!E&&F===null&&t.jsxs("button",{className:"mission-add-btn",onClick:Fn,children:[t.jsx(ln,{size:16}),"Add Milestone"]}),E&&F===null&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:K.title,onChange:B=>ee({...K,title:B.target.value}),onKeyDown:Ua,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:K.description,onChange:B=>ee({...K,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:Js,disabled:M,children:[M?t.jsx(lt,{size:14,className:"spinner"}):t.jsx(qn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Ns,children:"Cancel"})]})]}),g.milestones.length===0&&!E&&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:ue,onChange:B=>Ke(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:[bn.length," of ",ss]})]}),!Nn&&Fa&&t.jsx("div",{className:"mission-detail__activity-load-more mission-detail__activity-load-more--top",children:t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Xs,"data-testid":"mission-activity-load-more",children:"Load more"})}),Nn?t.jsxs("div",{className:"mission-manager__loading mission-detail__activity-loading",children:[t.jsx(lt,{size:18,className:"spinner"}),t.jsx("span",{children:"Loading mission activity..."})]}):bn.length===0?t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Ds,{size:18}),t.jsx("span",{children:"No events yet."})]}):t.jsxs("div",{ref:Vt,className:"mission-events","data-testid":"mission-activity-events",children:[bn.map(B=>{const Ce=!!(B.metadata&&Object.keys(B.metadata).length>0),De=pt.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 ${h0(B.eventType)}`,children:p0(B.eventType)}),t.jsx("span",{className:"mission-event__time",children:$o(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()}),Ce&&t.jsxs("div",{className:"mission-event__metadata",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>Os(B.id),"data-testid":`mission-event-metadata-${B.id}`,children:[De?"Hide":"Show"," metadata"]}),De&&t.jsx("pre",{className:"mission-event__metadata-content",children:JSON.stringify(B.metadata,null,2)})]})]},B.id)}),t.jsx("div",{ref:dn})]})]})]}):t.jsxs("div",{className:"mission-list",children:[S&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:C.title,onChange:B=>z({...C,title:B.target.value}),onKeyDown:Oa,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:C.description,onChange:B=>z({...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:_t,disabled:M,children:[M?t.jsx(lt,{size:14,className:"spinner"}):t.jsx(qn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:vt,children:"Cancel"})]})]}),f.map(B=>{const Ce=B,De=g,yt=De&&De.id===Ce.id,xn=Wa[Ce.status]||{bg:"",text:""},Rt=Ce.summary,Yt=We.get(Ce.id),Ue=d0(Yt),Be=!!(Rt&&(Rt.totalMilestones>0||Rt.totalFeatures>0)),jt=Yt?.totalTasks??0,yn=Yt?.tasksCompleted??0,Rs=Yt?.tasksFailed??0,Ti=Yt?.estimatedCompletionPercent??Rt?.progressPercent??0,ns=Be||jt>0||Rs>0||!!Yt?.lastActivityAt,Mn=Ce.status==="active"&&(Yt?.currentMilestoneId||Yt?.currentSliceId)?"Current milestone/slice in progress":null;return t.jsxs("div",{className:`mission-list__item ${yt?"mission-list__item--selected":""}`,onClick:()=>za(B),children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(ks,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{className:"mission-list__item-title",children:Ce.title}),B.autopilotEnabled&&t.jsx("span",{title:"Autopilot enabled",children:t.jsx(Yn,{size:12,className:"mission-list__item-autopilot-icon"})}),t.jsx("span",{className:`mission-health-badge mission-health-badge--${Ue}`,"data-testid":`mission-health-badge-${Ce.id}`,"aria-label":`Mission health: ${Ue}`}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:xn.bg,color:xn.text},children:Ce.status})]}),Ce.description&&t.jsx("p",{className:"mission-list__item-description",children:Ce.description}),Mn&&t.jsxs("p",{className:"mission-list__item-active-slice",children:["Active: ",Mn]}),ns&&t.jsxs("div",{className:"mission-list__item-summary",children:[Be&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"mission-list__item-stat",children:[Rt.completedMilestones,"/",Rt.totalMilestones," milestones"]}),t.jsxs("span",{className:"mission-list__item-stat",children:[Rt.completedFeatures,"/",Rt.totalFeatures," features"]})]}),t.jsxs("span",{className:"mission-list__item-stat","data-testid":`mission-task-stats-${Ce.id}`,children:[yn,"/",jt," tasks"]}),Rs>0&&t.jsxs("button",{className:"mission-list__item-failed",onClick:Wt=>{Wt.stopPropagation(),za(B)},"data-testid":`mission-failed-${Ce.id}`,title:"View mission failures",children:[Rs," failed"]}),t.jsxs("span",{className:"mission-relative-time","data-testid":`mission-last-activity-${Ce.id}`,children:["Activity ",$o(Yt?.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:Wt=>Wt.stopPropagation(),children:[Ce.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>us(Ce.id),title:"Stop mission",children:t.jsx(Cs,{size:14})}),Ce.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>ea(Ce.id),title:"Resume mission",children:t.jsx(En,{size:14})}),Ce.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>La(Ce.id),title:"Start mission",children:t.jsx(En,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>ot(B),title:"Edit mission",children:t.jsx(ms,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ce({type:"mission",id:Ce.id}),title:"Delete mission",children:t.jsx(on,{size:14})})]})]},Ce.id)}),N&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:C.title,onChange:B=>z({...C,title:B.target.value}),onKeyDown:Oa,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:C.description,onChange:B=>z({...C,description:B.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:C.status,onChange:B=>z({...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=>z({...C,autopilotEnabled:B.target.checked})}),t.jsx(Yn,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:_t,disabled:M,children:[M?t.jsx(lt,{size:14,className:"spinner"}):t.jsx(qn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:vt,children:"Cancel"})]})]}),f.length===0&&!S&&t.jsxs("div",{className:"mission-manager__empty mission-manager__empty--large",children:[t.jsx(ks,{size:32}),t.jsx("span",{children:"No missions yet. Create one to start planning."})]}),!S&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[He.length>0&&t.jsxs("div",{className:"mission-resume-prompt",children:[t.jsx(ps,{size:16}),t.jsx("span",{children:He.length===1?`Resume "${He[0].title}"?`:`${He.length} interview sessions pending`}),t.jsx("div",{style:{display:"flex",gap:"4px",marginLeft:"auto"},children:He.map(B=>t.jsxs("button",{className:"mission-add-btn",onClick:()=>{je(B.id),rt(!0),Ge([])},children:[B.status==="error"?t.jsx(Ln,{size:14}):t.jsx(os,{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:()=>rt(!0),children:[t.jsx(os,{size:16}),"Plan with AI"]}),t.jsxs("button",{className:"mission-add-btn",onClick:Qe,children:[t.jsx(ln,{size:16}),"New Mission"]})]})]})]})}),ve&&t.jsx("div",{className:"mission-confirm-panel mission-confirm-panel--danger",children:t.jsxs("div",{className:"mission-confirm-panel__content",children:[t.jsxs("p",{children:["Delete this ",ve.type,"? This cannot be undone."]}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--danger",onClick:async()=>{ve.type==="mission"?await Ht(ve.id):ve.type==="milestone"?await ae(ve.id):ve.type==="slice"?await un(ve.id):ve.type==="feature"&&await Tn(ve.id)},children:"Delete"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>ce(null),children:"Cancel"})]})]})}),Re&&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:nt,onChange:B=>et(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:()=>et(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:Wn,children:"Link"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>{Oe(null),et("")},children:"Cancel"})]})]})})]}),Yr=t.jsx(t0,{isOpen:Ze,onClose:()=>rt(!1),onMissionCreated:()=>{en(),i("Mission created from AI interview","success")},projectId:r,resumeSessionId:X}),na=Ae?t.jsx(i0,{isOpen:!0,onClose:()=>Te(null),onApplied:()=>{Te(null),g&&Ct(g.id)},targetType:Ae.type,targetId:Ae.id,targetTitle:Ae.title,missionContext:g?.title,projectId:r,resumeSessionId:Ae.resumeSessionId}):null;return n?t.jsxs(t.Fragment,{children:[Jr,Yr,na]}):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:Jr}),Yr,na]})}const ao=2e3;function lm({recipient:e,replyContext:n,agents:s=[],projectId:i,onSend:r,onCancel:o,addToast:l,isLoadingAgents:c=!1}){const[u,d]=a.useState(e?.id??""),[m,h]=a.useState(e?.type??"agent"),[f,p]=a.useState(""),[g,b]=a.useState(!1),[v,x]=a.useState(null),y=u.trim()!==""&&f.trim().length>0&&f.length<=ao,k=a.useCallback(async()=>{if(!(!y||g)){b(!0),x(null);try{const _=m==="agent"?"user-to-agent":"system";await jw({toId:u.trim(),toType:m,content:f.trim(),type:_,...n?{metadata:{replyTo:{messageId:n.messageId}}}:{}},i),r()}catch(_){const N=ke(_)||"Failed to send message";x(N),l?.(N,"error")}finally{b(!1)}}},[y,g,u,m,f,n,i,r,l]),S=a.useCallback(_=>{d(_),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(Kt,{size:16})})]}),t.jsxs("div",{className:"message-composer-body",children:[!e&&t.jsxs("div",{className:"message-composer-field",children:[t.jsx("label",{className:"message-composer-label",htmlFor:"message-recipient",children:"To:"}),t.jsxs("select",{id:"message-recipient",className:"message-composer-select",value:u,onChange:_=>S(_.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(_=>t.jsx("option",{value:_.id,children:_.name||_.id},_.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(Cn,{size:14}),e.id]})]}),n&&t.jsxs("div",{className:"message-composer-field","data-testid":"message-composer-reply-context",children:[t.jsx("span",{className:"message-composer-label",children:"Replying to:"}),t.jsx("span",{className:"message-composer-recipient-fixed",children:n.preview?.trim()?n.preview:`Message ${n.messageId}`})]}),t.jsxs("div",{className:"message-composer-field message-composer-field--content",children:[t.jsx("label",{className:"message-composer-label",htmlFor:"message-content",children:"Message:"}),t.jsx("textarea",{id:"message-content",className:"message-composer-textarea",placeholder:"Type your message…",value:f,onChange:_=>p(_.target.value),maxLength:ao,rows:4,"data-testid":"message-composer-content"}),t.jsx("div",{className:"message-composer-charcount","data-testid":"message-composer-charcount",children:t.jsxs("span",{className:f.length>ao?"over-limit":"",children:[f.length,"/",ao]})})]}),v&&t.jsxs("div",{className:"message-composer-error","data-testid":"message-composer-error",children:[t.jsx(ps,{size:14}),t.jsx("span",{children:v})]})]}),t.jsxs("div",{className:"message-composer-footer",children:[t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:o,"data-testid":"message-composer-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:k,disabled:!y||g,"data-testid":"message-composer-send",children:g?t.jsxs(t.Fragment,{children:[t.jsx(lt,{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 oa(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 b0(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 x0(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 cm(e,n=80){return e.length<=n?e:`${e.slice(0,n)}…`}function v0(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 y0({projectId:e,addToast:n,onUnreadCountChange:s}){const[i,r]=a.useState("inbox"),[o,l]=a.useState(null),[c,u]=a.useState(null),[d,m]=a.useState(0),[h,f]=a.useState(!1),[p,g]=a.useState(null),[b,v]=a.useState([]),[x,y]=a.useState(!1),[k,S]=a.useState(null),[_,N]=a.useState(null),[A,C]=a.useState(null),[z,M]=a.useState("inbox"),[T,U]=a.useState(null),[q,D]=a.useState([]),R=a.useMemo(()=>new Map(q.map(ie=>[ie.id,ie.name??""])),[q]),F=a.useCallback((ie,xe)=>b0(ie,xe,R),[R]),K=Ta()==="mobile",ee=!K,E=a.useCallback(async()=>{f(!0);try{const ie=await vw({limit:50},e);l(ie),m(ie.unreadCount),s?.(ie.unreadCount)}catch{}finally{f(!1)}},[e,s]),$=a.useCallback(async()=>{f(!0);try{const ie=await yw({limit:50},e);u(ie)}catch{}finally{f(!1)}},[e]),P=a.useCallback(async ie=>{f(!0);try{const xe=await Cw(ie,e);U(xe)}catch{}finally{f(!1)}},[e]),w=a.useCallback(async()=>{try{const ie=await Ra(void 0,e);D(ie)}catch{}},[e]),O=a.useCallback(async()=>{try{const ie=await Ap(e);m(ie.unreadCount),s?.(ie.unreadCount)}catch{}},[e,s]);a.useEffect(()=>{i==="inbox"?E():i==="outbox"?$():i==="agents"&&w()},[i,E,$,w]),a.useEffect(()=>{A&&P(A)},[A,P]),a.useEffect(()=>{O()},[O]),a.useEffect(()=>{w()},[w]),a.useEffect(()=>{if(typeof EventSource>"u")return;const ie=e?`?projectId=${encodeURIComponent(e)}`:"",xe=()=>{O(),i==="inbox"?E():i==="outbox"&&$(),A&&P(A)};return Gs(`/api/events${ie}`,{events:{"message:sent":xe,"message:received":xe,"message:read":xe,"message:deleted":xe}})},[e,i,A,O,E,$,P]);const Z=a.useCallback(async ie=>{if(g(ie),!ie.read)try{const xe=await kw(ie.id,e);xe&&l(Oe=>Oe&&{...Oe,messages:Oe.messages.map(nt=>nt.id===xe.id?xe:nt),unreadCount:Math.max(0,Oe.unreadCount-1)});const Re=Math.max(0,d-1);m(Re),s?.(Re)}catch{}try{const xe=await Sw(ie.fromId,ie.fromType,e);v(xe)}catch{v([ie])}},[e,d,s]),Ne=a.useCallback(()=>{g(null),v([])},[]),se=a.useCallback(async()=>{try{const ie=await ww(e);m(0),s?.(0),l(xe=>xe&&{...xe,messages:xe.messages.map(Re=>({...Re,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 Nw(ie,e),g(null),v([]),i==="inbox"?E():i==="outbox"?$():A&&P(A),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[e,i,A,E,$,P,n]),we=a.useCallback(ie=>{S({id:ie.fromId,type:ie.fromType}),N({messageId:ie.id,preview:cm(ie.content,120)}),y(!0)},[]),L=a.useCallback(()=>{y(!1),S(null),N(null),n?.("Message sent","success"),i==="outbox"?$():i==="agents"&&A&&P(A),O()},[i,$,A,P,n,O]),ne=a.useCallback(()=>{S(i==="agents"&&A?{id:A,type:"agent"}:null),N(null),y(!0)},[i,A]),Q=a.useCallback(()=>{y(!1),S(null),N(null)},[]),be=()=>!p||x?null:t.jsxs("div",{className:"mailbox-message-detail","data-testid":"mailbox-message-detail",children:[t.jsxs("div",{className:"mailbox-message-detail-header",children:[K&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:Ne,"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:x0(p.type)}),t.jsx("span",{className:"mailbox-message-time",children:oa(p.createdAt)})]}),t.jsxs("div",{className:"mailbox-message-detail-actions",children:[p.fromType==="agent"&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>we(p),"data-testid":"mailbox-reply",children:[t.jsx(Ni,{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(on,{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(Cn,{size:14}):t.jsx(sa,{size:14}),F(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(Cn,{size:14}):t.jsx(sa,{size:14}),F(p.toId,p.toType)]})]})]}),b.length>1&&t.jsxs("div",{className:"mailbox-conversation","data-testid":"mailbox-conversation",children:[t.jsx("div",{className:"mailbox-conversation-label",children:"Conversation"}),b.map(ie=>{const xe=ie.metadata?.replyTo?.messageId,Re=xe?b.find(Oe=>Oe.id===xe):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:F(ie.fromId,ie.fromType)}),t.jsx("span",{className:"mailbox-message-time",children:oa(ie.createdAt)})]}),xe&&t.jsxs("div",{className:"mailbox-reply-context","data-testid":`mailbox-reply-context-${ie.id}`,children:["↪ Replying to ",Re?cm(Re.content,60):`message ${xe}`]}),t.jsx("div",{className:"mailbox-conversation-msg-body",children:ie.content})]},ie.id)})]}),b.length<=1&&t.jsxs(t.Fragment,{children:[p.metadata?.replyTo?.messageId&&t.jsxs("div",{className:"mailbox-reply-context","data-testid":"mailbox-selected-reply-context",children:["↪ Replying to message ",p.metadata.replyTo.messageId]}),t.jsx("div",{className:"mailbox-message-body","data-testid":"mailbox-message-body",children:p.content})]})]}),de=()=>t.jsxs(t.Fragment,{children:[i==="inbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[h&&!o&&t.jsx(Il,{}),o&&o.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-inbox-empty",children:[t.jsx(or,{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:v0(o.messages).map(ie=>t.jsxs("div",{className:`mailbox-conversation-group ${ie.unreadCount>0?"unread":""}`,onClick:()=>Z(ie.latestMessage),"data-testid":`mailbox-conversation-${ie.key}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ie.fromType==="agent"?t.jsx(Cn,{size:16}):t.jsx(sa,{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:F(ie.fromId,ie.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:oa(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(Il,{}),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:()=>Z(ie),"data-testid":`mailbox-item-${ie.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ie.toType==="agent"?t.jsx(Cn,{size:16}):t.jsx(sa,{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: ",F(ie.toId,ie.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:oa(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:q.length===0?t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Cn,{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:A??"",onChange:ie=>{C(ie.target.value||null),M("inbox")},"data-testid":"mailbox-agent-select",children:[t.jsx("option",{value:"",children:"Select an agent…"}),q.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:ne,"data-testid":"mailbox-compose-btn",children:[t.jsx(Ni,{size:14}),t.jsx("span",{children:"Compose"})]})]}),A&&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 ${z==="inbox"?"active":""}`,onClick:()=>M("inbox"),"data-testid":"mailbox-agent-subtab-inbox",children:[t.jsx(or,{size:12}),t.jsx("span",{children:"Inbox"}),T&&T.unreadCount>0&&t.jsx("span",{className:"mailbox-tab-badge",children:T.unreadCount})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${z==="outbox"?"active":""}`,onClick:()=>M("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:[!A&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Cn,{size:32}),t.jsx("p",{children:"Select an agent to view their mailbox"})]}),A&&h&&!T&&t.jsx(Il,{}),A&&T&&z==="inbox"&&T.inbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(or,{size:32}),t.jsx("p",{children:"No received messages for this agent"})]}),A&&T&&z==="outbox"&&T.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"})]}),A&&T&&z==="inbox"&&T.inbox.map(ie=>t.jsxs("div",{className:`mailbox-item ${ie.read?"":"unread"}`,onClick:()=>Z(ie),"data-testid":`mailbox-item-${ie.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ie.fromType==="agent"?t.jsx(Cn,{size:16}):t.jsx(sa,{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:F(ie.fromId,ie.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:oa(ie.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ie.content.slice(0,80),ie.content.length>80?"…":""]})]})]},ie.id)),A&&T&&z==="outbox"&&T.outbox.map(ie=>t.jsxs("div",{className:"mailbox-item",onClick:()=>Z(ie),"data-testid":`mailbox-item-${ie.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ie.toType==="agent"?t.jsx(Cn,{size:16}):t.jsx(sa,{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: ",F(ie.toId,ie.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:oa(ie.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ie.content.slice(0,80),ie.content.length>80?"…":""]})]})]},ie.id))]})]})})]}),me=()=>x?t.jsx(lm,{recipient:k,replyContext:_,agents:q,projectId:e,onSend:L,onCancel:Q,addToast:n}):p?be():t.jsxs("div",{className:"mailbox-split-empty","data-testid":"mailbox-split-empty",children:[t.jsx(ba,{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(ba,{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:ne,title:"Compose message","data-testid":"mailbox-header-compose",children:[t.jsx(Ni,{size:14}),t.jsx("span",{children:"Compose"})]}),i==="inbox"&&d>0&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:se,title:"Mark all as read","data-testid":"mailbox-mark-all-read",children:[t.jsx(lb,{size:14}),t.jsx("span",{children:"Mark all read"})]}),t.jsx("button",{className:"btn-icon",onClick:()=>{i==="inbox"?E():i==="outbox"?$():A&&P(A)},disabled:h,title:"Refresh","data-testid":"mailbox-refresh",children:h?t.jsx(lt,{size:14,className:"spin"}):t.jsx(Ln,{size:14})})]})]}),t.jsxs("div",{className:"mailbox-tabs","data-testid":"mailbox-tabs",children:[t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="inbox"?"active":""}`,onClick:()=>{r("inbox"),g(null)},"data-testid":"mailbox-tab-inbox",children:[t.jsx(or,{size:14}),t.jsx("span",{children:"Inbox"}),d>0&&t.jsx("span",{className:"mailbox-tab-badge",children:d})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="outbox"?"active":""}`,onClick:()=>{r("outbox"),g(null)},"data-testid":"mailbox-tab-outbox",children:[t.jsx(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"),g(null)},"data-testid":"mailbox-tab-agents",children:[t.jsx(Cn,{size:14}),t.jsx("span",{children:"Agents"})]})]}),t.jsx("div",{className:"mailbox-content","data-testid":"mailbox-content",children:ee?t.jsxs("div",{className:"mailbox-split-layout","data-testid":"mailbox-split-layout",children:[t.jsx("div",{className:"mailbox-split-list-pane","data-testid":"mailbox-split-list-pane",children:de()}),t.jsx("div",{className:"mailbox-split-detail-pane","data-testid":"mailbox-split-detail-pane",children:me()})]}):t.jsxs(t.Fragment,{children:[be(),x&&t.jsx(lm,{recipient:k,replyContext:_,agents:q,projectId:e,onSend:L,onCancel:Q,addToast:n}),!p&&!x&&de()]})})]})}function Il(){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 ci(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 _i(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 j0(e,n){const s={};return(e[e.length-1]===""?[...e,""]:e).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const k0=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,w0=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,N0={};function dm(e,n){return(N0.jsx?w0:k0).test(e)}const S0=/[ \t\n\f\r]/g;function C0(e){return typeof e=="object"?e.type==="text"?um(e.value):!1:um(e)}function um(e){return e.replace(S0,"")===""}class Fr{constructor(n,s,i){this.normal=s,this.property=n,i&&(this.space=i)}}Fr.prototype.normal={};Fr.prototype.property={};Fr.prototype.space=void 0;function nf(e,n){const s={},i={};for(const r of e)Object.assign(s,r.property),Object.assign(i,r.normal);return new Fr(s,i,n)}function Uc(e){return e.toLowerCase()}class ws{constructor(n,s){this.attribute=s,this.property=n}}ws.prototype.attribute="";ws.prototype.booleanish=!1;ws.prototype.boolean=!1;ws.prototype.commaOrSpaceSeparated=!1;ws.prototype.commaSeparated=!1;ws.prototype.defined=!1;ws.prototype.mustUseProperty=!1;ws.prototype.number=!1;ws.prototype.overloadedBoolean=!1;ws.prototype.property="";ws.prototype.spaceSeparated=!1;ws.prototype.space=void 0;let E0=0;const Bt=Qi(),Un=Qi(),Bc=Qi(),st=Qi(),jn=Qi(),fa=Qi(),Ss=Qi();function Qi(){return 2**++E0}const Hc=Object.freeze(Object.defineProperty({__proto__:null,boolean:Bt,booleanish:Un,commaOrSpaceSeparated:Ss,commaSeparated:fa,number:st,overloadedBoolean:Bc,spaceSeparated:jn},Symbol.toStringTag,{value:"Module"})),$l=Object.keys(Hc);class kd extends ws{constructor(n,s,i,r){let o=-1;if(super(n,s),mm(this,"space",r),typeof i=="number")for(;++o<$l.length;){const l=$l[o];mm(this,$l[o],(i&Hc[l])===Hc[l])}}}kd.prototype.defined=!0;function mm(e,n,s){s&&(e[n]=s)}function $a(e){const n={},s={};for(const[i,r]of Object.entries(e.properties)){const o=new kd(i,e.transform(e.attributes||{},i),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(i)&&(o.mustUseProperty=!0),n[i]=o,s[Uc(i)]=i,s[Uc(o.attribute)]=i}return new Fr(n,s,e.space)}const sf=$a({properties:{ariaActiveDescendant:null,ariaAtomic:Un,ariaAutoComplete:null,ariaBusy:Un,ariaChecked:Un,ariaColCount:st,ariaColIndex:st,ariaColSpan:st,ariaControls:jn,ariaCurrent:null,ariaDescribedBy:jn,ariaDetails:null,ariaDisabled:Un,ariaDropEffect:jn,ariaErrorMessage:null,ariaExpanded:Un,ariaFlowTo:jn,ariaGrabbed:Un,ariaHasPopup:null,ariaHidden:Un,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:jn,ariaLevel:st,ariaLive:null,ariaModal:Un,ariaMultiLine:Un,ariaMultiSelectable:Un,ariaOrientation:null,ariaOwns:jn,ariaPlaceholder:null,ariaPosInSet:st,ariaPressed:Un,ariaReadOnly:Un,ariaRelevant:null,ariaRequired:Un,ariaRoleDescription:jn,ariaRowCount:st,ariaRowIndex:st,ariaRowSpan:st,ariaSelected:Un,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 af(e,n){return n in e?e[n]:n}function rf(e,n){return af(e,n.toLowerCase())}const _0=$a({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:fa,acceptCharset:jn,accessKey:jn,action:null,allow:null,allowFullScreen:Bt,allowPaymentRequest:Bt,allowUserMedia:Bt,alt:null,as:null,async:Bt,autoCapitalize:null,autoComplete:jn,autoFocus:Bt,autoPlay:Bt,blocking:jn,capture:null,charSet:null,checked:Bt,cite:null,className:jn,cols:st,colSpan:null,content:null,contentEditable:Un,controls:Bt,controlsList:jn,coords:st|fa,crossOrigin:null,data:null,dateTime:null,decoding:null,default:Bt,defer:Bt,dir:null,dirName:null,disabled:Bt,download:Bc,draggable:Un,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:Bt,formTarget:null,headers:jn,height:st,hidden:Bc,high:st,href:null,hrefLang:null,htmlFor:jn,httpEquiv:jn,id:null,imageSizes:null,imageSrcSet:null,inert:Bt,inputMode:null,integrity:null,is:null,isMap:Bt,itemId:null,itemProp:jn,itemRef:jn,itemScope:Bt,itemType:jn,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:Bt,low:st,manifest:null,max:null,maxLength:st,media:null,method:null,min:null,minLength:st,multiple:Bt,muted:Bt,name:null,nonce:null,noModule:Bt,noValidate:Bt,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:Bt,optimum:st,pattern:null,ping:jn,placeholder:null,playsInline:Bt,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:Bt,referrerPolicy:null,rel:jn,required:Bt,reversed:Bt,rows:st,rowSpan:st,sandbox:jn,scope:null,scoped:Bt,seamless:Bt,selected:Bt,shadowRootClonable:Bt,shadowRootDelegatesFocus:Bt,shadowRootMode:null,shape:null,size:st,sizes:null,slot:null,span:st,spellCheck:Un,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:Bt,useMap:null,value:Un,width:st,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:jn,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:Bt,declare:Bt,event:null,face:null,frame:null,frameBorder:null,hSpace:st,leftMargin:st,link:null,longDesc:null,lowSrc:null,marginHeight:st,marginWidth:st,noResize:Bt,noHref:Bt,noShade:Bt,noWrap:Bt,object:null,profile:null,prompt:null,rev:null,rightMargin:st,rules:null,scheme:null,scrolling:Un,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:Bt,disableRemotePlayback:Bt,prefix:null,property:null,results:st,security:null,unselectable:null},space:"html",transform:rf}),M0=$a({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:Ss,accentHeight: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:jn,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:Bt,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:fa,g2:fa,glyphName:fa,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:Ss,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:jn,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:st,pointsAtY:st,pointsAtZ:st,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Ss,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Ss,rev:Ss,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Ss,requiredFeatures:Ss,requiredFonts:Ss,requiredFormats:Ss,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant: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:Ss,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:Ss,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:Ss,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:af}),of=$a({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()}}),lf=$a({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:rf}),cf=$a({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,n){return"xml:"+n.slice(3).toLowerCase()}}),A0={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"},R0=/[A-Z]/g,hm=/-[a-z]/g,T0=/^data[-\w.:]+$/i;function P0(e,n){const s=Uc(n);let i=n,r=ws;if(s in e.normal)return e.property[e.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&T0.test(n)){if(n.charAt(4)==="-"){const o=n.slice(5).replace(hm,$0);i="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=n.slice(4);if(!hm.test(o)){let l=o.replace(R0,I0);l.charAt(0)!=="-"&&(l="-"+l),n="data"+l}}r=kd}return new r(i,n)}function I0(e){return"-"+e.toLowerCase()}function $0(e){return e.charAt(1).toUpperCase()}const D0=nf([sf,_0,of,lf,cf],"html"),wd=nf([sf,M0,of,lf,cf],"svg");function L0(e){return e.join(" ").trim()}var la={},Dl,pm;function z0(){if(pm)return Dl;pm=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,n=/\n/g,s=/^\s*/,i=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,r=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,l=/^[;\s]*/,c=/^\s+|\s+$/g,u=`
|
|
624
|
+
`,d="/",m="*",h="",f="comment",p="declaration";function g(v,x){if(typeof v!="string")throw new TypeError("First argument must be a string");if(!v)return[];x=x||{};var y=1,k=1;function S(D){var R=D.match(n);R&&(y+=R.length);var F=D.lastIndexOf(u);k=~F?D.length-F:k+D.length}function _(){var D={line:y,column:k};return function(R){return R.position=new N(D),z(),R}}function N(D){this.start=D,this.end={line:y,column:k},this.source=x.source}N.prototype.content=v;function A(D){var R=new Error(x.source+":"+y+":"+k+": "+D);if(R.reason=D,R.filename=x.source,R.line=y,R.column=k,R.source=v,!x.silent)throw R}function C(D){var R=D.exec(v);if(R){var F=R[0];return S(F),v=v.slice(F.length),R}}function z(){C(s)}function M(D){var R;for(D=D||[];R=T();)R!==!1&&D.push(R);return D}function T(){var D=_();if(!(d!=v.charAt(0)||m!=v.charAt(1))){for(var R=2;h!=v.charAt(R)&&(m!=v.charAt(R)||d!=v.charAt(R+1));)++R;if(R+=2,h===v.charAt(R-1))return A("End of comment missing");var F=v.slice(2,R-2);return k+=2,S(F),v=v.slice(R),k+=2,D({type:f,comment:F})}}function U(){var D=_(),R=C(i);if(R){if(T(),!C(r))return A("property missing ':'");var F=C(o),V=D({type:p,property:b(R[0].replace(e,h)),value:F?b(F[0].replace(e,h)):h});return C(l),V}}function q(){var D=[];M(D);for(var R;R=U();)R!==!1&&(D.push(R),M(D));return D}return z(),q()}function b(v){return v?v.replace(c,h):h}return Dl=g,Dl}var fm;function F0(){if(fm)return la;fm=1;var e=la&&la.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(la,"__esModule",{value:!0}),la.default=s;const n=e(z0());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 la}var Ka={},gm;function O0(){if(gm)return Ka;gm=1,Object.defineProperty(Ka,"__esModule",{value:!0}),Ka.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 Ka.camelCase=u,Ka}var Ga,bm;function U0(){if(bm)return Ga;bm=1;var e=Ga&&Ga.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},n=e(F0()),s=O0();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,Ga=i,Ga}var B0=U0();const H0=ep(B0),df=uf("end"),Nd=uf("start");function uf(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 q0(e){const n=Nd(e),s=df(e);if(n&&s)return{start:n,end:s}}function fr(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?xm(e.position):"start"in e||"end"in e?xm(e):"line"in e||"column"in e?qc(e):""}function qc(e){return vm(e&&e.line)+":"+vm(e&&e.column)}function xm(e){return qc(e&&e.start)+"-"+qc(e&&e.end)}function vm(e){return e&&typeof e=="number"?e:1}class cs 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=fr(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}}cs.prototype.file="";cs.prototype.name="";cs.prototype.reason="";cs.prototype.message="";cs.prototype.stack="";cs.prototype.column=void 0;cs.prototype.line=void 0;cs.prototype.ancestors=void 0;cs.prototype.cause=void 0;cs.prototype.fatal=void 0;cs.prototype.place=void 0;cs.prototype.ruleId=void 0;cs.prototype.source=void 0;const Sd={}.hasOwnProperty,V0=new Map,W0=/[A-Z]/g,K0=new Set(["table","tbody","thead","tfoot","tr"]),G0=new Set(["td","th"]),mf="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function J0(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=sS(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=nS(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"?wd:D0,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},o=hf(r,e,void 0);return o&&typeof o!="string"?o:r.create(e,r.Fragment,{children:o||void 0},void 0)}function hf(e,n,s){if(n.type==="element")return Y0(e,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return Q0(e,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return Z0(e,n,s);if(n.type==="mdxjsEsm")return X0(e,n);if(n.type==="root")return eS(e,n,s);if(n.type==="text")return tS(e,n)}function Y0(e,n,s){const i=e.schema;let r=i;n.tagName.toLowerCase()==="svg"&&i.space==="html"&&(r=wd,e.schema=r),e.ancestors.push(n);const o=ff(e,n.tagName,!1),l=iS(e,n);let c=Ed(e,n);return K0.has(n.tagName)&&(c=c.filter(function(u){return typeof u=="string"?!C0(u):!0})),pf(e,l,o,n),Cd(l,c),e.ancestors.pop(),e.schema=i,e.create(n,o,l,s)}function Q0(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)}Cr(e,n.position)}function X0(e,n){if(n.data&&n.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(n.data.estree);Cr(e,n.position)}function Z0(e,n,s){const i=e.schema;let r=i;n.name==="svg"&&i.space==="html"&&(r=wd,e.schema=r),e.ancestors.push(n);const o=n.name===null?e.Fragment:ff(e,n.name,!0),l=aS(e,n),c=Ed(e,n);return pf(e,l,o,n),Cd(l,c),e.ancestors.pop(),e.schema=i,e.create(n,o,l,s)}function eS(e,n,s){const i={};return Cd(i,Ed(e,n)),e.create(n,e.Fragment,i,s)}function tS(e,n){return n.value}function pf(e,n,s,i){typeof s!="string"&&s!==e.Fragment&&e.passNode&&(n.node=i)}function Cd(e,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(e.children=s)}}function nS(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 sS(e,n){return s;function s(i,r,o,l){const c=Array.isArray(o.children),u=Nd(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 iS(e,n){const s={};let i,r;for(r in n.properties)if(r!=="children"&&Sd.call(n.properties,r)){const o=rS(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 aS(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 Cr(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 Cr(e,n.position);else o=i.value===null?!0:i.value;s[r]=o}return s}function Ed(e,n){const s=[];let i=-1;const r=e.passKeys?new Map:V0;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=hf(e,o,l);c!==void 0&&s.push(c)}return s}function rS(e,n,s){const i=P0(e.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=i.commaSeparated?j0(s):L0(s)),i.property==="style"){let r=typeof s=="object"?s:oS(e,String(s));return e.stylePropertyNameCase==="css"&&(r=lS(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&i.space?A0[i.property]||i.property:i.attribute,s]}}function oS(e,n){try{return H0(n,{reactCompat:!0})}catch(s){if(e.ignoreInvalidStyle)return{};const i=s,r=new cs("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=mf+"#cannot-parse-style-attribute",r}}function ff(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=dm(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=dm(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(i.type==="Literal"){const r=i.value;return Sd.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(i);Cr(e)}function Cr(e,n){const s=new cs("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=mf+"#cannot-handle-mdx-estrees-without-createevaluater",s}function lS(e){const n={};let s;for(s in e)Sd.call(e,s)&&(n[cS(s)]=e[s]);return n}function cS(e){let n=e.replace(W0,dS);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function dS(e){return"-"+e.toLowerCase()}const Ll={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"]},uS={};function _d(e,n){const s=uS,i=typeof s.includeImageAlt=="boolean"?s.includeImageAlt:!0,r=typeof s.includeHtml=="boolean"?s.includeHtml:!0;return gf(e,i,r)}function gf(e,n,s){if(mS(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 ym(e.children,n,s)}return Array.isArray(e)?ym(e,n,s):""}function ym(e,n,s){const i=[];let r=-1;for(;++r<e.length;)i[r]=gf(e[r],n,s);return i.join("")}function mS(e){return!!(e&&typeof e=="object")}const jm=document.createElement("i");function Md(e){const n="&"+e+";";jm.innerHTML=n;const s=jm.textContent;return s.charCodeAt(s.length-1)===59&&e!=="semi"||s===n?!1:s}function Ms(e,n,s,i){const r=e.length;let o=0,l;if(n<0?n=-n>r?0:r+n:n=n>r?r:n,s=s>0?s:0,i.length<1e4)l=Array.from(i),l.unshift(n,s),e.splice(...l);else for(s&&e.splice(n,s);o<i.length;)l=i.slice(o,o+1e4),l.unshift(n,0),e.splice(...l),o+=1e4,n+=1e4}function $s(e,n){return e.length>0?(Ms(e,e.length,0,n),e):n}const km={}.hasOwnProperty;function bf(e){const n={};let s=-1;for(;++s<e.length;)hS(n,e[s]);return n}function hS(e,n){let s;for(s in n){const r=(km.call(e,s)?e[s]:void 0)||(e[s]={}),o=n[s];let l;if(o)for(l in o){km.call(r,l)||(r[l]=[]);const c=o[l];pS(r[l],Array.isArray(c)?c:c?[c]:[])}}}function pS(e,n){let s=-1;const i=[];for(;++s<n.length;)(n[s].add==="after"?e:i).push(n[s]);Ms(e,0,0,i)}function xf(e,n){const s=Number.parseInt(e,n);return s<9||s===11||s>13&&s<32||s>126&&s<160||s>55295&&s<57344||s>64975&&s<65008||(s&65535)===65535||(s&65535)===65534||s>1114111?"�":String.fromCodePoint(s)}function Vs(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const hs=Mi(/[A-Za-z]/),rs=Mi(/[\dA-Za-z]/),fS=Mi(/[#-'*+\--9=?A-Z^-~]/);function Do(e){return e!==null&&(e<32||e===127)}const Vc=Mi(/\d/),gS=Mi(/[\dA-Fa-f]/),bS=Mi(/[!-/:-@[-`{-~]/);function At(e){return e!==null&&e<-2}function vn(e){return e!==null&&(e<0||e===32)}function tn(e){return e===-2||e===-1||e===32}const il=Mi(/\p{P}|\p{S}/u),Ki=Mi(/\s/);function Mi(e){return n;function n(s){return s!==null&&s>-1&&e.test(String.fromCharCode(s))}}function Da(e){const n=[];let s=-1,i=0,r=0;for(;++s<e.length;){const o=e.charCodeAt(s);let l="";if(o===37&&rs(e.charCodeAt(s+1))&&rs(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 an(e,n,s,i){const r=i?i-1:Number.POSITIVE_INFINITY;let o=0;return l;function l(u){return tn(u)?(e.enter(s),c(u)):n(u)}function c(u){return tn(u)&&o++<r?(e.consume(u),c):(e.exit(s),n(u))}}const xS={tokenize:vS};function vS(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"),an(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 At(c)?(e.consume(c),e.exit("chunkText"),o):(e.consume(c),l)}}const yS={tokenize:jS},wm={tokenize:kS};function jS(e){const n=this,s=[];let i=0,r,o,l;return c;function c(k){if(i<s.length){const S=s[i];return n.containerState=S[1],e.attempt(S[0].continuation,u,d)(k)}return d(k)}function u(k){if(i++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,r&&y();const S=n.events.length;let _=S,N;for(;_--;)if(n.events[_][0]==="exit"&&n.events[_][1].type==="chunkFlow"){N=n.events[_][1].end;break}x(i);let A=S;for(;A<n.events.length;)n.events[A][1].end={...N},A++;return Ms(n.events,_+1,0,n.events.slice(S)),n.events.length=A,d(k)}return c(k)}function d(k){if(i===s.length){if(!r)return f(k);if(r.currentConstruct&&r.currentConstruct.concrete)return g(k);n.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return n.containerState={},e.check(wm,m,h)(k)}function m(k){return r&&y(),x(i),f(k)}function h(k){return n.parser.lazy[n.now().line]=i!==s.length,l=n.now().offset,g(k)}function f(k){return n.containerState={},e.attempt(wm,p,g)(k)}function p(k){return i++,s.push([n.currentConstruct,n.containerState]),f(k)}function g(k){if(k===null){r&&y(),x(0),e.consume(k);return}return r=r||n.parser.flow(n.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:o}),b(k)}function b(k){if(k===null){v(e.exit("chunkFlow"),!0),x(0),e.consume(k);return}return At(k)?(e.consume(k),v(e.exit("chunkFlow")),i=0,n.interrupt=void 0,c):(e.consume(k),b)}function v(k,S){const _=n.sliceStream(k);if(S&&_.push(null),k.previous=o,o&&(o.next=k),o=k,r.defineSkip(k.start),r.write(_),n.parser.lazy[k.start.line]){let N=r.events.length;for(;N--;)if(r.events[N][1].start.offset<l&&(!r.events[N][1].end||r.events[N][1].end.offset>l))return;const A=n.events.length;let C=A,z,M;for(;C--;)if(n.events[C][0]==="exit"&&n.events[C][1].type==="chunkFlow"){if(z){M=n.events[C][1].end;break}z=!0}for(x(i),N=A;N<n.events.length;)n.events[N][1].end={...M},N++;Ms(n.events,C+1,0,n.events.slice(A)),n.events.length=N}}function x(k){let S=s.length;for(;S-- >k;){const _=s[S];n.containerState=_[1],_[0].exit.call(n,e)}s.length=k}function y(){r.write([null]),o=void 0,r=void 0,n.containerState._closeFlow=void 0}}function kS(e,n,s){return an(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||vn(e)||Ki(e))return 1;if(il(e))return 2}function al(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 Wc={name:"attention",resolveAll:wS,tokenize:NS};function wS(e,n){let s=-1,i,r,o,l,c,u,d,m;for(;++s<e.length;)if(e[s][0]==="enter"&&e[s][1].type==="attentionSequence"&&e[s][1]._close){for(i=s;i--;)if(e[i][0]==="exit"&&e[i][1].type==="attentionSequence"&&e[i][1]._open&&n.sliceSerialize(e[i][1]).charCodeAt(0)===n.sliceSerialize(e[s][1]).charCodeAt(0)){if((e[i][1]._close||e[s][1]._open)&&(e[s][1].end.offset-e[s][1].start.offset)%3&&!((e[i][1].end.offset-e[i][1].start.offset+e[s][1].end.offset-e[s][1].start.offset)%3))continue;u=e[i][1].end.offset-e[i][1].start.offset>1&&e[s][1].end.offset-e[s][1].start.offset>1?2:1;const h={...e[i][1].end},f={...e[s][1].start};Nm(h,-u),Nm(f,u),l={type:u>1?"strongSequence":"emphasisSequence",start:h,end:{...e[i][1].end}},c={type:u>1?"strongSequence":"emphasisSequence",start:{...e[s][1].start},end:f},o={type:u>1?"strongText":"emphasisText",start:{...e[i][1].end},end:{...e[s][1].start}},r={type:u>1?"strong":"emphasis",start:{...l.start},end:{...c.end}},e[i][1].end={...l.start},e[s][1].start={...c.end},d=[],e[i][1].end.offset-e[i][1].start.offset&&(d=$s(d,[["enter",e[i][1],n],["exit",e[i][1],n]])),d=$s(d,[["enter",r,n],["enter",l,n],["exit",l,n],["enter",o,n]]),d=$s(d,al(n.parser.constructs.insideSpan.null,e.slice(i+1,s),n)),d=$s(d,[["exit",o,n],["enter",c,n],["exit",c,n],["exit",r,n]]),e[s][1].end.offset-e[s][1].start.offset?(m=2,d=$s(d,[["enter",e[s][1],n],["exit",e[s][1],n]])):m=0,Ms(e,i-1,s-i+3,d),s=i+d.length-m-2;break}}for(s=-1;++s<e.length;)e[s][1].type==="attentionSequence"&&(e[s][1].type="data");return e}function NS(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),f=!r||r===2&&m||s.includes(i);return d._open=!!(o===42?h:h&&(r||!f)),d._close=!!(o===42?f:f&&(m||!h)),n(u)}}function Nm(e,n){e.column+=n,e.offset+=n,e._bufferIndex+=n}const SS={name:"autolink",tokenize:CS};function CS(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 hs(p)?(e.consume(p),l):p===64?s(p):d(p)}function l(p){return p===43||p===45||p===46||rs(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||rs(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||Do(p)?s(p):(e.consume(p),u)}function d(p){return p===64?(e.consume(p),m):fS(p)?(e.consume(p),d):s(p)}function m(p){return rs(p)?h(p):s(p)}function h(p){return p===46?(e.consume(p),i=0,m):p===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.exit("autolink"),n):f(p)}function f(p){if((p===45||rs(p))&&i++<63){const g=p===45?f:h;return e.consume(p),g}return s(p)}}const Or={partial:!0,tokenize:ES};function ES(e,n,s){return i;function i(o){return tn(o)?an(e,r,"linePrefix")(o):r(o)}function r(o){return o===null||At(o)?n(o):s(o)}}const vf={continuation:{tokenize:MS},exit:AS,name:"blockQuote",tokenize:_S};function _S(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 tn(l)?(e.enter("blockQuotePrefixWhitespace"),e.consume(l),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),n):(e.exit("blockQuotePrefix"),n(l))}}function MS(e,n,s){const i=this;return r;function r(l){return tn(l)?an(e,o,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l):o(l)}function o(l){return e.attempt(vf,n,s)(l)}}function AS(e){e.exit("blockQuote")}const yf={name:"characterEscape",tokenize:RS};function RS(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 bS(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),n):s(o)}}const jf={name:"characterReference",tokenize:TS};function TS(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=rs,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=gS,m):(e.enter("characterReferenceValue"),o=7,l=Vc,m(h))}function m(h){if(h===59&&r){const f=e.exit("characterReferenceValue");return l===rs&&!Md(i.sliceSerialize(f))?s(h):(e.enter("characterReferenceMarker"),e.consume(h),e.exit("characterReferenceMarker"),e.exit("characterReference"),n)}return l(h)&&r++<o?(e.consume(h),m):s(h)}}const Sm={partial:!0,tokenize:IS},Cm={concrete:!0,name:"codeFenced",tokenize:PS};function PS(e,n,s){const i=this,r={partial:!0,tokenize:_};let o=0,l=0,c;return u;function u(N){return d(N)}function d(N){const A=i.events[i.events.length-1];return o=A&&A[1].type==="linePrefix"?A[2].sliceSerialize(A[1],!0).length:0,c=N,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),m(N)}function m(N){return N===c?(l++,e.consume(N),m):l<3?s(N):(e.exit("codeFencedFenceSequence"),tn(N)?an(e,h,"whitespace")(N):h(N))}function h(N){return N===null||At(N)?(e.exit("codeFencedFence"),i.interrupt?n(N):e.check(Sm,b,S)(N)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),f(N))}function f(N){return N===null||At(N)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),h(N)):tn(N)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),an(e,p,"whitespace")(N)):N===96&&N===c?s(N):(e.consume(N),f)}function p(N){return N===null||At(N)?h(N):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(N))}function g(N){return N===null||At(N)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),h(N)):N===96&&N===c?s(N):(e.consume(N),g)}function b(N){return e.attempt(r,S,v)(N)}function v(N){return e.enter("lineEnding"),e.consume(N),e.exit("lineEnding"),x}function x(N){return o>0&&tn(N)?an(e,y,"linePrefix",o+1)(N):y(N)}function y(N){return N===null||At(N)?e.check(Sm,b,S)(N):(e.enter("codeFlowValue"),k(N))}function k(N){return N===null||At(N)?(e.exit("codeFlowValue"),y(N)):(e.consume(N),k)}function S(N){return e.exit("codeFenced"),n(N)}function _(N,A,C){let z=0;return M;function M(R){return N.enter("lineEnding"),N.consume(R),N.exit("lineEnding"),T}function T(R){return N.enter("codeFencedFence"),tn(R)?an(N,U,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(R):U(R)}function U(R){return R===c?(N.enter("codeFencedFenceSequence"),q(R)):C(R)}function q(R){return R===c?(z++,N.consume(R),q):z>=l?(N.exit("codeFencedFenceSequence"),tn(R)?an(N,D,"whitespace")(R):D(R)):C(R)}function D(R){return R===null||At(R)?(N.exit("codeFencedFence"),A(R)):C(R)}}}function IS(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 zl={name:"codeIndented",tokenize:DS},$S={partial:!0,tokenize:LS};function DS(e,n,s){const i=this;return r;function r(d){return e.enter("codeIndented"),an(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):At(d)?e.attempt($S,l,u)(d):(e.enter("codeFlowValue"),c(d))}function c(d){return d===null||At(d)?(e.exit("codeFlowValue"),l(d)):(e.consume(d),c)}function u(d){return e.exit("codeIndented"),n(d)}}function LS(e,n,s){const i=this;return r;function r(l){return i.parser.lazy[i.now().line]?s(l):At(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),r):an(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):At(l)?r(l):s(l)}}const zS={name:"codeText",previous:OS,resolve:FS,tokenize:US};function FS(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 OS(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function US(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)):At(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||At(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 BS{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&&Ja(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),Ja(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),Ja(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);Ja(this.right,s.reverse())}else{const s=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);Ja(this.left,s.reverse())}}}function Ja(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 kf(e){const n={};let s=-1,i,r,o,l,c,u,d;const m=new BS(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,HS(m,s)),s=n[s],d=!0);else if(i[1]._container){for(o=s,r=void 0;o--;)if(l=m.get(o),l[1].type==="lineEnding"||l[1].type==="lineEndingBlank")l[0]==="enter"&&(r&&(m.get(r)[1].type="lineEndingBlank"),l[1].type="lineEnding",r=o);else if(!(l[1].type==="linePrefix"||l[1].type==="listItemIndent"))break;r&&(i[1].end={...m.get(r)[1].start},c=m.slice(r,s),c.unshift(i),m.splice(r,s-r+1,c))}}return Ms(e,0,Number.POSITIVE_INFINITY,m.slice(0)),!d}function HS(e,n){const s=e.get(n)[1],i=e.get(n)[2];let r=n-1;const o=[];let l=s._tokenizer;l||(l=i.parser[s.contentType](s.start),s._contentTypeTextTrailing&&(l._contentTypeTextTrailing=!0));const c=l.events,u=[],d={};let m,h,f=-1,p=s,g=0,b=0;const v=[b];for(;p;){for(;e.get(++r)[1]!==p;);o.push(r),p._tokenizer||(m=i.sliceStream(p),p.next||m.push(null),h&&l.defineSkip(p.start),p._isInFirstContentOfListItem&&(l._gfmTasklistFirstContentOfListItem=!0),l.write(m),p._isInFirstContentOfListItem&&(l._gfmTasklistFirstContentOfListItem=void 0)),h=p,p=p.next}for(p=s;++f<c.length;)c[f][0]==="exit"&&c[f-1][0]==="enter"&&c[f][1].type===c[f-1][1].type&&c[f][1].start.line!==c[f][1].end.line&&(b=f+1,v.push(b),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(l.events=[],p?(p._tokenizer=void 0,p.previous=void 0):v.pop(),f=v.length;f--;){const x=c.slice(v[f],v[f+1]),y=o.pop();u.push([y,y+x.length-1]),e.splice(y,2,x)}for(u.reverse(),f=-1;++f<u.length;)d[g+u[f][0]]=g+u[f][1],g+=u[f][1]-u[f][0]-1;return d}const qS={resolve:WS,tokenize:KS},VS={partial:!0,tokenize:GS};function WS(e){return kf(e),e}function KS(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):At(c)?e.check(VS,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"),an(e,o,"linePrefix")}function o(l){if(l===null||At(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 wf(e,n,s,i,r,o,l,c,u){const d=u||Number.POSITIVE_INFINITY;let m=0;return h;function h(x){return x===60?(e.enter(i),e.enter(r),e.enter(o),e.consume(x),e.exit(o),f):x===null||x===32||x===41||Do(x)?s(x):(e.enter(i),e.enter(l),e.enter(c),e.enter("chunkString",{contentType:"string"}),b(x))}function f(x){return x===62?(e.enter(o),e.consume(x),e.exit(o),e.exit(r),e.exit(i),n):(e.enter(c),e.enter("chunkString",{contentType:"string"}),p(x))}function p(x){return x===62?(e.exit("chunkString"),e.exit(c),f(x)):x===null||x===60||At(x)?s(x):(e.consume(x),x===92?g:p)}function g(x){return x===60||x===62||x===92?(e.consume(x),p):p(x)}function b(x){return!m&&(x===null||x===41||vn(x))?(e.exit("chunkString"),e.exit(c),e.exit(l),e.exit(i),n(x)):m<d&&x===40?(e.consume(x),m++,b):x===41?(e.consume(x),m--,b):x===null||x===32||x===40||Do(x)?s(x):(e.consume(x),x===92?v:b)}function v(x){return x===40||x===41||x===92?(e.consume(x),b):b(x)}}function Nf(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):At(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||At(p)||c++>999?(e.exit("chunkString"),m(p)):(e.consume(p),u||(u=!tn(p)),p===92?f:h)}function f(p){return p===91||p===92||p===93?(e.consume(p),c++,h):h(p)}}function Sf(e,n,s,i,r,o){let l;return c;function c(f){return f===34||f===39||f===40?(e.enter(i),e.enter(r),e.consume(f),e.exit(r),l=f===40?41:f,u):s(f)}function u(f){return f===l?(e.enter(r),e.consume(f),e.exit(r),e.exit(i),n):(e.enter(o),d(f))}function d(f){return f===l?(e.exit(o),u(l)):f===null?s(f):At(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),an(e,d,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),m(f))}function m(f){return f===l||f===null||At(f)?(e.exit("chunkString"),d(f)):(e.consume(f),f===92?h:m)}function h(f){return f===l||f===92?(e.consume(f),m):m(f)}}function gr(e,n){let s;return i;function i(r){return At(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),s=!0,i):tn(r)?an(e,i,s?"linePrefix":"lineSuffix")(r):n(r)}}const JS={name:"definition",tokenize:QS},YS={partial:!0,tokenize:XS};function QS(e,n,s){const i=this;let r;return o;function o(p){return e.enter("definition"),l(p)}function l(p){return Nf.call(i,e,c,s,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function c(p){return r=Vs(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 vn(p)?gr(e,d)(p):d(p)}function d(p){return wf(e,m,s,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function m(p){return e.attempt(YS,h,h)(p)}function h(p){return tn(p)?an(e,f,"whitespace")(p):f(p)}function f(p){return p===null||At(p)?(e.exit("definition"),i.parser.defined.push(r),n(p)):s(p)}}function XS(e,n,s){return i;function i(c){return vn(c)?gr(e,r)(c):s(c)}function r(c){return Sf(e,o,s,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function o(c){return tn(c)?an(e,l,"whitespace")(c):l(c)}function l(c){return c===null||At(c)?n(c):s(c)}}const ZS={name:"hardBreakEscape",tokenize:eC};function eC(e,n,s){return i;function i(o){return e.enter("hardBreakEscape"),e.consume(o),r}function r(o){return At(o)?(e.exit("hardBreakEscape"),n(o)):s(o)}}const tC={name:"headingAtx",resolve:nC,tokenize:sC};function nC(e,n){let s=e.length-2,i=3,r,o;return e[i][1].type==="whitespace"&&(i+=2),s-2>i&&e[s][1].type==="whitespace"&&(s-=2),e[s][1].type==="atxHeadingSequence"&&(i===s-1||s-4>i&&e[s-2][1].type==="whitespace")&&(s-=i+1===s?2:4),s>i&&(r={type:"atxHeadingText",start:e[i][1].start,end:e[s][1].end},o={type:"chunkText",start:e[i][1].start,end:e[s][1].end,contentType:"text"},Ms(e,i,s-i+1,[["enter",r,n],["enter",o,n],["exit",o,n],["exit",r,n]])),e}function sC(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||vn(m)?(e.exit("atxHeadingSequence"),c(m)):s(m)}function c(m){return m===35?(e.enter("atxHeadingSequence"),u(m)):m===null||At(m)?(e.exit("atxHeading"),n(m)):tn(m)?an(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||vn(m)?(e.exit("atxHeadingText"),c(m)):(e.consume(m),d)}}const iC=["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"],Em=["pre","script","style","textarea"],aC={concrete:!0,name:"htmlFlow",resolveTo:lC,tokenize:cC},rC={partial:!0,tokenize:uC},oC={partial:!0,tokenize:dC};function lC(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 cC(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),f):w===47?(e.consume(w),o=!0,b):w===63?(e.consume(w),r=3,i.interrupt?n:E):hs(w)?(e.consume(w),l=String.fromCharCode(w),v):s(w)}function f(w){return w===45?(e.consume(w),r=2,p):w===91?(e.consume(w),r=5,c=0,g):hs(w)?(e.consume(w),r=4,i.interrupt?n:E):s(w)}function p(w){return w===45?(e.consume(w),i.interrupt?n:E):s(w)}function g(w){const O="CDATA[";return w===O.charCodeAt(c++)?(e.consume(w),c===O.length?i.interrupt?n:U:g):s(w)}function b(w){return hs(w)?(e.consume(w),l=String.fromCharCode(w),v):s(w)}function v(w){if(w===null||w===47||w===62||vn(w)){const O=w===47,Z=l.toLowerCase();return!O&&!o&&Em.includes(Z)?(r=1,i.interrupt?n(w):U(w)):iC.includes(l.toLowerCase())?(r=6,O?(e.consume(w),x):i.interrupt?n(w):U(w)):(r=7,i.interrupt&&!i.parser.lazy[i.now().line]?s(w):o?y(w):k(w))}return w===45||rs(w)?(e.consume(w),l+=String.fromCharCode(w),v):s(w)}function x(w){return w===62?(e.consume(w),i.interrupt?n:U):s(w)}function y(w){return tn(w)?(e.consume(w),y):M(w)}function k(w){return w===47?(e.consume(w),M):w===58||w===95||hs(w)?(e.consume(w),S):tn(w)?(e.consume(w),k):M(w)}function S(w){return w===45||w===46||w===58||w===95||rs(w)?(e.consume(w),S):_(w)}function _(w){return w===61?(e.consume(w),N):tn(w)?(e.consume(w),_):k(w)}function N(w){return w===null||w===60||w===61||w===62||w===96?s(w):w===34||w===39?(e.consume(w),u=w,A):tn(w)?(e.consume(w),N):C(w)}function A(w){return w===u?(e.consume(w),u=null,z):w===null||At(w)?s(w):(e.consume(w),A)}function C(w){return w===null||w===34||w===39||w===47||w===60||w===61||w===62||w===96||vn(w)?_(w):(e.consume(w),C)}function z(w){return w===47||w===62||tn(w)?k(w):s(w)}function M(w){return w===62?(e.consume(w),T):s(w)}function T(w){return w===null||At(w)?U(w):tn(w)?(e.consume(w),T):s(w)}function U(w){return w===45&&r===2?(e.consume(w),F):w===60&&r===1?(e.consume(w),V):w===62&&r===4?(e.consume(w),$):w===63&&r===3?(e.consume(w),E):w===93&&r===5?(e.consume(w),ee):At(w)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(rC,P,q)(w)):w===null||At(w)?(e.exit("htmlFlowData"),q(w)):(e.consume(w),U)}function q(w){return e.check(oC,D,P)(w)}function D(w){return e.enter("lineEnding"),e.consume(w),e.exit("lineEnding"),R}function R(w){return w===null||At(w)?q(w):(e.enter("htmlFlowData"),U(w))}function F(w){return w===45?(e.consume(w),E):U(w)}function V(w){return w===47?(e.consume(w),l="",K):U(w)}function K(w){if(w===62){const O=l.toLowerCase();return Em.includes(O)?(e.consume(w),$):U(w)}return hs(w)&&l.length<8?(e.consume(w),l+=String.fromCharCode(w),K):U(w)}function ee(w){return w===93?(e.consume(w),E):U(w)}function E(w){return w===62?(e.consume(w),$):w===45&&r===2?(e.consume(w),E):U(w)}function $(w){return w===null||At(w)?(e.exit("htmlFlowData"),P(w)):(e.consume(w),$)}function P(w){return e.exit("htmlFlow"),n(w)}}function dC(e,n,s){const i=this;return r;function r(l){return At(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 uC(e,n,s){return i;function i(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(Or,n,s)}}const mC={name:"htmlText",tokenize:hC};function hC(e,n,s){const i=this;let r,o,l;return c;function c(E){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(E),u}function u(E){return E===33?(e.consume(E),d):E===47?(e.consume(E),_):E===63?(e.consume(E),k):hs(E)?(e.consume(E),C):s(E)}function d(E){return E===45?(e.consume(E),m):E===91?(e.consume(E),o=0,g):hs(E)?(e.consume(E),y):s(E)}function m(E){return E===45?(e.consume(E),p):s(E)}function h(E){return E===null?s(E):E===45?(e.consume(E),f):At(E)?(l=h,V(E)):(e.consume(E),h)}function f(E){return E===45?(e.consume(E),p):h(E)}function p(E){return E===62?F(E):E===45?f(E):h(E)}function g(E){const $="CDATA[";return E===$.charCodeAt(o++)?(e.consume(E),o===$.length?b:g):s(E)}function b(E){return E===null?s(E):E===93?(e.consume(E),v):At(E)?(l=b,V(E)):(e.consume(E),b)}function v(E){return E===93?(e.consume(E),x):b(E)}function x(E){return E===62?F(E):E===93?(e.consume(E),x):b(E)}function y(E){return E===null||E===62?F(E):At(E)?(l=y,V(E)):(e.consume(E),y)}function k(E){return E===null?s(E):E===63?(e.consume(E),S):At(E)?(l=k,V(E)):(e.consume(E),k)}function S(E){return E===62?F(E):k(E)}function _(E){return hs(E)?(e.consume(E),N):s(E)}function N(E){return E===45||rs(E)?(e.consume(E),N):A(E)}function A(E){return At(E)?(l=A,V(E)):tn(E)?(e.consume(E),A):F(E)}function C(E){return E===45||rs(E)?(e.consume(E),C):E===47||E===62||vn(E)?z(E):s(E)}function z(E){return E===47?(e.consume(E),F):E===58||E===95||hs(E)?(e.consume(E),M):At(E)?(l=z,V(E)):tn(E)?(e.consume(E),z):F(E)}function M(E){return E===45||E===46||E===58||E===95||rs(E)?(e.consume(E),M):T(E)}function T(E){return E===61?(e.consume(E),U):At(E)?(l=T,V(E)):tn(E)?(e.consume(E),T):z(E)}function U(E){return E===null||E===60||E===61||E===62||E===96?s(E):E===34||E===39?(e.consume(E),r=E,q):At(E)?(l=U,V(E)):tn(E)?(e.consume(E),U):(e.consume(E),D)}function q(E){return E===r?(e.consume(E),r=void 0,R):E===null?s(E):At(E)?(l=q,V(E)):(e.consume(E),q)}function D(E){return E===null||E===34||E===39||E===60||E===61||E===96?s(E):E===47||E===62||vn(E)?z(E):(e.consume(E),D)}function R(E){return E===47||E===62||vn(E)?z(E):s(E)}function F(E){return E===62?(e.consume(E),e.exit("htmlTextData"),e.exit("htmlText"),n):s(E)}function V(E){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(E),e.exit("lineEnding"),K}function K(E){return tn(E)?an(e,ee,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(E):ee(E)}function ee(E){return e.enter("htmlTextData"),l(E)}}const Ad={name:"labelEnd",resolveAll:bC,resolveTo:xC,tokenize:vC},pC={tokenize:yC},fC={tokenize:jC},gC={tokenize:kC};function bC(e){let n=-1;const s=[];for(;++n<e.length;){const i=e[n][1];if(s.push(e[n]),i.type==="labelImage"||i.type==="labelLink"||i.type==="labelEnd"){const r=i.type==="labelImage"?4:2;i.type="data",n+=r}}return e.length!==s.length&&Ms(e,0,e.length,s),e}function xC(e,n){let s=e.length,i=0,r,o,l,c;for(;s--;)if(r=e[s][1],o){if(r.type==="link"||r.type==="labelLink"&&r._inactive)break;e[s][0]==="enter"&&r.type==="labelLink"&&(r._inactive=!0)}else if(l){if(e[s][0]==="enter"&&(r.type==="labelImage"||r.type==="labelLink")&&!r._balanced&&(o=s,r.type!=="labelLink")){i=2;break}}else r.type==="labelEnd"&&(l=s);const u={type:e[o][1].type==="labelLink"?"link":"image",start:{...e[o][1].start},end:{...e[e.length-1][1].end}},d={type:"label",start:{...e[o][1].start},end:{...e[l][1].end}},m={type:"labelText",start:{...e[o+i+2][1].end},end:{...e[l-2][1].start}};return c=[["enter",u,n],["enter",d,n]],c=$s(c,e.slice(o+1,o+i+3)),c=$s(c,[["enter",m,n]]),c=$s(c,al(n.parser.constructs.insideSpan.null,e.slice(o+i+4,l-3),n)),c=$s(c,[["exit",m,n],e[l-2],e[l-1],["exit",d,n]]),c=$s(c,e.slice(l+1)),c=$s(c,[["exit",u,n]]),Ms(e,o,e.length,c),e}function vC(e,n,s){const i=this;let r=i.events.length,o,l;for(;r--;)if((i.events[r][1].type==="labelImage"||i.events[r][1].type==="labelLink")&&!i.events[r][1]._balanced){o=i.events[r][1];break}return c;function c(f){return o?o._inactive?h(f):(l=i.parser.defined.includes(Vs(i.sliceSerialize({start:o.end,end:i.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(f),e.exit("labelMarker"),e.exit("labelEnd"),u):s(f)}function u(f){return f===40?e.attempt(pC,m,l?m:h)(f):f===91?e.attempt(fC,m,l?d:h)(f):l?m(f):h(f)}function d(f){return e.attempt(gC,m,h)(f)}function m(f){return n(f)}function h(f){return o._balanced=!0,s(f)}}function yC(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 vn(h)?gr(e,o)(h):o(h)}function o(h){return h===41?m(h):wf(e,l,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function l(h){return vn(h)?gr(e,u)(h):m(h)}function c(h){return s(h)}function u(h){return h===34||h===39||h===40?Sf(e,d,s,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):m(h)}function d(h){return vn(h)?gr(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 jC(e,n,s){const i=this;return r;function r(c){return Nf.call(i,e,o,l,"reference","referenceMarker","referenceString")(c)}function o(c){return i.parser.defined.includes(Vs(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)))?n(c):s(c)}function l(c){return s(c)}}function kC(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 wC={name:"labelStartImage",resolveAll:Ad.resolveAll,tokenize:NC};function NC(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 SC={name:"labelStartLink",resolveAll:Ad.resolveAll,tokenize:CC};function CC(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 Fl={name:"lineEnding",tokenize:EC};function EC(e,n){return s;function s(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),an(e,n,"linePrefix")}}const ko={name:"thematicBreak",tokenize:_C};function _C(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||At(d))?(e.exit("thematicBreak"),n(d)):s(d)}function u(d){return d===r?(e.consume(d),i++,u):(e.exit("thematicBreakSequence"),tn(d)?an(e,c,"whitespace")(d):c(d))}}const vs={continuation:{tokenize:TC},exit:IC,name:"list",tokenize:RC},MC={partial:!0,tokenize:$C},AC={partial:!0,tokenize:PC};function RC(e,n,s){const i=this,r=i.events[i.events.length-1];let o=r&&r[1].type==="linePrefix"?r[2].sliceSerialize(r[1],!0).length:0,l=0;return c;function c(p){const g=i.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(g==="listUnordered"?!i.containerState.marker||p===i.containerState.marker:Vc(p)){if(i.containerState.type||(i.containerState.type=g,e.enter(g,{_container:!0})),g==="listUnordered")return e.enter("listItemPrefix"),p===42||p===45?e.check(ko,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 Vc(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(Or,i.interrupt?s:m,e.attempt(MC,f,h))}function m(p){return i.containerState.initialBlankLine=!0,o++,f(p)}function h(p){return tn(p)?(e.enter("listItemPrefixWhitespace"),e.consume(p),e.exit("listItemPrefixWhitespace"),f):s(p)}function f(p){return i.containerState.size=o+i.sliceSerialize(e.exit("listItemPrefix"),!0).length,n(p)}}function TC(e,n,s){const i=this;return i.containerState._closeFlow=void 0,e.check(Or,r,o);function r(c){return i.containerState.furtherBlankLines=i.containerState.furtherBlankLines||i.containerState.initialBlankLine,an(e,n,"listItemIndent",i.containerState.size+1)(c)}function o(c){return i.containerState.furtherBlankLines||!tn(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(AC,n,l)(c))}function l(c){return i.containerState._closeFlow=!0,i.interrupt=void 0,an(e,e.attempt(vs,n,s),"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function PC(e,n,s){const i=this;return an(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 IC(e){e.exit(this.containerState.type)}function $C(e,n,s){const i=this;return an(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!tn(o)&&l&&l[1].type==="listItemPrefixWhitespace"?n(o):s(o)}}const _m={name:"setextUnderline",resolveTo:DC,tokenize:LC};function DC(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 LC(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"),tn(d)?an(e,u,"lineSuffix")(d):u(d))}function u(d){return d===null||At(d)?(e.exit("setextHeadingLine"),n(d)):s(d)}}const zC={tokenize:FC};function FC(e){const n=this,s=e.attempt(Or,i,e.attempt(this.parser.constructs.flowInitial,r,an(e,e.attempt(this.parser.constructs.flow,r,e.attempt(qS,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 OC={resolveAll:Ef()},UC=Cf("string"),BC=Cf("text");function Cf(e){return{resolveAll:Ef(e==="text"?HC:void 0),tokenize:n};function n(s){const i=this,r=this.parser.constructs[e],o=s.attempt(r,l,c);return l;function l(m){return d(m)?o(m):c(m)}function c(m){if(m===null){s.consume(m);return}return s.enter("data"),s.consume(m),u}function u(m){return d(m)?(s.exit("data"),o(m)):(s.consume(m),u)}function d(m){if(m===null)return!0;const h=r[m];let f=-1;if(h)for(;++f<h.length;){const p=h[f];if(!p.previous||p.previous.call(i,i.previous))return!0}return!1}}}function Ef(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 HC(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 qC={42:vs,43:vs,45:vs,48:vs,49:vs,50:vs,51:vs,52:vs,53:vs,54:vs,55:vs,56:vs,57:vs,62:vf},VC={91:JS},WC={[-2]:zl,[-1]:zl,32:zl},KC={35:tC,42:ko,45:[_m,ko],60:aC,61:_m,95:ko,96:Cm,126:Cm},GC={38:jf,92:yf},JC={[-5]:Fl,[-4]:Fl,[-3]:Fl,33:wC,38:jf,42:Wc,60:[SS,mC],91:SC,92:[ZS,yf],93:Ad,95:Wc,96:zS},YC={null:[Wc,OC]},QC={null:[42,95]},XC={null:[]},ZC=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:QC,contentInitial:VC,disable:XC,document:qC,flow:KC,flowInitial:WC,insideSpan:YC,string:GC,text:JC},Symbol.toStringTag,{value:"Module"}));function e2(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:A(_),check:A(N),consume:y,enter:k,exit:S,interrupt:A(N,{interrupt:!0})},d={code:null,containerState:{},defineSkip:b,events:[],now:g,parser:e,previous:null,sliceSerialize:f,sliceStream:p,write:h};let m=n.tokenize.call(d,u);return n.resolveAll&&o.push(n),d;function h(T){return l=$s(l,T),v(),l[l.length-1]!==null?[]:(C(n,0),d.events=al(o,d.events,d),d.events)}function f(T,U){return n2(p(T),U)}function p(T){return t2(l,T)}function g(){const{_bufferIndex:T,_index:U,line:q,column:D,offset:R}=i;return{_bufferIndex:T,_index:U,line:q,column:D,offset:R}}function b(T){r[T.line]=T.column,M()}function v(){let T;for(;i._index<l.length;){const U=l[i._index];if(typeof U=="string")for(T=i._index,i._bufferIndex<0&&(i._bufferIndex=0);i._index===T&&i._bufferIndex<U.length;)x(U.charCodeAt(i._bufferIndex));else x(U)}}function x(T){m=m(T)}function y(T){At(T)?(i.line++,i.column=1,i.offset+=T===-3?2:1,M()):T!==-1&&(i.column++,i.offset++),i._bufferIndex<0?i._index++:(i._bufferIndex++,i._bufferIndex===l[i._index].length&&(i._bufferIndex=-1,i._index++)),d.previous=T}function k(T,U){const q=U||{};return q.type=T,q.start=g(),d.events.push(["enter",q,d]),c.push(q),q}function S(T){const U=c.pop();return U.end=g(),d.events.push(["exit",U,d]),U}function _(T,U){C(T,U.from)}function N(T,U){U.restore()}function A(T,U){return q;function q(D,R,F){let V,K,ee,E;return Array.isArray(D)?P(D):"tokenize"in D?P([D]):$(D);function $(Ne){return se;function se(le){const we=le!==null&&Ne[le],L=le!==null&&Ne.null,ne=[...Array.isArray(we)?we:we?[we]:[],...Array.isArray(L)?L:L?[L]:[]];return P(ne)(le)}}function P(Ne){return V=Ne,K=0,Ne.length===0?F:w(Ne[K])}function w(Ne){return se;function se(le){return E=z(),ee=Ne,Ne.partial||(d.currentConstruct=Ne),Ne.name&&d.parser.constructs.disable.null.includes(Ne.name)?Z():Ne.tokenize.call(U?Object.assign(Object.create(d),U):d,u,O,Z)(le)}}function O(Ne){return T(ee,E),R}function Z(Ne){return E.restore(),++K<V.length?w(V[K]):F}}}function C(T,U){T.resolveAll&&!o.includes(T)&&o.push(T),T.resolve&&Ms(d.events,U,d.events.length-U,T.resolve(d.events.slice(U),d)),T.resolveTo&&(d.events=T.resolveTo(d.events,d))}function z(){const T=g(),U=d.previous,q=d.currentConstruct,D=d.events.length,R=Array.from(c);return{from:D,restore:F};function F(){i=T,d.previous=U,d.currentConstruct=q,d.events.length=D,c=R,M()}}function M(){i.line in r&&i.column<2&&(i.column=r[i.line],i.offset+=r[i.line]-1)}}function t2(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 n2(e,n){let s=-1;const i=[];let r;for(;++s<e.length;){const o=e[s];let l;if(typeof o=="string")l=o;else switch(o){case-5:{l="\r";break}case-4:{l=`
|
|
625
|
+
`;break}case-3:{l=`\r
|
|
626
|
+
`;break}case-2:{l=n?" ":" ";break}case-1:{if(!n&&r)continue;l=" ";break}default:l=String.fromCharCode(o)}r=o===-2,i.push(l)}return i.join("")}function s2(e){const i={constructs:bf([ZC,...(e||{}).extensions||[]]),content:r(xS),defined:[],document:r(yS),flow:r(zC),lazy:{},string:r(UC),text:r(BC)};return i;function r(o){return l;function l(c){return e2(i,o,c)}}}function i2(e){for(;!kf(e););return e}const Mm=/[\0\t\n\r]/g;function a2(){let e=1,n="",s=!0,i;return r;function r(o,l,c){const u=[];let d,m,h,f,p;for(o=n+(typeof o=="string"?o.toString():new TextDecoder(l||void 0).decode(o)),h=0,n="",s&&(o.charCodeAt(0)===65279&&h++,s=void 0);h<o.length;){if(Mm.lastIndex=h,d=Mm.exec(o),f=d&&d.index!==void 0?d.index:o.length,p=o.charCodeAt(f),!d){n=o.slice(h);break}if(p===10&&h===f&&i)u.push(-3),i=void 0;else switch(i&&(u.push(-5),i=void 0),h<f&&(u.push(o.slice(h,f)),e+=f-h),p){case 0:{u.push(65533),e++;break}case 9:{for(m=Math.ceil(e/4)*4,u.push(-2);e++<m;)u.push(-1);break}case 10:{u.push(-4),e=1;break}default:i=!0,e=1}h=f+1}return c&&(i&&u.push(-5),n&&u.push(n),u.push(null)),u}}const r2=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function o2(e){return e.replace(r2,l2)}function l2(e,n,s){if(n)return n;if(s.charCodeAt(0)===35){const r=s.charCodeAt(1),o=r===120||r===88;return xf(s.slice(o?2:1),o?16:10)}return Md(s)||e}const _f={}.hasOwnProperty;function c2(e,n,s){return n&&typeof n=="object"&&(s=n,n=void 0),d2(s)(i2(s2(s).document().write(a2()(e,n,!0))))}function d2(e){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(Oe),autolinkProtocol:z,autolinkEmail:z,atxHeading:o(me),blockQuote:o(L),characterEscape:z,characterReference:z,codeFenced:o(ne),codeFencedFenceInfo:l,codeFencedFenceMeta:l,codeIndented:o(ne,l),codeText:o(Q,l),codeTextData:z,data:z,codeFlowValue:z,definition:o(be),definitionDestinationString:l,definitionLabelString:l,definitionTitleString:l,emphasis:o(de),hardBreakEscape:o(ie),hardBreakTrailing:o(ie),htmlFlow:o(xe,l),htmlFlowData:z,htmlText:o(xe,l),htmlTextData:z,image:o(Re),label:l,link:o(Oe),listItem:o(et),listItemValue:f,listOrdered:o(nt,h),listUnordered:o(nt),paragraph:o(Ze),reference:w,referenceString:l,resourceDestinationString:l,resourceTitleString:l,setextHeading:o(me),strong:o(rt),thematicBreak:o(Ge)},exit:{atxHeading:u(),atxHeadingSequence:_,autolink:u(),autolinkEmail:we,autolinkProtocol:le,blockQuote:u(),characterEscapeValue:M,characterReferenceMarkerHexadecimal:Z,characterReferenceMarkerNumeric:Z,characterReferenceValue:Ne,characterReference:se,codeFenced:u(v),codeFencedFence:b,codeFencedFenceInfo:p,codeFencedFenceMeta:g,codeFlowValue:M,codeIndented:u(x),codeText:u(R),codeTextData:M,data:M,definition:u(),definitionDestinationString:S,definitionLabelString:y,definitionTitleString:k,emphasis:u(),hardBreakEscape:u(U),hardBreakTrailing:u(U),htmlFlow:u(q),htmlFlowData:M,htmlText:u(D),htmlTextData:M,image:u(V),label:ee,labelText:K,lineEnding:T,link:u(F),listItem:u(),listOrdered:u(),listUnordered:u(),paragraph:u(),referenceString:O,resourceDestinationString:E,resourceTitleString:$,resource:P,setextHeading:u(C),setextHeadingLineSequence:A,setextHeadingText:N,strong:u(),thematicBreak:u()}};Mf(n,(e||{}).mdastExtensions||[]);const s={};return i;function i(oe){let je={type:"root",children:[]};const X={stack:[je],tokenStack:[],config:n,enter:c,exit:d,buffer:l,resume:m,data:s},Ae=[];let Te=-1;for(;++Te<oe.length;)if(oe[Te][1].type==="listOrdered"||oe[Te][1].type==="listUnordered")if(oe[Te][0]==="enter")Ae.push(Te);else{const pe=Ae.pop();Te=r(oe,pe,Te)}for(Te=-1;++Te<oe.length;){const pe=n[oe[Te][0]];_f.call(pe,oe[Te][1].type)&&pe[oe[Te][1].type].call(Object.assign({sliceSerialize:oe[Te][2].sliceSerialize},X),oe[Te][1])}if(X.tokenStack.length>0){const pe=X.tokenStack[X.tokenStack.length-1];(pe[1]||Am).call(X,void 0,pe[0])}for(je.position={start:ji(oe.length>0?oe[0][1].start:{line:1,column:1,offset:0}),end:ji(oe.length>0?oe[oe.length-2][1].end:{line:1,column:1,offset:0})},Te=-1;++Te<n.transforms.length;)je=n.transforms[Te](je)||je;return je}function r(oe,je,X){let Ae=je-1,Te=-1,pe=!1,_e,Fe,it,ve;for(;++Ae<=X;){const ce=oe[Ae];switch(ce[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{ce[0]==="enter"?Te++:Te--,ve=void 0;break}case"lineEndingBlank":{ce[0]==="enter"&&(_e&&!ve&&!Te&&!it&&(it=Ae),ve=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:ve=void 0}if(!Te&&ce[0]==="enter"&&ce[1].type==="listItemPrefix"||Te===-1&&ce[0]==="exit"&&(ce[1].type==="listUnordered"||ce[1].type==="listOrdered")){if(_e){let Ie=Ae;for(Fe=void 0;Ie--;){const he=oe[Ie];if(he[1].type==="lineEnding"||he[1].type==="lineEndingBlank"){if(he[0]==="exit")continue;Fe&&(oe[Fe][1].type="lineEndingBlank",pe=!0),he[1].type="lineEnding",Fe=Ie}else if(!(he[1].type==="linePrefix"||he[1].type==="blockQuotePrefix"||he[1].type==="blockQuotePrefixWhitespace"||he[1].type==="blockQuoteMarker"||he[1].type==="listItemIndent"))break}it&&(!Fe||it<Fe)&&(_e._spread=!0),_e.end=Object.assign({},Fe?oe[Fe][1].start:ce[1].end),oe.splice(Fe||Ae,0,["exit",_e,ce[2]]),Ae++,X++}if(ce[1].type==="listItemPrefix"){const Ie={type:"listItem",_spread:!1,start:Object.assign({},ce[1].start),end:void 0};_e=Ie,oe.splice(Ae,0,["enter",Ie,ce[2]]),Ae++,X++,it=void 0,ve=!0}}}return oe[je][1]._spread=pe,X}function o(oe,je){return X;function X(Ae){c.call(this,oe(Ae),Ae),je&&je.call(this,Ae)}}function l(){this.stack.push({type:"fragment",children:[]})}function c(oe,je,X){this.stack[this.stack.length-1].children.push(oe),this.stack.push(oe),this.tokenStack.push([je,X||void 0]),oe.position={start:ji(je.start),end:void 0}}function u(oe){return je;function je(X){oe&&oe.call(this,X),d.call(this,X)}}function d(oe,je){const X=this.stack.pop(),Ae=this.tokenStack.pop();if(Ae)Ae[0].type!==oe.type&&(je?je.call(this,oe,Ae[0]):(Ae[1]||Am).call(this,oe,Ae[0]));else throw new Error("Cannot close `"+oe.type+"` ("+fr({start:oe.start,end:oe.end})+"): it’s not open");X.position.end=ji(oe.end)}function m(){return _d(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function f(oe){if(this.data.expectingFirstListItemValue){const je=this.stack[this.stack.length-2];je.start=Number.parseInt(this.sliceSerialize(oe),10),this.data.expectingFirstListItemValue=void 0}}function p(){const oe=this.resume(),je=this.stack[this.stack.length-1];je.lang=oe}function g(){const oe=this.resume(),je=this.stack[this.stack.length-1];je.meta=oe}function b(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function v(){const oe=this.resume(),je=this.stack[this.stack.length-1];je.value=oe.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function x(){const oe=this.resume(),je=this.stack[this.stack.length-1];je.value=oe.replace(/(\r?\n|\r)$/g,"")}function y(oe){const je=this.resume(),X=this.stack[this.stack.length-1];X.label=je,X.identifier=Vs(this.sliceSerialize(oe)).toLowerCase()}function k(){const oe=this.resume(),je=this.stack[this.stack.length-1];je.title=oe}function S(){const oe=this.resume(),je=this.stack[this.stack.length-1];je.url=oe}function _(oe){const je=this.stack[this.stack.length-1];if(!je.depth){const X=this.sliceSerialize(oe).length;je.depth=X}}function N(){this.data.setextHeadingSlurpLineEnding=!0}function A(oe){const je=this.stack[this.stack.length-1];je.depth=this.sliceSerialize(oe).codePointAt(0)===61?1:2}function C(){this.data.setextHeadingSlurpLineEnding=void 0}function z(oe){const X=this.stack[this.stack.length-1].children;let Ae=X[X.length-1];(!Ae||Ae.type!=="text")&&(Ae=He(),Ae.position={start:ji(oe.start),end:void 0},X.push(Ae)),this.stack.push(Ae)}function M(oe){const je=this.stack.pop();je.value+=this.sliceSerialize(oe),je.position.end=ji(oe.end)}function T(oe){const je=this.stack[this.stack.length-1];if(this.data.atHardBreak){const X=je.children[je.children.length-1];X.position.end=ji(oe.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(je.type)&&(z.call(this,oe),M.call(this,oe))}function U(){this.data.atHardBreak=!0}function q(){const oe=this.resume(),je=this.stack[this.stack.length-1];je.value=oe}function D(){const oe=this.resume(),je=this.stack[this.stack.length-1];je.value=oe}function R(){const oe=this.resume(),je=this.stack[this.stack.length-1];je.value=oe}function F(){const oe=this.stack[this.stack.length-1];if(this.data.inReference){const je=this.data.referenceType||"shortcut";oe.type+="Reference",oe.referenceType=je,delete oe.url,delete oe.title}else delete oe.identifier,delete oe.label;this.data.referenceType=void 0}function V(){const oe=this.stack[this.stack.length-1];if(this.data.inReference){const je=this.data.referenceType||"shortcut";oe.type+="Reference",oe.referenceType=je,delete oe.url,delete oe.title}else delete oe.identifier,delete oe.label;this.data.referenceType=void 0}function K(oe){const je=this.sliceSerialize(oe),X=this.stack[this.stack.length-2];X.label=o2(je),X.identifier=Vs(je).toLowerCase()}function ee(){const oe=this.stack[this.stack.length-1],je=this.resume(),X=this.stack[this.stack.length-1];if(this.data.inReference=!0,X.type==="link"){const Ae=oe.children;X.children=Ae}else X.alt=je}function E(){const oe=this.resume(),je=this.stack[this.stack.length-1];je.url=oe}function $(){const oe=this.resume(),je=this.stack[this.stack.length-1];je.title=oe}function P(){this.data.inReference=void 0}function w(){this.data.referenceType="collapsed"}function O(oe){const je=this.resume(),X=this.stack[this.stack.length-1];X.label=je,X.identifier=Vs(this.sliceSerialize(oe)).toLowerCase(),this.data.referenceType="full"}function Z(oe){this.data.characterReferenceType=oe.type}function Ne(oe){const je=this.sliceSerialize(oe),X=this.data.characterReferenceType;let Ae;X?(Ae=xf(je,X==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Ae=Md(je);const Te=this.stack[this.stack.length-1];Te.value+=Ae}function se(oe){const je=this.stack.pop();je.position.end=ji(oe.end)}function le(oe){M.call(this,oe);const je=this.stack[this.stack.length-1];je.url=this.sliceSerialize(oe)}function we(oe){M.call(this,oe);const je=this.stack[this.stack.length-1];je.url="mailto:"+this.sliceSerialize(oe)}function L(){return{type:"blockquote",children:[]}}function ne(){return{type:"code",lang:null,meta:null,value:""}}function Q(){return{type:"inlineCode",value:""}}function be(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function de(){return{type:"emphasis",children:[]}}function me(){return{type:"heading",depth:0,children:[]}}function ie(){return{type:"break"}}function xe(){return{type:"html",value:""}}function Re(){return{type:"image",title:null,url:"",alt:null}}function Oe(){return{type:"link",title:null,url:"",children:[]}}function nt(oe){return{type:"list",ordered:oe.type==="listOrdered",start:null,spread:oe._spread,children:[]}}function et(oe){return{type:"listItem",spread:oe._spread,checked:null,children:[]}}function Ze(){return{type:"paragraph",children:[]}}function rt(){return{type:"strong",children:[]}}function He(){return{type:"text",value:""}}function Ge(){return{type:"thematicBreak"}}}function ji(e){return{line:e.line,column:e.column,offset:e.offset}}function Mf(e,n){let s=-1;for(;++s<n.length;){const i=n[s];Array.isArray(i)?Mf(e,i):u2(e,i)}}function u2(e,n){let s;for(s in n)if(_f.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 Am(e,n){throw e?new Error("Cannot close `"+e.type+"` ("+fr({start:e.start,end:e.end})+"): a different token (`"+n.type+"`, "+fr({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+fr({start:n.start,end:n.end})+") is still open")}function m2(e){const n=this;n.parser=s;function s(i){return c2(i,{...n.data("settings"),...e,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function h2(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 p2(e,n){const s={type:"element",tagName:"br",properties:{},children:[]};return e.patch(n,s),[e.applyData(n,s),{type:"text",value:`
|
|
627
|
+
`}]}function f2(e,n){const s=n.value?n.value+`
|
|
628
|
+
`:"",i={},r=n.lang?n.lang.split(/\s+/):[];r.length>0&&(i.className=["language-"+r[0]]);let o={type:"element",tagName:"code",properties:i,children:[{type:"text",value:s}]};return n.meta&&(o.data={meta:n.meta}),e.patch(n,o),o=e.applyData(n,o),o={type:"element",tagName:"pre",properties:{},children:[o]},e.patch(n,o),o}function g2(e,n){const s={type:"element",tagName:"del",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function b2(e,n){const s={type:"element",tagName:"em",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function x2(e,n){const s=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=String(n.identifier).toUpperCase(),r=Da(i.toLowerCase()),o=e.footnoteOrder.indexOf(i);let l,c=e.footnoteCounts.get(i);c===void 0?(c=0,e.footnoteOrder.push(i),l=e.footnoteOrder.length):l=o+1,c+=1,e.footnoteCounts.set(i,c);const u={type:"element",tagName:"a",properties:{href:"#"+s+"fn-"+r,id:s+"fnref-"+r+(c>1?"-"+c:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(l)}]};e.patch(n,u);const d={type:"element",tagName:"sup",properties:{},children:[u]};return e.patch(n,d),e.applyData(n,d)}function v2(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 y2(e,n){if(e.options.allowDangerousHtml){const s={type:"raw",value:n.value};return e.patch(n,s),e.applyData(n,s)}}function Af(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 j2(e,n){const s=String(n.identifier).toUpperCase(),i=e.definitionById.get(s);if(!i)return Af(e,n);const r={src:Da(i.url||""),alt:n.alt};i.title!==null&&i.title!==void 0&&(r.title=i.title);const o={type:"element",tagName:"img",properties:r,children:[]};return e.patch(n,o),e.applyData(n,o)}function k2(e,n){const s={src:Da(n.url)};n.alt!==null&&n.alt!==void 0&&(s.alt=n.alt),n.title!==null&&n.title!==void 0&&(s.title=n.title);const i={type:"element",tagName:"img",properties:s,children:[]};return e.patch(n,i),e.applyData(n,i)}function w2(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 N2(e,n){const s=String(n.identifier).toUpperCase(),i=e.definitionById.get(s);if(!i)return Af(e,n);const r={href:Da(i.url||"")};i.title!==null&&i.title!==void 0&&(r.title=i.title);const o={type:"element",tagName:"a",properties:r,children:e.all(n)};return e.patch(n,o),e.applyData(n,o)}function S2(e,n){const s={href:Da(n.url)};n.title!==null&&n.title!==void 0&&(s.title=n.title);const i={type:"element",tagName:"a",properties:s,children:e.all(n)};return e.patch(n,i),e.applyData(n,i)}function C2(e,n,s){const i=e.all(n),r=s?E2(s):Rf(n),o={},l=[];if(typeof n.checked=="boolean"){const m=i[0];let h;m&&m.type==="element"&&m.tagName==="p"?h=m:(h={type:"element",tagName:"p",properties:{},children:[]},i.unshift(h)),h.children.length>0&&h.children.unshift({type:"text",value:" "}),h.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:n.checked,disabled:!0},children:[]}),o.className=["task-list-item"]}let c=-1;for(;++c<i.length;){const m=i[c];(r||c!==0||m.type!=="element"||m.tagName!=="p")&&l.push({type:"text",value:`
|
|
629
|
+
`}),m.type==="element"&&m.tagName==="p"&&!r?l.push(...m.children):l.push(m)}const u=i[i.length-1];u&&(r||u.type!=="element"||u.tagName!=="p")&&l.push({type:"text",value:`
|
|
630
|
+
`});const d={type:"element",tagName:"li",properties:o,children:l};return e.patch(n,d),e.applyData(n,d)}function E2(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=Rf(s[i])}return n}function Rf(e){const n=e.spread;return n??e.children.length>1}function _2(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 M2(e,n){const s={type:"element",tagName:"p",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function A2(e,n){const s={type:"root",children:e.wrap(e.all(n))};return e.patch(n,s),e.applyData(n,s)}function R2(e,n){const s={type:"element",tagName:"strong",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function T2(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=Nd(n.children[1]),u=df(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 P2(e,n,s){const i=s?s.children:void 0,o=(i?i.indexOf(n):1)===0?"th":"td",l=s&&s.type==="table"?s.align:void 0,c=l?l.length:n.children.length;let u=-1;const d=[];for(;++u<c;){const h=n.children[u],f={},p=l?l[u]:void 0;p&&(f.align=p);let g={type:"element",tagName:o,properties:f,children:[]};h&&(g.children=e.all(h),e.patch(h,g),g=e.applyData(h,g)),d.push(g)}const m={type:"element",tagName:"tr",properties:{},children:e.wrap(d,!0)};return e.patch(n,m),e.applyData(n,m)}function I2(e,n){const s={type:"element",tagName:"td",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}const Rm=9,Tm=32;function $2(e){const n=String(e),s=/\r?\n|\r/g;let i=s.exec(n),r=0;const o=[];for(;i;)o.push(Pm(n.slice(r,i.index),r>0,!0),i[0]),r=i.index+i[0].length,i=s.exec(n);return o.push(Pm(n.slice(r),r>0,!1)),o.join("")}function Pm(e,n,s){let i=0,r=e.length;if(n){let o=e.codePointAt(i);for(;o===Rm||o===Tm;)i++,o=e.codePointAt(i)}if(s){let o=e.codePointAt(r-1);for(;o===Rm||o===Tm;)r--,o=e.codePointAt(r-1)}return r>i?e.slice(i,r):""}function D2(e,n){const s={type:"text",value:$2(String(n.value))};return e.patch(n,s),e.applyData(n,s)}function L2(e,n){const s={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(n,s),e.applyData(n,s)}const z2={blockquote:h2,break:p2,code:f2,delete:g2,emphasis:b2,footnoteReference:x2,heading:v2,html:y2,imageReference:j2,image:k2,inlineCode:w2,linkReference:N2,link:S2,listItem:C2,list:_2,paragraph:M2,root:A2,strong:R2,table:T2,tableCell:I2,tableRow:P2,text:D2,thematicBreak:L2,toml:ro,yaml:ro,definition:ro,footnoteDefinition:ro};function ro(){}const Tf=-1,rl=0,br=1,Lo=2,Rd=3,Td=4,Pd=5,Id=6,Pf=7,If=8,Im=typeof self=="object"?self:globalThis,F2=(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 rl:case Tf:return s(l,r);case br:{const c=s([],r);for(const u of l)c.push(i(u));return c}case Lo:{const c=s({},r);for(const[u,d]of l)c[i(u)]=i(d);return c}case Rd:return s(new Date(l),r);case Td:{const{source:c,flags:u}=l;return s(new RegExp(c,u),r)}case Pd:{const c=s(new Map,r);for(const[u,d]of l)c.set(i(u),i(d));return c}case Id:{const c=s(new Set,r);for(const u of l)c.add(i(u));return c}case Pf:{const{name:c,message:u}=l;return s(new Im[c](u),r)}case If: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 Im[o](l),r)};return i},$m=e=>F2(new Map,e)(0),ca="",{toString:O2}={},{keys:U2}=Object,Ya=e=>{const n=typeof e;if(n!=="object"||!e)return[rl,n];const s=O2.call(e).slice(8,-1);switch(s){case"Array":return[br,ca];case"Object":return[Lo,ca];case"Date":return[Rd,ca];case"RegExp":return[Td,ca];case"Map":return[Pd,ca];case"Set":return[Id,ca];case"DataView":return[br,s]}return s.includes("Array")?[br,s]:s.includes("Error")?[Pf,s]:[Lo,s]},oo=([e,n])=>e===rl&&(n==="function"||n==="symbol"),B2=(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]=Ya(l);switch(c){case rl:{let m=l;switch(u){case"bigint":c=If,m=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+u);m=null;break;case"undefined":return r([Tf],l)}return r([c,m],l)}case br:{if(u){let f=l;return u==="DataView"?f=new Uint8Array(l.buffer):u==="ArrayBuffer"&&(f=new Uint8Array(l)),r([u,[...f]],l)}const m=[],h=r([c,m],l);for(const f of l)m.push(o(f));return h}case Lo:{if(u)switch(u){case"BigInt":return r([u,l.toString()],l);case"Boolean":case"Number":case"String":return r([u,l.valueOf()],l)}if(n&&"toJSON"in l)return o(l.toJSON());const m=[],h=r([c,m],l);for(const f of U2(l))(e||!oo(Ya(l[f])))&&m.push([o(f),o(l[f])]);return h}case Rd:return r([c,l.toISOString()],l);case Td:{const{source:m,flags:h}=l;return r([c,{source:m,flags:h}],l)}case Pd:{const m=[],h=r([c,m],l);for(const[f,p]of l)(e||!(oo(Ya(f))||oo(Ya(p))))&&m.push([o(f),o(p)]);return h}case Id:{const m=[],h=r([c,m],l);for(const f of l)(e||!oo(Ya(f)))&&m.push(o(f));return h}}const{message:d}=l;return r([c,{name:u,message:d}],l)};return o},Dm=(e,{json:n,lossy:s}={})=>{const i=[];return B2(!(n||s),!!n,new Map,i)(e),i},zo=typeof structuredClone=="function"?(e,n)=>n&&("json"in n||"lossy"in n)?$m(Dm(e,n)):structuredClone(e):(e,n)=>$m(Dm(e,n));function H2(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 q2(e,n){return"Back to reference "+(e+1)+(n>1?"-"+n:"")}function V2(e){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=e.options.footnoteBackContent||H2,i=e.options.footnoteBackLabel||q2,r=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",l=e.options.footnoteLabelProperties||{className:["sr-only"]},c=[];let u=-1;for(;++u<e.footnoteOrder.length;){const d=e.footnoteById.get(e.footnoteOrder[u]);if(!d)continue;const m=e.all(d),h=String(d.identifier).toUpperCase(),f=Da(h.toLowerCase());let p=0;const g=[],b=e.footnoteCounts.get(h);for(;b!==void 0&&++p<=b;){g.length>0&&g.push({type:"text",value:" "});let y=typeof s=="string"?s:s(u,p);typeof y=="string"&&(y={type:"text",value:y}),g.push({type:"element",tagName:"a",properties:{href:"#"+n+"fnref-"+f+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof i=="string"?i:i(u,p),className:["data-footnote-backref"]},children:Array.isArray(y)?y:[y]})}const v=m[m.length-1];if(v&&v.type==="element"&&v.tagName==="p"){const y=v.children[v.children.length-1];y&&y.type==="text"?y.value+=" ":v.children.push({type:"text",value:" "}),v.children.push(...g)}else m.push(...g);const x={type:"element",tagName:"li",properties:{id:n+"fn-"+f},children:e.wrap(m,!0)};e.patch(d,x),c.push(x)}if(c.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...zo(l),id:"footnote-label"},children:[{type:"text",value:r}]},{type:"text",value:`
|
|
631
|
+
`},{type:"element",tagName:"ol",properties:{},children:e.wrap(c,!0)},{type:"text",value:`
|
|
632
|
+
`}]}}const ol=(function(e){if(e==null)return J2;if(typeof e=="function")return ll(e);if(typeof e=="object")return Array.isArray(e)?W2(e):K2(e);if(typeof e=="string")return G2(e);throw new Error("Expected function, string, or object as test")});function W2(e){const n=[];let s=-1;for(;++s<e.length;)n[s]=ol(e[s]);return ll(i);function i(...r){let o=-1;for(;++o<n.length;)if(n[o].apply(this,r))return!0;return!1}}function K2(e){const n=e;return ll(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 ll(n);function n(s){return s&&s.type===e}}function ll(e){return n;function n(s,i,r){return!!(Y2(s)&&e.call(this,s,typeof i=="number"?i:void 0,r||void 0))}}function J2(){return!0}function Y2(e){return e!==null&&typeof e=="object"&&"type"in e}const $f=[],Q2=!0,Kc=!1,X2="skip";function Df(e,n,s,i){let r;typeof n=="function"&&typeof s!="function"?(i=s,s=n):r=n;const o=ol(r),l=i?-1:1;c(e,void 0,[])();function c(u,d,m){const h=u&&typeof u=="object"?u:{};if(typeof h.type=="string"){const p=typeof h.tagName=="string"?h.tagName:typeof h.name=="string"?h.name:void 0;Object.defineProperty(f,"name",{value:"node ("+(u.type+(p?"<"+p+">":""))+")"})}return f;function f(){let p=$f,g,b,v;if((!n||o(u,d,m[m.length-1]||void 0))&&(p=Z2(s(u,m)),p[0]===Kc))return p;if("children"in u&&u.children){const x=u;if(x.children&&p[0]!==X2)for(b=(i?x.children.length:-1)+l,v=m.concat(x);b>-1&&b<x.children.length;){const y=x.children[b];if(g=c(y,b,v)(),g[0]===Kc)return g;b=typeof g[1]=="number"?g[1]:b+l}}return p}}}function Z2(e){return Array.isArray(e)?e:typeof e=="number"?[Q2,e]:e==null?$f:[e]}function $d(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),Df(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 Gc={}.hasOwnProperty,eE={};function tE(e,n){const s=n||eE,i=new Map,r=new Map,o=new Map,l={...z2,...s.handlers},c={all:d,applyData:sE,definitionById:i,footnoteById:r,footnoteCounts:o,footnoteOrder:[],handlers:l,one:u,options:s,patch:nE,wrap:aE};return $d(e,function(m){if(m.type==="definition"||m.type==="footnoteDefinition"){const h=m.type==="definition"?i:r,f=String(m.identifier).toUpperCase();h.has(f)||h.set(f,m)}}),c;function u(m,h){const f=m.type,p=c.handlers[f];if(Gc.call(c.handlers,f)&&p)return p(c,m,h);if(c.options.passThrough&&c.options.passThrough.includes(f)){if("children"in m){const{children:b,...v}=m,x=zo(v);return x.children=c.all(m),x}return zo(m)}return(c.options.unknownHandler||iE)(c,m,h)}function d(m){const h=[];if("children"in m){const f=m.children;let p=-1;for(;++p<f.length;){const g=c.one(f[p],m);if(g){if(p&&f[p-1].type==="break"&&(!Array.isArray(g)&&g.type==="text"&&(g.value=Lm(g.value)),!Array.isArray(g)&&g.type==="element")){const b=g.children[0];b&&b.type==="text"&&(b.value=Lm(b.value))}Array.isArray(g)?h.push(...g):h.push(g)}}}return h}}function nE(e,n){e.position&&(n.position=q0(e))}function sE(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,zo(o)),"children"in s&&s.children&&r!==null&&r!==void 0&&(s.children=r)}return s}function iE(e,n){const s=n.data||{},i="value"in n&&!(Gc.call(s,"hProperties")||Gc.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 aE(e,n){const s=[];let i=-1;for(n&&s.push({type:"text",value:`
|
|
633
|
+
`});++i<e.length;)i&&s.push({type:"text",value:`
|
|
634
|
+
`}),s.push(e[i]);return n&&e.length>0&&s.push({type:"text",value:`
|
|
635
|
+
`}),s}function Lm(e){let n=0,s=e.charCodeAt(n);for(;s===9||s===32;)n++,s=e.charCodeAt(n);return e.slice(n)}function zm(e,n){const s=tE(e,n),i=s.one(e,void 0),r=V2(s),o=Array.isArray(i)?{type:"root",children:i}:i||{type:"root",children:[]};return r&&o.children.push({type:"text",value:`
|
|
636
|
+
`},r),o}function rE(e,n){return e&&"run"in e?async function(s,i){const r=zm(s,{file:i,...n});await e.run(r,i)}:function(s,i){return zm(s,{file:i,...e||n})}}function Fm(e){if(e)throw e}var Ol,Om;function oE(){if(Om)return Ol;Om=1;var e=Object.prototype.hasOwnProperty,n=Object.prototype.toString,s=Object.defineProperty,i=Object.getOwnPropertyDescriptor,r=function(d){return typeof Array.isArray=="function"?Array.isArray(d):n.call(d)==="[object Array]"},o=function(d){if(!d||n.call(d)!=="[object Object]")return!1;var m=e.call(d,"constructor"),h=d.constructor&&d.constructor.prototype&&e.call(d.constructor.prototype,"isPrototypeOf");if(d.constructor&&!m&&!h)return!1;var f;for(f in d);return typeof f>"u"||e.call(d,f)},l=function(d,m){s&&m.name==="__proto__"?s(d,m.name,{enumerable:!0,configurable:!0,value:m.newValue,writable:!0}):d[m.name]=m.newValue},c=function(d,m){if(m==="__proto__")if(e.call(d,m)){if(i)return i(d,m).value}else return;return d[m]};return Ol=function u(){var d,m,h,f,p,g,b=arguments[0],v=1,x=arguments.length,y=!1;for(typeof b=="boolean"&&(y=b,b=arguments[1]||{},v=2),(b==null||typeof b!="object"&&typeof b!="function")&&(b={});v<x;++v)if(d=arguments[v],d!=null)for(m in d)h=c(b,m),f=c(d,m),b!==f&&(y&&f&&(o(f)||(p=r(f)))?(p?(p=!1,g=h&&r(h)?h:[]):g=h&&o(h)?h:{},l(b,{name:m,newValue:u(y,g,f)})):typeof f<"u"&&l(b,{name:m,newValue:f}));return b},Ol}var lE=oE();const Ul=ep(lE);function Jc(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 cE(){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?dE(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 dE(e,n){let s;return i;function i(...l){const c=e.length>l.length;let u;c&&l.push(r);try{u=e.apply(this,l)}catch(d){const m=d;if(c&&s)throw m;return r(m)}c||(u&&u.then&&typeof u.then=="function"?u.then(o,r):u instanceof Error?r(u):o(u))}function r(l,...c){s||(s=!0,n(l,...c))}function o(l){r(null,l)}}const ni={basename:uE,dirname:mE,extname:hE,join:pE,sep:"/"};function uE(e,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');Ur(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 mE(e){if(Ur(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 hE(e){Ur(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 pE(...e){let n=-1,s;for(;++n<e.length;)Ur(e[n]),e[n]&&(s=s===void 0?e[n]:s+"/"+e[n]);return s===void 0?".":fE(s)}function fE(e){Ur(e);const n=e.codePointAt(0)===47;let s=gE(e,!n);return s.length===0&&!n&&(s="."),s.length>0&&e.codePointAt(e.length-1)===47&&(s+="/"),n?"/"+s:s}function gE(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 Ur(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const bE={cwd:xE};function xE(){return"/"}function Yc(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function vE(e){if(typeof e=="string")e=new URL(e);else if(!Yc(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 yE(e)}function yE(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 Bl=["history","path","basename","stem","extname","dirname"];class Lf{constructor(n){let s;n?Yc(n)?s={path:n}:typeof n=="string"||jE(n)?s={value:n}:s=n:s={},this.cwd="cwd"in s?"":bE.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let i=-1;for(;++i<Bl.length;){const o=Bl[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)Bl.includes(r)||(this[r]=s[r])}get basename(){return typeof this.path=="string"?ni.basename(this.path):void 0}set basename(n){ql(n,"basename"),Hl(n,"basename"),this.path=ni.join(this.dirname||"",n)}get dirname(){return typeof this.path=="string"?ni.dirname(this.path):void 0}set dirname(n){Um(this.basename,"dirname"),this.path=ni.join(n||"",this.basename)}get extname(){return typeof this.path=="string"?ni.extname(this.path):void 0}set extname(n){if(Hl(n,"extname"),Um(this.dirname,"extname"),n){if(n.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(n.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=ni.join(this.dirname,this.stem+(n||""))}get path(){return this.history[this.history.length-1]}set path(n){Yc(n)&&(n=vE(n)),ql(n,"path"),this.path!==n&&this.history.push(n)}get stem(){return typeof this.path=="string"?ni.basename(this.path,this.extname):void 0}set stem(n){ql(n,"stem"),Hl(n,"stem"),this.path=ni.join(this.dirname||"",n+(this.extname||""))}fail(n,s,i){const r=this.message(n,s,i);throw r.fatal=!0,r}info(n,s,i){const r=this.message(n,s,i);return r.fatal=void 0,r}message(n,s,i){const r=new cs(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 Hl(e,n){if(e&&e.includes(ni.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+ni.sep+"`")}function ql(e,n){if(!e)throw new Error("`"+n+"` cannot be empty")}function Um(e,n){if(!e)throw new Error("Setting `"+n+"` requires `path` to be set too")}function jE(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const kE=(function(e){const i=this.constructor.prototype,r=i[e],o=function(){return r.apply(o,arguments)};return Object.setPrototypeOf(o,i),o}),wE={}.hasOwnProperty;class Dd extends kE{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=cE()}copy(){const n=new Dd;let s=-1;for(;++s<this.attachers.length;){const i=this.attachers[s];n.use(...i)}return n.data(Ul(!0,{},this.namespace)),n}data(n,s){return typeof n=="string"?arguments.length===2?(Kl("data",this.frozen),this.namespace[n]=s,this):wE.call(this.namespace,n)&&this.namespace[n]||void 0:n?(Kl("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=lo(n),i=this.parser||this.Parser;return Vl("parse",i),i(String(s),s)}process(n,s){const i=this;return this.freeze(),Vl("process",this.parser||this.Parser),Wl("process",this.compiler||this.Compiler),s?r(void 0,s):new Promise(r);function r(o,l){const c=lo(n),u=i.parse(c);i.run(u,c,function(m,h,f){if(m||!h||!f)return d(m);const p=h,g=i.stringify(p,f);CE(g)?f.value=g:f.result=g,d(m,f)});function d(m,h){m||!h?l(m):o?o(h):s(void 0,h)}}}processSync(n){let s=!1,i;return this.freeze(),Vl("processSync",this.parser||this.Parser),Wl("processSync",this.compiler||this.Compiler),this.process(n,r),Hm("processSync","process",s),i;function r(o,l){s=!0,Fm(o),i=l}}run(n,s,i){Bm(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=lo(s);r.run(n,u,d);function d(m,h,f){const p=h||n;m?c(m):l?l(p):i(void 0,p,f)}}}runSync(n,s){let i=!1,r;return this.run(n,s,o),Hm("runSync","run",i),r;function o(l,c){Fm(l),r=c,i=!0}}stringify(n,s){this.freeze();const i=lo(s),r=this.compiler||this.Compiler;return Wl("stringify",r),Bm(n),r(n,i)}use(n,...s){const i=this.attachers,r=this.namespace;if(Kl("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=Ul(!0,r.settings,d.settings))}function c(d){let m=-1;if(d!=null)if(Array.isArray(d))for(;++m<d.length;){const h=d[m];o(h)}else throw new TypeError("Expected a list of plugins, not `"+d+"`")}function u(d,m){let h=-1,f=-1;for(;++h<i.length;)if(i[h][0]===d){f=h;break}if(f===-1)i.push([d,...m]);else if(m.length>0){let[p,...g]=m;const b=i[f][1];Jc(b)&&Jc(p)&&(p=Ul(!0,b,p)),i[f]=[d,p,...g]}}}}const NE=new Dd().freeze();function Vl(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Wl(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Kl(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 Bm(e){if(!Jc(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Hm(e,n,s){if(!s)throw new Error("`"+e+"` finished async. Use `"+n+"` instead")}function lo(e){return SE(e)?e:new Lf(e)}function SE(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function CE(e){return typeof e=="string"||EE(e)}function EE(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const _E="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",qm=[],Vm={allowDangerousHtml:!0},ME=/^(https?|ircs?|mailto|xmpp)$/i,AE=[{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 oi(e){const n=RE(e),s=TE(e);return PE(n.runSync(n.parse(s),s),e)}function RE(e){const n=e.rehypePlugins||qm,s=e.remarkPlugins||qm,i=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Vm}:Vm;return NE().use(m2).use(s).use(rE,i).use(n)}function TE(e){const n=e.children||"",s=new Lf;return typeof n=="string"&&(s.value=n),s}function PE(e,n){const s=n.allowedElements,i=n.allowElement,r=n.components,o=n.disallowedElements,l=n.skipHtml,c=n.unwrapDisallowed,u=n.urlTransform||IE;for(const m of AE)Object.hasOwn(n,m.from)&&(""+m.from+(m.to?"use `"+m.to+"` instead":"remove it")+_E+m.id,void 0);return $d(e,d),J0(e,{Fragment:t.Fragment,components:r,ignoreInvalidStyle:!0,jsx:t.jsx,jsxs:t.jsxs,passKeys:!0,passNode:!0});function d(m,h,f){if(m.type==="raw"&&f&&typeof h=="number")return l?f.children.splice(h,1):f.children[h]={type:"text",value:m.value},h;if(m.type==="element"){let p;for(p in Ll)if(Object.hasOwn(Ll,p)&&Object.hasOwn(m.properties,p)){const g=m.properties[p],b=Ll[p];(b===null||b.includes(m.tagName))&&(m.properties[p]=u(String(g||""),p,m))}}if(m.type==="element"){let p=s?!s.includes(m.tagName):o?o.includes(m.tagName):!1;if(!p&&i&&typeof h=="number"&&(p=!i(m,h,f)),p&&f&&typeof h=="number")return c&&m.children?f.children.splice(h,1,...m.children):f.children.splice(h,1),h}}}function IE(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||ME.test(e.slice(0,n))?e:""}function Wm(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 $E(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function DE(e,n,s){const r=ol((s||{}).ignore||[]),o=LE(n);let l=-1;for(;++l<o.length;)Df(e,"text",c);function c(d,m){let h=-1,f;for(;++h<m.length;){const p=m[h],g=f?f.children:void 0;if(r(p,g?g.indexOf(p):void 0,f))return;f=p}if(f)return u(d,m)}function u(d,m){const h=m[m.length-1],f=o[l][0],p=o[l][1];let g=0;const v=h.children.indexOf(d);let x=!1,y=[];f.lastIndex=0;let k=f.exec(d.value);for(;k;){const S=k.index,_={index:k.index,input:k.input,stack:[...m,d]};let N=p(...k,_);if(typeof N=="string"&&(N=N.length>0?{type:"text",value:N}:void 0),N===!1?f.lastIndex=S+1:(g!==S&&y.push({type:"text",value:d.value.slice(g,S)}),Array.isArray(N)?y.push(...N):N&&y.push(N),g=S+k[0].length,x=!0),!f.global)break;k=f.exec(d.value)}return x?(g<d.value.length&&y.push({type:"text",value:d.value.slice(g)}),h.children.splice(v,1,...y)):y=[d],v+y.length}}function LE(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([zE(r[0]),FE(r[1])])}return n}function zE(e){return typeof e=="string"?new RegExp($E(e),"g"):e}function FE(e){return typeof e=="function"?e:function(){return e}}const Gl="phrasing",Jl=["autolink","link","image","label"];function OE(){return{transforms:[KE],enter:{literalAutolink:BE,literalAutolinkEmail:Yl,literalAutolinkHttp:Yl,literalAutolinkWww:Yl},exit:{literalAutolink:WE,literalAutolinkEmail:VE,literalAutolinkHttp:HE,literalAutolinkWww:qE}}}function UE(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Gl,notInConstruct:Jl},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Gl,notInConstruct:Jl},{character:":",before:"[ps]",after:"\\/",inConstruct:Gl,notInConstruct:Jl}]}}function BE(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function Yl(e){this.config.enter.autolinkProtocol.call(this,e)}function HE(e){this.config.exit.autolinkProtocol.call(this,e)}function qE(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 VE(e){this.config.exit.autolinkEmail.call(this,e)}function WE(e){this.exit(e)}function KE(e){DE(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,GE],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,JE]],{ignore:["link","linkReference"]})}function GE(e,n,s,i,r){let o="";if(!zf(r)||(/^w/i.test(n)&&(s=n+s,n="",o="http://"),!YE(s)))return!1;const l=QE(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 JE(e,n,s,i){return!zf(i,!0)||/[-\d_]$/.test(s)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+s,children:[{type:"text",value:n+"@"+s}]}}function YE(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 QE(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=Wm(e,"(");let o=Wm(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 zf(e,n){const s=e.input.charCodeAt(e.index-1);return(e.index===0||Ki(s)||il(s))&&(!n||s!==47)}Ff.peek=r_;function XE(){this.buffer()}function ZE(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function e_(){this.buffer()}function t_(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function n_(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=Vs(this.sliceSerialize(e)).toLowerCase(),s.label=n}function s_(e){this.exit(e)}function i_(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=Vs(this.sliceSerialize(e)).toLowerCase(),s.label=n}function a_(e){this.exit(e)}function r_(){return"["}function Ff(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 o_(){return{enter:{gfmFootnoteCallString:XE,gfmFootnoteCall:ZE,gfmFootnoteDefinitionLabelString:e_,gfmFootnoteDefinition:t_},exit:{gfmFootnoteCallString:n_,gfmFootnoteCall:s_,gfmFootnoteDefinitionLabelString:i_,gfmFootnoteDefinition:a_}}}function l_(e){let n=!1;return e&&e.firstLineBlank&&(n=!0),{handlers:{footnoteDefinition:s,footnoteReference:Ff},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function s(i,r,o,l){const c=o.createTracker(l);let u=c.move("[^");const d=o.enter("footnoteDefinition"),m=o.enter("label");return u+=c.move(o.safe(o.associationId(i),{before:u,after:"]"})),m(),u+=c.move("]:"),i.children&&i.children.length>0&&(c.shift(4),u+=c.move((n?`
|
|
637
|
+
`:" ")+o.indentLines(o.containerFlow(i,c.current()),n?Of:c_))),d(),u}}function c_(e,n,s){return n===0?e:Of(e,n,s)}function Of(e,n,s){return(s?"":" ")+e}const d_=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Uf.peek=f_;function u_(){return{canContainEols:["delete"],enter:{strikethrough:h_},exit:{strikethrough:p_}}}function m_(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:d_}],handlers:{delete:Uf}}}function h_(e){this.enter({type:"delete",children:[]},e)}function p_(e){this.exit(e)}function Uf(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 f_(){return"~"}function g_(e){return e.length}function b_(e,n){const s=n||{},i=(s.align||[]).concat(),r=s.stringLength||g_,o=[],l=[],c=[],u=[];let d=0,m=-1;for(;++m<e.length;){const b=[],v=[];let x=-1;for(e[m].length>d&&(d=e[m].length);++x<e[m].length;){const y=x_(e[m][x]);if(s.alignDelimiters!==!1){const k=r(y);v[x]=k,(u[x]===void 0||k>u[x])&&(u[x]=k)}b.push(y)}l[m]=b,c[m]=v}let h=-1;if(typeof i=="object"&&"length"in i)for(;++h<d;)o[h]=Km(i[h]);else{const b=Km(i);for(;++h<d;)o[h]=b}h=-1;const f=[],p=[];for(;++h<d;){const b=o[h];let v="",x="";b===99?(v=":",x=":"):b===108?v=":":b===114&&(x=":");let y=s.alignDelimiters===!1?1:Math.max(1,u[h]-v.length-x.length);const k=v+"-".repeat(y)+x;s.alignDelimiters!==!1&&(y=v.length+y+x.length,y>u[h]&&(u[h]=y),p[h]=y),f[h]=k}l.splice(1,0,f),c.splice(1,0,p),m=-1;const g=[];for(;++m<l.length;){const b=l[m],v=c[m];h=-1;const x=[];for(;++h<d;){const y=b[h]||"";let k="",S="";if(s.alignDelimiters!==!1){const _=u[h]-(v[h]||0),N=o[h];N===114?k=" ".repeat(_):N===99?_%2?(k=" ".repeat(_/2+.5),S=" ".repeat(_/2-.5)):(k=" ".repeat(_/2),S=k):S=" ".repeat(_)}s.delimiterStart!==!1&&!h&&x.push("|"),s.padding!==!1&&!(s.alignDelimiters===!1&&y==="")&&(s.delimiterStart!==!1||h)&&x.push(" "),s.alignDelimiters!==!1&&x.push(k),x.push(y),s.alignDelimiters!==!1&&x.push(S),s.padding!==!1&&x.push(" "),(s.delimiterEnd!==!1||h!==d-1)&&x.push("|")}g.push(s.delimiterEnd===!1?x.join("").replace(/ +$/,""):x.join(""))}return g.join(`
|
|
638
|
+
`)}function x_(e){return e==null?"":String(e)}function Km(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 v_(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()),y_);return r(),l}function y_(e,n,s){return">"+(s?"":" ")+e}function j_(e,n){return Gm(e,n.inConstruct,!0)&&!Gm(e,n.notInConstruct,!1)}function Gm(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 Jm(e,n,s,i){let r=-1;for(;++r<s.unsafe.length;)if(s.unsafe[r].character===`
|
|
639
|
+
`&&j_(s.stack,s.unsafe[r]))return/[ \t]/.test(i.before)?"":" ";return`\\
|
|
640
|
+
`}function k_(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 w_(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 N_(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 S_(e,n,s,i){const r=N_(s),o=e.value||"",l=r==="`"?"GraveAccent":"Tilde";if(w_(e,s)){const h=s.enter("codeIndented"),f=s.indentLines(o,C_);return h(),f}const c=s.createTracker(i),u=r.repeat(Math.max(k_(o,r)+1,3)),d=s.enter("codeFenced");let m=c.move(u);if(e.lang){const h=s.enter(`codeFencedLang${l}`);m+=c.move(s.safe(e.lang,{before:m,after:" ",encode:["`"],...c.current()})),h()}if(e.lang&&e.meta){const h=s.enter(`codeFencedMeta${l}`);m+=c.move(" "),m+=c.move(s.safe(e.meta,{before:m,after:`
|
|
641
|
+
`,encode:["`"],...c.current()})),h()}return m+=c.move(`
|
|
642
|
+
`),o&&(m+=c.move(o+`
|
|
643
|
+
`)),m+=c.move(u),d(),m}function C_(e,n,s){return(s?"":" ")+e}function Ld(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 E_(e,n,s,i){const r=Ld(s),o=r==='"'?"Quote":"Apostrophe",l=s.enter("definition");let c=s.enter("label");const u=s.createTracker(i);let d=u.move("[");return d+=u.move(s.safe(s.associationId(e),{before:d,after:"]",...u.current()})),d+=u.move("]: "),c(),!e.url||/[\0- \u007F]/.test(e.url)?(c=s.enter("destinationLiteral"),d+=u.move("<"),d+=u.move(s.safe(e.url,{before:d,after:">",...u.current()})),d+=u.move(">")):(c=s.enter("destinationRaw"),d+=u.move(s.safe(e.url,{before:d,after:e.title?" ":`
|
|
644
|
+
`,...u.current()}))),c(),e.title&&(c=s.enter(`title${o}`),d+=u.move(" "+r),d+=u.move(s.safe(e.title,{before:d,after:r,...u.current()})),d+=u.move(r),c()),l(),d}function __(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 Er(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Fo(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}}Bf.peek=M_;function Bf(e,n,s,i){const r=__(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=Fo(i.before.charCodeAt(i.before.length-1),d,r);m.inside&&(u=Er(d)+u.slice(1));const h=u.charCodeAt(u.length-1),f=Fo(i.after.charCodeAt(0),h,r);f.inside&&(u=u.slice(0,-1)+Er(h));const p=l.move(r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+u+p}function M_(e,n,s){return s.options.emphasis||"*"}function A_(e,n){let s=!1;return $d(e,function(i){if("value"in i&&/\r?\n|\r/.test(i.value)||i.type==="break")return s=!0,Kc}),!!((!e.depth||e.depth<3)&&_d(e)&&(n.options.setext||s))}function R_(e,n,s,i){const r=Math.max(Math.min(6,e.depth||1),1),o=s.createTracker(i);if(A_(e,s)){const m=s.enter("headingSetext"),h=s.enter("phrasing"),f=s.containerPhrasing(e,{...o.current(),before:`
|
|
645
|
+
`,after:`
|
|
646
|
+
`});return h(),m(),f+`
|
|
647
|
+
`+(r===1?"=":"-").repeat(f.length-(Math.max(f.lastIndexOf("\r"),f.lastIndexOf(`
|
|
648
|
+
`))+1))}const l="#".repeat(r),c=s.enter("headingAtx"),u=s.enter("phrasing");o.move(l+" ");let d=s.containerPhrasing(e,{before:"# ",after:`
|
|
649
|
+
`,...o.current()});return/^[\t ]/.test(d)&&(d=Er(d.charCodeAt(0))+d.slice(1)),d=d?l+" "+d:l,s.options.closeAtx&&(d+=" "+l),u(),c(),d}Hf.peek=T_;function Hf(e){return e.value||""}function T_(){return"<"}qf.peek=P_;function qf(e,n,s,i){const r=Ld(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 P_(){return"!"}Vf.peek=I_;function Vf(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 I_(){return"!"}Wf.peek=$_;function Wf(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 $_(){return"`"}function Kf(e,n){const s=_d(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))}Gf.peek=D_;function Gf(e,n,s,i){const r=Ld(s),o=r==='"'?"Quote":"Apostrophe",l=s.createTracker(i);let c,u;if(Kf(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 D_(e,n,s){return Kf(e,s)?"<":"["}Jf.peek=L_;function Jf(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 L_(){return"["}function zd(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 z_(e){const n=zd(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 F_(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 Yf(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 O_(e,n,s,i){const r=s.enter("list"),o=s.bulletCurrent;let l=e.ordered?F_(s):zd(s);const c=e.ordered?l==="."?")":".":z_(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),Yf(s)===l&&m){let h=-1;for(;++h<e.children.length;){const f=e.children[h];if(f&&f.type==="listItem"&&f.children&&f.children[0]&&f.children[0].type==="thematicBreak"){u=!0;break}}}}u&&(l=c),s.bulletCurrent=l;const d=s.containerFlow(e,i);return s.bulletLastUsed=l,s.bulletCurrent=o,r(),d}function U_(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 B_(e,n,s,i){const r=U_(s);let o=s.bulletCurrent||zd(s);n&&n.type==="list"&&n.ordered&&(o=(typeof n.start=="number"&&n.start>-1?n.start:1)+(s.options.incrementListMarker===!1?0:n.children.indexOf(e))+o);let l=o.length+1;(r==="tab"||r==="mixed"&&(n&&n.type==="list"&&n.spread||e.spread))&&(l=Math.ceil(l/4)*4);const c=s.createTracker(i);c.move(o+" ".repeat(l-o.length)),c.shift(l);const u=s.enter("listItem"),d=s.indentLines(s.containerFlow(e,c.current()),m);return u(),d;function m(h,f,p){return f?(p?"":" ".repeat(l))+h:(p?o:o+" ".repeat(l-o.length))+h}}function H_(e,n,s,i){const r=s.enter("paragraph"),o=s.enter("phrasing"),l=s.containerPhrasing(e,i);return o(),r(),l}const q_=ol(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function V_(e,n,s,i){return(e.children.some(function(l){return q_(l)})?s.containerPhrasing:s.containerFlow).call(s,e,i)}function W_(e){const n=e.options.strong||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize strong with `"+n+"` for `options.strong`, expected `*`, or `_`");return n}Qf.peek=K_;function Qf(e,n,s,i){const r=W_(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=Fo(i.before.charCodeAt(i.before.length-1),d,r);m.inside&&(u=Er(d)+u.slice(1));const h=u.charCodeAt(u.length-1),f=Fo(i.after.charCodeAt(0),h,r);f.inside&&(u=u.slice(0,-1)+Er(h));const p=l.move(r+r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+u+p}function K_(e,n,s){return s.options.strong||"*"}function G_(e,n,s,i){return s.safe(e.value,i)}function J_(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 Y_(e,n,s){const i=(Yf(s)+(s.options.ruleSpaces?" ":"")).repeat(J_(s));return s.options.ruleSpaces?i.slice(0,-1):i}const Xf={blockquote:v_,break:Jm,code:S_,definition:E_,emphasis:Bf,hardBreak:Jm,heading:R_,html:Hf,image:qf,imageReference:Vf,inlineCode:Wf,link:Gf,linkReference:Jf,list:O_,listItem:B_,paragraph:H_,root:V_,strong:Qf,text:G_,thematicBreak:Y_};function Q_(){return{enter:{table:X_,tableData:Ym,tableHeader:Ym,tableRow:eM},exit:{codeText:tM,table:Z_,tableData:Ql,tableHeader:Ql,tableRow:Ql}}}function X_(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 Z_(e){this.exit(e),this.data.inTable=void 0}function eM(e){this.enter({type:"tableRow",children:[]},e)}function Ql(e){this.exit(e)}function Ym(e){this.enter({type:"tableCell",children:[]},e)}function tM(e){let n=this.resume();this.data.inTable&&(n=n.replace(/\\([\\|])/g,nM));const s=this.stack[this.stack.length-1];s.type,s.value=n,this.exit(e)}function nM(e,n){return n==="|"?n:e}function sM(e){const n=e||{},s=n.tableCellPadding,i=n.tablePipeAlign,r=n.stringLength,o=s?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
|
|
650
|
+
`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:f,table:l,tableCell:u,tableRow:c}};function l(p,g,b,v){return d(m(p,b,v),p.align)}function c(p,g,b,v){const x=h(p,b,v),y=d([x]);return y.slice(0,y.indexOf(`
|
|
651
|
+
`))}function u(p,g,b,v){const x=b.enter("tableCell"),y=b.enter("phrasing"),k=b.containerPhrasing(p,{...v,before:o,after:o});return y(),x(),k}function d(p,g){return b_(p,{align:g,alignDelimiters:i,padding:s,stringLength:r})}function m(p,g,b){const v=p.children;let x=-1;const y=[],k=g.enter("table");for(;++x<v.length;)y[x]=h(v[x],g,b);return k(),y}function h(p,g,b){const v=p.children;let x=-1;const y=[],k=g.enter("tableRow");for(;++x<v.length;)y[x]=u(v[x],p,g,b);return k(),y}function f(p,g,b){let v=Xf.inlineCode(p,g,b);return b.stack.includes("tableCell")&&(v=v.replace(/\|/g,"\\$&")),v}}function iM(){return{exit:{taskListCheckValueChecked:Qm,taskListCheckValueUnchecked:Qm,paragraph:rM}}}function aM(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:oM}}}function Qm(e){const n=this.stack[this.stack.length-2];n.type,n.checked=e.type==="taskListCheckValueChecked"}function rM(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 oM(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=Xf.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 lM(){return[OE(),o_(),u_(),Q_(),iM()]}function cM(e){return{extensions:[UE(),l_(e),m_(),sM(e),aM()]}}const dM={tokenize:gM,partial:!0},Zf={tokenize:bM,partial:!0},eg={tokenize:xM,partial:!0},tg={tokenize:vM,partial:!0},uM={tokenize:yM,partial:!0},ng={name:"wwwAutolink",tokenize:pM,previous:ig},sg={name:"protocolAutolink",tokenize:fM,previous:ag},xi={name:"emailAutolink",tokenize:hM,previous:rg},di={};function mM(){return{text:di}}let Di=48;for(;Di<123;)di[Di]=xi,Di++,Di===58?Di=65:Di===91&&(Di=97);di[43]=xi;di[45]=xi;di[46]=xi;di[95]=xi;di[72]=[xi,sg];di[104]=[xi,sg];di[87]=[xi,ng];di[119]=[xi,ng];function hM(e,n,s){const i=this;let r,o;return l;function l(h){return!Qc(h)||!rg.call(i,i.previous)||Fd(i.events)?s(h):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(h))}function c(h){return Qc(h)?(e.consume(h),c):h===64?(e.consume(h),u):s(h)}function u(h){return h===46?e.check(uM,m,d)(h):h===45||h===95||rs(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&&hs(i.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),n(h)):s(h)}}function pM(e,n,s){const i=this;return r;function r(l){return l!==87&&l!==119||!ig.call(i,i.previous)||Fd(i.events)?s(l):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(dM,e.attempt(Zf,e.attempt(eg,o),s),s)(l))}function o(l){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),n(l)}}function fM(e,n,s){const i=this;let r="",o=!1;return l;function l(h){return(h===72||h===104)&&ag.call(i,i.previous)&&!Fd(i.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),r+=String.fromCodePoint(h),e.consume(h),c):s(h)}function c(h){if(hs(h)&&r.length<5)return r+=String.fromCodePoint(h),e.consume(h),c;if(h===58){const f=r.toLowerCase();if(f==="http"||f==="https")return e.consume(h),u}return s(h)}function u(h){return h===47?(e.consume(h),o?d:(o=!0,u)):s(h)}function d(h){return h===null||Do(h)||vn(h)||Ki(h)||il(h)?s(h):e.attempt(Zf,e.attempt(eg,m),s)(h)}function m(h){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),n(h)}}function gM(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 bM(e,n,s){let i,r,o;return l;function l(d){return d===46||d===95?e.check(tg,u,c)(d):d===null||vn(d)||Ki(d)||d!==45&&il(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 xM(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(tg,n,o)(l):l===null||vn(l)||Ki(l)?n(l):(e.consume(l),r)}function o(l){return l===41&&i++,e.consume(l),r}}function vM(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||vn(c)||Ki(c)?n(c):s(c)}function r(c){return c===null||c===40||c===91||vn(c)||Ki(c)?n(c):i(c)}function o(c){return hs(c)?l(c):s(c)}function l(c){return c===59?(e.consume(c),i):hs(c)?(e.consume(c),l):s(c)}}function yM(e,n,s){return i;function i(o){return e.consume(o),r}function r(o){return rs(o)?s(o):n(o)}}function ig(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||vn(e)}function ag(e){return!hs(e)}function rg(e){return!(e===47||Qc(e))}function Qc(e){return e===43||e===45||e===46||e===95||rs(e)}function Fd(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 jM={tokenize:MM,partial:!0};function kM(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:CM,continuation:{tokenize:EM},exit:_M}},text:{91:{name:"gfmFootnoteCall",tokenize:SM},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:wM,resolveTo:NM}}}}function wM(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=Vs(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 NM(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 SM(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||vn(h))return s(h);if(h===93){e.exit("chunkString");const f=e.exit("gfmFootnoteCallString");return r.includes(Vs(i.sliceSerialize(f)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),n):s(h)}return vn(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 CM(e,n,s){const i=this,r=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);let o,l=0,c;return u;function u(g){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),d}function d(g){return g===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",m):s(g)}function m(g){if(l>999||g===93&&!c||g===null||g===91||vn(g))return s(g);if(g===93){e.exit("chunkString");const b=e.exit("gfmFootnoteDefinitionLabelString");return o=Vs(i.sliceSerialize(b)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),f}return vn(g)||(c=!0),l++,e.consume(g),g===92?h:m}function h(g){return g===91||g===92||g===93?(e.consume(g),l++,m):m(g)}function f(g){return g===58?(e.enter("definitionMarker"),e.consume(g),e.exit("definitionMarker"),r.includes(o)||r.push(o),an(e,p,"gfmFootnoteDefinitionWhitespace")):s(g)}function p(g){return n(g)}}function EM(e,n,s){return e.check(Or,n,e.attempt(jM,n,s))}function _M(e){e.exit("gfmFootnoteDefinition")}function MM(e,n,s){const i=this;return an(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 AM(e){let s=(e||{}).singleTilde;const i={name:"strikethrough",tokenize:o,resolveAll:r};return s==null&&(s=!0),{text:{126:i},insideSpan:{null:[i]},attentionMarkers:{null:[126]}};function r(l,c){let u=-1;for(;++u<l.length;)if(l[u][0]==="enter"&&l[u][1].type==="strikethroughSequenceTemporary"&&l[u][1]._close){let d=u;for(;d--;)if(l[d][0]==="exit"&&l[d][1].type==="strikethroughSequenceTemporary"&&l[d][1]._open&&l[u][1].end.offset-l[u][1].start.offset===l[d][1].end.offset-l[d][1].start.offset){l[u][1].type="strikethroughSequence",l[d][1].type="strikethroughSequence";const m={type:"strikethrough",start:Object.assign({},l[d][1].start),end:Object.assign({},l[u][1].end)},h={type:"strikethroughText",start:Object.assign({},l[d][1].end),end:Object.assign({},l[u][1].start)},f=[["enter",m,c],["enter",l[d][1],c],["exit",l[d][1],c],["enter",h,c]],p=c.parser.constructs.insideSpan.null;p&&Ms(f,f.length,0,al(p,l.slice(d+1,u),c)),Ms(f,f.length,0,[["exit",h,c],["enter",l[u][1],c],["exit",l[u][1],c],["exit",m,c]]),Ms(l,d-1,u-d+3,f),u=d+f.length-2;break}}for(u=-1;++u<l.length;)l[u][1].type==="strikethroughSequenceTemporary"&&(l[u][1].type="data");return l}function o(l,c,u){const d=this.previous,m=this.events;let h=0;return f;function f(g){return d===126&&m[m.length-1][1].type!=="characterEscape"?u(g):(l.enter("strikethroughSequenceTemporary"),p(g))}function p(g){const b=ja(d);if(g===126)return h>1?u(g):(l.consume(g),h++,p);if(h<2&&!s)return u(g);const v=l.exit("strikethroughSequenceTemporary"),x=ja(g);return v._open=!x||x===2&&!!b,v._close=!b||b===2&&!!x,c(g)}}}class RM{constructor(){this.map=[]}add(n,s,i){TM(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 TM(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 PM(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 IM(){return{flow:{null:{name:"table",tokenize:$M,resolveAll:DM}}}}function $M(e,n,s){const i=this;let r=0,o=0,l;return c;function c(M){let T=i.events.length-1;for(;T>-1;){const D=i.events[T][1].type;if(D==="lineEnding"||D==="linePrefix")T--;else break}const U=T>-1?i.events[T][1].type:null,q=U==="tableHead"||U==="tableRow"?N:u;return q===N&&i.parser.lazy[i.now().line]?s(M):q(M)}function u(M){return e.enter("tableHead"),e.enter("tableRow"),d(M)}function d(M){return M===124||(l=!0,o+=1),m(M)}function m(M){return M===null?s(M):At(M)?o>1?(o=0,i.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(M),e.exit("lineEnding"),p):s(M):tn(M)?an(e,m,"whitespace")(M):(o+=1,l&&(l=!1,r+=1),M===124?(e.enter("tableCellDivider"),e.consume(M),e.exit("tableCellDivider"),l=!0,m):(e.enter("data"),h(M)))}function h(M){return M===null||M===124||vn(M)?(e.exit("data"),m(M)):(e.consume(M),M===92?f:h)}function f(M){return M===92||M===124?(e.consume(M),h):h(M)}function p(M){return i.interrupt=!1,i.parser.lazy[i.now().line]?s(M):(e.enter("tableDelimiterRow"),l=!1,tn(M)?an(e,g,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(M):g(M))}function g(M){return M===45||M===58?v(M):M===124?(l=!0,e.enter("tableCellDivider"),e.consume(M),e.exit("tableCellDivider"),b):_(M)}function b(M){return tn(M)?an(e,v,"whitespace")(M):v(M)}function v(M){return M===58?(o+=1,l=!0,e.enter("tableDelimiterMarker"),e.consume(M),e.exit("tableDelimiterMarker"),x):M===45?(o+=1,x(M)):M===null||At(M)?S(M):_(M)}function x(M){return M===45?(e.enter("tableDelimiterFiller"),y(M)):_(M)}function y(M){return M===45?(e.consume(M),y):M===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(M),e.exit("tableDelimiterMarker"),k):(e.exit("tableDelimiterFiller"),k(M))}function k(M){return tn(M)?an(e,S,"whitespace")(M):S(M)}function S(M){return M===124?g(M):M===null||At(M)?!l||r!==o?_(M):(e.exit("tableDelimiterRow"),e.exit("tableHead"),n(M)):_(M)}function _(M){return s(M)}function N(M){return e.enter("tableRow"),A(M)}function A(M){return M===124?(e.enter("tableCellDivider"),e.consume(M),e.exit("tableCellDivider"),A):M===null||At(M)?(e.exit("tableRow"),n(M)):tn(M)?an(e,A,"whitespace")(M):(e.enter("data"),C(M))}function C(M){return M===null||M===124||vn(M)?(e.exit("data"),A(M)):(e.consume(M),M===92?z:C)}function z(M){return M===92||M===124?(e.consume(M),C):C(M)}}function DM(e,n){let s=-1,i=!0,r=0,o=[0,0,0,0],l=[0,0,0,0],c=!1,u=0,d,m,h;const f=new RM;for(;++s<e.length;){const p=e[s],g=p[1];p[0]==="enter"?g.type==="tableHead"?(c=!1,u!==0&&(Xm(f,n,u,d,m),m=void 0,u=0),d={type:"table",start:Object.assign({},g.start),end:Object.assign({},g.end)},f.add(s,0,[["enter",d,n]])):g.type==="tableRow"||g.type==="tableDelimiterRow"?(i=!0,h=void 0,o=[0,0,0,0],l=[0,s+1,0,0],c&&(c=!1,m={type:"tableBody",start:Object.assign({},g.start),end:Object.assign({},g.end)},f.add(s,0,[["enter",m,n]])),r=g.type==="tableDelimiterRow"?2:m?3:1):r&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")?(i=!1,l[2]===0&&(o[1]!==0&&(l[0]=l[1],h=co(f,n,o,r,void 0,h),o=[0,0,0,0]),l[2]=s)):g.type==="tableCellDivider"&&(i?i=!1:(o[1]!==0&&(l[0]=l[1],h=co(f,n,o,r,void 0,h)),o=l,l=[o[1],s,0,0])):g.type==="tableHead"?(c=!0,u=s):g.type==="tableRow"||g.type==="tableDelimiterRow"?(u=s,o[1]!==0?(l[0]=l[1],h=co(f,n,o,r,s,h)):l[1]!==0&&(h=co(f,n,l,r,s,h)),r=0):r&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")&&(l[3]=s)}for(u!==0&&Xm(f,n,u,d,m),f.consume(n.events),s=-1;++s<n.events.length;){const p=n.events[s];p[0]==="enter"&&p[1].type==="table"&&(p[1]._align=PM(n.events,s))}return e}function co(e,n,s,i,r,o){const l=i===1?"tableHeader":i===2?"tableDelimiter":"tableData",c="tableContent";s[0]!==0&&(o.end=Object.assign({},ha(n.events,s[0])),e.add(s[0],0,[["exit",o,n]]));const u=ha(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=ha(n.events,s[2]),m=ha(n.events,s[3]),h={type:c,start:Object.assign({},d),end:Object.assign({},m)};if(e.add(s[2],0,[["enter",h,n]]),i!==2){const f=n.events[s[2]],p=n.events[s[3]];if(f[1].end=Object.assign({},p[1].end),f[1].type="chunkText",f[1].contentType="text",s[3]>s[2]+1){const g=s[2]+1,b=s[3]-s[2]-1;e.add(g,b,[])}}e.add(s[3]+1,0,[["exit",h,n]])}return r!==void 0&&(o.end=Object.assign({},ha(n.events,r)),e.add(r,0,[["exit",o,n]]),o=void 0),o}function Xm(e,n,s,i,r){const o=[],l=ha(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 ha(e,n){const s=e[n],i=s[0]==="enter"?"start":"end";return s[1][i]}const LM={name:"tasklistCheck",tokenize:FM};function zM(){return{text:{91:LM}}}function FM(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 vn(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 At(u)?n(u):tn(u)?e.check({tokenize:OM},n,s)(u):s(u)}}function OM(e,n,s){return an(e,i,"whitespace");function i(r){return r===null?s(r):n(r)}}function UM(e){return bf([mM(),kM(),AM(e),IM(),zM()])}const BM={};function li(e){const n=this,s=e||BM,i=n.data(),r=i.micromarkExtensions||(i.micromarkExtensions=[]),o=i.fromMarkdownExtensions||(i.fromMarkdownExtensions=[]),l=i.toMarkdownExtensions||(i.toMarkdownExtensions=[]);r.push(UM(s)),o.push(lM()),l.push(cM(s))}const Zm=100;function og(e,n,s){const[i,r]=a.useState([]),[o,l]=a.useState(!1),[c,u]=a.useState(!1),[d,m]=a.useState(null),[h,f]=a.useState(!1),p=a.useRef(null),g=a.useRef(!1),b=a.useRef(0),v=a.useRef(e),x=a.useRef(s),y=a.useRef(n),k=a.useRef(0);(v.current!==e||x.current!==s||y.current!==n)&&(v.current=e,x.current=s,y.current=n,b.current++,g.current=!0,r([]),l(!1),u(!1),m(null),f(!1),p.current&&(p.current(),p.current=null)),a.useEffect(()=>{if(!e||!n){p.current&&(p.current(),p.current=null);return}const A=b.current,C=++k.current;g.current=!1;const z=e,M=s;async function T(){if(!z)return;l(!0),f(!1);try{const q=await Yd(z,M,{limit:Zm});if(g.current||b.current!==A||k.current!==C)return;r(q.entries),u(q.hasMore),m(q.total)}catch{if(g.current||b.current!==A||k.current!==C)return;r([]),u(!1),m(null)}finally{!g.current&&b.current===A&&k.current===C&&l(!1)}const U=M?`?projectId=${encodeURIComponent(M)}`:"";p.current=Gs(`/api/tasks/${z}/logs/stream${U}`,{events:{"agent:log":q=>{if(!(g.current||b.current!==A))try{const D=JSON.parse(q.data);r(R=>[...R,D]),m(R=>R!==null?R+1:null)}catch{}}}})}return T(),()=>{g.current=!0,p.current&&(p.current(),p.current=null)}},[e,n,s]);const _=a.useCallback(async()=>{if(!e||h)return;const A=b.current,C=i.length,z=e;f(!0);try{const M=await Yd(z,s,{limit:Zm,offset:C});if(g.current||b.current!==A)return;r(T=>[...M.entries,...T]),u(M.hasMore),m(M.total)}catch{}finally{f(!1)}},[e,s,i.length,h]),N=a.useCallback(()=>r([]),[]);return{entries:i,loading:o,clear:N,loadMore:_,hasMore:c,total:d,loadingMore:h}}function HM(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 eh={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})},lg=50,qM={triage:"Plan"};function th(e){return e.scrollHeight-(e.scrollTop+e.clientHeight)<=lg}function Xc(e){return[e.taskId,e.timestamp,e.agent??"",e.type,e.text,e.detail??""].join("|")}function VM(e){const n=new Map;return e.map(s=>{const i=Xc(s),r=n.get(i)??0;return n.set(i,r+1),`${i}|${r}`})}function WM(e){return e==="tool"||e==="tool_result"||e==="tool_error"}function Xl(e){return e?t.jsx("pre",{className:"agent-log-tool-detail",children:e}):null}function KM(e,n){return e.agent?WM(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]??`${Xc(r)}|fallback`,l=i>0?e[i-1]:void 0,c=KM(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]??`${Xc(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 JM({entries:e,loading:n,executorModel:s,validatorModel:i,planningModel:r,hasMore:o=!1,onLoadMore:l,loadingMore:c=!1,totalCount:u=null}){const d=a.useRef(null),m=a.useRef(0),h=a.useRef(0),f=a.useRef(null),p=a.useRef(null),[g,b]=a.useState(!0),[v,x]=a.useState(!1),[y,k]=a.useState(!1),[S,_]=a.useState(!0),N=a.useMemo(()=>VM(e),[e]),A=a.useMemo(()=>GM(e,N),[e,N]);a.useLayoutEffect(()=>{const R=d.current;if(!R)return;const F=e.length,V=m.current,K=h.current||R.scrollHeight,ee=N[0]??null,E=N[N.length-1]??null,$=f.current!==ee,P=p.current!==E;if(F>V)if(V===0)R.scrollTop=R.scrollHeight;else{const w=K-(R.scrollTop+R.clientHeight)<=lg,O=P&&!$,Z=$&&!P;if(O&&w&&(R.scrollTop=R.scrollHeight),Z){const Ne=R.scrollHeight-K;Ne>0&&(R.scrollTop+=Ne)}}m.current=F,h.current=R.scrollHeight,f.current=ee,p.current=E,_(th(R))},[e,N]);const C=a.useCallback(()=>{const R=d.current;R&&_(th(R))},[]),z=a.useCallback(()=>{const R=d.current;R&&(R.scrollTop=R.scrollHeight,_(!0))},[]),M=a.useCallback(R=>{R.key==="Escape"&&v&&x(!1)},[v]);a.useEffect(()=>{if(v)return document.addEventListener("keydown",M),()=>{document.removeEventListener("keydown",M)}},[v,M]);const T=s?.provider&&s?.modelId,U=i?.provider&&i?.modelId,q=r?.provider&&r?.modelId,D=a.useMemo(()=>{const R=[];return T&&R.push({role:"Executor",provider:s.provider,modelId:s.modelId}),U&&R.push({role:"Reviewer",provider:i.provider,modelId:i.modelId}),q&&R.push({role:"Planning",provider:r.provider,modelId:r.modelId}),R},[T,s,U,i,q,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:[D.map(R=>t.jsx(An,{provider:R.provider,size:"sm"},`${R.role}-${R.provider}-${R.modelId??"default"}`)),t.jsx("button",{className:"agent-log-model-expand-btn",onClick:()=>k(R=>!R),"aria-label":y?"Collapse model details":"Expand model details","aria-expanded":y,"aria-controls":"agent-log-model-details","data-testid":"agent-log-model-expand",children:y?t.jsx(sn,{size:14}):t.jsx(kn,{size:14})})]}),t.jsxs("div",{className:"agent-log-model-header-toggle",children:[t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>b(R=>!R),"aria-label":g?"Switch to plain text mode":"Switch to markdown mode","aria-pressed":g,"data-testid":"agent-log-mode-toggle",title:g?"Show raw text":"Show formatted markdown",children:g?"Markdown":"Plain"}),t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>x(R=>!R),"aria-label":v?"Exit full screen":"Expand agent log to full screen","data-testid":"agent-log-fullscreen-toggle",title:v?"Exit full screen":"Expand agent log to full screen",children:v?t.jsx(Ir,{size:14}):t.jsx(Go,{size:14})})]}),y&&t.jsxs("div",{id:"agent-log-model-details",className:"agent-log-model-details",children:[t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Executor:"}),T?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(An,{provider:s.provider,size:"sm"}),t.jsxs("span",{children:[s.provider,"/",s.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]}),t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Reviewer:"}),U?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(An,{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:"}),q?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(An,{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(lt,{size:14,className:"animate-spin"}),"Loading…"]}):"Load More"})}),A.map(R=>{const F=R.kind==="single"?R.entry:R.entries[0],V=R.showBadge?t.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:HM(F.timestamp)}):null,K=R.showBadge?t.jsxs("span",{className:"agent-log-badge-row",children:[t.jsxs("span",{className:"agent-log-agent-badge",children:["[",qM[F.agent]??F.agent,"]"]}),V]}):null;if(R.kind==="single"){const{entry:E}=R;if(E.type==="tool")return t.jsxs("div",{className:"agent-log-tool",children:[K,t.jsxs("div",{className:"agent-log-tool-title",children:["⚡ ",E.text]}),Xl(E.detail)]},R.key);if(E.type==="tool_result")return t.jsxs("div",{className:"agent-log-tool-result",children:[K,t.jsxs("div",{className:"agent-log-tool-title",children:["✓ ",E.text]}),Xl(E.detail)]},R.key);if(E.type==="tool_error")return t.jsxs("div",{className:"agent-log-tool-error",children:[K,t.jsxs("div",{className:"agent-log-tool-title",children:["✗ ",E.text]}),Xl(E.detail)]},R.key)}const ee=R.kind==="single"?F.text:R.entries.map(E=>E.text).join("");return R.kind==="thinking"?t.jsxs("div",{className:"agent-log-thinking",children:[K,g?t.jsx("div",{className:"markdown-body",children:t.jsx(oi,{remarkPlugins:[li],components:eh,children:ee})}):t.jsx("pre",{className:"agent-log-plain-block",children:ee})]},R.key):t.jsxs("div",{className:"agent-log-text",children:[K,g?t.jsx("div",{className:"markdown-body",children:t.jsx(oi,{remarkPlugins:[li],components:eh,children:ee})}):t.jsx("pre",{className:"agent-log-plain-block",children:ee})]},R.key)}),!S&&t.jsxs("button",{type:"button",className:"agent-log-return-to-live",onClick:z,"data-testid":"agent-log-return-to-live",children:[t.jsx(sn,{size:12}),t.jsx("span",{children:"Live"})]})]})]})}function ka(e){return e??void 0}function uo(e){return{provider:ka(e.modelProvider),modelId:ka(e.modelId)}}function mo(e){return{provider:ka(e.validatorModelProvider),modelId:ka(e.validatorModelId)}}function ho(e){return{provider:ka(e.planningModelProvider),modelId:ka(e.planningModelId)}}function YM(e,n){return Ip(e,n)}function QM(e,n){return $p(e,n)}function XM(e,n){return Dp(e,n)}function Zl(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 ec(e){return e.provider&&e.modelId?`${e.provider}/${e.modelId}`:""}function tc(e,n){return e.provider===n.provider&&e.modelId===n.modelId}function ZM(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 eA({task:e,addToast:n,onTaskUpdated:s,settings:i}){const[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState([]),[m,h]=a.useState(!1),[f,p]=a.useState(null),[g,b]=a.useState(()=>uo(e)),[v,x]=a.useState(()=>uo(e)),[y,k]=a.useState(()=>mo(e)),[S,_]=a.useState(()=>mo(e)),[N,A]=a.useState(()=>ho(e)),[C,z]=a.useState(()=>ho(e)),[M,T]=a.useState(()=>e.thinkingLevel??null),[U,q]=a.useState(()=>e.thinkingLevel??null),[D,R]=a.useState(null),F=a.useRef(e.id);a.useEffect(()=>{h(!0),p(null),fs().then(de=>{o(de.models),c(de.favoriteProviders),d(de.favoriteModels)}).catch(de=>{p(de.message||"Failed to load models")}).finally(()=>{h(!1)})},[]);const V=a.useCallback(async de=>{const me=l,xe=me.includes(de)?me.filter(Re=>Re!==de):[de,...me];c(xe);try{await gn({favoriteProviders:xe,favoriteModels:u})}catch{c(me),n("Failed to update favorites","error")}},[l,u,n]),K=a.useCallback(async de=>{const me=u,xe=me.includes(de)?me.filter(Re=>Re!==de):[de,...me];d(xe);try{await gn({favoriteProviders:l,favoriteModels:xe})}catch{d(me),n("Failed to update model favorites","error")}},[u,l,n]);a.useEffect(()=>{F.current=e.id;const de=uo(e),me=mo(e),ie=ho(e);b(de),x(de),k(me),_(me),A(ie),z(ie);const xe=e.thinkingLevel??null;T(xe),q(xe),R(null)},[e.id,e.modelProvider,e.modelId,e.validatorModelProvider,e.validatorModelId,e.planningModelProvider,e.planningModelId,e.thinkingLevel]);const ee=a.useMemo(()=>ec(g),[g]),E=a.useMemo(()=>ec(y),[y]),$=a.useMemo(()=>ec(N),[N]),P=a.useMemo(()=>YM(e,i),[e,i]),w=a.useMemo(()=>QM(e,i),[e,i]),O=a.useMemo(()=>XM(e,i),[e,i]),Z=D!==null,Ne=a.useCallback(async(de,me)=>{const ie=e.id,xe=v,Re=S,Oe=C;R(de);try{const nt=s?de==="executor"?{modelProvider:me.provider??null,modelId:me.modelId??null}:de==="validator"?{validatorModelProvider:me.provider??null,validatorModelId:me.modelId??null}:{planningModelProvider:me.provider??null,planningModelId:me.modelId??null}:{modelProvider:(de==="executor"?me:v).provider??null,modelId:(de==="executor"?me:v).modelId??null,validatorModelProvider:(de==="validator"?me:S).provider??null,validatorModelId:(de==="validator"?me:S).modelId??null,planningModelProvider:(de==="planning"?me:C).provider??null,planningModelId:(de==="planning"?me:C).modelId??null},et=await ii(ie,nt);if(F.current!==ie)return;const Ze=uo(et),rt=mo(et),He=ho(et);x(Ze),b(Ze),_(rt),k(rt),z(He),A(He),s?.(et),n(ZM(de,{executor:Ze,validator:rt,planning:He}[de]),"success")}catch(nt){if(F.current!==ie)return;de==="executor"?b(xe):de==="validator"?k(Re):A(Oe),n(ke(nt)||"Failed to save model settings","error")}finally{F.current===ie&&R(null)}},[e.id,v,S,C,n,s]),se=a.useCallback(de=>{const me=Zl(de);b(me),!tc(me,v)&&Ne("executor",me)},[v,Ne]),le=a.useCallback(de=>{const me=Zl(de);k(me),!tc(me,S)&&Ne("validator",me)},[S,Ne]),we=a.useCallback(de=>{const me=Zl(de);A(me),!tc(me,C)&&Ne("planning",me)},[C,Ne]),L=a.useCallback(async de=>{const me=e.id,ie=U,xe=de===""?null:de;T(xe),R("thinking");try{const Re=await ii(me,{thinkingLevel:xe});if(F.current!==me)return;const Oe=Re.thinkingLevel??null;q(Oe),T(Oe),s?.(Re);const nt=i?.defaultThinkingLevel??"off";n(Oe===null?`Thinking level set to default (${nt})`:`Thinking level set to ${Oe}`,"success")}catch(Re){if(F.current!==me)return;T(ie),n(ke(Re)||"Failed to save thinking level","error")}finally{F.current===me&&R(null)}},[e.id,U,i,n,s]),ne=!v.provider&&!v.modelId,Q=!S.provider&&!S.modelId,be=!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…"}):f?t.jsxs("div",{className:"model-selector-error",children:["Error loading models: ",f,t.jsx("button",{className:"btn btn-sm",onClick:()=>{h(!0),p(null),fs().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:ne?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",P.provider&&P.modelId?` (${P.provider}/${P.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[v.provider&&t.jsx(An,{provider:v.provider,size:"sm"}),v.provider,"/",v.modelId]})}),t.jsx(Xn,{id:"executorModel",label:"Executor Model",value:ee,onChange:se,models:r,disabled:Z,placeholder:"Select executor model…",favoriteProviders:l,onToggleFavorite:V,favoriteModels:u,onToggleModelFavorite:K}),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:Q?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:[S.provider&&t.jsx(An,{provider:S.provider,size:"sm"}),S.provider,"/",S.modelId]})}),t.jsx(Xn,{id:"validatorModel",label:"Reviewer Model",value:E,onChange:le,models:r,disabled:Z,placeholder:"Select reviewer model…",favoriteProviders:l,onToggleFavorite:V,favoriteModels:u,onToggleModelFavorite:K}),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:be?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",O.provider&&O.modelId?` (${O.provider}/${O.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[C.provider&&t.jsx(An,{provider:C.provider,size:"sm"}),C.provider,"/",C.modelId]})}),t.jsx(Xn,{id:"planningModel",label:"Planning Model",value:$,onChange:we,models:r,disabled:Z,placeholder:"Select planning model…",favoriteProviders:l,onToggleFavorite:V,favoriteModels:u,onToggleModelFavorite:K}),t.jsx("small",{children:"The AI model used for task specification (triage phase)."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"thinkingLevel",children:"Thinking Level"}),t.jsx("div",{className:"model-selector-current",children:U===null?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default (",i?.defaultThinkingLevel??"off",")"]}):t.jsx("span",{className:"model-badge model-badge-custom",children:U})}),t.jsxs("select",{id:"thinkingLevel",value:M??"",onChange:de=>L(de.target.value),disabled:Z,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:ne&&Q&&be&&U===null?"Using project or global default models.":"Model settings are up to date."})]})]})}const tA={open:t.jsx(qo,{size:16}),closed:t.jsx(Tr,{size:16}),merged:t.jsx(op,{size:16})};function nA({taskId:e,projectId:n,prInfo:s,automationStatus:i,autoMerge:r=!1,prAuthAvailable:o,onPrCreated:l,onPrUpdated:c,addToast:u}){const[d,m]=a.useState(!1),[h,f]=a.useState(""),[p,g]=a.useState(""),[b,v]=a.useState(!1),[x,y]=a.useState(!1),[k,S]=a.useState(null),_=a.useCallback(async()=>{if(h.trim()){v(!0);try{const z=await qy(e,{title:h.trim(),body:p.trim()||void 0},n);l(z),m(!1),f(""),g(""),u(`Created PR #${z.number}`,"success")}catch(z){u(ke(z)||"Failed to create PR","error")}finally{v(!1)}}},[e,h,p,n,l,u]),N=a.useCallback(async()=>{if(s){y(!0);try{const z=await Vy(e,n);S(z),c(z.prInfo),u("PR status refreshed","success")}catch(z){u(ke(z)||"Failed to refresh PR","error")}finally{y(!1)}}},[e,s,n,c,u]);if(!s)return i==="creating-pr"?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Es,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsx("div",{className:"pr-hint pr-hint--muted",children:"fn is creating a pull request automatically for this task."})]}):r?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Es,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsx("div",{className:"pr-hint pr-hint--muted",children:"Auto-merge will handle this task automatically."})]}):d?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Es,{size:16,className:"pr-section-icon"}),"Create Pull Request"]}),t.jsxs("div",{className:"pr-form",children:[t.jsx("input",{type:"text",placeholder:"PR title",value:h,onChange:z=>f(z.target.value),disabled:b,className:"pr-input"}),t.jsx("textarea",{placeholder:"PR description (optional)",value:p,onChange:z=>g(z.target.value),disabled:b,className:"pr-textarea",rows:3}),t.jsxs("div",{className:"pr-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>m(!1),disabled:b,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:_,disabled:!h.trim()||b,children:b?"Creating…":"Create PR"})]})]})]}):t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Es,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>m(!0),disabled:!o,title:o?"Create a PR for this task":"PR auth unavailable — run 'gh auth login'",children:[t.jsx(ln,{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 A=tA[s.status]??t.jsx(qo,{size:16}),C=k?.blockingReasons??[];return t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Es,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsxs("div",{className:`pr-card pr-card--status-${s.status}`,children:[t.jsxs("div",{className:"pr-header",children:[t.jsx("span",{className:"pr-status-icon",children:A}),t.jsx("span",{className:`pr-status-badge pr-status-badge--${s.status}`,children:s.status}),t.jsxs("span",{className:"pr-number",children:["#",s.number]}),t.jsx("div",{className:"pr-spacer"}),t.jsx("button",{className:"btn btn-sm pr-refresh-btn",onClick:N,disabled:x,title:"Refresh PR status",children:t.jsx(Ln,{size:14,style:{verticalAlign:"middle",opacity:x?.5:1}})})]}),t.jsx("div",{className:"pr-title",children:s.title}),t.jsxs("div",{className:"pr-meta",children:[t.jsx("span",{children:s.headBranch}),t.jsx("span",{className:"pr-meta-arrow",children:"→"}),t.jsx("span",{children:s.baseBranch})]}),i==="merging-pr"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:"fn is merging this pull request automatically."}),i==="awaiting-pr-checks"&&t.jsx("div",{className:"pr-hint pr-hint--info",children: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(Ni,{size:14}),s.commentCount]}),t.jsxs("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"pr-link",children:[t.jsx(Db,{size:14}),"View on GitHub"]})]})]})]})}const nh=2e3;function sA(e){const n=e.updatedAt||e.createdAt,s=new Date(n).toLocaleString();return e.updatedAt?`${s} (edited)`:s}function iA(e){return e==="agent"||e==="system"}function aA({task:e,onTaskUpdated:n,addToast:s,currentAuthor:i="user",projectId:r}){const[o,l]=a.useState(""),[c,u]=a.useState(null),[d,m]=a.useState(""),[h,f]=a.useState(!1),[p,g]=a.useState(null),b=a.useMemo(()=>[...e.comments||[]].sort((A,C)=>new Date(C.createdAt).getTime()-new Date(A.createdAt).getTime()),[e.comments]),v=o.length>nh;async function x(){const A=o.trim();if(A){f(!0);try{const C=await by(e.id,A,r);l(""),n?.(C),s("Comment added","success")}catch(C){s(ke(C)||"Failed to add comment","error")}finally{f(!1)}}}async function y(A){const C=d.trim();if(C){f(!0);try{const z=await my(e.id,A,C,r);u(null),m(""),n?.(z),s("Comment updated","success")}catch(z){s(ke(z)||"Failed to update comment","error")}finally{f(!1)}}}async function k(A){g(A);try{const C=await hy(e.id,A,r);n?.(C),s("Comment deleted","success")}catch(C){s(ke(C)||"Failed to delete comment","error")}finally{g(null)}}function S(A){A.key==="Enter"&&(A.ctrlKey||A.metaKey)&&(A.preventDefault(),x())}return t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Comments"}),b.length===0?t.jsx("div",{className:"detail-log-empty",children:"No comments yet."}):t.jsx("div",{className:"detail-activity-list",children:b.map(A=>{const C=A.author===i,z=c===A.id,M=iA(A.author);return t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header comments-header-row",children:[t.jsxs("div",{className:"comments-author-row",children:[M?t.jsx("span",{className:"ai-guidance-badge","data-testid":"ai-guidance-badge",children:"AI Guidance"}):t.jsx("strong",{children:A.author}),t.jsx("span",{className:"detail-log-timestamp",children:sA(A)})]}),C&&!z?t.jsxs("div",{className:"comments-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{u(A.id),m(A.text)},children:"Edit"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void k(A.id),disabled:p===A.id,children:p===A.id?"Deleting…":"Delete"})]}):null]}),z?t.jsxs("div",{className:"comments-edit-form",children:[t.jsx("textarea",{value:d,onChange:T=>m(T.target.value),rows:3,className:"comments-textarea"}),t.jsxs("div",{className:"comments-edit-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{u(null),m("")},disabled:h,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void y(A.id),disabled:h||!d.trim(),children:"Save"})]})]}):t.jsx("div",{className:"detail-log-outcome comments-outcome-text",children:A.text})]},A.id)})}),t.jsxs("div",{className:"comments-compose-form",children:[t.jsx("textarea",{value:o,onChange:A=>l(A.target.value),onKeyDown:S,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," / ",nh]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void x(),disabled:h||!o.trim()||v,children:h?"Posting…":"Add Comment"})]})]})]})}function rA(e){return e?e.slice(0,7):"Unknown"}function oA({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:rA(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 cg(e){return e.split(`
|
|
652
|
+
`).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}
|
|
653
|
+
`},i):t.jsx(So.Fragment,{children:`${s}
|
|
654
|
+
`},i)})}function lA(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function cA({isOpen:e,taskId:n,files:s,stats:i,mergeDetails:r,column:o,onClose:l,onRefresh:c}){const[u,d]=a.useState(null),[m,h]=a.useState(!0),f=a.useRef(null);ci(f,e,"fusion:changes-diff-modal-size");const p=_i(l);a.useEffect(()=>{s.length>0&&u===null&&d(0)},[s,u]);const g=a.useCallback(()=>{d(y=>y!==null&&y>0?y-1:y)},[]),b=a.useCallback(()=>{d(y=>y!==null&&y<s.length-1?y+1:y)},[]);if(a.useEffect(()=>{if(!e)return;const y=k=>{if(k.key==="Escape"){l();return}k.key==="ArrowUp"&&(k.metaKey||k.ctrlKey)&&(k.preventDefault(),g()),k.key==="ArrowDown"&&(k.metaKey||k.ctrlKey)&&(k.preventDefault(),b())};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[e,l,g,b]),!e)return null;const v=u!==null?s[u]:null,x=o==="done";return t.jsx("div",{className:"modal-overlay open",...p,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal changes-diff-modal",ref:f,children:[t.jsxs("div",{className:"modal-header changes-diff-modal-header",children:[t.jsxs("div",{className:"changes-diff-header-title",children:[t.jsx(Hs,{size:18}),t.jsxs("span",{children:["Changes — ",n]}),t.jsxs("span",{className:"changes-stat-summary",children:[t.jsxs("span",{className:"diff-add",children:["+",i.additions]})," ",t.jsxs("span",{className:"diff-del",children:["-",i.deletions]})]})]}),t.jsxs("div",{className:"changes-diff-header-actions",children:[s.length>0&&t.jsxs("div",{className:"changes-nav",children:[t.jsx("button",{className:"btn btn-sm btn-icon",onClick:g,disabled:u===null||u<=0,title:"Previous file (Ctrl+↑)","aria-label":"Previous file",children:t.jsx(Ho,{size:14})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:u!==null?`${u+1}/${s.length}`:`—/${s.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:b,disabled:u===null||u>=s.length-1,title:"Next file (Ctrl+↓)","aria-label":"Next file",children:t.jsx(kn,{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(_o,{size:14})}),c&&t.jsxs("button",{className:"btn btn-sm",onClick:c,children:[t.jsx(Ln,{size:14}),"Refresh"]}),t.jsx("button",{className:"modal-close",onClick:l,"aria-label":"Close",children:t.jsx(Kt,{size:20})})]})]}),t.jsxs("div",{className:"changes-diff-body",children:[t.jsxs("div",{className:"changes-diff-sidebar",children:[x&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(Pr,{size:14}),t.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergeCommitMessage&&t.jsx("div",{className:"commit-diff-message",children:r.mergeCommitMessage}),r.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),t.jsx("div",{className:"changes-diff-file-list",children:s.map((y,k)=>t.jsxs("button",{className:`changes-diff-file-item ${u===k?"selected":""}`,onClick:()=>d(k),title:y.path,children:[t.jsx("span",{className:`changes-file-status changes-file-status--${y.status}`,children:lA(y.status)}),t.jsx("span",{className:"changes-diff-file-path",title:y.path,children:t.jsx("bdo",{dir:"ltr",children:y.path})}),t.jsxs("span",{className:"changes-diff-file-stat",children:["+",y.additions," -",y.deletions]})]},y.path))})]}),t.jsx("div",{className:"changes-diff-content",children:v?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"changes-diff-file-header-bar",children:[t.jsx("span",{className:"changes-diff-file-header-name",children:v.path}),t.jsxs("span",{className:"changes-diff-file-header-stats",children:["+",v.additions," -",v.deletions]})]}),v.patch?t.jsx("div",{className:"changes-diff-viewer",children:t.jsx("pre",{className:`changes-diff-patch ${m?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:t.jsx("code",{children:cg(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(Hs,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to view its diff"})]})})]})]})})}function dg(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function nc(e,n,s){return t.jsxs("div",{className:"detail-section task-changes-tab",children:[n&&s&&t.jsxs("div",{className:"commit-diff-meta",children:[s.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(Pr,{size:14}),t.jsx("code",{children:s.commitSha.slice(0,7)})]}),s.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(s.mergedAt).toLocaleString()]})]}),t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Hs,{size:24}),t.jsxs("p",{children:[e.length," file",e.length===1?"":"s"," modified during execution."]}),t.jsx("span",{className:"task-changes-state-hint",children:n?"The recorded merge commit has no diff (likely collapsed into a squash on main). Showing file paths only — patches unavailable.":"The live worktree diff is empty. Showing the last file paths captured during execution — patches unavailable."})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:e.map(i=>t.jsx("div",{className:"changes-file-item",children:t.jsxs("div",{className:"changes-file-header changes-file-header--static",children:[t.jsx("span",{className:"changes-file-status changes-file-status--unknown",title:"status unknown",children:dg("unknown")}),t.jsx("span",{className:"changes-file-path",title:i,children:t.jsx("bdo",{dir:"ltr",children:i})})]})},i))})]})}function dA({taskId:e,worktree:n,projectId:s,column:i,mergeDetails:r,modifiedFiles:o}){const[l,c]=a.useState([]),[u,d]=a.useState({filesChanged:0,additions:0,deletions:0}),[m,h]=a.useState(!0),[f,p]=a.useState(null),[g,b]=a.useState(new Set),[v,x]=a.useState(null),[y,k]=a.useState(!0),[S,_]=a.useState(!1),N=i==="done",A=N&&!!r?.commitSha,C=i==="in-progress"||i==="in-review"||A,z=a.useCallback(async()=>{if(!C){h(!1);return}try{h(!0),p(null);const D=await Cp(e,void 0,s),R=D.files.map(F=>({path:F.path,status:F.status,additions:F.additions,deletions:F.deletions,patch:F.patch}));c(R),d(D.stats),R.length>0&&(b(new Set([R[0].path])),x(0))}catch(D){p(ke(D)||"Failed to load diff")}finally{h(!1)}},[e,s,C]);a.useEffect(()=>{z()},[z]);const M=D=>{b(R=>{const F=new Set(R);if(F.has(D))F.delete(D);else{F.add(D);const V=l.findIndex(K=>K.path===D);V!==-1&&x(V)}return F})},T=D=>{if(D<0||D>=l.length)return;const R=l[D].path;b(new Set([R])),x(D)},U=v!==null&&v>0,q=v!==null&&v<l.length-1;if(m)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--loading",children:[t.jsx("div",{className:"loading-spinner"}),t.jsx("span",{children:"Loading changes..."})]})});if(f)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--error",children:[t.jsx(ps,{size:16}),t.jsxs("span",{children:["Error loading changes: ",f]})]})});if(!N&&!n)return o&&o.length>0?nc(o,!1):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Hs,{size:24}),t.jsx("p",{children:"No worktree available for this task."}),t.jsx("span",{className:"task-changes-state-hint",children:"Changes will be shown once the task is in progress."})]})});if(N&&!A){if(o&&o.length>0)return nc(o,!0,r);const D=r?.filesChanged,R=r?.insertions,F=r?.deletions,V=D!=null||R!=null||F!=null;return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Hs,{size:24}),t.jsx("p",{children:"Detailed file changes unavailable."}),t.jsx("span",{className:"task-changes-state-hint",children:V?`Merge summary: ${D??0} file${(D??0)===1?"":"s"} changed, +${R??0} additions, -${F??0} deletions.`:"No merge commit was recorded for this task."})]})})}return l.length===0?o&&o.length>0?nc(o,N,r):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Hs,{size:24}),t.jsx("p",{children:"No files modified."}),t.jsx("span",{className:"task-changes-state-hint",children:N?"No file changes were recorded in the merge commit.":"The agent did not modify any files during execution."})]})}):t.jsxs("div",{className:"detail-section task-changes-tab",children:[N&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(Pr,{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(Hs,{size:16}),"Files Changed (",u.filesChanged,")"]}),t.jsxs("span",{className:"task-changes-stats changes-stat-summary",children:[t.jsxs("span",{className:"diff-add",children:["+",u.additions]})," ",t.jsxs("span",{className:"diff-del",children:["-",u.deletions]})]})]}),t.jsxs("div",{className:"changes-header-actions-wrapper",children:[t.jsxs("div",{className:"changes-header-actions",children:[l.length>0&&t.jsxs("div",{className:"changes-nav",children:[t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>U&&T(v-1),disabled:!U,title:"Previous file","aria-label":"Previous file",children:t.jsx(Ho,{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:()=>q&&T(v+1),disabled:!q,title:"Next file","aria-label":"Next file",children:t.jsx(kn,{size:14})})]}),t.jsx("button",{className:`btn btn-sm ${y?"btn-primary":""}`,onClick:()=>k(D=>!D),title:y?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(_o,{size:14})})]}),t.jsxs("div",{className:"changes-header-actions-secondary",children:[t.jsx("button",{className:"btn btn-sm",onClick:z,disabled:m,children:"Refresh"}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>_(!0),title:"Expand to full-screen diff view","aria-label":"Expand diff view",children:t.jsx(Go,{size:14})})]})]})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:l.map(D=>{const R=g.has(D.path);return t.jsxs("div",{className:`changes-file-item ${R?"expanded":""}`,children:[t.jsxs("button",{className:"changes-file-header",onClick:()=>M(D.path),children:[t.jsx("span",{className:"changes-file-toggle",children:R?t.jsx(sn,{size:14}):t.jsx(kn,{size:14})}),t.jsx("span",{className:`changes-file-status changes-file-status--${D.status}`,title:D.status,children:dg(D.status)}),t.jsx("span",{className:"changes-file-path",title:D.path,children:t.jsx("bdo",{dir:"ltr",children:D.path})}),t.jsxs("span",{className:"changes-file-stat",title:`+${D.additions} -${D.deletions}`,children:["+",D.additions," -",D.deletions]})]}),R&&D.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:cg(D.patch)})})})]},D.path)})}),t.jsx(cA,{isOpen:S,taskId:e,files:l,stats:u,mergeDetails:r,column:i,onClose:()=>_(!1),onRefresh:z})]})}function sh(e){return{executorValue:e?.executorProvider&&e?.executorModelId?`${e.executorProvider}/${e.executorModelId}`:"",validatorValue:e?.validatorProvider&&e?.validatorModelId?`${e.validatorProvider}/${e.validatorModelId}`:""}}function uA(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function YL(e,n){const s=uA(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 mA(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}const ih=["image/png","image/jpeg","image/gif","image/webp"];function hA(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 ug({mode:e,description:n,onDescriptionChange:s,title:i,onTitleChange:r,dependencies:o,onDependenciesChange:l,nodeId:c,onNodeIdChange:u,nodeOptions:d,nodeOverrideDisabled:m=!1,nodeOverrideDisabledReason:h,priority:f,onPriorityChange:p,executorModel:g,onExecutorModelChange:b,validatorModel:v,onValidatorModelChange:x,planningModel:y,onPlanningModelChange:k,thinkingLevel:S,onThinkingLevelChange:_,presetMode:N,onPresetModeChange:A,selectedPresetId:C,onSelectedPresetIdChange:z,selectedWorkflowSteps:M,onWorkflowStepsChange:T,onDefaultOnApplied:U,pendingImages:q,onImagesChange:D,tasks:R,projectId:F,disabled:V=!1,addToast:K,isActive:ee=!0,onAutoSaveDescription:E,onPlanningMode:$,onSubtaskBreakdown:P,onClose:w,renderBelowPrimary:O,renderBelowModelConfiguration:Z,hideDependencies:Ne,autoExpandMoreOptionsOnSelection:se=!0,reviewLevel:le,onReviewLevelChange:we,executionMode:L,onExecutionModeChange:ne}){const Q=(Ne?!1:o.length>0)||q.length>0||M.length>0||N!=="default"||(f??_s)!==_s||g!==""||v!==""||(y||"")!==""||(S||"")!==""||le!==void 0||L==="fast"||(c||"")!=="",[be,de]=a.useState(!1),[me,ie]=a.useState(se?Q:!1),[xe,Re]=a.useState(""),[Oe,nt]=a.useState([]),[et,Ze]=a.useState([]),[rt,He]=a.useState([]),[Ge,oe]=a.useState(!1),[je,X]=a.useState(null),[Ae,Te]=a.useState([]),[pe,_e]=a.useState("idle"),[Fe,it]=a.useState(!1),[ve,ce]=a.useState(!1),[Ie,he]=a.useState(!1),Me=a.useRef(null),Je=a.useRef(null),$e=a.useRef(null),ft=a.useRef(null),J=a.useRef(null),re=a.useRef(null),ye=a.useRef(null),at=a.useRef(!1),te=a.useRef(Q),Ye=a.useRef(n.trim()),mt=a.useRef(n.trim());a.useEffect(()=>{ee&&(oe(!0),fs().then(j=>{nt(j.models),Ze(j.favoriteProviders),He(j.favoriteModels)}).catch(()=>{}).finally(()=>oe(!1)),Yo(F).then(j=>X(j)).catch(()=>X(null)),Qo(F).then(j=>Te(j.filter(Y=>Y.enabled))).catch(()=>Te([])))},[ee,F]);const ht=je?.modelPresets||[],xt=ht.find(j=>j.id===C),St=(Ne?!1:o.length>0)||q.length>0||M.length>0||N!=="default"||(f??_s)!==_s||g!==""||v!==""||(y||"")!==""||(S||"")!==""||le!==void 0||L==="fast"||(c||"")!=="";a.useEffect(()=>{if(e!=="create"||!ee||!je?.autoSelectModelPreset)return;const j=(je.defaultPresetBySize,void 0);if(j){const Y=sh(j);z(j.id),A("preset"),b(Y.executorValue),x(Y.validatorValue)}},[ee,je,ht,e]);const bt=a.useRef(!1);a.useEffect(()=>{if(e!=="create"||!ee||bt.current||Ae.length===0)return;const j=Ae.filter(fe=>fe.defaultOn);if(j.length===0)return;bt.current=!0;const Y=j.map(fe=>fe.id);T(Y),U?.(Y)},[e,ee,Ae]),a.useEffect(()=>{ee||(bt.current=!1)},[ee]),a.useEffect(()=>{if(!se){te.current=St;return}St&&!te.current&&ie(!0),te.current=St},[St,se]),a.useEffect(()=>{me||(de(!1),Re(""))},[me]),a.useEffect(()=>{e!=="edit"||!ee||ft.current&&(ft.current.focus(),ft.current.select())},[e,ee]),a.useEffect(()=>{if(!be)return;const j=Y=>{Je.current&&!Je.current.contains(Y.target)&&de(!1)};return document.addEventListener("mousedown",j),()=>document.removeEventListener("mousedown",j)},[be]),a.useEffect(()=>{(e!=="edit"||V)&&he(!1)},[e,V]),a.useEffect(()=>{if(e!=="edit"){_e("idle");return}const j=n.trim();Ye.current=j,mt.current=j,_e("idle")},[e]),a.useEffect(()=>{if(e!=="edit"||!E||!ee)return;const j=n.trim(),Y=Ye.current;if(j===Y||j===mt.current){re.current&&(clearTimeout(re.current),re.current=null),at.current||_e("idle");return}return re.current&&clearTimeout(re.current),re.current=setTimeout(async()=>{if(!at.current){at.current=!0,_e("saving");try{await E(j),mt.current=j,_e("saved"),ye.current&&clearTimeout(ye.current),ye.current=setTimeout(()=>{_e("idle"),ye.current=null},2e3)}catch{_e("idle")}finally{at.current=!1,re.current=null}}},1500),()=>{re.current&&(clearTimeout(re.current),re.current=null)}},[e,n,E,ee]),a.useEffect(()=>()=>{re.current&&clearTimeout(re.current),ye.current&&clearTimeout(ye.current)},[]),a.useEffect(()=>{if(!Fe)return;const j=Y=>{Me.current&&!Me.current.contains(Y.target)&&it(!1)};return document.addEventListener("mousedown",j),()=>document.removeEventListener("mousedown",j)},[Fe]);const Nt=a.useCallback(j=>{const Y=j.clipboardData?.items;if(Y)for(let fe=0;fe<Y.length;fe++){const Pe=Y[fe];if(Pe.type.startsWith("image/")){const We=Pe.getAsFile();if(We&&ih.includes(We.type)){j.preventDefault(),D([...q,{file:We,previewUrl:URL.createObjectURL(We)}]);return}}}},[q,D]),Qt=a.useCallback(j=>{j.preventDefault();const Y=j.dataTransfer.files;for(let fe=0;fe<Y.length;fe++){const Pe=Y[fe];if(ih.includes(Pe.type)){D([...q,{file:Pe,previewUrl:URL.createObjectURL(Pe)}]);return}}},[q,D]),Pt=a.useCallback(j=>{const Y=q[j];Y&&URL.revokeObjectURL(Y.previewUrl),D(q.filter((fe,Pe)=>Pe!==j))},[q,D]),Dt=a.useCallback(j=>{l(o.includes(j)?o.filter(Y=>Y!==j):[...o,j])},[o,l]),Et=(j,Y)=>j.length>Y?j.slice(0,Y)+"…":j,Xt=a.useCallback(j=>{s(j.target.value);const Y=j.target;Y.style.height="auto",Y.style.height=Y.scrollHeight+"px"},[s]),Lt=a.useCallback(()=>{he(j=>!j)},[]),Ft=a.useCallback(j=>{!Ie||j.key!=="Escape"||(j.preventDefault(),j.stopPropagation(),he(!1))},[Ie]),zt=a.useCallback(async j=>{const Y=n.trim();if(!(!Y||ve)){ce(!0);try{const fe=await kp(Y,j,F);s(fe),it(!1),K("Description refined with AI","success"),$e.current&&($e.current.style.height="auto",$e.current.style.height=$e.current.scrollHeight+"px")}catch(fe){const Pe=wp(fe);K(Pe,"error")}finally{ce(!1)}}},[n,ve,K,s,F]),Tt=a.useCallback(async j=>{const Y=et,Pe=Y.includes(j)?Y.filter(We=>We!==j):[j,...Y];Ze(Pe);try{await gn({favoriteProviders:Pe,favoriteModels:rt})}catch{Ze(Y)}},[et,rt]),Gt=a.useCallback(async j=>{const Y=rt,Pe=Y.includes(j)?Y.filter(We=>We!==j):[j,...Y];He(Pe);try{await gn({favoriteProviders:et,favoriteModels:Pe})}catch{He(Y)}},[rt,et]),Ot=a.useCallback(j=>{if(j<=0)return;const Y=[...M];[Y[j-1],Y[j]]=[Y[j],Y[j-1]],T(Y)},[M,T]),qt=a.useCallback(j=>{if(j>=M.length-1)return;const Y=[...M];[Y[j],Y[j+1]]=[Y[j+1],Y[j]],T(Y)},[M,T]),nn=a.useCallback(j=>{T(M.filter(Y=>Y!==j))},[M,T]),ge=new Map;for(const j of Ae)ge.set(j.id,{name:j.name,description:j.description});const ze=R.filter(j=>!o.includes(j.id)).sort((j,Y)=>{const fe=Y.createdAt.localeCompare(j.createdAt);if(fe!==0)return fe;const Pe=parseInt(j.id.slice(j.id.lastIndexOf("-")+1),10)||0;return(parseInt(Y.id.slice(Y.id.lastIndexOf("-")+1),10)||0)-Pe}),dt=xe?ze.filter(j=>j.id.toLowerCase().includes(xe.toLowerCase())||j.title&&j.title.toLowerCase().includes(xe.toLowerCase())||j.description&&j.description.toLowerCase().includes(xe.toLowerCase())):ze;return t.jsxs("div",{className:"task-form",onDrop:Qt,onDragOver:j=>j.preventDefault(),onPaste:Nt,children:[t.jsxs("div",{className:"task-form-primary-section",children:[e==="edit"&&r&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"task-form-title",children:"Title"}),t.jsx("input",{ref:ft,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:"Task title",value:i||"",onChange:j=>r(j.target.value),disabled:V})]}),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${Ie?" description--fullscreen":""}`,ref:Me,onKeyDown:Ft,children:[Ie&&t.jsxs("div",{className:"description-fullscreen-header",children:[t.jsx("span",{children:"Editing Description"}),t.jsx("button",{type:"button",className:"btn btn-sm description-expand-btn",onClick:Lt,"aria-label":"Collapse description",title:"Collapse description",children:t.jsx(Ir,{size:14})})]}),t.jsx("textarea",{ref:$e,autoFocus:e==="create",id:"task-form-description",value:n,onChange:Xt,placeholder:"What needs to be done?",rows:e==="edit"?8:5,disabled:V||ve}),(()=>{const j=!!n.trim()&&!V;return t.jsxs(t.Fragment,{children:[!Ie&&t.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${j?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:Lt,"aria-label":"Expand description",title:"Expand description",children:t.jsx(Go,{size:14})}),j&&t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${ve?"refine-button--loading":""}`,onClick:()=>it(Y=>!Y),disabled:ve,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(os,{size:12,style:{verticalAlign:"middle"}}),ve?"Refining...":"Refine"]})]})})(),Fe&&t.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:j=>j.preventDefault(),children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>zt("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:()=>zt("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:()=>zt("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:()=>zt("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"&&($||P)&&t.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[$&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const j=n.trim();if(!j){K("Enter a description first","error");return}w?.(),$(j)},disabled:V||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),P&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const j=n.trim();if(!j){K("Enter a description first","error");return}w?.(),P(j)},disabled:V||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),O,t.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>ie(j=>!j),"aria-expanded":me,"aria-controls":"task-form-more-options",disabled:V,"data-testid":"task-form-more-options-toggle",children:[t.jsx("span",{children:"More options"}),me?t.jsx(gi,{size:14}):t.jsx(sn,{size:14})]}),t.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${me?"":" collapsed"}`,"aria-hidden":!me,hidden:!me,"data-testid":"task-form-more-options",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Attachments"}),q.length>0&&t.jsx("div",{className:"inline-create-previews",children:q.map((j,Y)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:j.previewUrl,alt:j.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>Pt(Y),disabled:V,title:"Remove image",children:"×"})]},j.previewUrl))}),t.jsx("input",{ref:J,type:"file",accept:"image/*",onChange:j=>{const Y=j.target.files?.[0];Y&&(D([...q,{file:Y,previewUrl:URL.createObjectURL(Y)}]),j.target.value="")},style:{display:"none"}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>J.current?.click(),disabled:V,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:j=>u(j.target.value||void 0),disabled:V||m,children:[t.jsx("option",{value:"",children:"Use project default / local"}),(d??[]).map(j=>t.jsxs("option",{value:j.id,children:[j.name," (",mA(j.status),")"]},j.id))]}),(()=>{const j=(d??[]).find(Y=>Y.id===c);return j?t.jsx("div",{className:"task-form-node-status",children:t.jsx(Vi,{status:j.status,showLabel:!0})}):null})(),t.jsx("small",{children:h??"Task override takes priority over project default node routing."})]}),!Ne&&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:Je,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>de(j=>!j),disabled:V,children:o.length>0?`${o.length} selected`:"Add dependencies"}),be&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:xe,onChange:j=>Re(j.target.value),onClick:j=>j.stopPropagation()}),dt.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):dt.map(j=>t.jsxs("div",{className:`dep-dropdown-item${o.includes(j.id)?" selected":""}`,onClick:()=>Dt(j.id),onMouseDown:Y=>Y.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:j.id}),t.jsx("span",{className:"dep-dropdown-title",children:Et(j.title||j.description||j.id,30)})]},j.id))]})]}),o.length>0&&t.jsx("div",{className:"selected-deps",children:o.map(j=>t.jsxs("span",{className:"dep-chip",children:[j,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>Dt(j),disabled:V,children:"×"})]},j))})]})}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Model Configuration"}),p&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"task-priority",className:"model-select-label",children:"Priority"}),t.jsx("select",{id:"task-priority","data-testid":"task-priority-select",value:f??_s,onChange:j=>p(j.target.value),disabled:V,children:fd.map(j=>t.jsx("option",{value:j,children:j[0].toUpperCase()+j.slice(1)},j))})]}),ne&&L!==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:L,onChange:j=>ne(j.target.value),disabled:V,children:[t.jsx("option",{value:"standard",children:"Standard"}),t.jsx("option",{value:"fast",children:"Fast"})]})]}),Ge?t.jsx("div",{className:"model-selector-loading",children:"Loading models…"}):Oe.length===0?t.jsx("small",{children:"No models available. Configure authentication in Settings."}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"model-preset",className:"model-select-label",children:"Preset"}),t.jsxs("select",{id:"model-preset",value:N==="preset"?C:N,onChange:j=>{const Y=j.target.value;if(Y==="default"){A("default"),z(""),b(""),x("");return}if(Y==="custom"){A("custom"),z("");return}const fe=ht.find(We=>We.id===Y),Pe=sh(fe);A("preset"),z(Y),b(Pe.executorValue),x(Pe.validatorValue)},disabled:V,children:[t.jsx("option",{value:"default",children:"Use default"}),ht.length>0?t.jsx("option",{disabled:!0,children:"──────────"}):null,ht.map(j=>t.jsx("option",{value:j.id,children:j.name},j.id)),t.jsx("option",{value:"custom",children:"Custom"})]})]}),N==="preset"&&xt?t.jsxs("small",{children:["Using preset: ",xt.name]}):null,N==="preset"?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>A("custom"),disabled:V,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(Xn,{id:"executor-model",label:"Executor Model",value:g,onChange:j=>{A("custom"),z(""),b(j)},models:Oe,disabled:V||N==="preset",favoriteProviders:et,onToggleFavorite:Tt,favoriteModels:rt,onToggleModelFavorite:Gt})]}),t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"validator-model",className:"model-select-label",children:"Reviewer"}),t.jsx(Xn,{id:"validator-model",label:"Reviewer Model",value:v,onChange:j=>{A("custom"),z(""),x(j)},models:Oe,disabled:V||N==="preset",favoriteProviders:et,onToggleFavorite:Tt,favoriteModels:rt,onToggleModelFavorite:Gt})]}),k&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"planning-model",className:"model-select-label",children:"Planning"}),t.jsx(Xn,{id:"planning-model",label:"Planning Model",value:y||"",onChange:j=>{A("custom"),z(""),k(j)},models:Oe,disabled:V||N==="preset",favoriteProviders:et,onToggleFavorite:Tt,favoriteModels:rt,onToggleModelFavorite:Gt})]}),_&&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:S||"",onChange:j=>_(j.target.value),disabled:V||N==="preset",children:[t.jsxs("option",{value:"",children:["Default (",je?.defaultThinkingLevel??"off",")"]}),t.jsx("option",{value:"off",children:"Off"}),t.jsx("option",{value:"minimal",children:"Minimal"}),t.jsx("option",{value:"low",children:"Low"}),t.jsx("option",{value:"medium",children:"Medium"}),t.jsx("option",{value:"high",children:"High"})]})]}),we&&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:j=>we(j.target.value===""?void 0:parseInt(j.target.value,10)),disabled:V,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"})]})]})]})]}),Z,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(j=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${j.id}`,children:[t.jsx("input",{type:"checkbox",checked:M.includes(j.id),onChange:Y=>{T(Y.target.checked?[...M,j.id]:M.filter(fe=>fe!==j.id))},disabled:V}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[j.name,hA(j.phase||"pre-merge",j.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:j.description})]})]},j.id))})]}),M.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),M.map((j,Y)=>{const fe=ge.get(j);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${j}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:Y+1}),t.jsx("span",{className:"workflow-step-order-name",children:fe?.name||j}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Ot(Y),disabled:V||Y===0,"data-testid":`workflow-step-move-up-${j}`,title:"Move up",children:t.jsx(gi,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>qt(Y),disabled:V||Y===M.length-1,"data-testid":`workflow-step-move-down-${j}`,title:"Move down",children:t.jsx(sn,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>nn(j),disabled:V,"data-testid":`workflow-step-remove-${j}`,title:"Remove",children:t.jsx(Kt,{size:14})})]})]},j)})]})]})]})]})}const ah={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 pA(e){switch(e){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return e}}function fA(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 gA(e){return e?new Date(e).toLocaleString():null}function bA(e){const n=e.split(`
|
|
655
|
+
`);return n.length<=1?e:`${n.length} lines`}function po(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 xA({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 vA({taskId:e,results:n,loading:s,enabledWorkflowSteps:i,canEdit:r,projectId:o,isTaskInProgress:l,onWorkflowStepsChange:c}){const[u,d]=a.useState({}),[m,h]=a.useState({}),[f,p]=a.useState(null),[g,b]=a.useState([]),[v,x]=a.useState(!1),y=n.some(w=>w.status==="pending"),{entries:k}=og(e,!!l&&y,o);a.useEffect(()=>{let w=!1;return Qo(o).then(O=>{w||b(O.filter(Z=>Z.enabled))}).catch(()=>{w||b([])}),()=>{w=!0}},[o]);const S=i??[],_=a.useMemo(()=>g.map(w=>({id:w.id,name:w.name,description:w.description,phase:w.phase||"pre-merge"})),[g]),N=a.useMemo(()=>new Map(_.map(w=>[w.id,w])),[_]),A=w=>{d(O=>({...O,[w]:!O[w]}))},C=w=>{h(O=>{const Z=O[w]??"markdown";return{...O,[w]:Z==="markdown"?"plain":"markdown"}})},z=w=>{p(w)},M=()=>{p(null)};a.useEffect(()=>{if(!f)return;const w=O=>{O.key==="Escape"&&M()};return document.addEventListener("keydown",w),()=>{document.removeEventListener("keydown",w)}},[f]);const T=a.useCallback((w,O)=>{if(c){if(O){if(S.includes(w)){c(S);return}c([...S,w]);return}c(S.filter(Z=>Z!==w))}},[c,S]),U=a.useCallback(w=>{if(!c||w<=0)return;const O=[...S];[O[w-1],O[w]]=[O[w],O[w-1]],c(O)},[c,S]),q=a.useCallback(w=>{if(!c||w>=S.length-1)return;const O=[...S];[O[w],O[w+1]]=[O[w+1],O[w]],c(O)},[c,S]),D=a.useCallback(w=>{c&&c(S.filter(O=>O!==w))},[c,S]),R=n.length>0,F=S.length>0;a.useEffect(()=>{r||x(!1)},[r]);const V=a.useMemo(()=>S.map(w=>{const O=N.get(w);return{id:w,name:O?.name||w,description:O?.description||"Step definition not found.",phase:O?.phase||"pre-merge"}}),[S,N]),K=()=>!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:_.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:S.includes(w.id),onChange:O=>T(w.id,O.target.checked)}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[w.name,po(w.phase,w.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:w.description})]})]},w.id))})]}),S.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:"}),S.map((w,O)=>{const Z=N.get(w);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${w}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:O+1}),t.jsx("span",{className:"workflow-step-order-name",children:Z?.name||w}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>U(O),disabled:O===0,"data-testid":`workflow-step-move-up-${w}`,title:"Move up",children:t.jsx(gi,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>q(O),disabled:O===S.length-1,"data-testid":`workflow-step-move-down-${w}`,title:"Move down",children:t.jsx(sn,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>D(w),"data-testid":`workflow-step-remove-${w}`,title:"Remove",children:t.jsx(Kt,{size:14})})]})]},w)})]})]}),ee=()=>{if(s)return t.jsxs("div",{className:"workflow-results-loading","data-testid":"workflow-results-loading",children:[t.jsx("div",{className:"workflow-results-spinner"}),t.jsx("span",{children:"Loading workflow results…"})]});if(!R)return t.jsxs("div",{className:"workflow-results-empty","data-testid":"workflow-results-empty",children:[t.jsx("p",{children:"No workflow steps configured for this task."}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."})]});const w=n.filter(le=>le.status==="passed").length,O=n.filter(le=>le.status==="failed").length,Z=n.filter(le=>le.status==="skipped").length,Ne=n.filter(le=>le.status==="pending").length,se=[`${n.length} step${n.length!==1?"s":""}`];return w>0&&se.push(`${w} passed`),O>0&&se.push(`${O} failed`),Z>0&&se.push(`${Z} skipped`),Ne>0&&se.push(`${Ne} 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:se.join(" · ")}),n.map((le,we)=>{const L=le.phase||"pre-merge",ne=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,po(L,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:pA(le.status)})]}),t.jsxs("div",{className:"workflow-result-meta",children:[le.startedAt&&t.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",gA(le.startedAt)]}),le.completedAt&&t.jsx("span",{className:"workflow-result-duration",children:fA(le.startedAt,le.completedAt)})]}),le.status==="pending"&&le.startedAt?t.jsx(xA,{entries:k,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:()=>A(le.workflowStepId),"data-testid":`workflow-result-toggle-${le.workflowStepId}`,children:ne?"Hide output":"Show output"}),!ne&&t.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${le.workflowStepId}`,children:bA(le.output)}),ne&&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:()=>z(le.workflowStepId),"data-testid":`workflow-result-expand-${le.workflowStepId}`,title:"Expand output",children:t.jsx(Go,{size:12})})]})]}),ne&&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(oi,{remarkPlugins:[li],components:ah,children:le.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:le.output})})]}):null]},`${le.workflowStepId}-${we}`)})]})},E=r?t.jsx("button",{type:"button",className:"modal-edit-btn workflow-results-edit-toggle",onClick:()=>x(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(qn,{size:14}),"Done"]}):t.jsxs(t.Fragment,{children:[t.jsx(ms,{size:14}),"Edit"]})}):null,$=!s&&!R&&F,P=r&&R;return t.jsxs("div",{className:"workflow-results-tab","data-task-id":e,children:[$?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:[V.length," step",V.length===1?"":"s"]})]}),E]}),t.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:V.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,po(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."}),K()]}):t.jsxs(t.Fragment,{children:[P&&t.jsxs("div",{className:"workflow-results-edit-header","data-testid":"workflow-results-edit-header",children:[t.jsx("h4",{children:"Workflow Steps"}),E]}),ee(),K()]}),f&&(()=>{const w=n.find(Ne=>Ne.workflowStepId===f);if(!w)return null;const O=m[w.workflowStepId]??"markdown",Z=w.phase||"pre-merge";return t.jsx("div",{className:"workflow-output-modal-overlay",onClick:Ne=>{Ne.target===Ne.currentTarget&&M()},"data-testid":"workflow-output-modal",children:t.jsxs("div",{className:"workflow-output-modal",role:"dialog","aria-modal":"true",children:[t.jsxs("div",{className:"workflow-output-modal-header",children:[t.jsxs("div",{className:"workflow-output-modal-title",children:[t.jsx("span",{className:"workflow-output-modal-name",children:w.workflowStepName}),po(Z,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:O==="markdown"?"Switch to plain text":"Switch to markdown",children:O==="markdown"?"Markdown":"Plain"}),t.jsx("button",{className:"workflow-output-modal-close",onClick:M,"data-testid":"workflow-output-modal-close","aria-label":"Close",children:t.jsx(Kt,{size:16})})]})]}),t.jsx("div",{className:"workflow-output-modal-body",children:t.jsx("div",{className:`workflow-result-output workflow-result-output--expanded${O==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":"workflow-output-modal-content",children:O==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(oi,{remarkPlugins:[li],components:ah,children:w.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:w.output})})})]})})})()]})}function yA(e){return e==="block"?"Block execution":e==="fallback-local"?"Fall back to local":"Not configured"}const jA=new Set(["planning","researching","executing","finalizing","merging"]);function kA(e){return e!==void 0&&e!=="online"}function wA({task:e,settings:n,addToast:s,onTaskUpdated:i}){const[r,o]=a.useState([]),[l,c]=a.useState(!1),[u,d]=a.useState(null),[m,h]=a.useState(e.nodeId??""),[f,p]=a.useState(!1),g=a.useRef(e.id);a.useEffect(()=>{g.current=e.id,h(e.nodeId??""),p(!1)},[e.id,e.nodeId]),a.useEffect(()=>{c(!0),d(null),Ro().then(M=>{o(M)}).catch(M=>{d(ke(M)||"Failed to load nodes")}).finally(()=>{c(!1)})},[]);const b=a.useMemo(()=>new Map(r.map(M=>[M.id,M])),[r]),v=a.useMemo(()=>[...r].sort((M,T)=>M.name.localeCompare(T.name)),[r]),x=n,y=e.nodeId??x?.defaultNodeId??null,k=e.nodeId?"Per-task override":x?.defaultNodeId?"Project default":"No routing",S=y?b.get(y):void 0,_=S?`${S.name} (${S.type})`:y?`${y} (node unavailable or unknown)`:"Local (no routing configured)",N=e.column==="in-progress"||jA.has(e.status),A=N||f||l,C=a.useCallback(async M=>{if(M===m)return;const T=e.id,U=m;h(M),p(!0);try{const q=await ii(T,{nodeId:M||null});if(g.current!==T)return;h(q.nodeId??""),i?.(q),s(M?"Node override updated":"Node override cleared","success")}catch(q){if(g.current!==T)return;h(U),s(ke(q)||"Failed to update node override","error")}finally{g.current===T&&p(!1)}},[s,i,m,e.id]),z=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:[S?t.jsx(Vi,{status:S.status,compact:!0}):null,_,kA(S?.status)?t.jsx("span",{className:"routing-summary-warning",children:"Unhealthy"}):null]})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Routing source"}),t.jsx("span",{className:"routing-summary-value",children:k})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Unavailable-node policy"}),t.jsx("span",{className:"routing-summary-value",children:yA(x?.unavailableNodePolicy)})]})]}),N&&y?t.jsx("div",{className:"routing-tab__info-banner",children:"Routing is locked while this task is active. Node override cannot be changed until the task is no longer active."}):null]}),t.jsxs("section",{className:"routing-tab__section",children:[t.jsx("h5",{children:"Node Override"}),N?t.jsx("div",{className:"routing-tab__warning-banner",children:"Node override cannot be changed while the task is active."}):null,t.jsx("label",{className:"routing-tab__selector-label",htmlFor:`routing-node-${e.id}`,children:"Select execution node"}),t.jsxs("select",{id:`routing-node-${e.id}`,className:"select routing-tab__selector",value:m,disabled:A,onChange:M=>{C(M.target.value)},children:[t.jsx("option",{value:"",children:"Use project default"}),v.map(M=>t.jsxs("option",{value:M.id,title:`Status: ${M.status}`,children:[M.name," (",M.type,") — ",M.status]},M.id))]}),u?t.jsx("div",{className:"routing-tab__error",children:u}):null,e.nodeId?t.jsxs("div",{className:"routing-tab__override-row",children:[t.jsxs("span",{className:"routing-tab__override-text",children:["Override set to: ",b.get(e.nodeId)?.name??e.nodeId]}),t.jsx("button",{type:"button",className:"btn btn-sm",disabled:N||f,onClick:z,children:"Clear override"})]}):null]})]})}const NA=/^[a-zA-Z0-9_-]{1,64}$/,SA=200;function rh(e){return e?new Date(e).toLocaleString():""}function CA(e,n=SA){return e.length<=n?e:e.substring(0,n)+"…"}function EA({taskId:e,addToast:n,onTaskUpdated:s,projectId:i,canEdit:r=!1}){const[o,l]=a.useState([]),[c,u]=a.useState(!0),[d,m]=a.useState(null),[h,f]=a.useState(""),[p,g]=a.useState(null),[b,v]=a.useState(""),[x,y]=a.useState(null),[k,S]=a.useState([]),[_,N]=a.useState(!1),[A,C]=a.useState(!1),[z,M]=a.useState(""),[T,U]=a.useState(""),[q,D]=a.useState(!1),[R,F]=a.useState(null),[V,K]=a.useState(null),[ee,E]=a.useState(!1),$=a.useCallback(async()=>{try{const L=await py(e,i);l(L)}catch(L){n(ke(L)||"Failed to load documents","error")}finally{u(!1)}},[e,i,n]);a.useEffect(()=>{$()},[$]);async function P(L){d===L.key?(m(null),f(""),g(null),v(""),y(null),S([]),E(!1)):(m(L.key),f(L.content),g(null),v(""),y(null),S([]),E(!1))}async function w(L){if(x===L)y(null),S([]);else{y(L),N(!0);try{const ne=await fy(e,L,i);S(ne)}catch(ne){n(ke(ne)||"Failed to load revisions","error")}finally{N(!1)}}}function O(){d&&(g(d),v(h))}function Z(){g(null),v("")}async function Ne(){if(!(!p||!b.trim())){D(!0);try{await Qd(e,p,b,{},i),g(null),v(""),await $();const L=o.find(ne=>ne.key===p);L&&f(L.content),n("Document saved","success")}catch(L){n(ke(L)||"Failed to save document","error")}finally{D(!1)}}}async function se(){const L=z.trim(),ne=T.trim();if(!L){n("Document key is required","error");return}if(!NA.test(L)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!ne){n("Content is required","error");return}D(!0);try{await Qd(e,L,ne,{},i),C(!1),M(""),U(""),await $(),n("Document created","success")}catch(Q){n(ke(Q)||"Failed to create document","error")}finally{D(!1)}}async function le(L){F(L);try{await gy(e,L,i),K(null),F(null),d===L&&(m(null),f("")),x===L&&(y(null),S([])),await $(),n("Document deleted","success")}catch(ne){n(ke(ne)||"Failed to delete document","error")}finally{F(null)}}function we(L){f(L.content),g(null),v("")}return c?t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),t.jsx("div",{className:"detail-log-empty",children:"Loading documents…"})]}):t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),A&&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:z,onChange:L=>M(L.target.value),placeholder:"e.g., plan, notes, research",disabled:q}),t.jsx("span",{className:"form-hint",children:"Alphanumeric, hyphens, underscores (1-64 chars)"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-content",children:"Content"}),t.jsx("textarea",{id:"doc-content",value:T,onChange:L=>U(L.target.value),rows:6,placeholder:"Enter document content…",disabled:q})]}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{C(!1),M(""),U("")},disabled:q,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void se(),disabled:q||!z.trim()||!T.trim(),children:q?"Creating…":"Create"})]})]}),o.length===0&&!A?t.jsx("div",{className:"detail-log-empty",children:"No documents yet."}):t.jsx("div",{className:"task-documents-list",children:o.map(L=>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(Bi,{size:14}),t.jsx("span",{className:"task-document-key",children:L.key}),t.jsxs("span",{className:"task-document-revision-badge",children:["v",L.revision]})]}),t.jsxs("div",{className:"task-document-meta",children:[t.jsx("span",{className:"task-document-author",children:L.author}),t.jsx("span",{className:"task-document-timestamp",children:rh(L.updatedAt||L.createdAt)})]})]}),d===L.key&&p!==L.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:()=>E(ne=>!ne),"aria-label":ee?"Switch to plain text":"Switch to markdown","aria-pressed":ee,title:ee?"Switch to plain text":"Switch to markdown",children:ee?"Markdown":"Plain"})}),t.jsx("div",{className:"task-document-content",children:ee?t.jsx("div",{className:"task-document-content-markdown",children:t.jsx("div",{className:"markdown-body",children:t.jsx(oi,{remarkPlugins:[li],children:h})})}):t.jsx("pre",{className:"task-document-content-text",children:h})}),x===L.key&&t.jsxs("div",{className:"task-document-revisions",children:[t.jsx("h5",{children:"Revision History"}),_?t.jsx("div",{className:"detail-log-empty",children:"Loading…"}):k.length<=1?t.jsx("div",{className:"detail-log-empty",children:"No previous revisions."}):t.jsx("div",{className:"task-document-revision-list",children:k.filter(ne=>ne.revision<L.revision).sort((ne,Q)=>Q.revision-ne.revision).map(ne=>t.jsxs("div",{className:"task-document-revision-item",onClick:()=>we(ne),children:[t.jsxs("div",{className:"revision-header",children:[t.jsxs("span",{className:"revision-badge",children:["v",ne.revision]}),t.jsx("span",{className:"revision-author",children:ne.author}),t.jsx("span",{className:"revision-timestamp",children:rh(ne.createdAt)})]}),t.jsx("div",{className:"revision-preview",children:CA(ne.content,100)})]},ne.id))})]})]}),p===L.key&&t.jsxs("div",{className:"task-document-edit-form",children:[t.jsx("textarea",{value:b,onChange:ne=>v(ne.target.value),rows:10,disabled:q}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:Z,disabled:q,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Ne(),disabled:q||!b.trim(),children:q?"Saving…":"Save"})]})]}),t.jsxs("div",{className:"task-document-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>void P(L),children:d===L.key?t.jsxs(t.Fragment,{children:[t.jsx(gi,{size:14})," Collapse"]}):t.jsxs(t.Fragment,{children:[t.jsx(sn,{size:14})," Expand"]})}),d===L.key&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>void w(L.key),children:[t.jsx(xr,{size:14})," History"]}),r&&p!==L.key&&t.jsx("button",{className:"btn btn-sm",onClick:O,children:"Edit"}),r&&(V===L.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(L.key),disabled:R===L.key,children:R===L.key?"…":"Yes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>K(null),disabled:R===L.key,children:"No"})]}):t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>K(L.key),children:t.jsx(on,{size:14})}))]})]})]},L.key))}),r&&!A&&t.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>C(!0),children:[t.jsx(ln,{size:14})," New Document"]})]})}function fo(e){return e.toLocaleString()}function sc(e){const n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString()}function Qa(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 _A(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 MA({tokenUsage:e,loading:n,task:s}){const i=Bp(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=_A(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:Qa(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:Qa(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:Qa(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} (${Qa(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} (${Qa(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 ${sc(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:fo(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:fo(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:fo(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:fo(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:sc(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:sc(e.lastUsedAt)})})]})]})]}):t.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:"No token usage recorded for this task yet."})]})]})}const AA=new Set(["planning","researching","executing","finalizing","merging"]);function RA(e,n){return Ip(e,n)}function TA(e,n){return $p(e,n)}function PA(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 IA(e,n,s){if(e.planningModelProvider&&e.planningModelId)return{provider:e.planningModelProvider,modelId:e.planningModelId};const i=PA(n);return i||Dp(e,s)}function $A(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 DA(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 LA(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function zA(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 oh(e,n){return e.length>n?e.slice(0,n)+"…":e}function lh(e=[],n=[]){return e.length===n.length&&e.every((s,i)=>s===n[i])}function ic(e){const n=e.indexOf("/");return!e||n===-1?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function ac(e){return e.trim()}function FA(e){const n=e.trim();return n.length>0?n:void 0}function Xa(e){return typeof e=="string"&&fd.includes(e)?e:_s}function Za(e){return e==="fast"?"fast":"standard"}function OA(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}const UA=a.lazy(()=>hn(()=>import("./AgentDetailView-B7j297GT.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8])).then(e=>({default:e.AgentDetailView})));function BA(e,n={}){switch(e.sourceType){case"dashboard_ui":return{label:"Dashboard"};case"quick_chat":return{label:"Quick Chat"};case"chat_session":return{label:"Chat Session"};case"agent_heartbeat":return{label:n.sourceAgentName??e.sourceAgentId??"agent",sourceAgentId:e.sourceAgentId};case"automation":return{label:"Automation"};case"cron":return{label:"Scheduled Task"};case"workflow_step":return{label:"Workflow Step"};case"github_import":return{label:"GitHub Import",contextInfo:OA(e.sourceMetadata)};case"task_refine":return{label:"Refinement",parentTaskId:e.sourceParentTaskId};case"task_duplicate":return{label:"Duplicate",parentTaskId:e.sourceParentTaskId};case"cli":return{label:"CLI"};case"api":return{label:"API"};case"recovery":return{label:"Recovery"};case"unknown":default:return null}}const rc=200,HA=new Set(["triage","todo"]);function qA({task:e,projectId:n,tasks:s=[],onClose:i,onOpenDetail:r,onMoveTask:o,onDeleteTask:l,onMergeTask:c,onRetryTask:u,onResetTask:d,onDuplicateTask:m,onTaskUpdated:h,addToast:f,prAuthAvailable:p,initialTab:g="definition"}){const[b,v]=a.useState(g),[x,y]=a.useState(()=>"prompt"in e?e:null),[k,S]=a.useState(()=>!("prompt"in e));a.useEffect(()=>{if("prompt"in e){y(e),S(!1);return}let G=!1;return S(!0),y(null),jr(e.id,n).then(qe=>{G||(y(qe),S(!1))}).catch(()=>{G||S(!1)}),()=>{G=!0}},[e.id,n]);const _=x?{...x,...e,prompt:x.prompt,log:x.log}:{...e,prompt:""},N=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,C]=a.useState(null),[z,M]=a.useState(null),T=BA(_,{sourceAgentName:A?.name});a.useEffect(()=>{v(g)},[g]),a.useEffect(()=>{R(!1)},[e.id]);const[U,q]=a.useState("activity"),[D,R]=a.useState(!1),[F,V]=a.useState(e.attachments||[]),[K,ee]=a.useState(!1),[E,$]=a.useState(e.dependencies||[]),[P,w]=a.useState(!1),[O,Z]=a.useState(""),[Ne,se]=a.useState(null),[le,we]=a.useState([]),[L,ne]=a.useState(!1),[Q,be]=a.useState(!1),[de,me]=a.useState(!1),[ie,xe]=a.useState(!1),[Re,Oe]=a.useState(!1),[nt,et]=a.useState(_.prompt||""),[Ze,rt]=a.useState(""),[He,Ge]=a.useState(!1),[oe,je]=a.useState(""),[X,Ae]=a.useState(!1),[Te,pe]=a.useState(!1),[_e,Fe]=a.useState(e.title||""),[it,ve]=a.useState(e.description||""),[ce,Ie]=a.useState(e.dependencies||[]),[he,Me]=a.useState(""),[Je,$e]=a.useState(""),[ft,J]=a.useState(""),[re,ye]=a.useState(""),[at,te]=a.useState("default"),[Ye,mt]=a.useState(void 0),[ht,xt]=a.useState(_s),[St,bt]=a.useState(e.nodeId),[Nt,Qt]=a.useState(Za(e.executionMode)),[Pt,Dt]=a.useState(""),[Et,Xt]=a.useState(e.enabledWorkflowSteps||[]),[Lt,Ft]=a.useState(e.sourceIssue?.provider??""),[zt,Tt]=a.useState(e.sourceIssue?.repository??""),[Gt,Ot]=a.useState(e.sourceIssue?.externalIssueId??""),[qt,nn]=a.useState(e.sourceIssue?.url??""),[ge,ze]=a.useState([]),[dt,j]=a.useState(!1),Y=a.useRef(!1),[fe,Pe]=a.useState(!1),[We,gt]=a.useState(!1),[Mt,cn]=a.useState(!1),bn=a.useRef(null),rn=a.useRef(null),Jt=a.useRef(null),Sn=a.useRef(null);ci(Sn,!0,"fusion:task-detail-modal-size");const{getSlotsForId:Se}=Rp(n),ut=Se("task-detail-tab");a.useEffect(()=>(Y.current=!0,()=>{Y.current=!1}),[]);const[Zt,_n]=a.useState(void 0),[Nn,zn]=a.useState([]),[ss,Rn]=a.useState(!1),[ue,Ke]=a.useState(e.enabledWorkflowSteps||[]),pt=e.column==="in-progress"||AA.has(e.status);a.useEffect(()=>{Fe(e.title||""),ve(e.description||""),Ft(e.sourceIssue?.provider??""),Tt(e.sourceIssue?.repository??""),Ot(e.sourceIssue?.externalIssueId??""),nn(e.sourceIssue?.url??""),Qt(Za(e.executionMode)),cn(!1),pe(!1)},[e.id,e.title,e.description,e.sourceIssue,e.executionMode]),a.useEffect(()=>{Ke(e.enabledWorkflowSteps||[])},[e.id,e.enabledWorkflowSteps]),a.useEffect(()=>{let G=!1;return Yo(n).then(qe=>{G||_n(qe)}).catch(()=>{}),()=>{G=!0}},[n]),a.useEffect(()=>{if(b!=="workflow")return;let G=!1;return Rn(!0),Wj(e.id,n).then(qe=>{G||zn(qe)}).catch(qe=>{G||f(`Failed to load workflow results: ${ke(qe)}`,"error")}).finally(()=>{G||Rn(!1)}),()=>{G=!0}},[b,e.id,n,f]),a.useEffect(()=>{if(b!=="workflow")return;const G=n?`?projectId=${encodeURIComponent(n)}`:"",qe=ct=>{try{const Ut=JSON.parse(ct.data);Ut.id===e.id&&Array.isArray(Ut.workflowStepResults)&&zn(Ut.workflowStepResults)}catch{}};return Gs(`/api/events${G}`,{events:{"task:updated":qe}})},[b,e.id,n]),a.useEffect(()=>{P||Z("")},[P]),a.useEffect(()=>{if(!e.assignedAgentId){se(null);return}const G=le.find(ct=>ct.id===e.assignedAgentId);if(G){se(G);return}let qe=!1;return $c(e.assignedAgentId,n).then(ct=>{qe||se(ct)}).catch(()=>{qe||se(null)}),()=>{qe=!0}},[e.assignedAgentId,n,le]),a.useEffect(()=>{if(!e.sourceAgentId){C(null);return}const G=le.find(ct=>ct.id===e.sourceAgentId);if(G){C(G);return}let qe=!1;return Promise.resolve($c(e.sourceAgentId,n)).then(ct=>{qe||C(ct??null)}).catch(()=>{qe||C(null)}),()=>{qe=!0}},[e.sourceAgentId,n,le]),a.useEffect(()=>{ne(!1)},[e.id]),a.useEffect(()=>{if(!(fe||We))return;const qe=ct=>{const Ut=ct.target,Xs=bn.current?.contains(Ut),Os=Jt.current?.contains(Ut);!Xs&&fe&&Pe(!1),!Os&&We&>(!1)};return document.addEventListener("mousedown",qe),()=>document.removeEventListener("mousedown",qe)},[fe,We]),a.useEffect(()=>{if(!(fe||We))return;const qe=ct=>{ct.key==="Escape"&&(ct.stopPropagation(),fe&&Pe(!1),We&>(!1))};return document.addEventListener("keydown",qe),()=>document.removeEventListener("keydown",qe)},[fe,We]),a.useEffect(()=>{Oe(!1),et(_.prompt||""),rt("")},[e.id,_.prompt]);const $t=HA.has(e.column)&&!dt,Vt=a.useCallback(()=>{if(!$t)return;pe(!0),Fe(e.title||""),ve(e.description||""),Ie(e.dependencies||[]);const G=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"",qe=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"",ct=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";Me(G),$e(qe),J(ct),ye(e.thinkingLevel??""),bt(e.nodeId),te(G||qe||ct?"custom":"default"),Dt(""),Xt(e.enabledWorkflowSteps||[]),Qt(Za(e.executionMode)),Ft(e.sourceIssue?.provider??""),Tt(e.sourceIssue?.repository??""),Ot(e.sourceIssue?.externalIssueId??""),nn(e.sourceIssue?.url??""),ze([]),mt(e.reviewLevel),xt(Xa(e.priority))},[$t,e]),dn=a.useCallback(()=>{pe(!1),Fe(e.title||""),ve(e.description||""),Ie(e.dependencies||[]),bt(e.nodeId),Ft(e.sourceIssue?.provider??""),Tt(e.sourceIssue?.repository??""),Ot(e.sourceIssue?.externalIssueId??""),nn(e.sourceIssue?.url??""),xt(Xa(e.priority)),Qt(Za(e.executionMode)),ge.forEach(G=>URL.revokeObjectURL(G.previewUrl)),ze([])},[e.title,e.description,e.dependencies,e.nodeId,e.priority,e.executionMode,ge]),Vn=a.useCallback(async()=>{j(!0);try{const G={},qe=_e.trim(),ct=it.trim();qe&&qe!==(e.title??"")&&(G.title=qe),ct&&ct!==(e.description??"")&&(G.description=ct),lh(ce,e.dependencies??[])||(G.dependencies=ce),lh(Et,e.enabledWorkflowSteps??[])||(G.enabledWorkflowSteps=Et);const Ut=ic(he),Xs=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"";he!==Xs&&(G.modelProvider=Ut?.provider??null,G.modelId=Ut?.modelId??null);const Os=ic(Je),Oa=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"";Je!==Oa&&(G.validatorModelProvider=Os?.provider??null,G.validatorModelId=Os?.modelId??null);const Ua=ic(ft),Kr=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";ft!==Kr&&(G.planningModelProvider=Ua?.provider??null,G.planningModelId=Ua?.modelId??null);const Gr=e.thinkingLevel??"";re!==Gr&&(G.thinkingLevel=re!==""?re:null),(e.nodeId??void 0)!==St&&(G.nodeId=St??null);const ul=e.reviewLevel;Ye!==ul&&(G.reviewLevel=Ye);const Jr=Xa(e.priority);ht!==Jr&&(G.priority=ht);const Yr=Za(e.executionMode);Nt!==Yr&&(G.executionMode=Nt==="fast"?"fast":null);const na=ac(Lt),B=ac(zt),Ce=ac(Gt),De=FA(qt);if(na.length===0&&B.length===0&&Ce.length===0&&!De)e.sourceIssue&&(G.sourceIssue=null);else{if(!na||!B||!Ce){f("Source issue provider, repository, and issue identifier are required","error"),j(!1);return}const Rt=Number.parseInt(Ce,10),Yt=e.sourceIssue?.issueNumber??Rt;if(!Number.isFinite(Yt)||Yt<=0){f("Source issue identifier must be numeric for new metadata","error"),j(!1);return}const Ue={provider:na,repository:B,externalIssueId:Ce,issueNumber:Yt,...De?{url:De}:{}},Be=e.sourceIssue;(!Be||Be.provider!==Ue.provider||Be.repository!==Ue.repository||Be.externalIssueId!==Ue.externalIssueId||Be.issueNumber!==Ue.issueNumber||(Be.url??void 0)!==Ue.url)&&(G.sourceIssue=Ue)}if(Object.keys(G).length>0){const Rt=await ii(e.id,G,n);h?.(Rt)}if(ge.length>0){const Rt=[];for(const Yt of ge)try{const Ue=await kr(e.id,Yt.file,n);V(Be=>[...Be,Ue])}catch{Rt.push(Yt.file.name)}Rt.length>0&&f(`Failed to upload: ${Rt.join(", ")}`,"error")}ge.forEach(Rt=>URL.revokeObjectURL(Rt.previewUrl)),ze([]),f(`Updated ${e.id}`,"success"),pe(!1)}catch(G){f(`Failed to update ${e.id}: ${ke(G)}`,"error")}finally{Y.current&&j(!1)}},[e,_e,it,ce,he,Je,ft,re,St,Ye,ht,Nt,Et,Lt,zt,Gt,qt,ge,f,n,h]),$n=a.useCallback(async G=>{try{await ii(e.id,{description:G},n),f("Description saved","success")}catch(qe){f(`Failed to save: ${ke(qe)}`,"error")}},[e.id,f,n]),Dn=a.useCallback(G=>{Te&&(G.key==="Escape"?(G.preventDefault(),dn()):G.key==="Enter"&&(G.ctrlKey||G.metaKey)&&(G.preventDefault(),Vn()))},[Te,dn,Vn]);a.useEffect(()=>{if(Te)return document.addEventListener("keydown",Dn),()=>document.removeEventListener("keydown",Dn)},[Te,Dn]);const en=a.useRef(null),{nodes:Ct}=tl(),{confirm:pn}=Ks(),{entries:W,loading:Le,loadMore:Qe,hasMore:ot,total:vt,loadingMore:_t}=og(e.id,b==="logs"&&U==="agent-log",n);a.useEffect(()=>{const G=qe=>{qe.key==="Escape"&&!Te&&i()};return document.addEventListener("keydown",G),()=>document.removeEventListener("keydown",G)},[i,Te]);const Ht=_i(i),Fn=a.useCallback(async G=>{try{await o(e.id,G),i(),f(`Moved to ${Bn[G]}`,"success")}catch(qe){f(ke(qe),"error")}},[e.id,o,i,f]),ds=a.useCallback(async()=>{if(await pn({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0}))try{await l(e.id),i(),f(`Deleted ${e.id}`,"info")}catch(qe){const ct=zA(qe);if(!ct||ct.dependentIds.length===0){f(ke(qe),"error");return}const Ut=ct.dependentIds.join(", ");if(!await pn({title:"Force Delete Task",message:`${e.id} is a dependency of ${Ut}.
|
|
656
|
+
|
|
657
|
+
Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await l(e.id,{removeDependencyReferences:!0}),i(),f(`Deleted ${e.id} after removing dependency references`,"info")}catch(Os){f(ke(Os),"error")}}},[e.id,l,i,f,pn]),Ns=a.useCallback(async()=>{await pn({title:"Merge Task",message:`Merge ${e.id} into the current branch?`})&&(i(),f(`Merging ${e.id}...`,"info"),c(e.id).then(qe=>{const ct=qe.merged?`Merged ${e.id} (branch: ${qe.branch})`:`Closed ${e.id} (${qe.error||"no branch to merge"})`;f(ct,"success")}).catch(qe=>{f(ke(qe),"error")}))},[e.id,c,i,f,pn]),Js=a.useCallback(()=>{u&&(i(),u(e.id).then(()=>{f(`Retried ${e.id}`,"success")}).catch(G=>{f(ke(G),"error")}))},[e.id,u,i,f]),ae=a.useCallback(()=>{d&&window.confirm(`This will erase all progress for ${e.id} and start the task from scratch. Continue?`)&&(i(),d(e.id).then(()=>{f(`Reset ${e.id} — fresh run will be allocated`,"success")}).catch(G=>{f(ke(G),"error")}))},[e.id,d,i,f]),Ee=a.useCallback(async()=>{if(!(!m||!await pn({title:"Duplicate Task",message:`Duplicate ${e.id}? This will create a new task in Triage with the same description and prompt.`})))try{const qe=await m(e.id);i(),f(`Duplicated ${e.id} → ${qe.id}`,"success")}catch(qe){f(ke(qe),"error")}},[e.id,m,i,f,pn]),tt=a.useCallback(async()=>{try{e.paused?(await sy(e.id,n),f(`Unpaused ${e.id}`,"success")):(await xp(e.id,n),f(`Paused ${e.id}`,"success")),i()}catch(G){f(ke(G),"error")}},[e.id,e.paused,i,f]),kt=a.useCallback(async()=>{try{await oy(e.id,n),f(`Plan approved — ${e.id} moved to Todo`,"success"),i()}catch(G){f(ke(G),"error")}},[e.id,i,f]),wt=a.useCallback(async()=>{if(await pn({title:"Reject Plan",message:"Reject this plan? The specification will be discarded and regenerated.",danger:!0}))try{await ly(e.id,n),f(`Plan rejected — ${e.id} returned to Planning for replanning`,"info"),i()}catch(qe){f(ke(qe),"error")}},[e.id,i,f,pn]),fn=a.useCallback(async()=>{if(await pn({title:"Rebuild Plan",message:"Rebuild the plan for this task? The task will move to planning for replanning."}))try{await vy(e.id,n),i(),f(`Replanning ${e.id}...`,"info")}catch(qe){f(ke(qe),"error")}},[e.id,n,i,f,pn]),un=a.useCallback(()=>{Ge(!0),je("")},[]),Xe=a.useCallback(()=>{Pe(!1),gt(!1)},[]),It=a.useCallback(G=>{Xe(),Fn(G)},[Xe]),mn=a.useCallback(G=>{Xe(),G()},[Xe]),es=a.useCallback(()=>{Xe(),Ns()},[Xe,Ns]),Hn=a.useCallback(()=>{Ge(!1),je(""),Ae(!1)},[]),On=a.useCallback(async()=>{if(!oe.trim()){f("Please enter feedback describing what needs refinement","error");return}if(oe.length>2e3){f("Feedback must be 2000 characters or less","error");return}Ae(!0);try{const G=await yy(e.id,oe.trim(),n);f(`Refinement task created: ${G.id}`,"success"),i()}catch(G){f(ke(G),"error")}finally{Ae(!1)}},[e.id,oe,f,i]),Tn=a.useCallback(async G=>{ee(!0);try{const qe=await kr(e.id,G,n);V(ct=>[...ct,qe]),f("Screenshot attached","success")}catch(qe){f(ke(qe),"error")}finally{ee(!1)}},[e.id,f]),Wn=a.useCallback(async G=>{const qe=G.target.files?.[0];qe&&(await Tn(qe),en.current&&(en.current.value=""))},[Tn]);a.useEffect(()=>{const G=qe=>{const ct=qe.clipboardData?.items;if(ct)for(let Ut=0;Ut<ct.length;Ut++){const Xs=ct[Ut];if(Xs.type.startsWith("image/")){const Os=Xs.getAsFile();if(Os){qe.preventDefault(),Tn(Os);return}}}};return document.addEventListener("paste",G),()=>document.removeEventListener("paste",G)},[Tn]);const gs=a.useCallback(G=>{G.preventDefault()},[]),Pn=a.useCallback(G=>{G.preventDefault();const qe=G.dataTransfer.files;for(let ct=0;ct<qe.length;ct++){const Ut=qe[ct];if(Ut.type.startsWith("image/")){Tn(Ut);return}}},[Tn]),Kn=a.useCallback(async G=>{try{await uy(e.id,G,n),V(qe=>qe.filter(ct=>ct.filename!==G)),f("Attachment deleted","info")}catch(qe){f(ke(qe),"error")}},[e.id,f]),bs=a.useCallback(async G=>{const qe=ue;Ke(G);try{const ct=await ii(e.id,{enabledWorkflowSteps:G},n);f("Workflow steps updated","success"),h?.(ct)}catch(ct){Ke(qe),f(`Failed to update workflow steps: ${ke(ct)}`,"error")}},[e.id,n,ue,h,f]),zs=a.useCallback(async()=>{be(!0);try{const G=await Ra(void 0,n);we(G),ne(!0)}catch(G){f(`Failed to load agents: ${ke(G)}`,"error"),ne(!1)}finally{be(!1)}},[n,f]),xs=a.useCallback(async G=>{try{const qe=await lu(e.id,G,n),ct=le.find(Ut=>Ut.id===G)??null;se(ct||(Ut=>Ut?.id===G?Ut:null)),ne(!1),h?.(qe),f("Assigned agent updated","success")}catch(qe){f(`Failed to assign agent: ${ke(qe)}`,"error")}},[e.id,n,le,h,f]),In=a.useCallback(async()=>{try{const G=await lu(e.id,null,n);se(null),ne(!1),h?.(G),f("Agent unassigned","success")}catch(G){f(`Failed to unassign agent: ${ke(G)}`,"error")}},[e.id,n,h,f]),Gn=a.useCallback(async G=>{const qe=[...E,G];$(qe);try{await ii(e.id,{dependencies:qe},n)}catch(ct){$(E),f(ke(ct),"error")}},[e.id,E,f]),Fs=a.useCallback(async(G,qe)=>{G.stopPropagation();const ct=E.filter(Ut=>Ut!==qe);$(ct);try{await ii(e.id,{dependencies:ct},n)}catch(Ut){$(E),f(ke(Ut),"error")}},[e.id,E,f]),Ai=a.useCallback(async G=>{try{const qe=await jr(G,n);r(qe)}catch{f(`Failed to load dependency ${G}`,"error")}},[r,f]),Ri=a.useCallback(async G=>{me(!0);try{await ii(_.id,{prompt:G},n),f("Spec updated","success"),x&&(x.prompt=G)}catch(qe){throw f(ke(qe),"error"),qe}finally{me(!1)}},[_,x,f]),Br=a.useCallback(async G=>{xe(!0);try{await xy(e.id,G,n),f("AI revision requested. Task moved to planning.","success"),i()}catch(qe){const ct=ke(qe);ct.includes("done")||ct.includes("archived")?f("Cannot request revision: Task must be in 'triage', 'todo', 'in-progress', or 'in-review' column.","error"):f(ct,"error")}finally{xe(!1)}},[e.id,f,i]),Ys=a.useCallback(()=>{Oe(!0),et(_.prompt||""),rt("")},[_.prompt]),vi=a.useCallback(()=>{Oe(!1),et(_.prompt||""),rt("")},[_.prompt]),Xi=a.useCallback(async()=>{if(nt===(_.prompt||"")){vi();return}Oe(!1);try{await Ri(nt)}catch(G){throw Oe(!0),G}},[nt,_.prompt,Ri,vi]),cl=a.useCallback(async()=>{Ze.trim()&&await Br(Ze.trim())},[Ze,Br]),dl=a.useCallback(G=>{G.key==="Escape"?(G.preventDefault(),vi()):G.key==="Enter"&&(G.ctrlKey||G.metaKey)&&(G.preventDefault(),Xi())},[vi,Xi]),Hr=s.filter(G=>G.id!==e.id&&!E.includes(G.id)).sort((G,qe)=>{const ct=qe.createdAt.localeCompare(G.createdAt);if(ct!==0)return ct;const Ut=parseInt(G.id.slice(G.id.lastIndexOf("-")+1),10)||0;return(parseInt(qe.id.slice(qe.id.lastIndexOf("-")+1),10)||0)-Ut}),Qs=Ne?.name??e.assignedAgentId??null,ui=a.useMemo(()=>{const G=[];return _.modelProvider&&G.push(_.modelProvider),_.validatorModelProvider&&!G.includes(_.validatorModelProvider)&&G.push(_.validatorModelProvider),_.planningModelProvider&&!G.includes(_.planningModelProvider)&&G.push(_.planningModelProvider),G},[_.modelProvider,_.validatorModelProvider,_.planningModelProvider]),Zi=Dc[e.column]||[],qr=["todo","in-progress"],Vr=e.column==="in-review"?qr:Zi,ts=Vr[0],ea=Vr.slice(1),us=ea.length>0,La=a.useCallback(()=>{Pe(!1),rn.current?.focus()},[]),Wr=a.useCallback(G=>{if(!us){ts&&It(ts);return}const qe=G.currentTarget.querySelector(".detail-move-btn__arrow");if(!!(G.target instanceof Element&&G.target.closest(".detail-move-btn__arrow")||qe&&G.clientX>0&&G.clientX>=qe.getBoundingClientRect().left)){Pe(Ut=>!Ut),gt(!1);return}ts&&It(ts)},[us,ts,It]),za=a.useCallback(G=>{!us||!(G.key==="ArrowDown"||G.altKey&&G.key==="ArrowDown")||(G.preventDefault(),Pe(!0),gt(!1))},[us]),ta=a.useCallback(G=>{G.key==="Escape"&&(G.preventDefault(),G.stopPropagation(),La())},[La]);a.useEffect(()=>{if(!fe)return;bn.current?.querySelector(".detail-move-menu-item")?.focus()},[fe]);const Fa={"creating-pr":"Creating PR…","awaiting-pr-checks":"Awaiting PR checks","merging-pr":"Merging PR…"},mi=e.status?Fa[e.status]:void 0;return t.jsx("div",{className:"modal-overlay open",...Ht,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg task-detail-modal",ref:Sn,onDragOver:gs,onDrop:Pn,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:Bn[e.column]})]}),t.jsxs("div",{className:"modal-header-actions",children:[!Te&&$t&&t.jsx("button",{className:"modal-edit-btn",onClick:Vt,title:"Edit task","aria-label":"Edit task",children:t.jsx(ms,{size:14})}),t.jsx("button",{className:"modal-close",onClick:i,"aria-label":"Close",children:"×"})]})]}),t.jsxs("div",{className:`detail-body${b==="logs"&&U==="agent-log"&&!Te?" detail-body--agent-log":""}`,children:[Te?t.jsx("div",{className:"modal-edit-form",children:t.jsx(ug,{mode:"edit",title:_e,onTitleChange:Fe,description:it,onDescriptionChange:ve,dependencies:ce,onDependenciesChange:Ie,executorModel:he,onExecutorModelChange:Me,validatorModel:Je,onValidatorModelChange:$e,planningModel:ft,onPlanningModelChange:J,thinkingLevel:re,onThinkingLevelChange:ye,presetMode:at,onPresetModeChange:te,selectedPresetId:Pt,onSelectedPresetIdChange:Dt,selectedWorkflowSteps:Et,onWorkflowStepsChange:Xt,pendingImages:ge,onImagesChange:ze,tasks:s.filter(G=>G.id!==e.id),projectId:n,disabled:dt,addToast:f,isActive:Te,onAutoSaveDescription:$n,reviewLevel:Ye,onReviewLevelChange:mt,priority:ht,onPriorityChange:xt,nodeId:St,onNodeIdChange:bt,nodeOptions:Ct,nodeOverrideDisabled:pt,nodeOverrideDisabledReason:pt?"Execution node override is locked while a task is active/in progress.":void 0,executionMode:Nt,onExecutionModeChange:Qt,renderBelowModelConfiguration:t.jsxs("div",{className:"form-group detail-source-edit-group",children:[t.jsx("label",{children:"Source Issue"}),t.jsxs("div",{className:"detail-source-edit-grid",children:[t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Provider (e.g. github)",value:Lt,onChange:G=>Ft(G.target.value),disabled:dt,"data-testid":"task-source-provider-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Repository (e.g. owner/repo)",value:zt,onChange:G=>Tt(G.target.value),disabled:dt,"data-testid":"task-source-repository-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Issue identifier",value:Gt,onChange:G=>Ot(G.target.value),disabled:dt,"data-testid":"task-source-external-id-input"}),t.jsx("input",{type:"url",className:"modal-edit-input",placeholder:"Issue URL",value:qt,onChange:G=>nn(G.target.value),disabled:dt,"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 G=e.title||e.description||e.id,qe=!D&&G.length>rc;return t.jsxs(t.Fragment,{children:[t.jsx("h2",{className:"detail-title",children:qe?G.slice(0,rc)+"…":G}),G.length>rc&&t.jsx("button",{className:"detail-description-toggle",onClick:()=>R(!D),children:D?"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--${Xa(e.priority)}`,children:["Priority: ",Xa(e.priority)]}),T&&t.jsxs("div",{className:"detail-provenance",children:[t.jsx(Ws,{"aria-hidden":"true"}),t.jsxs("span",{children:[_.sourceType==="agent_heartbeat"?t.jsxs(t.Fragment,{children:["Created by"," ",T.sourceAgentId?t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>M(T.sourceAgentId),children:T.label}):T.label]}):t.jsxs(t.Fragment,{children:["Created via ",T.label]}),T.parentTaskId&&t.jsxs(t.Fragment,{children:[" ","of"," ",t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>Ai(T.parentTaskId),children:T.parentTaskId})]}),T.contextInfo?` (${T.contextInfo})`:""]})]})]})]}),e.status==="failed"&&e.error&&t.jsxs("div",{className:"detail-error-alert",children:[t.jsx("span",{className:"detail-error-icon",children:"⚠"}),t.jsxs("div",{className:"detail-error-content",children:[t.jsx("div",{className:"detail-error-title",children:"Task Failed"}),t.jsx("div",{className:"detail-error-message",children:e.error})]})]}),!Te&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"detail-tabs",children:[t.jsx("button",{className:`detail-tab${b==="definition"?" detail-tab-active":""}`,onClick:()=>v("definition"),children:"Definition"}),t.jsx("button",{className:`detail-tab${b==="logs"?" detail-tab-active":""}`,onClick:()=>v("logs"),children:"Logs"}),(e.column==="in-progress"||e.column==="in-review"||e.column==="done")&&t.jsx("button",{className:`detail-tab${b==="changes"?" detail-tab-active":""}`,onClick:()=>v("changes"),children:"Changes"}),t.jsx("button",{className:`detail-tab${b==="comments"?" detail-tab-active":""}`,onClick:()=>v("comments"),children:"Comments"}),t.jsx("button",{className:`detail-tab${b==="documents"?" detail-tab-active":""}`,onClick:()=>v("documents"),children:"Documents"}),t.jsx("button",{className:`detail-tab${b==="model"?" detail-tab-active":""}`,onClick:()=>v("model"),children:"Model"}),t.jsx("button",{className:`detail-tab${b==="workflow"?" detail-tab-active":""}`,onClick:()=>v("workflow"),children:"Workflow"}),t.jsx("button",{className:`detail-tab${b==="stats"?" detail-tab-active":""}`,onClick:()=>v("stats"),children:"Stats"}),t.jsx("button",{className:`detail-tab${b==="routing"?" detail-tab-active":""}`,onClick:()=>v("routing"),children:"Routing"}),ut.map((G,qe)=>{const ct=`plugin-${qe}`;return t.jsx("button",{className:`detail-tab${b===ct?" detail-tab-active":""}`,onClick:()=>v(ct),children:G.slot.label},`plugin-tab-${G.pluginId}`)})]}),b==="workflow"?t.jsx("div",{className:"detail-section",children:t.jsx(vA,{taskId:e.id,results:Nn,loading:ss,enabledWorkflowSteps:ue,canEdit:$t,projectId:n,isTaskInProgress:e.column==="in-progress"&&e.status!=="paused",onWorkflowStepsChange:bs})}):b==="model"?t.jsx("div",{className:"detail-section",children:t.jsx(eA,{task:e,addToast:f,onTaskUpdated:h,settings:Zt})}):b==="logs"?t.jsxs("div",{className:`detail-section${U==="agent-log"?" detail-section--agent-log":""}`,children:[t.jsxs("div",{className:"log-subview-toggle",children:[t.jsx("button",{className:`log-subview-btn${U==="activity"?" log-subview-btn-active":""}`,onClick:()=>q("activity"),children:"Activity"}),t.jsx("button",{className:`log-subview-btn${U==="agent-log"?" log-subview-btn-active":""}`,onClick:()=>q("agent-log"),children:"Agent Log"})]}),U==="agent-log"?t.jsx(JM,{entries:W,loading:Le,executorModel:RA(e,Zt),validatorModel:TA(e,Zt),planningModel:IA(e,W,Zt),hasMore:ot,onLoadMore:Qe,loadingMore:_t,totalCount:vt}):t.jsxs("div",{className:"detail-activity",children:[t.jsx("h4",{children:"Activity"}),_.activityLogTruncatedCount?t.jsxs("div",{className:"detail-log-truncated",children:["Showing the most recent ",_.log.length," activity entries."]}):null,_.log&&_.log.length>0?t.jsx("div",{className:"detail-activity-list",children:[..._.log].reverse().map((G,qe)=>t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-timestamp",children:DA(G.timestamp)}),t.jsx("span",{className:"detail-log-action",children:G.action})]}),G.outcome&&t.jsx("div",{className:"detail-log-outcome",children:G.outcome})]},qe))}):t.jsx("div",{className:"detail-log-empty",children:"(no activity)"})]})]}):b==="changes"?t.jsx(dA,{taskId:e.id,worktree:e.worktree,projectId:n,column:e.column,mergeDetails:e.mergeDetails,modifiedFiles:e.modifiedFiles}):b==="comments"?t.jsx(aA,{task:e,addToast:f,projectId:n,onTaskUpdated:h}):b==="documents"?t.jsx(EA,{taskId:e.id,addToast:f,projectId:n,onTaskUpdated:h,canEdit:$t}):typeof b=="string"&&b.startsWith("plugin-")?t.jsx("div",{className:"detail-section",children:t.jsx(Zo,{slotId:"task-detail-tab",projectId:n})}):b==="stats"?t.jsx("div",{className:"detail-section",children:t.jsx(MA,{tokenUsage:_.tokenUsage,loading:k,task:_})}):b==="routing"?t.jsx("div",{className:"detail-section",children:t.jsx(wA,{task:e,settings:Zt,addToast:f,onTaskUpdated:h})}):t.jsxs(t.Fragment,{children:[e.column==="done"&&e.summary&&t.jsxs("div",{className:"detail-section detail-summary",children:[t.jsx("h4",{children:"Summary"}),t.jsx("div",{className:"markdown-body",children:t.jsx(oi,{remarkPlugins:[li],children:e.summary})})]}),t.jsx(oA,{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":Mt,"aria-label":Mt?"Collapse source issue details":"Expand source issue details",onClick:()=>cn(G=>!G),children:t.jsx(kn,{size:16,className:Mt?"detail-source-chevron--expanded":void 0})})]}),Mt&&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:[ui.length>0&&t.jsx("span",{className:"detail-provider-icons","data-testid":"detail-provider-icons",children:ui.map(G=>t.jsx(An,{provider:G,size:"sm"},G))}),t.jsxs("span",{className:"detail-meta-label",children:[t.jsx(Cn,{size:14,style:{verticalAlign:"middle",marginRight:6}}),"Agent"]})]}),t.jsxs("div",{className:"detail-agent-actions",children:[Qs?t.jsxs("span",{className:"detail-agent-chip",children:[t.jsx(Cn,{size:14}),Qs,t.jsx("button",{className:"detail-agent-clear",onClick:()=>void In(),title:"Unassign agent",children:t.jsx(Kt,{size:12})})]}):t.jsx("button",{className:"btn btn-sm",onClick:()=>{L?ne(!1):zs()},children:"Assign Agent"}),L&&t.jsxs("div",{className:"agent-picker-dropdown",children:[Q&&t.jsx("div",{className:"agent-picker-loading",children:"Loading agents..."}),!Q&&le.filter(G=>G.state!=="terminated").map(G=>t.jsxs("button",{className:`agent-picker-item${e.assignedAgentId===G.id?" selected":""}`,onClick:()=>void xs(G.id),children:[t.jsx(Cn,{size:14}),t.jsx("span",{className:"agent-picker-name",children:G.name}),t.jsx("span",{className:"agent-picker-role",children:G.role})]},G.id)),!Q&&le.filter(G=>G.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"}),_.steps&&_.steps.length>0?t.jsxs("div",{className:"step-progress-wrapper",children:[t.jsx("div",{className:"step-progress-bar",children:_.steps.map((G,qe)=>t.jsx("div",{className:`step-progress-segment step-progress-segment--${G.status}`,"data-tooltip":`${G.name} (${G.status})`,style:{backgroundColor:$A(G.status)}},qe))}),t.jsxs("span",{className:"step-progress-label",children:[_.steps.filter(G=>G.status==="done").length,"/",_.steps.length," step",_.steps.length===1?"":"s"]})]}):t.jsx("div",{className:"step-progress-empty",children:"(no steps defined)"})]}),t.jsxs("div",{className:"detail-section",children:[!Re&&t.jsx("div",{className:"detail-spec-edit-trigger",children:t.jsx("button",{className:"btn btn-sm",onClick:Ys,children:"Edit"})}),Re?t.jsxs("div",{className:"spec-editor-edit-mode",children:[t.jsx("textarea",{className:"spec-editor-textarea",value:nt,onChange:G=>et(G.target.value),onKeyDown:dl,disabled:de,placeholder:"Enter task specification in Markdown...",rows:12}),t.jsxs("div",{className:"spec-editor-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:vi,disabled:de,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Xi(),disabled:nt===(_.prompt||"")||de,children:de?"Saving…":"Save"})]}),t.jsxs("div",{className:"spec-editor-hint",children:[t.jsx("kbd",{children:"Ctrl"}),"+",t.jsx("kbd",{children:"Enter"})," to save · ",t.jsx("kbd",{children:"Escape"})," to cancel"]}),t.jsxs("div",{className:"spec-editor-revision",children:[t.jsx("h4",{children:"Ask AI to Revise"}),t.jsx("p",{className:"spec-editor-revision-help",children:"Provide feedback for the AI to improve this specification. The task will move to planning for replanning."}),t.jsx("textarea",{className:"spec-editor-feedback",value:Ze,onChange:G=>rt(G.target.value),placeholder:"e.g., 'Add more details about error handling', 'Split this into smaller steps', 'Include tests for the API endpoints'...",disabled:ie,rows:4,maxLength:2e3}),t.jsxs("div",{className:"spec-editor-revision-actions",children:[t.jsxs("span",{className:"spec-editor-char-count",children:[Ze.length,"/2000"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void cl(),disabled:!Ze.trim()||ie,children:ie?"Requesting…":"Request AI Revision"})]})]})]}):k?t.jsx("div",{className:"spec-loading",children:"Loading specification…"}):_.prompt?t.jsx("div",{className:"markdown-body",children:t.jsx(oi,{remarkPlugins:[li],children:_.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"}),F.length>0?t.jsx("div",{className:"detail-attachments-grid",children:F.map(G=>{const qe=ri(`/api/tasks/${e.id}/attachments/${G.filename}`);return t.jsxs("div",{className:"detail-attachment-card",children:[t.jsx("a",{className:"detail-attachment-link",href:qe,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{src:qe,alt:G.originalName,className:"detail-attachment-image"})}),t.jsxs("div",{className:"detail-attachment-meta",children:[G.originalName," (",LA(G.size),")"]}),t.jsx("button",{className:"detail-attachment-delete",onClick:()=>Kn(G.filename),title:"Delete attachment",children:"×"})]},G.filename)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no attachments)"}),t.jsx("input",{className:"detail-hidden-file-input",ref:en,type:"file",accept:"image/*",onChange:Wn}),t.jsx("button",{className:"btn btn-sm",onClick:()=>en.current?.click(),disabled:K,children:K?"Uploading…":"Attach Screenshot"})]}),t.jsxs("div",{className:"detail-deps",children:[t.jsx("h4",{children:"Dependencies"}),E.length>0?t.jsx("ul",{className:"detail-dep-list",children:E.map(G=>{const qe=s.find(Ut=>Ut.id===G),ct=qe?.title||qe?.description||G;return t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>Ai(G),onKeyDown:Ut=>{(Ut.key==="Enter"||Ut.key===" ")&&(Ut.preventDefault(),Ai(G))},role:"link",tabIndex:0,title:`Click to view ${G}`,children:[t.jsx("span",{className:"detail-dep-id",children:G}),t.jsx("span",{className:"detail-dep-label",children:oh(ct,40)})]}),t.jsx("button",{className:"dep-remove-btn",onClick:Ut=>Fs(Ut,G),title:`Remove dependency ${G}`,children:"×"})]},G)})}):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:()=>{P&&Z(""),w(G=>!G)},children:"Add Dependency"}),P&&(()=>{const G=O.toLowerCase(),qe=G?Hr.filter(ct=>ct.id.toLowerCase().includes(G)||ct.title&&ct.title.toLowerCase().includes(G)||ct.description&&ct.description.toLowerCase().includes(G)):Hr;return t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:O,onChange:ct=>Z(ct.target.value),onClick:ct=>ct.stopPropagation()}),qe.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):qe.map(ct=>t.jsxs("div",{className:"dep-dropdown-item",onClick:()=>{Gn(ct.id),w(!1)},children:[t.jsx("span",{className:"dep-dropdown-id",children:ct.id}),t.jsx("span",{className:"dep-dropdown-title",children:oh(ct.title||ct.description||ct.id,30)})]},ct.id))]})})()]})]}),e.column==="in-review"&&t.jsx(nA,{taskId:e.id,projectId:n,prInfo:e.prInfo,automationStatus:e.status??null,autoMerge:Zt?.autoMerge??!1,prAuthAvailable:p??!1,onPrCreated:G=>{e.prInfo=G,f(`PR #${G.number} created`,"success")},onPrUpdated:G=>{e.prInfo=G},addToast:f})]})]})]}),t.jsx("div",{className:"modal-actions",children:Te?t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"modal-edit-hint",children:[t.jsx("kbd",{children:"Ctrl+Enter"})," to save · ",t.jsx("kbd",{children:"Escape"})," to cancel"]}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("button",{className:"btn btn-sm",onClick:dn,disabled:dt,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Vn,disabled:dt,children:dt?"Saving…":"Save"})]}):t.jsxs(t.Fragment,{children:[e.column==="triage"&&e.status==="awaiting-approval"&&_.prompt&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:kt,children:"Approve Plan"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:wt,children:"Reject Plan"})]}),e.column==="triage"&&e.status!=="awaiting-approval"&&!N&&t.jsx("button",{className:"btn btn-sm btn-danger",onClick:ds,"aria-label":"Delete task",title:"Delete task",children:"Delete"}),(e.column!=="triage"||e.status==="awaiting-approval"||N||e.paused)&&t.jsxs("div",{className:"detail-actions-dropdown",ref:Jt,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>{gt(G=>!G),Pe(!1)},"aria-haspopup":"menu","aria-expanded":We,children:["Actions",t.jsx(sn,{size:12})]}),We&&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:()=>mn(ds),children:"Delete"}),m&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>mn(Ee),children:"Duplicate"}),(e.column==="done"||e.column==="in-review")&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>mn(un),children:"Refine"}),t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>mn(fn),children:"Respecify"}),N&&u&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>mn(Js),children:"Retry"}),d&&e.column!=="done"&&e.column!=="archived"&&t.jsx("button",{className:"detail-actions-menu-item detail-actions-menu-item-danger",role:"menuitem",onClick:()=>mn(ae),children:"Reset"}),e.column!=="done"&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>mn(tt),children:e.paused?"Unpause":"Pause"})]})]}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("div",{className:"detail-move-dropdown",ref:bn,children:e.column==="in-review"?t.jsxs("div",{className:"detail-move-actions-in-review",children:[t.jsxs("div",{children:[t.jsxs("button",{ref:rn,className:"btn btn-primary btn-sm detail-move-btn",onClick:Wr,onKeyDown:za,disabled:!ts,"aria-label":ts?`Move to ${Bn[ts]}`:void 0,"aria-haspopup":us?"menu":void 0,"aria-expanded":us?fe:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",ts?Bn[ts]:""]}),us&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(sn,{size:12})})]}),fe&&us&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:ta,children:ea.map(G=>t.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>It(G),onKeyDown:ta,children:G==="in-progress"?"Back to In Progress":`Move to ${Bn[G]}`},G))})]}),mi?t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!0,children:mi}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:es,children:"Merge & Close"})]}):t.jsxs("div",{children:[t.jsxs("button",{ref:rn,className:"btn btn-primary btn-sm detail-move-btn",onClick:Wr,onKeyDown:za,disabled:!ts,"aria-label":ts?`Move to ${Bn[ts]}`:void 0,"aria-haspopup":us?"menu":void 0,"aria-expanded":us?fe:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",ts?Bn[ts]:""]}),us&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(sn,{size:12})})]}),fe&&us&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:ta,children:ea.map(G=>t.jsxs("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>It(G),onKeyDown:ta,children:["Move to ",Bn[G]]},G))})]})})]})}),He&&t.jsx("div",{className:"modal-overlay open detail-refine-overlay",onClick:Hn,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal detail-refine-modal",onClick:G=>G.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:Hn,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"detail-body",children:[t.jsx("p",{className:"detail-refine-help",children:"Describe what needs to be refined or improved..."}),t.jsx("textarea",{className:"detail-refine-textarea",value:oe,onChange:G=>je(G.target.value),placeholder:"Enter your feedback here...",rows:6,maxLength:2e3,autoFocus:!0}),t.jsxs("div",{className:"detail-refine-input-group",children:[t.jsxs("div",{className:"detail-refine-char-count",children:[oe.length,"/2000 characters"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:On,disabled:!oe.trim()||X,children:X?"Creating...":"Create Refinement Task"})]})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:Hn,disabled:X,children:"Cancel"})})]})}),z&&t.jsx(a.Suspense,{fallback:null,children:t.jsx(UA,{agentId:z,projectId:n,onClose:()=>M(null),addToast:f})})]})})}const VA=640;function WA({isOpen:e,onClose:n,onImport:s,tasks:i,projectId:r}){const[o,l]=a.useState(""),[c,u]=a.useState(""),[d,m]=a.useState(""),[h,f]=a.useState(!1),[p,g]=a.useState("issues"),[b,v]=a.useState([]),[x,y]=a.useState(null),[k,S]=a.useState([]),[_,N]=a.useState(null),[A,C]=a.useState(null),[z,M]=a.useState(!1),[T,U]=a.useState([]),[q,D]=a.useState(!1),[R,F]=a.useState(""),V=a.useRef(!1),K=a.useRef(null);ci(K,e,"fusion:github-modal-size");const ee=_i(n),[E,$]=a.useState(!1),[P,w]=a.useState("list"),O=a.useRef(null),Z=new Set;for(const pe of i){const _e=pe.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);_e&&Z.add(_e[1]);const Fe=pe.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);Fe&&Z.add(Fe[1])}a.useEffect(()=>{if(e)return l(""),u(""),m(""),v([]),y(null),S([]),N(null),g("issues"),C(null),M(!1),U([]),D(!0),F(""),O.current=null,V.current=!0,zy().then(pe=>{if(V.current)if(U(pe),D(!1),pe.length===1){const _e=pe[0];l(_e.owner),u(_e.repo),F(_e.name)}else pe.length>1&&(l(""),u(""),F(""))}).catch(()=>{V.current&&D(!1)}),()=>{V.current=!1}},[e]);const Ne=a.useCallback(pe=>{if(F(pe),pe==="")l(""),u("");else{const _e=T.find(Fe=>Fe.name===pe);_e&&(l(_e.owner),u(_e.repo))}},[T]),se=a.useCallback(async()=>{if(!o.trim()||!c.trim()){C("Repository must be selected");return}f(!0),C(null),v([]),y(null);try{const pe=d.split(",").map(Fe=>Fe.trim()).filter(Boolean),_e=await Iy(o.trim(),c.trim(),30,pe.length>0?pe:void 0);v(_e),_e.length===0&&C("No open issues found")}catch(pe){C(ke(pe)||"Failed to fetch issues")}finally{f(!1)}},[o,c,d]),le=a.useCallback(async()=>{if(!o.trim()||!c.trim()){C("Repository must be selected");return}f(!0),C(null),S([]),N(null);try{const pe=await Dy(o.trim(),c.trim(),30);S(pe),pe.length===0&&C("No open pull requests found")}catch(pe){C(ke(pe)||"Failed to fetch pull requests")}finally{f(!1)}},[o,c]);a.useEffect(()=>{if(!e||!o.trim()||!c.trim()||h||z)return;const pe={owner:o.trim(),repo:c.trim(),labels:d.trim(),tab:p};O.current?.owner===pe.owner&&O.current?.repo===pe.repo&&O.current?.labels===pe.labels&&O.current?.tab===pe.tab||(O.current=pe,p==="issues"?se():le())},[o,c,d,p,e,h,z,se,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=()=>{$(window.innerWidth<=VA)};return pe(),window.addEventListener("resize",pe),()=>window.removeEventListener("resize",pe)},[e]);const we=a.useCallback(pe=>{y(pe),E&&w("preview")},[E]),L=a.useCallback(pe=>{N(pe),E&&w("preview")},[E]),ne=a.useCallback(()=>{w("list")},[]),Q=a.useCallback(async()=>{if(p==="issues"){if(x===null)return;M(!0),C(null);try{const pe=await $y(o.trim(),c.trim(),x,r);s(pe),y(null),E&&P==="preview"&&w("list")}catch(pe){const _e=ke(pe);_e?.includes("already imported")?C(_e):C(_e||"Failed to import issue")}finally{M(!1)}}else{if(_===null)return;M(!0),C(null);try{const pe=await Ly(o.trim(),c.trim(),_,r);s(pe),N(null),E&&P==="preview"&&w("list")}catch(pe){const _e=ke(pe);_e?.includes("already imported")?C(_e):C(_e||"Failed to import pull request")}finally{M(!1)}}},[p,x,_,o,c,s,E,P]),be=b.find(pe=>pe.number===x),de=k.find(pe=>pe.number===_);if(!e)return null;const me=T.length>0,ie=T.length===1,xe=b.filter(pe=>Z.has(pe.html_url)).length,Re=k.filter(pe=>Z.has(pe.html_url)).length,Oe=A==="No open issues found",nt=A==="No open pull requests found",et=p==="issues"?Oe:nt,Ze=!!A&&!Oe&&b.length===0&&!h,rt=!!A&&!nt&&k.length===0&&!h,He=p==="issues"?Ze:rt,Ge=h||b.length>0||Oe||Ze,oe=h||k.length>0||nt||rt,je=p==="issues"?Ge:oe,X=!!A&&b.length>0&&!Oe,Ae=!!A&&k.length>0&&!nt,Te=p==="issues"?X:Ae;return t.jsx("div",{className:"modal-overlay open",...ee,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg github-import-modal",ref:K,children:[t.jsxs("div",{className:"modal-header github-import-modal__header",children:[t.jsxs("div",{children:[t.jsx("h3",{children:"Import from GitHub"}),t.jsx("p",{className:"github-import-modal__subtitle",children:"Choose a detected remote, load open issues or pull requests, and import one into the board."})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close import modal",children:"×"})]}),t.jsxs("div",{className:"modal-body github-import-modal__body",children:[t.jsxs("div",{className:"github-import-tabs",role:"tablist","aria-label":"Import type",children:[t.jsxs("button",{role:"tab","aria-selected":p==="issues","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="issues"?"active":""}`,onClick:()=>{g("issues"),N(null)},disabled:h||z,children:[t.jsx(qo,{size:16}),t.jsx("span",{children:"Issues"})]}),t.jsxs("button",{role:"tab","aria-selected":p==="pulls","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="pulls"?"active":""}`,onClick:()=>{g("pulls"),y(null)},disabled:h||z,children:[t.jsx(Es,{size:16}),t.jsx("span",{children:"Pull Requests"})]})]}),t.jsxs("div",{className:"github-import-toolbar","data-testid":"github-import-toolbar",role:"toolbar","aria-label":"GitHub import controls",children:[t.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--remote",children:q?t.jsxs("div",{className:"github-import-toolbar__loading",role:"status","aria-live":"polite",children:[t.jsx(lt,{size:16,className:"spin"}),t.jsx("span",{children:"Detecting…"})]}):me?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:T[0].name}),t.jsxs("span",{className:"github-import-remote-pill__repo",children:[T[0].owner,"/",T[0].repo]})]}):t.jsxs("div",{className:"github-import-remote-select",children:[t.jsx("label",{htmlFor:"gh-remote",className:"visually-hidden",children:"Repository"}),t.jsxs("select",{id:"gh-remote",value:R,onChange:pe=>Ne(pe.target.value),disabled:h||z,"aria-label":"Select Git remote",children:[t.jsx("option",{value:"",children:"Select remote…"}),T.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"&&se(),disabled:h||z||!me,"aria-label":"Filter issues by labels"})]}):t.jsxs("span",{className:"github-import-filter-hint",children:["Open pull requests from ",o||"selected remote"]})}),t.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--action",children:t.jsxs("button",{id:"gh-load",className:"btn btn-primary github-import-load-button",onClick:p==="issues"?se:le,disabled:h||z||!o.trim()||!c.trim(),"aria-label":h?`Loading ${p}`:`Load ${p} from repository`,title:h?"Loading…":`Load ${p}`,children:[h?t.jsx(lt,{size:14,className:"spin"}):t.jsx(Ln,{size:14}),t.jsx("span",{children:h?"Loading…":"Load"})]})})]}),!q&&!me&&t.jsxs("div",{className:"github-import-state github-import-state--warning",role:"alert",children:[t.jsxs("div",{children:[t.jsx("strong",{children:"No GitHub remotes detected"}),t.jsx("span",{children:"Add a GitHub remote to this repository, then reopen the modal."})]}),t.jsx("code",{className:"github-import-command",children:"git remote add origin https://github.com/owner/repo.git"})]}),Te&&t.jsx("div",{className:"form-error github-import-banner",role:"alert",children:A}),t.jsxs("div",{className:"github-import-workspace",children:[t.jsxs("section",{className:`github-import-list-pane ${E?"mobile":""} ${P==="list"?"active":""}`,"data-testid":"github-import-list-pane","aria-labelledby":"github-import-results-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[t.jsx("h4",{id:"github-import-results-heading",children:p==="issues"?"Issues":"Pull Requests"}),p==="issues"&&b.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[b.length," issue",b.length===1?"":"s"]}),t.jsxs("span",{children:[xe," imported"]})]}),p==="pulls"&&k.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[k.length," pull request",k.length===1?"":"s"]}),t.jsxs("span",{children:[Re," imported"]})]})]}),t.jsxs("div",{className:"github-import-pane-content",children:[!je&&t.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-results-idle",children:t.jsxs("div",{children:[t.jsx("strong",{children:"Nothing loaded yet"}),t.jsx("span",{children:"Select a repository and click Load to start reviewing import candidates."})]})}),h&&t.jsxs("div",{className:"github-import-state github-import-state--loading",role:"status","aria-live":"polite",children:[t.jsx(lt,{size:16,className:"spin"}),t.jsxs("div",{children:[t.jsxs("strong",{children:["Loading open ",p==="issues"?"issues":"pull requests","…"]}),t.jsx("span",{children:"Fetching the latest list from GitHub."})]})]}),He&&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:A})]})}),et&&t.jsx("div",{className:"github-import-state github-import-state--empty",role:"status",children:t.jsxs("div",{children:[t.jsxs("strong",{children:["No open ",p==="issues"?"issues":"pull requests"," found"]}),t.jsx("span",{children:p==="issues"?"Try a different label filter or choose another repository.":"Choose another repository."})]})}),p==="issues"&&b.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:b.map(pe=>{const _e=Z.has(pe.html_url);return t.jsxs("div",{className:`issue-item ${x===pe.number?"selected":""} ${_e?"imported":""}`,onClick:()=>!_e&&we(pe.number),children:[t.jsx("input",{type:"radio",name:"issue",checked:x===pe.number,onChange:()=>we(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"&&k.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:k.map(pe=>{const _e=Z.has(pe.html_url);return t.jsxs("div",{className:`issue-item ${_===pe.number?"selected":""} ${_e?"imported":""}`,onClick:()=>!_e&&L(pe.number),children:[t.jsx("input",{type:"radio",name:"pull",checked:_===pe.number,onChange:()=>L(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 ${E?"mobile":""} ${P==="preview"?"active":""}`,"data-testid":"github-import-preview-pane","aria-labelledby":"github-import-preview-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[E&&t.jsxs("button",{className:"github-import-back-button",onClick:ne,"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"&&be?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Issue #",be.number]}),t.jsx("div",{className:"preview-title",children:be.title}),t.jsx("div",{className:"preview-body",children:be.body?be.body.slice(0,200)+(be.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:z,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:Q,disabled:(p==="issues"?x===null:_===null)||z,children:z?t.jsx(lt,{size:14,className:"spin"}):"Import"})]})]})})}const KA=["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 GA(e,n){return e&&n?`${e}/${n}`:""}function JA(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 YA({isOpen:e,onClose:n,onTaskCreated:s,onTasksCreated:i,tasks:r,initialPlan:o,projectId:l,resumeSessionId:c}){const[u,d]=a.useState(""),[m,h]=a.useState({type:"initial"}),[f,p]=a.useState(null),[g,b]=a.useState([]),[v,x]=a.useState([]),[y,k]=a.useState(null),S=a.useRef(!1),_=a.useRef(!1),[N,A]=a.useState(""),[C,z]=a.useState(!0),[M,T]=a.useState(!1),[U,q]=a.useState(!1),[D,R]=a.useState(null),[F,V]=a.useState(0),K=a.useRef(null),ee=a.useRef(null),E=a.useRef(null),$=a.useRef(null),[P,w]=a.useState(c??null),O=a.useMemo(()=>Yi(),[]),{isLockedByOther:Z,takeControl:Ne,isLoading:se}=sl(e?P:null),{activeTabMap:le,broadcastUpdate:we,broadcastCompleted:L,broadcastLock:ne,broadcastUnlock:Q,broadcastHeartbeat:be}=Ia(),[de,me]=a.useState(void 0),[ie,xe]=a.useState(void 0),[Re,Oe]=a.useState([]),[nt,et]=a.useState(!1),[Ze,rt]=a.useState(null),[He,Ge]=a.useState([]),[oe,je]=a.useState([]),X=a.useRef(null),[Ae,Te]=a.useState([]),[pe,_e]=a.useState(!1),[Fe,it]=a.useState(c??null),[ve,ce]=a.useState(!!c),[Ie,he]=a.useState(null),[Me,Je]=a.useState(!1),$e=a.useRef(!1),ft=a.useRef(null);ci(ee,e,"fusion:planning-modal-size"),a.useEffect(()=>{const j=ft.current;if(!j)return;j.scrollHeight-j.scrollTop-j.clientHeight<32&&(j.scrollTop=j.scrollHeight)},[N]),a.useEffect(()=>{if(m.type!=="loading"){R(null),V(0);return}const j=Date.now();R(j),V(0);const Y=setInterval(()=>{V(Math.max(0,Math.floor((Date.now()-j)/1e3)))},1e3);return()=>clearInterval(Y)},[m.type]);const J=a.useCallback(()=>{d(""),h({type:"initial"}),p(null),b([]),x([]),k(null),A(""),T(!1),q(!1),me(void 0),xe(void 0),$.current=null,w(null)},[]),re=GA(de,ie),ye=a.useCallback((j,Y)=>{if(!j||!Y)return"Using default";const fe=Re.find(Pe=>Pe.provider===j&&Pe.id===Y);return fe?`${fe.provider}/${fe.id}`:`${j}/${Y}`},[Re]),at=a.useCallback(async()=>{et(!0),rt(null);try{const j=await fs();Oe(j.models),Ge(j.favoriteProviders),je(j.favoriteModels)}catch(j){rt(ke(j)||"Failed to load models")}finally{et(!1)}},[]),te=a.useCallback(j=>{Ge(Y=>{const fe=Y,We=fe.includes(j)?fe.filter(gt=>gt!==j):[j,...fe];return gn({favoriteProviders:We,favoriteModels:oe}).catch(()=>{Ge(fe)}),We})},[oe]),Ye=a.useCallback(j=>{je(Y=>{const fe=Y,We=fe.includes(j)?fe.filter(gt=>gt!==j):[j,...fe];return gn({favoriteProviders:He,favoriteModels:We}).catch(()=>{je(fe)}),We})},[He]),mt=a.useCallback(j=>{E.current?.close();const Y=zj(j,l,{onThinking:fe=>{A(Pe=>Pe+fe),we({sessionId:j,status:"generating",needsInput:!1,owningTabId:O,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onQuestion:fe=>{T(!1),q(!1),ra(l),h({type:"question",session:{sessionId:j,currentQuestion:fe,summary:null}}),A(""),we({sessionId:j,status:"awaiting_input",needsInput:!0,owningTabId:O,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onSummary:fe=>{T(!1),q(!1),ra(l),h({type:"summary",session:{sessionId:j,currentQuestion:null,summary:fe},summary:fe}),k(fe),A(""),we({sessionId:j,status:"complete",needsInput:!1,owningTabId:O,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onError:fe=>{const Pe=fe||"Session failed while contacting the AI.";T(!0),(async()=>{try{const We=await fi(j);if(We&&(We.status==="generating"||We.status==="awaiting_input")){mt(j);return}}catch{}T(!1),q(!1),p(null),h(We=>We.type==="question"||We.type==="summary"||We.type==="error"?{type:"error",session:We.session,errorMessage:Pe}:{type:"error",session:{sessionId:j,currentQuestion:null,summary:null},errorMessage:Pe}),A(""),$.current=j,we({sessionId:j,status:"error",needsInput:!1,owningTabId:O,type:"planning",title:u.trim()||"Planning session",projectId:l??null}),L({sessionId:j,status:"error"})})()},onComplete:()=>{T(!1),q(!1),$.current=null,L({sessionId:j,status:"complete"})},onConnectionStateChange:fe=>{T(fe==="reconnecting")}});E.current=Y},[L,we,u,l,O]),ht=a.useCallback(async j=>{const Y=j??u;if(Y.trim()){p(null),A(""),x([]),b([]),T(!1),h({type:"loading"});try{const fe=de&&ie?{planningModelProvider:de,planningModelId:ie}:void 0,{sessionId:Pe}=await yj(Y.trim(),l,fe);$.current=Pe,w(Pe),it(Pe),mt(Pe),b([])}catch(fe){T(!1),p(ke(fe)||"Failed to start planning session"),h({type:"initial"}),$.current=null,w(null)}}},[mt,u,ie,de,l]);a.useEffect(()=>{e&&m.type==="initial"&&K.current?.focus()},[e,m.type]),a.useEffect(()=>{e&&at()},[e,at]),a.useEffect(()=>{if(e&&o&&!S.current&&m.type==="initial"){d(o);const j=setTimeout(()=>{S.current=!0,ht(o)},0);return()=>clearTimeout(j)}else if(e&&!o&&!S.current&&!_.current&&m.type==="initial"){_.current=!0;const j=z1(l);j&&d(j)}},[e,o,m.type,ht,l]);const xt=a.useCallback(async j=>{E.current?.close(),E.current=null,p(null),A(""),b([]),x([]),k(null),q(!1),h({type:"loading"});try{const Y=await fi(j);if(!Y){it(null),ce(!1),h({type:"initial"});return}$.current=j,w(j);const fe=ya(Y.conversationHistory);if(x(fe),b(fe.map(Pe=>Pe.response).filter(Pe=>!!(Pe&&typeof Pe=="object"&&!Array.isArray(Pe)))),Y.status==="awaiting_input"&&Y.currentQuestion){ra(l);const Pe=JSON.parse(Y.currentQuestion);h({type:"question",session:{sessionId:j,currentQuestion:Pe,summary:null}}),Y.thinkingOutput&&A(Y.thinkingOutput),mt(j)}else if(Y.status==="complete"&&Y.result){ra(l);const Pe=JSON.parse(Y.result);h({type:"summary",session:{sessionId:j,currentQuestion:null,summary:Pe},summary:Pe}),k(Pe)}else Y.status==="generating"?(h({type:"loading"}),Y.thinkingOutput&&A(Y.thinkingOutput),mt(j)):Y.status==="error"&&h({type:"error",session:{sessionId:j,currentQuestion:null,summary:null},errorMessage:Y.error||"Session failed"})}catch{p("Failed to load session"),h({type:"initial"})}},[mt,l]);a.useEffect(()=>{!e||!c||$.current!==c&&(it(c),ce(!0),xt(c))},[e,c,xt]),a.useEffect(()=>{e&&Fe&&(c&&c===Fe||E.current?.isConnected()||xt(Fe))},[e]);const St=a.useCallback(async()=>{_e(!0);try{const Y=(await ud(l,{includeCompleted:!0,includeArchived:Me})).filter(fe=>fe.type==="planning").sort((fe,Pe)=>Date.parse(Pe.updatedAt)-Date.parse(fe.updatedAt));Te(Y)}catch{}finally{_e(!1)}},[l,Me]);a.useEffect(()=>{e&&St()},[e,St]),a.useEffect(()=>{if(!e)return;const j=l?`?projectId=${encodeURIComponent(l)}`:"",Y=Pe=>{try{const We=JSON.parse(Pe.data);if(We.type!=="planning")return;Te(gt=>{const Mt=gt.findIndex(bn=>bn.id===We.id);return(Mt>=0?[...gt.slice(0,Mt),We,...gt.slice(Mt+1)]:[We,...gt]).sort((bn,rn)=>Date.parse(rn.updatedAt)-Date.parse(bn.updatedAt))})}catch{}},fe=Pe=>{try{const We=JSON.parse(Pe.data);Te(gt=>gt.filter(Mt=>Mt.id!==We))}catch{}};return Gs(`/api/events${j}`,{events:{"ai_session:updated":Y,"ai_session:deleted":fe},onReconnect:()=>{St()}})},[e,l,St]);const bt=a.useCallback(j=>{if(Fe===j){ce(!0);return}it(j),ce(!0),xt(j)},[xt,Fe]),Nt=a.useCallback(()=>{E.current?.close(),E.current=null,J(),it(null),ce(!0)},[J]),Qt=a.useCallback(()=>{ce(!1)},[]),Pt=a.useCallback(async j=>{const Y=Pe=>Pe==="generating"||Pe==="awaiting_input",fe=Ae.find(Pe=>Pe.id===j);if(fe&&Y(fe.status))try{await jp(j,l,O)}catch{}try{await Mp(j)}catch{}L({sessionId:j,status:"complete",timestamp:Date.now()}),Te(Pe=>Pe.filter(We=>We.id!==j)),Fe===j&&(E.current?.close(),E.current=null,J(),it(null),ce(!1)),he(null)},[L,Ae,l,J,Fe,O]),Dt=a.useCallback(async j=>{const fe=Ae.find(Pe=>Pe.id===j)?.archived===!0;try{fe?await pw(j):await hw(j)}catch{return}Te(Pe=>!fe&&!Me?Pe.filter(We=>We.id!==j):Pe.map(We=>We.id===j?{...We,archived:!fe}:We)),!fe&&Fe===j&&!Me&&(E.current?.close(),E.current=null,J(),it(null),ce(!1))},[Ae,J,Fe,ce,Me]);a.useEffect(()=>{e||(S.current=!1,_.current=!1,T(!1),q(!1),w(null))},[e]),a.useEffect(()=>{if(!e){X.current&&(Q(X.current,O),X.current=null);return}if(P&&X.current!==P){X.current&&Q(X.current,O),ne(P,O),X.current=P;return}!P&&X.current&&(Q(X.current,O),X.current=null)},[ne,Q,e,P,O]),a.useEffect(()=>{if(!e||!P||X.current!==P)return;be(O);const j=setInterval(()=>{be(O)},3e4);return()=>{clearInterval(j)}},[be,e,P,O]),a.useEffect(()=>()=>{E.current?.close(),E.current=null,X.current&&(Q(X.current,O),X.current=null)},[Q,O]),a.useEffect(()=>{if(!e)return;const j=()=>{E.current?.close(),E.current=null};return window.addEventListener("beforeunload",j),()=>window.removeEventListener("beforeunload",j)},[e]);const Et=a.useCallback(()=>{u&&m.type==="initial"&&L1(u,l),E.current?.close(),E.current=null,T(!1),q(!1),n()},[u,n,l,m.type]);a.useEffect(()=>{if(!e)return;const j=Y=>{Y.key==="Escape"&&Et()};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[e,Et]);const Xt=a.useCallback(async j=>{if(m.type!=="question")return;const{session:Y}=m,fe=Y.sessionId,Pe=Y.currentQuestion;if(!Pe){p("No active question in session");return}p(null),b(We=>[...We,j]),x(We=>[...We,{question:Pe,response:j}]),h({type:"loading"}),A("");try{await jj(fe,j,l,O)}catch(We){p(ke(We)||"Failed to submit response"),h({type:"question",session:Y})}},[l,O,m]),Lt=a.useCallback(async()=>{const j=$.current;if(j){try{await wj(j,l,O)}catch{}E.current?.close(),E.current=null,T(!1),q(!1),h({type:"error",session:{sessionId:j,currentQuestion:null,summary:null},errorMessage:"Generation stopped by user. You can retry or start a new session."}),A("")}},[l,O]),Ft=a.useCallback(async()=>{if(m.type!=="error")return;const j=m.session;p(null),q(!0),A(""),h({type:"loading"}),mt(j.sessionId);try{$.current=j.sessionId,w(j.sessionId),await kj(j.sessionId,l,O)}catch(Y){let fe=Y;if((ke(Y)||"").includes("not in an error state"))try{const We=await fi(j.sessionId);if(!We)throw new Error("Failed to refresh planning session.");if($.current=We.id,w(We.id),We.status==="generating")A(We.thinkingOutput??""),h({type:"loading"});else if(We.status==="awaiting_input"){if(!We.currentQuestion)throw new Error("Planning session is awaiting input but has no current question.");const gt=JSON.parse(We.currentQuestion);ra(l),h({type:"question",session:{sessionId:We.id,currentQuestion:gt,summary:null}}),E.current?.isConnected()||mt(We.id)}else if(We.status==="complete"){if(!We.result)throw new Error("Planning session is complete but has no result.");const gt=JSON.parse(We.result);ra(l),h({type:"summary",session:{sessionId:We.id,currentQuestion:null,summary:gt},summary:gt}),k(gt)}else We.status==="error"&&h({type:"error",session:{sessionId:We.id,currentQuestion:null,summary:null},errorMessage:We.error||"Retry failed. Please try again."});T(!1);return}catch(We){fe=We}E.current?.close(),E.current=null,h({type:"error",session:j,errorMessage:ke(fe)||"Retry failed. Please try again."}),T(!1)}finally{q(!1)}},[mt,l,O,m]),zt=a.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const j=m.session.sessionId,Y=await Nj(j,y??void 0,l);s(Y),it(null),Te(fe=>fe.filter(Pe=>Pe.id!==j)),L({sessionId:j,status:"complete",timestamp:Date.now()}),Et()}catch(j){p(ke(j)||"Failed to create task"),h({type:"summary",session:m.session,summary:m.summary})}}},[L,y,m,l,s,Et]),Tt=a.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const j=await Sj(m.session.sessionId,y??void 0,l);w(j.sessionId),h({type:"breakdown",sessionId:j.sessionId,subtasks:j.subtasks,dirty:!1})}catch(j){p(ke(j)||"Failed to start breakdown"),h({type:"summary",session:m.session,summary:m.summary})}}},[y,m,l]),Gt=a.useCallback(async()=>{if(m.type==="breakdown"){p(null),h({type:"creating"});try{const j=m.sessionId,Y=await Cj(j,m.subtasks,l);i(Y.tasks),Te(fe=>fe.filter(Pe=>Pe.id!==j)),L({sessionId:j,status:"complete",timestamp:Date.now()}),d(""),h({type:"initial"}),p(null),b([]),x([]),k(null),A(""),me(void 0),xe(void 0),$.current=null,w(null),it(null),n()}catch(j){p(ke(j)||"Failed to create tasks"),h({type:"breakdown",sessionId:m.sessionId,subtasks:m.subtasks,dirty:m.dirty})}}},[L,m,i,n,l]),Ot=a.useCallback(()=>{if(m.type==="question"&&g.length>0){const j=g.slice(0,-1);b(j),h({type:"question",session:m.session})}},[m,g]),qt=()=>m.type==="question"?Math.min(g.length+1,3):3,nn=P?le.get(P):null,ge=nn&&nn.tabId!==O,ze=!!(ge&&!nn.stale),dt=Z&&(!ge||nn.stale);return e?t.jsx("div",{className:"modal-overlay open",onMouseDown:j=>{$e.current=j.target===j.currentTarget},onClick:j=>{j.target===j.currentTarget&&$e.current&&Et(),$e.current=!1},role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",ref:ee,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[ve&&t.jsx("button",{className:"modal-back planning-mobile-back",onClick:Qt,"aria-label":"Back to sessions",title:"Back to sessions",children:t.jsx(Ho,{size:18})}),t.jsx(ai,{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:Et,"aria-label":"Close",children:t.jsx(Kt,{size:20})})})]}),t.jsxs("div",{className:`planning-modal-body planning-modal-body--split ${ve?"planning-modal-body--show-detail":"planning-modal-body--show-list"}`,children:[t.jsx(tR,{sessions:Ae,loading:pe,selectedSessionId:Fe,pendingDeleteId:Ie,showArchived:Me,onToggleShowArchived:()=>Je(j=>!j),onArchive:j=>void Dt(j),onSelectSession:bt,onNewSession:Nt,onRequestDelete:he,onConfirmDelete:j=>void Pt(j),onCancelDelete:()=>he(null)}),t.jsxs("div",{className:"planning-detail",children:[f&&t.jsx("div",{className:"form-error planning-error",children:f}),M&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),ze&&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(os,{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:K,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:j=>d(j.target.value),onKeyDown:j=>{j.key==="Enter"&&!j.shiftKey&&u.trim()&&(j.preventDefault(),ht())}})]}),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:KA.map((j,Y)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>d(j),children:j.length>40?j.slice(0,40)+"...":j},Y))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"planning-modal-model",className:"form-label",children:["Planning Model",nt&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(Xn,{id:"planning-modal-model",label:"Planning Model",value:re,onChange:j=>{const{provider:Y,modelId:fe}=JA(j);me(Y),xe(fe)},models:Re,disabled:nt,favoriteProviders:He,onToggleFavorite:te,favoriteModels:oe,onToggleModelFavorite:Ye}),Ze&&t.jsxs("div",{className:"form-hint form-hint-error",children:[Ze," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{at()},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:ye(de,ie)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>ht(),disabled:!u.trim(),children:[t.jsx(ai,{size:16,className:"icon-mr-8"}),"Start Planning"]})})]}),m.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(lt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:N?"AI is thinking...":"Generating next question..."}),D&&t.jsxs("div",{className:"planning-elapsed",children:["Thinking… (",F,"s)"]}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>z(!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 Lt(),children:[t.jsx(vb,{size:14}),t.jsx("span",{className:"icon-ml-6",children:"Stop"})]})}),C&&N&&t.jsx("div",{className:"planning-thinking-output",ref:ft,children:t.jsx("pre",{children:N})})]})]}),m.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[v.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ls,{entries:v}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:m.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void Ft(),disabled:U,children:[U?t.jsx(lt,{size:14,className:"spin"}):t.jsx(Ln,{size:14}),t.jsx("span",{className:"icon-ml-6",children:U?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Et,disabled:U,children:"Dismiss"})]})]})]})}),m.type==="creating"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(lt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:"Creating tasks..."})]}),m.type==="question"&&m.session.currentQuestion&&t.jsx("div",{className:"planning-question",children:t.jsx(QA,{question:m.session.currentQuestion,progress:qt(),historyEntries:v,onSubmit:Xt,onBack:g.length>0?Ot:void 0})}),m.type==="summary"&&y&&t.jsx(XA,{summary:y,historyEntries:v,onSummaryChange:k,tasks:r,onCreateTask:zt,onBreakIntoTasks:Tt,onRefine:()=>{h({type:"question",session:m.session})},isLoading:!1}),m.type==="breakdown"&&t.jsx(eR,{subtasks:m.subtasks,dirty:m.dirty,isLoading:!1,onUpdateSubtasks:j=>h({...m,subtasks:j,dirty:!0}),onCreateTasks:Gt,onBack:()=>{const Y={sessionId:m.sessionId,currentQuestion:null,summary:y??null};y&&h({type:"summary",session:Y,summary:y})}})]}),Z&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Ko,{size:16}),t.jsx("span",{children:dt?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),dt&&t.jsx("button",{type:"button",onClick:()=>{Ne()},disabled:se,className:"btn btn-primary session-lock-take-control",children:se?"Taking control...":"Take Control"})]})})]})]})}):null}function QA({question:e,progress:n,historyEntries:s,onSubmit:i,onBack:r}){const[o,l]=a.useState({}),[c,u]=a.useState(""),d=a.useCallback(()=>{e.type==="text"?i({[e.id]:c}):e.type==="confirm"?i({[e.id]:o[e.id]===!0}):i(o)},[e,o,c,i]);a.useEffect(()=>{l({}),u("")},[e.id]);const m=()=>{switch(e.type){case"text":return c.trim().length>0;case"single_select":return o[e.id]!==void 0;case"multi_select":return Array.isArray(o[e.id])&&o[e.id].length>0;case"confirm":return o[e.id]!==void 0;default:return!0}};return t.jsxs("div",{className:"planning-question-form",children:[t.jsxs("div",{className:"planning-view-scroll planning-question-scroll",children:[s.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ls,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3].map(h=>t.jsx("div",{className:`planning-progress-step ${h<=n?"active":""}`},h))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~3"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:c,onChange:h=>u(h.target.value),onKeyDown:h=>{h.key==="Enter"&&!h.shiftKey&&c.trim()&&(h.preventDefault(),d())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(h=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:h.id,checked:o[e.id]===h.id,onChange:()=>l({[e.id]:h.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:h.label}),h.description&&t.jsx("span",{className:"planning-option-desc",children:h.description})]})]},h.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(h=>{const f=o[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:h.id,checked:f.includes(h.id),onChange:p=>{const g=p.target.checked?[...f,h.id]:f.filter(b=>b!==h.id);l({[e.id]:g})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:h.label}),h.description&&t.jsx("span",{className:"planning-option-desc",children:h.description})]})]},h.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!0?"selected":""}`,onClick:()=>l({[e.id]:!0}),children:[t.jsx(wn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!1?"selected":""}`,onClick:()=>l({[e.id]:!1}),children:[t.jsx(Kt,{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(Rr,{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),f=p=>{const g=m.includes(p)?m.filter(b=>b!==p):[...m,p];h(g),s({...e,suggestedDependencies:g})};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ls,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(wn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Planning Complete!"}),t.jsx("p",{className:"text-muted",children:"Review and refine your task before creating it."})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{children:["Description",t.jsx("button",{type:"button",className:"planning-expand-btn",onClick:()=>d(!u),children:u?"Collapse":"Expand"})]}),t.jsx("textarea",{className:`planning-textarea ${u?"expanded":""}`,rows:u?10:4,value:e.description,onChange:p=>s({...e,description:p.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Suggested Size"}),t.jsxs("select",{className:"planning-size-select",value:e.suggestedSize,onChange:p=>s({...e,suggestedSize:p.target.value}),disabled:c,children:[t.jsx("option",{value:"S",children:"S (Small)"}),t.jsx("option",{value:"M",children:"M (Medium)"}),t.jsx("option",{value:"L",children:"L (Large)"})]})]}),i.length>0&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Suggested Dependencies"}),t.jsx("div",{className:"planning-deps-list",children:i.map(p=>t.jsxs("label",{className:`planning-dep-chip ${m.includes(p.id)?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:m.includes(p.id),onChange:()=>f(p.id)}),t.jsx("span",{className:"planning-dep-id",children:p.id}),t.jsx("span",{className:"planning-dep-title",children:p.title||p.description.slice(0,30)})]},p.id))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Key Deliverables"}),t.jsx("ul",{className:"planning-deliverables",children:e.keyDeliverables.map((p,g)=>t.jsx("li",{children:p},g))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:l,disabled:c,children:[t.jsx(_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(lt,{size:16,className:"spin icon-mr-8"}),"Breaking down..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Wo,{size:16,className:"icon-mr-8"}),"Break into Tasks"]})}),t.jsx("button",{className:"btn btn-primary",onClick:r,disabled:c,children:c?t.jsxs(t.Fragment,{children:[t.jsx(lt,{size:16,className:"spin icon-mr-8"}),"Creating..."]}):t.jsxs(t.Fragment,{children:[t.jsx(wn,{size:16,className:"icon-mr-8"}),"Create Task"]})})]})]})]})}function ch(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 ZA(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function eR({subtasks:e,dirty:n,isLoading:s,onUpdateSubtasks:i,onCreateTasks:r,onBack:o}){const[l,c]=a.useState(null),[u,d]=a.useState(null),[m,h]=a.useState(null),f=a.useRef([]),p=a.useMemo(()=>e.length===0||e.some(A=>!A.title.trim())?!0:ch(e),[e]),g=a.useCallback((A,C)=>{i(e.map(z=>z.id===A?{...z,...C}:z))},[e,i]),b=a.useCallback(()=>{i([...e,ZA(e.length+1)])},[e,i]),v=a.useCallback(A=>{i(e.filter(C=>C.id!==A).map(C=>({...C,dependsOn:C.dependsOn.filter(z=>z!==A)})))},[e,i]),x=a.useCallback((A,C)=>{if(C<0||C>=e.length)return;const z=[...e],[M]=z.splice(A,1);z.splice(C,0,M),i(z)},[e,i]),y=a.useCallback(A=>C=>{c(A),C.dataTransfer.setData("text/plain",A),C.dataTransfer.effectAllowed="move"},[]),k=a.useCallback(()=>{c(null),d(null),h(null)},[]),S=a.useCallback(A=>C=>{if(C.preventDefault(),A===l)return;const z=C.currentTarget.getBoundingClientRect(),M=z.top+z.height/2,T=C.clientY<M?"before":"after";d(A),h(T)},[l]),_=a.useCallback(A=>C=>{C.preventDefault();const z=C.dataTransfer.getData("text/plain");if(!z||z===A){k();return}const M=e.findIndex(R=>R.id===z),T=e.findIndex(R=>R.id===A);if(M===-1||T===-1){k();return}const U=[...e],[q]=U.splice(M,1);let D=T;m==="after"&&M<T&&D--,m==="after"&&D++,U.splice(D,0,q),i(U),k()},[e,m,i,k]),N=a.useCallback(A=>{const C=A.currentTarget.getBoundingClientRect(),z=A.clientX,M=A.clientY;(z<C.left||z>C.right||M<C.top||M>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(Wo,{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((A,C)=>{const z=l===A.id,M=u===A.id,T=["task-detail-section","subtask-item",z?"subtask-item-dragging":"",M?"subtask-item-drop-target":"",M&&m==="before"?"subtask-item-drop-before":"",M&&m==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:T,"data-testid":`subtask-item-${C}`,draggable:!s,onDragStart:y(A.id),onDragEnd:k,onDragOver:S(A.id),onDrop:_(A.id),onDragLeave:N,children:[t.jsxs("div",{className:"detail-title-row subtask-item-header subtask-item-header--between",children:[t.jsxs("div",{className:"subtask-drag-handle",title:"Drag to reorder",children:[t.jsx(od,{size:16}),t.jsx("strong",{children:A.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>x(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:()=>x(C,C+1),disabled:s||C===e.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(Ar,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>v(A.id),disabled:s,children:[t.jsx(on,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:U=>{f.current[C]=U},value:A.title,onChange:U=>g(A.id,{title:U.target.value}),onKeyDown:U=>{U.key==="Enter"&&(U.preventDefault(),C<e.length-1&&f.current[C+1]?.focus())},disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:A.description,onChange:U=>g(A.id,{description:U.target.value}),disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Size"}),t.jsxs("select",{className:"planning-size-select",value:A.suggestedSize,onChange:U=>g(A.id,{suggestedSize:U.target.value}),disabled:s,children:[t.jsx("option",{value:"S",children:"S"}),t.jsx("option",{value:"M",children:"M"}),t.jsx("option",{value:"L",children:"L"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"planning-deps-list",children:[e.slice(0,C).filter(U=>U.id!==A.id).map(U=>{const q=A.dependsOn.includes(U.id);return t.jsxs("label",{className:`planning-dep-chip ${q?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:q,onChange:()=>{const D=q?A.dependsOn.filter(R=>R!==U.id):[...A.dependsOn,U.id];g(A.id,{dependsOn:D})},disabled:s}),t.jsx("span",{className:"planning-dep-id",children:U.id}),t.jsx("span",{className:"planning-dep-title",children:U.title||"Untitled"})]},U.id)}),C===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),C>0&&e.slice(0,C).filter(U=>U.id!==A.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},A.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:b,disabled:s,children:[t.jsx(ln,{size:16,className:"icon-mr-6"})," Add subtask"]}),ch(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(lt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]})}function tR({sessions:e,loading:n,selectedSessionId:s,pendingDeleteId:i,showArchived:r,onToggleShowArchived:o,onArchive:l,onSelectSession:c,onNewSession:u,onRequestDelete:d,onConfirmDelete:m,onCancelDelete:h}){return t.jsxs("aside",{className:"planning-sidebar","aria-label":"Planning sessions",children:[t.jsx("div",{className:"planning-sidebar-header",children:t.jsxs("button",{className:`planning-sidebar-new ${s===null?"active":""}`,onClick:u,type:"button",children:[t.jsx(Tx,{size:16}),t.jsx("span",{children:"New session"})]})}),t.jsxs("div",{className:"planning-sidebar-list",children:[e.length===0&&!n&&t.jsx("div",{className:"planning-sidebar-empty text-muted",children:"No saved sessions yet. Start one on the right to see it here."}),e.map(f=>{const p=f.id===s,g=i===f.id,b=f.archived===!0,v=f.status==="complete"||f.status==="error";return t.jsxs("div",{className:`planning-sidebar-item ${p?"selected":""} ${g?"pending-delete":""} ${b?"archived":""}`,children:[t.jsxs("button",{type:"button",className:"planning-sidebar-item-button",onClick:()=>c(f.id),children:[t.jsx(nR,{status:f.status}),t.jsxs("span",{className:"planning-sidebar-item-body",children:[t.jsx("span",{className:"planning-sidebar-item-title",children:f.title||"Untitled session"}),t.jsxs("span",{className:"planning-sidebar-item-meta",children:[t.jsx(sR,{status:f.status}),t.jsx("span",{"aria-hidden":!0,children:" · "}),t.jsx("span",{children:iR(f.updatedAt)})]})]})]}),g?t.jsxs("div",{className:"planning-sidebar-confirm",children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-danger",onClick:()=>m(f.id),children:"Delete"}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,children:"Cancel"})]}):t.jsxs("div",{className:"planning-sidebar-item-actions",children:[v&&t.jsx("button",{type:"button",className:"planning-sidebar-item-archive",onClick:x=>{x.stopPropagation(),l(f.id)},"aria-label":b?"Unarchive session":"Archive session",title:b?"Unarchive session":"Archive session",children:b?t.jsx(Gg,{size:14}):t.jsx(Mr,{size:14})}),t.jsx("button",{type:"button",className:"planning-sidebar-item-delete",onClick:x=>{x.stopPropagation(),d(f.id)},"aria-label":"Delete session",title:"Delete session",children:t.jsx(on,{size:14})})]})]},f.id)})]}),t.jsx("div",{className:"planning-sidebar-footer",children:t.jsx("a",{href:"#",className:"planning-sidebar-toggle-archived-link",onClick:f=>{f.preventDefault(),o()},"aria-pressed":r,children:r?"Hide archived":"Show archived"})})]})}function nR({status:e}){switch(e){case"generating":return t.jsx(lt,{size:14,className:"spin planning-sidebar-status-icon planning-sidebar-status-generating"});case"awaiting_input":return t.jsx(wc,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-awaiting"});case"complete":return t.jsx(wn,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-complete"});case"error":return t.jsx(ps,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-error"});default:return t.jsx(Ci,{size:14,className:"planning-sidebar-status-icon"})}}function sR({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 iR(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 aR(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function dh(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 rR({isOpen:e,onClose:n,initialDescription:s,onTasksCreated:i,parentTaskId:r,projectId:o,resumeSessionId:l}){const[c,u]=a.useState({type:"initial"}),[d,m]=a.useState([]),[h,f]=a.useState([]),[p,g]=a.useState(""),[b,v]=a.useState(!0),[x,y]=a.useState(!1),[k,S]=a.useState(!1),[_,N]=a.useState(s),[A,C]=a.useState(null),[z,M]=a.useState(!1),[T,U]=a.useState(null),[q,D]=a.useState(null),[R,F]=a.useState(null),V=a.useRef(null),K=a.useRef([]),ee=a.useRef(!1),E=a.useRef(null),$=c.type==="generating"||c.type==="editing"||c.type==="creating"||c.type==="error"?c.sessionId:null,P=a.useMemo(()=>Yi(),[]),{isLockedByOther:w,takeControl:O,isLoading:Z}=sl(e?$:null),{activeTabMap:Ne,broadcastUpdate:se,broadcastCompleted:le,broadcastLock:we,broadcastUnlock:L,broadcastHeartbeat:ne}=Ia(),Q=a.useMemo(()=>d.length===0||d.some(ce=>!ce.title.trim())?!0:dh(d),[d]),be=c.type==="generating"||c.type==="editing"||c.type==="error",de=$?Ne.get($):null,{confirm:me}=Ks(),ie=de&&de.tabId!==P,xe=!!(ie&&!de.stale),Re=w&&(!ie||de.stale),Oe=a.useCallback(()=>{_&&F1(_,o),V.current?.close(),V.current=null,u({type:"initial"}),m([]),f([]),g(""),v(!0),y(!1),S(!1),C(null),M(!1),ee.current=!1},[_,o]),nt=a.useCallback(()=>{V.current?.close(),V.current=null,n()},[n]),et=a.useCallback(async()=>{if(!((z||c.type==="editing"||c.type==="creating")&&!await me({title:"Discard Changes",message:"Close subtask breakdown? Unsaved changes will be lost.",danger:!0}))){if($)try{await Np($,o,P)}catch{}Oe(),n()}},[z,n,Oe,$,P,c.type,o,me]),Ze=a.useCallback(ce=>{V.current?.close(),V.current=ek(ce,o,{onThinking:Ie=>{g(he=>he+Ie),se({sessionId:ce,status:"generating",needsInput:!1,owningTabId:P,type:"subtask",title:_.trim()||"Subtask breakdown",projectId:o??null})},onSubtasks:Ie=>{y(!1),S(!1),_l(o),m(Ie),u({type:"editing",sessionId:ce}),M(!1),se({sessionId:ce,status:"awaiting_input",needsInput:!0,owningTabId:P,type:"subtask",title:_.trim()||"Subtask breakdown",projectId:o??null})},onError:Ie=>{const he=Ie||"Session failed while contacting the AI.";y(!1),S(!1),C(null),u({type:"error",sessionId:ce,errorMessage:he}),se({sessionId:ce,status:"error",needsInput:!1,owningTabId:P,type:"subtask",title:_.trim()||"Subtask breakdown",projectId:o??null}),le({sessionId:ce,status:"error"})},onComplete:()=>{le({sessionId:ce,status:"complete"})},onConnectionStateChange:Ie=>{y(Ie==="reconnecting")}})},[le,se,_,o,P]),rt=a.useCallback(async()=>{if(_.trim()){C(null),f([]),g(""),y(!1);try{const{sessionId:ce}=await Qj(_.trim(),o);u({type:"generating",sessionId:ce}),Ze(ce)}catch(ce){C(ke(ce)||"Failed to start subtask breakdown"),u({type:"initial"})}}},[Ze,_,o]);a.useEffect(()=>{if(!e){Oe();return}if(e&&s&&!ee.current)N(s),ee.current=!0,rt();else if(e&&!s&&!ee.current){const ce=O1(o);ce&&N(ce)}},[e,s,rt,Oe]),a.useEffect(()=>{!e||!l||c.type!=="initial"||(async()=>{try{const ce=await fi(l);if(!ce)return;const Ie=ya(ce.conversationHistory);if(f(Ie),ce.status==="generating"||ce.status==="awaiting_input")g(ce.thinkingOutput??""),u({type:"generating",sessionId:l}),Ze(l);else if(ce.status==="complete"&&ce.result){_l(o);const he=JSON.parse(ce.result);m(he),u({type:"editing",sessionId:l})}else ce.status==="error"&&(C(null),u({type:"error",sessionId:l,errorMessage:ce.error??"Session encountered an error"}))}catch(ce){C(ke(ce)||"Failed to resume session")}})()},[Ze,e,l,c.type,o]),a.useEffect(()=>{if(!e){E.current&&(L(E.current,P),E.current=null);return}if($&&E.current!==$){E.current&&L(E.current,P),we($,P),E.current=$;return}!$&&E.current&&(L(E.current,P),E.current=null)},[we,L,e,$,P]),a.useEffect(()=>{if(!e||!$||E.current!==$)return;ne(P);const ce=setInterval(()=>{ne(P)},3e4);return()=>{clearInterval(ce)}},[ne,e,$,P]),a.useEffect(()=>()=>{V.current?.close(),E.current&&(L(E.current,P),E.current=null)},[L,P]),a.useEffect(()=>{if(!e)return;const ce=Ie=>{Ie.key==="Escape"&&(Ie.preventDefault(),et())};return document.addEventListener("keydown",ce),()=>document.removeEventListener("keydown",ce)},[e,et]);const He=a.useCallback((ce,Ie)=>{m(he=>he.map(Me=>Me.id===ce?{...Me,...Ie}:Me)),M(!0)},[]),Ge=a.useCallback(()=>{m(ce=>[...ce,aR(ce.length+1)]),M(!0)},[]),oe=a.useCallback(ce=>{m(Ie=>Ie.filter(he=>he.id!==ce).map(he=>({...he,dependsOn:he.dependsOn.filter(Me=>Me!==ce)}))),M(!0)},[]),je=a.useCallback(ce=>Ie=>{U(ce),Ie.dataTransfer.setData("text/plain",ce),Ie.dataTransfer.effectAllowed="move"},[]),X=a.useCallback(()=>{U(null),D(null),F(null)},[]),Ae=a.useCallback(ce=>Ie=>{if(Ie.preventDefault(),ce===T)return;const he=Ie.currentTarget.getBoundingClientRect(),Me=he.top+he.height/2,Je=Ie.clientY<Me?"before":"after";D(ce),F(Je)},[T]),Te=a.useCallback(ce=>Ie=>{Ie.preventDefault();const he=Ie.dataTransfer.getData("text/plain");if(!he||he===ce){U(null),D(null),F(null);return}m(Me=>{const Je=Me.findIndex(ye=>ye.id===he),$e=Me.findIndex(ye=>ye.id===ce);if(Je===-1||$e===-1)return Me;const ft=[...Me],[J]=ft.splice(Je,1);let re=$e;return R==="after"&&Je<$e&&re--,R==="after"&&re++,ft.splice(re,0,J),ft}),M(!0),U(null),D(null),F(null)},[R]),pe=a.useCallback(ce=>{const Ie=ce.currentTarget.getBoundingClientRect(),he=ce.clientX,Me=ce.clientY;(he<Ie.left||he>Ie.right||Me<Ie.top||Me>Ie.bottom)&&(D(null),F(null))},[]),_e=a.useCallback((ce,Ie)=>{Ie<0||Ie>=d.length||(m(he=>{const Me=[...he],[Je]=Me.splice(ce,1);return Me.splice(Ie,0,Je),Me}),M(!0))},[d.length]),Fe=a.useCallback(ce=>{K.current[ce+1]?.focus()},[]),it=a.useCallback(async()=>{if(!(!$||Q)){C(null),u({type:"creating",sessionId:$});try{const ce=await tk($,d,r,o);i(ce.tasks),Oe(),n()}catch(ce){C(ke(ce)||"Failed to create tasks"),u({type:"editing",sessionId:$})}}},[Q,n,i,r,o,Oe,$,d]),ve=a.useCallback(async()=>{if(c.type!=="error")return;const ce=c.sessionId;C(null),S(!0),g(""),u({type:"generating",sessionId:ce}),Ze(ce);try{await Xj(ce,o,P)}catch(Ie){let he=Ie;if((ke(Ie)||"").includes("not in an error state"))try{const Je=await fi(ce);if(!Je)throw new Error("Failed to refresh subtask session.");if(f(ya(Je.conversationHistory)),Je.status==="generating"||Je.status==="awaiting_input")g(Je.thinkingOutput??""),u({type:"generating",sessionId:Je.id}),V.current?.isConnected()||Ze(Je.id);else if(Je.status==="complete"){if(!Je.result)throw new Error("Subtask session is complete but has no result.");_l(o);const $e=JSON.parse(Je.result);m($e),u({type:"editing",sessionId:Je.id}),M(!1)}else Je.status==="error"&&u({type:"error",sessionId:Je.id,errorMessage:Je.error??"Retry failed. Please try again."});y(!1);return}catch(Je){he=Je}V.current?.close(),V.current=null,u({type:"error",sessionId:ce,errorMessage:ke(he)||"Retry failed. Please try again."}),y(!1)}finally{S(!1)}},[Ze,o,P,c]);return e?t.jsx("div",{className:"modal-overlay open",onClick:ce=>ce.target===ce.currentTarget&&void et(),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(Wo,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Subtask Breakdown"})]}),t.jsxs("div",{className:"modal-header-actions",children:[be&&t.jsx("button",{className:"modal-send-to-background",onClick:nt,title:"Send to background","aria-label":"Send to background",children:t.jsx(Ir,{size:16})}),t.jsx("button",{className:"modal-close",onClick:()=>void et(),"aria-label":"Close",children:t.jsx(Kt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[A&&t.jsx("div",{className:"form-error planning-error",children:A}),x&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),xe&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),c.type==="initial"&&t.jsx("div",{className:"planning-initial",children:t.jsxs("div",{className:"planning-view-scroll",children:[t.jsx("p",{className:"text-muted",children:"Preparing to break this task into subtasks."}),t.jsx("pre",{className:"planning-thinking-output",children:_})]})}),c.type==="generating"&&t.jsxs("div",{className:"planning-loading",children:[h.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ls,{entries:h,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsx(lt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:"AI is generating subtasks..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>v(!b),type:"button",children:b?"Hide thinking":"Show thinking"}),b&&p&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:p})})]})]}),c.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[h.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ls,{entries:h,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:c.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void ve(),disabled:k,children:[k?t.jsx(lt,{size:14,className:"spin"}):t.jsx(Ln,{size:14}),t.jsx("span",{className:"icon-ml-6",children:k?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:()=>void et(),disabled:k,children:"Cancel"})]})]})]})}),(c.type==="editing"||c.type==="creating")&&t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[h.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ls,{entries:h}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(wn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Review your subtasks"}),t.jsx("p",{className:"text-muted",children:"Edit titles, descriptions, sizes, and dependencies before creating all tasks at once."})]}),t.jsxs("div",{className:"planning-summary-form",children:[d.map((ce,Ie)=>{const he=T===ce.id,Me=q===ce.id,Je=["task-detail-section","subtask-item",he?"subtask-item-dragging":"",Me?"subtask-item-drop-target":"",Me&&R==="before"?"subtask-item-drop-before":"",Me&&R==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:Je,"data-testid":`subtask-item-${Ie}`,draggable:c.type!=="creating",onDragStart:je(ce.id),onDragEnd:X,onDragOver:Ae(ce.id),onDrop:Te(ce.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(od,{size:16}),t.jsx("strong",{children:ce.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>_e(Ie,Ie-1),disabled:c.type==="creating"||Ie===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(Ie,Ie+1),disabled:c.type==="creating"||Ie===d.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(Ar,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>oe(ce.id),disabled:c.type==="creating",children:[t.jsx(on,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:$e=>{K.current[Ie]=$e},value:ce.title,onChange:$e=>He(ce.id,{title:$e.target.value}),onKeyDown:$e=>{$e.key==="Enter"&&($e.preventDefault(),Fe(Ie))},disabled:c.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:8,value:ce.description,onChange:$e=>He(ce.id,{description:$e.target.value}),disabled:c.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Size"}),t.jsxs("select",{className:"planning-size-select",value:ce.suggestedSize,onChange:$e=>He(ce.id,{suggestedSize:$e.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,Ie).filter($e=>$e.id!==ce.id).map($e=>{const ft=ce.dependsOn.includes($e.id);return t.jsxs("label",{className:`planning-dep-chip ${ft?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:ft,onChange:()=>{const J=ft?ce.dependsOn.filter(re=>re!==$e.id):[...ce.dependsOn,$e.id];He(ce.id,{dependsOn:J})},disabled:c.type==="creating"}),t.jsx("span",{className:"planning-dep-id",children:$e.id}),t.jsx("span",{className:"planning-dep-title",children:$e.title||"Untitled"})]},$e.id)}),Ie===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),Ie>0&&d.slice(0,Ie).filter($e=>$e.id!==ce.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},ce.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:Ge,disabled:c.type==="creating",children:[t.jsx(ln,{size:16,className:"icon-mr-6"})," Add subtask"]}),dh(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 et(),disabled:c.type==="creating",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:()=>void it(),disabled:c.type==="creating"||Q,children:c.type==="creating"?t.jsxs(t.Fragment,{children:[t.jsx(lt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]}),w&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Ko,{size:16}),t.jsx("span",{children:Re?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),Re&&t.jsx("button",{type:"button",onClick:()=>{O()},disabled:Z,className:"btn btn-primary session-lock-take-control",children:Z?"Taking control...":"Take Control"})]})})]})]})}):null}const oR=5,lR=1e3,cR=45e3;function go(){return{scrollback:null,connected:null,data:[]}}function dR(e,n){const[s,i]=a.useState("disconnected"),r=a.useRef(0),o=a.useRef(e),l=a.useRef(n),c=o.current!==e||l.current!==n;c&&(o.current=e,l.current=n,r.current++);const u=a.useRef(null),d=a.useRef(0),m=a.useRef(null),h=a.useRef(null),f=a.useRef(!1),p=a.useRef(new Set),g=a.useRef(new Set),b=a.useRef(new Set),v=a.useRef(new Set),x=a.useRef(new Set),y=a.useRef(go()),k=a.useCallback(D=>{p.current.add(D);const R=y.current;return R.data.length>0&&(R.data.forEach(F=>D(F)),R.data=[]),()=>p.current.delete(D)},[]),S=a.useCallback(D=>(g.current.add(D),()=>g.current.delete(D)),[]),_=a.useCallback(D=>{b.current.add(D);const R=y.current;return R.connected&&(D(R.connected),R.connected=null),()=>b.current.delete(D)},[]),N=a.useCallback(D=>{v.current.add(D);const R=y.current;return R.scrollback&&(D(R.scrollback),R.scrollback=null),()=>v.current.delete(D)},[]),A=a.useCallback(D=>(x.current.add(D),()=>x.current.delete(D)),[]),C=a.useCallback(D=>{const R=u.current;R?.readyState===WebSocket.OPEN&&R.send(JSON.stringify({type:"input",data:D}))},[]),z=a.useCallback((D,R)=>{const F=u.current;F?.readyState===WebSocket.OPEN&&F.send(JSON.stringify({type:"resize",cols:D,rows:R}))},[]),M=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=go()},[]),T=a.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.current=null),u.current&&(f.current=!0,u.current.close(),u.current=null),y.current=go()},[]),U=a.useCallback(()=>{if(!e){i("disconnected");return}if(u.current?.readyState===WebSocket.OPEN)return;u.current&&(f.current=!0,u.current.close()),f.current=!1,i("connecting");const D=r.current;let F=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/terminal/ws?sessionId=${encodeURIComponent(e)}`;n&&(F+=`&projectId=${encodeURIComponent(n)}`);const V=new WebSocket(ri(F));u.current=V,V.onopen=()=>{if(r.current!==D){V.close();return}y.current=go(),i("connected"),d.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{r.current===D&&V.readyState===WebSocket.OPEN&&V.send(JSON.stringify({type:"ping"}))},cR)},V.onmessage=K=>{if(r.current===D)try{const ee=JSON.parse(K.data),E=y.current;switch(ee.type){case"data":ee.data&&(p.current.size===0&&E.data.push(ee.data),p.current.forEach($=>$(ee.data)));break;case"scrollback":ee.data&&(E.scrollback=ee.data,v.current.forEach($=>$(ee.data)));break;case"connected":ee.shell&&ee.cwd&&(E.connected={shell:ee.shell,cwd:ee.cwd},b.current.forEach($=>$({shell:ee.shell,cwd:ee.cwd})));break;case"exit":ee.exitCode!==void 0&&g.current.forEach($=>$(ee.exitCode));break;case"ping":V.readyState===WebSocket.OPEN&&V.send(JSON.stringify({type:"pong"}));break;case"pong":break}}catch{}},V.onclose=K=>{if(r.current!==D)return;if(u.current=null,h.current&&(clearInterval(h.current),h.current=null),f.current){i("disconnected");return}if(K.code===4e3||K.code===4004){i("disconnected"),K.code===4004&&x.current.forEach($=>$());return}if(d.current++,d.current>oR){i("disconnected");return}const ee=lR*Math.pow(2,d.current-1);i("reconnecting");const E=r.current;m.current=setTimeout(()=>{r.current===E&&(f.current||U())},Math.min(ee,16e3))},V.onerror=()=>{}},[e,n]),q=a.useCallback(()=>{d.current=0,T(),U()},[T,U]);return a.useEffect(()=>(c&&(M(),d.current=0,i("disconnected")),e?U():i("disconnected"),T),[e,n,c,U,T,M]),{connectionStatus:s,sendInput:C,resize:z,onData:k,onExit:S,onConnect:_,onScrollback:N,reconnect:q,onSessionInvalid:A}}const mg="kb-terminal-tabs",uR=15e3,mR=15e3;function uh(){return`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function mh(e){if(typeof window>"u")return[];try{const n=Zn(mg,e);if(n)return JSON.parse(n)}catch{}return[]}function oc(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return n.includes("Failed to parse URL")||n.includes("Invalid URL")}function hh(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 hR(e){const[n,s]=a.useState(()=>mh(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(mh(e)),r(!1),l(!0),u(null)},[e]),a.useEffect(()=>{try{ys(mg,JSON.stringify(n),e)}catch{}},[e,n]),a.useEffect(()=>{let _=!1;const N=h.current;return(async()=>{if(!_)try{const C=await hh(Ky(e),uR,"listTerminalSessions");if(_||N!==h.current)return;const z=new Set(C.map(M=>M.id));l(!0),s(M=>{if(_||N!==h.current)return M;const U=M.map(R=>({...R,_verified:z.has(R.sessionId)})).filter(R=>R._verified);if(U.length===0)return[];const q=U.map(({_verified:R,...F})=>F);return q.find(R=>R.isActive)?q:q.map((R,F)=>({...R,isActive:F===0}))}),r(!0)}catch(C){if(_||N!==h.current)return;const z=oc(C);z||console.warn("Failed to validate terminal sessions with server:",C),l(!z),r(!0)}})(),()=>{_=!0}},[e]),a.useEffect(()=>{if(n.length===0&&i&&o){const _=h.current,N=setTimeout(()=>{hh(Xr(void 0,void 0,void 0,e),mR,"createTerminalSession").then(A=>{if(_!==h.current)return;const C={id:uh(),sessionId:A.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};s(z=>z.length>0?z:[...z.map(T=>({...T,isActive:!1})),C]),u(null)}).catch(A=>{if(_!==h.current)return;oc(A)||console.error(A);const C=A instanceof Error?A.message:typeof A=="string"?A:"Failed to create terminal session";u(C)})},0);return()=>clearTimeout(N)}},[i,o,n.length,d]);const f=a.useCallback(async()=>{const _=await Xr(void 0,void 0,void 0,e),N={id:uh(),sessionId:_.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};return s(A=>[...A.map(z=>({...z,isActive:!1})),N]),N},[n.length]),p=a.useCallback(async()=>f(),[f]),g=a.useCallback(_=>{s(N=>{const A=N.find(T=>T.id===_);if(!A)return N;Xd(A.sessionId,e).catch(T=>{console.warn(`Failed to kill terminal session ${A.sessionId}:`,T)});const C=N.findIndex(T=>T.id===_),z=A.isActive,M=N.filter(T=>T.id!==_);if(M.length===0)return[];if(z){const T=Math.min(C,M.length-1);return M.map((U,q)=>({...U,isActive:q===T}))}return M})},[]),b=a.useCallback(_=>{s(N=>{let A=!1;const C=N.map(z=>z.id===_?(A=!0,{...z,isActive:!0}):{...z,isActive:!1});return A?C:N})},[]),v=a.useCallback((_,N)=>{s(A=>A.map(C=>C.id===_?{...C,title:N}:C))},[]),x=a.useCallback(async()=>{s(A=>{const C=A.find(z=>z.isActive);return C&&Xd(C.sessionId,e).catch(z=>{console.warn(`Failed to kill old session ${C.sessionId}:`,z)}),A});const _=n.find(A=>A.isActive);if(!_)return;const N=await Xr(void 0,void 0,void 0,e);s(A=>A.map(C=>C.id===_.id?{...C,sessionId:N.sessionId}:C))},[n]),y=a.useCallback(async()=>{const _=n.find(N=>N.isActive);if(_)try{const N=await Xr(void 0,void 0,void 0,e);s(A=>A.map(C=>C.id===_.id?{...C,sessionId:N.sessionId}:C)),u(null)}catch(N){oc(N)||console.error(N);const A=N instanceof Error?N.message:typeof N=="string"?N:"Failed to create terminal session";u(A)}},[n]),k=n.find(_=>_.isActive)??null,S=a.useCallback(()=>{u(null),h.current+=1,m(_=>_+1)},[]);return{tabs:n,activeTab:k,isReady:i,bootstrapError:c,createTab:p,closeTab:g,setActiveTab:b,updateTabTitle:v,restartActiveTab:x,retryBootstrap:S,replaceActiveTabSession:y}}const pR=1e4,fR=[500,1500,3e3],hg="kb-terminal-font-size",ur=14,gR=8,bR=32,xR='"Fusion Terminal Nerd Font Symbols", "MesloLGS NF", "MesloLGM Nerd Font", "JetBrainsMono Nerd Font", "FiraCode Nerd Font", "Hack Nerd Font", ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace';function vR(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 yR(e){return`\x1B${e}`}const jR=[{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 mr(e){return Math.min(bR,Math.max(gR,e))}function kR(){if(typeof window>"u")return ur;try{const e=window.localStorage.getItem(hg);if(!e)return ur;const n=Number.parseInt(e,10);return Number.isFinite(n)?mr(n):ur}catch{return ur}}function wR(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 NR(e){return new Promise(n=>setTimeout(n,e))}async function SR(e,n=fR){let s;for(let i=0;i<=n.length;i+=1)try{return await e()}catch(r){if(!wR(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 NR(o)}throw s??new Error("Dynamic import failed")}function ph(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}function CR(){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=ER()-e.offsetTop-e.height;return i>=30&&i>80?i:0}let lc=null;function ER(){return lc===null&&(lc=window.innerHeight),lc}function _R({isOpen:e,onClose:n,initialCommand:s,projectId:i}){const[r,o]=a.useState(null),[l,c]=a.useState(null),[u,d]=a.useState(!1),[m,h]=a.useState(null),[f,p]=a.useState(0),[g,b]=a.useState(0),[v,x]=a.useState(null),[y,k]=a.useState(()=>kR()),[S,_]=a.useState(!1),[N,A]=a.useState(null),C=a.useRef(null),z=a.useRef(null),M=a.useRef(!1);ci(z,e,"fusion:terminal-modal-size");const T=a.useRef(null),U=a.useRef(null),q=a.useRef(!1),D=a.useRef(!1),R=a.useRef(null),F=a.useRef(()=>{}),V=a.useRef(null),K=a.useRef(0),ee=a.useRef(y),E=a.useRef(null),$=a.useRef(i);K.current=g,ee.current=y;const P=a.useCallback(he=>{if(he&&D.current!==he)return;const Me=U.current,Je=T.current,$e=R.current;if(!(!Me||!Je)&&!(he&&D.current!==he))try{Me.fit(),$e&&$e(Je.cols,Je.rows)}catch{}},[]);a.useEffect(()=>{e&&p(he=>he+1)},[e]),a.useEffect(()=>{if(!e||!ph())return;const he=window.visualViewport;if(!he)return;const Me=()=>{const Je=CR();b(Je),x(he.height),Je>0&&z.current?.scrollIntoView&&z.current.scrollIntoView({block:"end",behavior:"smooth"}),E.current!==null&&(cancelAnimationFrame(E.current),E.current=null);const $e=typeof D.current=="string"?D.current:void 0;E.current=requestAnimationFrame(()=>{E.current=null,P($e)})};return Me(),he.addEventListener("resize",Me),he.addEventListener("scroll",Me),()=>{he.removeEventListener("resize",Me),he.removeEventListener("scroll",Me),E.current!==null&&(cancelAnimationFrame(E.current),E.current=null),b(0),x(null)}},[P,e]),a.useEffect(()=>{if(!e)return;const he=z.current;if(!he||typeof ResizeObserver>"u")return;let Me=null;const Je=new ResizeObserver(()=>{Me!==null&&cancelAnimationFrame(Me),Me=requestAnimationFrame(()=>{Me=null;const $e=typeof D.current=="string"?D.current:void 0;P($e)})});return Je.observe(he),()=>{Je.disconnect(),Me!==null&&cancelAnimationFrame(Me)}},[P,e]);const{tabs:w,activeTab:O,isReady:Z,bootstrapError:Ne,createTab:se,closeTab:le,setActiveTab:we,updateTabTitle:L,restartActiveTab:ne,retryBootstrap:Q,replaceActiveTabSession:be}=hR(i),{connectionStatus:de,sendInput:me,resize:ie,onData:xe,onConnect:Re,onExit:Oe,onScrollback:nt,reconnect:et,onSessionInvalid:Ze}=dR(O?.sessionId??null,i);R.current=ie,F.current=me,a.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(hg,String(y))}catch{}},[y]);const rt=a.useCallback(()=>{const he=T.current;if(he)try{U.current?.fit(),ie(he.cols,he.rows)}catch{}},[ie]);a.useEffect(()=>{if(!e||!Z)return;const he=O?.sessionId;if(!he)return;const Me=$.current!==i;if(Me&&($.current=i),D.current===he&&T.current&&!Me)return;T.current&&(D.current!==he||Me)&&(T.current.dispose(),T.current=null,U.current=null,D.current=!1,V.current&&(window.removeEventListener("resize",V.current),V.current=null),d(!1),h(null));let Je=!0,$e;return(async()=>{const J=SR(()=>Promise.all([hn(()=>import("./vendor-xterm-DzcZoU0P.js").then(te=>te.x),__vite__mapDeps([6,1,7])),hn(()=>import("./addon-fit-C7jRorKK.js").then(te=>te.a),__vite__mapDeps([9,1])),hn(()=>import("./addon-web-links-CkJwd4cQ.js").then(te=>te.a),__vite__mapDeps([10,1]))])),re=new Promise((te,Ye)=>{$e=setTimeout(()=>{Ye(new Error("xterm initialization timed out"))},pR)});let ye,at;try{const[{Terminal:te},{FitAddon:Ye},{WebLinksAddon:mt}]=await Promise.race([J,re]);if(!Je||!C.current||T.current)return;ye=new te({cursorBlink:!0,cursorStyle:"block",fontSize:ee.current,fontFamily:xR,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}),at=new Ye,ye.loadAddon(at);const ht=new mt;if(ye.loadAddon(ht),!ph())try{const{WebglAddon:bt}=await hn(async()=>{const{WebglAddon:Qt}=await import("./addon-webgl-BjvOw43o.js").then(Pt=>Pt.a);return{WebglAddon:Qt}},__vite__mapDeps([11,1])),Nt=new bt;Nt.onContextLoss(()=>{Nt.dispose()}),ye.loadAddon(Nt)}catch{}ye.open(C.current),$e&&clearTimeout($e);const xt=C.current?.querySelector(".xterm-helper-textarea");if(xt&&xt.focus(),C.current)try{C.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}setTimeout(()=>{at.fit();const bt=C.current?.querySelector(".xterm-helper-textarea");bt&&bt.focus()},50),T.current=ye,U.current=at,D.current=he,K.current>0&&(E.current!==null&&(cancelAnimationFrame(E.current),E.current=null),E.current=requestAnimationFrame(()=>{E.current=null,P(he)})),ye.onData(bt=>{D.current===he&&F.current(bt)});const St=()=>{if(D.current===he&&U.current&&T.current)try{U.current.fit();const{cols:bt,rows:Nt}=T.current;R.current?.(bt,Nt)}catch{}};window.addEventListener("resize",St),V.current&&window.removeEventListener("resize",V.current),V.current=St,d(!0),h(null)}catch(te){if($e&&clearTimeout($e),!Je)return;const Ye=te instanceof Error?te.message:"xterm initialization failed";h(Ye)}})(),()=>{Je=!1,$e&&clearTimeout($e)}},[P,e,Z,O?.sessionId,i]),a.useEffect(()=>{e||(T.current&&(T.current.dispose(),T.current=null),U.current=null,D.current=!1,V.current&&(window.removeEventListener("resize",V.current),V.current=null),d(!1),h(null),q.current=!1,o(null),c(null),_(!1),A(null))},[e]),a.useEffect(()=>{if(!u||!T.current||!O)return;const he=O.sessionId,Me=re=>{D.current===he&&T.current?.write(re)},Je=xe(re=>{Me(re)}),$e=nt(re=>{Me(re)}),ft=Re(re=>{L(O.id,pd(re.shell)||re.shell)}),J=Oe(re=>{D.current===he&&(c(re),T.current?.write(`\r
|
|
658
|
+
\x1B[33m[Process exited with code ${re}]\x1B[0m\r
|
|
659
|
+
`))});return()=>{Je(),$e(),ft(),J()}},[u,O?.sessionId,O?.id,O,de,xe,nt,Re,Oe,L]),a.useEffect(()=>{de==="connected"&&s&&q.current!==s&&O&&(q.current=s,setTimeout(()=>{me(s+`
|
|
660
|
+
`)},500))},[de,s,me,O,f]),a.useEffect(()=>{if(!u||!T.current)return;T.current.options.fontSize=y,E.current!==null&&(cancelAnimationFrame(E.current),E.current=null);const he=requestAnimationFrame(()=>{E.current=null,rt()});return E.current=he,()=>{E.current===he&&(cancelAnimationFrame(he),E.current=null)}},[y,u,rt]),a.useEffect(()=>{if(!e)return;const he=Me=>{if(!(!Me.ctrlKey&&!Me.metaKey)){if(Me.code==="Equal"||Me.code==="NumpadAdd"){Me.preventDefault(),k(Je=>mr(Je+1));return}if(Me.code==="Minus"||Me.code==="NumpadSubtract"){Me.preventDefault(),k(Je=>mr(Je-1));return}if(Me.code==="Digit0"||Me.code==="Numpad0"){Me.preventDefault(),k(ur);return}}};return window.addEventListener("keydown",he),()=>window.removeEventListener("keydown",he)},[e,rt]),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"&&T.current&&setTimeout(()=>{if(!T.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 He=a.useCallback(()=>{if(!C.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;T.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 Je=Me.value.length;Me.setSelectionRange(Je,Je)},[]);a.useEffect(()=>Ze(()=>{T.current?.clear(),c(null),q.current=!1,T.current&&(T.current.dispose(),T.current=null),U.current=null,D.current=!1,V.current&&(window.removeEventListener("resize",V.current),V.current=null),d(!1),h(null),be().catch(Me=>{console.error("Failed to replace invalid terminal session:",Me)})}),[Ze,be]);const Ge=a.useCallback(he=>{he.target===he.currentTarget&&(M.current=!0)},[]),oe=a.useCallback(he=>{M.current&&he.target===he.currentTarget&&n(),M.current=!1},[n]),je=a.useCallback(()=>{T.current?.clear()},[]),X=a.useCallback(async()=>{T.current?.clear(),c(null),q.current=!1;try{await ne()}catch(he){o(ke(he)||"Failed to restart terminal session")}},[ne]),Ae=a.useCallback(()=>{T.current&&(T.current.dispose(),T.current=null),U.current=null,D.current=!1,V.current&&(window.removeEventListener("resize",V.current),V.current=null),h(null),d(!1)},[]),Te=a.useCallback(()=>{window.location.reload()},[]),pe=a.useCallback(()=>{k(he=>mr(he+1))},[]),_e=a.useCallback(()=>{k(he=>mr(he-1))},[]),Fe=a.useCallback(he=>{A(Me=>Me===he?null:he)},[]),it=a.useCallback(he=>{if(N==="ctrl"){me(vR(he)),A(null);return}if(N==="alt"){me(yR(he)),A(null);return}me(he)},[me,N]),ve=a.useCallback(he=>{me(he),A(null)},[me]);if(!e)return null;const ce=()=>{switch(de){case"connected":return t.jsx("span",{className:"terminal-status connected",title:"Connected"});case"connecting":case"reconnecting":return t.jsx("span",{className:"terminal-status connecting",title:"Connecting..."});case"disconnected":return t.jsx("span",{className:"terminal-status disconnected",title:"Disconnected"});default:return null}},Ie=!Z||!O&&!Ne;return t.jsx("div",{className:"modal-overlay open",onMouseDown:Ge,onMouseUp:oe,role:"dialog","aria-modal":"true","data-testid":"terminal-modal-overlay",style:g>0?{"--overlay-padding-top":"0px"}:void 0,children:t.jsxs("div",{ref:z,className:"modal terminal-modal","data-testid":"terminal-modal",style:g>0?{"--keyboard-overlap":`${g}px`,"--vv-height":v?`${v}px`:void 0}:void 0,children:[t.jsxs("div",{className:"terminal-header",children:[t.jsxs("div",{className:"terminal-tabs","data-testid":"terminal-tabs",children:[w.map(he=>t.jsxs("div",{className:`terminal-tab ${he.isActive?"terminal-tab--active":""}`,onClick:()=>we(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:se,title:"New terminal",children:"+"})]}),t.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[t.jsx(pi,{size:16}),ce()]}),t.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[de==="disconnected"&&O&&t.jsxs("button",{className:"terminal-reconnect-btn",onClick:et,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[t.jsx(Ln,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),l!==null&&t.jsxs("button",{className:"terminal-restart-btn",onClick:X,title:"New Session","data-testid":"terminal-restart-btn",children:[t.jsx(Ln,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:je,"data-testid":"terminal-clear-btn",title:"Clear terminal",children:[t.jsx(on,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Clear"})]}),t.jsxs("button",{className:"terminal-clear-btn terminal-clear-btn--shortcut",onClick:()=>_(he=>!he),"data-testid":"terminal-shortcut-toggle",title:"Shortcuts","aria-pressed":S,children:[t.jsx(bx,{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(Kt,{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:[Ie&&!Ne&&t.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[t.jsx("div",{className:"terminal-spinner"}),t.jsx("span",{children:"Starting terminal..."})]}),Ne&&!O&&t.jsx("div",{className:"terminal-loading","data-testid":"terminal-bootstrap-error",children:t.jsxs("div",{className:"terminal-error-content",children:[t.jsxs("span",{children:["Failed to start terminal: ",Ne]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:Q,"data-testid":"terminal-retry-btn",children:[t.jsx(Ln,{size:14}),"Retry"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Te,"data-testid":"terminal-bootstrap-refresh-btn",children:[t.jsx(Ln,{size:14}),"Refresh page"]})]})]})}),m&&O&&t.jsx("div",{className:"terminal-loading","data-testid":"terminal-xterm-init-error",children:t.jsxs("div",{className:"terminal-error-content",children:[t.jsxs("span",{children:["Terminal UI failed to initialize: ",m]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:Ae,"data-testid":"terminal-reinit-btn",children:[t.jsx(Ln,{size:14}),"Reinitialize"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Te,"data-testid":"terminal-xterm-refresh-btn",children:[t.jsx(Ln,{size:14}),"Refresh page"]})]})]})}),t.jsx("div",{ref:C,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:He,onTouchStart:He},O?.sessionId)]}),S&&t.jsxs("div",{className:"terminal-shortcut-panel","data-testid":"terminal-shortcut-panel",children:[t.jsxs("div",{className:"terminal-shortcut-modifier-row",children:[t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${N==="ctrl"?"is-active":""}`,"data-testid":"terminal-modifier-ctrl",onClick:()=>Fe("ctrl"),"aria-pressed":N==="ctrl",children:"Ctrl"}),t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${N==="alt"?"is-active":""}`,"data-testid":"terminal-modifier-alt",onClick:()=>Fe("alt"),"aria-pressed":N==="alt",children:"Alt"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>ve("\x1B"),children:"ESC"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>ve(" "),children:"Tab"})]}),jR.map(he=>t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>it(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(Dx,{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(ln,{size:14})})]}),t.jsx("span",{className:"terminal-shortcuts",children:"Ctrl++/- zoom • ⌨ Shortcuts panel • Esc close"})]})]})})}const er={name:"",command:""};function fh(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function MR(e,n=60){return e.length<=n?e:e.slice(0,n-3)+"..."}function AR({isOpen:e,onClose:n,addToast:s,projectId:i,onRunScript:r}){const[o,l]=a.useState({}),[c,u]=a.useState(!0),[d,m]=a.useState(!1),[h,f]=a.useState(null),[p,g]=a.useState(er),[b,v]=a.useState(!1),[x,y]=a.useState(null),[k,S]=a.useState(null),_=_i(n),N=a.useCallback(async()=>{try{u(!0);const F=await Nr(i);l(F)}catch(F){s(ke(F)||"Failed to load scripts","error")}finally{u(!1)}},[s,i]);a.useEffect(()=>{e&&N()},[e,N]);const A=a.useCallback(()=>{m(!0),f(null),g(er),S(null)},[]),C=a.useCallback((F,V)=>{f(F),m(!1),g({name:F,command:V}),S(null)},[]),z=a.useCallback(()=>{f(null),m(!1),g(er),S(null)},[]),M=a.useCallback(F=>{g(V=>({...V,name:F})),F&&!fh(F)?S("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):S(null)},[]),T=a.useCallback(async()=>{const F=p.name.trim(),V=p.command.trim();if(!F){s("Script name is required","error");return}if(!fh(F)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!V){s("Script command is required","error");return}v(!0);try{await Jj(F,V,i),s(h?"Script updated":"Script created","success"),f(null),m(!1),g(er),S(null),await N()}catch(K){const ee=ke(K);ee?.includes("already exists")?s("A script with this name already exists","error"):s(ee||"Failed to save script","error")}finally{v(!1)}},[p,h,s,N,i]),U=a.useCallback(async F=>{try{await Yj(F,i),s("Script deleted","success"),y(null),h===F&&(f(null),g(er)),await N()}catch(V){s(ke(V)||"Failed to delete script","error")}},[h,s,N,i]),q=a.useCallback((F,V)=>{r&&r(F,V)},[r]);if(!e)return null;const D=d||h!==null,R=Object.entries(o).map(([F,V])=>({name:F,command:V}));return t.jsx("div",{className:"modal-overlay open",..._,"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(pi,{size:18,style:{marginRight:"8px",verticalAlign:"middle"}}),"Scripts"]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]}),t.jsx("div",{className:"modal-body scripts-modal-body",children:c?t.jsxs("div",{style:{textAlign:"center",padding:"32px",color:"var(--text-muted)"},children:[t.jsx(lt,{size:24,className:"spin",style:{margin:"0 auto 8px",display:"block"}}),"Loading scripts..."]}):D?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:F=>M(F.target.value),placeholder:"e.g., build, test, lint",disabled:b||h!==null,"data-testid":"script-name-input",style:{width:"100%",borderColor:k?"var(--color-error)":void 0}}),k&&t.jsx("div",{style:{fontSize:"12px",color:"var(--color-error)",marginTop:"4px"},"data-testid":"script-name-error",children:k}),t.jsx("div",{style:{fontSize:"11px",color:"var(--text-muted)",marginTop:"4px"},children:"Letters, numbers, hyphens, and underscores only"})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"script-command",style:{display:"block",marginBottom:"4px",fontSize:"13px",fontWeight:500,color:"var(--text)"},children:"Command"}),t.jsx("textarea",{id:"script-command",className:"input",value:p.command,onChange:F=>g(V=>({...V,command:F.target.value})),placeholder:"e.g., npm run build",rows:3,disabled:b,"data-testid":"script-command-input",style:{width:"100%",resize:"vertical",fontFamily:"monospace"}})]}),t.jsxs("div",{className:"scripts-modal-form-actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end"},children:[t.jsx("button",{className:"btn btn-secondary",onClick:z,disabled:b,"data-testid":"script-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:T,disabled:b||!!k,"data-testid":"script-save-btn",children:b?t.jsxs(t.Fragment,{children:[t.jsx(lt,{size:14,className:"spin",style:{marginRight:"6px"}}),"Saving..."]}):h?"Update":"Create"})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"scripts-modal-list-header",style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[t.jsx("div",{style:{fontSize:"13px",color:"var(--text-muted)"},children:R.length===0?"No scripts defined":`${R.length} script${R.length===1?"":"s"}`}),t.jsxs("button",{className:"btn btn-primary",onClick:A,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx(ln,{size:14}),"Add Script"]})]}),R.length===0?t.jsxs("div",{style:{textAlign:"center",padding:"32px",color:"var(--text-muted)",fontSize:"14px",border:"1px dashed var(--border)",borderRadius:"8px"},"data-testid":"empty-state",children:[t.jsx(pi,{size:32,style:{margin:"0 auto 12px",opacity:.5}}),t.jsx("div",{children:"No scripts defined yet."}),t.jsx("div",{style:{marginTop:"4px",fontSize:"12px"},children:"Add scripts to quickly run common commands from the dashboard."})]}):t.jsx("div",{className:"scripts-modal-list",style:{display:"flex",flexDirection:"column",gap:"8px"},children:R.map(F=>t.jsx("div",{className:"script-card","data-testid":`script-${F.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:F.name})}),t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:F.command,children:MR(F.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:()=>q(F.name,F.command),title:"Run script","aria-label":`Run ${F.name}`,"data-testid":`run-script-${F.name}`,style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 10px",fontSize:"12px"},children:[t.jsx(En,{size:12}),"Run"]}),t.jsx("button",{className:"btn-icon",onClick:()=>C(F.name,F.command),title:"Edit","aria-label":`Edit ${F.name}`,"data-testid":`edit-script-${F.name}`,children:t.jsx(ln,{size:14,style:{transform:"rotate(45deg)"}})}),x===F.name?t.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[t.jsx("button",{className:"btn-icon",onClick:()=>U(F.name),title:"Confirm delete","aria-label":`Confirm delete ${F.name}`,"data-testid":`confirm-delete-script-${F.name}`,style:{color:"var(--color-error)"},children:t.jsx(on,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>y(null),title:"Cancel delete","aria-label":"Cancel delete","data-testid":`cancel-delete-script-${F.name}`,children:t.jsx(Kt,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>y(F.name),title:"Delete","aria-label":`Delete ${F.name}`,"data-testid":`delete-script-${F.name}`,children:t.jsx(on,{size:14})})]})]})},F.name))})]})})]})})}function RR(e,n,s){const[i,r]=a.useState([]),[o,l]=a.useState("."),[c,u]=a.useState(!1),[d,m]=a.useState(null),[h,f]=a.useState(0),p=a.useCallback(()=>{f(b=>b+1)},[]),g=a.useCallback(b=>{l(b),m(null)},[]);return a.useEffect(()=>{l("."),m(null),r([])},[e]),a.useEffect(()=>{if(!n||!e)return;let b=!1;async function v(){u(!0),m(null);try{const x=await uj(e,o==="."?void 0:o,s);b||r(x.entries)}catch(x){b||(m(ke(x)||"Failed to load files"),r([]))}finally{b||u(!1)}}return v(),()=>{b=!0}},[e,o,n,h,s]),{entries:i,currentPath:o,setPath:g,loading:c,error:d,refresh:p}}function TR(e,n,s,i){const[r,o]=a.useState(""),[l,c]=a.useState(""),[u,d]=a.useState(null),[m,h]=a.useState(!1),[f,p]=a.useState(!1),[g,b]=a.useState(null),v=a.useCallback(k=>{o(k),b(null)},[]);a.useEffect(()=>{if(!e||!n){o(""),c(""),d(null),b(null);return}let k=!1;async function S(){h(!0),b(null);try{const _=await mj(e,n,i);k||(o(_.content),c(_.content),d(_.mtime))}catch(_){k||(b(ke(_)||"Failed to load file"),o(""),c(""),d(null))}finally{k||h(!1)}}return S(),()=>{k=!0}},[e,n,s,i]);const x=r!==l,y=a.useCallback(async()=>{if(!(!e||!n||!x)){p(!0),b(null);try{const k=await hj(e,n,r,i);c(r),d(k.mtime)}catch(k){throw b(ke(k)||"Failed to save file"),k}finally{p(!1)}}},[e,n,r,x,i]);return{content:r,setContent:v,originalContent:l,loading:m,saving:f,error:g,save:y,hasChanges:x,mtime:u}}const PR=1e4;function IR(e){const s=e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||e||"Project Root"}function $R(e){return{id:e.id,label:e.id,title:e.title,worktree:e.worktree,kind:"task"}}function DR(e){const[n,s]=a.useState("Project Root"),[i,r]=a.useState([]),[o,l]=a.useState(!0),[c,u]=a.useState(null);return a.useEffect(()=>{let d=!1;async function m(){try{const f=await dj(e);if(d)return;s(IR(f.project)),r(f.tasks.map($R)),u(null)}catch(f){d||u(ke(f)||"Failed to load workspaces")}finally{d||l(!1)}}m();const h=window.setInterval(()=>{m()},PR);return()=>{d=!0,window.clearInterval(h)}},[e]),{projectName:n,workspaces:i,loading:o,error:c}}function LR(e){return e===void 0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function zR(e){return e?new Date(e).toLocaleDateString():""}function gh(e,n){return zw(e,n)}const tr={visible:!1,x:0,y:0,entry:null,entryFullPath:""},cc={type:null,entry:null,entryFullPath:""},FR=200,OR=500,bh=10;function UR({x:e,y:n,entry:s,onAction:i,onClose:r}){const o=a.useRef(null),[l,c]=a.useState({x:e,y:n});a.useEffect(()=>{const m=o.current;if(!m)return;const h=m.getBoundingClientRect(),f=window.visualViewport,p=f?.width&&f.width>0?f.width:window.innerWidth,g=f?.height&&f.height>0?f.height:window.innerHeight,b=f?.offsetLeft??0,v=f?.offsetTop??0,x=8;let y=e-b,k=n-v;y+h.width>p-x&&(y=p-x-h.width),k+h.height>g-x&&(k=g-x-h.height),y<x&&(y=x),k<x&&(k=x),c({x:y+b,y:k+v})},[e,n]),a.useEffect(()=>{const m=h=>{h.key==="Escape"&&r()};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[r]);const u=s.type==="directory",d=[{id:"copy",label:"Copy",icon:Ui,disabled:!1},{id:"move",label:"Move",icon:Fx,disabled:!1},{id:"rename",label:"Rename",icon:ms,disabled:!1},...u?[{id:"download-zip",label:"Download as ZIP",icon:Mr,disabled:!1}]:[{id:"download",label:"Download",icon:Rb,disabled:!1}],{id:"divider",label:"",icon:Ui,disabled:!0},{id:"delete",label:"Delete",icon:on,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 BR({type:e,entry:n,entryFullPath:s,onConfirm:i,onCancel:r,loading:o,error:l}){const c=a.useRef(null),u=e==="rename"?n.name:"",[d,m]=a.useState(u);a.useEffect(()=>{setTimeout(()=>c.current?.focus(),50)},[]),a.useEffect(()=>{if(e==="rename"&&c.current){const g=n.name.lastIndexOf(".");g>0?c.current.setSelectionRange(0,g):c.current.select()}},[e,n.name]);const h=g=>{g.key==="Enter"&&d.trim()&&i(d.trim()),g.key==="Escape"&&r()};if(e==="delete")return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsxs("div",{className:"file-browser-dialog",onClick:g=>g.stopPropagation(),children:[t.jsxs("div",{className:"file-browser-dialog-title",children:["Delete ",n.type==="directory"?"Folder":"File"]}),t.jsxs("div",{className:"file-browser-dialog-message",children:["Are you sure you want to delete ",t.jsx("strong",{children:n.name}),"?",n.type==="directory"&&" This will delete all contents recursively."]}),l&&t.jsx("div",{className:"file-browser-dialog-error",children:l}),t.jsxs("div",{className:"file-browser-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:r,disabled:o,children:"Cancel"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>i(""),disabled:o,children:o?"Deleting...":"Delete"})]})]})});const p={copy:{title:"Copy",placeholder:"Destination path",confirm:"Copy"},move:{title:"Move",placeholder:"Destination path",confirm:"Move"},rename:{title:"Rename",placeholder:"New name",confirm:"Rename"}}[e];return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsxs("div",{className:"file-browser-dialog",onClick:g=>g.stopPropagation(),children:[t.jsx("div",{className:"file-browser-dialog-title",children:p.title}),t.jsx("div",{className:"file-browser-dialog-info",children:e==="rename"?n.name:s}),t.jsx("input",{ref:c,className:"file-browser-dialog-input",type:"text",value:d,onChange:g=>m(g.target.value),placeholder:p.placeholder,onKeyDown:h,disabled:o}),l&&t.jsx("div",{className:"file-browser-dialog-error",children:l}),t.jsxs("div",{className:"file-browser-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:r,disabled:o,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>i(d.trim()),disabled:o||!d.trim(),children:o?`${p.confirm}ing...`:p.confirm})]})]})})}function HR({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(tr),[f,p]=a.useState(cc),[g,b]=a.useState(!1),[v,x]=a.useState(null),[y,k]=a.useState(!1),[S,_]=a.useState(null),N=a.useRef(null),A=a.useRef(null),C=a.useRef(null),z=a.useRef(!1),M=a.useCallback(()=>{N.current!==null&&(window.clearTimeout(N.current),N.current=null),A.current!==null&&(window.clearTimeout(A.current),A.current=null)},[]),T=a.useCallback(()=>{M(),C.current=null,k(!1),_(null)},[M]);a.useEffect(()=>()=>{M()},[M]);const U=a.useCallback(($,P,w,O)=>{h({visible:!0,x:$,y:P,entry:w,entryFullPath:O})},[]),q=a.useCallback(($,P,w)=>{if($.touches.length!==1)return;const O=$.touches[0];O&&(T(),C.current={x:O.clientX,y:O.clientY},A.current=window.setTimeout(()=>{k(!0),_(w)},FR),N.current=window.setTimeout(()=>{const Z=C.current;Z&&(z.current=!0,k(!1),_(null),M(),U(Z.x,Z.y,P,w))},OR))},[T,M,U]),D=a.useCallback($=>{const P=C.current,w=$.touches[0];!P||!w||(Math.abs(w.clientX-P.x)>bh||Math.abs(w.clientY-P.y)>bh)&&T()},[T]),R=a.useCallback(()=>{T()},[T]);a.useEffect(()=>{if(!m.visible)return;const $=document.querySelector(".file-browser-list"),P=()=>{z.current=!1,T(),h(tr)};return $?.addEventListener("scroll",P),()=>$?.removeEventListener("scroll",P)},[T,m.visible]),a.useEffect(()=>{if(!m.visible)return;const $=P=>{P.key==="Escape"&&(z.current=!1,h(tr))};return document.addEventListener("keydown",$),()=>document.removeEventListener("keydown",$)},[m.visible]);const F=a.useCallback(($,P)=>{$.preventDefault(),$.stopPropagation(),T(),z.current=!1,U($.clientX,$.clientY,P,gh(n,P.name))},[T,n,U]),V=a.useCallback($=>{if(!m.entry)return;z.current=!1;const P=m.entry,w=m.entryFullPath;if(h(tr),$==="download"){if(!c)return;const O=yp(c,w,d);window.open(ri(O),"_blank");return}if($==="download-zip"){if(!c)return;const O=vj(c,w,d);window.open(ri(O),"_blank");return}p({type:$,entry:P,entryFullPath:w}),x(null)},[m,c,d]),K=a.useCallback(async $=>{if(!(!f.type||!f.entry||!c)){b(!0),x(null);try{switch(f.type){case"copy":await fj(c,f.entryFullPath,$,d);break;case"move":await gj(c,f.entryFullPath,$,d);break;case"rename":await xj(c,f.entryFullPath,$,d);break;case"delete":await bj(c,f.entryFullPath,d);break}p(cc),u?.()}catch(P){x(ke(P)||"Operation failed")}finally{b(!1)}}},[f,c,u,d]),ee=a.useCallback(()=>{p(cc),x(null)},[]),E=a.useCallback(($,P)=>{if(z.current){z.current=!1;return}m.visible||($.type==="directory"?i(P):s(P))},[m.visible,i,s]);return r?t.jsxs("div",{className:"file-browser-loading",children:[t.jsx(lt,{className:"spin",size:24}),t.jsx("span",{children:"Loading files..."})]}):o?t.jsxs("div",{className:"file-browser-error",children:[t.jsxs("p",{children:["Error: ",o]}),l&&t.jsx("button",{className:"btn btn-sm",onClick:l,children:"Retry"})]}):t.jsxs("div",{className:"file-browser",children:[t.jsxs("div",{className:"file-browser-header",children:[n!=="."&&t.jsxs("button",{className:"file-browser-up",onClick:()=>{i(Fw(n))},children:[t.jsx(kn,{size:16,style:{transform:"rotate(-90deg)"}}),"Up one level"]}),t.jsx("span",{className:"file-browser-path",children:n==="."?"Root":Pa(n)})]}),t.jsx("div",{className:"file-browser-list",children:e.length===0?t.jsx("div",{className:"file-browser-empty",children:"(empty directory)"}):e.map($=>{const P=gh(n,$.name),w=y&&S===P;return t.jsxs("div",{className:`file-node file-node--${$.type} ${w?"file-node--long-pressing":""}`,onClick:()=>E($,P),onContextMenu:O=>F(O,$),onTouchStart:O=>q(O,$,P),onTouchMove:D,onTouchEnd:R,onTouchCancel:R,children:[t.jsx("div",{className:"file-node-icon",children:$.type==="directory"?t.jsx(Qn,{size:16}):t.jsx(rp,{size:16})}),t.jsx("div",{className:"file-node-name",children:$.name}),$.type==="file"&&$.size!==void 0&&t.jsx("div",{className:"file-node-size",children:LR($.size)}),$.mtime&&t.jsx("div",{className:"file-node-time",children:zR($.mtime)})]},$.name)})}),m.visible&&m.entry&&t.jsx(UR,{x:m.x,y:m.y,entry:m.entry,onAction:V,onClose:()=>{z.current=!1,h(tr)}}),f.type&&f.entry&&t.jsx(BR,{type:f.type,entry:f.entry,entryFullPath:f.entryFullPath,onConfirm:K,onCancel:ee,loading:g,error:v})]})}function qR(e){if(!e)return!1;const n=e.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function VR({content:e,onChange:n,readOnly:s,filePath:i}){const[r,o]=a.useState(!1),[l,c]=a.useState(!0),u=qR(i),d=u&&(s?!0:r),m=a.useCallback(()=>{o(!1)},[]),h=a.useCallback(()=>{o(!0)},[]),f=a.useCallback(()=>{c(p=>!p)},[]);return t.jsxs("div",{className:"file-editor-container",children:[u?t.jsxs("div",{className:"file-editor-toolbar",children:[t.jsxs("div",{className:"file-editor-mode-toggle",children:[!s&&t.jsxs("button",{className:`btn btn-sm ${d?"":"btn-primary"}`,onClick:m,disabled:!d,"aria-label":"Edit mode",children:[t.jsx(ap,{size:14}),"Edit"]}),t.jsxs("button",{className:`btn btn-sm ${d?"btn-primary":""}`,onClick:h,disabled:d,"aria-label":"Preview mode",children:[t.jsx(Ma,{size:14}),"Preview"]})]}),!s&&t.jsx("button",{className:`btn btn-sm ${l?"btn-primary":""}`,onClick:f,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(_o,{size:14})})]}):!s&&t.jsxs("div",{className:"file-editor-toolbar",children:[t.jsx("div",{className:"file-editor-mode-toggle"}),t.jsx("button",{className:`btn btn-sm ${l?"btn-primary":""}`,onClick:f,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(_o,{size:14})})]}),d?t.jsx("div",{className:"file-editor-preview markdown-body",children:t.jsx(oi,{remarkPlugins:[li],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 WR(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function KR({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(Bd,{size:14}):t.jsx(Cc,{size:14}),t.jsx("span",{className:"workspace-selector-trigger-label",children:l}),t.jsx(sn,{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(Bd,{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(Cc,{size:14}),t.jsx("span",{children:c.id})]}),c.title&&t.jsx("span",{className:"workspace-selector-option-meta",title:c.title,children:WR(c.title)})]},c.id))]})]})]})}const GR=768,JR=280,bo=180,xo=500,xh="fusion:file-browser-sidebar-width",pg=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),YR=new Set([...pg,".exe",".dll",".so",".dylib",".zip",".tar",".gz",".bz2",".xz",".7z",".rar",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".mp3",".mp4",".avi",".mov",".webm",".mkv",".flv",".woff",".woff2",".ttf",".otf",".eot",".wasm",".bin"]);function vh(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return YR.has(n)}function QR(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return pg.has(n)}function XR({initialWorkspace:e="project",onClose:n,onWorkspaceChange:s,projectId:i}){const{projectName:r,workspaces:o}=DR(i),l=a.useRef(null);ci(l,!0,"fusion:files-modal-size");const c=_i(n),[u,d]=a.useState(e),[m,h]=a.useState(null),[f,p]=a.useState(!1),[g,b]=a.useState("list"),[v,x]=a.useState(JR),{entries:y,currentPath:k,setPath:S,loading:_,error:N,refresh:A}=RR(u,!0,i),{content:C,setContent:z,originalContent:M,loading:T,saving:U,error:q,save:D,hasChanges:R,mtime:F}=TR(u,m,!0,i);a.useEffect(()=>{d(e)},[e]),a.useEffect(()=>{const le=()=>{p(window.innerWidth<=GR)};return le(),window.addEventListener("resize",le),()=>window.removeEventListener("resize",le)},[]),a.useEffect(()=>{m||b("list")},[m]),a.useEffect(()=>{try{const le=localStorage.getItem(xh);if(!le)return;const we=Number.parseInt(le,10);if(!Number.isNaN(we)){const L=Math.max(bo,Math.min(xo,we));x(L)}}catch{}},[]),a.useEffect(()=>{const le=we=>{we.key==="Escape"&&n(),(we.metaKey||we.ctrlKey)&&we.key==="s"&&(we.preventDefault(),R&&!U&&D())};return document.addEventListener("keydown",le),()=>document.removeEventListener("keydown",le)},[n,R,U,D]);const V=a.useCallback(le=>{h(le),f&&b("editor")},[f]),K=a.useCallback(()=>{b("list")},[]),ee=a.useCallback(()=>{z(M)},[M,z]),E=a.useCallback(le=>{d(le),h(null),b("list"),s?.(le)},[s]),$=a.useCallback(le=>{try{localStorage.setItem(xh,String(le))}catch{}},[]),P=a.useCallback(le=>{if(f)return;le.preventDefault(),le.stopPropagation();const we=le.currentTarget;typeof we.setPointerCapture=="function"&&we.setPointerCapture(le.pointerId);const L=le.clientX,ne=v;let Q=ne;document.body.style.userSelect="none";const be=me=>{const ie=me.clientX-L,xe=Math.max(bo,Math.min(xo,ne+ie));Q=xe,x(xe)},de=me=>{typeof we.releasePointerCapture=="function"&&we.releasePointerCapture(me.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",be),document.removeEventListener("pointerup",de),$(Q)};document.addEventListener("pointermove",be),document.addEventListener("pointerup",de)},[f,$,v]),w=a.useCallback(le=>{if(f)return;const we=20;if(le.key!=="ArrowLeft"&&le.key!=="ArrowRight")return;le.preventDefault();const L=le.key==="ArrowLeft"?-we:we,ne=Math.max(bo,Math.min(xo,v+L));x(ne),$(ne)},[f,$,v]),Z=`Files — ${a.useMemo(()=>u==="project"?"Project":o.find(le=>le.id===u)?.id??u,[u,o])}`,Ne=a.useMemo(()=>!m||!QR(m)?null:yp(u,m,i),[m,u,i]),se=le=>{const we=new Blob([le]).size;return we<1024?`${we} B`:`${(we/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(Qn,{size:18}),t.jsx("span",{children:Z}),m&&t.jsx("span",{className:"file-browser-header-path",children:m})]}),t.jsxs("div",{className:"file-browser-header-actions",children:[t.jsx(KR,{currentWorkspace:u,projectName:r,workspaces:o,onSelect:E}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Kt,{size:20})})]})]}),t.jsxs("div",{className:"file-browser-body",children:[t.jsx("div",{className:`file-browser-sidebar ${f?"mobile":""} ${g==="list"?"active":""}`,style:f?void 0:{width:`${v}px`},children:t.jsx(HR,{entries:y,currentPath:k,onSelectFile:V,onNavigate:S,loading:_,error:N,onRetry:A,workspace:u,onRefresh:A,projectId:i})}),!f&&t.jsx("div",{className:"file-browser-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":bo,"aria-valuemax":xo,"aria-valuenow":v,"aria-label":"Resize sidebar",tabIndex:0,onPointerDown:P,onKeyDown:w}),t.jsx("div",{className:`file-browser-content ${f?"mobile":""} ${g==="editor"?"active":""}`,children:m?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"file-browser-toolbar",children:[t.jsxs("div",{className:"file-browser-file-info",children:[f&&g==="editor"&&t.jsxs("button",{className:"file-browser-back-button",onClick:K,"aria-label":"Back to file list",children:[t.jsx(_a,{size:16}),t.jsx("span",{children:"Back"})]}),m,vh(m)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(Yb,{size:12}),"Binary file — read only"]}),F&&t.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date(F).toLocaleString()]}),T&&t.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),t.jsx("div",{className:"file-browser-actions",children:!Ne&&R&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:ee,disabled:U,children:[t.jsx(Yx,{size:14}),"Discard"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void D(),disabled:U,children:[t.jsx(mp,{size:14}),U?"Saving...":"Save"]})]})})]}),q&&!Ne&&t.jsx("div",{className:"file-browser-error-banner",children:q}),Ne?t.jsx("div",{className:"file-browser-image-preview",children:t.jsx("img",{src:Ne,alt:m??"",className:"file-browser-image"})}):t.jsx("div",{className:"file-editor-wrapper",children:t.jsx(VR,{content:C,onChange:z,filePath:m,readOnly:vh(m)})}),!Ne&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:se(C)}),R&&t.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):t.jsxs("div",{className:"file-browser-placeholder",children:[t.jsx(Qn,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to edit"})]})})]})]})})}function ZR(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 jy();r({providers:m,loading:!1,error:null,lastUpdated:new Date})}catch(m){if(m instanceof Error&&m.name==="AbortError")return;r(h=>({...h,loading:!1,error:ke(m)||"Failed to fetch usage data"}))}},[]);a.useEffect(()=>{c()},[c]),a.useEffect(()=>{if(s)return o.current=setInterval(()=>{c(!1)},n),()=>{o.current&&(clearInterval(o.current),o.current=null)}},[s,n,c]),a.useEffect(()=>()=>{l.current&&l.current.abort(),o.current&&clearInterval(o.current)},[]);const u=a.useCallback(()=>c(!0),[c]);return{providers:i.providers,loading:i.loading,error:i.error,lastUpdated:i.lastUpdated,refresh:u}}function eT(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 tT(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}const fg="kb-usage-hidden-windows";function yh(e){const n=Zn(fg,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 nT(e,n){ys(fg,JSON.stringify(e),n)}function gg(e,n,s){return s[e]?.includes(n)??!1}function sT({window:e,viewMode:n,isHidden:s,onToggleHidden:i}){const r=tT(e.percentUsed),o=n==="remaining",l=Math.round(o?e.percentLeft:e.percentUsed),c=o?`${Math.round(e.percentLeft)}% remaining`:`${Math.round(e.percentUsed)}% used`,u=o?`${Math.round(e.percentUsed)}% used`:`${Math.round(e.percentLeft)}% left`;let d=e.resetText;if(!d&&e.resetAt){const v=new Date(e.resetAt).getTime()-Date.now();if(v>0){const x=Math.floor(v/36e5),y=Math.floor(x/24),k=x%24;y>0&&k>0?d=`resets in ${y}d ${k}h`:y>0?d=`resets in ${y}d`:x>0?d=`resets in ${x}h`:d=`resets in ${Math.floor(v/6e4)}m`}}const m=e.pace,h=m!==void 0;let f=0;h&&(f=o?100-m.percentElapsed:m.percentElapsed);const p=m?.status==="ahead",g=m?.status==="behind",b=m?.status==="on-track";return t.jsxs("div",{className:`usage-window ${s?"usage-window--hidden":""}`,children:[t.jsxs("div",{className:"usage-window-header",children:[t.jsx("span",{className:"usage-window-label",children:e.label}),t.jsxs("div",{className:"usage-window-header-controls",children:[!s&&t.jsx("span",{className:"usage-window-percentage",children:c}),!s&&t.jsx("button",{className:"btn-icon usage-window-hide-btn",onClick:i,"aria-label":`Hide ${e.label}`,"data-testid":"usage-window-hide-btn",children:t.jsx(Ma,{size:14})})]})]}),t.jsxs("div",{className:"usage-progress-wrapper",children:[t.jsx("div",{className:"usage-progress-bar",children:t.jsx("div",{className:`usage-progress-fill ${r}`,style:{width:`${l}%`},role:"progressbar","aria-valuenow":l,"aria-valuemin":0,"aria-valuemax":100,"aria-label":`${e.label}: ${c}`})}),h&&t.jsx("div",{className:"usage-pace-marker",style:{left:`${f}%`},"aria-hidden":"true","data-testid":"pace-marker"})]}),t.jsxs("div",{className:"usage-window-footer",children:[t.jsx("span",{className:"usage-window-left",children:u}),t.jsxs("span",{className:"usage-window-reset-group",children:[d&&t.jsx("span",{className:"usage-window-reset",children:d}),e.resetAt&&t.jsx("span",{className:"usage-window-reset-at",children:eT(e.resetAt)})]})]}),h&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[p&&t.jsxs(t.Fragment,{children:[t.jsx(ld,{size:14,className:"pace-icon pace-ahead"}),t.jsx("span",{className:"pace-text pace-ahead",children:m.message})]}),g&&t.jsxs(t.Fragment,{children:[t.jsx(xv,{size:14,className:"pace-icon pace-behind"}),t.jsx("span",{className:"pace-text pace-behind",children:m.message})]}),b&&t.jsxs(t.Fragment,{children:[t.jsx(wn,{size:14,className:"pace-icon pace-ontrack"}),t.jsx("span",{className:"pace-text pace-ontrack",children:m.message})]})]})]})}function iT(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 aT({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(An,{provider:iT(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=gg(e.name,c.label,s);return t.jsx(sT,{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 rT(){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 oT({isOpen:e,onClose:n,projectId:s,anchorRect:i}){const{providers:r,loading:o,error:l,lastUpdated:c,refresh:u}=ZR({autoRefresh:e}),[d,m]=a.useState(!1),[h,f]=a.useState(()=>typeof window<"u"?window.innerWidth>=769:!1),[p,g]=a.useState("used"),[b,v]=a.useState(()=>yh(s)),x=a.useRef(null),y=a.useRef(e),k=a.useRef(!1);a.useEffect(()=>{e||(k.current=!1)},[e]),a.useEffect(()=>{r.length>0&&(k.current=!0)},[r.length]),a.useEffect(()=>{if(typeof window>"u")return;const R=()=>{f(window.innerWidth>=769)};return window.addEventListener("resize",R),()=>window.removeEventListener("resize",R)},[]),a.useEffect(()=>{!y.current&&e&&(!c||Date.now()-c.getTime()>5e3)&&u(),y.current=e},[e,c,u]),a.useEffect(()=>{const R=Zn("kb-usage-view-mode",s);if(R==="used"||R==="remaining"){g(R);return}g("used")},[s]);const S=a.useCallback(R=>{g(R),ys("kb-usage-view-mode",R,s)},[s]);a.useEffect(()=>{v(yh(s))},[s]),a.useEffect(()=>{nT(b,s)},[b,s]);const _=a.useCallback((R,F)=>{v(V=>{if(gg(R,F,V)){const K=(V[R]??[]).filter(ee=>ee!==F);if(K.length===0){const{[R]:ee,...E}=V;return E}return{...V,[R]:K}}return{...V,[R]:[...V[R]??[],F]}})},[]),N=a.useCallback(R=>{v(F=>{if(!F[R])return F;const{[R]:V,...K}=F;return K})},[]),A=a.useCallback(async()=>{m(!0),await u(),m(!1)},[u]);a.useEffect(()=>{if(!e)return;const R=F=>{F.key==="Escape"&&n()};return document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)},[e,n]);const C=a.useCallback(R=>{R.target===R.currentTarget&&n()},[n]);if(!e)return null;const z=!!(i&&h),U=z?Math.min((i?.bottom??0)+8,window.innerHeight-12):void 0,q=z?Math.max(window.innerWidth-(i?.right??0),0):void 0,D=t.jsxs("div",{className:`usage-modal${z?" usage-modal--popover":" modal"}`,"data-testid":"usage-modal",style:z?{position:"fixed",top:U,right:q}:void 0,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"usage-header",children:[t.jsx(Ds,{size:18,className:"usage-header-icon"}),t.jsx("h3",{children:"Usage"})]}),t.jsxs("div",{className:"usage-header-actions",children:[t.jsxs("div",{className:"usage-view-toggle",role:"group","aria-label":"Usage view mode",children:[t.jsx("button",{className:`usage-view-toggle-btn ${p==="used"?"active":""}`,onClick:()=>S("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:()=>S("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(Kt,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:x,children:(o||!k.current&&!l)&&r.length===0?t.jsx(rT,{}):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:A,children:"Retry"})]}):r.length===0?t.jsxs("div",{className:"usage-empty",children:[t.jsx("p",{children:"No AI providers configured"}),t.jsx("p",{className:"usage-empty-hint",children:"Configure authentication in Settings to see usage data."})]}):t.jsx("div",{className:"usage-providers",children:r.map(R=>t.jsx(aT,{provider:R,viewMode:p,hiddenWindows:b,onToggleWindow:_,onShowAllHidden:N},R.name))})}),t.jsxs("div",{className:"modal-actions usage-actions",children:[t.jsx("div",{className:"modal-actions-left usage-actions-left",children:t.jsx("div",{className:"usage-last-updated",children:c&&t.jsxs("span",{children:["Last updated: ",c.toLocaleTimeString()]})})}),t.jsxs("div",{className:"modal-actions-right usage-actions-right",children:[t.jsxs("button",{className:"btn btn-sm",onClick:A,disabled:o||d,"data-testid":"usage-refresh-btn",children:[t.jsx(Ln,{size:14,className:d?"spin":"",style:{marginRight:6}}),"Refresh"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]});return z?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"usage-popover-backdrop",onClick:n,"data-testid":"usage-modal-overlay"}),D]}):t.jsx("div",{className:"modal-overlay open",onClick:C,"data-testid":"usage-modal-overlay",children:D})}function bg(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 Oo(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 lT={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},xg={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},cT={cron:sp,webhook:pp,api:ip,manual:Yn},dT={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},uT={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function mT({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(wn,{size:12}):t.jsx(Tr,{size:12}),t.jsx("span",{children:e.success?"Success":"Failed"}),n>0&&t.jsx("span",{className:"schedule-run-duration",children:bg(n)})]})}function hT({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"} ${Oo(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx(wn,{size:12}):t.jsx(Tr,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:Oo(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:xg[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:bg(r)}),s?t.jsx(gi,{size:12}):t.jsx(sn,{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 pT({routine:e,onEdit:n,onDelete:s,onRun:i,onToggle:r,running:o,lastRunOutput:l}){const[c,u]=a.useState(!1),{confirm:d}=Ks(),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=lT[e.trigger.type],f=cT[e.trigger.type],p=e.trigger.type==="cron"?("cronExpression"in e.trigger?e.trigger.cronExpression:void 0)||e.cronExpression||"":e.cronExpression||"";return t.jsxs("div",{className:`routine-card${e.enabled?"":" disabled"}${o?" running":""}`,children:[t.jsxs("div",{className:"routine-card-header",children:[t.jsxs("div",{className:"routine-card-info",children:[t.jsxs("div",{className:"routine-card-name-row",children:[t.jsx("span",{className:"routine-card-name",children:e.name}),t.jsxs("span",{className:"routine-trigger-badge",style:{borderColor:h,color:h},children:[t.jsx(f,{size:10}),xg[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(Vo,{size:10}):t.jsx(Qn,{size:10}),e.scope]})]}),e.description&&t.jsx("p",{className:"routine-card-description",children:e.description})]}),t.jsxs("div",{className:"routine-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>i(e),disabled:o,title:o?"Running…":"Run now","aria-label":o?"Running…":`Run ${e.name} now`,children:o?t.jsx(lt,{size:14,className:"spinner"}):t.jsx(En,{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(qs,{size:14}):t.jsx(En,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:"Edit","aria-label":`Edit ${e.name}`,children:t.jsx(ms,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:m,title:"Delete","aria-label":`Delete ${e.name}`,children:t.jsx(on,{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(Ci,{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:dT[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:uT[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:Oo(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:Oo(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(mT,{result:e.lastRunResult}),t.jsxs("div",{className:"routine-meta-item",children:[t.jsx("span",{className:"routine-meta-label",children:"Runs:"}),t.jsx("span",{children:e.runCount})]})]}),l&&t.jsxs("div",{className:`routine-run-output ${l.success?"success":"failure"}`,children:[l.output&&t.jsx("pre",{className:"routine-run-output-text",children:l.output}),l.error&&t.jsx("div",{className:"routine-run-output-error",children:l.error})]}),e.runHistory.length>0&&t.jsxs("div",{className:"routine-card-history",children:[t.jsxs("button",{className:"schedule-history-toggle",onClick:()=>u(g=>!g),"aria-expanded":c,children:[c?t.jsx(gi,{size:12}):t.jsx(sn,{size:12}),t.jsxs("span",{children:["Run History (",e.runHistory.length,")"]})]}),c&&t.jsxs("div",{className:"schedule-history-list",children:[e.runHistory.slice(0,10).map((g,b)=>t.jsx(hT,{result:g,index:b},`${g.startedAt}-${b}`)),e.runHistory.length>10&&t.jsxs("div",{className:"schedule-history-more",children:["…and ",e.runHistory.length-10," more"]})]})]})]})}function fT({type:e,size:n=12}){return e==="command"?t.jsxs("span",{className:"step-type-badge step-type-command",title:"Command step",children:[t.jsx(pi,{size:n}),t.jsx("span",{children:"Command"})]}):e==="create-task"?t.jsxs("span",{className:"step-type-badge step-type-create-task",title:"Create Task step",children:[t.jsx(wx,{size:n}),t.jsx("span",{children:"Create Task"})]}):t.jsxs("span",{className:"step-type-badge step-type-ai-prompt",title:"AI Prompt step",children:[t.jsx(os,{size:n}),t.jsx("span",{children:"AI Prompt"})]})}function dc(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function gT(e){return e==="command"?{id:dc(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:dc(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:dc(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function bT({step:e,onSave:n,onCancel:s}){const[i,r]=a.useState(e.name),[o,l]=a.useState(e.type),[c,u]=a.useState(e.command??""),[d,m]=a.useState(e.prompt??""),[h,f]=a.useState(e.modelProvider??""),[p,g]=a.useState(e.modelId??""),[b,v]=a.useState(e.taskTitle??""),[x,y]=a.useState(e.taskDescription??""),[k,S]=a.useState(e.taskColumn??"triage"),[_,N]=a.useState(e.timeoutMs),[A,C]=a.useState(e.continueOnFailure??!1),[z,M]=a.useState({}),[T,U]=a.useState([]),[q,D]=a.useState(!1),[R,F]=a.useState(null);a.useEffect(()=>{let $=!1;return D(!0),F(null),fs().then(P=>{$||U(P.models)}).catch(P=>{$||F(P instanceof Error?P.message:"Failed to load models")}).finally(()=>{$||D(!1)}),()=>{$=!0}},[]);const V=a.useCallback(()=>{const $={};return i.trim()||($.name="Step name is required"),o==="command"&&!c.trim()&&($.command="Command is required"),o==="ai-prompt"&&!d.trim()&&($.prompt="Prompt is required"),o==="create-task"&&!x.trim()&&($.taskDescription="Task description is required"),(o==="ai-prompt"||o==="create-task")&&(h||p)&&(!h||!p)&&($.modelProvider="Both model provider and model ID must be set together"),_!==void 0&&_<1e3&&($.timeoutMs="Timeout must be at least 1 second (1000ms)"),M($),Object.keys($).length===0},[i,o,c,d,x,h,p,_]),K=h&&p?`${h}/${p}`:"",ee=a.useCallback($=>{if(!$)f(""),g("");else{const P=$.indexOf("/");P!==-1&&(f($.slice(0,P)),g($.slice(P+1)))}},[]),E=a.useCallback(()=>{if(!V())return;const $={...e,name:i.trim(),type:o,command:o==="command"?c.trim():void 0,prompt:o==="ai-prompt"?d.trim():void 0,taskTitle:o==="create-task"&&b.trim()?b.trim():void 0,taskDescription:o==="create-task"&&x.trim()?x.trim():void 0,taskColumn:o==="create-task"?k:void 0,modelProvider:(o==="ai-prompt"||o==="create-task")&&h.trim()?h.trim():void 0,modelId:(o==="ai-prompt"||o==="create-task")&&p.trim()?p.trim():void 0,timeoutMs:_||void 0,continueOnFailure:A};o!=="ai-prompt"&&delete $.prompt,o!=="create-task"&&(delete $.taskTitle,delete $.taskDescription,delete $.taskColumn),n($)},[V,n,e,i,o,c,d,b,x,k,h,p,_,A]);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:$=>r($.target.value),"aria-invalid":!!z.name}),z.name&&t.jsx("small",{className:"field-error",children:z.name})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-type-${e.id}`,children:"Step Type"}),t.jsxs("select",{id:`step-type-${e.id}`,value:o,onChange:$=>l($.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:$=>u($.target.value),rows:2,"aria-invalid":!!z.command}),z.command&&t.jsx("small",{className:"field-error",children:z.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:$=>m($.target.value),rows:3,"aria-invalid":!!z.prompt}),z.prompt&&t.jsx("small",{className:"field-error",children:z.prompt})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-model-${e.id}`,children:"Model (optional)"}),t.jsx(Xn,{id:`step-model-${e.id}`,label:"Model",models:T,value:K,onChange:ee,placeholder:"Use default",disabled:q}),R&&t.jsx("small",{className:"field-error",children:R}),t.jsx("small",{children:"AI model for this step. Uses default if not selected."})]})]}),o==="create-task"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-title-${e.id}`,children:"Task Title (optional)"}),t.jsx("input",{id:`step-task-title-${e.id}`,type:"text",placeholder:"e.g. Review weekly dependencies",value:b,onChange:$=>v($.target.value)}),t.jsx("small",{children:"Leave blank to auto-summarize from description"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-description-${e.id}`,children:"Task Description *"}),t.jsx("textarea",{id:`step-task-description-${e.id}`,placeholder:"e.g. Check all npm dependencies for security vulnerabilities and update outdated packages",value:x,onChange:$=>y($.target.value),rows:4,"aria-invalid":!!z.taskDescription}),z.taskDescription&&t.jsx("small",{className:"field-error",children:z.taskDescription})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-column-${e.id}`,children:"Target Column"}),t.jsxs("select",{id:`step-task-column-${e.id}`,value:k,onChange:$=>S($.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(Xn,{id:`step-task-model-${e.id}`,label:"Model",models:T,value:K,onChange:ee,placeholder:"Use default",disabled:q}),R&&t.jsx("small",{className:"field-error",children:R}),z.modelProvider&&t.jsx("small",{className:"field-error",children:z.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:_??"",onChange:$=>N($.target.value?Number($.target.value):void 0),"aria-invalid":!!z.timeoutMs}),z.timeoutMs&&t.jsx("small",{className:"field-error",children:z.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:A,onChange:$=>C($.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:E,children:"Save Step"})]})]})}function xT({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=gT(d);n([...e,m]),r(m.id)},[e,n]),l=a.useCallback(d=>{n(e.filter(m=>m.id!==d)),i===d&&r(null)},[e,n,i]),c=a.useCallback((d,m)=>{const h=e.findIndex(g=>g.id===d);if(h<0)return;const f=m==="up"?h-1:h+1;if(f<0||f>=e.length)return;const p=[...e];[p[h],p[f]]=[p[f],p[h]],n(p)},[e,n]),u=a.useCallback(d=>{n(e.map(m=>m.id===d.id?d:m)),r(null)},[e,n]);return t.jsxs("div",{className:"steps-editor",children:[t.jsx("div",{className:"steps-editor-header",children:t.jsxs("span",{className:"steps-editor-title",children:["Steps (",e.length,")"]})}),e.length===0&&t.jsx("div",{className:"steps-empty-state",children:t.jsx("p",{children:"No steps added yet. Add a command or AI prompt step to get started."})}),t.jsx("div",{className:"steps-list",children:e.map((d,m)=>t.jsx("div",{className:"step-card",children:i===d.id?t.jsx(bT,{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(od,{size:14})}),t.jsx("span",{className:"step-card-index",children:m+1}),t.jsx(fT,{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(gi,{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(sn,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(d.id),title:"Edit","aria-label":`Edit ${d.name}`,children:t.jsx(ms,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>l(d.id),title:"Delete","aria-label":`Delete ${d.name}`,children:t.jsx(on,{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(ln,{size:14}),"Add Command Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ai-prompt"),children:[t.jsx(ln,{size:14}),"Add AI Prompt Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("create-task"),children:[t.jsx(ln,{size:14}),"Add Create Task Step"]})]})]})}const vg={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},vT={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function yT(e){const n=e.trim();for(const[s,i]of Object.entries(vg))if(i===n)return s;return"custom"}function jT(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function kT(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 wT(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 NT=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],ST=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function jh(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function kh({routine:e,onSubmit:n,onCancel:s,scope:i,projectId:r,onScopeChange:o}){const l=!!e,c=e?wT(e):{triggerType:"cron",cronExpression:"0 * * * *",webhookPath:"",webhookSecret:"",endpoint:""},[u,d]=a.useState(e?.name??""),[m,h]=a.useState(e?.description??""),[f,p]=a.useState(c.triggerType),[g,b]=a.useState(c.cronExpression),[v,x]=a.useState(()=>c.triggerType!=="cron"?"custom":yT(c.cronExpression)),[y,k]=a.useState(c.webhookPath),[S,_]=a.useState(c.webhookSecret),[N,A]=a.useState(c.endpoint),[C,z]=a.useState(e?.executionPolicy??"queue"),[M,T]=a.useState(e?.catchUpPolicy??"run_one"),[U,q]=a.useState(e?.enabled??!0),D=e?.steps&&e.steps.length===1&&e.steps[0].type==="ai-prompt"&&!e.command,R=e?.steps&&e.steps.length===1&&e.steps[0].type==="create-task"&&!e.command,[F,V]=a.useState(e?.steps&&e.steps.length>0&&!D&&!R?"advanced":"simple"),[K,ee]=a.useState(()=>D?"ai-prompt":R?"create-task":"command"),[E,$]=a.useState(e?.command??""),[P,w]=a.useState(e?.steps??[]),[O,Z]=a.useState(!1),[Ne,se]=a.useState(e?.timeoutMs??3e5),[le,we]=a.useState(D?e.steps?.[0]?.prompt??"":""),[L,ne]=a.useState(R?e.steps?.[0]?.taskTitle??"":""),[Q,be]=a.useState(R?e.steps?.[0]?.taskDescription??"":""),[de,me]=a.useState(R?e.steps?.[0]?.taskColumn??"triage":"triage"),[ie,xe]=a.useState(D||R?e.steps?.[0]?.modelProvider??"":""),[Re,Oe]=a.useState(D||R?e.steps?.[0]?.modelId??"":""),[nt,et]=a.useState([]),[Ze,rt]=a.useState(!1),[He,Ge]=a.useState(null),[oe,je]=a.useState(i??"global"),[X,Ae]=a.useState({}),[Te,pe]=a.useState(!1),_e=a.useRef(!0);a.useEffect(()=>()=>{_e.current=!1},[]),a.useEffect(()=>{i&&je(i)},[i]),a.useEffect(()=>{let te=!1;return rt(!0),Ge(null),fs().then(Ye=>{te||et(Ye.models)}).catch(Ye=>{te||Ge(Ye instanceof Error?Ye.message:"Failed to load models")}).finally(()=>{te||rt(!1)}),()=>{te=!0}},[]);const Fe=ie&&Re?`${ie}/${Re}`:"",it=a.useCallback(te=>{if(!te){xe(""),Oe("");return}const Ye=te.indexOf("/");Ye!==-1&&(xe(te.slice(0,Ye)),Oe(te.slice(Ye+1)))},[]),ve=a.useCallback(()=>{const te={};if(u.trim()||(te.name="Name is required"),oe==="project"&&!r&&(te.scope="Project-specific entries require an active project."),f==="cron"&&v==="custom"&&(g.trim()?jT(g)||(te.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):te.cronExpression="Cron expression is required"),f==="webhook"&&!y.trim()&&(te.webhookPath="Webhook path is required"),f==="api"&&!N.trim()&&(te.endpoint="API endpoint is required"),F==="simple")K==="command"&&!E.trim()&&(te.command="Command is required"),K==="ai-prompt"&&!le.trim()&&(te.prompt="Prompt is required"),K==="create-task"&&!Q.trim()&&(te.taskDescription="Task description is required"),(ie.trim()&&!Re.trim()||!ie.trim()&&Re.trim())&&(te.model="Both model provider and model ID must be set, or both must be empty");else{P.length===0&&(te.steps="At least one step is required"),O&&(te.stepsEditing="Please save or cancel all step edits before saving the routine");const Ye=[];P.forEach((mt,ht)=>{mt.name?.trim()||Ye.push(`Step ${ht+1}: Name is required`),mt.type==="command"&&!mt.command?.trim()&&Ye.push(`Step ${ht+1}: Command is required`),mt.type==="ai-prompt"&&!mt.prompt?.trim()&&Ye.push(`Step ${ht+1}: Prompt is required`),mt.type==="create-task"&&!mt.taskDescription?.trim()&&Ye.push(`Step ${ht+1}: Task description is required`)}),Ye.length>0&&(te.steps=Ye.join("; "))}return Ne<1e3&&(te.timeoutMs="Timeout must be at least 1 second (1000ms)"),Ae(te),Object.keys(te).length===0},[u,f,g,v,y,N,oe,r,F,K,E,le,Q,ie,Re,P,O,Ne]),ce=a.useCallback(async te=>{if(te.preventDefault(),!!ve()){pe(!0);try{let Ye=e?.scope??oe??(r?"project":"global");Ye==="project"&&!r&&(Ye="global");const mt=kT(f,g,y,S,N);let ht,xt;F==="simple"?K==="command"?ht=E.trim()||void 0:K==="ai-prompt"?xt=[{id:jh(),type:"ai-prompt",name:u.trim(),prompt:le.trim(),modelProvider:ie.trim()||void 0,modelId:Re.trim()||void 0}]:xt=[{id:jh(),type:"create-task",name:u.trim(),taskTitle:L.trim()||void 0,taskDescription:Q.trim(),taskColumn:de,modelProvider:ie.trim()||void 0,modelId:Re.trim()||void 0}]:xt=P;const St={name:u.trim(),agentId:e?.agentId??"",description:m.trim()||void 0,trigger:mt,command:ht,steps:xt,timeoutMs:Ne,executionPolicy:C,catchUpPolicy:M,enabled:U,scope:Ye};await n(St)}finally{_e.current&&pe(!1)}}},[ve,n,u,m,f,g,y,S,N,F,K,E,le,ie,Re,L,Q,de,P,Ne,C,M,U,oe,r,e?.scope,e?.agentId]),Ie="routine-name-error",he="routine-cron-error",Me="routine-webhook-error",Je="routine-endpoint-error",$e="routine-command-error",ft="routine-prompt-error",J="routine-task-description-error",re="routine-model-error",ye="routine-timeout-error",at=a.useCallback(te=>{x(te),te!=="custom"&&b(vg[te])},[]);return t.jsxs("form",{className:"routine-form",onSubmit:ce,noValidate:!0,children:[t.jsx("h4",{className:"settings-section-heading",children:l?"Edit Routine":"New Routine"}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-name",children:"Name"}),t.jsx("input",{id:"routine-name",type:"text",placeholder:"e.g. Daily standup reminder",value:u,onChange:te=>d(te.target.value),"aria-invalid":!!X.name,"aria-describedby":X.name?Ie:void 0}),X.name&&t.jsx("small",{id:Ie,className:"field-error",children:X.name})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-description",children:"Description (optional)"}),t.jsx("textarea",{id:"routine-description",placeholder:"What does this routine do?",value:m,onChange:te=>h(te.target.value),rows:2})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Scope"}),t.jsxs("div",{className:"routine-scope-toggle",role:"radiogroup","aria-label":"Routine scope",children:[t.jsxs("button",{type:"button",className:`routine-scope-btn${oe==="global"?" active":""}`,onClick:()=>{je("global"),o?.("global")},role:"radio","aria-checked":oe==="global"?"true":"false",disabled:!!e?.scope,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:"Global scope",children:[t.jsx(Vo,{size:12}),"Global"]}),t.jsxs("button",{type:"button",className:`routine-scope-btn${oe==="project"?" active":""}`,onClick:()=>{je("project"),o?.("project")},role:"radio","aria-checked":oe==="project"?"true":"false",disabled:!!e?.scope||!r,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:r?"Project scope":"Select a project to enable project scope",children:[t.jsx(Qn,{size:12}),"Project"]})]}),t.jsx("small",{children:!r&&!e?.scope?"No active project. Routines will be created at global scope.":oe==="project"&&r?"This routine will be scoped to the current project.":"This routine will be created at global scope."}),X.scope&&t.jsx("small",{className:"field-error",children:X.scope})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Trigger Type"}),t.jsxs("div",{className:"routine-trigger-type-selector",role:"radiogroup","aria-label":"Trigger type",children:[t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="cron"?" active":""}`,onClick:()=>p("cron"),role:"radio","aria-checked":f==="cron",children:[t.jsx(sp,{size:14}),"Cron"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="webhook"?" active":""}`,onClick:()=>p("webhook"),role:"radio","aria-checked":f==="webhook",children:[t.jsx(pp,{size:14}),"Webhook"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="api"?" active":""}`,onClick:()=>p("api"),role:"radio","aria-checked":f==="api",children:[t.jsx(ip,{size:14}),"API"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="manual"?" active":""}`,onClick:()=>p("manual"),role:"radio","aria-checked":f==="manual",children:[t.jsx(Yn,{size:14}),"Manual"]})]})]}),f==="cron"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-frequency",children:"Frequency"}),t.jsx("select",{id:"routine-frequency",value:v,onChange:te=>at(te.target.value),children:Object.entries(vT).map(([te,Ye])=>t.jsx("option",{value:te,children:Ye},te))}),t.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),t.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:g,onChange:te=>b(te.target.value),disabled:v!=="custom","aria-invalid":!!X.cronExpression,"aria-describedby":X.cronExpression?he:void 0}),X.cronExpression?t.jsx("small",{id:he,className:"field-error",children:X.cronExpression}):t.jsx("small",{children:v==="custom"?t.jsxs(t.Fragment,{children:["min hour day month weekday — ",t.jsx("a",{href:"https://crontab.guru",target:"_blank",rel:"noopener noreferrer",children:"crontab.guru"})]}):`Auto-filled from preset: ${g}`})]}),f==="webhook"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-path",children:"Webhook Path"}),t.jsx("input",{id:"routine-webhook-path",type:"text",placeholder:"/trigger/my-routine",value:y,onChange:te=>k(te.target.value),"aria-invalid":!!X.webhookPath,"aria-describedby":X.webhookPath?Me:void 0}),X.webhookPath?t.jsx("small",{id:Me,className:"field-error",children:X.webhookPath}):t.jsx("small",{children:"URL path for the webhook endpoint"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-secret",children:"Webhook Secret (optional)"}),t.jsx("input",{id:"routine-webhook-secret",type:"password",placeholder:"Optional — leave empty for unauthenticated webhooks",value:S,onChange:te=>_(te.target.value)}),t.jsx("small",{children:"HMAC secret for signature verification. Leave empty for unauthenticated webhooks."})]})]}),f==="api"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-endpoint",children:"API Endpoint"}),t.jsx("input",{id:"routine-endpoint",type:"text",placeholder:"/api/routine/my-routine",value:N,onChange:te=>A(te.target.value),"aria-invalid":!!X.endpoint,"aria-describedby":X.endpoint?Je:void 0}),X.endpoint?t.jsx("small",{id:Je,className:"field-error",children:X.endpoint}):t.jsx("small",{children:"API endpoint path that triggers this routine"})]}),f==="manual"&&t.jsx("div",{className:"form-group",children:t.jsx("small",{className:"routine-trigger-info",children:"This routine will be triggered manually via the dashboard or API."})}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Action Mode"}),t.jsxs("div",{className:"schedule-mode-toggle",role:"radiogroup","aria-label":"Action mode",children:[t.jsx("button",{type:"button",className:`schedule-mode-btn${F==="simple"?" active":""}`,onClick:()=>V("simple"),role:"radio","aria-checked":F==="simple",children:"Simple"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${F==="advanced"?" active":""}`,onClick:()=>V("advanced"),role:"radio","aria-checked":F==="advanced",children:"Multi-Step"})]}),t.jsx("small",{children:F==="simple"?"Run one command, prompt, or task creation action":"Run multiple actions sequentially"})]}),F==="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${K==="command"?" active":""}`,onClick:()=>ee("command"),role:"radio","aria-checked":K==="command",children:"Command"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${K==="ai-prompt"?" active":""}`,onClick:()=>ee("ai-prompt"),role:"radio","aria-checked":K==="ai-prompt",children:"AI Prompt"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${K==="create-task"?" active":""}`,onClick:()=>ee("create-task"),role:"radio","aria-checked":K==="create-task",children:"Create Task"})]})]}),K==="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:E,onChange:te=>$(te.target.value),"aria-invalid":!!X.command,"aria-describedby":X.command?$e:void 0}),X.command?t.jsx("small",{id:$e,className:"field-error",children:X.command}):t.jsx("small",{children:"Shell command to execute."})]}):K==="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:te=>we(te.target.value),rows:3,"aria-invalid":!!X.prompt,"aria-describedby":X.prompt?ft:void 0}),X.prompt?t.jsx("small",{id:ft,className:"field-error",children:X.prompt}):t.jsx("small",{children:"AI prompt to execute."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-model",children:"Model (optional)"}),t.jsx(Xn,{id:"routine-model",label:"Model",models:nt,value:Fe,onChange:it,placeholder:"Use default",disabled:Ze}),He&&t.jsx("small",{className:"field-error",children:He}),X.model&&t.jsx("small",{id:re,className:"field-error",children:X.model})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-title",children:"Task Title (optional)"}),t.jsx("input",{id:"routine-task-title",type:"text",placeholder:"e.g. Review weekly dependencies",value:L,onChange:te=>ne(te.target.value)})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-description",children:"Task Description"}),t.jsx("textarea",{id:"routine-task-description",placeholder:"e.g. Check npm dependencies for security vulnerabilities",value:Q,onChange:te=>be(te.target.value),rows:4,"aria-invalid":!!X.taskDescription,"aria-describedby":X.taskDescription?J:void 0}),X.taskDescription?t.jsx("small",{id:J,className:"field-error",children:X.taskDescription}):t.jsx("small",{children:"Describes the task that will be created."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-column",children:"Target Column"}),t.jsxs("select",{id:"routine-task-column",value:de,onChange:te=>me(te.target.value),children:[t.jsx("option",{value:"triage",children:"Triage"}),t.jsx("option",{value:"todo",children:"To Do"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-model",children:"Executor Model (optional)"}),t.jsx(Xn,{id:"routine-task-model",label:"Executor Model",models:nt,value:Fe,onChange:it,placeholder:"Use default",disabled:Ze}),He&&t.jsx("small",{className:"field-error",children:He}),X.model&&t.jsx("small",{id:re,className:"field-error",children:X.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(xT,{steps:P,onChange:w,onEditingChange:Z}),X.steps&&t.jsx("small",{className:"field-error",children:X.steps}),X.stepsEditing&&t.jsx("small",{className:"field-error",children:X.stepsEditing})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-timeout",children:"Timeout (ms)"}),t.jsx("input",{id:"routine-timeout",type:"number",min:1e3,step:1e3,value:Ne,onChange:te=>se(Number(te.target.value)),"aria-invalid":!!X.timeoutMs,"aria-describedby":X.timeoutMs?ye:void 0}),X.timeoutMs?t.jsx("small",{id:ye,className:"field-error",children:X.timeoutMs}):t.jsx("small",{children:"Maximum execution time in milliseconds."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-execution-policy",children:"Execution Policy"}),t.jsx("select",{id:"routine-execution-policy",value:C,onChange:te=>z(te.target.value),children:NT.map(te=>t.jsx("option",{value:te.value,children:te.label},te.value))}),t.jsx("small",{children:"How to handle concurrent executions of this routine"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-catchup-policy",children:"Catch-up Policy"}),t.jsx("select",{id:"routine-catchup-policy",value:M,onChange:te=>T(te.target.value),children:ST.map(te=>t.jsx("option",{value:te.value,children:te.label},te.value))}),t.jsx("small",{children:"What to do when a scheduled run is missed"})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:"routine-enabled",className:"checkbox-label",children:[t.jsx("input",{id:"routine-enabled",type:"checkbox",checked:U,onChange:te=>q(te.target.checked)}),"Enabled"]}),t.jsx("small",{children:"When disabled, the routine will not run automatically"})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,disabled:Te,children:"Cancel"}),t.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:Te,children:Te?"Saving…":l?"Save Changes":"Create Routine"})]})]})}const CT=3e4;function ET({onClose:e,addToast:n,projectId:s}){const[i,r]=a.useState(()=>s?"project":"global"),[o,l]=a.useState([]),[c,u]=a.useState("list"),[d,m]=a.useState(),[h,f]=a.useState(null),[p,g]=a.useState({}),b=a.useRef(null);ci(b,!0,"fusion:automation-modal-size");const v=a.useMemo(()=>({scope:i,projectId:i==="project"?s:void 0}),[i,s]),x=a.useCallback(async()=>{try{const D=await Fj(v);l(D),g(R=>{const F={...R};for(const V of D){const K=F[V.id];if(!K||!V.lastRunResult)continue;const ee=V.lastRunResult;ee.success===K.success&&(ee.output||"")===K.output&&(ee.error||"")===(K.error||"")&&delete F[V.id]}return F})}catch(D){n(ke(D)||"Failed to load routines","error")}},[n,v]);a.useEffect(()=>{x()},[x]),a.useEffect(()=>{const D=setInterval(()=>{x()},CT);return()=>clearInterval(D)},[x]),a.useEffect(()=>{const D=R=>{R.key==="Escape"&&(c!=="list"?(u("list"),m(void 0)):e())};return document.addEventListener("keydown",D),()=>document.removeEventListener("keydown",D)},[e,c]);const y=_i(e),k=a.useCallback(async D=>{try{await Oj(D,v),n("Routine created","success"),u("list"),await x()}catch(R){n(ke(R)||"Failed to create routine","error")}},[n,x,v]),S=a.useCallback(D=>{m(D),u("edit")},[]),_=a.useCallback(async D=>{if(d)try{await iu(d.id,D,v),n("Routine updated","success"),u("list"),m(void 0),await x()}catch(R){n(ke(R)||"Failed to update routine","error")}},[d,n,x,v]),N=a.useCallback(async D=>{try{await Uj(D.id,v),n(`Deleted "${D.name}"`,"success"),await x()}catch(R){n(ke(R)||"Failed to delete routine","error")}},[n,x,v]),A=a.useCallback(async D=>{f(D.id);try{const{result:R}=await Bj(D.id,v);g(F=>({...F,[D.id]:{output:R.output||"",error:R.error,success:R.success}})),R.success?n(`"${D.name}" completed successfully`,"success"):n(`"${D.name}" failed: ${R.error||"Unknown error"}`,"error"),await x()}catch(R){n(ke(R)||"Failed to run routine","error")}finally{f(null)}},[n,x,v]),C=a.useCallback(async D=>{try{await iu(D.id,{enabled:!D.enabled},v),n(`"${D.name}" ${D.enabled?"disabled":"enabled"}`,"success"),await x()}catch(R){n(ke(R)||"Failed to toggle routine","error")}},[n,x,v]),z=a.useCallback(()=>{u("list"),m(void 0)},[]);a.useEffect(()=>{c!=="list"&&g({})},[c]);const M=a.useCallback(D=>{r(D),u("list"),m(void 0),g({})},[]),T=()=>c==="create"?t.jsx(kh,{onSubmit:k,onCancel:z,scope:i,projectId:s}):c==="edit"&&d?t.jsx(kh,{routine:d,onSubmit:_,onCancel:z,scope:i,projectId:s}):o.length===0?t.jsxs("div",{className:"routine-empty-state",children:[t.jsx(Yn,{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(ln,{size:14}),"Create your first automation"]})]}):t.jsx("div",{className:"routine-list",children:o.map(D=>t.jsx(pT,{routine:D,onEdit:S,onDelete:N,onRun:A,onToggle:C,running:h===D.id,lastRunOutput:p[D.id]??null},D.id))}),U=()=>T(),q=c==="list"&&o.length>0;return t.jsx("div",{className:"modal-overlay open",...y,children:t.jsxs("div",{ref:b,className:"modal modal-lg automation-modal",role:"dialog","aria-modal":"true","aria-labelledby":"schedules-modal-title",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(Yn,{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(Kt,{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:()=>M("global"),"aria-pressed":i==="global",title:"Global (user-level) automations",children:[t.jsx(Vo,{size:14}),"Global"]}),t.jsxs("button",{type:"button",className:`scope-btn${i==="project"?" active":""}`,onClick:()=>M("project"),"aria-pressed":i==="project",title:"Project-scoped automations",children:[t.jsx(Qn,{size:14}),"Project"]})]}),t.jsxs("span",{className:"scheduling-count",children:[t.jsx(Yn,{size:14}),o.length," automation",o.length===1?"":"s"]})]}),t.jsx("div",{className:"scheduling-toolbar-right",children:q&&t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>u("create"),"aria-label":"Create new automation",children:[t.jsx(ln,{size:14}),"New Automation"]})})]}),t.jsx("div",{className:"schedule-modal-content",id:"scheduled-tasks-content",children:U()})]})})}const _T=3e4,Zc=new Map,uc=new Map;function wh(e){return e??"default"}function Nh(e){const n=Zc.get(e);return n?Date.now()>=n.expiresAt?(Zc.delete(e),null):n:null}function MT(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 AT(e){const n=uc.get(e);if(n)return n;const s=wr().then(({providers:i,ghCli:r})=>{const l={...MT(i,r),ghCli:r,expiresAt:Date.now()+_T};return Zc.set(e,l),l}).finally(()=>{uc.delete(e)});return uc.set(e,s),s}function yg(e){const n=wh(e),s=Nh(n),[i,r]=a.useState(s?.hasAiProvider??!1),[o,l]=a.useState(s?.hasGithub??!1),[,c]=a.useState(s?.ghCli),[u,d]=a.useState(s==null),m=a.useRef(!!s);return a.useEffect(()=>{let h=!1;const f=wh(e),p=Nh(f);if(p)return r(p.hasAiProvider),l(p.hasGithub),c(p.ghCli),d(!1),m.current=!0,()=>{h=!0};m.current=!1;async function g(){!m.current&&d(!0);try{const v=await AT(f);if(h)return;r(v.hasAiProvider),l(v.hasGithub),c(v.ghCli)}catch{}finally{h||(m.current=!0,d(!1))}}return g(),()=>{h=!0}},[e]),a.useMemo(()=>({hasAiProvider:i,hasGithub:o,loading:u,hasWarnings:!i||!o}),[i,o,u])}function jg({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(Kt,{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 RT({isOpen:e,onClose:n,projectId:s,tasks:i,onCreateTask:r,addToast:o,onPlanningMode:l,onSubtaskBreakdown:c}){const{confirm:u}=Ks(),[d,m]=a.useState(""),[h,f]=a.useState([]),[p,g]=a.useState([]),[b,v]=a.useState(!1),[x,y]=a.useState(""),[k,S]=a.useState(""),[_,N]=a.useState(""),[A,C]=a.useState(""),[z,M]=a.useState(""),[T,U]=a.useState("default"),[q,D]=a.useState(!1),[R,F]=a.useState([]),[V,K]=a.useState(!1),[ee,E]=a.useState(void 0),[$,P]=a.useState(_s),[w,O]=a.useState(void 0),[Z,Ne]=a.useState(null),[se,le]=a.useState([]),[we,L]=a.useState(!1),[ne,Q]=a.useState(!1),be=a.useRef(null),[de,me]=a.useState(!1),[ie,xe]=a.useState(""),Re=a.useRef(null),{hasAiProvider:Oe,hasGithub:nt,loading:et}=yg(s),{nodes:Ze}=tl(),rt=a.useCallback(ve=>{K(!0),F(ve)},[]),He=a.useCallback(()=>{K(!1)},[]),Ge=a.useCallback(async()=>{if(se.length>0){L(!0);return}Q(!0);try{const ve=await Ra(void 0,s);le(ve),L(!0)}catch(ve){const ce=ke(ve);o(ce?`Failed to load agents: ${ce}`:"Failed to load agents","error"),L(!1)}finally{Q(!1)}},[se.length,s,o]);a.useEffect(()=>{if(!we)return;const ve=ce=>{be.current&&!be.current.contains(ce.target)&&L(!1)};return document.addEventListener("mousedown",ve),()=>document.removeEventListener("mousedown",ve)},[we]),a.useEffect(()=>{if(!de)return;const ve=ce=>{Re.current&&!Re.current.contains(ce.target)&&(me(!1),xe(""))};return document.addEventListener("mousedown",ve),()=>document.removeEventListener("mousedown",ve)},[de]);const oe=i.filter(ve=>!h.includes(ve.id)).sort((ve,ce)=>{const Ie=ce.createdAt.localeCompare(ve.createdAt);if(Ie!==0)return Ie;const he=parseInt(ve.id.slice(ve.id.lastIndexOf("-")+1),10)||0;return(parseInt(ce.id.slice(ce.id.lastIndexOf("-")+1),10)||0)-he}),je=ie?oe.filter(ve=>ve.id.toLowerCase().includes(ie.toLowerCase())||ve.title&&ve.title.toLowerCase().includes(ie.toLowerCase())||ve.description&&ve.description.toLowerCase().includes(ie.toLowerCase())):oe,X=(ve,ce)=>ve.length>ce?ve.slice(0,ce)+"…":ve;a.useEffect(()=>{const ve=d.trim()!==""||h.length>0||p.length>0||x!==""||k!==""||_!==""||A!==""||R.length>0||Z!==null||ee!==void 0||$!==_s||w!==void 0;D(ve)},[d,h,p,x,k,_,A,R,Z,ee,$,w]);const Ae=a.useCallback(async()=>{q&&!await u({title:"Discard Changes",message:"You have unsaved changes. Discard them?",danger:!0})||(p.forEach(ve=>URL.revokeObjectURL(ve.previewUrl)),g([]),m(""),f([]),y(""),S(""),N(""),C(""),M(""),U("default"),F([]),K(!1),Ne(null),L(!1),E(void 0),P(_s),O(void 0),D(!1),n())},[q,n,p,u]),Te=a.useCallback(async()=>{const ve=d.trim();if(!(!ve||b)){v(!0);try{const ce=x.indexOf("/"),Ie=k.indexOf("/"),he=_.indexOf("/"),Me=await r({title:void 0,description:ve,column:"triage",dependencies:h.length?h:void 0,enabledWorkflowSteps:V?R.length>0?R:[]:void 0,...Z?{assignedAgentId:Z}:{},modelPresetId:T==="preset"&&z||void 0,modelProvider:x&&ce!==-1?x.slice(0,ce):void 0,modelId:x&&ce!==-1?x.slice(ce+1):void 0,validatorModelProvider:k&&Ie!==-1?k.slice(0,Ie):void 0,validatorModelId:k&&Ie!==-1?k.slice(Ie+1):void 0,planningModelProvider:_&&he!==-1?_.slice(0,he):void 0,planningModelId:_&&he!==-1?_.slice(he+1):void 0,thinkingLevel:A!==""?A:void 0,reviewLevel:ee,priority:$,nodeId:w});if(p.length>0){const Je=[];for(const $e of p)try{await kr(Me.id,$e.file,s)}catch{Je.push($e.file.name)}Je.length>0&&o(`Failed to upload: ${Je.join(", ")}`,"error")}p.forEach(Je=>URL.revokeObjectURL(Je.previewUrl)),g([]),m(""),f([]),y(""),S(""),N(""),C(""),M(""),U("default"),F([]),K(!1),Ne(null),L(!1),E(void 0),P(_s),O(void 0),o(`Created ${Me.id}`,"success"),n()}catch(ce){o(ke(ce)||"Failed to create task","error")}finally{v(!1)}}},[d,h,p,x,k,_,A,b,r,o,n,s,T,z,R,V,Z,ee,$,w]),pe=a.useCallback(ve=>{ve.key==="Escape"&&(ve.preventDefault(),Ae())},[Ae]),Fe=(Z?se.find(ve=>ve.id===Z):void 0)?.name??Z,it=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:Re,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>me(ve=>!ve),disabled:b,"data-testid":"dep-trigger",children:h.length>0?`${h.length} selected`:"Add dependencies"}),de&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:ie,onChange:ve=>xe(ve.target.value),onClick:ve=>ve.stopPropagation()}),je.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):je.map(ve=>t.jsxs("div",{className:`dep-dropdown-item${h.includes(ve.id)?" selected":""}`,onClick:()=>{f(h.includes(ve.id)?h.filter(ce=>ce!==ve.id):[...h,ve.id]),me(!1),xe("")},onMouseDown:ce=>ce.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:ve.id}),t.jsx("span",{className:"dep-dropdown-title",children:X(ve.title||ve.description||ve.id,30)})]},ve.id))]})]}),h.length>0&&t.jsx("div",{className:"selected-deps",children:h.map(ve=>t.jsxs("span",{className:"dep-chip",children:[ve,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>f(h.filter(ce=>ce!==ve)),disabled:b,children:"×"})]},ve))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Assign Agent"}),t.jsxs("div",{className:"agent-trigger-wrap",ref:be,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{we?L(!1):Ge()},disabled:b,"data-testid":"new-task-agent-button",children:[t.jsx(Cn,{size:12,style:{verticalAlign:"middle"}}),Fe?` ${Fe}`:" Assign agent"]}),we&&t.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:ve=>ve.preventDefault(),children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),ne&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!ne&&se.filter(ve=>ve.state!=="terminated").map(ve=>t.jsxs("div",{className:`dep-dropdown-item${Z===ve.id?" selected":""}`,onMouseDown:ce=>ce.preventDefault(),onClick:()=>{Ne(ve.id===Z?null:ve.id),L(!1)},"data-testid":`agent-option-${ve.id}`,children:[t.jsx(Cn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:ve.role}),t.jsx("span",{className:"dep-dropdown-title",children:ve.name})]},ve.id)),!ne&&se.filter(ve=>ve.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),Z&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:ve=>ve.preventDefault(),onClick:()=>{Ne(null),L(!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:ve=>ve.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:"New Task"}),t.jsx("button",{className:"modal-close",onClick:Ae,disabled:b,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!et&&t.jsx(jg,{hasAiProvider:Oe,hasGithub:nt}),t.jsx(ug,{mode:"create",description:d,onDescriptionChange:m,dependencies:h,onDependenciesChange:f,executorModel:x,onExecutorModelChange:y,validatorModel:k,onValidatorModelChange:S,presetMode:T,onPresetModeChange:U,selectedPresetId:z,onSelectedPresetIdChange:M,selectedWorkflowSteps:R,onWorkflowStepsChange:rt,onDefaultOnApplied:He,pendingImages:p,onImagesChange:g,tasks:i,projectId:s,disabled:b,addToast:o,isActive:e,onPlanningMode:l,onSubtaskBreakdown:c,onClose:Ae,planningModel:_,onPlanningModelChange:N,thinkingLevel:A,onThinkingLevelChange:C,reviewLevel:ee,onReviewLevelChange:E,priority:$,onPriorityChange:P,nodeId:w,onNodeIdChange:O,nodeOptions:Ze,renderBelowPrimary:it,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:Ae,disabled:b,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Te,disabled:!d.trim()||b,children:b?"Creating...":"Create Task"})]})]})}):null}function Bs(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 Sh(e,n){return!Number.isFinite(e)||!Number.isFinite(n)||n<=0?"—":`${(e/n*100).toFixed(1)}%`}function TT(e,n){if(n<=0)return"normal";const s=e/n;return s>=.85?"critical":s>=.65?"warning":"normal"}function PT(e,n){if(n<=0)return"normal";const s=e/n;return s>=.5?"critical":s>=.25?"warning":"normal"}function IT(e,n){if(n<=0)return"normal";const s=e/n;return s>=.9?"critical":s>=.75?"warning":"normal"}function mc(e){return e==="critical"?"system-stats-modal__value--critical":e==="warning"?"system-stats-modal__value--warning":""}function $T(e){if(!e)return"Not yet";const n=new Date(e);return Number.isNaN(n.getTime())?"Not yet":n.toLocaleString()}function DT({isOpen:e,onClose:n,projectId:s}){const[i,r]=a.useState(null),[o,l]=a.useState(!1),[c,u]=a.useState(null),[d,m]=a.useState(!0),[h,f]=a.useState(90),[p,g]=a.useState(!1),[b,v]=a.useState(!1),[x,y]=a.useState(null),[k,S]=a.useState(null),[_,N]=a.useState(null),A=a.useCallback(async O=>{l(!0);try{const Z=await pk(s);r(Z),u(null),N(Date.now()),O?.preserveKillResult||y(null)}catch(Z){u(Z instanceof Error?Z.message:"Failed to load system stats")}finally{l(!1)}},[s]);a.useEffect(()=>{if(!e)return;A();const O=window.setInterval(()=>{A()},5e3);return()=>{window.clearInterval(O)}},[e,A]),a.useEffect(()=>{if(!e)return;(async()=>{try{const Z=await Ji();m(Z.vitestAutoKillEnabled??!0),f(Z.vitestKillThresholdPct??90),S(null)}catch(Z){S(Z instanceof Error?Z.message:"Failed to load vitest settings")}})()},[e]),a.useEffect(()=>{if(!e)return;const O=Z=>{Z.key==="Escape"&&n()};return document.addEventListener("keydown",O),()=>document.removeEventListener("keydown",O)},[e,n]);const C=a.useMemo(()=>{if(!i)return[];const O=i.systemStats,Z=mc(TT(O.heapUsed,O.heapLimit)),Ne=mc(PT(O.rss,O.systemTotalMem));return[{label:"RSS",value:Bs(O.rss),detail:Sh(O.rss,O.systemTotalMem),className:Ne},{label:"Heap Used",value:Bs(O.heapUsed),detail:`of ${Bs(O.heapTotal)}`,className:Z},{label:"Heap Limit",value:Bs(O.heapLimit),detail:"V8 limit"},{label:"External",value:Bs(O.external)},{label:"Array Buffers",value:Bs(O.arrayBuffers)}]},[i]),z=a.useCallback(async O=>{m(O);try{await gn({vitestAutoKillEnabled:O}),S(null)}catch(Z){S(Z instanceof Error?Z.message:"Failed to save vitest settings")}},[]),M=a.useCallback(async O=>{const Z=Math.min(99,Math.max(50,Number.isFinite(O)?Math.round(O):90));f(Z);try{await gn({vitestKillThresholdPct:Z}),S(null)}catch(Ne){S(Ne instanceof Error?Ne.message:"Failed to save vitest settings")}},[]),T=a.useCallback(async()=>{if(!p){if(!b){v(!0);return}g(!0);try{const O=await fk(s);y(O),v(!1),await A({preserveKillResult:!0})}catch(O){u(O instanceof Error?O.message:"Failed to kill vitest processes")}finally{g(!1)}}},[b,p,A,s]);if(!e)return null;const U=i?.systemStats,q=o&&!!i,D=_?`Updated ${new Date(_).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`:"Waiting for first update",R=i?.taskStats,F=U?U.systemTotalMem-U.systemFreeMem:0,V=U?IT(F,U.systemTotalMem):"normal",K=U?mc(V):"",ee=U&&Number.isFinite(U.systemTotalMem)&&U.systemTotalMem>0?Math.max(0,Math.min(100,F/U.systemTotalMem*100)):0,E=U?`System memory used: ${ee.toFixed(1)}% (${Bs(F)} of ${Bs(U.systemTotalMem)})`:"System memory usage unavailable",$=i?.vitestProcessCount,P=x?x.killed>0?"system-stats-modal__kill-result system-stats-modal__kill-result--success":"system-stats-modal__kill-result system-stats-modal__kill-result--error":"",w=$T(i?.vitestLastAutoKillAt);return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"system-stats-modal-title",onClick:O=>{O.target===O.currentTarget&&n()},"data-testid":"system-stats-modal-overlay",children:t.jsxs("div",{className:"modal modal-lg system-stats-modal","data-testid":"system-stats-modal",children:[t.jsxs("div",{className:"modal-header system-stats-modal__header",children:[t.jsxs("h2",{id:"system-stats-modal-title",className:"system-stats-modal__title",children:[t.jsx(vr,{}),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:D})]}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>void A(),title:"Refresh","aria-label":"Refresh system stats",children:t.jsx(Ln,{size:16,className:q?"system-stats-modal__refresh--spinning":void 0})}),t.jsx("button",{type:"button",className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Kt,{})})]})]}),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(O=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:O.label}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${O.className}`.trim(),children:O.value}),O.detail?t.jsx("span",{className:"system-stats-modal__detail",children:O.detail}):null]})]},O.label))})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"CPU and load stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"CPU & Load"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Load Avg"}),t.jsx("dd",{children:U?.loadAvg.map(O=>O.toFixed(2)).join(" ")??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Cores"}),t.jsx("dd",{children:U?.cpuCount??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Platform"}),t.jsx("dd",{children:U?.platform??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Node"}),t.jsx("dd",{children:U?.nodeVersion??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"PID"}),t.jsx("dd",{children:U?.pid??"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"System memory stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"System"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row system-stats-modal__row--memory-used",children:[t.jsx("dt",{children:"Memory Used"}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${K}`.trim(),children:U?Bs(F):"—"}),t.jsx("span",{className:"system-stats-modal__detail",children:U?`${Sh(F,U.systemTotalMem)} of ${Bs(U.systemTotalMem)}`:""})]}),t.jsx("div",{className:"system-stats-modal__memory-progress-wrapper",children:t.jsx("div",{className:`system-stats-modal__memory-progress-track system-stats-modal__memory-progress-track--${V}`,role:"progressbar","aria-valuenow":Math.round(ee),"aria-valuemin":0,"aria-valuemax":100,"aria-label":E,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${V}`,style:{width:`${ee}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Memory Free"}),t.jsx("dd",{children:U?Bs(U.systemFreeMem):"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Task stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Tasks"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Total"}),t.jsx("dd",{children:R?.total??0})]}),Object.entries(R?.byColumn??{}).map(([O,Z])=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:O}),t.jsx("dd",{children:Z})]},O))]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Agent stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Agents"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"idle"}),t.jsx("dd",{children:R?.agents.idle??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"active"}),t.jsx("dd",{children:R?.agents.active??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"running"}),t.jsx("dd",{children:R?.agents.running??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"error"}),t.jsx("dd",{children:R?.agents.error??0})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Vitest controls",children:[t.jsxs("h3",{className:"system-stats-modal__section-title system-stats-modal__section-title--with-icon",children:[t.jsx(av,{}),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:$??"—"})]})}),t.jsxs("div",{className:"system-stats-modal__vitest-controls",children:[t.jsx("div",{className:"system-stats-modal__kill-row",children:t.jsxs("button",{type:"button",className:"btn btn-danger",onClick:()=>void T(),disabled:p||$===0,children:[t.jsx(cv,{}),t.jsx("span",{children:b?"Confirm Kill?":"Kill Vitest Processes"})]})}),t.jsxs("label",{className:"system-stats-modal__toggle-row",children:[t.jsx("input",{type:"checkbox",checked:d,onChange:O=>{z(O.target.checked)}}),t.jsx("span",{children:"Auto-kill vitest on memory pressure"})]}),t.jsxs("div",{className:"system-stats-modal__threshold-row",children:[t.jsx("label",{htmlFor:"vitest-threshold-number",children:"Kill threshold (%)"}),t.jsxs("div",{className:"system-stats-modal__threshold-controls",children:[t.jsx("input",{id:"vitest-threshold-range",type:"range",min:50,max:99,value:h,"aria-label":"Kill threshold slider (%)",onChange:O=>{const Z=Number.parseInt(O.target.value,10);M(Number.isNaN(Z)?90:Z)}}),t.jsx("input",{id:"vitest-threshold-number",type:"number",className:"input",min:50,max:99,value:h,"aria-label":"Kill threshold (%)",onChange:O=>{const Z=Number.parseInt(O.target.value,10);M(Number.isNaN(Z)?90:Z)},onBlur:()=>{M(h)}})]})]}),x&&t.jsxs("p",{className:P,children:["Killed ",x.killed," processes"]}),t.jsxs("p",{className:"system-stats-modal__last-kill",children:["Last auto-kill: ",w]}),k&&t.jsx("p",{className:"system-stats-modal__kill-result system-stats-modal__kill-result--error",children:k})]})]})]}),c&&i&&t.jsxs("div",{className:"system-stats-modal__footer-error",children:["Latest refresh failed: ",c]})]})})}const LT=5e3;function zT(e={}){const{projectId:n,type:s,limit:i=50,autoRefresh:r=!0,useCentralFeed:o=!1}=e,[l,c]=a.useState([]),[u,d]=a.useState(!1),[m,h]=a.useState(null),[f,p]=a.useState(!1),g=a.useRef(null),b=a.useRef(void 0),v=a.useCallback(async()=>{try{d(!0),h(null);let k;o?k=await uu({limit:i,projectId:n,type:s}):k=(await au({limit:i,type:s,projectId:n})).map(_=>({..._,projectId:n??"",projectName:""})),c(k),p(k.length===i),k.length>0&&(b.current=k[k.length-1].timestamp)}catch(k){h(k instanceof Error?k.message:"Failed to load activity log")}finally{d(!1)}},[i,n,s,o]),x=a.useCallback(async()=>{if(b.current)try{d(!0);let k;o?k=await uu({limit:i,projectId:n,type:s,since:b.current}):k=(await au({limit:i,type:s,since:b.current,projectId:n})).map(_=>({..._,projectId:n??"",projectName:""})),c(S=>[...S,...k]),p(k.length===i),k.length>0&&(b.current=k[k.length-1].timestamp)}catch(k){h(k instanceof Error?k.message:"Failed to load more entries")}finally{d(!1)}},[i,n,s,o]),y=a.useCallback(()=>{c([]),p(!1),b.current=void 0},[]);return a.useEffect(()=>{v()},[v]),a.useEffect(()=>{if(r)return g.current=setInterval(()=>{v()},LT),()=>{g.current&&(clearInterval(g.current),g.current=null)}},[r,v]),{entries:l,loading:u,error:m,refresh:v,clear:y,hasMore:f,loadMore:x}}const hc={"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"},FT={"task:created":t.jsx(ln,{size:14,className:"activity-icon created"}),"task:moved":t.jsx(Rr,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx(Ln,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(Kt,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx(wn,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(Tr,{size:14,className:"activity-icon failed"}),"settings:updated":t.jsx(hr,{size:14,className:"activity-icon settings"})};function OT(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 UT({isOpen:e,onClose:n,tasks:s,onOpenTaskDetail:i,projectId:r,projects:o=[],onProjectFilterChange:l,currentProject:c}){const[u,d]=a.useState("all"),[m,h]=a.useState(r||"all"),[f,p]=a.useState(!1);a.useEffect(()=>{h(r||"all")},[r]);const g=u==="all"?void 0:u,b=m==="all"?void 0:m,v=!c&&o.length>0,{entries:x,loading:y,error:k,refresh:S,hasMore:_}=zT({projectId:b,type:g,limit:100,autoRefresh:e,useCentralFeed:v}),N=x.map(T=>({id:T.id,timestamp:T.timestamp,type:T.type,taskId:T.taskId,taskTitle:T.taskTitle,details:T.details,metadata:T.metadata,projectId:T.projectId,projectName:T.projectName})),A=async()=>{try{await Hj(),S(),p(!1)}catch{p(!1)}},C=T=>{i&&i(T)},z=T=>{h(T),l?.(T==="all"?void 0:T)};a.useEffect(()=>{if(!e)return;const T=U=>{U.key==="Escape"&&(f?p(!1):n())};return document.addEventListener("keydown",T),()=>document.removeEventListener("keydown",T)},[e,n,f]);const M=u!=="all"||m!=="all";return e?t.jsx("div",{className:"modal-overlay open",onClick:T=>{T.target===T.currentTarget&&n()},role:"dialog","aria-modal":"true","data-testid":"activity-log-modal-overlay",children:t.jsxs("div",{className:"modal modal-lg activity-log-modal","data-testid":"activity-log-modal",children:[t.jsxs("div",{className:"modal-header activity-log-header",children:[t.jsxs("div",{className:"activity-log-title",children:[t.jsx(xr,{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(Qn,{size:14}),t.jsxs("select",{value:m,onChange:T=>z(T.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[t.jsx("option",{value:"all",children:"All Projects"}),o.map(T=>t.jsx("option",{value:T.id,children:T.name},T.id))]})]}),t.jsxs("div",{className:"activity-log-filter",children:[t.jsx(Eo,{size:14}),t.jsxs("select",{value:u,onChange:T=>d(T.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:"All Events"}),Object.entries(hc).map(([T,U])=>t.jsx("option",{value:T,children:U},T))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>S(),title:"Refresh","data-testid":"activity-refresh",children:y?t.jsx(lt,{size:14,className:"spin"}):t.jsx(Ln,{size:14})}),N.length>0&&t.jsx("button",{className:"activity-log-clear",onClick:()=>p(!0),title:"Clear Log","data-testid":"activity-clear",children:t.jsx(on,{size:14})})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",title:"Close","data-testid":"activity-close",children:"×"})]}),M&&t.jsxs("div",{className:"activity-log-active-filters",children:[t.jsx("span",{className:"activity-log-filter-label",children:"Active filters:"}),m!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Project: ",o.find(T=>T.id===m)?.name||m]}),u!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",hc[u]]}),t.jsx("button",{className:"activity-log-clear-filters",onClick:()=>{d("all"),h("all"),l?.(void 0)},children:"Clear all"})]}),t.jsxs("div",{className:"activity-log-content","data-testid":"activity-log-content",children:[k&&t.jsxs("div",{className:"activity-log-error","data-testid":"activity-error",children:[t.jsx(ps,{size:16}),t.jsx("span",{children:k})]}),N.length===0&&!y&&!k&&t.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[t.jsx(xr,{size:48,className:"activity-log-empty-icon"}),t.jsx("p",{children:M?"No activity matches the current filters":"No activity recorded yet"}),M&&t.jsx("button",{className:"btn btn-secondary",onClick:()=>{d("all"),h("all"),l?.(void 0)},children:"Clear Filters"})]}),t.jsx("div",{className:"activity-log-list",children:N.map(T=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:FT[T.type]}),t.jsxs("div",{className:"activity-log-entry-content",children:[t.jsxs("div",{className:"activity-log-entry-header",children:[t.jsx("span",{className:"activity-log-entry-type",children:hc[T.type]}),t.jsx("span",{className:"activity-log-entry-time",children:OT(T.timestamp)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[T.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>C(T.taskId),"data-testid":"activity-task-link",children:T.taskId}),T.taskTitle&&t.jsx("span",{className:"activity-log-task-title",children:T.taskTitle}),t.jsx("span",{className:"activity-log-entry-text",children:T.details})]}),T.metadata&&Object.keys(T.metadata).length>0&&t.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof T.metadata.from=="string"&&typeof T.metadata.to=="string"&&t.jsxs("span",{className:"activity-log-metadata-item",children:[T.metadata.from," → ",T.metadata.to]}),typeof T.metadata.merged=="boolean"&&t.jsx("span",{className:`activity-log-metadata-item ${T.metadata.merged?"success":"error"}`,children:T.metadata.merged?"Merged":"Not merged"})]})]})]},T.id))}),_&&!y&&t.jsx("button",{className:"activity-log-load-more",onClick:S,"data-testid":"activity-load-more",children:"Load More"}),y&&N.length>0&&t.jsx("div",{className:"activity-log-loading",children:t.jsx(lt,{size:20,className:"spin"})})]}),f&&t.jsx("div",{className:"activity-log-confirm-overlay",children:t.jsxs("div",{className:"activity-log-confirm-dialog",children:[t.jsx("h3",{children:"Clear Activity Log?"}),t.jsx("p",{children:"This will permanently delete all activity log entries. This action cannot be undone."}),t.jsxs("div",{className:"activity-log-confirm-actions",children:[t.jsx("button",{className:"activity-log-confirm-cancel",onClick:()=>p(!1),children:"Cancel"}),t.jsx("button",{className:"activity-log-confirm-clear",onClick:A,children:"Clear Log"})]})]})})]})}):null}const nr=[{id:"status",label:"Status",icon:up},{id:"changes",label:"Changes",icon:Sc},{id:"commits",label:"Commits",icon:Pr},{id:"branches",label:"Branches",icon:Ws},{id:"worktrees",label:"Worktrees",icon:dx},{id:"stashes",label:"Stashes",icon:Mr},{id:"remotes",label:"Remotes",icon:op}];function Ch({status:e}){switch(e){case"added":case"untracked":return t.jsx(Vb,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(ap,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(Bb,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return t.jsx(Bi,{size:14,className:"gm-file-icon gm-file-renamed"});default:return t.jsx(Kb,{size:14,className:"gm-file-icon"})}}function Eh({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 BT(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 HT({isOpen:e,onClose:n,tasks:s,addToast:i,projectId:r}){const o=Ks(),[l,c]=a.useState("status"),[u,d]=a.useState(!1),[m,h]=a.useState(null),f=a.useRef(null);ci(f,e,"fusion:git-modal-size");const p=_i(n),g=BT(i),[b,v]=a.useState(null),[x,y]=a.useState([]),[k,S]=a.useState(new Set),[_,N]=a.useState(""),[A,C]=a.useState(!1),[z,M]=a.useState(null),[T,U]=a.useState(!1),[q,D]=a.useState(null),[R,F]=a.useState(null),V=a.useRef(0),[K,ee]=a.useState([]),[E,$]=a.useState(null),[P,w]=a.useState(null),[O,Z]=a.useState(!1),[Ne,se]=a.useState(20),[le,we]=a.useState(""),[L,ne]=a.useState([]),[Q,be]=a.useState(""),[de,me]=a.useState(""),[ie,xe]=a.useState(""),[Re,Oe]=a.useState(null),[nt,et]=a.useState([]),[Ze,rt]=a.useState(!1),[He,Ge]=a.useState(null),[oe,je]=a.useState(null),[X,Ae]=a.useState(!1),[Te,pe]=a.useState([]),[_e,Fe]=a.useState([]),[it,ve]=a.useState(""),[ce,Ie]=a.useState(null),[he,Me]=a.useState(null),[Je,$e]=a.useState(null),ft=a.useCallback(async()=>{if(e){d(!0),h(null);try{switch(l){case"status":{const ge=await Us(r);v(ge);break}case"changes":{const[ge,ze]=await Promise.all([Us(r),ia(r)]);v(ge),y(ze),S(new Set),F(null),M(null),D(null);break}case"commits":{const ge=await Gy(Ne,r);ee(ge);break}case"branches":{const[ge,ze]=await Promise.all([Ba(r),Us(r)]);ne(ge),v(ze);break}case"worktrees":{const ge=await Xy(r);pe(ge);break}case"stashes":{const ge=await Zr(r);Fe(ge);break}case"remotes":{const ge=await Us(r);v(ge);break}}}catch(ge){h(ke(ge)||"Failed to fetch git data"),i(ke(ge)||"Failed to fetch git data","error")}finally{d(!1)}}},[l,e,Ne,i,r]);a.useEffect(()=>{e&&ft()},[ft,e]),a.useEffect(()=>{if(!e)return;const ge=ze=>{if(ze.key==="Escape"){n();return}if((ze.key==="ArrowUp"||ze.key==="ArrowDown")&&ze.altKey){ze.preventDefault();const dt=nr.findIndex(j=>j.id===l);ze.key==="ArrowUp"&&dt>0?c(nr[dt-1].id):ze.key==="ArrowDown"&&dt<nr.length-1&&c(nr[dt+1].id)}};return document.addEventListener("keydown",ge),()=>document.removeEventListener("keydown",ge)},[e,n,l]);const J=a.useCallback(async ge=>{try{await eu(ge,r),i(`Staged ${ge.length} file(s)`,"success");const ze=await ia(r);y(ze),S(new Set),F(null),M(null),D(null)}catch(ze){i(ke(ze)||"Failed to stage files","error")}},[i,r]),re=a.useCallback(async ge=>{try{await lj(ge,r),i(`Unstaged ${ge.length} file(s)`,"success");const ze=await ia(r);y(ze),S(new Set),F(null),M(null),D(null)}catch(ze){i(ke(ze)||"Failed to unstage files","error")}},[i,r]),ye=a.useCallback(async ge=>{if(await o.confirm({title:"Discard Changes",message:`Discard changes to ${ge.length} file(s)? This cannot be undone.`,danger:!0}))try{await cj(ge,r),i(`Discarded changes to ${ge.length} file(s)`,"success");const[dt,j]=await Promise.all([ia(r),Us(r)]);y(dt),v(j),S(new Set),F(null),M(null),D(null)}catch(dt){i(ke(dt)||"Failed to discard changes","error")}},[i,r,confirm]),at=a.useCallback(async ge=>{if(ge.preventDefault(),!!_.trim()){C(!0);try{const ze=await tu(_.trim(),r);i(`Committed: ${ze.hash}`,"success"),N("");const[dt,j]=await Promise.all([ia(r),Us(r)]);y(dt),v(j),F(null),M(null),D(null)}catch(ze){i(ke(ze)||"Failed to commit","error")}finally{C(!1)}}},[_,i,r]),te=a.useCallback(async()=>{if(_.trim()){C(!0);try{const ge=x.filter(Y=>!Y.staged).map(Y=>Y.file);ge.length>0&&await eu(ge,r);const ze=await tu(_.trim(),r);i(`Committed: ${ze.hash}`,"success"),N("");const[dt,j]=await Promise.all([ia(r),Us(r)]);y(dt),v(j),F(null),M(null),D(null)}catch(ge){i(ke(ge)||"Failed to commit","error")}finally{C(!1)}}},[_,x,i,r]),Ye=a.useCallback(async(ge,ze)=>{F({file:ge,staged:ze}),U(!0),D(null);const dt=V.current+1;V.current=dt;try{const j=await oj(ge,ze,r);if(V.current!==dt)return;M(j)}catch(j){if(V.current!==dt)return;const Y=ke(j)||"Failed to load file diff";M(null),D(Y),i(Y,"error")}finally{V.current===dt&&U(!1)}},[i,r]),mt=a.useCallback(ge=>{S(ze=>{const dt=new Set(ze);return dt.has(ge)?dt.delete(ge):dt.add(ge),dt})},[]),ht=a.useCallback(async ge=>{if(E===ge){$(null),w(null);return}$(ge),Z(!0);try{const ze=await Ao(ge,r);w(ze)}catch(ze){i(ke(ze)||"Failed to load diff","error"),w(null)}finally{Z(!1)}},[E,i,r]),xt=a.useCallback(()=>{se(ge=>Math.min(ge+20,100))},[]),St=a.useMemo(()=>{if(!le.trim())return K;const ge=le.toLowerCase();return K.filter(ze=>ze.message.toLowerCase().includes(ge)||ze.author.toLowerCase().includes(ge)||ze.shortHash.toLowerCase().includes(ge))},[K,le]),bt=a.useCallback(async ge=>{if(ge.preventDefault(),!!Q.trim()){d(!0);try{await Zy(Q.trim(),de.trim()||void 0,r),i(`Created branch ${Q}`,"success"),be(""),me("");const ze=await Ba(r);ne(ze)}catch(ze){i(ke(ze)||"Failed to create branch","error")}finally{d(!1)}}},[Q,de,i,r]),Nt=a.useCallback(async ge=>{d(!0);try{await ej(ge,r),i(`Switched to ${ge}`,"success");const[ze,dt]=await Promise.all([Us(r),Ba(r)]);v(ze),ne(dt)}catch(ze){i(ke(ze)||"Failed to checkout branch","error")}finally{d(!1)}},[i,r]),Qt=a.useCallback(async ge=>{if(await o.confirm({title:"Delete Branch",message:`Delete branch "${ge}"?`,danger:!0})){d(!0);try{await Zd(ge,void 0,r),i(`Deleted branch ${ge}`,"success");const dt=await Ba(r);ne(dt)}catch(dt){if(ke(dt).includes("not fully merged")){if(await o.confirm({title:"Force Delete Branch",message:"Branch has unmerged commits. Force delete?",danger:!0}))try{await Zd(ge,!0,r),i(`Force deleted branch ${ge}`,"success");const Y=await Ba(r);ne(Y)}catch(Y){i(ke(Y)||"Failed to delete branch","error")}}else i(ke(dt)||"Failed to delete branch","error")}finally{d(!1)}}},[i,r,confirm]),Pt=a.useMemo(()=>{if(!ie.trim())return L;const ge=ie.toLowerCase();return L.filter(ze=>ze.name.toLowerCase().includes(ge))},[L,ie]),Dt=a.useCallback(async ge=>{if(Re===ge){Oe(null),et([]),Ge(null),je(null);return}Oe(ge),et([]),Ge(null),je(null),rt(!0);try{const ze=await Qy(ge,10,r);et(ze)}catch{et([])}finally{rt(!1)}},[Re,r]),Et=a.useCallback(async ge=>{if(He===ge){Ge(null),je(null);return}Ge(ge),je(null),Ae(!0);try{const ze=await Ao(ge,r);je(ze)}catch{je(null)}finally{Ae(!1)}},[He,r]),Xt=a.useCallback(()=>{Oe(null),et([]),Ge(null),je(null)},[]),Lt=a.useCallback(async ge=>{ge.preventDefault(),Ie("create");try{await ij(it.trim()||void 0,r),i("Changes stashed","success"),ve("");const ze=await Zr(r);Fe(ze)}catch(ze){i(ke(ze)||"Failed to stash changes","error")}finally{Ie(null)}},[it,i,r]),Ft=a.useCallback(async(ge,ze=!1)=>{Ie(`apply-${ge}`);try{await aj(ge,ze,r),i(ze?"Stash popped":"Stash applied","success");const dt=await Zr(r);Fe(dt)}catch(dt){i(ke(dt)||"Failed to apply stash","error")}finally{Ie(null)}},[i,r]),zt=a.useCallback(async ge=>{if(await o.confirm({title:"Drop Stash",message:`Drop stash@{${ge}}? This cannot be undone.`,danger:!0})){Ie(`drop-${ge}`);try{await rj(ge,r),i("Stash dropped","success");const dt=await Zr(r);Fe(dt)}catch(dt){i(ke(dt)||"Failed to drop stash","error")}finally{Ie(null)}}},[i,r,confirm]),Tt=a.useCallback(async()=>{Me("fetch");try{const ge=await tj(void 0,r);$e(ge),i(ge.message||"Fetch completed",ge.fetched?"success":"info");const ze=await Us(r);v(ze)}catch(ge){i(ke(ge)||"Fetch failed","error")}finally{Me(null)}},[i,r]),Gt=a.useCallback(async()=>{Me("pull");try{const ge=await nj(r);$e(ge),ge.conflict?i("Merge conflict detected. Resolve manually.","error"):i(ge.message||"Pull completed","success");const ze=await Us(r);v(ze)}catch(ge){i(ke(ge)||"Pull failed","error")}finally{Me(null)}},[i,r]),Ot=a.useCallback(async()=>{Me("push");try{const ge=await sj(r);$e(ge),i(ge.message||"Push completed","success");const ze=await Us(r);v(ze)}catch(ge){i(ke(ge)||"Push failed","error")}finally{Me(null)}},[i,r]),qt=a.useMemo(()=>x.filter(ge=>ge.staged),[x]),nn=a.useMemo(()=>x.filter(ge=>!ge.staged),[x]);return e?t.jsx("div",{className:"modal-overlay open",...p,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal gm-modal",ref:f,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h3",{children:[t.jsx(Cc,{size:18,style:{marginRight:8,verticalAlign:"middle"}}),"Git Manager"]}),t.jsxs("div",{className:"gm-header-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:ft,disabled:u,title:"Refresh",children:t.jsx(Ln,{size:14,className:u?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Kt,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:nr.map(ge=>{const ze=ge.icon;return t.jsxs("button",{role:"tab","aria-selected":l===ge.id,className:`gm-nav-item${l===ge.id?" active":""}`,onClick:()=>c(ge.id),children:[t.jsx(ze,{size:16}),t.jsx("span",{className:"gm-nav-label",children:ge.label})]},ge.id)})}),t.jsxs("div",{className:"gm-content",role:"tabpanel",children:[u&&t.jsxs("div",{className:"gm-loading",children:[t.jsx(lt,{size:24,className:"spin"}),t.jsx("span",{children:"Loading..."})]}),m&&!u&&t.jsxs("div",{className:"gm-error",children:[t.jsx(ps,{size:18}),t.jsx("span",{children:m}),t.jsx("button",{className:"btn btn-sm",onClick:ft,children:"Retry"})]}),l==="status"&&!u&&b&&t.jsx(qT,{status:b,copyToClipboard:g}),l==="changes"&&!u&&t.jsx(VT,{status:b,stagedFiles:qt,unstagedFiles:nn,selectedFiles:k,toggleFileSelection:mt,onStageFiles:J,onUnstageFiles:re,onDiscardChanges:ye,onSelectDiffFile:Ye,selectedDiffTarget:R,changeDiff:z,loadingChangeDiff:T,changeDiffError:q,commitMessage:_,setCommitMessage:N,onCommit:at,onStageAllAndCommit:te,committing:A}),l==="commits"&&!u&&t.jsx(WT,{commits:St,commitSearch:le,setCommitSearch:we,selectedCommit:E,commitDiff:P,loadingDiff:O,onCommitClick:ht,onLoadMore:xt,canLoadMore:K.length>=Ne&&Ne<100,copyToClipboard:g}),l==="branches"&&!u&&t.jsx(KT,{branches:Pt,branchSearch:ie,setBranchSearch:xe,newBranchName:Q,setNewBranchName:be,branchBase:de,setBranchBase:me,onCreateBranch:bt,onCheckoutBranch:Nt,onDeleteBranch:Qt,loading:u,allBranches:L,selectedBranch:Re,branchCommits:nt,loadingBranchCommits:Ze,expandedBranchCommit:He,branchCommitDiff:oe,loadingBranchCommitDiff:X,onSelectBranch:Dt,onBranchCommitClick:Et,onCloseBranchDetails:Xt}),l==="worktrees"&&!u&&t.jsx(GT,{worktrees:Te}),l==="stashes"&&!u&&t.jsx(JT,{stashes:_e,stashMessage:it,setStashMessage:ve,onCreateStash:Lt,onApplyStash:Ft,onDropStash:zt,stashLoading:ce}),l==="remotes"&&!u&&t.jsx(YT,{status:b,remoteLoading:he,lastRemoteResult:Je,onFetch:Tt,onPull:Gt,onPush:Ot,addToast:i,projectId:r,copyToClipboard:g})]})]})]})}):null}function qT({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(Ws,{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(Ui,{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(ps,{size:12}),"Modified"]}):t.jsxs(t.Fragment,{children:[t.jsx(wn,{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(Ar,{size:12}),e.behind]}),e.ahead===0&&e.behind===0&&t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(wn,{size:12}),"Up to date"]})]})]})]})]})}function VT({status:e,stagedFiles:n,unstagedFiles:s,selectedFiles:i,toggleFileSelection:r,onStageFiles:o,onUnstageFiles:l,onDiscardChanges:c,onSelectDiffFile:u,selectedDiffTarget:d,changeDiff:m,loadingChangeDiff:h,changeDiffError:f,commitMessage:p,setCommitMessage:g,onCommit:b,onStageAllAndCommit:v,committing:x}){const y=s.filter(S=>i.has(`unstaged:${S.file}`)),k=n.filter(S=>i.has(`staged:${S.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(Ws,{size:14}),e.branch]}),e.isDirty&&t.jsx("span",{className:"gm-dirty-badge",children:"Modified"})]}),t.jsxs("div",{className:"gm-changes-split",children:[t.jsxs("div",{className:"gm-changes-lists",children:[t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Unstaged Changes (",s.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[y.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>o(y.map(S=>S.file)),title:"Stage selected",children:[t.jsx(ln,{size:12})," Stage (",y.length,")"]}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>c(y.map(S=>S.file)),title:"Discard selected",children:t.jsx(Tr,{size:12})})]}),s.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>o(s.map(S=>S.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(S=>{const _=d?.file===S.file&&d.staged===!1;return t.jsxs("div",{className:`gm-file-item${_?" active":""}`,onClick:()=>u(S.file,!1),role:"button",tabIndex:0,onKeyDown:N=>{(N.key==="Enter"||N.key===" ")&&(N.preventDefault(),u(S.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:N=>N.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`unstaged:${S.file}`),onChange:()=>r(`unstaged:${S.file}`)})}),t.jsx(Ch,{status:S.status}),t.jsx("span",{className:"gm-file-name",title:S.file,children:t.jsx("bdo",{dir:"ltr",children:S.file})}),t.jsx(Eh,{status:S.status}),t.jsx("button",{className:"gm-icon-btn",onClick:N=>{N.stopPropagation(),o([S.file])},title:"Stage file",children:t.jsx(ln,{size:12})})]},`unstaged:${S.file}`)})})]}),t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Staged Changes (",n.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[k.length>0&&t.jsxs("button",{className:"btn btn-sm",onClick:()=>l(k.map(S=>S.file)),title:"Unstage selected",children:["Unstage (",k.length,")"]}),n.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(n.map(S=>S.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(S=>{const _=d?.file===S.file&&d.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${_?" active":""}`,onClick:()=>u(S.file,!0),role:"button",tabIndex:0,onKeyDown:N=>{(N.key==="Enter"||N.key===" ")&&(N.preventDefault(),u(S.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:N=>N.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`staged:${S.file}`),onChange:()=>r(`staged:${S.file}`)})}),t.jsx(Ch,{status:S.status}),t.jsx("span",{className:"gm-file-name",title:S.file,children:t.jsx("bdo",{dir:"ltr",children:S.file})}),t.jsx(Eh,{status:S.status}),t.jsx("button",{className:"gm-icon-btn",onClick:N=>{N.stopPropagation(),l([S.file])},title:"Unstage file",children:t.jsx(Kt,{size:12})})]},`staged:${S.file}`)})})]})]}),t.jsx("div",{className:"gm-changes-diff",children:d||h||m||f?t.jsxs("div",{className:"gm-diff-section",children:[d&&t.jsxs("div",{className:"gm-diff-target",children:[t.jsx(Sc,{size:14}),t.jsxs("span",{children:[d.staged?"Staged":"Unstaged"," diff: "]}),t.jsx("code",{children:d.file})]}),h&&t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(lt,{size:16,className:"spin"}),"Loading diff..."]}),f&&!h&&t.jsx("div",{className:"gm-diff-error",children:f}),m&&!h&&t.jsxs("div",{className:"gm-diff-viewer",children:[m.stat&&t.jsx("pre",{className:"gm-diff-stat",children:m.stat}),t.jsx("pre",{className:"gm-diff-patch",children:m.patch})]})]}):t.jsxs("div",{className:"gm-diff-empty",children:[t.jsx(Sc,{size:20}),t.jsx("span",{children:"Select a file to view its diff"})]})})]}),t.jsxs("form",{className:"gm-commit-form",onSubmit:b,children:[t.jsx("textarea",{className:"gm-commit-input",placeholder:"Commit message...",value:p,onChange:S=>g(S.target.value),rows:3,disabled:x}),t.jsxs("div",{className:"gm-commit-actions",children:[t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:x||!p.trim()||n.length===0,title:n.length===0?"No staged changes to commit":"Commit staged changes",children:[x?t.jsx(lt,{size:14,className:"spin"}):t.jsx(zi,{size:14}),"Commit"]}),s.length>0&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:v,disabled:x||!p.trim(),title:"Stage all and commit",children:"Stage All & Commit"})]})]})]})}function WT({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(wi,{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(Ui,{size:12})})}),i===m.hash&&t.jsx("div",{className:"gm-commit-diff",children:o?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(lt,{size:16,className:"spin"}),"Loading diff..."]}):r?t.jsxs(t.Fragment,{children:[r.stat&&t.jsx("pre",{className:"gm-diff-stat",children:r.stat}),t.jsx("pre",{className:"gm-diff-patch",children:r.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]})]},m.hash))}),u&&t.jsx("button",{className:"gm-load-more",onClick:c,children:"Load more commits"})]})}function KT({branches:e,branchSearch:n,setBranchSearch:s,newBranchName:i,setNewBranchName:r,branchBase:o,setBranchBase:l,onCreateBranch:c,onCheckoutBranch:u,onDeleteBranch:d,loading:m,allBranches:h,selectedBranch:f,branchCommits:p,loadingBranchCommits:g,expandedBranchCommit:b,branchCommitDiff:v,loadingBranchCommitDiff:x,onSelectBranch:y,onBranchCommitClick:k,onCloseBranchDetails:S}){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(wi,{size:14}),t.jsx("input",{type:"text",placeholder:"Filter branches...",value:n,onChange:_=>s(_.target.value)})]})]}),t.jsxs("form",{className:"gm-create-form",onSubmit:c,children:[t.jsx("input",{type:"text",placeholder:"New branch name",value:i,onChange:_=>r(_.target.value),disabled:m}),t.jsxs("select",{value:o,onChange:_=>l(_.target.value),disabled:m,className:"gm-branch-select",children:[t.jsx("option",{value:"",children:"Base: HEAD"}),h.map(_=>t.jsx("option",{value:_.name,children:_.name},_.name))]}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:m||!i.trim(),children:[t.jsx(ln,{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(_=>t.jsxs("div",{children:[t.jsxs("div",{className:`gm-branch-item${_.isCurrent?" current":""}${f===_.name?" selected":""}`,onClick:()=>y(_.name),children:[t.jsxs("div",{className:"gm-branch-info",children:[t.jsxs("span",{className:"gm-branch-name",children:[_.isCurrent&&t.jsx(qn,{size:14,className:"gm-current-icon"}),_.name]}),_.remote&&t.jsxs("span",{className:"gm-branch-remote",children:["→ ",_.remote]}),_.lastCommitDate&&t.jsx("span",{className:"gm-branch-date",children:wa(_.lastCommitDate)})]}),t.jsx("div",{className:"gm-branch-actions",children:!_.isCurrent&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:N=>{N.stopPropagation(),u(_.name)},disabled:m,title:"Checkout",children:t.jsx(Ws,{size:14})}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:N=>{N.stopPropagation(),d(_.name)},disabled:m,title:"Delete",children:t.jsx(on,{size:14})})]})})]}),f===_.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(Pr,{size:14}),"Commits on ",_.name]}),t.jsx("button",{className:"gm-icon-btn",onClick:S,title:"Close","data-testid":"close-branch-details",children:t.jsx(Kt,{size:14})})]}),g?t.jsxs("div",{className:"gm-branch-details-loading",children:[t.jsx(lt,{size:16,className:"spin"}),"Loading commits..."]}):p.length===0?t.jsx("div",{className:"gm-empty",children:"No commits found"}):t.jsx("div",{className:"gm-branch-commits-list",children:p.map(N=>t.jsxs("div",{className:"gm-branch-commit",children:[t.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>k(N.hash),"data-testid":`branch-commit-${N.shortHash}`,children:[t.jsx("span",{className:"gm-commit-hash",children:N.shortHash}),t.jsx("span",{className:"gm-commit-message",title:N.message,children:N.message}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:N.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:wa(N.date)}),N.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),b===N.hash&&t.jsx("div",{className:"gm-commit-diff",children:x?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(lt,{size:16,className:"spin"}),"Loading diff..."]}):v?t.jsxs(t.Fragment,{children:[v.stat&&t.jsx("pre",{className:"gm-diff-stat",children:v.stat}),t.jsx("pre",{className:"gm-diff-patch",children:v.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},N.hash))})]})]},_.name))})]})}function GT({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:pd(n.path)||n.path})]}),t.jsxs("div",{className:"gm-worktree-detail",children:[n.branch&&t.jsxs("span",{className:"gm-worktree-branch",children:[t.jsx(Ws,{size:12}),n.branch]}),n.taskId&&t.jsx("span",{className:"gm-worktree-task",children:n.taskId})]})]})},n.path))})]})}function JT({stashes:e,stashMessage:n,setStashMessage:s,onCreateStash:i,onApplyStash:r,onDropStash:o,stashLoading:l}){return t.jsxs("div",{className:"gm-panel","data-testid":"stashes-panel",children:[t.jsx("div",{className:"gm-panel-header",children:t.jsx("h4",{children:"Stashes"})}),t.jsxs("form",{className:"gm-create-form",onSubmit:i,children:[t.jsx("input",{type:"text",placeholder:"Stash message (optional)",value:n,onChange:c=>s(c.target.value),disabled:l!==null}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:l!==null,children:[l==="create"?t.jsx(lt,{size:14,className:"spin"}):t.jsx(Mr,{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(Ws,{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(lt,{size:14,className:"spin"}):"Apply"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>r(c.index,!0),disabled:l!==null,title:"Pop stash (apply and drop)",children:"Pop"}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>o(c.index),disabled:l!==null,title:"Drop stash",children:l===`drop-${c.index}`?t.jsx(lt,{size:14,className:"spin"}):t.jsx(on,{size:14})})]})]},c.index))})]})}function YT({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:i,onPull:r,onPush:o,addToast:l,projectId:c,copyToClipboard:u}){const d=X=>{try{return new URL(X).hostname}catch{return X.replace(/^git@/,"").split(":")[0]||X}},[m,h]=a.useState([]),[f,p]=a.useState(!1),[g,b]=a.useState(null),[v,x]=a.useState(""),[y,k]=a.useState(""),[S,_]=a.useState(null),[N,A]=a.useState(""),[C,z]=a.useState(""),[M,T]=a.useState(!1),[U,q]=a.useState([]),[D,R]=a.useState(!1),[F,V]=a.useState(null),[K,ee]=a.useState([]),[E,$]=a.useState(!1),[P,w]=a.useState(null),O=m.find(X=>X.name===F),[Z,Ne]=a.useState(null),[se,le]=a.useState(null),[we,L]=a.useState(!1),[ne,Q]=a.useState(null),[be,de]=a.useState(null),[me,ie]=a.useState(!1);a.useEffect(()=>{xe()},[]),a.useEffect(()=>{e&&e.ahead>0?Re():e&&e.ahead===0&&q([])},[e?.ahead]),a.useEffect(()=>{m.length>0&&!F&&V(m[0].name)},[m]),a.useEffect(()=>{F?Oe(F):(ee([]),w(null))},[F]),a.useEffect(()=>{F&&!m.find(X=>X.name===F)&&V(m.length>0?m[0].name:null)},[m,F]);const xe=async()=>{p(!0);try{const X=await Fy(c);h(X)}catch(X){l(ke(X)||"Failed to load remotes","error")}finally{p(!1)}},Re=async()=>{R(!0);try{const X=await Jy(c);q(X)}catch{q([])}finally{R(!1)}},Oe=async X=>{$(!0),w(null);try{const Ae=await Yy(X,void 0,10,c);ee(Ae)}catch(Ae){w(ke(Ae)||"Failed to load remote commits"),ee([])}finally{$(!1)}},nt=Ks(),et=async X=>{if(X.preventDefault(),!(!v.trim()||!y.trim())){b("add");try{await Oy(v.trim(),y.trim(),c),l(`Remote '${v}' added successfully`,"success"),x(""),k(""),T(!1),await xe()}catch(Ae){l(ke(Ae)||"Failed to add remote","error")}finally{b(null)}}},Ze=async X=>{if(await nt.confirm({title:"Remove Remote",message:`Are you sure you want to remove remote '${X}'?`,danger:!0})){b(`remove-${X}`);try{await Uy(X,c),l(`Remote '${X}' removed`,"success"),await xe()}catch(Te){l(ke(Te)||"Failed to remove remote","error")}finally{b(null)}}},rt=async X=>{if(C.trim()){b(`rename-${X}`);try{await By(X,C.trim(),c),l(`Remote renamed to '${C.trim()}'`,"success"),_(null),z(""),await xe()}catch(Ae){l(ke(Ae)||"Failed to rename remote","error")}finally{b(null)}}},He=async X=>{if(N.trim()){b(`url-${X}`);try{await Hy(X,N.trim(),c),l("Remote URL updated","success"),_(null),A(""),await xe()}catch(Ae){l(ke(Ae)||"Failed to update remote URL","error")}finally{b(null)}}},Ge=a.useCallback(async(X,Ae)=>{if(Ae==="ahead"){if(Z===X){Ne(null),le(null);return}Ne(X),le(null),L(!0);try{const Te=await Ao(X);le(Te)}catch{le(null)}finally{L(!1)}}else{if(ne===X){Q(null),de(null);return}Q(X),de(null),ie(!0);try{const Te=await Ao(X);de(Te)}catch{de(null)}finally{ie(!1)}}},[Z,ne]),oe=X=>{_(`url-${X.name}`),A(X.pushUrl||X.fetchUrl)},je=X=>{_(`name-${X.name}`),z(X.name)};return t.jsx("div",{className:"gm-panel gm-remotes-panel","data-testid":"remotes-panel",children:t.jsxs("div",{className:"gm-remotes-layout",children:[t.jsxs("div",{className:"gm-remote-selector","data-testid":"remote-selector",children:[t.jsxs("div",{className:"gm-remote-selector-header",children:[t.jsx("span",{className:"gm-remote-selector-title",children:"Remotes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>T(!M),disabled:g!==null,title:M?"Cancel":"Add Remote",children:M?t.jsx(Kt,{size:14}):t.jsx(ln,{size:14})})]}),M&&t.jsxs("form",{className:"gm-remote-form",onSubmit:et,children:[t.jsx("input",{type:"text",placeholder:"Remote name",value:v,onChange:X=>x(X.target.value),disabled:g==="add",className:"gm-input"}),t.jsx("input",{type:"text",placeholder:"Repository URL",value:y,onChange:X=>k(X.target.value),disabled:g==="add",className:"gm-input gm-input-url"}),t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:!v.trim()||!y.trim()||g==="add",children:[g==="add"?t.jsx(lt,{size:12,className:"spin"}):t.jsx(ln,{size:12}),"Add"]})]}),f?t.jsxs("div",{className:"gm-loading",children:[t.jsx(lt,{size:16,className:"spin"}),"Loading..."]}):m.length===0?t.jsx("div",{className:"gm-empty",children:"No remotes"}):m.map(X=>t.jsxs("div",{className:`gm-remote-selector-item${F===X.name?" selected":""}`,onClick:()=>V(X.name),role:"button",tabIndex:0,children:[t.jsxs("div",{className:"gm-remote-selector-info",children:[t.jsxs("span",{className:"gm-remote-selector-name",children:[X.name,X.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),t.jsx("span",{className:"gm-remote-selector-host",children:d(X.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:Ae=>{Ae.stopPropagation(),Ze(X.name)},disabled:g!==null,title:"Remove remote",children:t.jsx(on,{size:14})})]},X.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[F&&O?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"gm-remote-sync-card","data-testid":"remote-sync-card",children:[t.jsxs("div",{className:"gm-remote-sync-card-header",children:[t.jsx("span",{className:"gm-remote-sync-card-title",children:F}),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(Ar,{size:14}),e.behind," to pull"]})]})]}),t.jsxs("div",{className:"gm-remote-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:i,disabled:n!==null||f,children:[n==="fetch"?t.jsx(lt,{size:14,className:"spin"}):t.jsx(Ln,{size:14}),"Fetch"]}),t.jsxs("button",{className:"btn btn-primary",onClick:r,disabled:n!==null||f,children:[n==="pull"?t.jsx(lt,{size:14,className:"spin"}):t.jsx(Es,{size:14}),"Pull"]}),t.jsxs("button",{className:"btn btn-primary",onClick:o,disabled:n!==null||f,children:[n==="push"?t.jsx(lt,{size:14,className:"spin"}):t.jsx(Fi,{size:14}),"Push"]})]})]}),t.jsxs("div",{className:"gm-remote-detail-card","data-testid":"remote-detail-card",children:[t.jsxs("div",{className:"gm-remote-detail-urls",children:[t.jsxs("div",{className:"gm-remote-detail-url-row",children:[t.jsx("span",{className:"gm-url-label",children:"Fetch:"}),S===`url-${F}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:N,onChange:X=>A(X.target.value),className:"gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>He(F),disabled:g===`url-${F}`,children:g===`url-${F}`?t.jsx(lt,{size:12,className:"spin"}):t.jsx(qn,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{_(null),A("")},title:"Cancel",children:t.jsx(Kt,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:O.fetchUrl,children:O.fetchUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>u(O.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:t.jsx(Ui,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>oe(O),disabled:g!==null,title:"Edit remote URL",children:t.jsx(ms,{size:14})})]})]}),O.pushUrl&&O.pushUrl!==O.fetchUrl&&t.jsxs("div",{className:"gm-remote-detail-url-row",children:[t.jsx("span",{className:"gm-url-label",children:"Push:"}),t.jsx("span",{className:"gm-url-value",title:O.pushUrl,children:O.pushUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>u(O.pushUrl,"push URL"),title:"Copy push URL",children:t.jsx(Ui,{size:14})})]})]}),t.jsx("div",{className:"gm-remote-detail-name-row",children:S===`name-${F}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:C,onChange:X=>z(X.target.value),className:"gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>rt(F),disabled:g===`rename-${F}`,children:g===`rename-${F}`?t.jsx(lt,{size:12,className:"spin"}):t.jsx(qn,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{_(null),z("")},title:"Cancel",children:t.jsx(Kt,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>je(O),disabled:g!==null,title:"Edit remote name",children:t.jsx(ms,{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,")"]})}),D?t.jsxs("div",{className:"gm-loading",children:[t.jsx(lt,{size:14,className:"spin"}),"Loading..."]}):U.length>0?t.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:U.map(X=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>Ge(X.hash,"ahead"),role:"button",tabIndex:0,title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:X.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:X.message,children:X.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:X.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:wa(X.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:Z===X.hash?t.jsx(sn,{size:14}):t.jsx(kn,{size:14})})]}),Z===X.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:we?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(lt,{size:16,className:"spin"}),"Loading diff..."]}):se?t.jsxs(t.Fragment,{children:[X.message&&t.jsx("div",{className:"gm-commit-message-full",children:X.message}),se.stat&&t.jsx("pre",{className:"gm-diff-stat",children:se.stat}),t.jsx("pre",{className:"gm-diff-patch",children:se.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},X.hash))}):t.jsx("div",{className:"gm-empty",children:"No ahead commits found (may need to fetch first)"})]}),t.jsxs("div",{className:"gm-remote-section","data-testid":"remote-commits-section",children:[t.jsx("div",{className:"gm-section-subheader",children:t.jsxs("h5",{children:[t.jsx(up,{size:14}),"Recent commits on ",F]})}),E?t.jsxs("div",{className:"gm-loading",children:[t.jsx(lt,{size:14,className:"spin"}),"Loading commits..."]}):P?t.jsxs("div",{className:"gm-error",children:[t.jsx(ps,{size:14}),P]}):K.length===0?t.jsxs("div",{className:"gm-empty",children:["No commits found on ",F,". Try fetching first."]}):t.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:K.map(X=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>Ge(X.hash,"remote"),role:"button",tabIndex:0,title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:X.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:X.message,children:X.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:X.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:wa(X.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:ne===X.hash?t.jsx(sn,{size:14}):t.jsx(kn,{size:14})})]}),ne===X.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:me?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(lt,{size:16,className:"spin"}),"Loading diff..."]}):be?t.jsxs(t.Fragment,{children:[X.message&&t.jsx("div",{className:"gm-commit-message-full",children:X.message}),be.stat&&t.jsx("pre",{className:"gm-diff-stat",children:be.stat}),t.jsx("pre",{className:"gm-diff-patch",children:be.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},X.hash))})]})]}):t.jsx("div",{className:"gm-empty",children:"Select a remote to view details"}),s&&t.jsx("div",{className:"gm-remote-result",children:s.message})]})]})})}const sr={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function QT(e,n){return e&&n?`${e}/${n}`:""}function XT(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 ZT(e){switch(e){case"file-text":return Bi;case"check-circle":return wn;case"shield":return ov;case"zap":return Yn;case"eye":return Ma;case"globe":return Vo;case"layout-grid":return qi;default:return wn}}function eP(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 tP({isOpen:e,onClose:n,addToast:s,projectId:i}){const[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState(!0),[m,h]=a.useState(!0),[f,p]=a.useState("my-steps"),[g,b]=a.useState(null),[v,x]=a.useState(!1),[y,k]=a.useState(sr),[S,_]=a.useState(!1),[N,A]=a.useState(!1),[C,z]=a.useState(null),[M,T]=a.useState(null),[U,q]=a.useState({}),[D,R]=a.useState([]),F=a.useRef(null);ci(F,e,"fusion:workflow-steps-modal-size");const V=a.useCallback(async()=>{try{d(!0);const L=await Qo(i);o(L)}catch(L){s(ke(L)||"Failed to load workflow steps","error")}finally{d(!1)}},[s,i]),K=a.useCallback(async()=>{try{const L=await Nr(i);q(L||{})}catch{}},[i]),ee=a.useCallback(async()=>{try{const L=await fs();R(L.models||[])}catch{}},[]),E=a.useCallback(async()=>{try{h(!0);const L=await Kj();c(L.templates)}catch(L){s(ke(L)||"Failed to load templates","error")}finally{h(!1)}},[s]);a.useEffect(()=>{e&&(V(),E(),K(),ee())},[e,V,E,K,ee]);const $=a.useCallback(()=>{x(!0),b(null),k(sr)},[]),P=a.useCallback(L=>{b(L.id),x(!1),k({name:L.name,description:L.description,mode:L.mode||"prompt",phase:L.phase||"pre-merge",prompt:L.prompt,scriptName:L.scriptName||"",enabled:L.enabled,defaultOn:L.defaultOn||!1,modelProvider:L.modelProvider||"",modelId:L.modelId||""})},[]),w=a.useCallback(()=>{b(null),x(!1),k(sr)},[]),O=a.useCallback(async()=>{if(!y.name.trim()||!y.description.trim()){s("Name and description are required","error");return}_(!0);try{const L=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 ne={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,...L};await ru(ne,i),s("Workflow step created","success")}else g&&(await qj(g,{name:y.name.trim(),description:y.description.trim(),mode:y.mode,phase:y.phase,prompt:y.mode==="prompt"?y.prompt:"",scriptName:y.mode==="script"?y.scriptName.trim():void 0,enabled:y.enabled,defaultOn:y.defaultOn,...L},i),s("Workflow step updated","success"));x(!1),b(null),k(sr),await V()}catch(L){s(ke(L)||"Failed to save workflow step","error")}finally{_(!1)}},[y,v,g,s,V]),Z=a.useCallback(async L=>{try{await Vj(L,i),s("Workflow step deleted","success"),z(null),g===L&&(b(null),k(sr)),await V()}catch(ne){s(ke(ne)||"Failed to delete workflow step","error")}},[g,s,V]),Ne=a.useCallback(async()=>{if(!(!g&&!v)&&y.mode==="prompt"){if(v){if(!y.name.trim()||!y.description.trim()){s("Name and description are required before refining","error");return}_(!0);try{const L=y.modelProvider&&y.modelId?{modelProvider:y.modelProvider,modelId:y.modelId}:{},ne={name:y.name.trim(),description:y.description.trim(),mode:"prompt",prompt:y.prompt.trim()||void 0,enabled:y.enabled,defaultOn:y.defaultOn||void 0,...L},Q=await ru(ne,i);x(!1),b(Q.id),A(!0);const be=await ou(Q.id,i);k(de=>({...de,prompt:be.prompt})),s("Prompt refined with AI","success"),await V()}catch(L){s(ke(L)||"Failed to refine prompt","error")}finally{_(!1),A(!1)}return}if(g){A(!0);try{const L=await ou(g,i);k(ne=>({...ne,prompt:L.prompt})),s("Prompt refined with AI","success"),await V()}catch(L){s(ke(L)||"Failed to refine prompt","error")}finally{A(!1)}}}},[g,v,y,s,V]),se=a.useCallback(async L=>{T(L.id);try{await Gj(L.id,i),s(`Added ${L.name} workflow step`,"success"),await V(),p("my-steps")}catch(ne){const Q=ke(ne);Q?.includes("already exists")?s(`A workflow step named '${L.name}' already exists`,"error"):s(Q||"Failed to add workflow step from template","error")}finally{T(null)}},[s,V]),le=_i(n);if(!e)return null;const we=v||g!==null;return t.jsx("div",{className:"modal-overlay open",...le,"data-testid":"workflow-step-manager",children:t.jsxs("div",{ref:F,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:[!we&&t.jsxs("div",{className:"wfm-tab-row",children:[t.jsxs("button",{className:`btn ${f==="my-steps"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>p("my-steps"),"data-testid":"tab-my-steps",children:[t.jsx(nb,{size:14}),"My Workflow Steps (",r.length,")"]}),t.jsxs("button",{className:`btn ${f==="templates"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>p("templates"),"data-testid":"tab-templates",children:[t.jsx(qi,{size:14}),"Templates (",l.length,")"]})]}),f==="my-steps"&&!we&&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(L=>t.jsx("div",{className:"wfm-step-card","data-testid":`workflow-step-${L.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:L.name}),t.jsx("span",{className:`wfm-badge ${L.enabled?"wfm-badge-enabled":"wfm-badge-disabled"}`,children:L.enabled?"Enabled":"Disabled"}),t.jsx("span",{className:`wfm-badge ${(L.mode||"prompt")==="script"?"wfm-badge-script":"wfm-badge-prompt"}`,children:(L.mode||"prompt")==="script"?"Script":"AI Prompt"}),t.jsx("span",{className:`wfm-badge ${(L.phase||"pre-merge")==="post-merge"?"wfm-badge-post-merge":"wfm-badge-pre-merge"}`,children:(L.phase||"pre-merge")==="post-merge"?"Post-merge":"Pre-merge"}),L.defaultOn&&t.jsx("span",{className:"wfm-badge wfm-badge-default-on",children:"Default on"})]}),t.jsx("div",{className:"wfm-step-card-desc",children:L.description})]}),t.jsxs("div",{className:"wfm-step-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>P(L),title:"Edit","aria-label":`Edit ${L.name}`,children:t.jsx(ms,{size:14})}),C===L.id?t.jsxs("div",{className:"wfm-delete-confirm",children:[t.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>Z(L.id),title:"Confirm delete","aria-label":`Confirm delete ${L.name}`,children:t.jsx(qn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>z(null),title:"Cancel delete","aria-label":"Cancel delete",children:t.jsx(Kt,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>z(L.id),title:"Delete","aria-label":`Delete ${L.name}`,children:t.jsx(on,{size:14})})]})]})},L.id))})]}),f==="templates"&&!we&&t.jsx(t.Fragment,{children:m?t.jsxs("div",{className:"wfm-loading",children:[t.jsx(lt,{size:24,className:"spin wfm-spinner"}),"Loading templates..."]}):l.length===0?t.jsx("div",{className:"wfm-empty","data-testid":"no-templates-state",children:"No templates available."}):t.jsx("div",{className:"wfm-template-list",children:l.map(L=>{const ne=ZT(L.icon),Q=eP(L.category),be=M===L.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`template-${L.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(ne,{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:L.name}),t.jsx("span",{className:Q,children:L.category})]}),t.jsx("div",{className:"wfm-template-desc",children:L.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>se(L),disabled:be,"data-testid":`add-template-${L.id}`,children:be?t.jsxs(t.Fragment,{children:[t.jsx(lt,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(ln,{size:12}),"Add"]})})]})]})},L.id)})})}),we&&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:L=>k(ne=>({...ne,name:L.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:L=>k(ne=>({...ne,description:L.target.value})),placeholder:"Brief description of what this step does",rows:2,"data-testid":"workflow-step-description"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Execution Mode"}),t.jsxs("div",{className:"wfm-mode-selector","data-testid":"workflow-step-mode-selector",children:[t.jsxs("button",{className:`btn ${y.mode==="prompt"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>k(L=>({...L,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[t.jsx(Ni,{size:14}),"AI Prompt"]}),t.jsxs("button",{className:`btn ${y.mode==="script"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>k(L=>({...L,mode:"script",prompt:"",modelProvider:"",modelId:""})),"data-testid":"mode-script",children:[t.jsx(pi,{size:14}),"Run Script"]})]})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Execution Phase"}),t.jsxs("div",{className:"wfm-mode-selector","data-testid":"workflow-step-phase-selector",children:[t.jsx("button",{className:`btn ${y.phase==="pre-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>k(L=>({...L,phase:"pre-merge"})),"data-testid":"phase-pre-merge",children:"Pre-merge"}),t.jsx("button",{className:`btn ${y.phase==="post-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>k(L=>({...L,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:Ne,disabled:!y.description.trim()||N,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[N?t.jsx(lt,{size:12,className:"spin"}):t.jsx(os,{size:12}),t.jsx("span",{children:"Refine with AI"})]})]}),t.jsx("textarea",{value:y.prompt,onChange:L=>k(ne=>({...ne,prompt:L.target.value})),placeholder:"Leave empty to use AI refinement",rows:6,className:"wfm-prompt-textarea","data-testid":"workflow-step-prompt"})]}),y.mode==="prompt"&&t.jsxs("div",{className:"wfm-field","data-testid":"workflow-step-model-field",children:[t.jsxs("div",{className:"wfm-model-header",children:[t.jsx("label",{children:"Model Override"}),y.modelProvider&&y.modelId&&t.jsxs("button",{type:"button",className:"btn-icon wfm-model-clear-btn",onClick:()=>k(L=>({...L,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[t.jsx(Kt,{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(Xn,{models:D,value:QT(y.modelProvider,y.modelId),onChange:L=>{const ne=XT(L);k(Q=>({...Q,modelProvider:ne.provider,modelId:ne.modelId}))},placeholder:"Select a model override…",label:"Model override for this workflow step"})})]}),y.mode==="script"&&t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Script"}),Object.keys(U).length===0?t.jsx("div",{className:"wfm-no-scripts","data-testid":"no-scripts-message",children:"No scripts configured. Add scripts in Settings → Scripts first."}):t.jsxs("select",{value:y.scriptName,onChange:L=>k(ne=>({...ne,scriptName:L.target.value})),"data-testid":"workflow-step-script-select",children:[t.jsx("option",{value:"",children:"Select a script…"}),Object.entries(U).map(([L,ne])=>t.jsxs("option",{value:L,children:[L," (",ne,")"]},L))]})]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:y.enabled,onChange:L=>k(ne=>({...ne,enabled:L.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:L=>k(ne=>({...ne,defaultOn:L.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:S,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:O,disabled:S||!y.name.trim()||!y.description.trim()||y.mode==="script"&&!y.scriptName.trim(),"data-testid":"save-workflow-step",children:S?"Saving...":v?"Create":"Save"})]})]})]})]})}),!we&&t.jsx("div",{className:"wfm-footer",children:t.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:$,"data-testid":"add-workflow-step",children:[t.jsx(ln,{size:14}),"Add Workflow Step"]})})]})})}const nP=36e5,sP=3e5,pc=[{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 iP(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 aP(e){return typeof e!="number"||!Number.isFinite(e)?nP:Math.max(sP,Math.round(e))}function QL(e){if(pc.some(s=>s.value===e))return[...pc];const n={value:e,label:`${iP(e)} (custom)`};return[...pc,n].sort((s,i)=>s.value-i.value)}const rP=4,oP=5*6e4;function lP(e){const n=aP(e?.heartbeatIntervalMs);return Math.max(n*rP,oP)}function cP(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 dP(e){const{state:n,lastHeartbeatAt:s,lastError:i,pauseReason:r,runtimeConfig:o}=e,l=cP(e),c=l||o?.enabled!==!1;if(n==="terminated")return{label:"Terminated",icon:t.jsx(Cs,{size:14}),color:"var(--state-error-text)",stateDerived:!0};if(n==="error")return{label:i??"Error",icon:t.jsx(Ds,{size:14}),color:"var(--state-error-text)",stateDerived:!i};if(n==="paused")return{label:r?`Paused: ${r}`:"Paused",icon:t.jsx(qs,{size:14}),color:"var(--state-paused-text)",stateDerived:!r};if(n==="running"||l&&n==="active")return{label:"Running",icon:t.jsx(Ds,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!c)return{label:"Heartbeat Disabled",icon:t.jsx(qs,{size:14}),color:"var(--state-paused-text)",stateDerived:!1};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:t.jsx(Cn,{size:14}),color:"var(--text-secondary)",stateDerived:!1};const u=new Date(s).getTime(),d=Date.now()-u,m=lP(o);return d>m?{label:"Unresponsive",icon:t.jsx(Ds,{size:14}),color:"var(--state-error-text)",stateDerived:!1}:{label:"Healthy",icon:t.jsx(mx,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}const ir=[{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 uP({isOpen:e,onClose:n,addToast:s,projectId:i}){const[r,o]=a.useState([]),[l,c]=a.useState(!1),[u,d]=a.useState(!1),[m,h]=a.useState(""),[f,p]=a.useState("custom"),[g,b]=a.useState("all"),[v,x]=a.useState(()=>{if(typeof window>"u")return"list";const P=Zn("fn-agent-view",i);return P==="board"||P==="list"?P:"list"});a.useEffect(()=>{const P=Zn("fn-agent-view",i);if(P==="board"||P==="list"){x(P);return}x("list")},[i]),a.useEffect(()=>{ys("fn-agent-view",v,i)},[i,v]);const[y,k]=a.useState(null),S=a.useRef(null),[_,N]=a.useState(new Set),[A,C]=a.useState(new Map),{confirm:z}=Ks(),M=a.useMemo(()=>A.size===0?r:r.map(P=>{const w=A.get(P.id);return w?{...P,state:w}:P}),[r,A]),T=a.useMemo(()=>g==="all"?M.filter(P=>P.state!=="terminated"):M,[M,g]),U=a.useCallback(async()=>{c(!0);try{const w=await Ra(g!=="all"?{state:g}:void 0,i);o(w)}catch(P){s(`Failed to load agents: ${ke(P)}`,"error")}finally{c(!1)}},[g,s,i]);a.useEffect(()=>{e&&U()},[e,U]),a.useEffect(()=>{if(!e)return;const P=setInterval(()=>{U()},3e4);return()=>{clearInterval(P)}},[e,U]);const q=async()=>{if(m.trim())try{await sk({name:m.trim(),role:f},i),s(`Agent "${m}" created`,"success"),h(""),d(!1),U()}catch(P){s(`Failed to create agent: ${ke(P)}`,"error")}},D=async(P,w)=>{if(!_.has(P)){N(O=>new Set(O).add(P)),C(O=>{const Z=new Map(O);return Z.set(P,w),Z});try{await ak(P,w,i),s(`Agent state updated to ${w}`,"success"),await U(),C(O=>{const Z=new Map(O);return Z.delete(P),Z})}catch(O){C(Z=>{const Ne=new Map(Z);return Ne.delete(P),Ne}),s(`Failed to update state: ${ke(O)}`,"error")}finally{N(O=>{const Z=new Set(O);return Z.delete(P),Z})}}},R=async(P,w)=>{if(await z({title:"Delete Agent",message:`Delete agent "${w}"? This cannot be undone.`,danger:!0}))try{await rk(P,i),s(`Agent "${w}" deleted`,"success"),U()}catch(Z){s(`Failed to delete agent: ${ke(Z)}`,"error")}},F=async(P,w)=>{const O=r.find(Z=>Z.id===P);if(O){if(O.role===w){k(null);return}try{await ik(P,{role:w},i),s(`Agent role updated to ${ir.find(Z=>Z.value===w)?.label??w}`,"success"),k(null),U()}catch(Z){s(`Failed to update role: ${ke(Z)}`,"error")}}},V=(P,w)=>{P.key==="Escape"&&k(null)},K=P=>ir.find(w=>w.value===P)?.label??P,ee=P=>ir.find(w=>w.value===P)?.icon??"◆",E=P=>dP(P),$=P=>P.color==="var(--state-active-text)"?"active":P.color==="var(--state-paused-text)"?"paused":P.color==="var(--state-error-text)"?"error":"muted";return e?t.jsx("div",{className:"modal-overlay open",onClick:P=>P.target===P.currentTarget&&n(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal--wide agent-list-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{className:"modal-title",children:[t.jsx(Cn,{size:20}),"Agents"]}),t.jsxs("div",{className:"modal-actions",children:[t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${v==="board"?" active":""}`,onClick:()=>x("board"),title:"Board view","aria-label":"Board view","aria-pressed":v==="board",children:t.jsx(qi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${v==="list"?" active":""}`,onClick:()=>x("list"),title:"List view","aria-label":"List view","aria-pressed":v==="list",children:t.jsx(Ec,{size:16})})]}),t.jsx("button",{className:"btn-icon",onClick:()=>void U(),title:"Refresh",disabled:l,children:t.jsx(Ln,{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(Eo,{size:14}),t.jsxs("select",{className:"agent-state-filter-select",value:g,onChange:P=>b(P.target.value),"aria-label":"Filter agents by state",children:[t.jsx("option",{value:"all",children:"All States"}),t.jsx("option",{value:"idle",children:"Idle"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"running",children:"Running"}),t.jsx("option",{value:"paused",children:"Paused"}),t.jsx("option",{value:"error",children:"Error"}),t.jsx("option",{value:"terminated",children:"Terminated"})]})]}),t.jsxs("button",{className:"btn btn-task-create btn-sm",onClick:()=>d(!u),children:[t.jsx(ln,{size:16}),u?"Cancel":"New Agent"]})]}),u&&t.jsxs("div",{className:"agent-create-form",children:[t.jsx("input",{type:"text",placeholder:"Agent name...",value:m,onChange:P=>h(P.target.value),onKeyDown:P=>P.key==="Enter"&&q(),className:"input",autoFocus:!0}),t.jsx("select",{className:"select",value:f,onChange:P=>p(P.target.value),children:ir.map(P=>t.jsxs("option",{value:P.value,children:[P.icon," ",P.label]},P.value))}),t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:()=>void q(),children:"Create"})]}),t.jsx("div",{className:v==="board"?"agent-board":"agent-list",children:T.length===0?t.jsxs("div",{className:"agent-empty",children:[t.jsx(Cn,{size:48,opacity:.3}),t.jsx("p",{children:"No agents found"}),t.jsx("p",{className:"text-secondary",children:"Create an agent to get started"})]}):v==="board"?T.map(P=>{const w=E(P),O=$(w);return t.jsxs("div",{className:"agent-board-card","data-state":P.state,children:[t.jsxs("div",{className:"agent-board-header",children:[t.jsx("span",{className:"agent-board-icon",children:ee(P.role)}),t.jsx("span",{className:"agent-board-badge","data-state":P.state,children:P.state}),t.jsx("span",{className:"agent-board-health","data-health":O,title:w.label,children:w.icon})]}),t.jsx("div",{className:"agent-board-name",title:P.name,children:P.name}),t.jsx("div",{className:"agent-board-id",children:P.id}),t.jsxs("div",{className:"agent-board-actions",children:[P.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void D(P.id,"active"),disabled:_.has(P.id),title:"Activate",children:t.jsx(En,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void R(P.id,P.name),title:"Delete",children:t.jsx(on,{size:14})})]}),P.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void D(P.id,"paused"),disabled:_.has(P.id),title:"Pause",children:t.jsx(qs,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void D(P.id,"terminated"),disabled:_.has(P.id),title:"Stop",children:t.jsx(Cs,{size:14})})]}),P.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void D(P.id,"active"),disabled:_.has(P.id),title:"Resume",children:t.jsx(En,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void D(P.id,"terminated"),disabled:_.has(P.id),title:"Stop",children:t.jsx(Cs,{size:14})})]}),P.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void D(P.id,"paused"),disabled:_.has(P.id),title:"Pause",children:t.jsx(qs,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void D(P.id,"terminated"),disabled:_.has(P.id),title:"Stop",children:t.jsx(Cs,{size:14})})]}),P.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void D(P.id,"active"),disabled:_.has(P.id),title:"Retry",children:t.jsx(En,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void D(P.id,"terminated"),disabled:_.has(P.id),title:"Stop",children:t.jsx(Cs,{size:14})})]}),P.state==="terminated"&&t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void R(P.id,P.name),title:"Delete",children:t.jsx(on,{size:14})})]})]},P.id)}):T.map(P=>{const w=E(P),O=$(w);return t.jsxs("div",{className:"agent-card","data-state":P.state,children:[t.jsxs("div",{className:"agent-card-header",children:[t.jsxs("div",{className:"agent-info",children:[y===P.id?t.jsx("select",{ref:S,className:"select agent-role-select",value:P.role,onChange:Z=>void F(P.id,Z.target.value),onKeyDown:Z=>V(Z,P.id),onBlur:()=>k(null),autoFocus:!0,children:ir.map(Z=>t.jsxs("option",{value:Z.value,children:[Z.icon," ",Z.label]},Z.value))}):t.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>k(P.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:Z=>{(Z.key==="Enter"||Z.key===" ")&&k(P.id)},children:ee(P.role)}),t.jsxs("div",{className:"agent-meta",children:[t.jsx("span",{className:"agent-name",children:P.name}),t.jsx("span",{className:"agent-id text-secondary",children:P.id})]})]}),t.jsxs("div",{className:"agent-badges",children:[t.jsx("span",{className:"badge agent-list-state-badge","data-state":P.state,children:P.state}),t.jsxs("span",{className:"badge agent-list-health-badge","data-health":O,title:w.label,children:[w.icon,!w.stateDerived&&` ${w.label}`]}),t.jsx("span",{className:"badge text-secondary",children:K(P.role)})]})]}),t.jsxs("div",{className:"agent-card-body",children:[P.taskId&&t.jsxs("div",{className:"agent-task",children:[t.jsx("span",{className:"text-secondary",children:"Working on:"}),t.jsx("span",{className:"badge",children:P.taskId})]}),P.lastHeartbeatAt&&t.jsxs("div",{className:"agent-heartbeat",children:[t.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),t.jsx("span",{children:new Date(P.lastHeartbeatAt).toLocaleString()})]})]}),t.jsxs("div",{className:"agent-card-actions",children:[P.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void D(P.id,"active"),disabled:_.has(P.id),title:"Activate",children:[t.jsx(En,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void R(P.id,P.name),title:"Delete",children:[t.jsx(on,{size:14})," Delete"]})]}),P.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void D(P.id,"paused"),disabled:_.has(P.id),title:"Pause",children:[t.jsx(qs,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void D(P.id,"terminated"),disabled:_.has(P.id),title:"Stop",children:[t.jsx(Cs,{size:14})," Stop"]})]}),P.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void D(P.id,"active"),disabled:_.has(P.id),title:"Resume",children:[t.jsx(En,{size:14})," Resume"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void D(P.id,"terminated"),disabled:_.has(P.id),title:"Stop",children:[t.jsx(Cs,{size:14})," Stop"]})]}),P.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void D(P.id,"paused"),disabled:_.has(P.id),title:"Pause",children:[t.jsx(qs,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void D(P.id,"terminated"),disabled:_.has(P.id),title:"Stop",children:[t.jsx(Cs,{size:14})," Stop"]})]}),P.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void D(P.id,"active"),disabled:_.has(P.id),title:"Retry",children:[t.jsx(En,{size:14})," Retry"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void D(P.id,"terminated"),disabled:_.has(P.id),title:"Stop",children:[t.jsx(Cs,{size:14})," Stop"]})]}),P.state==="terminated"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm btn-task-create",onClick:()=>void D(P.id,"active"),disabled:_.has(P.id),title:"Start",children:[t.jsx(En,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void R(P.id,P.name),title:"Delete",children:[t.jsx(on,{size:14})," Delete"]})]})]})]},P.id)})})]})]})}):null}function mP({authenticated:e,onToggled:n,compact:s=!1}){const[i,r]=a.useState(null),[o,l]=a.useState(null),[c,u]=a.useState(null),d=a.useRef(!0);a.useEffect(()=>(d.current=!0,()=>{d.current=!1}),[]);const m=a.useCallback(async()=>{try{const x=await ky();return d.current&&r(x),x}catch(x){return d.current&&u({kind:"error",message:x instanceof Error?x.message:String(x)}),null}},[]);a.useEffect(()=>{m()},[m]);const h=a.useCallback(async()=>{l("testing"),u(null),await m(),d.current&&l(null)},[m]),f=a.useCallback(async x=>{l(x?"enabling":"disabling"),u(null);try{const y=await Ny(x);d.current&&u({kind:y.enabled?"enabled":"disabled",restartRequired:y.restartRequired}),n?.(y.enabled),await m()}catch(y){d.current&&u({kind:"error",message:y instanceof Error?y.message:String(y)})}finally{d.current&&l(null)}},[n,m]),p=i?.binary.available??!1,g=i?.enabled??e,b=t.jsxs("span",{className:"onboarding-provider-card__description",children:["Route AI calls through your locally-installed ",t.jsx("code",{children:"claude"})," CLI. Uses your existing Claude subscription / quota instead of an API key."]}),v=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(lt,{size:12,className:"animate-spin"}),"Testing…"]}):"Test"}),g?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void f(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void f(!0),disabled:o!==null||!p,title:p?void 0:"`claude` binary not detected on PATH — install Claude CLI first.",children:o==="enabling"?"Enabling…":"Enable"})]});return s?t.jsxs("div",{className:`auth-provider-card auth-provider-card--cli${e?" auth-provider-card--authenticated":""}`,"data-testid":"claude-cli-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(An,{provider:"claude-cli",size:"sm"}),t.jsx("strong",{children:"Anthropic — via Claude CLI"}),t.jsx(hP,{status:i,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:v})]}),t.jsxs("details",{className:"auth-provider-cli-details",children:[t.jsx("summary",{children:"Details"}),t.jsxs("div",{className:"auth-provider-cli-details-body",children:[b,t.jsx(_h,{status:i,authenticated:e}),c&&t.jsx(Mh,{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(An,{provider:"claude-cli",size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:"Anthropic — via Claude CLI"}),b,t.jsx(_h,{status:i,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(Mh,{action:c})]})}function hP({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 _h({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(lt,{size:10,className:"animate-spin"})," Probing local CLI…"]});const{binary:s,enabled:i,extension:r,ready:o}=e;return s.available?i?r&&r.status!=="ok"?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--warning",children:["⚠ Extension load failed: ",r.reason??r.status]}):o||n?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--connected",children:["✓ Connected",s.version?` — ${s.version}`:""]}):t.jsx("small",{className:"settings-muted",children:"Enabled. Validating…"}):t.jsxs("small",{className:"settings-muted",children:[t.jsx("code",{children:"claude"})," ",s.version?`(${s.version})`:""," detected",s.binaryPath?` at ${s.binaryPath}`:"",". Click Enable to route AI calls through it."]}):t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--error",children:["✗ ",s.reason??"`claude` not found on PATH"]})}function Mh({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 pP({authenticated:e,onToggled:n,compact:s=!1}){const[i,r]=a.useState(null),[o,l]=a.useState(null),[c,u]=a.useState(null),d=a.useRef(!0);a.useEffect(()=>(d.current=!0,()=>{d.current=!1}),[]);const m=a.useCallback(async()=>{try{const x=await wy();return d.current&&r(x),x}catch(x){return d.current&&u({kind:"error",message:x instanceof Error?x.message:String(x)}),null}},[]);a.useEffect(()=>{m()},[m]);const h=a.useCallback(async()=>{l("testing"),u(null),await m(),d.current&&l(null)},[m]),f=a.useCallback(async x=>{l(x?"enabling":"disabling"),u(null);try{const y=await Sy(x);d.current&&u({kind:y.enabled?"enabled":"disabled",restartRequired:y.restartRequired}),n?.(y.enabled),await m()}catch(y){d.current&&u({kind:"error",message:y instanceof Error?y.message:String(y)})}finally{d.current&&l(null)}},[n,m]),p=i?.binary.available??!1,g=i?.enabled??e,b=t.jsxs("span",{className:"onboarding-provider-card__description",children:["Route AI calls through your locally-installed ",t.jsx("code",{children:"droid"})," CLI. Uses your existing Factory AI subscription / quota instead of an API key."]}),v=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(lt,{size:12,className:"animate-spin"}),"Testing…"]}):"Test"}),g?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void f(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void f(!0),disabled:o!==null||!p,title:p?void 0:"`droid` binary not detected on PATH — install Droid CLI first.",children:o==="enabling"?"Enabling…":"Enable"})]});return s?t.jsxs("div",{className:`auth-provider-card auth-provider-card--cli${e?" auth-provider-card--authenticated":""}`,"data-testid":"droid-cli-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(An,{provider:"droid-cli",size:"sm"}),t.jsx("strong",{children:"Factory AI — via Droid CLI"}),t.jsx(fP,{status:i,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:v})]}),t.jsxs("details",{className:"auth-provider-cli-details",children:[t.jsx("summary",{children:"Details"}),t.jsxs("div",{className:"auth-provider-cli-details-body",children:[b,t.jsx(Ah,{status:i,authenticated:e}),c&&t.jsx(Rh,{action:c})]})]})]}):t.jsxs("div",{className:`onboarding-provider-card${e?" onboarding-provider-card--connected":""}`,"data-testid":"droid-cli-provider-card",children:[t.jsx("div",{className:"onboarding-provider-card__icon",children:t.jsx(An,{provider:"droid-cli",size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:"Factory AI — via Droid CLI"}),b,t.jsx(Ah,{status:i,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(Rh,{action:c})]})}function fP({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 Ah({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(lt,{size:10,className:"animate-spin"})," Probing local CLI…"]});const{binary:s,enabled:i,extension:r,ready:o}=e;return s.available?i?r&&r.status!=="ok"?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--warning",children:["⚠ Extension load failed: ",r.reason??r.status]}):o||n?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--connected",children:["✓ Connected",s.version?` — ${s.version}`:""]}):t.jsx("small",{className:"settings-muted",children:"Enabled. Validating…"}):t.jsxs("small",{className:"settings-muted",children:[t.jsx("code",{children:"droid"})," ",s.version?`(${s.version})`:""," detected",s.binaryPath?` at ${s.binaryPath}`:"",". Click Enable to route AI calls through it."]}):t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--error",children:["✗ ",s.reason??"`droid` not found on PATH"]})}function Rh({action:e}){if(e.kind==="error")return t.jsx("p",{className:"onboarding-helper-text onboarding-helper-text--error",children:e.message});const n=e.kind==="enabled"?"Enabled":"Disabled";return t.jsxs("p",{className:"onboarding-helper-text",children:[n,"."," ",e.kind==="enabled"?"Factory AI (via Droid CLI) models are now visible in the model picker.":"Factory AI (via Droid CLI) models are hidden from the model picker.",e.restartRequired?" Restart required: restart your active CLI/chat session for routing changes to take effect.":""]})}function gP(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 fc({instructions:e,"data-testid":n}){const[s,i]=a.useState(!1),r=gP(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(qn,{size:12}):t.jsx(Ui,{size:12})})]})]},d))}):e})}const bP=new Set(["anthropic","claude-cli","pi-claude-cli","openai","openai-codex","google","gemini","google-antigravity","antigravity","google-vertex","vertex","google-cloud-code","cloud-code","google-gemini-cli","google-generative-ai","ollama","github","github-copilot","openrouter","minimax","minimax-cn","zai","kimi","moonshot","kimi-coding","bedrock","amazon-bedrock","xai","grok","opencode","opencode-go","qwen","qwen-ai","qwen-coder","alibaba","tongyi","lmstudio","lm-studio","huggingface","hugging-face","hf","mistral","mistral-ai","azure","azure-openai","azure-openai-responses","fireworks","fireworks-ai","fireworksai","cerebras","groq","vercel","vercel-ai-gateway","hermes","hermes-agent","hermesagent","openclaw","open-claw","paperclip","paperclipai","paperclip-ai"]),xP=/^[a-z][a-z0-9-]*$/,Th=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function Ph(){return{id:"",name:"",reasoning:!1}}function vP({initialConfig:e,onSave:n,onCancel:s,saving:i=!1,error:r}){const o=!!e,[l,c]=a.useState(e?.id??""),[u,d]=a.useState(e?.name??""),[m,h]=a.useState(e?.baseUrl??""),[f,p]=a.useState(e?.api??"openai-completions"),[g,b]=a.useState(e?.apiKey??""),[v,x]=a.useState(e?.models?.length?e.models:[Ph()]),[y,k]=a.useState(null),S=v.length>1,_=a.useMemo(()=>y??r??null,[y,r]);function N(M,T){x(U=>U.map((q,D)=>D===M?{...q,...T}:q))}function A(M){x(T=>T.length<=1?T:T.filter((U,q)=>q!==M))}function C(){if(!l.trim())return"Provider ID is required.";if(!xP.test(l.trim()))return"Provider ID must be kebab-case.";if(!o&&bP.has(l.trim()))return"Provider ID conflicts with a built-in provider.";if(!m.trim())return"Base URL is required.";try{const M=new URL(m.trim());if(M.protocol!=="http:"&&M.protocol!=="https:")return"Base URL must use http or https."}catch{return"Base URL must be a valid URL."}return Th.includes(f)?v.length===0?"At least one model is required.":v.some(M=>!M.id?.trim())?"Each model must have a model ID.":null:"API type is required."}async function z(M){M.preventDefault();const T=C();k(T),!T&&await n({id:l.trim(),name:u.trim()||void 0,baseUrl:m.trim(),api:f,apiKey:g.trim()||void 0,models:v.map(U=>({id:U.id.trim(),name:U.name?.trim()||void 0,reasoning:!!U.reasoning,contextWindow:U.contextWindow,maxTokens:U.maxTokens}))})}return t.jsxs("form",{onSubmit:z,className:"custom-provider-form","aria-label":"custom-provider-form",children:[t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-id",children:"Provider ID"}),t.jsx("input",{id:"custom-provider-id",className:"input",value:l,onChange:M=>c(M.target.value),disabled:o||i})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-name",children:"Display Name"}),t.jsx("input",{id:"custom-provider-name",className:"input",value:u,onChange:M=>d(M.target.value),disabled:i})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-base-url",children:"Base URL"}),t.jsx("input",{id:"custom-provider-base-url",className:"input",value:m,onChange:M=>h(M.target.value),disabled:i})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-api",children:"API Type"}),t.jsx("select",{id:"custom-provider-api",className:"select",value:f,onChange:M=>p(M.target.value),disabled:i,children:Th.map(M=>t.jsx("option",{value:M,children:M},M))})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-api-key",children:"API Key"}),t.jsx("input",{id:"custom-provider-api-key",className:"input",placeholder:"sk-..., MY_API_KEY, or !command",value:g,onChange:M=>b(M.target.value),disabled:i})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{children:"Models"}),t.jsx("div",{className:"custom-provider-form__models",children:v.map((M,T)=>t.jsxs("div",{className:"custom-provider-form__model-row",children:[t.jsx("input",{className:"input","aria-label":`Model ID ${T+1}`,placeholder:"Model ID",value:M.id,onChange:U=>N(T,{id:U.target.value}),disabled:i}),t.jsx("input",{className:"input","aria-label":`Model name ${T+1}`,placeholder:"Display name",value:M.name??"",onChange:U=>N(T,{name:U.target.value}),disabled:i}),t.jsxs("label",{className:"checkbox-label custom-provider-form__toggle",children:[t.jsx("input",{type:"checkbox",checked:!!M.reasoning,onChange:U=>N(T,{reasoning:U.target.checked}),disabled:i}),"Reasoning"]}),t.jsx("input",{className:"input","aria-label":`Context window ${T+1}`,placeholder:"Context window",type:"number",value:M.contextWindow??"",onChange:U=>N(T,{contextWindow:U.target.value?Number(U.target.value):void 0}),disabled:i}),t.jsx("input",{className:"input","aria-label":`Max tokens ${T+1}`,placeholder:"Max tokens",type:"number",value:M.maxTokens??"",onChange:U=>N(T,{maxTokens:U.target.value?Number(U.target.value):void 0}),disabled:i}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>A(T),disabled:i||!S,"aria-label":`Remove model ${T+1}`,children:"×"})]},`${T}-model`))}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>x(M=>[...M,Ph()]),disabled:i,children:"+ Add model"})]}),_?t.jsx("div",{className:"form-error",children:_}):null,t.jsxs("div",{className:"custom-provider-form__actions",children:[s?t.jsx("button",{type:"button",className:"btn",onClick:s,disabled:i,children:"Cancel"}):null,t.jsx("button",{type:"submit",className:"btn btn-primary",disabled:i,children:i?"Saving...":"Save Provider"})]})]})}const Gi="fusion_model_onboarding_state",Na=[],Sa=[],Uo=!1,Bo=!1,Ca={},yP=void 0,ki=["ai-setup","github","project-setup","first-task"],jP={"ai-setup":"AI Setup",github:"GitHub","project-setup":"Project","first-task":"First Task",complete:"Complete"};function As(){if(typeof window>"u")return null;try{const e=localStorage.getItem(Gi);if(!e)return null;const n=JSON.parse(e);return n&&typeof n=="object"&&"currentStep"in n&&typeof n.currentStep=="string"?kP(n):null}catch{return null}}function kP(e){const n=e.postOnboardingDismissedAt??yP;return{...e,completedSteps:e.completedSteps??Na,skippedSteps:e.skippedSteps??Sa,dismissed:e.dismissed??Uo,completed:e.completed??Bo,stepData:e.stepData??Ca,...n?{postOnboardingDismissedAt:n}:{}}}function vo(e,n){if(!(typeof window>"u")){if(!n){const s={currentStep:e,updatedAt:new Date().toISOString(),completedSteps:Na,skippedSteps:Sa,dismissed:Uo,completed:Bo,stepData:Ca};try{localStorage.setItem(Gi,JSON.stringify(s))}catch{}return}try{const s=As(),i=new Date().toISOString(),r=n.completed??Bo;let o=n.dismissed??Uo;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(Gi,JSON.stringify(d))}catch{}}}function wP(e){if(!(typeof window>"u"))try{const n=As(),s=new Date().toISOString();if(!n){const o={currentStep:e,updatedAt:s,completedSteps:Na,skippedSteps:[e],dismissed:Uo,completed:Bo,stepData:Ca};localStorage.setItem(Gi,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(Gi,JSON.stringify(r))}catch{}}function Ih(){if(!(typeof window>"u"))try{const e=As(),n=new Date().toISOString(),s=e?{...e,completedAt:n,completed:!0,dismissed:!1,updatedAt:n}:{currentStep:"complete",updatedAt:n,completedAt:n,completedSteps:Na,skippedSteps:Sa,dismissed:!1,completed:!0,stepData:Ca};localStorage.setItem(Gi,JSON.stringify(s))}catch{}}function Ea(){const e=As();return e?e.completed===!0?!0:typeof e.completedAt=="string"&&e.completedAt.length>0:!1}function NP(){if(!(typeof window>"u"))try{const e=As(),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(Gi,JSON.stringify(s))}catch{}}function kg(){const e=As();return e?typeof e.postOnboardingDismissedAt=="string"&&e.postOnboardingDismissedAt.length>0:!1}function SP(){const e=As();return!e||Ea()?!1:e.currentStep!=="complete"}function CP(){const e=As();if(!e||Ea()||e.currentStep==="complete")return null;const n=e.currentStep,s=jP[n]??MP(e.currentStep);return{currentStep:e.currentStep,label:s,completedSteps:e.completedSteps}}function EP(){const e=As();return e?e.skippedSteps:Sa}function _P(e){const n=As();return!n||!n.stepData?null:n.stepData[e]??null}function MP(e){return e.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const wg="fusion_onboarding_events",$h="fusion_onboarding_session_id",AP=200,RP=50;function Is(e,n={}){if(!(typeof window>"u"))try{const s=PP(),i=DP(n.step),r={type:e,timestamp:new Date().toISOString(),...i?{step:i}:{},metadata:n,sessionId:TP()},o=$P([...s,r]);IP(o)}catch{}}function TP(){if(typeof window>"u")return"server-session";try{const e=sessionStorage.getItem($h);if(e)return e;const n=Dh();return sessionStorage.setItem($h,n),n}catch{return Dh()}}function Dh(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function PP(){try{const e=localStorage.getItem(wg);if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(LP):[]}catch{return[]}}function IP(e){try{localStorage.setItem(wg,JSON.stringify(e))}catch{}}function $P(e){const n=[...e];for(;n.length>AP;)n.splice(0,RP);return n}function DP(e){if(e==="ai-setup"||e==="github"||e==="first-task"||e==="complete")return e}function LP(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 zP=e=>({id:e.id,name:e.name,baseUrl:e.baseUrl,api:"api"in e?e.api:e.apiType==="anthropic-compatible"?"anthropic-messages":"openai-responses",apiKey:e.apiKey,models:e.models?.map(n=>({id:n.id,name:n.name}))??[]}),FP={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"}}},Ng={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:"..."}},OP={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},Lh={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 ed(e){if(Lh[e])return Lh[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 gc=["anthropic","openai","google","gemini","ollama"],UP=["anthropic","claude-cli","droid-cli","openai-codex","gemini","minimax","kimi","zai"],BP={anthropic:"anthropic","claude-cli":"claude-cli","droid-cli":"droid-cli","openai-codex":"openai-codex",google:"gemini",gemini:"gemini",minimax:"minimax",kimi:"kimi",moonshot:"kimi","kimi-coding":"kimi",zai:"zai"},HP={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function td(e){return BP[e]??e}function zh(e){const n=td(e),s=UP.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function Fh(e,n){if(e.authenticated!==n.authenticated)return e.authenticated?-1:1;const s=zh(e.id),i=zh(n.id);if(s!==i)return s-i;const r=td(e.id),o=td(n.id);if(r!==o)return r.localeCompare(o);const l=HP[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 qP(e,n){const s=n.trim();if(!s)return"API key is required";const i=Ng[e]??OP;return i.pattern.test(s)?null:`${ed(e)} keys should follow this format: ${i.hint} (e.g. ${i.example})`}const Sg={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"},VP={description:"AI provider — connect to start using AI models",apiKeyInfo:Sg};function nd(e){return FP[e]??VP}function WP(e){return nd(e.id).apiKeyInfo??Sg}function si({summary:e,children:n,className:s=""}){const[i,r]=a.useState(!1);return t.jsxs("div",{className:`onboarding-disclosure ${s}`,children:[t.jsxs("button",{className:"onboarding-disclosure-trigger",onClick:()=>r(!i),"aria-expanded":i,type:"button",children:[t.jsx(kn,{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 KP({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 GP({provider:e,apiKeyInfo:n,inputValue:s,isSaving:i,error:r,success:o,isConnected:l,onInputChange:c,onSave:u,onClear:d}){const m=`onboarding-apikey-input-${e.id}`,h=i||!s.trim(),f=Ng[e.id],p=`input onboarding-apikey-input${r?" onboarding-apikey-input--error":""}${o?" onboarding-apikey-input--success":""}`,g=t.jsxs(t.Fragment,{children:[f&&t.jsxs("small",{className:"onboarding-apikey-hint",children:["Format: ",f.hint]}),t.jsx("p",{className:"onboarding-apikey-instructions",children:n.setupInstructions}),n.dashboardUrl&&t.jsx("a",{href:n.dashboardUrl,target:"_blank",rel:"noreferrer",className:"onboarding-apikey-dashboard-link",children:"Get your API key →"}),t.jsx("p",{className:"onboarding-apikey-usage",children:n.usageDescription})]});return l?t.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${e.id}`,children:[t.jsxs("div",{className:"onboarding-apikey-connected-header",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:n.fieldLabel}),t.jsx("span",{className:"auth-status-badge connected",children:"✓ API key saved"})]}),t.jsx("button",{className:"btn btn-sm",onClick:()=>d(e.id),disabled:i,children:i?"Removing…":"Remove Key"}),t.jsx(si,{summary:"Advanced setup details",children:g}),r&&t.jsx("small",{className:"field-error",children:r})]}):t.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${e.id}`,children:[t.jsx("label",{htmlFor:m,className:"onboarding-apikey-field-label",children:n.fieldLabel}),t.jsxs("div",{className:"onboarding-apikey-input-row",children:[t.jsx("input",{id:m,type:"password",className:p,placeholder:n.inputPlaceholder??"Enter API key",value:s,onChange:b=>c(e.id,b.target.value),onKeyDown:b=>{b.key==="Enter"&&u(e.id,s)},"data-testid":m}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>u(e.id,s),disabled:h,"data-testid":`onboarding-apikey-save-${e.id}`,children:i?"Saving…":"Save"})]}),r&&t.jsx("small",{className:"field-error",children:r}),o&&!r&&t.jsx("small",{className:"onboarding-apikey-success","data-testid":`onboarding-apikey-success-${e.id}`,children:o}),t.jsx(si,{summary:"Advanced setup details",children:g})]})}const JP=150;function YP({onComplete:e,addToast:n,projectId:s,onOpenSetupWizard:i,onOpenNewTask:r,onOpenGitHubImport:o,firstCreatedTask:l,onViewTask:c}){const u=As(),d=u?.currentStep,m=d==="complete"?"ai-setup":ki.includes(d)?d:"ai-setup",h=u?.completedSteps??[],f=u?.skippedSteps??EP(),[p,g]=a.useState(!0),[b,v]=a.useState(m),[x,y]=a.useState(h),[k,S]=a.useState(f),[_,N]=a.useState(!1),[A,C]=a.useState(""),[z,M]=a.useState(!1),[T,U]=a.useState(null),[q,D]=a.useState(null),[R,F]=a.useState([]),[V,K]=a.useState(void 0),[ee,E]=a.useState(!0),[$,P]=a.useState(null),[w,O]=a.useState({}),[Z,Ne]=a.useState([]),[se,le]=a.useState(""),[we,L]=a.useState(!1),[ne,Q]=a.useState({}),[be,de]=a.useState({}),[me,ie]=a.useState({}),[xe,Re]=a.useState([]),[Oe,nt]=a.useState(!1),[et,Ze]=a.useState(!1),[rt,He]=a.useState(),Ge=a.useRef({}),oe=a.useRef(null),je=a.useRef(null),X=a.useRef(null),[Ae,Te]=a.useState({}),[pe,_e]=a.useState(()=>As()?.stepData?.github?.skipped===!0),Fe=a.useRef(0),it=a.useRef(l),ve=a.useRef(!1),ce=u?.currentStep,Ie=!!u&&u.currentStep!=="complete";ci(je,p,"fusion:model-onboarding-modal-size"),a.useEffect(()=>{const W=oe.current;W&&(W.scrollTop=0)},[b]);const[he,Me]=a.useState(()=>As()?.stepData?.["ai-setup"]?.skippedProviders??{}),Je=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"project-setup",label:"Project"},{key:"first-task",label:"First Task"}],$e=Je.findIndex(W=>W.key===b),ft=b==="complete"?Je.length:$e;a.useEffect(()=>{b!=="complete"&&vo(b,{completedSteps:x,skippedSteps:k})},[b,x,k]),a.useEffect(()=>{ve.current||(ve.current=!0,Is("onboarding:wizard-opened",{source:Ie?"resume":"initial",resumedFromStep:ce}))},[Ie,ce]),a.useEffect(()=>{const W=it.current!=null,Le=l!=null;!W&&Le&&N(!0),Le||N(!1),it.current=l},[l]);const J=a.useRef(m);a.useEffect(()=>{if(J.current==="ai-setup"&&b!=="ai-setup"&&!R.some(Le=>Le.id!=="github"&&Le.authenticated)){const Le={};for(const Qe of R)Qe.id!=="github"&&!Qe.authenticated&&!he[Qe.id]&&(Le[Qe.id]=!0);if(Object.keys(Le).length>0){const Qe={...he,...Le};Me(Qe),vo(b,{stepData:{"ai-setup":{skippedProviders:Qe}}})}}J.current=b},[b,R,he]);const re=a.useCallback(async()=>{try{const{providers:W,ghCli:Le}=await wr();F(W),K(Le),O(Qe=>{const ot={};for(const[vt,_t]of Object.entries(Qe)){const Ht=W.find(Fn=>Fn.id===vt);Ht&&!Ht.authenticated&&Ht.loginInProgress&&(ot[vt]=_t)}return Object.keys(ot).length===Object.keys(Qe).length?Qe:ot}),Te(Qe=>{let ot=!1;const vt={...Qe};for(const[_t,Ht]of Object.entries(Qe)){if(Ht!=="pending")continue;W.find(ds=>ds.id===_t)?.loginInProgress||(delete vt[_t],ot=!0)}return ot?vt:Qe}),Me(Qe=>{const ot={...Qe};for(const vt of W)vt.authenticated&&ot[vt.id]&&delete ot[vt.id];return Object.keys(ot).length===Object.keys(Qe).length?Qe:ot})}catch{}},[]),ye=a.useCallback(async()=>{try{const W=await Cy();Re((W.providers??[]).map(zP))}catch{}},[]),at=a.useCallback(async W=>{Ze(!0),He(void 0);try{await _y(W),await ye(),await fs().then(Le=>Ne(Le.models??[])),nt(!1)}catch(Le){He(ke(Le)||"Failed to create custom provider")}finally{Ze(!1)}},[ye]),te=a.useRef(!1);a.useEffect(()=>{b==="ai-setup"&&ye(),te.current&&re(),te.current=b!=="ai-setup"},[b,re,ye]),a.useEffect(()=>{if(!R.some(Qe=>Qe.loginInProgress))return;const Le=setInterval(()=>{re()},2e3);return()=>clearInterval(Le)},[R,re]);const Ye=R.find(W=>W.id==="github"),mt=!!Ye,ht=Ye?.authenticated??!1,xt=Ye?.loginInProgress??!1,St=V?.authenticated??!1,bt=ht||St,Nt=!ht&&St,Qt=a.useCallback(W=>{if(W.authenticated)return"connected";const Le=Ae?.[W.id];return Le==="timeout"||Le==="failed"?"retry":he[W.id]?"skipped":"not-connected"},[Ae,he]);function Pt({status:W}){const Le={connected:{text:"✓ Connected",className:"auth-status-badge connected"},"not-connected":{text:"Not connected",className:"auth-status-badge not-connected"},skipped:{text:"Skipped",className:"auth-status-badge skipped"},retry:{text:"Retry",className:"auth-status-badge retry"}},{text:Qe,className:ot}=Le[W];return t.jsx("span",{"data-testid":"provider-status-badge",className:ot,"data-status":W,children:Qe})}const Dt=a.useCallback(()=>{if(bt)return"connected";const W=Ae.github;return W==="pending"?"pending":W==="failed"||W==="timeout"?"failed":pe?"skipped":"not-connected"},[bt,Ae,pe]);function Et({status:W}){const Le={connected:{text:"✓ Connected",className:"auth-status-badge connected"},pending:{text:"⏳ Connecting…",className:"auth-status-badge pending"},failed:{text:"✗ Connection failed",className:"auth-status-badge retry"},skipped:{text:"Skipped",className:"auth-status-badge skipped"},"not-connected":{text:"Not connected",className:"auth-status-badge not-connected"}},{text:Qe,className:ot}=Le[W];return t.jsx("span",{"data-testid":"github-status-badge",className:ot,"data-status":W,children:Qe})}const Xt=a.useCallback(async()=>{try{const W=await fs();Ne(W.models)}catch{}},[]),Lt=a.useCallback(async()=>{try{const W=await Ji();if(W.defaultProvider&&W.defaultModelId){const Le=`${W.defaultProvider}/${W.defaultModelId}`;le(Le)}}catch{}},[]);a.useEffect(()=>{Promise.all([re(),Xt(),Lt()]).finally(()=>E(!1))},[re,Xt,Lt]),a.useEffect(()=>{const W=_P("ai-setup");if(W?.loginOutcomes){const Le=W.loginOutcomes,Qe={};for(const[ot,vt]of Object.entries(Le))vt!=="pending"&&(Qe[ot]=vt);Object.keys(Qe).length>0&&Te(Qe)}},[]);const Ft=a.useCallback((W,Le)=>{vo(b,{completedSteps:x,stepData:{"ai-setup":{loginOutcomes:{[W]:Le}}}})},[b,x]);a.useEffect(()=>{const W=Object.entries(Ae).filter(([Le,Qe])=>Qe!=="pending");for(const[Le,Qe]of W)Ft(Le,Qe)},[Ae,Ft]),a.useEffect(()=>()=>{X.current&&clearInterval(X.current),Object.values(Ge.current).forEach(clearTimeout),Ge.current={}},[]);const zt=a.useCallback(W=>{_e(W),vo(b,{completedSteps:x,stepData:{github:{skipped:W}}})},[b,x]),Tt=a.useCallback(W=>W==="complete"?-1:ki.indexOf(W),[]),Gt=a.useCallback(()=>{y(Le=>[...new Set([...Le,b])]),S(Le=>Le.filter(Qe=>Qe!==b)),Is("onboarding:step-completed",{step:b}),b==="github"&&!ht&&zt(!1);const W=Tt(b);W>=0&&W<ki.length-1&&v(ki[W+1])},[b,ht,zt,Tt]),Ot=a.useCallback(()=>{S(Le=>[...new Set([...Le,b])]),wP(b),Is("onboarding:step-skipped",{step:b}),b==="github"&&!ht&&zt(!0);const W=Tt(b);W>=0&&W<ki.length-1&&v(ki[W+1])},[b,ht,zt,Tt]),qt=a.useCallback(()=>{const W=b;y(Qe=>Qe.filter(ot=>ot!==W)),S(Qe=>Qe.filter(ot=>ot!==W)),W==="github"&&!ht&&zt(!1);const Le=Tt(b);Le>0&&v(ki[Le-1])},[b,ht,zt,Tt]),nn=a.useCallback(()=>{Ot()},[Ot]),ge=a.useCallback(async W=>{Te(Le=>{const Qe=Le[W];if(Qe&&Qe!=="pending"){const{[W]:ot,...vt}=Le;return vt}return Le}),O(Le=>{if(!(W in Le))return Le;const Qe={...Le};return delete Qe[W],Qe}),Te(Le=>({...Le,[W]:"pending"})),P(W),Fe.current=0;try{const{url:Le,instructions:Qe}=await My(W);Qe?.trim()&&O(ot=>({...ot,[W]:Qe})),window.open(ri(Le),"_blank"),X.current=setInterval(async()=>{if(Fe.current++,Fe.current>=JP){X.current&&(clearInterval(X.current),X.current=null),P(null),Te(ot=>({...ot,[W]:"timeout"})),O(ot=>{if(!(W in ot))return ot;const vt={...ot};return delete vt[W],vt}),n("Login timed out. Please try again.","warning");return}try{const{providers:ot,ghCli:vt}=await wr();F(ot),K(vt),ot.find(Ht=>Ht.id===W)?.authenticated&&(X.current&&(clearInterval(X.current),X.current=null),P(null),Te(Ht=>({...Ht,[W]:"success"})),O(Ht=>{if(!(W in Ht))return Ht;const Fn={...Ht};return delete Fn[W],Fn}),W==="github"&&zt(!1),n("Login successful","success"))}catch{}},2e3)}catch(Le){Le instanceof Error&&Le.message.includes("already in progress")||Le&&typeof Le=="object"&&"status"in Le&&Le.status===409?(n("Login already in progress. Cancel it to retry.","warning"),Te(ot=>({...ot,[W]:"pending"})),re()):(n(Le instanceof Error?Le.message:"Login failed","error"),Te(ot=>({...ot,[W]:"failed"}))),P(null),O(ot=>{if(!(W in ot))return ot;const vt={...ot};return delete vt[W],vt})}},[n,re,zt]),ze=a.useCallback(async W=>{X.current&&(clearInterval(X.current),X.current=null),P(W),Fe.current=0;try{await Ry(W),await re(),Te(Le=>({...Le,[W]:"cancelled"})),n("Login cancelled","success")}catch(Le){n(ke(Le)||"Failed to cancel login","error")}finally{P(null),O(Le=>{if(!(W in Le))return Le;const Qe={...Le};return delete Qe[W],Qe})}},[n,re]),dt=a.useCallback((W,Le)=>{Q(ot=>({...ot,[W]:Le}));const Qe=Ge.current[W];Qe&&(clearTimeout(Qe),delete Ge.current[W]),de(ot=>{if(!ot[W])return ot;const vt={...ot};return delete vt[W],vt}),ie(ot=>{if(!ot[W])return ot;const vt={...ot};return delete vt[W],vt})},[]),j=a.useCallback(()=>{const W=oe.current;if(!W)return;const Le=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof W.scrollTo=="function"){W.scrollTo({top:0,behavior:Le?"auto":"smooth"});return}}catch{}W.scrollTop=0},[]),Y=a.useCallback(async(W,Le)=>{const Qe=(Le??ne[W]??"").trim(),ot=qP(W,Qe);if(ot){de(_t=>({..._t,[W]:ot}));return}const vt=Ge.current[W];vt&&(clearTimeout(vt),delete Ge.current[W]),P(W),de(_t=>{const Ht={..._t};return delete Ht[W],Ht}),ie(_t=>{if(!_t[W])return _t;const Ht={..._t};return delete Ht[W],Ht});try{await Ty(W,Qe),await re(),j(),Q(_t=>{const Ht={..._t};return delete Ht[W],Ht}),de(_t=>{if(!_t[W])return _t;const Ht={..._t};return delete Ht[W],Ht}),ie(_t=>({..._t,[W]:"✓ Key saved"})),Ge.current[W]=setTimeout(()=>{ie(_t=>{if(!_t[W])return _t;const Ht={..._t};return delete Ht[W],Ht}),delete Ge.current[W]},3e3),n("API key saved","success")}catch(_t){const Ht=_t instanceof TypeError&&_t.message.includes("Failed to fetch")?"Could not reach the server. Check your connection and try again.":_t instanceof Error?_t.message:"Failed to save API key";de(Fn=>({...Fn,[W]:Ht})),ie(Fn=>{if(!Fn[W])return Fn;const ds={...Fn};return delete ds[W],ds}),n(Ht,"error")}finally{P(null)}},[ne,n,re,j]),fe=a.useCallback(async W=>{P(W);try{await Py(W),await re(),n("API key removed","success")}catch(Le){n(Le instanceof Error?Le.message:"Failed to clear API key","error")}finally{P(null)}},[n,re]),Pe=a.useCallback(async W=>{P(W);try{await Ay(W),await re(),n("Logged out","success")}catch(Le){n(Le instanceof Error?Le.message:"Logout failed","error")}finally{P(null)}},[n,re]),We=a.useCallback(W=>{le(W)},[]),gt=a.useCallback(async()=>{try{const W={modelOnboardingComplete:!0};if(se){const Le=se.indexOf("/"),Qe=Le!==-1?se.slice(0,Le):void 0,ot=Le!==-1?se.slice(Le+1):se,vt=Z.find(_t=>_t.id===ot);vt?(W.defaultProvider=vt.provider,W.defaultModelId=vt.id):Qe&&ot&&(W.defaultProvider=Qe,W.defaultModelId=ot)}await gn(W),Ih()}catch{}},[se,Z,gn,Ih]),Mt=a.useCallback(async()=>{const W=[...new Set([...x,"first-task"])];L(!0);try{await gt(),Is("onboarding:completed",{completedSteps:W,skippedSteps:k}),y(W),S(Le=>Le.filter(Qe=>Qe!=="first-task")),v("complete")}finally{L(!1)}},[gt,x,k]),cn=a.useCallback(async()=>{if(!s)return;const W=A.trim();if(!W){U("Please enter a task description.");return}U(null),M(!0);let Le=!1;try{const Qe=await bp({description:W,source:{sourceType:"dashboard_ui"}},s);D(Qe),N(!0),Is("onboarding:first-task-created",{taskId:Qe?.id}),n("Task created","success"),Le=!0}catch(Qe){const ot=Qe instanceof Error?Qe.message:"Something went wrong creating your task. Please try again.";U(ot),n(ot,"error")}finally{M(!1)}Le&>()},[s,A,n,gt]),bn=a.useCallback(async()=>{L(!0);try{await gt()}finally{L(!1)}Is("onboarding:open-new-task",{}),r?.()},[gt,r]),rn=a.useCallback(async()=>{if(bt){L(!0);try{await gt()}finally{L(!1)}g(!1),e(),Is("onboarding:open-github-import",{}),o?.()}},[gt,bt,e,o]),Jt=a.useCallback(async()=>{Is("onboarding:dismissed",{currentStep:b,completedSteps:x,skippedSteps:k}),L(!0);try{await gn({modelOnboardingComplete:!0})}catch{}g(!1),e()},[b,x,k,e]),Sn=a.useCallback(()=>{Is("onboarding:finished",{}),g(!1),e()},[e]),Se=a.useCallback(()=>{const W=l??q;W&&(gt(),c?.(W),e())},[l,q,gt,c,e]),ut=a.useCallback(()=>{gt(),e()},[gt,e]);if(!p)return null;const Zt=Dt(),_n=R.filter(W=>W.id!=="github"),Nn=[..._n].sort(Fh),zn=Nn.some(W=>!W.type||W.type==="oauth"),ss=Nn.some(W=>W.type==="api_key"),Rn=_n.filter(W=>W.authenticated),ue=Rn.length>0,Ke=!!s,pt=b==="github"&&!ue,$t=(()=>{if(!se)return"";const W=se.indexOf("/"),Le=W===-1?void 0:se.slice(0,W),Qe=W===-1?se:se.slice(W+1),ot=Z.find(vt=>vt.id===Qe&&(!Le||vt.provider===Le));return ot?.name?ot.name:Le?`${ed(Le)} ${Qe}`:se})(),Vt=[];if(Ke?Vt.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):Vt.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),ue){const W=ed(Rn[0]?.id??"");Vt.push({label:"AI Provider",status:"connected",detail:`${W} connected — AI agents can work on tasks`})}else _n.length>0&&_n.some(W=>he[W.id])?Vt.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):Vt.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});bt?Vt.push({label:"GitHub",status:"connected",detail:Nt?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!mt||pe?Vt.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):Vt.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),$t&&Vt.push({label:"Default Model",status:"connected",detail:$t});const dn=l??q,Vn=dn?.description?.split(`
|
|
661
|
+
`)[0]?.trim()||dn?.title||"",$n=new Set(gc),Dn=Nn.filter(W=>$n.has(W.id)).sort((W,Le)=>{const Qe=gc.indexOf(W.id),ot=gc.indexOf(Le.id);return Qe!==ot?Qe-ot:Fh(W,Le)}),en=Nn.filter(W=>W.authenticated&&!$n.has(W.id)),Ct=Nn.filter(W=>!W.authenticated&&!$n.has(W.id)),pn=W=>{if(W.id==="droid-cli"&&W.type==="cli")return t.jsx(pP,{authenticated:W.authenticated,onToggled:()=>{re()}},W.id);if(W.id==="claude-cli"&&W.type==="cli")return t.jsx(mP,{authenticated:W.authenticated,onToggled:()=>{re()}},W.id);if(W.type==="api_key"){const Le=nd(W.id),Qe=WP(W);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${W.id}`,className:`onboarding-provider-card${W.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${W.id}`,"aria-hidden":"true",children:t.jsx(An,{provider:W.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(cp,{size:14,className:"onboarding-provider-key-icon"}),W.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:Le.description}),t.jsx(Pt,{status:Qt(W)}),W.authenticated&&W.keyHint&&t.jsxs("span",{className:"auth-key-hint",children:["Key: ",W.keyHint]})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx(GP,{provider:W,apiKeyInfo:Qe,inputValue:ne[W.id]??"",isSaving:$===W.id,error:be[W.id],success:me[W.id],isConnected:W.authenticated,onInputChange:dt,onSave:Y,onClear:fe})})]},W.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${W.id}`,className:`onboarding-provider-card${W.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${W.id}`,"aria-hidden":"true",children:t.jsx(An,{provider:W.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:W.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:nd(W.id).description}),t.jsx(Pt,{status:Qt(W)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:$===W.id?W.authenticated?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void ze(W.id),children:"Cancel"})]}):W.loginInProgress?t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void ze(W.id),children:"Cancel"})]}):W.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>Pe(W.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>ge(W.id),children:"Login"})}),($===W.id||W.loginInProgress)&&w[W.id]&&t.jsx(fc,{instructions:w[W.id],"data-testid":`onboarding-login-instructions-${W.id}`}),Ae[W.id]==="timeout"&&$!==W.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),Ae[W.id]==="failed"&&$!==W.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},W.id)};return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"onboarding-title",children:t.jsxs("div",{className:"modal model-onboarding-modal",ref:je,children:[t.jsxs("div",{className:"model-onboarding-header",children:[t.jsxs("h2",{id:"onboarding-title",className:"model-onboarding-title",children:[b==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(Yn,{size:24})," Set Up AI ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),b==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(Es,{size:24})," Connect GitHub ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),b==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(Hd,{size:24})," Set Up Your Project"]}),b==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(Hd,{size:24})," Create Your First Task"]}),b==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx(wn,{size:24})," All Set!"]})]}),b!=="complete"&&t.jsx("button",{className:"modal-close",onClick:Jt,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(Kt,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:Je.map((W,Le)=>{const Qe=ft>Le,ot=x.includes(W.key)&&Qe,vt=k.includes(W.key)&&!x.includes(W.key)&&Qe,_t=ot||vt;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[Le>0&&t.jsx("div",{className:`model-onboarding-step-connector ${Le<=ft?"done":""}`}),_t?t.jsxs("button",{className:`model-onboarding-step-indicator ${b===W.key?"active":""} ${ot?"done":""} ${vt?"skipped":""}`,onClick:()=>v(W.key),"aria-label":`Go back to ${W.label}`,title:`Review ${W.label}`,children:[t.jsx("span",{className:"step-number",children:ot?t.jsx(wn,{size:14}):vt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Le+1}),t.jsx("span",{className:"step-label",children:W.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${b===W.key?"active":""} ${ot?"done":""} ${vt?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:ot?t.jsx(wn,{size:14}):vt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Le+1}),t.jsx("span",{className:"step-label",children:W.label})]})]},W.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:oe,children:[b==="ai-setup"&&t.jsxs("div",{className:"model-onboarding-ai-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Fusion uses AI models to plan, write, and review code for you. Connect an AI provider below to get started — you can use a hosted service or enter an API key."}),t.jsx("p",{className:"onboarding-helper-text model-onboarding-primary-helper",children:"You only need one provider to get started."}),!ee&&R.length>0&&(()=>{const W=R.filter(_t=>_t.id!=="github"&&_t.authenticated).length,Le=R.filter(_t=>_t.id!=="github").length,Qe=Object.keys(he).filter(_t=>!R.find(Ht=>Ht.id===_t)?.authenticated).length;if(Le===0)return null;let ot="onboarding-provider-summary",vt="";return W>0?(ot+=" onboarding-provider-summary--connected",vt=`✓ ${W} of ${Le} provider${Le!==1?"s":""} connected`):Qe>0?(ot+=" onboarding-provider-summary--skipped",vt=`${Qe} provider${Qe!==1?"s":""} skipped`):(ot+=" onboarding-provider-summary--none",vt="No providers connected yet"),t.jsx("div",{className:ot,"data-testid":"provider-summary",children:vt})})(),t.jsx(si,{summary:"What are AI providers?",children:t.jsx("p",{className:"onboarding-helper-text",children:"AI providers like OpenAI and Anthropic power the AI capabilities in Fusion. Connecting a provider lets Fusion's agents use AI models to help with your tasks."})}),R.length>0&&!R.some(W=>W.authenticated)&&t.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),ee?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(lt,{size:24,className:"animate-spin"}),t.jsx("span",{children:"Loading providers…"})]}):R.length===0?t.jsx("div",{className:"model-onboarding-empty",children:"No AI providers are configured. Please check your Fusion configuration."}):t.jsxs(t.Fragment,{children:[t.jsxs("section",{className:"onboarding-provider-section","data-testid":"onboarding-quick-start-providers",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Quick start providers"}),Dn.length>0?t.jsx("div",{className:"model-onboarding-providers",children:Dn.map(W=>pn(W))}):t.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),en.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:en.map(W=>pn(W))})]}),t.jsxs("div",{className:"onboarding-model-section",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Default Model (Optional)"}),t.jsx("p",{className:"model-onboarding-description",children:"Pick a default model for AI tasks, or leave this blank to choose later. Models vary in speed, capability, and cost."}),t.jsx(si,{summary:"How do I choose a model?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Models vary in speed, capability, and cost. A good default is usually the latest model from your connected provider. You can always change this later in Settings."})}),Z.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(Xn,{models:Z,value:se,onChange:We,placeholder:"Select a default model…",label:"Default model"})}),se&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",Z.find(W=>W.id===se)?.name??se]})})]}),t.jsx(si,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:t.jsxs("div",{"data-testid":"onboarding-advanced-provider-settings",children:[Ct.length>0?t.jsx("div",{className:"model-onboarding-providers",children:Ct.map(W=>pn(W))}):t.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."}),xe.length>0?t.jsx("div",{className:"onboarding-custom-provider-list",children:xe.map(W=>t.jsxs("div",{className:"onboarding-custom-provider-item",children:[t.jsx(An,{provider:W.id,size:"sm"}),t.jsx("span",{children:W.name||W.id})]},W.id))}):null,Oe?t.jsx(vP,{onSave:at,onCancel:()=>{nt(!1),He(void 0)},saving:et,error:rt}):t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>nt(!0),children:"Add custom provider"})]})}),zn&&t.jsx(si,{summary:"How does login work?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Clicking Login opens the provider's website in a new tab where you sign in. Once you authorize Fusion, this page will automatically detect the connection. Your credentials are never stored in Fusion."})}),ss&&t.jsx(si,{summary:"What is an API key?",children:t.jsx("p",{className:"onboarding-helper-text",children:"An API key is a secret token that authenticates Fusion with the provider. You can find your key in the provider's dashboard under API settings. Keys are stored securely on your machine."})})]})]}),b==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[bt?t.jsx("p",{className:"model-onboarding-description",children:Nt?"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."}),!bt&&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"})]})}),pt&&t.jsxs("div",{className:"onboarding-skip-banner",role:"status",children:[t.jsx("strong",{children:"No AI provider connected"}),t.jsx("p",{children:"AI features like task planning and code generation won't be available until you connect one. You can set this up later in Settings."})]}),t.jsx(si,{summary:"What does GitHub integration do?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Without GitHub, you can still create and manage tasks manually. GitHub integration adds the ability to import issues as tasks, track pull request status alongside your work, and automatically link commits to tasks. Connect anytime from Settings → Authentication."})}),mt?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"onboarding-provider-row",children:[t.jsxs("div",{className:"onboarding-provider-info",children:[t.jsxs("strong",{children:[t.jsx(Es,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(Et,{status:Zt})})]}),ht&&($==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>Pe("github"),children:"Disconnect"}))]}),(Zt==="not-connected"||Zt==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[$==="github"||xt?t.jsxs("div",{className:"onboarding-github-connect-actions",children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void ze("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>ge("github"),children:[t.jsx(Es,{size:16}),"Connect"]}),($==="github"||xt)&&w.github&&t.jsx(fc,{instructions:w.github,"data-testid":"onboarding-login-instructions-github"})]}),Zt==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:Nt?"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."}),Zt==="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:()=>ge("github"),children:"Retry"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:nn,children:"Skip for now"})]})]}),Zt==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),Zt==="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:()=>ge("github"),children:"Connect anyway"})})]}),Zt==="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(An,{provider:"github",size:"lg"})}),Nt?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:Nt?"Continue with gh CLI auth →":"Continue without GitHub →"}),Nt&&($==="github"||xt?t.jsxs("button",{className:"btn btn-sm",disabled:!0,children:[t.jsx(lt,{size:14,className:"onboarding-spinner"}),"Waiting for OAuth login…"]}):t.jsxs("button",{className:"btn btn-sm",onClick:()=>ge("github"),children:[t.jsx(An,{provider:"github",size:"sm"}),"Connect OAuth (optional)"]}))]}),Nt&&($==="github"||xt)&&w.github&&t.jsx(fc,{instructions:w.github,"data-testid":"onboarding-login-instructions-github"})]})]}),b==="project-setup"&&t.jsxs("div",{className:"model-onboarding-project-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Choose your first project before creating or importing tasks. You can register an existing local directory or clone a GitHub repository URL through the setup wizard."}),Ke?t.jsx("div",{className:"onboarding-project-ready","data-testid":"onboarding-project-ready",role:"status",children:t.jsx("p",{children:"Project selected — task creation and imports are available."})}):t.jsxs("div",{className:"onboarding-project-prerequisite","data-testid":"onboarding-project-prerequisite",children:[t.jsx("p",{className:"onboarding-helper-text",children:"A project is required before first-task actions are available."}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:i,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"}),t.jsx("p",{className:"onboarding-helper-text",children:"In the setup wizard, pick an existing directory or paste a GitHub clone URL."})]}),t.jsx(si,{summary:"What does project setup do?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Project setup registers a workspace so Fusion knows where to read files, run commands, and track task changes."})})]}),b==="first-task"&&t.jsxs("div",{className:"model-onboarding-first-task",children:[t.jsx("p",{className:"model-onboarding-description",children:"Create your first task to start the board and launch AI execution."}),_&&dn?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx(wn,{size:56,className:"success-icon"}),t.jsx("h3",{className:"onboarding-task-created__title",children:"Your first task is ready!"}),t.jsx("div",{className:"onboarding-task-created__task-id",children:dn.id}),Vn&&t.jsx("p",{className:"onboarding-task-created__description",children:Vn}),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:Se,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:ut,children:"Go to Dashboard"})]})]}):t.jsxs(t.Fragment,{children:[Ke?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:A,onChange:W=>{C(W.target.value),U(null)},placeholder:"Example: Build a login page with email and password",rows:4}),t.jsx("div",{className:"onboarding-first-task-form__actions",children:t.jsx("button",{type:"button",className:"btn btn-primary",onClick:cn,disabled:z,"data-testid":"onboarding-first-task-submit",children:z?t.jsxs(t.Fragment,{children:[t.jsx(lt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),T&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:T}),t.jsx("p",{className:"onboarding-helper-text",children:"Your text has been preserved — fix the issue and try again."})]})]}):t.jsxs("div",{className:"onboarding-project-prerequisite","data-testid":"onboarding-project-prerequisite",children:[t.jsx("p",{className:"onboarding-helper-text",children:"A project must be selected before you can create tasks or import from GitHub."}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:i,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"})]}),t.jsx(KP,{items:Vt}),Ke&&t.jsxs(t.Fragment,{children:[t.jsx(si,{summary:"What happens when I create a task?",children:t.jsx("p",{className:"onboarding-helper-text",children:"A task describes something you want done. Fusion's AI agents will read your description and work on implementing it. You can track progress on the board and review the results."})}),t.jsxs("div",{className:"onboarding-cta-options",children:[t.jsxs("button",{className:"onboarding-cta-card primary",onClick:bn,disabled:we,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(ln,{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${bt?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:rn,disabled:we||!bt,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(Es,{size:24})}),t.jsxs("div",{className:"cta-content",children:[t.jsx("strong",{children:"Import from GitHub"}),t.jsx("span",{children:"Turn GitHub issues into tasks you can track here"}),!bt&&t.jsx("small",{className:"onboarding-cta-note",children:"Requires GitHub connection"})]})]})]}),t.jsxs("p",{className:"onboarding-skip-note",children:["You can create tasks anytime from the board, or use"," ",t.jsx("code",{children:"fn task create"})," in the terminal."]})]})]})]}),b==="complete"&&t.jsxs("div",{className:"model-onboarding-complete",children:[t.jsx(wn,{size:48,className:"success-icon"}),t.jsx("p",{children:"Setup complete! Head to the board to create your first task, or explore the dashboard to see what's available."})]})]}),t.jsxs("div",{className:"model-onboarding-footer",children:[b==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Jt,disabled:we,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Ot,children:"Skip setup →"}),t.jsx("button",{className:"btn btn-primary",onClick:Gt,children:"Next →"})]}),b==="github"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:qt,children:"← Back"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Ot,children:"Skip GitHub →"}),t.jsx("button",{className:"btn btn-primary",onClick:Gt,children:"Next →"})]}),b==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:qt,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:Gt,disabled:!Ke,children:"Next →"})]}),b==="first-task"&&!_&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:qt,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:Mt,disabled:we,children:we?t.jsxs(t.Fragment,{children:[t.jsx(lt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),b==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:Sn,children:[t.jsx(wn,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function Cg({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 QP=a.lazy(()=>hn(()=>import("./SetupWizardModal-BMJL6eNR.js"),__vite__mapDeps([12,1,13,14,15,6,7,16])).then(e=>({default:e.SetupWizardModal}))),XP=a.lazy(()=>hn(()=>import("./SettingsModal-UziTDnLh.js"),__vite__mapDeps([17,1,18,19,20,2,6,7,21])).then(e=>({default:e.SettingsModal})));function ZP(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{hn(()=>import("./SettingsModal-UziTDnLh.js"),__vite__mapDeps([17,1,18,19,20,2,6,7,21]))},{timeout:1500})}function eI({projectId:e,tasks:n,projects:s,currentProject:i,addToast:r,toasts:o,removeToast:l,modalManager:c,projectActions:u,taskHandlers:d,taskOperations:m,deepLink:h,settings:f,onSettingsClose:p,onReopenOnboarding:g}){const[b,v]=a.useState(null),x=c.detailTask?(()=>{const A=n.find(C=>C.id===c.detailTask?.id);return A?"prompt"in c.detailTask?{...c.detailTask,...A,prompt:c.detailTask.prompt,log:c.detailTask.log}:A:c.detailTask})():null,y=p??c.closeSettings,k=a.useCallback(()=>{c.openNewTask()},[c]),S=a.useCallback(()=>{c.openGitHubImport()},[c]),_=a.useCallback(A=>{v(null),c.closeModelOnboarding(),c.openDetailTask(A)},[c]),N=a.useCallback(async A=>{const C=await d.handleModalCreate(A);return c.modelOnboardingOpen&&v(C),C},[d.handleModalCreate,c.modelOnboardingOpen]);return a.useEffect(()=>{!c.modelOnboardingOpen&&b&&v(null)},[c.modelOnboardingOpen,b]),a.useEffect(()=>{ZP()},[]),t.jsxs(t.Fragment,{children:[x&&t.jsx(Ii,{children:t.jsx(qA,{task:x,projectId:e,tasks:n,onClose:h.handleDetailClose,onOpenDetail:c.openDetailTask,onMoveTask:m.moveTask,onDeleteTask:m.deleteTask,onMergeTask:m.mergeTask,onRetryTask:m.retryTask,onResetTask:m.resetTask,onDuplicateTask:m.duplicateTask,onTaskUpdated:c.updateDetailTask,addToast:r,prAuthAvailable:f.prAuthAvailable,initialTab:c.detailTaskInitialTab})}),c.settingsOpen&&t.jsx(Ii,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(XP,{onClose:y,addToast:r,initialSection:c.settingsInitialSection,projectId:e,themeMode:f.themeMode,colorTheme:f.colorTheme,onThemeModeChange:f.setThemeMode,onColorThemeChange:f.setColorTheme,dashboardFontScalePct:f.dashboardFontScalePct,onDashboardFontScaleChange:f.setDashboardFontScalePct,onReopenOnboarding:g})})}),t.jsx(WA,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:d.handleGitHubImport,tasks:n,projectId:e}),t.jsx(Ii,{children:t.jsx(YA,{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(rR,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:d.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx(_R,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx(AR,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx(XR,{initialWorkspace:c.fileBrowserWorkspace,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),t.jsx(oT,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e,anchorRect:c.usageAnchorRect}),t.jsx(DT,{isOpen:c.systemStatsOpen,onClose:c.closeSystemStats,projectId:e}),c.schedulesOpen&&t.jsx(ET,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx(Ii,{children:t.jsx(RT,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:N,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan,onSubtaskBreakdown:c.openSubtaskBreakdown})}),t.jsx(UT,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:i,onOpenTaskDetail:A=>{const C=n.find(z=>z.id===A);C&&c.openDetailTask(C)}}),t.jsx(Ii,{children:t.jsx(HT,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx(Ii,{children:t.jsx(tP,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(uP,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(a.Suspense,{fallback:null,children:t.jsx(QP,{onProjectRegistered:u.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(YP,{onComplete:u.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:u.handleAddProject,onOpenNewTask:k,onOpenGitHubImport:S,firstCreatedTask:b,onViewTask:_}),t.jsx(Cg,{toasts:o,onRemove:l})]})}function tI({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 sd=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function nI(e,n){if(n==="ready")return"done";const s=sd.findIndex(r=>r.id===n),i=sd.findIndex(r=>r.id===e);return i<s?"done":i===s?"active":"pending"}function sI({stage:e}){const[n]=a.useState(()=>Ev());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:sd.map(s=>{const i=nI(s.id,e);return t.jsxs("li",{className:`dashboard-loader__step dashboard-loader__step--${i}`,"data-testid":`dashboard-loader-step-${s.id}`,children:[t.jsx("span",{className:"dashboard-loader__step-icon","aria-hidden":"true",children:i==="done"?"✓":i==="active"?t.jsx(lt,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:s.label})]},s.id)})})]})})}const iI=5e3;function aI(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function rI(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++,Po(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 oI(e,n,s,i){const[r,o]=a.useState({globalPause:!1,enginePaused:!1,maxConcurrent:2}),[l,c]=a.useState(!0),[u,d]=a.useState(null),m=a.useRef(null),h=a.useRef(null),f=a.useCallback(async()=>{h.current&&h.current.abort(),h.current=new AbortController;try{c(!0),d(null);const v=await hk(n);o(v)}catch(v){if(v instanceof Error&&v.name==="AbortError")return;d(v instanceof Error?v.message:"Failed to fetch executor stats")}finally{c(!1)}},[n]);a.useEffect(()=>(f(),()=>{h.current&&h.current.abort()}),[f]),a.useEffect(()=>(m.current&&clearInterval(m.current),m.current=setInterval(()=>{f()},iI),()=>{m.current&&(clearInterval(m.current),m.current=null)}),[f]);const p=rI(e,s,i),g=aI(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:g,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:u,refresh:f}}const lI={planning:ai,subtask:Hi,mission_interview:ks,milestone_interview:ks,slice_interview:ks},cI={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function dI({sessions:e,generating:n,needsInput:s,onOpenSession:i,onDismissSession:r}){const{confirm:o}=Ks(),[l,c]=a.useState(!1),[u,d]=a.useState(new Set),m=a.useRef(null),h=a.useRef(new Map),f=a.useRef(null),{activeTabMap:p}=Ia(),g=a.useMemo(()=>Yi(),[]);if(a.useEffect(()=>{if(!l)return;const x=y=>{m.current&&!m.current.contains(y.target)&&c(!1)};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[l]),a.useEffect(()=>{const x=new Set,y=new Map;for(const k of e){const S=p.get(k.id),_=[k.status,k.updatedAt,S?.tabId??k.lockedByTab??"",S?.stale?"stale":"fresh"].join("|"),N=h.current.get(k.id);N&&N!==_&&x.add(k.id),y.set(k.id,_)}if(h.current=y,x.size!==0)return d(x),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{d(new Set),f.current=null},500),()=>{f.current&&(clearTimeout(f.current),f.current=null)}},[p,e]),e.length===0)return null;const b=e.length,v=s>0;return t.jsxs("div",{ref:m,className:"background-tasks-indicator",children:[t.jsxs("button",{className:`background-tasks-indicator__pill${v?" background-tasks-indicator__pill--attention":""}`,onClick:()=>c(x=>!x),title:`${b} background AI task${b!==1?"s":""}${s>0?` (${s} need${s!==1?"":"s"} input)`:""}`,children:[n>0&&t.jsx(lt,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&t.jsx(wc,{size:12}),t.jsxs("span",{children:["AI ",b]})]}),l&&t.jsxs("div",{className:"background-tasks-indicator__popover",children:[t.jsx("div",{className:"background-tasks-indicator__popover-header",children:"Background Tasks"}),t.jsx("div",{className:"background-tasks-indicator__popover-list",children:e.map(x=>{const y=lI[x.type],k=x.status==="generating",S=x.status==="awaiting_input",_=x.status==="error",N=p.get(x.id),A=N?.tabId??x.lockedByTab??null,C=!!(A&&A!==g&&!N?.stale),z=u.has(x.id);return t.jsxs("div",{className:`background-tasks-indicator__item${z?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:z?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:z?"translateY(-1px)":void 0},onClick:async()=>{C&&!await o({title:"Open Active Session",message:"This session is active in another tab. Open anyway?"})||(i(x),c(!1))},children:[_?t.jsx(ps,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--color-error)"}}):t.jsx(y,{size:14,className:"background-tasks-indicator__session-icon"}),t.jsxs("div",{className:"background-tasks-indicator__session-content",children:[t.jsx("div",{className:"background-tasks-indicator__session-title",children:x.title}),t.jsxs("div",{className:"background-tasks-indicator__session-meta",children:[_?"Failed":cI[x.type],k&&" — generating...",S&&!C&&" — needs input",S&&C&&" — active in another tab"]})]}),k&&t.jsx(lt,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),S&&!C&&t.jsx(wc,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),S&&C&&t.jsx(Ko,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),t.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:M=>{M.stopPropagation(),r(x.id)},title:"Dismiss",children:t.jsx(Kt,{size:12})})]},x.id)})})]})]})}function uI(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 mI(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:En};case"paused":return{label:"Paused",color:"var(--triage)",icon:qs};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:Yn}}}function hI({tasks:e,projectId:n,taskStuckTimeoutMs:s,backgroundSessions:i,backgroundGenerating:r,backgroundNeedsInput:o,onOpenBackgroundSession:l,onDismissBackgroundSession:c,lastFetchTimeMs:u,currentProjectPath:d,onOpenProjectDirectory:m}){const{stats:h,loading:f,error:p}=oI(e,n,s,u),[g,b]=a.useState(!1),v=a.useMemo(()=>mI(h.executorState),[h.executorState]),x=a.useMemo(()=>uI(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(ld,{size:14}),p]})}):f&&h.runningTaskCount===0?t.jsx("div",{className:"executor-status-bar executor-status-bar--loading",role:"status","aria-label":"Executor status",children:t.jsx("span",{className:"executor-status-bar__loading-text",children:"Loading..."})}):t.jsxs("div",{className:`executor-status-bar ${h.executorState==="running"?"executor-status-bar--running":""}`,role:"status","aria-label":"Executor status",children:[i&&i.length>0&&l&&c&&t.jsxs(t.Fragment,{children:[t.jsx(dI,{sessions:i,generating:r??0,needsInput:o??0,onOpenSession:l,onDismissSession:c}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--queued","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Queued"}),t.jsx("span",{className:"executor-status-bar__count",children:h.queuedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--running ${h.runningTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Running"}),t.jsx("span",{className:"executor-status-bar__count",children:h.runningTaskCount}),t.jsx("span",{className:"executor-status-bar__separator","aria-hidden":"true",children:"/"}),t.jsx("span",{className:"executor-status-bar__max",children:h.maxConcurrent})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),h.stuckTaskCount>0&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--stuck",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--stuck executor-status-bar__indicator--active","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Stuck"}),t.jsx("span",{className:"executor-status-bar__count executor-status-bar__count--error",children:h.stuckTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--blocked ${h.blockedTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Blocked"}),t.jsx("span",{className:`executor-status-bar__count ${h.blockedTaskCount>0?"executor-status-bar__count--warning":""}`,children:h.blockedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--review","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"In Review"}),t.jsx("span",{className:"executor-status-bar__count",children:h.inReviewCount})]}),d&&m&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--project-directory",children:[t.jsx("button",{className:`executor-status-bar__folder-toggle${g?" executor-status-bar__folder-toggle--active":""}`,onClick:()=>b(k=>!k),"aria-label":g?"Hide project directory":"Show project directory","aria-expanded":g,"data-testid":"executor-project-path-toggle",title:g?"Hide project directory":"Show project directory",children:t.jsx(Qn,{size:12,"aria-hidden":"true"})}),g&&t.jsx("button",{className:"executor-status-bar__project-path",onClick:m,title:d,"data-testid":"executor-project-path-link",children:d})]})]}),t.jsx("div",{className:"executor-status-bar__spacer"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--time",children:[t.jsx(Ci,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__time",children:x})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx(y,{size:12,style:{color:v.color},"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__state",style:{color:v.color},children:v.label})]})]})}const pI={planning:ai,subtask:Hi,mission_interview:ks,milestone_interview:ks,slice_interview:ks},fI={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},Li=new Set;function gI({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:i}){const[r,o]=a.useState(0),l=()=>o(g=>g+1);a.useEffect(()=>{if(Li.size===0)return;const g=new Map(e.map(v=>[v.id,v]));let b=!1;for(const v of Li){const x=g.get(v);x&&x.status!=="awaiting_input"&&x.status!=="error"&&(Li.delete(v),b=!0)}b&&l()},[e]);const c=a.useMemo(()=>e.filter(g=>(g.status==="awaiting_input"||g.status==="error")&&!Li.has(g.id)),[e,r]);if(c.length===0)return null;const u=c.filter(g=>g.status==="awaiting_input").length,d=c.filter(g=>g.status==="error").length;let m="";u>0&&d>0?m=`${u} AI session${u===1?"":"s"} need${u===1?"s":""} your input, ${d} failed`:u>0?m=`${u} AI session${u===1?"":"s"} need${u===1?"s":""} your input`:d>0&&(m=`${d} AI session${d===1?"":"s"} failed`);const h=g=>{Li.add(g),l()},f=g=>{Li.delete(g.id),l(),n(g)},p=()=>{for(const g of c)Li.add(g.id);l(),i()};return t.jsxs("section",{className:"session-notification-banner",role:"region","aria-live":"polite","aria-label":"AI sessions needing input or failed",children:[t.jsxs("div",{className:"session-notification-banner__header",children:[t.jsxs("div",{className:"session-notification-banner__headline",children:[t.jsx(ps,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:m})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[t.jsx(Kt,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Dismiss all"})]})]}),t.jsx("div",{className:"session-notification-banner__list",children:c.map(g=>{const b=pI[g.type],v=g.status==="error";return t.jsxs("article",{className:`session-notification-banner__item${v?" session-notification-banner__item--error":""}`,"data-session-type":g.type,"data-session-status":g.status,children:[t.jsxs("div",{className:"session-notification-banner__item-main",children:[v?t.jsx(ps,{size:16,className:"session-notification-banner__type-icon session-notification-banner__type-icon--error","aria-hidden":"true"}):t.jsx(b,{size:16,className:"session-notification-banner__type-icon","aria-hidden":"true"}),t.jsxs("div",{className:"session-notification-banner__text",children:[t.jsx("p",{className:"session-notification-banner__title",title:g.title,children:g.title}),t.jsx("p",{className:"session-notification-banner__meta",children:v?"Failed":fI[g.type]})]})]}),t.jsxs("div",{className:"session-notification-banner__actions",children:[t.jsx("button",{className:"session-notification-banner__resume",onClick:()=>f(g),children:v?"Retry":"Resume"}),t.jsx("button",{className:"session-notification-banner__dismiss",onClick:()=>{h(g.id),s(g.id)},"aria-label":`Dismiss ${g.title}`,children:t.jsx(Kt,{size:14,"aria-hidden":"true"})})]})]},g.id)})})]})}function bI({latestVersion:e,currentVersion:n,onDismiss:s}){return t.jsxs("div",{className:"update-available-banner",role:"status","aria-live":"polite",children:[t.jsxs("p",{className:"update-available-banner__text",children:["Update available: v",e," (current: v",n,"). Run ",t.jsx("code",{children:"npm i -g @runfusion/fusion"})," to update. "," ",t.jsx("a",{className:"update-available-banner__link",href:"https://github.com/Runfusion/Fusion/blob/main/CHANGELOG.md",target:"_blank",rel:"noreferrer",children:"Release notes"})," ","·"," ",t.jsx("a",{className:"update-available-banner__link",href:"https://runfusion.ai",target:"_blank",rel:"noreferrer",children:"Learn more"})]}),t.jsx("button",{type:"button",className:"update-available-banner__dismiss touch-target","aria-label":"Dismiss update notice",onClick:s,children:t.jsx(Kt,{size:16,"aria-hidden":"true"})})]})}function xI({onResume:e}){const n=CP();if(!n)return null;const s=n.completedSteps.length,i=ki.length,r=s>0?`${s} of ${i} step${s!==1?"s":""} complete — You're on the `:"You're on the ";return t.jsxs("section",{className:"onboarding-resume-card",role:"region","aria-label":"Resume onboarding",children:[t.jsxs("div",{className:"onboarding-resume-card__main",children:[t.jsx("div",{className:"onboarding-resume-card__icon","aria-hidden":"true",children:t.jsx(os,{size:20})}),t.jsxs("div",{className:"onboarding-resume-card__content",children:[t.jsx("h2",{className:"onboarding-resume-card__title",children:"Continue Setup"}),t.jsxs("p",{className:"onboarding-resume-card__description",children:[r,t.jsx("strong",{children:n.label})," step. Continue where you left off to complete your dashboard setup."]})]})]}),t.jsx("div",{className:"onboarding-resume-card__actions",children:t.jsxs("button",{className:"onboarding-resume-card__resume-btn btn btn-primary btn-sm",onClick:()=>{Is("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),e()},children:[t.jsx(En,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function vI({onOpenSettings:e,onOpenModelOnboarding:n}){const s=Ea(),i=kg(),[r,o]=a.useState(!0),[l,c]=a.useState(!1),[u,d]=a.useState(!1),[m,h]=a.useState({needsAiProvider:!1,needsDefaultModel:!1,needsGitHub:!1});a.useEffect(()=>{if(!s||i){o(!1);return}let x=!1;return(async()=>{try{o(!0),c(!1);const[k,S]=await Promise.all([wr(),Ji()]);if(x)return;const _=k.providers??[],N=_.find(T=>T.id==="github"),C=!_.some(T=>T.id!=="github"&&T.authenticated),z=!S.defaultProvider&&!S.defaultModelId,M=N?!N.authenticated:!1;h({needsAiProvider:C,needsDefaultModel:z,needsGitHub:M})}catch{x||c(!0)}finally{x||o(!1)}})(),()=>{x=!0}},[s,i]);const f=a.useCallback(()=>{NP(),d(!0)},[]),p=a.useCallback(()=>{n()},[n]),g=a.useCallback(()=>{e("global-models")},[e]),b=a.useCallback(()=>{e("authentication")},[e]),v=a.useMemo(()=>{const x=[];return m.needsAiProvider&&x.push({id:"ai-provider",title:"Connect AI Provider",description:"Connect an AI provider to enable AI agents for task planning and code generation",actionLabel:"Set Up AI",onAction:p,icon:Yn}),m.needsDefaultModel&&x.push({id:"default-model",title:"Select Default Model",description:"Choose a default AI model for task execution",actionLabel:"Choose Model",onAction:g,icon:cp}),m.needsGitHub&&x.push({id:"github",title:"Connect GitHub",description:"Connect GitHub to import issues and track pull requests",actionLabel:"Connect GitHub",onAction:b,icon:Es}),x},[m.needsAiProvider,m.needsDefaultModel,m.needsGitHub,b,g,p]);return!s||i||u||r||l||v.length===0?null:t.jsxs("section",{className:"post-onboarding-recommendations",role:"region","aria-label":"Setup recommendations",children:[t.jsxs("div",{className:"post-onboarding-recommendations__main",children:[t.jsx("div",{className:"post-onboarding-recommendations__icon","aria-hidden":"true",children:t.jsx(ai,{size:18,"aria-hidden":!0})}),t.jsxs("div",{className:"post-onboarding-recommendations__content",children:[t.jsx("h2",{className:"post-onboarding-recommendations__title",children:"Recommended Next Steps"}),t.jsx("p",{className:"post-onboarding-recommendations__description",children:"Complete these setup items to get the most out of Fusion."}),t.jsx("ul",{className:"post-onboarding-recommendations__list",children:v.map(x=>{const y=x.icon;return t.jsxs("li",{className:"post-onboarding-recommendations__item",children:[t.jsxs("span",{className:"post-onboarding-recommendations__item-icon","aria-hidden":"true",children:[t.jsx(ps,{size:14,"aria-hidden":!0}),t.jsx(y,{size:14,"aria-hidden":!0})]}),t.jsxs("span",{className:"post-onboarding-recommendations__item-text",children:[t.jsx("strong",{children:x.title}),t.jsx("span",{children:x.description})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-primary",onClick:x.onAction,children:x.actionLabel})]},x.id)})})]})]}),t.jsx("button",{type:"button",className:"post-onboarding-recommendations__dismiss",onClick:f,"aria-label":"Dismiss recommendations",children:t.jsx(Kt,{size:16,"aria-hidden":!0})})]})}function yI({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 bc(e){return e>99?"99+":String(e)}function jI({view:e,onChangeView:n,footerVisible:s,modalOpen:i=!1,keyboardOpen:r=!1,onOpenSettings:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:u,mailboxUnreadCount:d=0,onOpenGitManager:m,onOpenWorkflowSteps:h,onOpenSchedules:f,onOpenScripts:p,onToggleTerminal:g,onOpenFiles:b,onOpenGitHubImport:v,onOpenPlanning:x,onResumePlanning:y,activePlanningSessionCount:k=0,onOpenUsage:S,onRunScript:_,projectId:N,onViewAllProjects:A,showSkillsTab:C,experimentalFeatures:z}){const M=Ta(),[T,U]=a.useState(!1),[q,D]=a.useState(!1),[R,F]=a.useState({}),[V,K]=a.useState(!1),ee=a.useMemo(()=>Object.entries(R).sort(([L],[ne])=>L.localeCompare(ne)),[R]);a.useEffect(()=>{if(!q)return;let L=!1;return K(!0),Nr(N).then(ne=>{L||F(ne)}).catch(()=>{L||F({})}).finally(()=>{L||K(!1)}),()=>{L=!0}},[q,N]);const E=a.useCallback(()=>U(!1),[]),$=a.useCallback(L=>{E(),L?.()},[E]);if(a.useEffect(()=>{if(!T)return;const L=ne=>{ne.key==="Escape"&&U(!1)};return document.addEventListener("keydown",L),()=>document.removeEventListener("keydown",L)},[T]),M!=="mobile"||i||r)return null;const P=k>0&&y?y:x,w=!!z?.roadmap,O=!!C,Z=!!z?.todoView,Ne=w&&(!O||e==="roadmaps"),se=O&&(!w||e!=="roadmaps"),le=O&&!se,we=e==="documents"||e==="research"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||e==="todos"&&Z||e==="roadmaps"&&!Ne||e==="skills"&&!se;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(Cn,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Agents"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="missions"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-missions",role:"tab","aria-selected":e==="missions",onClick:()=>n("missions"),children:[t.jsx(ks,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Missions"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="chat"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-chat",role:"tab","aria-selected":e==="chat",onClick:()=>n("chat"),children:[t.jsx(Ni,{}),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(ba,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),d>0&&t.jsx("span",{className:"mobile-nav-tab-badge",children:bc(d)})]}),se&&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(Yn,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),Ne&&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(_c,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Roadmaps"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${we?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>U(L=>!L),children:[t.jsx(Nc,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),T&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mobile-more-sheet-backdrop",onClick:E}),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:()=>$(u),children:[t.jsx(ba,{}),t.jsx("span",{children:"Mailbox"}),d>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:bc(d)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>$(l),children:[t.jsx(Ds,{}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-system-stats",onClick:()=>$(c),children:[t.jsx(vr,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>$(m),children:[t.jsx(Ws,{}),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:()=>$(g),children:[t.jsx(pi,{}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>D(L=>!L),"aria-expanded":q,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(kn,{size:14,className:`mobile-more-chevron${q?" mobile-more-chevron--open":""}`})})]}),q&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:V?t.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[t.jsx(lt,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):ee.length>0?t.jsxs(t.Fragment,{children:[ee.map(([L,ne])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${L}`,onClick:()=>{_&&_(L,ne),E(),D(!1)},children:[t.jsx(En,{size:14}),t.jsx("span",{children:L})]},L)),p&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{E(),D(!1),p()},children:[t.jsx(Hs,{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:()=>{E(),D(!1),p()},children:[t.jsx(Hs,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-files",onClick:()=>$(b),children:[t.jsx(Qn,{}),t.jsx("span",{children:"Files"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>$(P),children:[t.jsx(ai,{}),t.jsx("span",{children:"Planning"}),k>0&&t.jsx("span",{className:"mobile-more-item-badge",children:bc(k)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>$(h),children:[t.jsx(Ac,{}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>$(f),children:[t.jsx(Ci,{}),t.jsx("span",{children:"Automation"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>$(v),children:[t.jsx(yI,{}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>$(S),children:[t.jsx(Ds,{}),t.jsx("span",{children:"Usage"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>$(A),children:[t.jsx(lp,{}),t.jsx("span",{children:"Projects"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>$(()=>n("documents")),children:[t.jsx(Bi,{}),t.jsx("span",{children:"Documents"})]}),le&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>$(()=>n("skills")),children:[t.jsx(Yn,{}),t.jsx("span",{children:"Skills"})]}),w&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-roadmaps",onClick:()=>$(()=>n("roadmaps")),children:[t.jsx(_c,{}),t.jsx("span",{children:"Roadmaps"})]}),z?.researchView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-research",onClick:()=>$(()=>n("research")),children:[t.jsx(wi,{}),t.jsx("span",{children:"Research"})]}),z?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>$(()=>n("insights")),children:[t.jsx(os,{}),t.jsx("span",{children:"Insights"})]}),z?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>$(()=>n("memory")),children:[t.jsx(Co,{}),t.jsx("span",{children:"Memory"})]}),z?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{$(()=>n("dev-server"))},children:[t.jsx(vr,{size:14}),t.jsx("span",{children:"Dev Server"})]}),Z&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-todos",onClick:()=>$(()=>n("todos")),children:[t.jsx(hp,{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:()=>$(o),children:[t.jsx(hr,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function kI({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(Cn,{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 Od="__fn_agent__";function Eg(e,n){const s=typeof e=="string"?e.trim():"",i=typeof n=="string"?n.trim():"";return!s||!i?{}:{modelProvider:s,modelId:i}}function Oh(e,n,s){const i=typeof e=="string"?e.trim():"",r=Eg(n,s),o=i||(r.modelProvider&&r.modelId?Od:"");return o?{agentId:o,...r}:null}function xc(e,n,s){const i=Eg(n,s),r=i.modelProvider??"",o=i.modelId??"";return`${e}::${r}/${o}`}function wI(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 Uh(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:wI(e.metadata),createdAt:e.createdAt}}function NI(e,n){const[s,i]=a.useState(null),[r,o]=a.useState(!1),[l,c]=a.useState([]),[u,d]=a.useState(!1),[m,h]=a.useState(!1),[f,p]=a.useState(""),[g,b]=a.useState(""),[v,x]=a.useState([]),[y,k]=a.useState(""),S=a.useRef(null),_=a.useRef(!1),N=a.useRef(null),A=a.useRef(""),C=a.useRef(null),z=a.useRef(""),M=a.useRef(null);a.useEffect(()=>{A.current=y},[y]);const T=a.useCallback(async $=>{const P={agentId:$.agentId};return $.modelProvider&&$.modelId&&(P.modelProvider=$.modelProvider,P.modelId=$.modelId),(await Mw(P,e)).session},[e]),U=a.useCallback(async($,P,w)=>{const O=Oh($,P,w);if(!O)return;const Z=xc(O.agentId,O.modelProvider,O.modelId);o(!0);try{const{session:Ne}=await _w({agentId:O.agentId,modelProvider:O.modelProvider,modelId:O.modelId},e);if(Ne)i(Ne),z.current=Z;else{const se=await T(O);i(se),z.current=Z}}catch(Ne){console.error("[useQuickChat] Failed to initialize session:",Ne),n?.("Failed to initialize chat","error")}finally{o(!1)}},[e,n,T]),q=a.useCallback(async()=>{if(s){d(!0);try{const $=await pu(s.id,{limit:50},e);c($.messages.map(Uh))}catch($){console.error("[useQuickChat] Failed to load messages:",$)}finally{d(!1)}}},[s,e]);a.useEffect(()=>{s?q():c([])},[s,q]);const D=a.useCallback(async()=>{if(s){d(!0);try{const $=await pu(s.id,{limit:50},e);c($.messages.map(Uh))}catch($){console.error("[useQuickChat] Failed to reload messages:",$)}finally{d(!1)}}},[s,e]),R=a.useCallback(async($,P,w)=>{const O=Oh($,P,w);if(!O)return;const Z=xc(O.agentId,O.modelProvider,O.modelId);M.current=O;const Ne=Z===z.current&&s;if(Ne||(S.current&&(S.current.close(),S.current=null),p(""),b(""),x([]),h(!1)),Ne){await D();return}i(null),c([]),z.current=Z,await U(O.agentId,O.modelProvider,O.modelId)},[U,D,s]),F=a.useCallback(async($,P)=>{await R(Od,$,P)},[R]),V=a.useCallback(async()=>{const $=M.current;if(!$)return;const P=xc($.agentId,$.modelProvider,$.modelId);S.current&&(S.current.close(),S.current=null),p(""),b(""),x([]),h(!1),c([]),i(null),o(!0);try{const w=await T($);i(w),z.current=P}catch(w){console.error("[useQuickChat] Failed to start a fresh session:",w),n?.("Failed to start a new chat","error")}finally{o(!1)}},[n,T]),K=a.useCallback(()=>{s&&(_.current=!0,N.current?.(),N.current=null,S.current?.close(),S.current=null,Aw(s.id,e).catch(()=>{}),h(!1),p(""),b(""),x([]))},[s,e]),ee=a.useCallback(()=>{A.current="",k("")},[]),E=a.useCallback(($,P)=>{if(!s||!$.trim()&&(!P||P.length===0))return Promise.resolve();if(m)return P&&P.length>0?Promise.reject(new Error("Cannot send attachments while a response is streaming")):(A.current=$,k($),Promise.resolve());const w=new Promise((O,Z)=>{C.current={resolve:O,reject:Z},_.current=!1,S.current&&(S.current.close(),S.current=null);const se={id:`temp-${Date.now()}`,sessionId:s.id,role:"user",content:$,createdAt:new Date().toISOString()};c(xe=>[...xe,se]),p(""),b(""),x([]),h(!0);let le="",we="",L=[],ne=null,Q=null;const be=()=>{ne=null,p(le)},de=()=>{Q=null,b(we)},me=()=>{ne!==null&&(cancelAnimationFrame(ne),ne=null),Q!==null&&(cancelAnimationFrame(Q),Q=null)};N.current=me;const ie={onThinking:xe=>{we+=xe,Q===null&&(Q=requestAnimationFrame(de))},onText:xe=>{le+=xe,ne===null&&(ne=requestAnimationFrame(be))},onToolStart:xe=>{L=[...L,{toolName:xe.toolName,args:xe.args,isError:!1,status:"running"}],x(L)},onToolEnd:xe=>{const Re=[...L];for(let Oe=Re.length-1;Oe>=0;Oe--){const nt=Re[Oe];if(nt?.toolName===xe.toolName&&nt.status==="running"){Re[Oe]={...nt,status:"completed",isError:xe.isError,result:xe.result},L=Re,x(Re);return}}L=[...Re,{toolName:xe.toolName,isError:xe.isError,result:xe.result,status:"completed"}],x(L)},onDone:xe=>{me();const Re={id:xe.messageId||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:le,thinkingOutput:we||void 0,toolCalls:L.length>0?L:void 0,createdAt:new Date().toISOString()};c(nt=>[...nt,Re]),p(""),b(""),x([]),h(!1),S.current=null,C.current?.resolve(),C.current=null;const Oe=A.current.trim();Oe&&(A.current="",k(""),E(Oe))},onError:xe=>{if(me(),p(""),b(""),x([]),h(!1),S.current=null,console.error("[useQuickChat] Stream error:",xe),n?.("Failed to get response","error"),C.current?.reject(new Error(typeof xe=="string"?xe:"Failed to get response")),C.current=null,!_.current){const Re=A.current.trim();Re&&(A.current="",k(""),E(Re))}D()}};S.current=Rw(s.id,$,ie,P,e)});return w.catch(()=>{}),w},[s,m,e,n,D]);return a.useEffect(()=>()=>{S.current&&(S.current.close(),S.current=null)},[]),a.useMemo(()=>({activeSession:s,sessionsLoading:r,messages:l,messagesLoading:u,isStreaming:m,streamingText:f,streamingThinking:g,streamingToolCalls:v,pendingMessage:y,sendMessage:E,stopStreaming:K,clearPendingMessage:ee,switchSession:R,startModelChat:F,startFreshSession:V,loadMessages:q,reloadMessages:D}),[s,r,l,u,m,f,g,v,y,E,K,ee,R,F,V,q,D])}function SI(e,n){const[s,i]=a.useState([]),[r,o]=a.useState(null),[l,c]=a.useState(!1),u=a.useCallback(async f=>{c(!0);try{const p=n?.filterState,g=p&&p!=="all"?{state:p}:void 0,b=n?.showSystemAgents??!1,v=await Ra({...g,...f,includeEphemeral:f?.includeEphemeral??b},e),x=Array.from(new Map(v.map(y=>[y.id,y])).values());i(x)}catch(p){console.error("Failed to load agents:",p)}finally{c(!1)}},[e,n?.filterState,n?.showSystemAgents]),d=a.useCallback(async()=>{try{const f=await ok(e);o(f)}catch(f){console.error("Failed to load agent stats:",f)}},[e]);a.useEffect(()=>{u(),d()},[u,d]),a.useEffect(()=>{const f=e?`?projectId=${encodeURIComponent(e)}`:"",p=()=>{u(),d()};return Gs(`/api/events${f}`,{events:{"agent:created":p,"agent:updated":p,"agent:deleted":p,"agent:stateChanged":p}})},[e,u,d]);const m=n?.showSystemAgents??!1,h=s.filter(f=>f.state!=="active"&&f.state!=="running"?!1:m||!Xw(f));return{agents:s,activeAgents:h,stats:r,isLoading:l,loadAgents:u,loadStats:d}}function CI({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=Lw(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(rp,{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 EI=200;function _I(e={}){const{projectId:n,workspace:s="project"}=e,[i,r]=a.useState(!1),[o,l]=a.useState(""),[c,u]=a.useState(-1),[d,m]=a.useState([]),[h,f]=a.useState(!1),[p,g]=a.useState(0),b=a.useRef(null),v=a.useRef(null);a.useEffect(()=>()=>{b.current&&clearTimeout(b.current),v.current?.abort()},[]);const x=a.useCallback((N,A)=>{if(A<0||A>N.length){r(!1);return}const C=z=>/[a-zA-Z0-9/_.-]/.test(z);for(let z=A-1;z>=0;z--){if(N[z]==="#")if(z===0){const M=N.slice(z+1,A);u(z),l(M),g(0),r(!0);return}else{const M=N[z-1];if(/[\s,.;:!?'"()[\]{}]/.test(M)){const T=N.slice(z+1,A);u(z),l(T),g(0),r(!0);return}r(!1);return}if(!C(N[z])){r(!1);return}}r(!1)},[]),y=a.useCallback(()=>{r(!1),l(""),u(-1),m([]),g(0),f(!1)},[]),k=a.useCallback(async N=>{if(!N.trim()){m([]),f(!1);return}v.current?.abort(),v.current=new AbortController;try{f(!0);const A=await pj(N,s,n);m(A.files),g(0)}catch(A){A.name!=="AbortError"&&m([])}finally{f(!1)}},[s,n]);a.useEffect(()=>{if(i)return b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{k(o)},EI),()=>{b.current&&clearTimeout(b.current)}},[o,i,k]);const S=a.useCallback((N,A)=>{if(!i||c<0)return A;const C=A.slice(0,c),z=A.slice(c+1),M=z.match(/[\s]|$/),T=M?M.index:z.length,U=z.slice(T);return`${C}#${N.path}${U}`},[i,c]),_=a.useCallback((N,A)=>{if(!i||d.length===0)return!1;switch(N.key){case"ArrowDown":return N.preventDefault(),g(C=>Math.min(C+1,d.length-1)),!0;case"ArrowUp":return N.preventDefault(),g(C=>Math.max(C-1,0)),!0;case"Enter":case"Tab":return d[p]?(N.preventDefault(),!0):!1;case"Escape":return N.preventDefault(),y(),!0;default:return!1}},[i,d,p,y]);return{mentionActive:i,files:d,loading:h,mentionQuery:o,selectedIndex:p,setSelectedIndex:g,detectMention:x,selectFile:S,dismissMention:y,handleKeyDown:_}}const MI=30,AI=16,RI=16;function TI(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let wo=null;function _g(){return wo===null&&(wo=window.visualViewport?.height??window.innerHeight),wo}function PI(e){const n=_g();e>n&&(wo=e)}function II(e){return e?e instanceof HTMLTextAreaElement?!0:e instanceof HTMLInputElement?!new Set(["checkbox","radio","button","submit","reset","file","range","color","hidden"]).has(e.type):e instanceof HTMLElement&&e.isContentEditable:!1}function $I(){if(typeof window>"u"||!window.visualViewport)return{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0};const e=window.visualViewport,n=II(document.activeElement),s=e.offsetTop;n||PI(e.height);const i=Math.max(0,window.innerHeight-e.offsetTop-e.height);if(i>0)return{overlap:i,open:!0,vvHeight:e.height,vvOffsetTop:s};const r=_g(),o=Math.max(0,r-e.offsetTop-e.height);if(o>=MI)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};if(o>=AI&&n)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};const l=Math.max(0,r-e.height);return n&&l>=RI?{overlap:0,open:!0,vvHeight:e.height,vvOffsetTop:s}:{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0}}function Mg({enabled:e=!0}={}){const[n,s]=a.useState(0),[i,r]=a.useState(null),[o,l]=a.useState(0),[c,u]=a.useState(!1);return a.useEffect(()=>{if(!e||!TI()){s(0),r(null),l(0),u(!1);return}const d=window.visualViewport;if(!d){s(0),r(null),l(0),u(!1);return}const m=()=>{const h=$I();s(h.overlap),r(h.vvHeight),l(h.vvOffsetTop),u(h.open)};return m(),d.addEventListener("resize",m),d.addEventListener("scroll",m),document.addEventListener("focusin",m),document.addEventListener("focusout",m),()=>{d.removeEventListener("resize",m),d.removeEventListener("scroll",m),document.removeEventListener("focusin",m),document.removeEventListener("focusout",m),s(0),r(null),l(0),u(!1)}},[e]),{keyboardOverlap:n,viewportHeight:i,viewportOffsetTop:o,keyboardOpen:c}}function DI(e){return`${e.name?.trim()||e.id} (${e.role})`}function LI(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 zI(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 No(e,n){return e.length<=n?e:`${e.slice(0,n)}…`}function FI(e){if(!e)return null;const n=Object.entries(e);return n.length===0?null:n.map(([s,i])=>{const r=typeof i=="string"?i:(()=>{try{return JSON.stringify(i)}catch{return String(i)}})();return`${s}=${No(r,50)}`}).join(", ")}function OI(e){if(e===void 0)return null;if(typeof e=="string")return No(e,200);try{return No(JSON.stringify(e),200)}catch{return No(String(e),200)}}function Ag(e,n=!1){if(!e||e.length===0)return null;const s=(f,p)=>{const g=f.status==="running",b=f.status==="completed"&&f.isError,v=FI(f.args),x=OI(f.result),y=g?v:x?`result: ${x}`:v?`args: ${v}`:null,k=n?null:y,S=g?"running":b?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${g?" chat-tool-call--running":""}${b?" chat-tool-call--error":""}`,open:g,children:[t.jsxs("summary",{children:[t.jsx("span",{className:"chat-tool-call-status-dot","aria-hidden":"true"}),t.jsx("span",{className:"chat-tool-call-name",title:f.toolName,children:f.toolName}),k&&t.jsx("span",{className:"chat-tool-call-preview",title:k,children:k}),t.jsx("span",{className:"chat-tool-call-status-text",children:S})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[v&&t.jsxs("div",{className:"chat-tool-call-row",children:[t.jsx("span",{className:"chat-tool-call-label",children:"args"}),t.jsx("span",{className:"chat-tool-call-value",children:v})]}),x&&t.jsxs("div",{className:`chat-tool-call-row${b?" chat-tool-call-row--error":""}`,children:[t.jsx("span",{className:"chat-tool-call-label",children:"result"}),t.jsx("span",{className:"chat-tool-call-value",children:x})]})]})]},`${f.toolName}-${p}`)},i=`chat-tool-calls${n?" chat-tool-calls--compact":""}`;if(e.length===1)return t.jsxs("div",{className:i,"data-testid":"chat-tool-calls",children:[t.jsxs("div",{className:"chat-tool-calls-header",children:[t.jsx(Vd,{size:12,"aria-hidden":"true"}),t.jsx("span",{children:"Tool calls"})]}),s(e[0],0)]});const r=e.filter(f=>f.status==="running").length,o=e.filter(f=>f.status==="completed"&&f.isError).length,l=r>0,c=Array.from(new Set(e.map(f=>f.toolName))),u=c.slice(0,5),d=Math.max(0,c.length-u.length),m=d>0?`${u.join(", ")}, +${d} more`:u.join(", "),h=l?`(${r} running)`:o>0?`(${o} ${o===1?"error":"errors"})`:null;return t.jsx("div",{className:i,"data-testid":"chat-tool-calls",children:t.jsxs("details",{className:`chat-tool-calls-group${n?" chat-tool-calls-group--compact":""}`,"data-testid":"chat-tool-calls-group",open:l,children:[t.jsxs("summary",{className:"chat-tool-calls-group-summary",children:[t.jsx(Vd,{size:12,"aria-hidden":"true"}),t.jsxs("span",{className:"chat-tool-calls-count",children:[e.length," tool calls"]}),t.jsx("span",{className:"chat-tool-calls-names",title:m,children:m}),h&&t.jsx("span",{className:"chat-tool-calls-group-status",children:h})]}),e.map((f,p)=>s(f,p))]})})}const Rg={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 UI(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 yo={width:320,height:400},BI=new Set(["image/png","image/jpeg","image/gif","image/webp","text/plain","application/json","text/yaml","text/x-log","text/csv","application/xml","text/markdown"]),HI=[".png",".jpg",".jpeg",".gif",".webp",".txt",".json",".yaml",".yml",".log",".csv",".xml",".md"];function qI(e){return e.type.startsWith("image/")}function VI(e){if(BI.has(e.type))return!0;const n=e.name.toLowerCase();return HI.some(s=>n.endsWith(s))}const da={width:280,height:260},as=768,ua=8;function WI(e,n){const s=a.useCallback(()=>{if(typeof window>"u")return 0;const b=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return b&&parseFloat(b)||0},[]),i=a.useCallback(()=>typeof window<"u"&&window.innerWidth<=768?{x:4,y:4+s()}:{x:24,y:24+s()},[s]),[r,o]=a.useState(()=>{if(typeof window>"u")return i();const b=`fusion-quick-chat-position-${e||"default"}`;try{const v=localStorage.getItem(b);if(v){const x=JSON.parse(v);if(typeof x.x=="number"&&typeof x.y=="number"&&!isNaN(x.x)&&!isNaN(x.y))return x}}catch{}return i()}),[l,c]=a.useState(!1),u=a.useRef(null),d=n??a.useRef(!1),m=a.useCallback(b=>{if(typeof window>"u")return b;const v=48,x=window.innerWidth<=768?4:8,y=window.innerWidth<=768?44:0,k=window.innerWidth>768?s():0,S=window.innerWidth-v-x,_=window.innerHeight-v-x-y-k;return{x:Math.max(x,Math.min(S,b.x)),y:Math.max(x,Math.min(_,b.y))}},[s]),h=a.useCallback(b=>{if(typeof window>"u")return;const v=`fusion-quick-chat-position-${e||"default"}`;try{localStorage.setItem(v,JSON.stringify(b))}catch{}},[e]),f=a.useCallback(b=>{if(b.button!==0&&b.pointerType==="mouse")return;const x=b.target.closest(".quick-chat-fab");x&&(b.preventDefault(),typeof x.setPointerCapture=="function"&&x.setPointerCapture(b.pointerId),u.current={x:r.x,y:r.y,pointerX:b.clientX,pointerY:b.clientY},d.current=!1,c(!0),document.body.style.userSelect="none")},[r]),p=a.useCallback(b=>{if(!u.current||!l)return;const v=b.clientX-u.current.pointerX,x=b.clientY-u.current.pointerY;if((Math.abs(v)>=5||Math.abs(x)>=5)&&(d.current=!0),d.current){const y=u.current.x-v,k=u.current.y-x,S=m({x:y,y:k});o(S)}},[l,m]),g=a.useCallback(b=>{if(!u.current)return;const v=b.target.closest(".quick-chat-fab");if(v&&typeof v.releasePointerCapture=="function"&&v.releasePointerCapture(b.pointerId),c(!1),document.body.style.userSelect="",!d.current){u.current=null;return}h(r),u.current=null,d.current=!1},[r,h]);return{position:r,isDragging:l,handlePointerDown:f,handlePointerMove:p,handlePointerUp:g}}function KI(e,n,s){const i=`fusion:quick-chat-size-${e||"default"}`,r=a.useCallback(()=>typeof window<"u"&&window.innerWidth>as,[]),o=a.useCallback((f,p,g)=>{if(typeof window>"u")return f;const b=Math.max(da.width,window.innerWidth-p-ua),v=Math.max(da.height,window.innerHeight-g-ua);return{width:Math.max(da.width,Math.min(b,f.width)),height:Math.max(da.height,Math.min(v,f.height))}},[]),l=a.useCallback(()=>{if(typeof window>"u"||window.innerWidth<=as)return yo;try{const f=localStorage.getItem(i);if(!f)return yo;const p=JSON.parse(f);return typeof p.width!="number"||typeof p.height!="number"?yo:{width:p.width,height:p.height}}catch{return yo}},[i]),[c,u]=a.useState(l),[d,m]=a.useState({right:0,bottom:0});a.useEffect(()=>{if(!r())return;const f={right:n+d.right,bottom:s+d.bottom};u(p=>o(p,f.right,f.bottom))},[o,r,n,s,d]),a.useEffect(()=>{if(r())try{localStorage.setItem(i,JSON.stringify(c))}catch{}},[r,c,i]);const h=a.useCallback(f=>{if(!r())return;const p=f.currentTarget.dataset.resizeDirection;if(!p)return;f.preventDefault(),f.stopPropagation();const g=f.currentTarget;typeof g.setPointerCapture=="function"&&g.setPointerCapture(f.pointerId);const b={pointerX:f.clientX,pointerY:f.clientY,width:c.width,height:c.height,anchorRight:d.right,anchorBottom:d.bottom};document.body.style.userSelect="none";const v=y=>{const k=y.clientX-b.pointerX,S=y.clientY-b.pointerY;let _=b.width,N=b.height,A=b.anchorRight,C=b.anchorBottom;if(p.includes("w")&&(_=b.width-k),p.includes("e")){const D=k;_=b.width+D,A=b.anchorRight-D}if(p.includes("n")&&(N=b.height-S),p.includes("s")){const D=S;N=b.height+D,C=b.anchorBottom-D}const z=n+A,M=s+C,T=o({width:_,height:N},z,M),U=Math.max(ua-n,Math.min(window.innerWidth-n-da.width-ua,A)),q=Math.max(ua-s,Math.min(window.innerHeight-s-da.height-ua,C));u(T),m({right:U,bottom:q})},x=y=>{typeof g.releasePointerCapture=="function"&&g.releasePointerCapture(y.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",x);try{localStorage.setItem(i,JSON.stringify({width:c.width,height:c.height}))}catch{}};document.addEventListener("pointermove",v),document.addEventListener("pointerup",x)},[d.bottom,d.right,o,s,n,r,c.height,c.width,i]);return{panelSize:c,anchorOffset:d,handleResizeStart:h}}const GI=a.memo(function({message:n,forcePlain:s,mentionAgentsByName:i,onToggleRender:r}){const o=n.role==="user",l=a.useMemo(()=>{if(!o)return null;const u=n.content,d=/@([\w-]+)/g,m=[];let h=0,f=d.exec(u);for(;f;){const[p,g=""]=f,b=f.index;b>h&&m.push(u.slice(h,b));const v=g.replace(/_/g," ").toLowerCase(),x=i.get(v);x?m.push(t.jsxs("span",{className:"chat-mention-chip",children:["@",x.name.replace(/\s+/g,"_")]},`${x.id}-${b}`)):m.push(p),h=b+p.length,f=d.exec(u)}return h<u.length&&m.push(u.slice(h)),m.length===0?u:m},[o,n.content,i]),c=a.useMemo(()=>o?null:s?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:n.content}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(oi,{remarkPlugins:[li],components:Rg,children:n.content})}),[o,s,n.content]);return t.jsxs("div",{className:`quick-chat-panel-message ${o?"quick-chat-panel-message--sent":"quick-chat-panel-message--received"}`,"data-testid":`quick-chat-message-${n.id}`,children:[o?t.jsx("p",{children:l}):t.jsxs(t.Fragment,{children:[c,t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${s?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":s?"Show rendered markdown":"Show plain text",onClick:()=>r(n.id),children:s?t.jsx(rd,{size:14}):t.jsx(Ma,{size:14})})]}),Ag(n.toolCalls,!0)]})});function JI({projectId:e,addToast:n,showFAB:s=!0,open:i,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:c,onToggleModelFavorite:u}){const{agents:d}=SI(e),[m,h]=a.useState(!1),f=i!==void 0,p=f?i:m,g=f?ue=>{r?.(typeof ue=="function"?ue(p):ue)}:h;Mg({enabled:p});const b=Ta(),[v,x]=a.useState("agent"),[y,k]=a.useState(""),[S,_]=a.useState([]),[N,A]=a.useState(!1),[C,z]=a.useState(""),[M,T]=a.useState(""),[U,q]=a.useState(""),[D,R]=a.useState(""),[F,V]=a.useState(!1),[K,ee]=a.useState(0),[E,$]=a.useState(-1),[P,w]=a.useState(()=>new Set),[O,Z]=a.useState([]),[Ne,se]=a.useState(!1),[,le]=a.useState(!1),[we,L]=a.useState({top:0,left:0}),ne=_I({projectId:e}),Q=a.useCallback(ue=>{if(!ue||!ne.mentionActive)return;const Ke=ue.getBoundingClientRect();L({top:Ke.top-260,left:Ke.left+8})},[ne.mentionActive]),be=a.useRef(!1),de=a.useRef(!1),me=a.useRef(""),ie=a.useRef(0),xe=a.useRef(null),Re=a.useRef(0),{position:Oe,isDragging:nt,handlePointerDown:et,handlePointerMove:Ze,handlePointerUp:rt}=WI(e,be),He=Oe.y+60,{panelSize:Ge,anchorOffset:oe,handleResizeStart:je}=KI(e,Oe.x,He),X=typeof window<"u"&&window.innerWidth>as,{activeSession:Ae,messages:Te,isStreaming:pe,streamingText:_e,streamingThinking:Fe,streamingToolCalls:it,sessionsLoading:ve,messagesLoading:ce,sendMessage:Ie,stopStreaming:he,pendingMessage:Me,clearPendingMessage:Je,switchSession:$e,startModelChat:ft,startFreshSession:J}=NI(e,n),re=a.useRef(null),ye=a.useRef(null),at=a.useRef(null),te=a.useRef(null),Ye=a.useRef(null),mt=a.useRef([]),ht=a.useRef(!1),xt=a.useRef(!1),St=a.useRef(!1),bt=a.useRef(null),Nt=a.useRef(!1);a.useEffect(()=>{if(!p||typeof window>"u"||typeof document>"u"||window.innerWidth>as)return;const ue=window.scrollY,Ke=document.documentElement,pt=document.body,$t={htmlOverflow:Ke.style.overflow,bodyOverflow:pt.style.overflow};return window.scrollTo(0,0),Ke.style.overflow="hidden",pt.style.overflow="hidden",()=>{Ke.style.overflow=$t.htmlOverflow,pt.style.overflow=$t.bodyOverflow,window.scrollTo(0,ue)}},[p]),a.useLayoutEffect(()=>{if(!p||typeof window>"u"||!window.visualViewport)return;const ue=re.current;if(!ue)return;const Ke=window.visualViewport,pt=()=>{Nt.current||(ue.style.setProperty("--vv-height",`${Ke.height}px`),ue.style.setProperty("--vv-offset-top",`${Ke.offsetTop||0}px`))};return pt(),Ke.addEventListener("resize",pt),Ke.addEventListener("scroll",pt),()=>{Ke.removeEventListener("resize",pt),Ke.removeEventListener("scroll",pt)}},[p]);const Qt=C||M,Pt=a.useMemo(()=>LI(Qt),[Qt]),Dt=a.useMemo(()=>S.find(ue=>`${ue.provider}/${ue.id}`===Qt)??null,[S,Qt]),Et=a.useMemo(()=>zI(Dt,Pt),[Dt,Pt]),Xt=a.useMemo(()=>v==="model"?Pt?`${Od}::${Pt.modelProvider}/${Pt.modelId}`:"":y?`${y}::`:"",[v,Pt,y]),Lt=v==="agent"?!!y:!!Pt,Ft=!Lt||!Ae;a.useEffect(()=>{if(d.length===0){k(""),x("model");return}d.some(Ke=>Ke.id===y)||k(d[0]?.id??"")},[d,y]),a.useEffect(()=>{!p||de.current||(de.current=!0,A(!0),fs().then(ue=>{const Ke=ue.models??[];if(_(Ke),C||Ke.length===0)return;const pt=ue.defaultProvider,$t=ue.defaultModelId;if(pt&&$t){const dn=`${pt}/${$t}`;if(Ke.some($n=>`${$n.provider}/${$n.id}`===dn)){T(dn),z(dn),x("model");return}}T("");const Vt=Ke[0];Vt&&z(`${Vt.provider}/${Vt.id}`)}).catch(ue=>{console.error("[QuickChatFAB] Failed to load models:",ue),_([]),T("")}).finally(()=>{A(!1)}))},[p,d.length,C]),a.useEffect(()=>{if(!p){me.current="";return}if(!Xt){me.current="";return}const ue=Xt===me.current&&!Ae&&!ve;if(!(Xt===me.current&&!ue)){if(me.current=Xt,v==="model"&&Pt){ft(Pt.modelProvider,Pt.modelId);return}v==="agent"&&y&&$e(y)}},[p,v,Pt,y,Xt,Ae,ve,ft,$e]),a.useEffect(()=>{p||(V(!1),R(""),$(-1),mt.current.forEach(ue=>{ue.previewUrl&&URL.revokeObjectURL(ue.previewUrl)}),Z([]))},[p]),a.useEffect(()=>{mt.current=O},[O]),a.useEffect(()=>{if(!p){ht.current=!1;return}typeof window>"u"||(ht.current=window.innerWidth<=as)},[p]),a.useEffect(()=>{if(!p||Ft||!ht.current)return;const ue=te.current;if(!ue)return;const Ke=document.activeElement,pt=Ke?re.current?.contains(Ke):!1,$t=Ke===document.body,Vt=Ke===bt.current;if(!pt&&!$t&&!Vt){ht.current=!1;return}if(Vt){ue.focus({preventScroll:!0}),ht.current=!1;return}const dn=requestAnimationFrame(()=>{ue.focus(),ht.current=!1});return()=>cancelAnimationFrame(dn)},[p,Ft]),a.useEffect(()=>()=>{mt.current.forEach(ue=>{ue.previewUrl&&URL.revokeObjectURL(ue.previewUrl)})},[]);const zt=a.useCallback(ue=>{k(ue)},[]),Tt=a.useCallback(ue=>{z(ue)},[]),Gt=a.useCallback(()=>{!Lt||ve||J()},[Lt,ve,J]),Ot=a.useMemo(()=>d.find(ue=>ue.id===y)??null,[d,y]),qt=a.useMemo(()=>{const ue=D.trim().toLowerCase();return ue?d.filter(Ke=>Ke.name.toLowerCase().includes(ue)):d},[d,D]),nn=a.useMemo(()=>{const ue=new Map;for(const Ke of d)ue.set(Ke.name.toLowerCase(),Ke);return ue},[d]);a.useEffect(()=>{ee(0)},[D,F]),a.useEffect(()=>()=>{xe.current!==null&&(window.clearTimeout(xe.current),xe.current=null)},[]),a.useEffect(()=>{if(!p)return;const ue=pt=>{const $t=pt.target;re.current?.contains($t)||ye.current?.contains($t)||$t.closest(".model-combobox-dropdown--portal")||g(!1)},Ke=pt=>{pt.key==="Escape"&&g(!1)};return document.addEventListener("mousedown",ue),document.addEventListener("keydown",Ke),()=>{document.removeEventListener("mousedown",ue),document.removeEventListener("keydown",Ke)}},[p,g]),a.useEffect(()=>{if(!p)return;const ue=at.current;ue&&(ue.scrollTop=ue.scrollHeight)},[Te,_e,Fe,p]);const ge=a.useMemo(()=>v==="agent"?Ot?`Message ${Ot.name||Ot.id}`:"Select an agent to start chatting":Et?`Message ${Et}`:"Select a model to start chatting",[v,Ot,Et]),ze=Me.length>50?`${Me.slice(0,50)}…`:Me,dt=a.useCallback(ue=>{if(!ue||ue.length===0)return;const Ke=[];for(let pt=0;pt<ue.length;pt+=1){const $t=ue[pt];VI($t)&&Ke.push({file:$t,previewUrl:qI($t)?URL.createObjectURL($t):""})}Ke.length>0&&Z(pt=>[...pt,...Ke])},[]),j=a.useCallback(ue=>{Z(Ke=>{const pt=Ke[ue];return pt?.previewUrl&&URL.revokeObjectURL(pt.previewUrl),Ke.filter(($t,Vt)=>Vt!==ue)})},[]),Y=a.useCallback(ue=>{dt(ue.clipboardData?.files)},[dt]),fe=a.useCallback(()=>{if(typeof window>"u"||window.innerWidth>as)return;const ue=te.current;!ue||ue.disabled||ue.focus({preventScroll:!0})},[]),Pe=a.useCallback(()=>{typeof window>"u"||window.innerWidth>as||(St.current=!0)},[]),We=a.useCallback(async()=>{const ue=U.trim(),Ke=mt.current;if(!(!ue&&Ke.length===0)&&!Ft){q(""),V(!1),R(""),$(-1);try{await Ie(ue,Ke.map(pt=>pt.file)),Ke.forEach(pt=>{pt.previewUrl&&URL.revokeObjectURL(pt.previewUrl)}),Z(pt=>pt.filter($t=>!Ke.includes($t)))}catch{}finally{fe(),St.current=!1}}},[Ie,Ft,U,fe]),gt=a.useCallback(ue=>{ue.preventDefault(),Re.current+=1,se(!0)},[]),Mt=a.useCallback(ue=>{ue.preventDefault(),ue.dataTransfer.dropEffect="copy",se(!0)},[]),cn=a.useCallback(ue=>{ue.preventDefault(),Re.current=Math.max(0,Re.current-1),Re.current===0&&se(!1)},[]),bn=a.useCallback(ue=>{ue.preventDefault(),Re.current=0,se(!1),dt(ue.dataTransfer?.files)},[dt]),rn=a.useCallback((ue,Ke)=>{const pt=UI(ue,Ke);if(pt){V(!0),R(pt.filter),$(pt.start);return}V(!1),R(""),$(-1)},[]),Jt=a.useCallback(ue=>{const Ke=te.current;if(!Ke||E<0)return;const pt=Ke.selectionStart??ie.current,$t=Ke.selectionEnd??pt,Vt=Math.max(pt,$t),dn=Math.min(E,Vt),$n=`${`@${ue.name.replace(/\s+/g,"_")}`} `,Dn=U.slice(0,dn)+$n+U.slice(Vt),en=dn+$n.length;q(Dn),V(!1),R(""),ee(0),$(-1),window.requestAnimationFrame(()=>{te.current&&(te.current.focus(),te.current.setSelectionRange(en,en))})},[E,U]),Sn=a.useCallback(ue=>{const Ke=ue.target.value,pt=ue.target.selectionStart??Ke.length;ie.current=pt,q(Ke),rn(Ke,pt),ne.detectMention(Ke,pt),le(ne.mentionActive),ne.mentionActive&&Q(ue.target)},[rn,ne,Q]),Se=a.useCallback(()=>{if(St.current){window.requestAnimationFrame(()=>{fe()});return}typeof window<"u"&&window.innerWidth<=as&&re.current&&(Nt.current=!0,re.current.style.removeProperty("--vv-height"),re.current.style.removeProperty("--vv-offset-top"),window.setTimeout(()=>{Nt.current=!1},450)),xe.current!==null&&window.clearTimeout(xe.current),xe.current=window.setTimeout(()=>{V(!1),R(""),$(-1),le(!1),ne.dismissMention(),xe.current=null},120)},[ne,fe]),ut=a.useCallback(()=>{Nt.current=!1,xe.current!==null&&(window.clearTimeout(xe.current),xe.current=null)},[]),Zt=a.useCallback(ue=>{const Ke=ue.currentTarget,pt=Ke.selectionStart??Ke.value.length;ie.current=pt,rn(Ke.value,pt),ne.detectMention(Ke.value,pt),le(ne.mentionActive),ne.mentionActive&&Q(Ke)},[rn,ne,Q]),_n=a.useCallback(ue=>{ue.key!=="Escape"&&Zt(ue)},[Zt]),Nn=a.useCallback(ue=>{w(Ke=>{const pt=new Set(Ke);return pt.has(ue)?pt.delete(ue):pt.add(ue),pt})},[]),zn=a.useCallback((ue,Ke=!1)=>Ke?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:ue}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(oi,{remarkPlugins:[li],components:Rg,children:ue})}),[]),ss=a.useCallback(ue=>{if(ie.current=ue.currentTarget.selectionStart??ie.current,ne.mentionActive&&ne.files.length>0){if(ne.handleKeyDown(ue,U),ue.key==="Enter"||ue.key==="Tab"){const Ke=ne.files[ne.selectedIndex];if(Ke){const pt=ne.selectFile(Ke,U);q(pt),ne.dismissMention(),le(!1)}}return}if(F&&ue.key==="ArrowDown"){ue.preventDefault(),qt.length>0&&ee(Ke=>(Ke+1)%qt.length);return}if(F&&ue.key==="ArrowUp"){ue.preventDefault(),qt.length>0&&ee(Ke=>Ke===0?qt.length-1:Ke-1);return}if(F&&ue.key==="Enter"){ue.preventDefault();const Ke=qt[K]??qt[0];Ke&&Jt(Ke);return}if(F&&ue.key==="Escape"){ue.preventDefault(),ue.stopPropagation(),V(!1),R(""),$(-1);return}ue.key!=="Enter"||ue.shiftKey||(ue.preventDefault(),We())},[F,qt,K,Jt,We,ne,U]),Rn=a.useCallback(()=>{if(be.current){be.current=!1;return}if(p){g(!1);return}typeof window<"u"&&window.innerWidth<=as&&bt.current?.focus({preventScroll:!0}),g(!0)},[p,g]);return t.jsxs(t.Fragment,{children:[t.jsx("input",{ref:bt,type:"text",className:"quick-chat-stealth-input","aria-hidden":"true",tabIndex:-1}),s&&t.jsx("button",{ref:ye,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":nt?"true":"false",style:{right:Oe.x,bottom:Oe.y},onPointerDown:et,onPointerMove:Ze,onPointerUp:rt,onClick:Rn,children:t.jsx(Ni,{size:24})}),p&&t.jsxs("div",{className:"quick-chat-panel",ref:re,"data-testid":"quick-chat-panel",style:{...X?{right:Oe.x+oe.right,bottom:He+oe.bottom,width:Ge.width,height:Ge.height}:{}},children:[X&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"n","data-testid":"quick-chat-resize-n",onPointerDown:je,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:je,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:je,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:je,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:je,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:je,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:je,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:je,role:"separator","aria-label":"Resize panel from bottom-right corner"})]}),t.jsxs("div",{className:"quick-chat-panel-header",children:[t.jsxs("div",{className:"quick-chat-panel-title-wrap",children:[t.jsx("h3",{children:"Quick Chat"}),v==="model"&&Et&&(()=>{const ue=Dt?.provider??Pt?.modelProvider??"";return b==="mobile"&&Et.length>12&&ue?t.jsx("span",{className:"quick-chat-model-tag quick-chat-model-tag--icon","data-testid":"quick-chat-model-tag",title:Et,"aria-label":Et,children:t.jsx(An,{provider:ue,size:"sm"})}):t.jsx("span",{className:"quick-chat-model-tag","data-testid":"quick-chat-model-tag",title:Et,children:Et})})()]}),t.jsxs("div",{className:"quick-chat-panel-header-actions",children:[d.length>0&&t.jsxs("div",{className:"quick-chat-header-mode-toggle","data-testid":"quick-chat-mode-toggle",children:[t.jsx("button",{type:"button",className:`quick-chat-mode-btn${v==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-mode-agent",onClick:()=>{x("agent"),z("")},"aria-label":"Switch to agent mode",title:"Agent mode",children:"Agent"}),t.jsx("button",{type:"button",className:`quick-chat-mode-btn${v==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-mode-model",onClick:()=>{x("model"),k("")},"aria-label":"Switch to model mode",title:"Model mode",children:"Model"})]}),t.jsx("button",{type:"button",className:"btn-icon quick-chat-new-chat-btn","data-testid":"quick-chat-new-thread","aria-label":"Start a new chat",onClick:Gt,disabled:!Lt||ve,children:t.jsx(ln,{size:16})}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":"Close quick chat","data-testid":"quick-chat-close",onClick:()=>g(!1),children:t.jsx(Kt,{size:16})})]})]}),v==="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:y,onChange:ue=>zt(ue.target.value),"data-testid":"quick-chat-agent-select",children:d.map(ue=>t.jsx("option",{value:ue.id,children:DI(ue)},ue.id))})]}),v==="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(Xn,{id:"quick-chat-model-override",models:S,value:C,onChange:Tt,label:"Select model override",placeholder:N?"Loading models…":"Select a model",disabled:N||S.length===0,favoriteProviders:o,favoriteModels:l,onToggleFavorite:c,onToggleModelFavorite:u})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:at,"data-testid":"quick-chat-messages",children:ve||ce?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):Te.length===0&&!_e&&!Fe&&!pe?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[Te.map(ue=>t.jsx(GI,{message:ue,forcePlain:ue.role!=="user"&&P.has(ue.id),mentionAgentsByName:nn,onToggleRender:Nn},ue.id)),pe&&t.jsxs("div",{className:"quick-chat-panel-message quick-chat-panel-message--received quick-chat-panel-message--streaming","data-testid":"quick-chat-streaming-message",children:[_e?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:zn(_e,P.has("__streaming__"))}),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${P.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":P.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>Nn("__streaming__"),children:P.has("__streaming__")?t.jsx(rd,{size:14}):t.jsx(Ma,{size:14})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:"Thinking…"}),Ag(it,!0),Fe&&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:Fe})]})]})]})}),O.length>0&&t.jsx("div",{className:"quick-chat-attachment-previews","data-testid":"quick-chat-attachment-previews",children:O.map((ue,Ke)=>t.jsxs("div",{className:"quick-chat-attachment-preview","data-testid":`quick-chat-attachment-preview-${Ke}`,children:[ue.previewUrl?t.jsx("img",{src:ue.previewUrl,alt:ue.file.name}):t.jsx("span",{className:"quick-chat-attachment-preview-name",children:ue.file.name}),t.jsx("button",{type:"button",className:"quick-chat-attachment-remove","data-testid":`quick-chat-attachment-remove-${Ke}`,"aria-label":`Remove ${ue.file.name}`,onClick:()=>j(Ke),children:"×"})]},`${ue.file.name}-${Ke}`))}),t.jsx("div",{className:"quick-chat-panel-input",children:t.jsxs("div",{className:`quick-chat-input-wrapper${Ne?" quick-chat-input-wrapper--dragover":""}`,onDragEnter:gt,onDragOver:Mt,onDragLeave:cn,onDrop:bn,children:[t.jsx("input",{ref:Ye,type:"file",accept:"image/*,.txt,.json,.yaml,.yml,.log,.csv,.xml,.md",multiple:!0,tabIndex:-1,"aria-hidden":"true",className:"quick-chat-attachment-input",onChange:ue=>{dt(ue.target.files),ue.target.value=""}}),t.jsxs("div",{className:"quick-chat-input-row","data-testid":"quick-chat-input-row",children:[t.jsx("button",{type:"button",className:"btn-icon quick-chat-attach-btn","data-testid":"quick-chat-attach-btn","aria-label":"Attach files",onClick:()=>Ye.current?.click(),children:t.jsx(dp,{size:16})}),t.jsx("input",{ref:te,type:"text",value:U,onChange:Sn,onKeyDown:ss,onKeyUp:_n,onClick:Zt,onBlur:Se,onFocus:ut,onPaste:Y,onTouchStart:ue=>{typeof window>"u"||window.innerWidth>as||document.activeElement!==ue.currentTarget&&(ue.preventDefault(),ue.currentTarget.focus({preventScroll:!0}))},placeholder:ge,disabled:Ft,"data-testid":"quick-chat-input"}),pe?t.jsx("button",{type:"button",className:"chat-input-stop quick-chat-send-btn",onPointerDown:ue=>{typeof window>"u"||window.innerWidth>as||(ue.preventDefault(),ue.pointerType&&ue.pointerType!=="mouse"&&(xt.current=!0,he()))},onTouchStart:ue=>{typeof window>"u"||window.innerWidth>as||(ue.preventDefault(),xt.current=!0,he())},onMouseDown:ue=>{typeof window>"u"||window.innerWidth>as||ue.preventDefault()},onClick:()=>{if(xt.current){xt.current=!1;return}he()},"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:t.jsx(Cs,{size:14})}):t.jsx("button",{type:"button",className:"quick-chat-send-btn",onPointerDown:ue=>{typeof window>"u"||window.innerWidth>as||(ue.preventDefault(),ue.pointerType&&ue.pointerType!=="mouse"&&(xt.current=!0,Pe(),fe(),We()))},onTouchStart:ue=>{typeof window>"u"||window.innerWidth>as||(ue.preventDefault(),xt.current=!0,Pe(),fe(),We())},onMouseDown:ue=>{typeof window>"u"||window.innerWidth>as||ue.preventDefault()},onClick:()=>{if(xt.current){xt.current=!1;return}We()},disabled:Ft||U.trim().length===0&&O.length===0,"data-testid":"quick-chat-send",children:t.jsx(zi,{size:16})})]}),t.jsx(kI,{agents:d,filter:D,highlightedIndex:K,visible:F,onSelect:Jt,position:"above"}),t.jsx(CI,{visible:ne.mentionActive&&!F,position:we,files:ne.files,selectedIndex:ne.selectedIndex,onSelect:ue=>{const Ke=ne.selectFile(ue,U);q(Ke),ne.dismissMention(),le(!1),te.current?.focus()},loading:ne.loading}),Me&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${ze}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:Je,children:"×"})]})]})})]})]})}function ar(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function Bh(e){return e.status==="generating"||e.status==="awaiting_input"}function rr(e){return e==="complete"||e==="error"}function YI(e){const[n,s]=a.useState([]),i=a.useRef(new Map),r=a.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:c,requestSync:u}=Ia(),d=a.useCallback(()=>{ud(e).then(p=>{const g=p.filter(v=>{const x=ar(v.updatedAt),y=r.current.get(v.id);return y===void 0?!0:x<=y?!1:(r.current.delete(v.id),!0)}),b=new Map;for(const v of g)b.set(v.id,ar(v.updatedAt));i.current=b,s(g)}).catch(p=>{console.warn("[useBackgroundSessions] Failed to fetch AI sessions:",p)})},[e]);a.useEffect(()=>{u(),d()},[d,u]),a.useEffect(()=>{s(p=>{if(o.size===0)return p;let g=!1;const b=new Map(p.map(v=>[v.id,v]));for(const v of o.values()){if(e&&v.projectId&&v.projectId!==e)continue;const x=v.lastEventTimestamp,y=i.current.get(v.sessionId)??0;if(x<y)continue;const k=r.current.get(v.sessionId);if(k!==void 0&&x<=k)continue;if(k!==void 0&&x>k&&!rr(v.status)&&r.current.delete(v.sessionId),rr(v.status)){b.delete(v.sessionId)&&(g=!0),i.current.set(v.sessionId,x);continue}const S=b.get(v.sessionId),_=v.type??S?.type,N=v.title??S?.title;if(!S&&(!_||!N))continue;const A={id:v.sessionId,type:_??"planning",status:v.status,title:N??"AI Session",projectId:v.projectId??S?.projectId??e??null,lockedByTab:v.owningTabId??S?.lockedByTab??null,updatedAt:v.updatedAt??S?.updatedAt??new Date(x).toISOString()},C=b.get(v.sessionId);(!C||C.status!==A.status||C.title!==A.title||C.type!==A.type||C.projectId!==A.projectId||C.lockedByTab!==A.lockedByTab||C.updatedAt!==A.updatedAt)&&(b.set(v.sessionId,A),i.current.set(v.sessionId,x),g=!0)}return g?[...b.values()].sort((v,x)=>ar(x.updatedAt)-ar(v.updatedAt)):p})},[e,o]),a.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",g=v=>{try{const x=JSON.parse(v.data),y=ar(x.updatedAt)||Date.now();s(k=>{const S=i.current.get(x.id)??0;if(y<S)return k;const _=r.current.get(x.id);if(_!==void 0&&y<=_)return k;if(_!==void 0&&y>_&&!rr(x.status)&&r.current.delete(x.id),i.current.set(x.id,y),rr(x.status))return k.filter(A=>A.id!==x.id);const N=k.findIndex(A=>A.id===x.id);if(N>=0){const A=[...k];return A[N]=x,A}return Bh(x)?[x,...k]:k}),l({sessionId:x.id,status:x.status,needsInput:x.status==="awaiting_input",type:x.type,title:x.title,projectId:x.projectId,owningTabId:x.lockedByTab,updatedAt:x.updatedAt,timestamp:y}),rr(x.status)&&c({sessionId:x.id,status:x.status,timestamp:y})}catch{}},b=v=>{try{const x=JSON.parse(v.data),y=Date.now();r.current.set(x,y),i.current.set(x,Math.max(i.current.get(x)??0,y)),c({sessionId:x,status:"complete",timestamp:y}),s(k=>k.filter(S=>S.id!==x))}catch{}};return Gs(`/api/events${p}`,{events:{"ai_session:updated":g,"ai_session:deleted":b},onReconnect:()=>{d()}})},[c,l,e,d]);const m=a.useCallback(async p=>{const b=n.find(k=>k.id===p)?.type,v=Yi();let x=!1;if(b==="planning")try{await jp(p,e,v)}catch(k){x=!0,k instanceof Error&&k.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of planning session ${p} despite lock by another tab`)}else if(b==="subtask")try{await Np(p,e,v)}catch(k){x=!0,k instanceof Error&&k.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of subtask session ${p} despite lock by another tab`)}else if(b==="mission_interview")try{await _p(p,e,v)}catch(k){x=!0,k instanceof Error&&k.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of mission interview session ${p} despite lock by another tab`)}x&&console.warn(`[useBackgroundSessions] Cancellation failed for session ${p}, attempting delete anyway`);const y=Date.now();r.current.set(p,y),i.current.set(p,Math.max(i.current.get(p)??0,y)),c({sessionId:p,status:"complete",timestamp:y});try{await Mp(p)}catch{}s(k=>k.filter(S=>S.id!==p))},[c,e,n]),h=a.useMemo(()=>n.filter(p=>Bh(p)),[n]),f=a.useMemo(()=>h.filter(p=>p.type==="planning"),[h]);return{sessions:h,generating:h.filter(p=>p.status==="generating").length,needsInput:h.filter(p=>p.status==="awaiting_input").length,planningSessions:f,dismissSession:m,refresh:d}}function Jn(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 Hh(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function QI(e,n){return{...n,columnMovedAt:e.columnMovedAt??n.columnMovedAt,executionStartedAt:e.executionStartedAt??n.executionStartedAt,executionCompletedAt:e.executionCompletedAt??n.executionCompletedAt,worktree:n.worktree??e.worktree,modifiedFiles:n.modifiedFiles??e.modifiedFiles,timedExecutionMs:n.timedExecutionMs??e.timedExecutionMs,workflowStepResults:n.workflowStepResults??e.workflowStepResults,tokenUsage:n.tokenUsage??e.tokenUsage,mergeDetails:n.mergeDetails??e.mergeDetails}}function vc(e,n){if(Hh(n.updatedAt,e.updatedAt)<0)return e;if(e.column===n.column)return QI(e,n);const i=Hh(e.columnMovedAt,n.columnMovedAt);return e.columnMovedAt&&!n.columnMovedAt?{...n,column:e.column,columnMovedAt:e.columnMovedAt}:i>0?{...n,column:e.column,columnMovedAt:e.columnMovedAt}:n}function XI(e){const n=e?.projectId,s=e?.searchQuery,i=e?.sseEnabled??!0,[r,o]=a.useState([]),[l,c]=a.useState(!1),u=a.useRef(l);u.current=l;const d=a.useRef(r),m=a.useRef(0),h=a.useRef(0),f=a.useRef(s),p=a.useRef(null),g=a.useRef(void 0),b=a.useRef(0),v=a.useRef(n);d.current=r,f.current=s,v.current!==n&&(v.current=n,b.current++);const x=1e3,y=a.useCallback(async K=>{const ee=++m.current,E=n,$=K?.searchQueryOverride??f.current,P=K?.includeArchivedOverride??u.current;try{const w=await Jv(void 0,void 0,E,$,P);if(m.current!==ee||n!==E)return;o(w.map(Jn)),g.current=Date.now()}catch{if(m.current!==ee||n!==E)return;if(K?.clearOnError){o([]);return}o(w=>w)}},[n]);p.current=y;const k=a.useCallback(async()=>{u.current||(c(!0),u.current=!0,await p.current({includeArchivedOverride:!0}))},[]),S=a.useRef(s);a.useEffect(()=>{if(s===void 0&&S.current===void 0)return;S.current=s;const K=setTimeout(()=>{y({searchQueryOverride:s})},300);return()=>clearTimeout(K)},[s]),a.useEffect(()=>{y({clearOnError:!0});const K=()=>{if(document.visibilityState!=="visible")return;const ee=Date.now();ee-h.current<x||(h.current=ee,y())};return document.addEventListener("visibilitychange",K),()=>{document.removeEventListener("visibilitychange",K)}},[y]),a.useEffect(()=>{if(i===!1)return;const K=b.current,ee=n?`?projectId=${encodeURIComponent(n)}`:"",E=()=>b.current!==K;let $=!0;const P=le=>{if(E())return;const we=Jn(JSON.parse(le.data));if(f.current){p.current({searchQueryOverride:f.current});return}o(L=>{const ne=L.findIndex(me=>me.id===we.id);if(ne===-1)return[...L,we];const Q=L[ne],be=vc(Q,we);if(be===Q)return L;const de=[...L];return de[ne]=be,de}),g.current=Date.now()},w=le=>{if(E())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:we,to:L}=JSON.parse(le.data),ne=Jn(we);o(Q=>Q.map(be=>be.id===ne.id?{...ne,column:L}:be)),g.current=Date.now()},O=le=>{if(E())return;if(f.current){p.current({searchQueryOverride:f.current});return}const we=Jn(JSON.parse(le.data));o(L=>L.map(ne=>ne.id!==we.id?ne:vc(ne,we))),g.current=Date.now()},Z=le=>{if(E())return;if(f.current){p.current({searchQueryOverride:f.current});return}const we=Jn(JSON.parse(le.data));o(L=>L.filter(ne=>ne.id!==we.id))},Ne=le=>{if(E())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:we}=JSON.parse(le.data),L=Jn(we);o(ne=>ne.map(Q=>Q.id===L.id?{...L,column:"done"}:Q))},se=Gs(`/api/events${ee}`,{events:{"task:created":P,"task:moved":w,"task:updated":O,"task:deleted":Z,"task:merged":Ne},onReconnect:()=>{$&&(E()||p.current())}});return()=>{$=!1,se()}},[n,i]);const _=a.useCallback(async K=>{const ee=Jn(await bp(K,n));return o(E=>E.some($=>$.id===ee.id)?E:[...E,ee]),ee},[n]),N=a.useCallback(async(K,ee)=>Jn(await Qv(K,ee,n)),[n]),A=a.useCallback(async K=>Jn(await xp(K,n)),[n]),C=a.useCallback(async K=>Jn(await Xv(K,n)),[n]),z=a.useCallback(async K=>Zv(K,n),[n]),M=a.useCallback(async K=>Jn(await ey(K,n)),[n]),T=a.useCallback(async K=>Jn(await ty(K,n)),[n]),U=a.useCallback(async K=>{const ee=Jn(await ny(K,n));return o(E=>E.some($=>$.id===ee.id)?E:[...E,ee]),ee},[n]),q=a.useCallback(async(K,ee)=>{const E=d.current.find(P=>P.id===K),$=E?{...E,...ee,updatedAt:new Date().toISOString()}:void 0;$&&o(P=>P.map(w=>w.id===K?$:w));try{const P=Jn(await ii(K,ee,n));return o(w=>w.map(O=>O.id===K?P:O)),P}catch(P){throw E&&o(w=>w.map(O=>O.id===K?E:O)),P}},[n]),D=a.useCallback(async K=>{const ee=Jn(await iy(K,n));return o(E=>E.map($=>$.id===K?ee:$)),ee},[n]),R=a.useCallback(async K=>{const ee=Jn(await ay(K,n));return o(E=>E.map($=>$.id===K?ee:$)),ee},[n]),F=a.useCallback(async()=>{const ee=(await ry(n)).map(Jn);return o(E=>E.map($=>ee.find(w=>w.id===$.id)||$)),ee},[n]),V=a.useCallback(K=>{if(K.length===0)return;if(f.current){p.current({searchQueryOverride:f.current});return}const ee=K.map(Jn);o(E=>{let $=E;for(const P of ee){const w=$.findIndex(Ne=>Ne.id===P.id);if(w===-1){$===E&&($=[...E]),$.push(P);continue}const O=$[w],Z=vc(O,P);Z!==O&&($===E&&($=[...E]),$[w]=Z)}return $}),g.current=Date.now()},[]);return{tasks:r,createTask:_,moveTask:N,pauseTask:A,deleteTask:C,mergeTask:z,retryTask:M,resetTask:T,duplicateTask:U,updateTask:q,archiveTask:D,unarchiveTask:R,archiveAllDone:F,loadArchivedTasks:k,includeArchived:l,ingestCreatedTasks:V,lastFetchTimeMs:g.current}}const ZI=5e3,e4=1e3;function t4(){const[e,n]=a.useState([]),[s,i]=a.useState(!0),[r,o]=a.useState(null),l=a.useRef(null),c=a.useRef(0),u=a.useCallback(async()=>{try{o(null);const f=await cu();n(f)}catch(f){o(f instanceof Error?f.message:"Failed to fetch projects")}},[]);a.useEffect(()=>{let f=!1;async function p(){i(!0);const b=performance.now();try{const v=await cu(),y=`initial fetchProjectsAcrossNodes took ${Math.round(performance.now()-b)}ms (${v.length} projects)`;console.log(`[useProjects] ${y}`),pr("[useProjects]",y),f||(n(v),o(null))}catch(v){const y=`initial fetch failed after ${Math.round(performance.now()-b)}ms: ${v instanceof Error?v.message:String(v)}`;console.warn(`[useProjects] ${y}`),pr("[useProjects]",y),f||o(v instanceof Error?v.message:"Failed to fetch projects")}finally{f||i(!1)}}p();const g=()=>{if(document.visibilityState!=="visible")return;const b=Date.now();b-c.current<e4||(c.current=b,u())};return document.addEventListener("visibilitychange",g),()=>{f=!0,document.removeEventListener("visibilitychange",g)}},[u]),a.useEffect(()=>{if(!s)return l.current=setInterval(()=>{u()},ZI),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async f=>{const p=await mk(f);return n(g=>[...g,p]),p},[]),m=a.useCallback(async(f,p)=>{const g=await xk(f,p);return n(b=>b.map(v=>v.id===f?g:v)),g},[]),h=a.useCallback(async f=>{await Sp(f),n(p=>p.filter(g=>g.id!==f))},[]);return{projects:e,loading:s,error:r,refresh:u,register:d,update:m,unregister:h}}const n4="kb-dashboard-current-project";function s4(e){return e??"local"}function i4(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=s4(s);a.useEffect(()=>{let p=!1;async function g(){try{const b=await Ji();if(p)return;d.current=b.dashboardCurrentProjectIdByNode??{};const v=d.current[m];if(v){const x=e.find(y=>y.id===v);x&&(r(x),c.current=!0)}if(!v)try{const x=localStorage.getItem(n4);if(x){const y=JSON.parse(x);y?.id&&e.some(S=>S.id===y.id)&&(r(y),c.current=!0,d.current={...d.current,[m]:y.id},await gn({dashboardCurrentProjectIdByNode:d.current}).catch(()=>{}))}}catch{}}catch{}finally{p||l(!1)}}return g(),()=>{p=!0}},[m,e]),a.useEffect(()=>{if(!o){if(i){if(!e.some(b=>b.id===i.id)&&e.length>0){const b=e.find(v=>v.status==="active");r(b||e[0]||null);return}const g={...d.current,[m]:i.id};d.current=g,gn({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}else if(e.length>0&&!u.current){const p=e.find(g=>g.status==="active");p&&r(p)}}},[i,e,o,m]);const h=a.useCallback(p=>{if(u.current=!1,r(p),p){const g={...d.current,[m]:p.id};d.current=g,gn({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}},[m]),f=a.useCallback(()=>{u.current=!0,r(null);const p={...d.current};delete p[m],d.current=p,gn({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[m]);return{currentProject:i,setCurrentProject:h,clearCurrentProject:f,loading:o}}const Tg=a.createContext(null);function a4({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()},[]),So.createElement(Tg.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function r4(){const e=a.useContext(Tg);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const Pg="kb-dashboard-theme-mode",Ig="kb-dashboard-color-theme",$g="kb-dashboard-font-scale-pct",id=100,o4=85,l4=125,Dg=[...Yw],ad="theme-data",yc="theme-data.css";function c4(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.endsWith("/")?e.slice(0,-1)+`/${yc}`:e.replace(/\/[^/]+$/,`/${yc}`):`/${yc}`}const js=typeof window<"u",d4=js?a.useLayoutEffect:a.useEffect;function Lg(e){return e==="dark"||e==="light"||e==="system"}function qh(){if(!js)return"dark";try{const e=localStorage.getItem(Pg);if(Lg(e))return e}catch{}return"dark"}function Vh(){if(!js)return"default";try{const e=localStorage.getItem(Ig);if(e&&Dg.includes(e))return e}catch{}return"default"}function Wh(e){if(js)try{localStorage.setItem(Pg,e)}catch{}}function Kh(e){if(js)try{localStorage.setItem(Ig,e)}catch{}}function _r(e){return typeof e!="number"||!Number.isFinite(e)?id:Math.min(l4,Math.max(o4,Math.round(e)))}function Gh(){if(!js)return id;try{const e=Number(localStorage.getItem($g));return _r(e)}catch{return id}}function Jh(e){if(js)try{localStorage.setItem($g,String(_r(e)))}catch{}}function u4(e,n){return e==="system"?n?"dark":"light":e}function m4(e,n,s,i){if(!js)return;const r=u4(e,i);document.documentElement.setAttribute("data-theme",r),document.documentElement.setAttribute("data-color-theme",n),document.documentElement.style.fontSize=`${_r(s)}%`}function Yh(){if(!js)return;const e=c4(),n=document.getElementById(ad);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=ad,document.head.appendChild(s)}function Qh(){if(!js)return;const e=document.getElementById(ad);e&&e.remove()}function h4(){const[e,n]=a.useState(()=>qh()),[s,i]=a.useState(()=>Vh()),[r,o]=a.useState(()=>Gh()),[l,c]=a.useState(!0),[u,d]=a.useState(()=>js?window.matchMedia("(prefers-color-scheme: dark)").matches:!0),m=a.useRef(e),h=a.useRef(s),f=a.useRef(r),p=a.useRef(!1),g=a.useRef(!1),b=a.useRef(!1);a.useEffect(()=>{m.current=e},[e]),a.useEffect(()=>{h.current=s},[s]),a.useEffect(()=>{f.current=r},[r]),a.useEffect(()=>{if(!js||!l)return;let k=!1;return Ji().then(S=>{if(!k&&(Lg(S.themeMode)&&!p.current&&(m.current!==S.themeMode&&(m.current=S.themeMode,n(S.themeMode)),qh()!==S.themeMode&&Wh(S.themeMode)),S.colorTheme&&Dg.includes(S.colorTheme)&&!g.current&&(h.current!==S.colorTheme&&(h.current=S.colorTheme,i(S.colorTheme)),Vh()!==S.colorTheme&&Kh(S.colorTheme)),!b.current)){const _=_r(S.dashboardFontScalePct);f.current!==_&&(f.current=_,o(_)),Gh()!==_&&Jh(_)}}).catch(S=>{console.warn("[useTheme] Failed to hydrate theme from global settings",S)}).finally(()=>{k||c(!1)}),()=>{k=!0}},[l]),a.useEffect(()=>{if(!js)return;const k=window.matchMedia("(prefers-color-scheme: dark)"),S=_=>{d(_.matches)};return k.addEventListener("change",S),()=>k.removeEventListener("change",S)},[]),d4(()=>{m4(e,s,r,u)},[e,s,r,u]),a.useEffect(()=>{!js||l||(s!=="default"?Yh():Qh())},[s,l]);const v=a.useCallback(k=>{p.current=!0,m.current=k,n(k),Wh(k),gn({themeMode:k}).catch(S=>{console.warn("[useTheme] Failed to persist themeMode to global settings",S)})},[]),x=a.useCallback(k=>{g.current=!0,h.current=k,i(k),Kh(k),k!=="default"?Yh():Qh(),gn({colorTheme:k}).catch(S=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",S)})},[]),y=a.useCallback(k=>{const S=_r(k);b.current=!0,f.current=S,o(S),Jh(S),gn({dashboardFontScalePct:S}).catch(_=>{console.warn("[useTheme] Failed to persist dashboardFontScalePct to global settings",_)})},[]);return{themeMode:e,colorTheme:s,dashboardFontScalePct:r,setThemeMode:v,setColorTheme:x,setDashboardFontScalePct:y,isSystemDark:u}}function p4(e){const{planningSessions:n}=e,[s,i]=a.useState(!1),[r,o]=a.useState(!1),[l,c]=a.useState(null),[u,d]=a.useState(void 0),[m,h]=a.useState(!1),[f,p]=a.useState(null),[g,b]=a.useState(void 0),[v,x]=a.useState(null),[y,k]=a.useState("definition"),[S,_]=a.useState(!1),[N,A]=a.useState(void 0),[C,z]=a.useState(!1),[M,T]=a.useState(!1),[U,q]=a.useState(!1),[D,R]=a.useState(null),[F,V]=a.useState(!1),[K,ee]=a.useState(!1),[E,$]=a.useState(void 0),[P,w]=a.useState(!1),[O,Z]=a.useState("project"),[Ne,se]=a.useState(!1),[le,we]=a.useState(!1),[L,ne]=a.useState(!1),[Q,be]=a.useState(!1),[de,me]=a.useState(!1),[ie,xe]=a.useState(!1),[Re,Oe]=a.useState(!1),nt=!!(v||S||s||r||m||K||P||Ne||le||L||de||Q||U||F||C||M||ie||Re),et=a.useCallback(()=>i(!0),[]),Ze=a.useCallback(()=>i(!1),[]),rt=a.useCallback(()=>o(!0),[]),He=a.useCallback(ge=>{c(ge),o(!0)},[]),Ge=a.useCallback(()=>{const ge=n[0];ge&&(d(ge.id),o(!0))},[n]),oe=a.useCallback(ge=>{d(ge),o(!0)},[]),je=a.useCallback(()=>{o(!1),c(null),d(void 0)},[]),X=a.useCallback(ge=>{p(ge),h(!0)},[]),Ae=a.useCallback(ge=>{b(ge),h(!0)},[]),Te=a.useCallback(()=>{h(!1),p(null),b(void 0)},[]),pe=a.useCallback((ge,ze="definition")=>{x(ge),k(ze)},[]),_e=a.useCallback(ge=>{x(ge),k("changes")},[]),Fe=a.useCallback(ge=>{x(ze=>ze&&{...ze,...ge})},[]),it=a.useCallback(()=>{x(null)},[]),ve=a.useCallback(ge=>{A(ge),_(!0)},[]),ce=a.useCallback(()=>{_(!1),A(void 0)},[]),Ie=a.useCallback(()=>z(!0),[]),he=a.useCallback(()=>z(!1),[]),Me=a.useCallback(()=>T(!0),[]),Je=a.useCallback(()=>T(!1),[]),$e=a.useCallback(ge=>{R(ge??null),q(!0)},[]),ft=a.useCallback(()=>{q(!1),R(null)},[]),J=a.useCallback(()=>V(!0),[]),re=a.useCallback(()=>V(!1),[]),ye=a.useCallback(()=>{ee(ge=>!ge)},[]),at=a.useCallback(()=>{ee(!1),$(void 0)},[]),te=a.useCallback(()=>w(!0),[]),Ye=a.useCallback(()=>w(!1),[]),mt=a.useCallback(ge=>{Z(ge)},[]),ht=a.useCallback(()=>se(!0),[]),xt=a.useCallback(()=>se(!1),[]),St=a.useCallback(()=>we(!0),[]),bt=a.useCallback(()=>we(!1),[]),Nt=a.useCallback(()=>ne(!0),[]),Qt=a.useCallback(()=>ne(!1),[]),Pt=a.useCallback(()=>be(!0),[]),Dt=a.useCallback(()=>be(!1),[]),Et=a.useCallback(()=>me(!0),[]),Xt=a.useCallback(()=>me(!1),[]),Lt=a.useCallback(async(ge,ze)=>{me(!1),$(ze),ee(!0)},[]),Ft=a.useCallback(()=>xe(!0),[]),zt=a.useCallback(()=>xe(!1),[]),Tt=a.useCallback(()=>Oe(!0),[]),Gt=a.useCallback(()=>Oe(!1),[]),Ot=a.useCallback((ge,ze)=>{ze(`Created ${ge.id} from planning mode`,"success"),o(!1),c(null)},[]),qt=a.useCallback((ge,ze)=>{const dt=ge.map(j=>j.id).join(", ");ze(`Created ${dt} from planning mode`,"success"),o(!1),c(null)},[]),nn=a.useCallback((ge,ze)=>{const dt=ge.map(j=>j.id).join(", ");ze(`Created ${dt} from subtask breakdown`,"success"),h(!1),p(null)},[]);return{newTaskModalOpen:s,isPlanningOpen:r,planningInitialPlan:l,planningResumeSessionId:u,isSubtaskOpen:m,subtaskInitialDescription:f,subtaskResumeSessionId:g,detailTask:v,detailTaskInitialTab:y,settingsOpen:S,settingsInitialSection:N,schedulesOpen:C,githubImportOpen:M,usageOpen:U,usageAnchorRect:D,systemStatsOpen:F,terminalOpen:K,terminalInitialCommand:E,filesOpen:P,fileBrowserWorkspace:O,activityLogOpen:Ne,gitManagerOpen:le,workflowStepsOpen:L,agentsOpen:Q,scriptsOpen:de,setupWizardOpen:ie,modelOnboardingOpen:Re,anyModalOpen:nt,openNewTask:et,closeNewTask:Ze,openPlanning:rt,openPlanningWithInitialPlan:He,resumePlanning:Ge,openPlanningWithSession:oe,closePlanning:je,openSubtaskBreakdown:X,openSubtaskWithSession:Ae,closeSubtask:Te,openDetailTask:pe,openDetailWithChangesTab:_e,updateDetailTask:Fe,closeDetailTask:it,openSettings:ve,closeSettings:ce,openSchedules:Ie,closeSchedules:he,openGitHubImport:Me,closeGitHubImport:Je,openUsage:$e,closeUsage:ft,openSystemStats:J,closeSystemStats:re,toggleTerminal:ye,closeTerminal:at,openFiles:te,closeFiles:Ye,setFileWorkspace:mt,openActivityLog:ht,closeActivityLog:xt,openGitManager:St,closeGitManager:bt,openWorkflowSteps:Nt,closeWorkflowSteps:Qt,openAgents:Pt,closeAgents:Dt,openScripts:Et,closeScripts:Xt,runScript:Lt,openSetupWizard:Ft,closeSetupWizard:zt,openModelOnboarding:Tt,closeModelOnboarding:Gt,onPlanningTaskCreated:Ot,onPlanningTasksCreated:qt,onSubtaskTasksCreated:nn}}function f4(e){const[n,s]=a.useState(2),[i,r]=a.useState("."),[o,l]=a.useState(!0),[c,u]=a.useState(!1),[d,m]=a.useState(!1),[h,f]=a.useState(void 0),[p,g]=a.useState(!1),[b,v]=a.useState(!1),[x,y]=a.useState(!1),[k,S]=a.useState({}),[_,N]=a.useState(!1),[A,C]=a.useState(!1),[z,M]=a.useState(!1),[T,U]=a.useState(!1),[q,D]=a.useState(!1),R=a.useCallback(async()=>{const[E,$]=await Promise.allSettled([cy(e),Yo(e)]);if(E.status==="fulfilled"&&(s(E.value.maxConcurrent),r(E.value.rootDir)),$.status==="fulfilled"){const P=$.value;l(!!P.autoMerge),u(!!P.globalPause),m(!!P.enginePaused),v(!!P.prAuthAvailable),f(P.taskStuckTimeoutMs),g(P.showQuickChatFAB===!0),S(P.experimentalFeatures??{});const w=P.experimentalFeatures??{};N(w.insights===!0),C(w.roadmap===!0),M(w.memoryView===!0),U(w.devServerView===!0||w.devServer===!0),D(w.todoView===!0)}y(!0)},[e]);a.useEffect(()=>{y(!1),S({}),N(!1),C(!1),M(!1),U(!1),D(!1),R()},[R]);const F=a.useCallback(async()=>{const E=!o;l(E);try{await Qr({autoMerge:E},e)}catch{l(!E)}},[o,e]),V=a.useCallback(async()=>{const E=!c;u(E);try{await Qr({globalPause:E,globalPauseReason:E?"manual":void 0},e)}catch{u(!E)}},[c,e]),K=a.useCallback(async()=>{const E=!d;m(E);try{await Qr({enginePaused:E},e)}catch{m(!E)}},[d,e]),ee=a.useCallback(async()=>{const E=!p;g(E);try{await Qr({showQuickChatFAB:E},e)}catch{g(!E)}},[p,e]);return{maxConcurrent:n,rootDir:i,autoMerge:o,globalPaused:c,enginePaused:d,taskStuckTimeoutMs:h,showQuickChatFAB:p,prAuthAvailable:b,settingsLoaded:x,experimentalFeatures:k,insightsEnabled:_,roadmapEnabled:A,memoryEnabled:z,devServerEnabled:T,todosEnabled:q,toggleAutoMerge:F,toggleGlobalPause:V,toggleEnginePause:K,toggleShowQuickChatFAB:ee,refresh:R}}function g4(e){const{projectId:n,projects:s,projectsLoading:i,currentProject:r,setCurrentProject:o,addToast:l,openTaskDetail:c,closeTaskDetail:u}=e,d=a.useRef(!1),m=a.useRef(null);return a.useEffect(()=>{const f=new URLSearchParams(window.location.search),p=f.get("project"),g=f.get("task");if(!g||i)return;if(p){const v=s.find(x=>x.id===p);if(!v){l(`Project '${p}' not found`,"error");return}r?.id!==v.id&&o(v)}if(d.current)return;d.current=!0,jr(g,p??n).then(v=>{c(v),m.current=g}).catch(()=>{l(`Task ${g} not found`,"error")})},[n,s,i,r,o,l,c]),{handleDetailClose:a.useCallback(()=>{if(m.current){const f=new URLSearchParams(window.location.search);f.delete("task");const p=f.toString();window.history.replaceState(null,"",p?`${window.location.pathname}?${p}`:window.location.pathname),m.current=null}u()},[u])}}function b4(){const[e,n]=a.useState([]),[s,i]=a.useState([]),[r,o]=a.useState([]),l=a.useRef(s),c=a.useRef(r);a.useEffect(()=>{fs().then(m=>{n(m.models),l.current=m.favoriteProviders,c.current=m.favoriteModels,i(m.favoriteProviders),o(m.favoriteModels)}).catch(()=>{})},[]),a.useEffect(()=>{l.current=s},[s]),a.useEffect(()=>{c.current=r},[r]);const u=a.useCallback(async m=>{const h=l.current,p=h.includes(m)?h.filter(g=>g!==m):[m,...h];l.current=p,i(()=>p);try{await gn({favoriteProviders:p,favoriteModels:c.current})}catch(g){throw l.current=h,i(()=>h),g}},[]),d=a.useCallback(async m=>{const h=c.current,p=h.includes(m)?h.filter(g=>g!==m):[m,...h];c.current=p,o(()=>p);try{await gn({favoriteProviders:l.current,favoriteModels:p})}catch(g){throw c.current=h,o(()=>h),g}},[]);return{availableModels:e,favoriteProviders:s,favoriteModels:r,toggleFavoriteProvider:u,toggleFavoriteModel:d}}function x4({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;wr().then(({providers:u})=>{const d=u.some(h=>h.authenticated);if(u.length>0&&!d||u.length>0&&d)return Ji().then(h=>{const f=!!(h.defaultProvider&&h.defaultModelId);(h.modelOnboardingComplete===!1||h.modelOnboardingComplete===void 0)&&(!d||!f)&&!Ea()?l=!0:!d&&!Ea()&&(c=!0)})}).then(()=>{if(o.current){r.current=!1;return}l?(Is("onboarding:auto-triggered",{trigger:"first-run"}),s()):c&&(Is("onboarding:auto-triggered",{trigger:"missing-provider"}),i("authentication"))}).catch(()=>{})},[e,n,s,i])}const Xh="kb-update-banner-dismissed";function v4(){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(Xh)==="true";d(h);let f=!1;return dy().then(p=>{f||p.disabled||(i(p.updateAvailable===!0),o(typeof p.latestVersion=="string"?p.latestVersion:null),c(typeof p.currentVersion=="string"?p.currentVersion:null))}).catch(()=>{}).finally(()=>{f||n(!1)}),()=>{f=!0}},[]);const m=a.useCallback(()=>{d(!0),sessionStorage.setItem(Xh,"true")},[]);return{updateAvailable:s,latestVersion:r,currentVersion:l,loading:e,dismissed:u,dismiss:m}}const y4=["board","list","agents","missions","chat","documents","research","roadmaps","skills","mailbox","insights","memory","devserver","dev-server","todos"];function Zh(e){return e!==null&&y4.includes(e)}function j4(e){return e==="devserver"?"dev-server":e}function k4(e){const{projectsLoading:n,projectsError:s,currentProjectLoading:i,currentProject:r,projectsLength:o,setupWizardOpen:l,openSetupWizard:c,themeMode:u,setThemeMode:d}=e,[m,h]=a.useState(()=>{if(typeof window<"u"){const x=window.localStorage.getItem("kb-dashboard-view-mode");if(x==="overview"||x==="project")return x}return"overview"}),[f,p]=a.useState(()=>{const x=Zn("kb-dashboard-task-view");return Zh(x)?x:"board"}),g=a.useRef(!1);a.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",m)},[m]),a.useEffect(()=>{const x=Zn("kb-dashboard-task-view",r?.id);if(Zh(x)){const y=!g.current&&x==="devserver";p(y?"devserver":j4(x))}else p("board");r?.id&&(g.current=!0)},[r?.id]),a.useEffect(()=>{ys("kb-dashboard-task-view",f,r?.id)},[r?.id,f]),a.useEffect(()=>{n||i||r&&m==="overview"&&h("project")},[n,i,r,m]),a.useEffect(()=>{if(n||i||l||s||o>0||r)return;const x=window.setTimeout(()=>{c()},500);return()=>window.clearTimeout(x)},[n,s,o,i,r,l,c]);const b=a.useCallback(x=>{p(x)},[]),v=a.useCallback(()=>{const x=["dark","light","system"],y=x.indexOf(u),k=x[(y+1)%x.length];d(k)},[u,d]);return{viewMode:m,setViewMode:h,taskView:f,setTaskView:p,handleChangeTaskView:b,handleToggleTheme:v}}function w4(e){const{setCurrentProject:n,clearCurrentProject:s,setViewMode:i,currentProject:r,refreshProjects:o,toggleFavoriteProvider:l,toggleFavoriteModel:c,addToast:u,openSettings:d,openSetupWizard:m,closeSetupWizard:h,closeModelOnboarding:f}=e,p=a.useCallback(C=>{n(C),i("project")},[n,i]),g=a.useCallback(()=>{s(),i("overview")},[s,i]),b=a.useCallback(()=>{d()},[d]),v=a.useCallback(()=>{m()},[m]),x=a.useCallback(C=>{h(),n(C),i("project"),u(`Project ${C.name} registered successfully`,"success"),o()},[h,n,i,u,o]),y=a.useCallback(()=>{f()},[f]),k=a.useCallback(async C=>{try{await gk(C.id),u(`Project ${C.name} paused`,"success"),await o()}catch{u(`Failed to pause project ${C.name}`,"error")}},[u,o]),S=a.useCallback(async C=>{try{await bk(C.id),u(`Project ${C.name} resumed`,"success"),await o()}catch{u(`Failed to resume project ${C.name}`,"error")}},[u,o]),_=a.useCallback(async C=>{try{await Sp(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]),N=a.useCallback(async C=>{try{await l(C)}catch{u("Failed to update favorites","error")}},[l,u]),A=a.useCallback(async C=>{try{await c(C)}catch{u("Failed to update model favorites","error")}},[c,u]);return{handleSelectProject:p,handleViewAllProjects:g,handleOpenSettings:b,handleAddProject:v,handleSetupComplete:x,handleModelOnboardingComplete:y,handlePauseProject:k,handleResumeProject:S,handleRemoveProject:_,handleToggleFavorite:N,handleToggleModelFavorite:A}}function N4(e){const{createTask:n,ingestCreatedTasks:s,onPlanningTaskCreated:i,onPlanningTasksCreated:r,onSubtaskTasksCreated:o,addToast:l}=e,c=a.useCallback(async p=>n({...p,column:"triage",source:{sourceType:"dashboard_ui"}}),[n]),u=a.useCallback(async p=>await n({...p,column:"triage",source:{sourceType:"dashboard_ui"}}),[n]),d=a.useCallback(p=>{s([p]),i(p,l)},[l,s,i]),m=a.useCallback(p=>{s(p),r(p,l)},[l,s,r]),h=a.useCallback(p=>{s(p),o(p,l)},[l,s,o]),f=a.useCallback(p=>{l(`Imported ${p.id} from GitHub`,"success")},[l]);return{handleBoardQuickCreate:c,handleModalCreate:u,handlePlanningTaskCreated:d,handlePlanningTasksCreated:m,handleSubtaskTasksCreated:h,handleGitHubImport:f}}async function S4(e){return Xo("/health",{nodeId:e})}async function C4(e){return Xo("/projects",{nodeId:e})}async function E4(e,n,s){const i=new URLSearchParams({projectId:n});return s&&s.trim()&&i.set("q",s.trim()),Xo(`/tasks?${i.toString()}`,{nodeId:e})}async function _4(e,n){return Xo(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:e})}async function XL(e){return I(`/nodes/${encodeURIComponent(e)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function ZL(e){return I(`/nodes/${encodeURIComponent(e)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function ez(e){return I(`/nodes/${encodeURIComponent(e)}/settings/sync-status`)}async function tz(e){return I(`/nodes/${encodeURIComponent(e)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}function M4(e,n){const{projectId:s,searchQuery:i}=n??{},[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState(null),[m,h]=a.useState(!1),[f,p]=a.useState(null),g=a.useRef(null),b=a.useCallback(async()=>{if(!e){o([]),c([]),d(null),h(!1),p(null);return}g.current?.abort();const x=new AbortController;g.current=x,h(!0),p(null);try{const y=[S4(e),C4(e)];s&&(y.push(E4(e,s,i)),y.push(_4(e,s)));const k=await Promise.allSettled(y);if(x.signal.aborted)return;const S=k[0],_=k[1];if(S.status==="rejected"){p(`Failed to fetch node health: ${S.reason}`),h(!1);return}if(d(S.value),_.status==="rejected"){p(`Failed to fetch projects: ${_.reason}`),h(!1);return}if(o(_.value),s&&k[2]){const N=k[2];if(N.status==="rejected"){p(`Failed to fetch tasks: ${N.reason}`),h(!1);return}N.status==="fulfilled"&&c(N.value)}h(!1)}catch(y){x.signal.aborted||(p(y instanceof Error?y.message:"Unknown error"),h(!1))}},[e,s,i]);a.useEffect(()=>(b(),()=>{g.current?.abort()}),[b]);const v=a.useCallback(()=>{b()},[b]);return{projects:r,tasks:l,health:u,loading:m,error:f,refresh:v}}function A4(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 Gs(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 R4="fusion-dashboard-current-node",zg=a.createContext(null);function T4({children:e}){const[n,s]=a.useState(null),[i,r]=a.useState(!0),o=a.useRef(!1),l=a.useRef(void 0);a.useEffect(()=>{let m=!1;async function h(){try{const f=await Ji();if(m)return;l.current=f.dashboardCurrentNodeId;const p=f.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const g=localStorage.getItem(R4);if(g){const b=JSON.parse(g);b?.id&&b?.type==="remote"&&(l.current=b.id,await gn({dashboardCurrentNodeId:b.id}).catch(()=>{}))}}catch{}}catch{}finally{m||r(!1)}}return h(),()=>{m=!0}},[]),a.useEffect(()=>{if(!i)if(n&&n.type==="remote"&&n.id){const m=n.id;l.current!==m&&(l.current=m,gn({dashboardCurrentNodeId:m}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,gn({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,i]);const c=a.useCallback(m=>{s(m)},[]),u=a.useCallback(()=>{s(null),l.current=void 0,gn({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),d={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:u};return t.jsx(zg.Provider,{value:d,children:e})}function P4(){const e=a.useContext(zg);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}function I4({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&&(zv(l),window.location.reload())},[n]),o=a.useCallback(()=>{Fv(),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 $4=200,D4=a.lazy(()=>hn(()=>import("./AgentsView-Dvf_xUkx.js"),__vite__mapDeps([22,1,3,4,23,14,6,7,24])).then(e=>({default:e.AgentsView}))),L4=a.lazy(()=>hn(()=>import("./DocumentsView-j8ic1xUw.js"),__vite__mapDeps([25,1,6,7,26])).then(e=>({default:e.DocumentsView}))),z4=a.lazy(()=>hn(()=>import("./InsightsView-CpAz3o0i.js"),__vite__mapDeps([27,1,20,6,7,28])).then(e=>({default:e.InsightsView}))),F4=a.lazy(()=>hn(()=>import("./ResearchView-CLyyqAWE.js"),__vite__mapDeps([29,1,6,7,30])).then(e=>({default:e.ResearchView}))),O4=a.lazy(()=>hn(()=>import("./NodesView-Bo_Yhr4N.js"),__vite__mapDeps([31,1,23,6,7,32])).then(e=>({default:e.NodesView}))),U4=a.lazy(()=>hn(()=>import("./ChatView-BgUt38ty.js"),__vite__mapDeps([33,1,6,7])).then(e=>({default:e.ChatView}))),B4=a.lazy(()=>hn(()=>import("./RoadmapsView-tG7IdOoc.js"),__vite__mapDeps([34,1,6,7,35])).then(e=>({default:e.RoadmapsView}))),H4=a.lazy(()=>hn(()=>import("./SkillsView-x4_YwBz6.js"),__vite__mapDeps([36,1,6,7,37])).then(e=>({default:e.SkillsView}))),q4=a.lazy(()=>hn(()=>import("./MemoryView-BcQsi_JK.js"),__vite__mapDeps([38,1,18,19,6,7,39])).then(e=>({default:e.MemoryView}))),V4=a.lazy(()=>hn(()=>import("./DevServerView-C2qTJch7.js"),__vite__mapDeps([40,1,6,7,41])).then(e=>({default:e.DevServerView}))),W4=a.lazy(()=>hn(()=>import("./TodoView-BBYcMbXE.js"),__vite__mapDeps([42,1,5,6,7,43])).then(e=>({default:e.TodoView})));function K4(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{hn(()=>import("./AgentsView-Dvf_xUkx.js"),__vite__mapDeps([22,1,3,4,23,14,6,7,24])),hn(()=>import("./DocumentsView-j8ic1xUw.js"),__vite__mapDeps([25,1,6,7,26])),hn(()=>import("./InsightsView-CpAz3o0i.js"),__vite__mapDeps([27,1,20,6,7,28])),hn(()=>import("./ResearchView-CLyyqAWE.js"),__vite__mapDeps([29,1,6,7,30])),hn(()=>import("./NodesView-Bo_Yhr4N.js"),__vite__mapDeps([31,1,23,6,7,32])),hn(()=>import("./ChatView-BgUt38ty.js"),__vite__mapDeps([33,1,6,7])),hn(()=>import("./RoadmapsView-tG7IdOoc.js"),__vite__mapDeps([34,1,6,7,35])),hn(()=>import("./SkillsView-x4_YwBz6.js"),__vite__mapDeps([36,1,6,7,37])),hn(()=>import("./MemoryView-BcQsi_JK.js"),__vite__mapDeps([38,1,18,19,6,7,39])),hn(()=>import("./DevServerView-C2qTJch7.js"),__vite__mapDeps([40,1,6,7,41])),hn(()=>import("./TodoView-BBYcMbXE.js"),__vite__mapDeps([42,1,5,6,7,43]))})}const jc="kb-setup-warning-dismissed";function G4(){const{toasts:e,addToast:n,removeToast:s}=r4(),i=typeof window<"u"&&!!window.electronAPI;a.useEffect(()=>{K4()},[]);const{projects:r,loading:o,error:l,refresh:c}=t4(),{nodes:u}=tl(),{currentNode:d,currentNodeId:m,isRemote:h,setCurrentNode:f,clearCurrentNode:p}=P4(),{currentProject:g,setCurrentProject:b,clearCurrentProject:v,loading:x}=i4(r,{nodeId:m}),{hasAiProvider:y,hasGithub:k,loading:S,hasWarnings:_}=yg(g?.id),{updateAvailable:N,latestVersion:A,currentVersion:C,dismissed:z,dismiss:M}=v4();a.useEffect(()=>{if(m&&!d&&u.length>0){const Xe=u.find(It=>It.id===m);if(Xe){f(Xe);return}}m&&u.length>0&&(u.some(It=>It.id===m)||p())},[m,d,u,f,p]);const[T,U]=a.useState(""),q=M4(m,{projectId:g?.id,searchQuery:T||void 0});A4(m);const D=h&&q.projects.length>0?q.projects:r,{themeMode:R,colorTheme:F,dashboardFontScalePct:V,setThemeMode:K,setColorTheme:ee,setDashboardFontScalePct:E}=h4(),{sessions:$,generating:P,needsInput:w,planningSessions:O,dismissSession:Z}=YI(g?.id),Ne=$.filter(Xe=>Xe.status==="awaiting_input"||Xe.status==="error"),se=p4({projectId:g?.id,planningSessions:O}),{viewMode:le,setViewMode:we,taskView:L,handleChangeTaskView:ne}=k4({projectsLoading:o,projectsError:l,currentProjectLoading:x,currentProject:g,projectsLength:r.length,setupWizardOpen:se.setupWizardOpen,openSetupWizard:se.openSetupWizard,themeMode:R,setThemeMode:K}),Q=a.useCallback(Xe=>{Xe==="missions"&&(ht(void 0),St(void 0),Nt(void 0)),ne(Xe)},[ne]),be=L==="board"||L==="list",{tasks:de,createTask:me,moveTask:ie,pauseTask:xe,deleteTask:Re,mergeTask:Oe,retryTask:nt,resetTask:et,updateTask:Ze,duplicateTask:rt,archiveTask:He,unarchiveTask:Ge,archiveAllDone:oe,loadArchivedTasks:je,ingestCreatedTasks:X,lastFetchTimeMs:Ae}=XI({...g?{projectId:g.id}:{},searchQuery:T||void 0,sseEnabled:be}),[Te,pe]=a.useState(!1),[_e,Fe]=a.useState(0),it=a.useRef(performance.now()),ve=a.useRef(!1),ce=a.useRef(!1),Ie=a.useMemo(()=>o?"projects":x?"project":"tasks",[o,x]);a.useEffect(()=>{if(!o&&!ve.current){ve.current=!0;const Xe=`projects loaded at ${Math.round(performance.now()-it.current)}ms from mount`;console.log(`[App] ${Xe}`),pr("[App]",Xe)}if(!x&&!ce.current){ce.current=!0;const Xe=`current-project resolved at ${Math.round(performance.now()-it.current)}ms from mount`;console.log(`[App] ${Xe}`),pr("[App]",Xe)}},[o,x]),a.useEffect(()=>{if(Te||o||x)return;const Xe=performance.now(),It=window.setTimeout(()=>{const mn=`dashboard ready at ${Math.round(performance.now()-it.current)}ms from mount (settle delay=${Math.round(performance.now()-Xe)}ms)`;console.log(`[App] ${mn}`),pr("[App]",mn),pe(!0)},$4);return()=>{window.clearTimeout(It)}},[Te,o,x]);const Me=Ta()==="mobile",{keyboardOpen:Je}=Mg({enabled:Me}),$e=Me&&Je,[ft,J]=a.useState(0),re=a.useCallback(()=>{Ap(g?.id).then(Xe=>{J(Xe.unreadCount)}).catch(Xe=>{console.warn("[App] Failed to fetch mailbox unread count:",Xe)})},[g?.id]);a.useEffect(()=>{re();const Xe=new URLSearchParams;g?.id&&Xe.set("projectId",g.id);const It=Xe.size>0?`?${Xe.toString()}`:"";return Gs(`/api/events${It}`,{events:{"message:sent":re,"message:received":re,"message:read":re,"message:deleted":re}})},[g?.id,re]);const[ye,at]=a.useState(!1),[te,Ye]=a.useState(!1),[mt,ht]=a.useState(void 0),[xt,St]=a.useState(void 0),[bt,Nt]=a.useState(void 0),[Qt,Pt]=a.useState(!1),[Dt,Et]=a.useState(!1),[Xt,Lt]=a.useState(()=>Zn(jc,g?.id)==="true");a.useEffect(()=>{Lt(Zn(jc,g?.id)==="true")},[g?.id]),a.useEffect(()=>{const Xe=()=>{Et(!0)};return window.addEventListener(Pc,Xe),()=>{window.removeEventListener(Pc,Xe)}},[]);const Ft=a.useCallback(()=>{ys(jc,"true",g?.id),Lt(!0)},[g?.id]),{maxConcurrent:zt,autoMerge:Tt,globalPaused:Gt,enginePaused:Ot,taskStuckTimeoutMs:qt,showQuickChatFAB:nn,prAuthAvailable:ge,settingsLoaded:ze,experimentalFeatures:dt,insightsEnabled:j,roadmapEnabled:Y,memoryEnabled:fe,devServerEnabled:Pe,todosEnabled:We,toggleAutoMerge:gt,toggleGlobalPause:Mt,toggleEnginePause:cn,refresh:bn}=f4(g?.id),rn=dt.skillsView===!0,Jt=dt.nodesView===!0,Sn=dt.researchView===!0,Se=dt.agentOnboarding===!0,ut=!0;a.useEffect(()=>{ze&&(L==="skills"&&!rn&&ne("board"),L==="insights"&&!j&&ne("board"),L==="roadmaps"&&!Y&&ne("board"),L==="memory"&&!fe&&ne("board"),(L==="devserver"||L==="dev-server")&&!Pe&&ne("board"),L==="todos"&&!We&&ne("board"),L==="research"&&!Sn&&ne("board"))},[L,ze,rn,j,Y,ne,ut,fe,Pe,We,Sn]),a.useEffect(()=>{ye&&!Jt&&at(!1)},[ye,Jt]);const{availableModels:Zt,favoriteProviders:_n,favoriteModels:Nn,toggleFavoriteProvider:zn,toggleFavoriteModel:ss}=b4();x4({projectId:g?.id,setupWizardOpen:se.setupWizardOpen,openModelOnboarding:se.openModelOnboarding,openSettings:se.openSettings});const{handleSelectProject:Rn,handleViewAllProjects:ue,handleOpenSettings:Ke,handleAddProject:pt,handleSetupComplete:$t,handleModelOnboardingComplete:Vt,handlePauseProject:dn,handleResumeProject:Vn,handleRemoveProject:$n,handleToggleFavorite:Dn,handleToggleModelFavorite:en}=w4({setCurrentProject:b,clearCurrentProject:v,setViewMode:we,currentProject:g,refreshProjects:c,toggleFavoriteProvider:zn,toggleFavoriteModel:ss,addToast:n,openSettings:se.openSettings,openSetupWizard:se.openSetupWizard,closeSetupWizard:se.closeSetupWizard,closeModelOnboarding:se.closeModelOnboarding}),{handleDetailClose:Ct}=g4({projectId:g?.id,projects:r,projectsLoading:o,currentProject:g,setCurrentProject:b,addToast:n,openTaskDetail:se.openDetailTask,closeTaskDetail:se.closeDetailTask}),{handleBoardQuickCreate:pn,handleModalCreate:W,handlePlanningTaskCreated:Le,handlePlanningTasksCreated:Qe,handleSubtaskTasksCreated:ot,handleGitHubImport:vt}=N4({createTask:me,ingestCreatedTasks:X,onPlanningTaskCreated:se.onPlanningTaskCreated,onPlanningTasksCreated:se.onPlanningTasksCreated,onSubtaskTasksCreated:se.onSubtaskTasksCreated,addToast:n}),_t=a.useCallback((Xe,It)=>{if(It==="changes"){se.openDetailWithChangesTab(Xe);return}se.openDetailTask(Xe,It)},[se]),Ht=a.useCallback(async Xe=>{try{const It=await jr(Xe,g?.id);se.openDetailTask(It,"logs")}catch(It){n(`Failed to open task logs: ${It.message}`,"error")}},[se,g?.id,n]),Fn=a.useCallback(()=>{Jt&&at(Xe=>!Xe)},[Jt]),ds=a.useCallback(()=>{se.setFileWorkspace("project"),se.openFiles()},[se]),Ns=a.useCallback(async()=>{Ye(!0);try{await c()}finally{Ye(!1)}},[c]),Js=a.useCallback(Xe=>{St(Xe),ht(void 0),ne("missions")},[ne]),ae=a.useCallback(Xe=>{Xe.type==="planning"?se.openPlanningWithSession(Xe.id):Xe.type==="subtask"?se.openSubtaskWithSession(Xe.id):Xe.type==="mission_interview"?(St(void 0),ht(Xe.id),Nt(void 0),ne("missions")):(Xe.type==="milestone_interview"||Xe.type==="slice_interview")&&(ht(void 0),St(void 0),Nt(Xe.id),ne("missions"))},[ne,se]),Ee=a.useCallback(()=>{},[]),tt=a.useCallback(()=>{},[]),kt=!o&&!x&&r.length===0&&!g&&!!l,wt=()=>kt?t.jsx(tI,{errorMessage:l??"Failed to fetch projects",isRetrying:te,onRetry:Ns}):ye?t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(O4,{addToast:n,onClose:()=>at(!1)})})})}):le==="overview"?t.jsx(is,{children:t.jsx(_1,{projects:r,loading:o,onSelectProject:Rn,onAddProject:pt,onPauseProject:dn,onResumeProject:Vn,onRemoveProject:$n,nodes:u})}):L==="skills"?!ze||!rn?null:t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(H4,{addToast:n,projectId:g?.id,onClose:()=>ne("board")})})}):L==="chat"?t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(U4,{addToast:n,projectId:g?.id})})}):L==="mailbox"?t.jsx(is,{children:t.jsx(y0,{projectId:g?.id,addToast:n,onUnreadCountChange:J})}):L==="roadmaps"?!ze||!Y?null:t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(B4,{addToast:n,projectId:g?.id})})}):L==="missions"?t.jsx(is,{children:t.jsx(g0,{isInline:!0,isOpen:!0,onClose:()=>{St(void 0),ht(void 0),Nt(void 0),ne("board")},addToast:n,projectId:g?.id,onSelectTask:Xe=>{const It=de.find(mn=>mn.id===Xe);It&&se.openDetailTask(It)},availableTasks:de.map(Xe=>({id:Xe.id,title:Xe.title})),resumeSessionId:mt,targetMissionId:xt,milestoneSliceResumeSessionId:bt,onMilestoneSliceResumeFetchError:()=>Nt(void 0)})}):L==="agents"&&ut?t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(D4,{addToast:n,projectId:g?.id,onOpenTaskLogs:Ht,agentOnboardingEnabled:Se})})}):L==="documents"?t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(L4,{projectId:g?.id,addToast:n,onOpenDetail:se.openDetailTask})})}):L==="insights"?!ze||!j?null:t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(z4,{projectId:g?.id,addToast:n,onClose:()=>ne("board")})})}):L==="research"?!ze||!Sn?null:t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(F4,{projectId:g?.id,addToast:n,onOpenSettings:Xe=>se.openSettings(Xe),readinessVersion:_e})})}):L==="memory"?!ze||!fe?null:t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(q4,{addToast:n,projectId:g?.id})})}):L==="todos"?!ze||!We?null:t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(W4,{addToast:n,projectId:g?.id})})}):L==="devserver"||L==="dev-server"?!ze||!Pe?null:t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(V4,{addToast:n,projectId:g?.id})})}):L==="board"?t.jsx(is,{children:t.jsx(p1,{tasks:h&&q.tasks.length>0?q.tasks:de,projectId:g?.id,maxConcurrent:zt,onMoveTask:ie,onPauseTask:xe,onOpenDetail:se.openDetailTask,addToast:n,onQuickCreate:pn,onNewTask:se.openNewTask,onPlanningMode:se.openPlanningWithInitialPlan,onSubtaskBreakdown:se.openSubtaskBreakdown,autoMerge:Tt,onToggleAutoMerge:gt,globalPaused:Gt,onUpdateTask:Ze,onRetryTask:nt,onArchiveTask:He,onUnarchiveTask:Ge,onDeleteTask:Re,onArchiveAllDone:oe,onLoadArchivedTasks:je,searchQuery:T,availableModels:Zt,onOpenDetailWithTab:_t,favoriteProviders:_n,favoriteModels:Nn,onToggleFavorite:Dn,onToggleModelFavorite:en,taskStuckTimeoutMs:qt,onOpenMission:Js,lastFetchTimeMs:Ae})}):t.jsx(is,{children:t.jsx(x1,{tasks:h&&q.tasks.length>0?q.tasks:de,projectId:g?.id,onMoveTask:ie,onRetryTask:nt,onOpenDetail:se.openDetailTask,addToast:n,globalPaused:Gt,onNewTask:se.openNewTask,onQuickCreate:pn,onPlanningMode:se.openPlanningWithInitialPlan,onSubtaskBreakdown:se.openSubtaskBreakdown,availableModels:Zt,favoriteProviders:_n,favoriteModels:Nn,onToggleFavorite:Dn,onToggleModelFavorite:en,taskStuckTimeoutMs:qt,searchQuery:T,lastFetchTimeMs:Ae})});if(!Te)return t.jsxs(t.Fragment,{children:[t.jsx(sI,{stage:Ie}),t.jsx(Cg,{toasts:e,onRemove:s})]});const fn=!se.modelOnboardingOpen&&SP(),un=!se.modelOnboardingOpen&&!fn&&Ea()&&!kg();return t.jsxs(t.Fragment,{children:[t.jsx(Uw,{isElectron:i,onOpenSettings:Ke,onOpenGitHubImport:se.openGitHubImport,onOpenPlanning:se.openPlanning,onResumePlanning:se.resumePlanning,activePlanningSessionCount:O.length,onOpenUsage:se.openUsage,onOpenActivityLog:se.openActivityLog,onOpenSystemStats:se.openSystemStats,onOpenMailbox:()=>Q("mailbox"),mailboxUnreadCount:ft,onOpenSchedules:se.openSchedules,onOpenGitManager:se.openGitManager,onOpenNodes:Fn,showNodesButton:Jt,onOpenWorkflowSteps:se.openWorkflowSteps,onOpenScripts:se.openScripts,onRunScript:se.runScript,onToggleTerminal:se.toggleTerminal,onOpenFiles:se.openFiles,filesOpen:se.filesOpen,globalPaused:Gt,enginePaused:Ot,onToggleGlobalPause:Mt,onToggleEnginePause:cn,view:L,onChangeView:le==="project"&&g?Q:void 0,showSkillsTab:rn,showAgentsTab:ut,searchQuery:T,onSearchChange:U,projects:D,currentProject:g,onSelectProject:Rn,onViewAllProjects:ue,projectId:g?.id,mobileNavEnabled:Me,availableNodes:u,currentNode:d,onSelectNode:Xe=>{Xe===null?p():f(Xe)},isRemote:h,experimentalFeatures:{insights:j,roadmap:Y,memoryView:fe,devServer:Pe,devServerView:Pe,todoView:We,researchView:Sn}}),le==="project"&&g&&!ye&&L!=="missions"&&!se.isPlanningOpen&&t.jsx(gI,{sessions:Ne,onResumeSession:ae,onDismissSession:Ee,onDismissAll:tt}),le==="project"&&g&&fn&&t.jsx(xI,{onResume:se.openModelOnboarding}),le==="project"&&g&&un&&t.jsx(vI,{onOpenModelOnboarding:se.openModelOnboarding,onOpenSettings:Xe=>se.openSettings(Xe)}),le==="project"&&g&&N&&A&&C&&!z&&t.jsx(bI,{latestVersion:A,currentVersion:C,onDismiss:M}),le==="project"&&g&&!S&&_&&!Xt&&t.jsx(jg,{hasAiProvider:y,hasGithub:k,onDismiss:Ft}),t.jsx("div",{className:`project-content${le==="project"&&g?" project-content--with-footer":""}${Me&&!$e?" project-content--with-mobile-nav":""}`,children:wt()}),le==="project"&&g&&!ye&&t.jsx(hI,{tasks:h&&q.tasks.length>0?q.tasks:de,projectId:g.id,taskStuckTimeoutMs:qt,backgroundSessions:$,backgroundGenerating:P,backgroundNeedsInput:w,onOpenBackgroundSession:ae,onDismissBackgroundSession:Z,lastFetchTimeMs:Ae,currentProjectPath:g.path,onOpenProjectDirectory:ds}),t.jsx(jI,{view:L,onChangeView:le==="project"&&g?Q:()=>{},footerVisible:le==="project"&&!!g,modalOpen:se.anyModalOpen,keyboardOpen:$e,onOpenSettings:Ke,onOpenActivityLog:se.openActivityLog,onOpenSystemStats:se.openSystemStats,onOpenMailbox:()=>Q("mailbox"),mailboxUnreadCount:ft,onOpenGitManager:se.openGitManager,onOpenWorkflowSteps:se.openWorkflowSteps,onOpenSchedules:se.openSchedules,onOpenScripts:se.openScripts,onToggleTerminal:se.toggleTerminal,onOpenFiles:se.openFiles,onOpenGitHubImport:se.openGitHubImport,onOpenPlanning:se.openPlanning,onResumePlanning:se.resumePlanning,activePlanningSessionCount:O.length,onOpenUsage:()=>se.openUsage(null),onViewAllProjects:ue,onRunScript:se.runScript,projectId:g?.id,showSkillsTab:rn,experimentalFeatures:{insights:j,roadmap:Y,memoryView:fe,devServer:Pe,devServerView:Pe,todoView:We,researchView:Sn}}),le==="project"&&g&&L!=="chat"&&L!=="mailbox"&&L!=="insights"&&L!=="devserver"&&L!=="dev-server"&&t.jsx(JI,{projectId:g.id,addToast:n,showFAB:nn,open:Qt,onOpenChange:Pt,favoriteProviders:_n,favoriteModels:Nn,onToggleFavorite:Dn,onToggleModelFavorite:en}),t.jsx(eI,{projectId:g?.id,tasks:de,projects:r,currentProject:g,addToast:n,toasts:e,removeToast:s,modalManager:se,projectActions:{handleAddProject:pt,handleSetupComplete:$t,handleModelOnboardingComplete:Vt},taskHandlers:{handleModalCreate:W,handlePlanningTaskCreated:Le,handlePlanningTasksCreated:Qe,handleSubtaskTasksCreated:ot,handleGitHubImport:vt},taskOperations:{moveTask:ie,deleteTask:Re,mergeTask:Oe,retryTask:nt,resetTask:et,duplicateTask:rt},deepLink:{handleDetailClose:Ct},settings:{prAuthAvailable:ge,themeMode:R,colorTheme:F,dashboardFontScalePct:V,setThemeMode:K,setColorTheme:ee,setDashboardFontScalePct:E},onSettingsClose:()=>{se.closeSettings(),Fe(Xe=>Xe+1),bn()},onReopenOnboarding:()=>{se.closeSettings(),se.openModelOnboarding()}}),t.jsx(I4,{open:Dt})]})}function J4(){return t.jsx(a4,{children:t.jsx(T4,{children:t.jsx(tN,{children:t.jsx(G4,{})})})})}Wv();Rv();Fg.createRoot(document.getElementById("root")).render(t.jsx(a.StrictMode,{children:t.jsx(Tv,{children:t.jsx(J4,{})})}));"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{sP as $,Ds as A,Cn as B,wn as C,Xw as D,kD as E,Bi as F,Vo as G,Ec as H,Ws as I,ln as J,Eo as K,lt as L,QL as M,kn as N,pc as O,An as P,En as Q,Ln as R,wi as S,ld as T,qs as U,on as V,sn as W,Kt as X,dP as Y,Yn as Z,ik as _,ys as a,Cs as a$,iP as a0,ak as a1,vD as a2,rk as a3,hn as a4,I$ as a5,$$ as a6,mj as a7,rd as a8,Ma as a9,XL as aA,ZL as aB,tz as aC,yr as aD,ov as aE,hr as aF,Rb as aG,ms as aH,mp as aI,tl as aJ,t4 as aK,ML as aL,pu as aM,Sr as aN,Mw as aO,AL as aP,RL as aQ,Aw as aR,Rw as aS,_I as aT,Ta as aU,Mg as aV,SL as aW,Ho as aX,dp as aY,kI as aZ,CI as a_,_a as aa,oi as ab,li as ac,gi as ad,TL as ae,$L as af,IL as ag,PL as ah,DL as ai,os as aj,ps as ak,xv as al,ai as am,Db as an,Mr as ao,Ci as ap,LL as aq,FL as ar,qL as as,HL as at,BL as au,UL as av,OL as aw,zL as ax,wr as ay,ez as az,_D as b,eL as b$,zi as b0,Ni as b1,rp as b2,Vd as b3,DD as b4,zD as b5,LD as b6,FD as b7,OD as b8,UD as b9,y$ as bA,b$ as bB,g$ as bC,u$ as bD,k$ as bE,VR as bF,tD as bG,eD as bH,oD as bI,Z$ as bJ,nD as bK,sD as bL,iD as bM,aD as bN,$j as bO,rD as bP,dd as bQ,Tj as bR,Pj as bS,Ij as bT,Rj as bU,X$ as bV,Ir as bW,Go as bX,av as bY,vr as bZ,Xx as b_,BD as ba,HD as bb,qD as bc,VD as bd,WD as be,KD as bf,GD as bg,JD as bh,QD as bi,XD as bj,YD as bk,qn as bl,od as bm,Ui as bn,EL as bo,CL as bp,_L as bq,p$ as br,h$ as bs,m$ as bt,f$ as bu,N$ as bv,S$ as bw,j$ as bx,x$ as by,v$ as bz,Ve as c,Zo as c$,tL as c0,nL as c1,sL as c2,iL as c3,aL as c4,rL as c5,ZD as c6,bp as c7,xa as c8,mk as c9,MD as cA,e$ as cB,n$ as cC,d$ as cD,c$ as cE,Fy as cF,My as cG,ri as cH,Ry as cI,Ay as cJ,Ty as cK,Py as cL,M$ as cM,AD as cN,RD as cO,TD as cP,_i as cQ,WL as cR,KL as cS,$D as cT,s$ as cU,wc as cV,Qn as cW,HR as cX,mP as cY,pP as cZ,fc as c_,zv as ca,Fv as cb,jL as cc,L$ as cd,D$ as ce,kL as cf,z$ as cg,W$ as ch,H$ as ci,F$ as cj,q$ as ck,O$ as cl,V$ as cm,U$ as cn,B$ as co,nb as cp,Cy as cq,K$ as cr,Ey as cs,G$ as ct,ci as cu,RR as cv,C$ as cw,ID as cx,X4 as cy,Z4 as cz,CD as d,a$ as d0,t$ as d1,r$ as d2,i$ as d3,o$ as d4,l$ as d5,Vi as d6,Gw as d7,el as d8,GL as d9,yD as dA,Tr as dB,JM as dC,uD as dD,dD as dE,hj as dF,mD as dG,fD as dH,fL as dI,cD as dJ,gL as dK,Yx as dL,Mc as dM,wL as dN,vL as dO,xL as dP,yL as dQ,bL as dR,PD as dS,VL as dT,A$ as dU,E$ as dV,_$ as dW,T$ as dX,P$ as dY,R$ as dZ,sh as da,JL as db,YL as dc,w$ as dd,oL as de,cL as df,mL as dg,dL as dh,lL as di,uL as dj,hL as dk,$c as dl,Yd as dm,mx as dn,pL as dp,jD as dq,gD as dr,xD as ds,bD as dt,ND as du,wD as dv,ap as dw,pD as dx,hD as dy,nP as dz,ED as e,jr as f,Zn as g,fs as h,Ra as i,NL as j,Xn as k,sk as l,lD as m,Ls as n,Q$ as o,J$ as p,Y$ as q,aP as r,Gs as s,SD as t,gn as u,SI as v,Ks as w,Yo as x,Qr as y,ke as z};
|